beads/internal/storage/sqlbuild/labels.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

116 lines
4.2 KiB
Go

package sqlbuild
import (
"fmt"
"strings"
"github.com/steveyegge/beads/internal/types"
)
// LabelSearchPlan rewrites label predicates (Labels AND-set, LabelsAny) from
// IN-subqueries into JOINs against the labels table, which the optimizer
// handles far better on large corpora. Filter is the input filter with the
// rewritten label fields cleared; callers pass it (not the original) to
// BuildIssueFilterClauses and then merge Where/Args via MergeInto.
type LabelSearchPlan struct {
FromSQL string
Where []string
Args []any
Distinct bool
Filter types.IssueFilter
}
// MergeInto prepends the plan's label clauses to filter-built clauses,
// preserving the historical clause and arg ordering of both stacks.
// Single-use: the result shares the plan's backing arrays, so merging one
// plan into two clause sets could clobber the first result's tail.
func (p LabelSearchPlan) MergeInto(where []string, args []any) ([]string, []any) {
if len(p.Where) == 0 {
return where, args
}
return append(p.Where, where...), append(p.Args, args...)
}
// BuildLabelDrivenSearch produces the FROM clause (with label JOINs when label
// predicates are present) and the residual filter for a table family.
func BuildLabelDrivenSearch(filter types.IssueFilter, tables FilterTables) LabelSearchPlan {
labels := CompactNonEmptyStrings(filter.Labels)
labelsAny := CompactNonEmptyStrings(filter.LabelsAny)
if len(labels) == 0 && len(labelsAny) == 0 {
return LabelSearchPlan{FromSQL: tables.Main, Filter: filter}
}
filterForClauses := filter
filterForClauses.Labels = nil
filterForClauses.LabelsAny = nil
var joins, where []string
var args []any
for i, label := range labels {
alias := fmt.Sprintf("label_filter_%d", i)
joins = append(joins, fmt.Sprintf("JOIN %s %s ON %s.issue_id = %s.id", tables.Labels, alias, alias, tables.Main))
where = append(where, fmt.Sprintf("%s.label = ?", alias))
args = append(args, label)
}
if len(labelsAny) > 0 {
alias := "label_filter_any"
joins = append(joins, fmt.Sprintf("JOIN %s %s ON %s.issue_id = %s.id", tables.Labels, alias, alias, tables.Main))
placeholders := make([]string, len(labelsAny))
for i, label := range labelsAny {
placeholders[i] = "?"
args = append(args, label)
}
where = append(where, fmt.Sprintf("%s.label IN (%s)", alias, strings.Join(placeholders, ", ")))
}
return LabelSearchPlan{
FromSQL: tables.Main + " " + strings.Join(joins, " "),
Where: where,
Args: args,
Distinct: true,
Filter: filterForClauses,
}
}
// LabelSetClauses builds the AND / OR / NOT label predicates as IN-subqueries
// against tables.Labels, keyed on idExpr. Semantics are the ones users already
// know from bd list and bd ready: labels is AND (carry all of them), labelsAny
// is OR (carry at least one), exclude drops an issue carrying any. Clause and
// arg ordering, and the treatment of empty entries, mirror the equivalent
// blocks in BuildIssueFilterClauses so every listing command filters labels
// identically.
//
// BuildLabelDrivenSearch rewrites the AND/OR pair into JOINs for the search
// path, which the optimizer prefers on large corpora. This is the subquery
// form, for callers whose FROM clause is fixed and cannot take a join.
func LabelSetClauses(idExpr string, tables FilterTables, labels, labelsAny, exclude []string) ([]string, []any) {
var where []string
var args []any
for _, label := range labels {
where = append(where, fmt.Sprintf("%s IN (SELECT issue_id FROM %s WHERE label = ?)", idExpr, tables.Labels))
args = append(args, label)
}
if len(labelsAny) > 0 {
placeholders := make([]string, len(labelsAny))
for i, label := range labelsAny {
placeholders[i] = "?"
args = append(args, label)
}
where = append(where, fmt.Sprintf("%s IN (SELECT issue_id FROM %s WHERE label IN (%s))",
idExpr, tables.Labels, strings.Join(placeholders, ", ")))
}
if len(exclude) > 0 {
placeholders := make([]string, len(exclude))
for i, label := range exclude {
placeholders[i] = "?"
args = append(args, label)
}
where = append(where, fmt.Sprintf("%s NOT IN (SELECT issue_id FROM %s WHERE label IN (%s))",
idExpr, tables.Labels, strings.Join(placeholders, ", ")))
}
return where, args
}