beads/internal/storage/sqlbuild/labels_test.go
Robin Carswell 734701824a
feat(stale,blocked): add label filtering to bd stale and bd blocked (#5822)
* feat(stale,blocked): add label filtering to bd stale and bd blocked

bd stale and bd blocked were the last two issue-listing commands with no way
to scope output by label; bd list, bd ready, bd orphans, bd count and bd
search all have it. Add -l/--label (AND), --label-any (OR) and
--exclude-label (NOT) to both, reusing the existing help text so the flags
mean the same thing wherever a user meets them.

bd blocked was also silently discarding label filters it already accepted:
types.WorkFilter has carried Labels/LabelsAny/ExcludeLabels all along and
blockedCmd builds a WorkFilter, but GetBlockedIssuesInTx only ever read
ParentID, so a caller setting them got unfiltered results back and no error.

New sqlbuild.LabelSetClauses is the IN-subquery form of the three predicates,
for callers whose FROM clause is fixed and cannot take the JOIN that
BuildLabelDrivenSearch builds. A test pins it against the equivalent blocks in
BuildIssueFilterClauses so the two cannot drift: --label should mean the same
thing whichever command it is passed to.

On stale the predicates go in the WHERE clause rather than onto the hydrated
rows, because filter.Limit is this query's LIMIT and post-filtering would make
--label x --limit 10 return fewer than ten matching issues. On blocked they go
in the per-table scan, so issues filter against labels and wisps against
wisp_labels, which also spares the blocker-dependency and hydration passes any
work on rows that cannot survive.

Both the direct and the proxied-server path now build the blocked filter
through one blockedFilterFromFlags helper rather than assembling it twice.

Co-Authored-By: Claude <noreply@anthropic.com>

* fix(stale,blocked): normalize the new label filters, as every sibling does

Review feedback on #5822. The new flags built exact `label = ?` clauses from
raw pflag values, while every other label filter in bd normalizes first --
list_input.go:293-295, search.go:106, orphans.go:56, workapi/ready.go:56-58.

That gap is the read-side twin of #5812, and #5813 does not cure it:
normalize-on-write only protects labels a fixed bd wrote, whereas a filter
input still needs trimming wherever it comes from.

Two shapes, both verified on the embedded engine:

- `--label ' theme:a'` returned 0 rows while `bd list --label ' theme:a'`
  returned the issue. This is the everyday case, not an exotic one: pflag's CSV
  split leaves the space on the second value of `--label 'a, b'`.
- `--label 'a,,b'` ANDed in a `label = ''` clause, which nothing can satisfy,
  turning a valid filter into an empty result.

Both fail silently -- a filtered list short of rows reads exactly like a
complete one -- and both cut against the promise LabelSetClauses is documented
to keep, that --label means the same thing whichever command you reach for.

Normalization sits at the two shared choke points, so no route is missed:
blockedFilterFromFlags (direct + proxied blocked) and stale's RunE, which
builds the StaleFilter both its routes use.

Six new embedded subtests across bd stale and bd blocked pin trimming, the
empty-element case, and that both apply to --label-any and --exclude-label.
Verified failing with this commit's normalization reverted (6 fail, the nine
pre-existing label subtests still pass) and passing with it.

CHANGELOG: the flag addition, plus the WorkFilter silent-drop fix found en
route -- bd blocked accepted Labels/LabelsAny/ExcludeLabels and read only
ParentID, so programmatic callers got unfiltered results and no error.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-20 15:12:04 -07:00

177 lines
5.6 KiB
Go

package sqlbuild
import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// TestLabelSetClauses pins the SQL and arg ordering shared by the listing
// commands that cannot take a label JOIN (bd stale, bd blocked). The clauses
// must stay interchangeable with the equivalent blocks in
// BuildIssueFilterClauses — see TestLabelSetClausesMatchesFilterClauses.
func TestLabelSetClauses(t *testing.T) {
t.Parallel()
cases := []struct {
name string
idExpr string
tables FilterTables
labels []string
labelsAny []string
exclude []string
wantWhere []string
wantArgs []any
}{
{
name: "no labels yields no clauses",
idExpr: "id",
tables: IssuesFilterTables,
},
{
name: "single AND label",
idExpr: "id",
tables: IssuesFilterTables,
labels: []string{"theme:personal"},
wantWhere: []string{"id IN (SELECT issue_id FROM labels WHERE label = ?)"},
wantArgs: []any{"theme:personal"},
},
{
name: "AND labels emit one clause each, in order",
idExpr: "id",
tables: IssuesFilterTables,
labels: []string{"theme:personal", "actor:robin"},
wantWhere: []string{
"id IN (SELECT issue_id FROM labels WHERE label = ?)",
"id IN (SELECT issue_id FROM labels WHERE label = ?)",
},
wantArgs: []any{"theme:personal", "actor:robin"},
},
{
name: "OR labels collapse into one IN clause",
idExpr: "id",
tables: IssuesFilterTables,
labelsAny: []string{"p0", "p1"},
wantWhere: []string{"id IN (SELECT issue_id FROM labels WHERE label IN (?, ?))"},
wantArgs: []any{"p0", "p1"},
},
{
name: "exclude labels emit a NOT IN clause",
idExpr: "id",
tables: IssuesFilterTables,
exclude: []string{"monitor"},
wantWhere: []string{"id NOT IN (SELECT issue_id FROM labels WHERE label IN (?))"},
wantArgs: []any{"monitor"},
},
{
name: "all three combine, AND then OR then NOT",
idExpr: "id",
tables: IssuesFilterTables,
labels: []string{"theme:personal"},
labelsAny: []string{"p0", "p1"},
exclude: []string{"monitor"},
wantWhere: []string{
"id IN (SELECT issue_id FROM labels WHERE label = ?)",
"id IN (SELECT issue_id FROM labels WHERE label IN (?, ?))",
"id NOT IN (SELECT issue_id FROM labels WHERE label IN (?))",
},
wantArgs: []any{"theme:personal", "p0", "p1", "monitor"},
},
{
name: "wisps use their own label table",
idExpr: "id",
tables: WispsFilterTables,
labels: []string{"theme:personal"},
wantWhere: []string{"id IN (SELECT issue_id FROM wisp_labels WHERE label = ?)"},
wantArgs: []any{"theme:personal"},
},
{
name: "qualified id expression is used verbatim",
idExpr: "issues.id",
tables: IssuesFilterTables,
labels: []string{"theme:personal"},
wantWhere: []string{"issues.id IN (SELECT issue_id FROM labels WHERE label = ?)"},
wantArgs: []any{"theme:personal"},
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
where, args := LabelSetClauses(tc.idExpr, tc.tables, tc.labels, tc.labelsAny, tc.exclude)
if len(where) != len(tc.wantWhere) {
t.Fatalf("got %d clauses %v, want %d %v", len(where), where, len(tc.wantWhere), tc.wantWhere)
}
for i := range where {
if where[i] != tc.wantWhere[i] {
t.Errorf("clause %d = %q, want %q", i, where[i], tc.wantWhere[i])
}
}
if len(args) != len(tc.wantArgs) {
t.Fatalf("got %d args %v, want %d %v", len(args), args, len(tc.wantArgs), tc.wantArgs)
}
for i := range args {
if args[i] != tc.wantArgs[i] {
t.Errorf("arg %d = %v, want %v", i, args[i], tc.wantArgs[i])
}
}
})
}
}
// TestLabelSetClausesPlaceholderArgAgreement guards the failure mode that
// actually bites at runtime: a clause carrying more ? than the args beside it,
// which the driver reports far from the code that built it.
func TestLabelSetClausesPlaceholderArgAgreement(t *testing.T) {
t.Parallel()
where, args := LabelSetClauses("id", IssuesFilterTables,
[]string{"a", "b"}, []string{"c", "d", "e"}, []string{"f", "g"})
placeholders := 0
for _, clause := range where {
placeholders += strings.Count(clause, "?")
}
if placeholders != len(args) {
t.Errorf("clauses carry %d placeholders but %d args were returned: %v / %v",
placeholders, len(args), where, args)
}
}
// TestLabelSetClausesMatchesFilterClauses pins the helper against the inline
// label handling in BuildIssueFilterClauses. The two must agree: bd stale and
// bd blocked filter through the helper while bd list filters through
// BuildIssueFilterClauses, and a user is entitled to the same answer from
// --label whichever command they reach for.
func TestLabelSetClausesMatchesFilterClauses(t *testing.T) {
t.Parallel()
labels := []string{"theme:personal", "actor:robin"}
labelsAny := []string{"p0", "p1"}
exclude := []string{"monitor"}
helperWhere, helperArgs := LabelSetClauses("id", IssuesFilterTables, labels, labelsAny, exclude)
filterWhere, filterArgs, err := BuildIssueFilterClauses("", types.IssueFilter{
Labels: labels,
LabelsAny: labelsAny,
ExcludeLabels: exclude,
}, IssuesFilterTables)
if err != nil {
t.Fatalf("BuildIssueFilterClauses: %v", err)
}
if strings.Join(helperWhere, " AND ") != strings.Join(filterWhere, " AND ") {
t.Errorf("clause mismatch:\n helper: %v\n filter: %v", helperWhere, filterWhere)
}
if len(helperArgs) != len(filterArgs) {
t.Fatalf("arg count mismatch: helper %v, filter %v", helperArgs, filterArgs)
}
for i := range helperArgs {
if helperArgs[i] != filterArgs[i] {
t.Errorf("arg %d: helper %v, filter %v", i, helperArgs[i], filterArgs[i])
}
}
}