feat(issueops): put bd purge and bd prune behind the Sweeper role (bd-pn231)

`bd purge` selected closed wisps in one transaction and deleted them in
another. A bead closed, unpinned or cited in the window between the two was
judged on one state and acted on in a different one — the TOCTOU the bead
names — and the proxied twin held a second copy of the whole flow: its own
candidate filter, its own glob match, its own closed_at recheck, its own
reference scan and 190 lines of output kept character-identical to the direct
route's by hand.

PURGE AND PRUNE ARE ONE CAPABILITY, which the design left open and the code
answers plainly: both routes already ran ONE function with a `purgeScope`
struct choosing the tier. So issueops.Sweeper has ONE method, reached through
store.Sweeper() and the provider's own accessor, and SweepRequest.Tier selects
the plane — `ephemeral` is purge, `durable` is prune, and the two are disjoint
by construction. What genuinely differed became request fields rather than a
second role: the require-a-filter refusal keys on Tier, and the citation
protection is ASKED FOR (ProtectReferenced) instead of being inferred from a
command name, which is what the shared body did (`scope.cmdName == "prune"`).

Q9 ANSWERED IN THE ROLE. The require-a-filter gate is
workapi.ValidateSweepRequest, below every front door: a durable sweep with
neither a cutoff nor an id pattern is ErrValidation. It is a safety invariant,
not presentation — without it a second front door is one handler away from an
unguarded mass delete, which is exactly what this commit's HTTP operation would
otherwise have been. The CLI keeps its friendly message, and says in place that
it is there for the WORDING while the guard is the role's; the contract case is
what proves the guard survives that branch being deleted.

THE DEFECT, AND ITS PRICE. The whole sweep is now one transaction, so the set
the result describes IS the set it deleted. That gives up the server-backed
store's batched wisp deletion (200 per transaction, added for Dolt's 10s write
timeout after bd-2ehd and ff-tqm): a sweep too large now fails WHOLE. That is
the better failure — the partial one it replaces reported a deleted count of
ZERO while having deleted rows — and the other two backends already worked this
way. It is written down as a promise WITH its cost, and recorded for sign-off.

TWO MORE DEFECTS the single call site removed. `--dry-run` passed force=false
to the delete where the real run passed force=true, so a preview could FAIL
over dependents the sweep would have orphaned — and the CLI answered that
failure with zeros. And `filepath.Match`'s error was discarded on both routes,
so `--pattern '['` printed "No closed beads to prune" and exited 0; it is now
ErrValidation quoting the pattern.

THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/sweeper_contract.go holds ten cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the
result the sweep reported about itself, which on a destructive operation is the
assertion that matters; every case scopes itself with an id pattern, because a
sweep is asked of a whole TIER and an unscoped one would clear the next case's
seeds. They are TWO INDEPENDENT BODIES plus an engine check: dolt and
embeddeddolt share internal/storage/issueops.SweepInTx and differ only in how
they reach a transaction, and the unit-of-work provider reaches the same four
questions through the domain use cases.

THE HTTP OPERATION, spec first (per bd-jtp1h's A2 scope decision):
POST /v0/beads/issues:sweep, capability `issues.sweep` — the first DESTRUCTIVE
operation on a surface that was reads plus one claim. It is a collection-level
custom method with a body rather than DELETE with a query string, because a
dropped query parameter widens what is erased where an unknown body member is
refused by name. The handler decodes six members and calls the role; it does
not implement the safety gate, the tier vocabulary or the glob, all of which
are the role's ErrValidation reaching the wire as a 400 through failSweepErr.
No component carries allOf and none is x-go-type-pinned — there is no canonical
Go struct whose JSON encoding is this body, since the CLI publishes these
numbers under `purged_count`/`pruned_count` — so the projection is tested
instead. `bd serve --help` grew a DESTRUCTIVE OPERATIONS section and the
--allow-non-loopback warning now says peers can bulk-delete closed beads.

`bd gc` keeps the closed-candidate recheck by calling the SAME pure function
the role calls (workapi.FilterSweepCandidates), so the two cannot drift; the
reference matcher and its 10K-body budget moved to internal/workapi with the
scan. cmd/bd/purge.go and purge_proxied_server.go LEFT the forbidigo exception
list, which is how a role commit proves its front doors reached the role.

USER-VISIBLE, for the wave's changelog pass: the version-control label for a
sweep is now `bd: sweep <n> <tier> bead(s)` on both routes, where proxied wrote
`bd: prune <n> bead(s)` and direct wrote `bd: delete <n> issue(s)` — an HTTP
sweep is not `bd prune`, so the label names the operation and the tier from
every door; a malformed `--pattern` now exits non-zero; `--dry-run` no longer
refuses over dependents the real sweep orphans; and `bd serve` gains a
bulk-delete endpoint. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-swp-1..9.

Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestSweeperContract 10/10 at
dolt, embeddeddolt and uow; the internal/workapi, internal/storage and
internal/telemetry suites; TestEmbeddedPurge, TestEmbeddedPurgeConcurrent,
TestEmbeddedPrune, TestPrune_protectsBeadCitedByCustomStatusBead and
TestEmbeddedGC under BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerPrune under
BEADS_TEST_PROXIED_SERVER=1; TestProxiedLookup*; and the root layering pins.
The protocol corpus has no purge/prune case to account for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
CI Bot 2026-08-05 16:20:44 +00:00
commit 519fb1479b
44 changed files with 6525 additions and 1038 deletions

View file

@ -254,7 +254,7 @@ linters:
linters:
- forbidigo
# Inside cmd/bd the rule is deny-by-default, so each entry below is a
# HOLE in it and carries the reason that hole exists. 61 of the 388
# HOLE in it and carries the reason that hole exists. 59 of the 389
# non-test files under cmd/bd are on this list; widening it is an edit
# here and a diff a reviewer sees. internal/httpapi has no entry and is
# meant not to.
@ -303,7 +303,14 @@ linters:
# issueops request and name no filter type, so the hole they needed is
# closed rather than merely unused. Removing an entry here is how a role
# commit proves its front doors reached the role.
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|todo|wisp)(_proxied_server)?\.go$'
#
# `purge` left it the same way when the Sweeper role took the candidate
# filter off both `bd purge` and `bd prune`: cmd/bd/purge.go now builds an
# issueops.SweepRequest, and cmd/bd/purge_proxied_server.go is down to the
# provider's capability accessor. `gc` stays — it is a different command
# that still selects its own closed beads, and it now shares only the pure
# recheck (workapi.FilterSweepCandidates) with the role.
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|search|todo|wisp)(_proxied_server)?\.go$'
linters:
- forbidigo
# Molecule reporting: each selects the members of one molecule.

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,560 @@
package conformance
import (
"context"
"errors"
"fmt"
"reflect"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
// This file holds the semantic contract every implementation of
// publicops.Sweeper must satisfy. Each case asserts what issueops/sweeper.go
// PROMISES, cited by line, rather than what any one backend happens to do; a
// backend that genuinely disagrees is parked at its own wiring site with
// skipKnownDivergence so the case still runs on the ones that agree.
//
// THERE ARE TWO BODIES BEHIND THE THREE WIRINGS. dolt and embeddeddolt share
// internal/storage/issueops.SweepInTx and differ only in how they reach a
// transaction; the unit-of-work provider reaches the same four questions
// through the domain use cases and is genuinely separate code. So the wirings
// are one vote plus an engine check, and a second independent vote — and the
// selection half of both votes runs through the SAME internal/workapi
// functions, which is why the cases below spend their assertions on what only
// a real backend can show: which rows are actually gone, what a dry run left
// alone, and whether the version-control plane recorded anything.
//
// EVERY CASE SCOPES ITSELF WITH AN ID PATTERN, and here that is not hygiene
// but a precondition. A sweep is asked of a whole TIER, so a case that swept
// without a pattern would delete the rows the next case seeded — and, on the
// ephemeral tier, would be a legal unfiltered request that the role does not
// refuse. Each Run therefore seeds under fixture.IssuePrefix + its own tag and
// passes that tag as SweepRequest.IDPattern.
//
// EVERY CASE PINS closed_at EXPLICITLY. The recheck the role performs is
// against a cutoff, and a seeded row whose closed_at defaulted to "now" would
// make "closed before now" a race with the test's own clock.
// SweeperFixture supplies adapter-specific storage access for the
// bulk-clearance assertions. Every field is named and typed exactly like the
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
// accessor plus prefix with no adapter in between.
type SweeperFixture struct {
// IssuePrefix namespaces the ids each assertion seeds, so several of them
// can share one database.
IssuePrefix string
// Sweeper is the surface under test.
Sweeper publicops.Sweeper
// CreateIssue seeds a durable issue in the issues plane.
CreateIssue func(context.Context, *types.Issue, string) error
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
// field rather than an Ephemeral flag on CreateIssue because the three
// adapters reach the two planes through different verbs.
CreateWisp func(context.Context, *types.Issue, string) error
// QueryScalar runs a single-row query and scans it. It is how these cases
// observe the ONE thing a sweep result cannot be trusted to report about
// itself: whether the rows are really gone.
QueryScalar func(context.Context, string, []any, ...any) error
// CountHistory reports how many history entries the fixture's branch has.
// A nil hook means "this backend cannot observe history", and the case
// that needs it SKIPS with that reason rather than passing quietly.
CountHistory func(context.Context) (int, error)
}
// sweeperClosedAt is the stamp every seeded candidate carries, and
// sweeperCutoff is an instant strictly after it. Fixed values rather than
// offsets from time.Now so the cutoff cases assert an interval rather than
// race the clock.
var (
sweeperClosedAt = time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
sweeperCutoff = time.Date(2026, 4, 1, 12, 0, 0, 0, time.UTC)
)
// RunSweeperRefusesAnUnfilteredDurableSweep pins the safety invariant the role
// took off the CLI (issueops/sweeper.go:59-73): a durable sweep with neither a
// cutoff nor a pattern is ErrValidation, and it is the WHOLE POINT of the
// guard living below the front doors that this is asserted at the role rather
// than at a handler.
//
// It asserts the refusal AND its effect. A guard that returned an error after
// deleting would satisfy an errors.Is assertion perfectly, and on this
// operation that is the failure worth spending a seeded row to rule out.
func RunSweeperRefusesAnUnfilteredDurableSweep(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
id := sweeperSeedClosedIssue(t, ctx, fixture, "gate", false)
result, err := fixture.Sweeper.Sweep(ctx, publicops.SweepRequest{Tier: publicops.SweepDurable})
if !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("Sweep(durable, no cutoff, no pattern) error = %v, want ErrValidation: "+
"the require-a-filter guard is a safety invariant of the ROLE, so a second front door inherits it", err)
}
if result.Swept != 0 {
t.Errorf("refused sweep reported Swept = %d, want 0", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 1, id)
// The ephemeral tier carries no such gate: an unfiltered sweep of closed
// wisps is the ordinary use of `bd purge`. Asked with a pattern that
// matches nothing so the case does not clear another case's seeds.
if _, err := fixture.Sweeper.Sweep(ctx, publicops.SweepRequest{
Tier: publicops.SweepEphemeral,
IDPattern: fixture.IssuePrefix + "-gate-nothing-*",
}); err != nil {
t.Fatalf("Sweep(ephemeral) error = %v, want nil: the gate is the durable tier's, not every tier's", err)
}
}
// RunSweeperRefusesAMalformedRequest pins the other two ErrValidation clauses
// (issueops/sweeper.go): an unset or unrecognized Tier, and an IDPattern that
// is not a well-formed glob.
//
// The pattern case is a DEFECT FIX with teeth. Both front doors used to
// discard filepath.Match's error, so `--pattern '['` reported "nothing to
// prune" — indistinguishable from a correct pattern over an empty set, on a
// command whose entire job is to delete what it matched.
func RunSweeperRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
for _, test := range []struct {
name string
request publicops.SweepRequest
}{
{"unset tier", publicops.SweepRequest{IDPattern: "*"}},
{"unrecognized tier", publicops.SweepRequest{Tier: publicops.SweepTier("wisps"), IDPattern: "*"}},
{"malformed pattern", publicops.SweepRequest{Tier: publicops.SweepDurable, IDPattern: "[bad"}},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := fixture.Sweeper.Sweep(ctx, test.request); !errors.Is(err, publicops.ErrValidation) {
t.Fatalf("Sweep(%s) error = %v, want ErrValidation", test.name, err)
}
})
}
}
// RunSweeperClearsOneTierAndLeavesTheOther pins the disjointness that makes
// `bd purge` and `bd prune` ONE capability with a tier parameter
// (issueops/sweeper.go, SweepTier): a sweep of one tier can never touch a row
// of the other.
//
// Both planes are seeded with ids the SAME pattern admits, so a body that
// forgot the tier — or that let the pattern do the work the filter should do —
// deletes the wrong rows rather than merely reporting a wrong number.
func RunSweeperClearsOneTierAndLeavesTheOther(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
issueID := sweeperSeedClosedIssue(t, ctx, fixture, "tier", false)
wispID := sweeperSeedClosedIssue(t, ctx, fixture, "tier", true)
result := sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: sweeperPattern(fixture, "tier"),
})
if result.Swept != 1 {
t.Fatalf("durable sweep reported Swept = %d, want 1", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 0, issueID)
sweeperAssertWispRows(t, ctx, fixture, 1, wispID)
result = sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepEphemeral,
IDPattern: sweeperPattern(fixture, "tier"),
})
if result.Swept != 1 {
t.Fatalf("ephemeral sweep reported Swept = %d, want 1", result.Swept)
}
sweeperAssertWispRows(t, ctx, fixture, 0, wispID)
}
// RunSweeperProtectsPinnedRows pins the protection no request field overrides
// (issueops.SweepSkips.Pinned): a pinned closed row is held back and counted,
// and the sweep still clears everything beside it.
func RunSweeperProtectsPinnedRows(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
plain := sweeperSeedClosedIssue(t, ctx, fixture, "pin", false)
pinned := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "pin", "keep", false), func(issue *types.Issue) {
issue.Pinned = true
})
result := sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: sweeperPattern(fixture, "pin"),
})
if result.Swept != 1 {
t.Errorf("Swept = %d, want 1 — the pinned row must not be one of them", result.Swept)
}
if result.Skipped.Pinned != 1 {
t.Errorf("Skipped.Pinned = %d, want 1", result.Skipped.Pinned)
}
sweeperAssertIssueRows(t, ctx, fixture, 0, plain)
sweeperAssertIssueRows(t, ctx, fixture, 1, pinned)
}
// RunSweeperHonorsTheCutoffAndThePattern pins the two narrowing fields.
//
// The CUTOFF is HALF-OPEN, and that is asserted rather than assumed: a row
// closed exactly at the cutoff is KEPT (issueops.SweepRequest.ClosedBefore,
// "strictly before"). An off-by-one there deletes a bead closed the instant a
// scheduled sweep names, which is the one row a caller reasoning about the
// boundary is thinking of.
//
// The PATTERN is matched in Go rather than translated to SQL, so the case
// includes a character class — the construct a LIKE translation would get
// wrong, on the operation where getting it wrong deletes rows.
func RunSweeperHonorsTheCutoffAndThePattern(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
old := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "when", "old", false), nil)
atCutoff := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "when", "edge", false), func(issue *types.Issue) {
at := sweeperCutoff
issue.ClosedAt = &at
})
cutoff := sweeperCutoff
result := sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepDurable,
ClosedBefore: &cutoff,
IDPattern: sweeperPattern(fixture, "when"),
})
if result.Swept != 1 {
t.Errorf("Swept = %d, want 1 — ClosedBefore is strictly before, so the row closed AT the cutoff stays", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 0, old)
sweeperAssertIssueRows(t, ctx, fixture, 1, atCutoff)
// A character class, and a row the class excludes.
inClass := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "glob", "a1", false), nil)
outOfClass := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "glob", "z9", false), nil)
result = sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: fixture.IssuePrefix + "-glob-[a-c]*",
})
if result.Swept != 1 {
t.Errorf("Swept = %d, want 1 for the character-class pattern", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 0, inClass)
sweeperAssertIssueRows(t, ctx, fixture, 1, outOfClass)
}
// RunSweeperDryRunChangesNothing pins the promise a preview is worth reading
// for (issueops.Sweeper.Sweep, "A DRY RUN CHANGES NOTHING"): the preview
// reports the same counts the real sweep goes on to report, and leaves every
// row where it was.
//
// The two are compared against EACH OTHER rather than against a literal,
// because that is the property a caller relies on — a preview whose number
// differs from the run it precedes is worse than no preview.
func RunSweeperDryRunChangesNothing(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
ids := []string{
sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "dry", "1", false), nil),
sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "dry", "2", false), nil),
}
request := publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: sweeperPattern(fixture, "dry"),
}
preview := sweeperSweep(t, ctx, fixture, sweeperWithDryRun(request, true))
if !preview.DryRun {
t.Error("preview.DryRun = false; the result must echo the request it answered")
}
if preview.Swept != 2 {
t.Fatalf("preview Swept = %d, want 2", preview.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 2, ids...)
// A second preview: a dry run that had deleted anything would report a
// smaller number here, which is the failure this repetition rules out.
if again := sweeperSweep(t, ctx, fixture, sweeperWithDryRun(request, true)); again.Swept != preview.Swept {
t.Fatalf("second preview Swept = %d, first = %d: the first preview changed the store", again.Swept, preview.Swept)
}
real := sweeperSweep(t, ctx, fixture, request)
if real.Swept != preview.Swept {
t.Errorf("real Swept = %d, preview said %d: a preview that disagrees with its run is worse than none",
real.Swept, preview.Swept)
}
if real.DryRun {
t.Error("real.DryRun = true")
}
sweeperAssertIssueRows(t, ctx, fixture, 0, ids...)
}
// RunSweeperProtectsCitedRows pins ProtectReferenced
// (issueops.SweepRequest.ProtectReferenced): a candidate whose id appears in a
// not-done bead's description is held back, counted, and named in the bounded
// sample — and the SAME request without the protection deletes it.
//
// The two halves matter together. Asserting only the protection would pass for
// an implementation that skipped every candidate; asserting only the
// unprotected sweep would pass for one that never scanned at all.
//
// The citation is at a WORD BOUNDARY and there is a near-miss beside it, so an
// implementation that fell back to a bare substring search protects a row
// nothing cites.
func RunSweeperProtectsCitedRows(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
cited := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "ref", "cited", false), nil)
free := sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "ref", "free", false), nil)
citing := sweeperIssue(fixture, "ref", "live", false)
citing.Status = types.StatusOpen
citing.ClosedAt = nil
// The near-miss: `<cited>x` must NOT protect anything, and the parenthesised
// occurrence must.
citing.Description = fmt.Sprintf("superseded by (%s). unrelated: %sx", cited, free)
// The citing bead is OPEN, so the pattern below must not admit it as a
// candidate — it would be skipped by the closed recheck either way, but a
// case that relied on that would be asserting the wrong protection.
sweeperSeedOpen(t, ctx, fixture, citing)
request := publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: sweeperPattern(fixture, "ref"),
ProtectReferenced: true,
}
result := sweeperSweep(t, ctx, fixture, request)
if result.Skipped.Referenced != 1 {
t.Fatalf("Skipped.Referenced = %d, want 1 (sample %v)", result.Skipped.Referenced, result.ReferencedIDs)
}
if len(result.ReferencedIDs) != 1 || result.ReferencedIDs[0] != cited {
t.Errorf("ReferencedIDs = %v, want [%s]", result.ReferencedIDs, cited)
}
if result.Swept != 1 {
t.Errorf("Swept = %d, want 1 — the uncited candidate goes", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 1, cited)
sweeperAssertIssueRows(t, ctx, fixture, 0, free)
// Without the protection the same candidate goes, and nothing is reported
// as protected — a caller reading Referenced=0 without having asked has
// learned nothing, which the field doc says out loud.
request.ProtectReferenced = false
result = sweeperSweep(t, ctx, fixture, request)
if result.Skipped.Referenced != 0 {
t.Errorf("Skipped.Referenced = %d with ProtectReferenced false, want 0", result.Skipped.Referenced)
}
if result.Swept != 1 {
t.Errorf("Swept = %d, want 1 — the cited candidate is no longer protected", result.Swept)
}
sweeperAssertIssueRows(t, ctx, fixture, 0, cited)
}
// RunSweeperEmptyMatchIsZeroAndNil pins the not-found story
// (issueops.Sweeper.Sweep, "A REQUEST THAT MATCHES NOTHING"): a zero result and
// a nil error, which is the answer a scheduled sweep gets every time it runs
// after the first.
func RunSweeperEmptyMatchIsZeroAndNil(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
for _, tier := range []publicops.SweepTier{publicops.SweepDurable, publicops.SweepEphemeral} {
t.Run(string(tier), func(t *testing.T) {
result, err := fixture.Sweeper.Sweep(ctx, publicops.SweepRequest{
Tier: tier,
IDPattern: fixture.IssuePrefix + "-none-ever-*",
})
if err != nil {
t.Fatalf("Sweep(nothing matches) error = %v, want nil", err)
}
if result.Swept != 0 {
t.Errorf("Swept = %d, want 0", result.Swept)
}
if len(result.ReferencedIDs) != 0 {
t.Errorf("ReferencedIDs = %v, want empty", result.ReferencedIDs)
}
})
}
}
// RunSweeperRecordsAtMostOneHistoryEntry pins the versioning clause
// (issueops.Sweeper.Sweep, "A DRY RUN CHANGES NOTHING, including history"): a
// dry run and a no-op record NONE, and a sweep that deleted rows records at
// most ONE — the deletion is one act, not one per row.
//
// "AT MOST" rather than "exactly" is the honest promise across these backends:
// the server-backed store records a Dolt commit, the embedded one commits
// outside the SQL transaction and records none here, and an ephemeral sweep
// touches only tables the version-control plane ignores. A case demanding
// exactly one would be asserting a property of one wiring.
func RunSweeperRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
if fixture.CountHistory == nil {
t.Skip("this backend cannot observe history, so the entry-per-call clause is unobservable here")
}
ids := []string{
sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "hist", "1", false), nil),
sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, "hist", "2", false), nil),
}
request := publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: sweeperPattern(fixture, "hist"),
}
before := sweeperHistory(t, ctx, fixture)
sweeperSweep(t, ctx, fixture, sweeperWithDryRun(request, true))
if after := sweeperHistory(t, ctx, fixture); after != before {
t.Errorf("history went %d -> %d across a DRY RUN, want no entry at all", before, after)
}
before = sweeperHistory(t, ctx, fixture)
sweeperSweep(t, ctx, fixture, publicops.SweepRequest{
Tier: publicops.SweepDurable,
IDPattern: fixture.IssuePrefix + "-hist-nothing-*",
})
if after := sweeperHistory(t, ctx, fixture); after != before {
t.Errorf("history went %d -> %d across a sweep that deleted nothing, want no entry", before, after)
}
before = sweeperHistory(t, ctx, fixture)
sweeperSweep(t, ctx, fixture, request)
after := sweeperHistory(t, ctx, fixture)
if after < before || after > before+1 {
t.Errorf("history went %d -> %d across one sweep of %d rows, want at most one more entry",
before, after, len(ids))
}
}
// RunSweeperDoesNotMutateTheCallerRequest pins the no-mutation promise
// (issueops.SweepRequest: "Implementations never mutate caller-owned request
// values"). ClosedBefore is the pointer that would otherwise be written
// through, and a normalization step is exactly the kind of edit that does it.
func RunSweeperDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture SweeperFixture) {
t.Helper()
cutoff := sweeperCutoff
request := publicops.SweepRequest{
Tier: publicops.SweepDurable,
Actor: "sweeper-contract",
ClosedBefore: &cutoff,
IDPattern: sweeperPattern(fixture, "immutable"),
ProtectReferenced: true,
DryRun: true,
}
snapshot := request
snapshotCutoff := cutoff
if _, err := fixture.Sweeper.Sweep(ctx, request); err != nil {
t.Fatalf("Sweep() error = %v", err)
}
if !reflect.DeepEqual(request, snapshot) {
t.Errorf("request changed across the call: got %+v, want %+v", request, snapshot)
}
if !cutoff.Equal(snapshotCutoff) {
t.Errorf("the caller's cutoff changed: got %v, want %v", cutoff, snapshotCutoff)
}
}
// --- fixture helpers -------------------------------------------------------
// sweeperPattern is the glob that scopes one case's ids, and the reason every
// case has one: a sweep is asked of a whole tier.
func sweeperPattern(fixture SweeperFixture, tag string) string {
return fixture.IssuePrefix + "-" + tag + "-*"
}
func sweeperIssue(fixture SweeperFixture, tag, name string, ephemeral bool) *types.Issue {
closedAt := sweeperClosedAt
return &types.Issue{
ID: fmt.Sprintf("%s-%s-%s", fixture.IssuePrefix, tag, name),
Title: tag + " " + name,
Status: types.StatusClosed,
Priority: 2,
IssueType: types.TypeTask,
Ephemeral: ephemeral,
ClosedAt: &closedAt,
}
}
// sweeperSeed writes one issue through the plane its Ephemeral flag names and
// returns its id. mutate runs on the issue before it is written, which is how
// a case seeds a pinned row or moves a closed_at.
func sweeperSeed(t *testing.T, ctx context.Context, fixture SweeperFixture, issue *types.Issue, mutate func(*types.Issue)) string {
t.Helper()
if mutate != nil {
mutate(issue)
}
create := fixture.CreateIssue
if issue.Ephemeral {
create = fixture.CreateWisp
}
if err := create(ctx, issue, "sweeper-seed"); err != nil {
t.Fatalf("seeding %s: %v", issue.ID, err)
}
return issue.ID
}
func sweeperSeedClosedIssue(t *testing.T, ctx context.Context, fixture SweeperFixture, tag string, ephemeral bool) string {
t.Helper()
name := "durable"
if ephemeral {
name = "wisp"
}
return sweeperSeed(t, ctx, fixture, sweeperIssue(fixture, tag, name, ephemeral), nil)
}
func sweeperSeedOpen(t *testing.T, ctx context.Context, fixture SweeperFixture, issue *types.Issue) string {
t.Helper()
issue.Status = types.StatusOpen
issue.ClosedAt = nil
return sweeperSeed(t, ctx, fixture, issue, nil)
}
func sweeperWithDryRun(request publicops.SweepRequest, dryRun bool) publicops.SweepRequest {
request.DryRun = dryRun
return request
}
func sweeperSweep(t *testing.T, ctx context.Context, fixture SweeperFixture, request publicops.SweepRequest) publicops.SweepResult {
t.Helper()
result, err := fixture.Sweeper.Sweep(ctx, request)
if err != nil {
t.Fatalf("Sweep(%+v) error = %v", request, err)
}
return result
}
// sweeperAssertIssueRows counts the named ids in the ISSUES plane. It is the
// only assertion in this file that does not trust the result the sweep
// reported about itself, which on a destructive operation is the assertion
// that matters.
func sweeperAssertIssueRows(t *testing.T, ctx context.Context, fixture SweeperFixture, want int, ids ...string) {
t.Helper()
sweeperAssertRows(t, ctx, fixture, "issues", want, ids...)
}
func sweeperAssertWispRows(t *testing.T, ctx context.Context, fixture SweeperFixture, want int, ids ...string) {
t.Helper()
sweeperAssertRows(t, ctx, fixture, "wisps", want, ids...)
}
func sweeperAssertRows(t *testing.T, ctx context.Context, fixture SweeperFixture, table string, want int, ids ...string) {
t.Helper()
var got int
args := make([]any, len(ids))
placeholders := ""
for i, id := range ids {
args[i] = id
if i > 0 {
placeholders += ", "
}
placeholders += "?"
}
query := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id IN (%s)", table, placeholders)
if err := fixture.QueryScalar(ctx, query, args, &got); err != nil {
t.Fatalf("counting %s rows for %v: %v", table, ids, err)
}
if got != want {
t.Errorf("%s rows for %v = %d, want %d", table, ids, got, want)
}
}
func sweeperHistory(t *testing.T, ctx context.Context, fixture SweeperFixture) int {
t.Helper()
entries, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory: %v", err)
}
return entries
}

View file

@ -4,60 +4,38 @@ import (
"time"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
type closedDeletionCandidateStats struct {
PinnedSkipped int
NilSkipped int
NonClosedSkipped int
MissingClosedAtSkipped int
RecentClosedAtSkipped int
}
// The closed-candidate recheck used to live here in full, shared by `bd gc`,
// `bd purge` and `bd prune`. purge and prune are behind issueops.Sweeper now
// and the role applies it below both front doors; `bd gc` is not, so what is
// left here is a thin call into the SAME pure function
// (workapi.FilterSweepCandidates) plus gc's own warning line.
//
// One definition, two callers: gc and the role cannot come to disagree about
// what "a closed bead safe to delete" means, which is exactly the drift this
// file existed to prevent between purge and prune in the first place.
func (s closedDeletionCandidateStats) SafetySkipped() int {
return s.NilSkipped + s.NonClosedSkipped + s.MissingClosedAtSkipped + s.RecentClosedAtSkipped
}
type closedDeletionCandidateStats = issueops.SweepSkips
// filterClosedDeletionCandidates keeps the closed, unpinned, old-enough
// candidates and reports what it held back. `bd gc` matches no glob, so it
// passes the empty pattern, which admits everything.
func filterClosedDeletionCandidates(issues []*types.Issue, cutoff *time.Time) ([]*types.Issue, closedDeletionCandidateStats) {
filtered := make([]*types.Issue, 0, len(issues))
var stats closedDeletionCandidateStats
for _, issue := range issues {
if issue == nil {
stats.NilSkipped++
continue
}
if issue.Pinned {
stats.PinnedSkipped++
continue
}
if issue.Status != types.StatusClosed {
stats.NonClosedSkipped++
continue
}
if issue.ClosedAt == nil {
stats.MissingClosedAtSkipped++
continue
}
if cutoff != nil && !issue.ClosedAt.Before(*cutoff) {
stats.RecentClosedAtSkipped++
continue
}
filtered = append(filtered, issue)
}
return filtered, stats
return workapi.FilterSweepCandidates(issues, "", cutoff)
}
func warnClosedDeletionSafetySkips(stats closedDeletionCandidateStats) {
if stats.SafetySkipped() == 0 {
if workapi.SweepDefenseSkips(stats) == 0 {
return
}
WarnError("skipped %d deletion candidate(s) after closed_at safety recheck (nil=%d, non_closed=%d, missing_closed_at=%d, too_recent=%d)",
stats.SafetySkipped(),
stats.NilSkipped,
stats.NonClosedSkipped,
stats.MissingClosedAtSkipped,
stats.RecentClosedAtSkipped,
workapi.SweepDefenseSkips(stats),
stats.Unreadable,
stats.NotClosed,
stats.UnknownClosedAt,
stats.ClosedAtOrAfterCutoff,
)
}

View file

@ -1,72 +0,0 @@
package main
import (
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
)
func TestFilterClosedDeletionCandidatesRechecksClosedAtCutoff(t *testing.T) {
cutoff := time.Date(2026, 3, 27, 20, 1, 44, 0, time.UTC)
oldClosedAt := cutoff.Add(-time.Second)
recentClosedAt := cutoff.Add(time.Second)
candidates := []*types.Issue{
{ID: "old-closed", Status: types.StatusClosed, ClosedAt: &oldClosedAt},
{ID: "recent-closed", Status: types.StatusClosed, ClosedAt: &recentClosedAt},
{ID: "missing-closed-at", Status: types.StatusClosed},
{ID: "open-with-old-closed-at", Status: types.StatusOpen, ClosedAt: &oldClosedAt},
{ID: "pinned-old", Status: types.StatusClosed, ClosedAt: &oldClosedAt, Pinned: true},
nil,
}
filtered, stats := filterClosedDeletionCandidates(candidates, &cutoff)
if len(filtered) != 1 || filtered[0].ID != "old-closed" {
t.Fatalf("filtered IDs = %v, want only old-closed", closedDeletionCandidateIDs(filtered))
}
if stats.PinnedSkipped != 1 {
t.Fatalf("PinnedSkipped = %d, want 1", stats.PinnedSkipped)
}
if stats.RecentClosedAtSkipped != 1 {
t.Fatalf("RecentClosedAtSkipped = %d, want 1", stats.RecentClosedAtSkipped)
}
if stats.MissingClosedAtSkipped != 1 {
t.Fatalf("MissingClosedAtSkipped = %d, want 1", stats.MissingClosedAtSkipped)
}
if stats.NonClosedSkipped != 1 {
t.Fatalf("NonClosedSkipped = %d, want 1", stats.NonClosedSkipped)
}
if stats.NilSkipped != 1 {
t.Fatalf("NilSkipped = %d, want 1", stats.NilSkipped)
}
}
func TestFilterClosedDeletionCandidatesWithoutCutoffStillRequiresClosedAt(t *testing.T) {
closedAt := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
candidates := []*types.Issue{
{ID: "closed", Status: types.StatusClosed, ClosedAt: &closedAt},
{ID: "closed-missing-time", Status: types.StatusClosed},
}
filtered, stats := filterClosedDeletionCandidates(candidates, nil)
if len(filtered) != 1 || filtered[0].ID != "closed" {
t.Fatalf("filtered IDs = %v, want only closed", closedDeletionCandidateIDs(filtered))
}
if stats.MissingClosedAtSkipped != 1 {
t.Fatalf("MissingClosedAtSkipped = %d, want 1", stats.MissingClosedAtSkipped)
}
if stats.RecentClosedAtSkipped != 0 {
t.Fatalf("RecentClosedAtSkipped = %d, want 0 without cutoff", stats.RecentClosedAtSkipped)
}
}
func closedDeletionCandidateIDs(issues []*types.Issue) []string {
ids := make([]string, len(issues))
for i, issue := range issues {
ids[i] = issue.ID
}
return ids
}

View file

@ -4,6 +4,7 @@ import (
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/issueops"
)
var pruneCmd = &cobra.Command{
@ -53,14 +54,17 @@ EXAMPLES:
ignoreRefs, _ := cmd.Flags().GetBool("ignore-references")
return runPurgeOrPrune(cmd, purgeScope{
cmdName: "prune",
pastTense: "pruned",
countKey: "pruned_count",
dryRunCountKey: "prune_count",
subjectNoun: "closed bead",
ephemeralOnly: false,
requireFilter: true,
ignoreReferences: ignoreRefs,
cmdName: "prune",
pastTense: "pruned",
countKey: "pruned_count",
dryRunCountKey: "prune_count",
subjectNoun: "closed bead",
tier: issueops.SweepDurable,
// The flag is the NEGATIVE of the request field: --ignore-references
// asks the role NOT to protect. The reporting is unconditional, so
// `--json` keeps publishing the keys with the flag set.
protectReferenced: !ignoreRefs,
reportsReferences: true,
})
},
}

View file

@ -1,140 +0,0 @@
//go:build cgo
package main
import (
"context"
"fmt"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// mockRefStore satisfies storage.DoltStorage using only SearchIssues and
// GetIssueComments; all other methods panic if called.
type mockRefStore struct {
storage.DoltStorage
openBeads []*types.Issue
}
func (m *mockRefStore) SearchIssues(_ context.Context, _ string, _ types.IssueFilter) ([]*types.Issue, error) {
return m.openBeads, nil
}
func (m *mockRefStore) GetIssueComments(_ context.Context, _ string) ([]*types.Comment, error) {
return nil, nil
}
// GetCustomStatusesDetailed lets buildReferencedSet enumerate active custom
// statuses; this fixture configures none.
func (m *mockRefStore) GetCustomStatusesDetailed(_ context.Context) ([]types.CustomStatus, error) {
return nil, nil
}
func TestCandidateIDMatcherWordBoundaries(t *testing.T) {
candidates := map[string]bool{
"be-ref-001": true,
"be-ref-001.1": true,
"be-ref-002": true,
}
matcher := newCandidateIDMatcher(candidates)
found := make(map[string]bool)
matcher.findAll("see (be-ref-001), be-ref-001.1 and xbe-ref-002 but not be-ref-002x", found)
if !found["be-ref-001"] {
t.Fatal("expected be-ref-001 to match at punctuation boundaries")
}
if !found["be-ref-001.1"] {
t.Fatal("expected be-ref-001.1 to match at punctuation boundaries")
}
if found["be-ref-002"] {
t.Fatal("did not expect be-ref-002 to match inside word boundaries")
}
}
// TestPruneLargeFixture asserts that buildReferencedSet completes in <5s on a
// 10K-open-bead × ~5KB-body fixture (NFR-02 from be-5sn).
func TestPruneLargeFixture(t *testing.T) {
if testing.Short() {
t.Skip("skipping large fixture bench")
}
const (
openBeadCount = 10_000
candidateCount = 100
seededRefCount = 20
bodyPadding = 5_000 // bytes of filler per bead
maxDurationSeconds = 5
)
// Build 100 closed candidate IDs (be-ref-000 … be-ref-099).
candidates := make(map[string]bool, candidateCount)
for i := 0; i < candidateCount; i++ {
candidates[fmt.Sprintf("be-ref-%03d", i)] = true
}
// Build the seeded ID set (first 20 candidates).
seeded := make([]string, seededRefCount)
i := 0
for id := range candidates {
if i >= seededRefCount {
break
}
seeded[i] = id
i++
}
// Padding text that does NOT contain any candidate ID substring.
pad := strings.Repeat("x", bodyPadding)
// Create 10K open beads. Every 500th bead gets one seeded ID planted in
// its description so that exactly seededRefCount beads carry references.
openBeads := make([]*types.Issue, openBeadCount)
seededIdx := 0
for j := 0; j < openBeadCount; j++ {
desc := pad
if seededIdx < seededRefCount && j%500 == 0 {
desc = fmt.Sprintf("%s %s %s", pad[:100], seeded[seededIdx], pad[100:])
seededIdx++
}
openBeads[j] = &types.Issue{
ID: fmt.Sprintf("be-open-%05d", j),
Status: types.StatusOpen,
Description: desc,
}
}
st := &mockRefStore{openBeads: openBeads}
ctx := context.Background()
start := time.Now()
refSet, err := buildReferencedSet(ctx, st, candidates)
elapsed := time.Since(start)
if err != nil {
t.Fatalf("buildReferencedSet error: %v", err)
}
// Performance assertion (NFR-02). The race detector adds multi-x overhead
// that invalidates a wall-clock budget (buildReferencedSet measures ~4x
// slower under -race), so only enforce the bound in non-race builds. The
// correctness assertions below still run under -race, which is where the
// large-fixture pass earns its keep as a data-race check.
if !raceEnabled && elapsed > maxDurationSeconds*time.Second {
t.Errorf("buildReferencedSet took %v; must complete in <%ds on 10K-bead fixture", elapsed, maxDurationSeconds)
}
// Correctness assertion: exactly the seeded IDs should be in the reference set.
if len(refSet) != seededIdx {
t.Errorf("expected %d referenced IDs, got %d", seededIdx, len(refSet))
}
for _, id := range seeded[:seededIdx] {
if !refSet[id] {
t.Errorf("expected %s to be in refSet but it was not", id)
}
}
}

View file

@ -177,9 +177,15 @@ func TestProxiedServerPrune(t *testing.T) {
if got := readDoltLogCountSince(t, db, before); got < 1 {
t.Errorf("prune should create a dolt commit, got %d new commits", got)
}
// The label is the ROLE's, not this command's: one sweep, one entry,
// naming the operation and the tier it cleared. It used to read
// "bd: prune N bead(s)" here and "bd: delete N issue(s)" on the direct
// route, which named neither the command nor the tier — the two front
// doors now write the same sentence, and so does an HTTP sweep, where
// there is no `bd prune` to name.
msg := readDoltLogTopMessage(t, db)
if !strings.HasPrefix(msg, "bd: prune ") {
t.Errorf("dolt commit message should begin with 'bd: prune ', got: %q", msg)
if !strings.HasPrefix(msg, "bd: sweep ") || !strings.Contains(msg, "durable") {
t.Errorf("dolt commit message should name the sweep and its tier, got: %q", msg)
}
})
}

View file

@ -1,24 +1,26 @@
package main
import (
"context"
"fmt"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
// purgeScope parameterizes the shared purge/prune implementation so both
// commands can share filter plumbing, preview/dry-run/force semantics, and
// messaging without copying 200 lines of boilerplate.
// purgeScope is what `bd purge` and `bd prune` still differ by once the
// operation itself is behind issueops.Sweeper: a tier, a reference policy, and
// the words each command prints.
//
// It used to carry the SEMANTICS too — ephemeralOnly, requireFilter,
// ignoreReferences — and each route read them and re-derived the same
// selection, the same pinned protection and the same safety gate from them.
// All of that is request fields now, so what is left here is presentation plus
// the two request values a flag chooses.
type purgeScope struct {
// cmdName is the user-visible command name (e.g. "purge", "prune").
// Used in messages and the suggested `--force` hint.
@ -33,18 +35,18 @@ type purgeScope struct {
// (e.g. "closed ephemeral bead", "closed bead"). "(s)" is appended by
// the printer when multiple items are involved.
subjectNoun string
// ephemeralOnly restricts the filter to ephemeral beads when true.
// When false, restricts to non-ephemeral beads — the scopes are
// deliberately disjoint so `prune` never touches wisps that `purge`
// would handle, and vice versa.
ephemeralOnly bool
// requireFilter forces the user to pass --older-than or --pattern.
// Without this gate, `bd prune --force` would silently delete every
// closed non-ephemeral bead in the repo.
requireFilter bool
// ignoreReferences, when true, bypasses the reference-aware skip in prune.
// Always false for purge — ephemeral beads' references are themselves transient.
ignoreReferences bool
// tier is the plane this command sweeps. The two are DISJOINT, which is
// what makes purge and prune one capability rather than two: `prune` never
// touches a wisp that `purge` would handle, and vice versa.
tier issueops.SweepTier
// protectReferenced asks the role to skip candidates cited by a bead that
// is not done. `bd prune` asks unless --ignore-references; `bd purge`
// never does, because a wisp's citations are as transient as the wisp.
protectReferenced bool
// reportsReferences publishes the reference-skip keys under --json. It is
// separate from protectReferenced because `bd prune --ignore-references`
// still publishes them, as zeroes, which is the shipped shape.
reportsReferences bool
}
var purgeCmd = &cobra.Command{
@ -87,138 +89,39 @@ EXAMPLES:
countKey: "purged_count",
dryRunCountKey: "purge_count",
subjectNoun: "closed ephemeral bead",
ephemeralOnly: true,
requireFilter: false,
tier: issueops.SweepEphemeral,
})
},
}
// buildReferencedSet scans every non-closed bead's description, notes, and
// comments for literal occurrences of any candidate ID and returns the set of
// candidate IDs that were found. Uses a Statuses filter (not ExcludeStatus)
// to avoid the PG ExcludeStatus coverage gap (be-jdeief).
func buildReferencedSet(ctx context.Context, st storage.DoltStorage, candidateIDs map[string]bool) (map[string]bool, error) {
if len(candidateIDs) == 0 {
return nil, nil
// openSweeper hands back the bulk-clearance role for whichever route this
// invocation is on, each through its OWN capability accessor — the store's for
// the direct route and the provider's for the proxied one.
//
// Neither branch builds a filter, matches a glob, rechecks closed_at or scans
// for citations. That is the whole of what moved behind the role, and it used
// to be written out twice, once per route, with the selection and the deletion
// in two DIFFERENT transactions on this one.
func openSweeper() (issueops.Sweeper, error) {
if usesProxiedServer() {
return proxiedSweeper()
}
matcher := newCandidateIDMatcher(candidateIDs)
// Scan every non-done bead: built-in active statuses plus any configured
// custom statuses whose category is not "done". A repo can define custom
// statuses (status.custom) in active/wip/frozen categories; a bead in such
// a status that cites a closed bead must protect it from prune exactly like
// a built-in open bead does. Reading custom statuses is required, not
// best-effort: if we cannot enumerate them we must not under-scan and risk
// deleting a referenced bead, so the error propagates and aborts the prune.
notClosedStatuses := []types.Status{
types.StatusOpen,
types.StatusInProgress,
types.StatusBlocked,
types.StatusDeferred,
types.StatusPinned,
types.StatusHooked,
}
customStatuses, err := st.GetCustomStatusesDetailed(ctx)
if err != nil {
return nil, fmt.Errorf("reading custom statuses for reference scan: %w", err)
}
for _, cs := range customStatuses {
if cs.Category != types.CategoryDone {
notClosedStatuses = append(notClosedStatuses, types.Status(cs.Name))
}
}
notClosed := types.IssueFilter{Statuses: notClosedStatuses}
openBeads, err := st.SearchIssues(ctx, "", notClosed)
if err != nil {
return nil, err
}
refSet := make(map[string]bool)
scanText := func(text string) {
matcher.findAll(text, refSet)
}
for _, iss := range openBeads {
scanText(iss.Description)
scanText(iss.Notes)
comments, err := st.GetIssueComments(ctx, iss.ID)
if err != nil {
if store == nil {
if err := ensureStoreActive(); err != nil {
return nil, err
}
for _, c := range comments {
scanText(c.Text)
}
}
return refSet, nil
return store.Sweeper()
}
type candidateIDMatcher struct {
byFirstByte map[byte][]string
}
func newCandidateIDMatcher(candidateIDs map[string]bool) candidateIDMatcher {
byFirstByte := make(map[byte][]string)
for id := range candidateIDs {
if id == "" {
continue
}
byFirstByte[id[0]] = append(byFirstByte[id[0]], id)
}
for first := range byFirstByte {
ids := byFirstByte[first]
sort.Slice(ids, func(i, j int) bool {
if len(ids[i]) == len(ids[j]) {
return ids[i] < ids[j]
}
return len(ids[i]) > len(ids[j])
})
byFirstByte[first] = ids
}
return candidateIDMatcher{byFirstByte: byFirstByte}
}
func (m candidateIDMatcher) findAll(text string, found map[string]bool) {
for i := 0; i < len(text); i++ {
ids := m.byFirstByte[text[i]]
if len(ids) == 0 || !isWordBoundaryAt(text, i) {
continue
}
for _, id := range ids {
end := i + len(id)
if end <= len(text) && strings.HasPrefix(text[i:], id) && isWordBoundaryAt(text, end) {
found[id] = true
break
}
}
}
}
func isWordBoundaryAt(s string, idx int) bool {
var before, after byte
if idx > 0 {
before = s[idx-1]
}
if idx < len(s) {
after = s[idx]
}
return isASCIIWordByte(before) != isASCIIWordByte(after)
}
func isASCIIWordByte(b byte) bool {
return b == '_' ||
('0' <= b && b <= '9') ||
('A' <= b && b <= 'Z') ||
('a' <= b && b <= 'z')
}
// runPurgeOrPrune implements the shared delete-closed-beads flow used by
// both `bd purge` (ephemeral scope) and `bd prune` (non-ephemeral scope).
// The caller's scope controls the filter, messaging, and safety gate.
// runPurgeOrPrune implements the shared delete-closed-beads flow used by both
// `bd purge` (ephemeral tier) and `bd prune` (durable tier).
//
// It is ONE body across both routes now rather than two: the proxied twin held
// a second copy of the selection, the recheck, the reference scan and every
// line of output, and the two routes disagreed about which transaction the
// deletion ran in.
func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
if usesProxiedServer() {
return runPurgeOrPruneProxied(cmd, scope)
}
CheckReadonly(scope.cmdName)
force, _ := cmd.Flags().GetBool("force")
@ -226,7 +129,15 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
olderThan, _ := cmd.Flags().GetString("older-than")
pattern, _ := cmd.Flags().GetString("pattern")
if scope.requireFilter && olderThan == "" && pattern == "" {
// The ROLE refuses an unfiltered durable sweep — that guard is
// workapi.ValidateSweepRequest, below every front door, so an HTTP handler
// or a library embedder inherits it instead of having to remember it. This
// branch is here for the MESSAGE and nothing else: the role's refusal
// names request fields, and a person who typed `bd prune --force` needs to
// be told which two flags to reach for. The contract case
// RunSweeperRefusesAnUnfilteredDurableSweep is what proves the guard
// survives this branch being deleted.
if scope.tier == issueops.SweepDurable && olderThan == "" && pattern == "" {
return HandleErrorWithHint(
fmt.Sprintf("bd %s requires --older-than or --pattern", scope.cmdName),
"Protects against accidental bulk deletion. Use `--pattern '*'` to\n"+
@ -234,228 +145,194 @@ func runPurgeOrPrune(cmd *cobra.Command, scope purgeScope) error {
" / `--pattern '<glob>'` to narrow the deletion.")
}
if store == nil {
if err := ensureStoreActive(); err != nil {
return HandleErrorRespectJSON("%v", err)
}
request := issueops.SweepRequest{
Actor: actor,
Tier: scope.tier,
IDPattern: pattern,
ProtectReferenced: scope.protectReferenced,
// A --dry-run and an UNCONFIRMED run ask the role the same question —
// "what would this do" — so both send DryRun. --force is this
// command's confirmation, not a request field, and a sweep that
// answered the confirmation prompt by deleting would be the worst
// possible reading of it.
DryRun: dryRun || !force,
}
ctx := rootCtx
statusClosed := types.StatusClosed
ephemeralFlag := scope.ephemeralOnly
filter := types.IssueFilter{
Status: &statusClosed,
Ephemeral: &ephemeralFlag,
}
var cutoff *time.Time
if olderThan != "" {
days, err := parseHumanDuration(olderThan)
if err != nil {
return HandleErrorRespectJSON("invalid --older-than value %q: %v", olderThan, err)
}
cutoffTime := time.Now().UTC().AddDate(0, 0, -days)
cutoff = &cutoffTime
filter.ClosedBefore = cutoff
cutoff := time.Now().UTC().AddDate(0, 0, -days)
request.ClosedBefore = &cutoff
}
closedIssues, err := store.SearchIssues(ctx, "", filter)
sweeper, err := openSweeper()
if err != nil {
return HandleErrorRespectJSON("listing issues: %v", err)
return HandleErrorRespectJSON("%v", err)
}
if pattern != "" {
var matched []*types.Issue
for _, issue := range closedIssues {
if ok, _ := filepath.Match(pattern, issue.ID); ok {
matched = append(matched, issue)
}
}
closedIssues = matched
}
var safetyStats closedDeletionCandidateStats
closedIssues, safetyStats = filterClosedDeletionCandidates(closedIssues, cutoff)
pinnedCount := safetyStats.PinnedSkipped
warnClosedDeletionSafetySkips(safetyStats)
// Reference-aware skip (prune only): filter closed beads cited by open beads.
referencedCount := 0
var referencedSample []string
if scope.cmdName == "prune" && !scope.ignoreReferences {
candidateIDs := make(map[string]bool, len(closedIssues))
for _, iss := range closedIssues {
candidateIDs[iss.ID] = true
}
refSet, err := buildReferencedSet(ctx, store, candidateIDs)
if err != nil {
return HandleErrorRespectJSON("scanning open beads for references: %v", err)
}
nonReferenced := closedIssues[:0]
for _, iss := range closedIssues {
if refSet[iss.ID] {
referencedCount++
if len(referencedSample) < 100 {
referencedSample = append(referencedSample, iss.ID)
}
} else {
nonReferenced = append(nonReferenced, iss)
}
}
closedIssues = nonReferenced
}
if len(closedIssues) == 0 {
if jsonOutput {
stats := map[string]interface{}{
scope.countKey: 0,
"message": fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName),
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
}
return outputJSON(stats)
}
msg := fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName)
if olderThan != "" {
msg += fmt.Sprintf(" (older than %s)", olderThan)
}
if pattern != "" {
msg += fmt.Sprintf(" (matching %q)", pattern)
}
fmt.Println(msg)
if referencedCount > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf(
" (%d closed bead(s) protected by open-bead references — use --ignore-references to override)",
referencedCount)))
}
return nil
}
issueIDs := make([]string, len(closedIssues))
for i, issue := range closedIssues {
issueIDs[i] = issue.ID
}
if dryRun {
result, err := store.DeleteIssues(ctx, issueIDs, false, false, true)
if jsonOutput {
stats := map[string]interface{}{
"dry_run": true,
scope.dryRunCountKey: len(issueIDs),
"dependencies": 0,
"labels": 0,
"events": 0,
}
if err == nil {
stats["dependencies"] = result.DependenciesCount
stats["labels"] = result.LabelsCount
stats["events"] = result.EventsCount
}
if pinnedCount > 0 {
stats["pinned_skipped"] = pinnedCount
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
}
return outputJSON(stats)
}
fmt.Printf("Would %s %d %s(s)\n", scope.cmdName, len(issueIDs), scope.subjectNoun)
if err == nil {
fmt.Printf(" Dependencies: %d\n", result.DependenciesCount)
fmt.Printf(" Labels: %d\n", result.LabelsCount)
fmt.Printf(" Events: %d\n", result.EventsCount)
}
if pinnedCount > 0 {
fmt.Printf(" Pinned (skipped): %d\n", pinnedCount)
}
if referencedCount > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), referencedCount)
sample := referencedSample
if len(sample) > 5 {
sample = sample[:5]
}
idStrs := make([]string, len(sample))
for i, id := range sample {
idStrs[i] = ui.IDStyle.Render(id)
}
suffix := ""
if referencedCount > 5 {
suffix = ui.MutedStyle.Render(", ...")
}
fmt.Printf(" %s %s%s\n", ui.MutedStyle.Render("Referenced IDs (sample):"), strings.Join(idStrs, ", "), suffix)
}
fmt.Printf("\n(Dry-run mode — no changes made)\n")
return nil
}
if !force {
fmt.Printf("Found %d %s(s) to %s\n", len(issueIDs), scope.subjectNoun, scope.cmdName)
if pinnedCount > 0 {
fmt.Printf("Skipping %d pinned bead(s)\n", pinnedCount)
}
if referencedCount > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf("Skipping %d referenced bead(s)", referencedCount)))
}
hint := fmt.Sprintf("bd %s --force", scope.cmdName)
if olderThan != "" {
hint += " --older-than " + olderThan
}
if pattern != "" {
hint += " --pattern " + pattern
}
return HandleErrorWithHint(
fmt.Sprintf("would %s %d bead(s)", scope.cmdName, len(issueIDs)),
fmt.Sprintf("Use --force to confirm or --dry-run to preview.\n %s", hint))
}
result, err := store.DeleteIssues(ctx, issueIDs, false, true, false)
result, err := sweeper.Sweep(rootCtx, request)
if err != nil {
return HandleErrorRespectJSON("%s failed: %v", scope.cmdName, err)
}
commandDidWrite.Store(true)
if result.DeletedCount > 0 {
commandMayEmptyJSONLExport.Store(true)
warnSweepDefenseSkips(result.Skipped)
switch {
case result.Swept == 0:
return emitSweepEmpty(scope, olderThan, pattern, result)
case dryRun:
return emitSweepDryRun(scope, result)
case !force:
return emitSweepConfirm(scope, olderThan, pattern, result)
}
commandDidWrite.Store(true)
commandMayEmptyJSONLExport.Store(true)
return emitSweepResult(scope, result)
}
// warnSweepDefenseSkips reports the candidates the role's own recheck threw
// out. A non-zero count means the tier query and the recheck disagreed about
// which rows are closed, which is worth a line on stderr whatever the output
// mode — see issueops.SweepSkips.
func warnSweepDefenseSkips(skips issueops.SweepSkips) {
total := skips.Unreadable + skips.NotClosed + skips.UnknownClosedAt + skips.ClosedAtOrAfterCutoff
if total == 0 {
return
}
WarnError("skipped %d deletion candidate(s) after closed_at safety recheck (nil=%d, non_closed=%d, missing_closed_at=%d, too_recent=%d)",
total,
skips.Unreadable,
skips.NotClosed,
skips.UnknownClosedAt,
skips.ClosedAtOrAfterCutoff,
)
}
// addReferenceStats attaches the reference-skip members to a --json payload.
// `bd prune` publishes them whether or not the protection was asked for, which
// is the shipped shape; `bd purge` never does.
func addReferenceStats(scope purgeScope, stats map[string]interface{}, result issueops.SweepResult) {
if !scope.reportsReferences {
return
}
stats["referenced_skipped"] = result.Skipped.Referenced
stats["referenced_count"] = result.Skipped.Referenced
if len(result.ReferencedIDs) > 0 {
stats["referenced_ids_sample"] = result.ReferencedIDs
}
}
func emitSweepEmpty(scope purgeScope, olderThan, pattern string, result issueops.SweepResult) error {
if jsonOutput {
stats := map[string]interface{}{
scope.countKey: result.DeletedCount,
"dependencies": result.DependenciesCount,
"labels": result.LabelsCount,
"events": result.EventsCount,
}
if pinnedCount > 0 {
stats["pinned_skipped"] = pinnedCount
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
scope.countKey: 0,
"message": fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName),
}
addReferenceStats(scope, stats, result)
return outputJSON(stats)
}
fmt.Printf("%s %s %d %s(s)\n", ui.RenderPass("✓"), capitalize(scope.pastTense), result.DeletedCount, scope.subjectNoun)
fmt.Printf(" Dependencies removed: %d\n", result.DependenciesCount)
fmt.Printf(" Labels removed: %d\n", result.LabelsCount)
fmt.Printf(" Events removed: %d\n", result.EventsCount)
if pinnedCount > 0 {
fmt.Printf(" Pinned (skipped): %d\n", pinnedCount)
msg := fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName)
if olderThan != "" {
msg += fmt.Sprintf(" (older than %s)", olderThan)
}
if referencedCount > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), referencedCount)
if pattern != "" {
msg += fmt.Sprintf(" (matching %q)", pattern)
}
fmt.Println(msg)
if result.Skipped.Referenced > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf(
" (%d closed bead(s) protected by open-bead references — use --ignore-references to override)",
result.Skipped.Referenced)))
}
return nil
}
func emitSweepDryRun(scope purgeScope, result issueops.SweepResult) error {
if jsonOutput {
stats := map[string]interface{}{
"dry_run": true,
scope.dryRunCountKey: result.Swept,
"dependencies": result.Dependencies,
"labels": result.Labels,
"events": result.Events,
}
if result.Skipped.Pinned > 0 {
stats["pinned_skipped"] = result.Skipped.Pinned
}
addReferenceStats(scope, stats, result)
return outputJSON(stats)
}
fmt.Printf("Would %s %d %s(s)\n", scope.cmdName, result.Swept, scope.subjectNoun)
fmt.Printf(" Dependencies: %d\n", result.Dependencies)
fmt.Printf(" Labels: %d\n", result.Labels)
fmt.Printf(" Events: %d\n", result.Events)
if result.Skipped.Pinned > 0 {
fmt.Printf(" Pinned (skipped): %d\n", result.Skipped.Pinned)
}
if result.Skipped.Referenced > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), result.Skipped.Referenced)
sample := result.ReferencedIDs
if len(sample) > 5 {
sample = sample[:5]
}
idStrs := make([]string, len(sample))
for i, id := range sample {
idStrs[i] = ui.IDStyle.Render(id)
}
suffix := ""
if result.Skipped.Referenced > 5 {
suffix = ui.MutedStyle.Render(", ...")
}
fmt.Printf(" %s %s%s\n", ui.MutedStyle.Render("Referenced IDs (sample):"), strings.Join(idStrs, ", "), suffix)
}
fmt.Printf("\n(Dry-run mode — no changes made)\n")
return nil
}
func emitSweepConfirm(scope purgeScope, olderThan, pattern string, result issueops.SweepResult) error {
fmt.Printf("Found %d %s(s) to %s\n", result.Swept, scope.subjectNoun, scope.cmdName)
if result.Skipped.Pinned > 0 {
fmt.Printf("Skipping %d pinned bead(s)\n", result.Skipped.Pinned)
}
if result.Skipped.Referenced > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf("Skipping %d referenced bead(s)", result.Skipped.Referenced)))
}
hint := fmt.Sprintf("bd %s --force", scope.cmdName)
if olderThan != "" {
hint += " --older-than " + olderThan
}
if pattern != "" {
hint += " --pattern " + pattern
}
return HandleErrorWithHint(
fmt.Sprintf("would %s %d bead(s)", scope.cmdName, result.Swept),
fmt.Sprintf("Use --force to confirm or --dry-run to preview.\n %s", hint))
}
func emitSweepResult(scope purgeScope, result issueops.SweepResult) error {
if jsonOutput {
stats := map[string]interface{}{
scope.countKey: result.Swept,
"dependencies": result.Dependencies,
"labels": result.Labels,
"events": result.Events,
}
if result.Skipped.Pinned > 0 {
stats["pinned_skipped"] = result.Skipped.Pinned
}
addReferenceStats(scope, stats, result)
return outputJSON(stats)
}
fmt.Printf("%s %s %d %s(s)\n", ui.RenderPass("✓"), capitalize(scope.pastTense), result.Swept, scope.subjectNoun)
fmt.Printf(" Dependencies removed: %d\n", result.Dependencies)
fmt.Printf(" Labels removed: %d\n", result.Labels)
fmt.Printf(" Events removed: %d\n", result.Events)
if result.Skipped.Pinned > 0 {
fmt.Printf(" Pinned (skipped): %d\n", result.Skipped.Pinned)
}
if result.Skipped.Referenced > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), result.Skipped.Referenced)
}
return nil
}

View file

@ -1,359 +1,32 @@
package main
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
type purgeProxiedTxResult struct {
empty bool
dryRun bool
needsConfirm bool
issueIDs []string
deleteResult domain.DeleteIssuesResult
deleteErr error
pinnedCount int
referencedCount int
referencedSample []string
safetyStats closedDeletionCandidateStats
}
func runPurgeOrPruneProxied(cmd *cobra.Command, scope purgeScope) error {
CheckReadonly(scope.cmdName)
force, _ := cmd.Flags().GetBool("force")
dryRun, _ := cmd.Flags().GetBool("dry-run")
olderThan, _ := cmd.Flags().GetString("older-than")
pattern, _ := cmd.Flags().GetString("pattern")
if scope.requireFilter && olderThan == "" && pattern == "" {
return HandleErrorWithHint(
fmt.Sprintf("bd %s requires --older-than or --pattern", scope.cmdName),
"Protects against accidental bulk deletion. Use `--pattern '*'` to\n"+
" include all closed beads in this scope, or `--older-than 1d`\n"+
" / `--pattern '<glob>'` to narrow the deletion.")
}
// proxiedSweeper hands back the guarded bulk-clearance surface for the
// proxied-server provider, through the provider's OWN capability accessor —
// the same two-step proxiedCounter performs, and for the same reason: the
// accessor is where each layer is added.
//
// This file used to hold a second copy of `bd purge` and `bd prune`: it parsed
// the flags again, opened a unit of work, built the candidate filter, matched
// the glob, re-applied the pinned and closed_at rechecks, ran its own
// reference scan, and then printed 190 lines of output that had to be kept
// character-identical to the direct route's by hand. All of that is behind the
// role now, so the proxied route differs from the direct one by which accessor
// it asks and nothing else.
func proxiedSweeper() (issueops.Sweeper, error) {
if uowProvider == nil {
return HandleErrorRespectJSON("proxied-server UOW provider not initialized")
return nil, errors.New("proxied-server UOW provider not initialized")
}
ctx := rootCtx
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (purgeProxiedTxResult, string, error) {
var result purgeProxiedTxResult
statusClosed := types.StatusClosed
ephemeralFlag := scope.ephemeralOnly
filter := types.IssueFilter{
Status: &statusClosed,
Ephemeral: &ephemeralFlag,
}
var cutoff *time.Time
if olderThan != "" {
days, err := parseHumanDuration(olderThan)
if err != nil {
return result, "", fmt.Errorf("invalid --older-than value %q: %w", olderThan, err)
}
cutoffTime := time.Now().UTC().AddDate(0, 0, -days)
cutoff = &cutoffTime
filter.ClosedBefore = cutoff
}
page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter)
if err != nil {
return result, "", fmt.Errorf("listing issues: %w", err)
}
closedIssues := page.Items
if pattern != "" {
var matched []*types.Issue
for _, issue := range closedIssues {
if ok, _ := filepath.Match(pattern, issue.ID); ok {
matched = append(matched, issue)
}
}
closedIssues = matched
}
closedIssues, result.safetyStats = filterClosedDeletionCandidates(closedIssues, cutoff)
result.pinnedCount = result.safetyStats.PinnedSkipped
if scope.cmdName == "prune" && !scope.ignoreReferences {
candidateIDs := make(map[string]bool, len(closedIssues))
for _, iss := range closedIssues {
candidateIDs[iss.ID] = true
}
refSet, err := buildReferencedSetProxied(ctx, uw, candidateIDs)
if err != nil {
return result, "", fmt.Errorf("scanning open beads for references: %w", err)
}
nonReferenced := closedIssues[:0]
for _, iss := range closedIssues {
if refSet[iss.ID] {
result.referencedCount++
if len(result.referencedSample) < 100 {
result.referencedSample = append(result.referencedSample, iss.ID)
}
} else {
nonReferenced = append(nonReferenced, iss)
}
}
closedIssues = nonReferenced
}
if len(closedIssues) == 0 {
result.empty = true
return result, "", nil
}
result.issueIDs = make([]string, len(closedIssues))
for i, issue := range closedIssues {
result.issueIDs[i] = issue.ID
}
if dryRun {
result.dryRun = true
result.deleteResult, result.deleteErr = uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: result.issueIDs,
DryRun: true,
}, actor)
return result, "", nil
}
if !force {
result.needsConfirm = true
return result, "", nil
}
deleteResult, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: result.issueIDs,
}, actor)
if err != nil {
return result, "", fmt.Errorf("%s failed: %w", scope.cmdName, err)
}
result.deleteResult = deleteResult
return result, fmt.Sprintf("bd: %s %d bead(s)", scope.cmdName, deleteResult.DeletedCount), nil
})
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
warnClosedDeletionSafetySkips(res.safetyStats)
switch {
case res.empty:
return emitProxiedPruneEmpty(scope, olderThan, pattern, res.referencedCount, res.referencedSample)
case res.dryRun:
return emitProxiedPruneDryRun(scope, res.issueIDs, res.deleteResult, res.deleteErr, res.pinnedCount, res.referencedCount, res.referencedSample)
case res.needsConfirm:
return emitProxiedPruneConfirm(scope, res.issueIDs, olderThan, pattern, res.pinnedCount, res.referencedCount)
default:
return emitProxiedPruneResult(scope, res.deleteResult, res.pinnedCount, res.referencedCount, res.referencedSample)
src, ok := uowProvider.(uow.SweeperSource)
if !ok {
return nil, fmt.Errorf("proxied-server provider %T does not offer the bulk-clearance surface", uowProvider)
}
}
func buildReferencedSetProxied(ctx context.Context, uw uow.UnitOfWork, candidateIDs map[string]bool) (map[string]bool, error) {
if len(candidateIDs) == 0 {
return nil, nil
}
matcher := newCandidateIDMatcher(candidateIDs)
notClosedStatuses := []types.Status{
types.StatusOpen,
types.StatusInProgress,
types.StatusBlocked,
types.StatusDeferred,
types.StatusPinned,
types.StatusHooked,
}
customStatuses, err := uw.ConfigUseCase().GetCustomStatuses(ctx)
if err != nil {
return nil, fmt.Errorf("reading custom statuses for reference scan: %w", err)
}
for _, cs := range customStatuses {
if cs.Category != types.CategoryDone {
notClosedStatuses = append(notClosedStatuses, types.Status(cs.Name))
}
}
notClosed := types.IssueFilter{Statuses: notClosedStatuses}
page, err := uw.IssueUseCase().SearchIssues(ctx, "", notClosed)
if err != nil {
return nil, err
}
openBeads := page.Items
openIDs := make([]string, len(openBeads))
for i, iss := range openBeads {
openIDs[i] = iss.ID
}
commentsByIssue, err := uw.CommentUseCase().GetCommentsForIssues(ctx, openIDs)
if err != nil {
return nil, err
}
refSet := make(map[string]bool)
scanText := func(text string) {
matcher.findAll(text, refSet)
}
for _, iss := range openBeads {
scanText(iss.Description)
scanText(iss.Notes)
for _, c := range commentsByIssue[iss.ID] {
scanText(c.Text)
}
}
return refSet, nil
}
func emitProxiedPruneEmpty(scope purgeScope, olderThan, pattern string, referencedCount int, referencedSample []string) error {
if jsonOutput {
stats := map[string]interface{}{
scope.countKey: 0,
"message": fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName),
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
}
return outputJSON(stats)
}
msg := fmt.Sprintf("No %ss to %s", scope.subjectNoun, scope.cmdName)
if olderThan != "" {
msg += fmt.Sprintf(" (older than %s)", olderThan)
}
if pattern != "" {
msg += fmt.Sprintf(" (matching %q)", pattern)
}
fmt.Println(msg)
if referencedCount > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf(
" (%d closed bead(s) protected by open-bead references — use --ignore-references to override)",
referencedCount)))
}
return nil
}
func emitProxiedPruneDryRun(scope purgeScope, issueIDs []string, result domain.DeleteIssuesResult, resultErr error, pinnedCount, referencedCount int, referencedSample []string) error {
if jsonOutput {
stats := map[string]interface{}{
"dry_run": true,
scope.dryRunCountKey: len(issueIDs),
"dependencies": 0,
"labels": 0,
"events": 0,
}
if resultErr == nil {
stats["dependencies"] = result.DependenciesCount
stats["labels"] = result.LabelsCount
stats["events"] = result.EventsCount
}
if pinnedCount > 0 {
stats["pinned_skipped"] = pinnedCount
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
}
return outputJSON(stats)
}
fmt.Printf("Would %s %d %s(s)\n", scope.cmdName, len(issueIDs), scope.subjectNoun)
if resultErr == nil {
fmt.Printf(" Dependencies: %d\n", result.DependenciesCount)
fmt.Printf(" Labels: %d\n", result.LabelsCount)
fmt.Printf(" Events: %d\n", result.EventsCount)
}
if pinnedCount > 0 {
fmt.Printf(" Pinned (skipped): %d\n", pinnedCount)
}
if referencedCount > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), referencedCount)
sample := referencedSample
if len(sample) > 5 {
sample = sample[:5]
}
idStrs := make([]string, len(sample))
for i, id := range sample {
idStrs[i] = ui.IDStyle.Render(id)
}
suffix := ""
if referencedCount > 5 {
suffix = ui.MutedStyle.Render(", ...")
}
fmt.Printf(" %s %s%s\n", ui.MutedStyle.Render("Referenced IDs (sample):"), strings.Join(idStrs, ", "), suffix)
}
fmt.Printf("\n(Dry-run mode — no changes made)\n")
return nil
}
func emitProxiedPruneConfirm(scope purgeScope, issueIDs []string, olderThan, pattern string, pinnedCount, referencedCount int) error {
fmt.Printf("Found %d %s(s) to %s\n", len(issueIDs), scope.subjectNoun, scope.cmdName)
if pinnedCount > 0 {
fmt.Printf("Skipping %d pinned bead(s)\n", pinnedCount)
}
if referencedCount > 0 {
fmt.Println(ui.MutedStyle.Render(fmt.Sprintf("Skipping %d referenced bead(s)", referencedCount)))
}
hint := fmt.Sprintf("bd %s --force", scope.cmdName)
if olderThan != "" {
hint += " --older-than " + olderThan
}
if pattern != "" {
hint += " --pattern " + pattern
}
return HandleErrorWithHint(
fmt.Sprintf("would %s %d bead(s)", scope.cmdName, len(issueIDs)),
fmt.Sprintf("Use --force to confirm or --dry-run to preview.\n %s", hint))
}
func emitProxiedPruneResult(scope purgeScope, result domain.DeleteIssuesResult, pinnedCount, referencedCount int, referencedSample []string) error {
if jsonOutput {
stats := map[string]interface{}{
scope.countKey: result.DeletedCount,
"dependencies": result.DependenciesCount,
"labels": result.LabelsCount,
"events": result.EventsCount,
}
if pinnedCount > 0 {
stats["pinned_skipped"] = pinnedCount
}
if scope.cmdName == "prune" {
stats["referenced_skipped"] = referencedCount
stats["referenced_count"] = referencedCount
if len(referencedSample) > 0 {
stats["referenced_ids_sample"] = referencedSample
}
}
return outputJSON(stats)
}
fmt.Printf("%s %s %d %s(s)\n", ui.RenderPass("✓"), capitalize(scope.pastTense), result.DeletedCount, scope.subjectNoun)
fmt.Printf(" Dependencies removed: %d\n", result.DependenciesCount)
fmt.Printf(" Labels removed: %d\n", result.LabelsCount)
fmt.Printf(" Events removed: %d\n", result.EventsCount)
if pinnedCount > 0 {
fmt.Printf(" Pinned (skipped): %d\n", pinnedCount)
}
if referencedCount > 0 {
fmt.Printf(" %s %d\n", ui.MutedStyle.Render("Referenced (skipped):"), referencedCount)
}
return nil
return src.Sweeper()
}

View file

@ -77,7 +77,17 @@ WHAT THIS DOES NOT DO
An actor on an HTTP request is caller-asserted provenance for the audit trail,
not authenticated identity — the same thing it has always been on the CLI,
where any local process can pass any --actor.`,
where any local process can pass any --actor.
DESTRUCTIVE OPERATIONS
POST /v0/beads/issues:sweep deletes closed beads in bulk — the operation
behind bd purge and bd prune — and nothing it deletes comes back. It shares
the library surface those commands call, so it inherits their guards: pinned
beads are never swept, and a durable sweep with neither a cutoff nor an id
pattern is refused rather than clearing every closed bead in the workspace.
Combined with the trust model above, that means anyone who can reach this
address can erase closed work; bind it accordingly.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runServe()
@ -152,7 +162,8 @@ func runServe() error {
if serveAllowNonLoopback {
fmt.Fprintf(os.Stderr,
"bd serve: WARNING: --allow-non-loopback binds %s beyond loopback. "+
"This API has no authentication and no TLS: any peer that can reach it can read every issue and claim work as any actor.\n",
"This API has no authentication and no TLS: any peer that can reach it can read every issue, claim work as any actor, "+
"and bulk-delete closed beads.\n",
serveAddr)
}

View file

@ -258,7 +258,14 @@ func TestServeBuildsOnlyAProviderBackedServer(t *testing.T) {
continue
}
switch key.Name {
case "Reader", "Claimer", "EdgeReader":
// NOT the whole role set — Settings, Stats, CycleDetector and
// ReadyCounter are absent, which is a gap someone should close
// by inverting this into "any key that is not one of the
// non-role fields". Sweeper is here because it is the one
// whose absence would cost most: a roles-backed server over
// the embedded store answers a BULK DELETE while its
// per-request atomicity claim is false.
case "Reader", "Claimer", "EdgeReader", "Sweeper":
t.Errorf("%s: bd serve sets httpapi.Config.%s. The roles source bypasses the unit-of-work "+
"provider serveModeGate vouched for, and internal/httpapi cannot tell an embedded-backed "+
"role from any other — read serveModeGate before changing this",

View file

@ -100,6 +100,16 @@ in; 13 is the HTTP surface, which lands with the command rather than after it.
`hook_counter.go`). Either way the accessor must EXIST on the decorator: it
is declared, never inherited, and there is a reflection test that says so.
**The read/write split is about the HOOK VOCABULARY, not about whether the
role writes.** `internal/hooks` publishes on_create, on_update and on_close
and nothing else, so a write the vocabulary cannot name recurses like a
read: `issueops.Sweeper` deletes rows and `hook_sweeper.go` is three lines,
because there is no on_delete to fire and the rows a hook script would be
handed are gone. Say which it is and why in the file, and assert it in
`role_accessor_decorator_test.go`'s wrapped/unwrapped table — the whole
point of that table is that "recurses" reads identically whether it was a
decision or an omission.
7. **The telemetry wrapper.** `internal/telemetry/<role>.go`. No read/write
distinction here — telemetry spans reads too, so every method gets
`storage.op` / `storage.done`.

View file

@ -25,6 +25,24 @@ func (e HealthStatus) Valid() bool {
}
}
// Defines values for SweepRequestTier.
const (
Durable SweepRequestTier = "durable"
Ephemeral SweepRequestTier = "ephemeral"
)
// Valid indicates whether the value is a known member of the SweepRequestTier enum.
func (e SweepRequestTier) Valid() bool {
switch e {
case Durable:
return true
case Ephemeral:
return true
default:
return false
}
}
// Defines values for QueryIssuesParamsSort.
const (
QueryIssuesParamsSortAssignee QueryIssuesParamsSort = "assignee"
@ -120,7 +138,7 @@ type ContextResponse struct {
// BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback.
BeadsDir string `json:"beads_dir"`
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.claim`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.claim`, `issues.sweep`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
Capabilities []string `json:"capabilities"`
// Database Logical database name (not a host or a DSN).
@ -316,6 +334,79 @@ type StatsResponse struct {
Summary Statistics `json:"summary"`
}
// SweepRequest Which closed beads to clear. The predicate is FIXED at "closed beads of one tier" and the two narrowing members only narrow it: there is no status, no assignee, no label and no free-text query here, because every one of those would be another way to spell a destructive selection that a caller could get subtly wrong.
//
// `additionalProperties: false`, so an unknown member is a `400` naming the member — the same posture the query-parameter rule takes, and for the same reason: on this operation a silently ignored narrowing term widens what is erased.
type SweepRequest struct {
// Actor Caller-asserted attribution for wherever the backend records it, under the same rules and for the same reasons as `ClaimRequest`'s `actor`: trimmed, refused when empty after trimming, over 256 BYTES, or carrying any control character. Optional — a deleted bead leaves no row to attribute the deletion on.
Actor *string `json:"actor,omitempty"`
// ClosedBefore Keep only beads closed STRICTLY BEFORE this instant (RFC 3339). A bead closed exactly at it is kept, which is the half-open interval every other time bound on this surface uses. `bd prune --older-than 30d` resolves the duration itself and sends the resulting instant.
ClosedBefore *time.Time `json:"closed_before,omitempty"`
// DryRun Report what the sweep WOULD do and delete nothing. The counts, the skips and the refusals are the same ones the real sweep would produce, computed against the same snapshot — and nothing is recorded in history either.
DryRun *bool `json:"dry_run,omitempty"`
// Pattern Keep only beads whose id matches this shell glob (`*`, `?`, `[...]`, `\` escapes; `*` also crosses `-` and `.`, since an id is not a path). Absent matches every bead in the tier. A MALFORMED glob is a `400`, never a pattern that matches nothing.
Pattern *string `json:"pattern,omitempty"`
// ProtectReferenced Skip candidates whose id is CITED — as a literal, at word boundaries — in the description, notes or comments of any bead that is not done, so a decision trail a live bead still points at is not deleted out from under it. It costs a full scan of the not-done set and its comments, which is why it is asked for rather than always on. `bd prune` asks unless `--ignore-references`; `bd purge` never does.
ProtectReferenced *bool `json:"protect_referenced,omitempty"`
// Tier Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and `durable` is the issue tier (`bd prune`). The two are DISJOINT: a sweep of one can never touch a bead of the other. Required, with no default — a caller handed the wrong tier has nothing to notice until the beads are gone.
Tier SweepRequestTier `json:"tier"`
}
// SweepRequestTier Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and `durable` is the issue tier (`bd prune`). The two are DISJOINT: a sweep of one can never touch a bead of the other. Required, with no default — a caller handed the wrong tier has nothing to notice until the beads are gone.
type SweepRequestTier string
// SweepResult What one sweep did. Every number describes the SAME snapshot, because the selection and the deletion ran in one transaction.
//
// It is NOT `x-go-type`-pinned, for the reason `ReadyCount` is not: there is no canonical Go struct whose JSON encoding is this contract. The CLI publishes these numbers under its own per-command keys (`purged_count`, `pruned_count`), which are a stdout presentation rather than a wire type, so pinning would weld this body to one of them.
type SweepResult struct {
// Dependencies Dependency edge rows removed with them. Reported because a sweep's visible effect is much larger than its bead count.
Dependencies int `json:"dependencies"`
// DryRun Echoes the request, so a result carries whether its numbers describe beads that are gone or beads that would go.
DryRun bool `json:"dry_run"`
// Events Event rows removed with the swept beads.
Events int `json:"events"`
// Labels Label rows removed with the swept beads.
Labels int `json:"labels"`
// ReferencedIds A BOUNDED SAMPLE of the ids `skipped.referenced` counts — at most 100, in the order the candidate query returned them. It is a sample, not the set: compare its length against 100 to tell a truncated one from a complete one. Absent when nothing was protected.
ReferencedIds *[]string `json:"referenced_ids,omitempty"`
// Skipped The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: the first two are PROTECTIONS, and the last four are the sweep declining to trust its own input.
Skipped SweepSkips `json:"skipped"`
// Swept How many beads were deleted, or under `dry_run` would be.
Swept int `json:"swept"`
}
// SweepSkips The candidates a sweep declined to delete, bucketed by WHY. They are separate counters rather than one number because they mean different things: the first two are PROTECTIONS, and the last four are the sweep declining to trust its own input.
type SweepSkips struct {
// ClosedAtOrAfterCutoff Candidates whose close timestamp did not satisfy `closed_before`. See `not_closed`.
ClosedAtOrAfterCutoff int `json:"closed_at_or_after_cutoff"`
// NotClosed Candidates the tier query returned that the recheck found were not closed. A NON-ZERO VALUE HERE IS A DEFENSE FIRING, not a normal outcome: the query asked for exactly the beads this excludes.
NotClosed int `json:"not_closed"`
// Pinned Candidates protected by the pinned flag. No request member overrides it — a caller who wants a pinned bead gone unpins it first.
Pinned int `json:"pinned"`
// Referenced Candidates protected by `protect_referenced`. Always 0 when that member is false or absent, so a 0 read without having asked says nothing about whether beads are cited.
Referenced int `json:"referenced"`
// UnknownClosedAt Closed candidates carrying no close timestamp. See `not_closed`.
UnknownClosedAt int `json:"unknown_closed_at"`
// Unreadable Rows the tier query returned as nothing at all. A defense of the same kind, on a shape rather than a value.
Unreadable int `json:"unreadable"`
}
// IssueID defines model for IssueID.
type IssueID = string
@ -574,3 +665,6 @@ type GetStatsParams struct {
// ClaimIssueJSONRequestBody defines body for ClaimIssue for application/json ContentType.
type ClaimIssueJSONRequestBody = ClaimRequest
// SweepIssuesJSONRequestBody defines body for SweepIssues for application/json ContentType.
type SweepIssuesJSONRequestBody = SweepRequest

View file

@ -34,9 +34,10 @@ const (
// maxActorBytes is the document's cap on `actor`. The schema's maxLength
// counts characters; this byte limit is the binding one.
maxActorBytes = 256
// maxClaimBodyBytes bounds the request body. The only member is an actor of
// at most a few hundred bytes, so this is pure refusal of the absurd.
maxClaimBodyBytes = 1 << 20
// maxJSONBodyBytes bounds every request body on this surface. The largest
// documented one is a handful of short members, so this is pure refusal of
// the absurd.
maxJSONBodyBytes = 1 << 20
// claimContentType is the one media type this operation accepts, and
// refusing anything else is a CSRF control, not pedantry: a JSON content
// type is not CORS-"simple", so a cross-origin claim always triggers a
@ -175,7 +176,7 @@ func (s *Server) requireJSONContent(w http.ResponseWriter, r *http.Request) bool
// assignee column AND interpolated into the storage commit message — where an
// unvalidated newline forges audit-trail lines that look like separate commits.
func (s *Server) claimActor(w http.ResponseWriter, r *http.Request) (string, bool) {
members, res := decodeClaimBody(w, r)
members, res := decodeJSONObjectBody(w, r)
if res != nil {
s.fail(w, r, *res)
return "", false
@ -223,12 +224,15 @@ func (s *Server) claimActor(w http.ResponseWriter, r *http.Request) (string, boo
return trimmed, true
}
// decodeClaimBody reads the body as a JSON object of raw members. Decoding the
// members rather than the generated struct is what makes the schema's
// decodeJSONObjectBody reads the body as a JSON object of raw members. Decoding
// the members rather than the generated struct is what makes the schema's
// additionalProperties: false enforceable by NAME: encoding/json's
// DisallowUnknownFields reports the offender only inside an error string, and
// this endpoint exists to let clients stop parsing prose.
func decodeClaimBody(w http.ResponseWriter, r *http.Request) (map[string]json.RawMessage, *Result) {
// these endpoints exist to let clients stop parsing prose.
//
// Shared with the sweep, which has the same posture and the same reason for
// it; the member vocabulary each operation accepts is its own.
func decodeJSONObjectBody(w http.ResponseWriter, r *http.Request) (map[string]json.RawMessage, *Result) {
// A body with no nameable part: `param` is documented absent on exactly
// this case and present on every other 400.
unparseable := func(detail string) *Result {
@ -237,11 +241,11 @@ func decodeClaimBody(w http.ResponseWriter, r *http.Request) (map[string]json.Ra
}
var members map[string]json.RawMessage
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxClaimBodyBytes))
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxJSONBodyBytes))
if err := dec.Decode(&members); err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return nil, unparseable(fmt.Sprintf("request body is larger than %d bytes", maxClaimBodyBytes))
return nil, unparseable(fmt.Sprintf("request body is larger than %d bytes", maxJSONBodyBytes))
}
return nil, unparseable("request body must be a JSON object")
}
@ -364,6 +368,7 @@ var (
_ uow.IssueClaimerSource = timedProvider{}
_ uow.ReadyCounterSource = timedProvider{}
_ uow.QuerierSource = timedProvider{}
_ uow.SweeperSource = timedProvider{}
)
// IssueReader builds the reader OVER THIS WRAPPER rather than delegating to the
@ -443,6 +448,15 @@ func (p timedProvider) Querier() (issueops.Querier, error) {
return uow.NewQuerier(p)
}
// Sweeper builds the sweeper OVER THIS WRAPPER, for the same reason as the two
// above and with the sharpest version of the hazard: the sweep is the longest
// unit of work on this surface, so a sweeper bound to the untimed provider
// would report uow_ms=0.000 for exactly the request whose duration an operator
// most wants in the log.
func (p timedProvider) Sweeper() (issueops.Sweeper, error) {
return uow.NewSweeper(p)
}
func (p timedProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) {
start := time.Now()
uw, err := p.inner.NewUOW(ctx)

View file

@ -611,10 +611,10 @@ func TestClaimRejectsMalformedRequests(t *testing.T) {
// rather than over a socket: a megabyte in flight makes the assertion about
// timing instead of about the rule.
func TestClaimBodyCapIsEnforcedWhileReading(t *testing.T) {
oversized := `{"actor":"` + strings.Repeat("x", maxClaimBodyBytes) + `"}`
oversized := `{"actor":"` + strings.Repeat("x", maxJSONBodyBytes) + `"}`
r := httptest.NewRequest(http.MethodPost, claimPath, strings.NewReader(oversized))
members, res := decodeClaimBody(httptest.NewRecorder(), r)
members, res := decodeJSONObjectBody(httptest.NewRecorder(), r)
if res == nil {
t.Fatalf("a %d-byte body was accepted (%d members)", len(oversized), len(members))
}

View file

@ -161,6 +161,9 @@ const (
OpListDependencies = "listDependencies"
OpCountReadyWork = "countReadyWork"
OpQueryIssues = "queryIssues"
// OpSweepIssues is the one DESTRUCTIVE operation on this surface: bulk
// clearance of closed beads from one tier, behind issueops.Sweeper.
OpSweepIssues = "sweepIssues"
)
// operationCodes is the per-operation problem vocabulary: exactly the codes
@ -220,6 +223,13 @@ var operationCodes = map[string][]Code{
// recovery is the same as for any other malformed parameter value, and a
// code it cannot act on differently is a code it should not have to know.
OpQueryIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
// The 400 here is the widest on this surface, and most of it is not this
// handler's: an unknown or malformed body member is, but the unfiltered
// durable sweep, the unrecognized tier and the malformed glob are all the
// ROLE's ErrValidation reaching the wire through failSweepErr. No 404 —
// this operation names no id — and no 409: a sweep has nothing to conflict
// with, since a bead another sweep already took is simply not in the set.
OpSweepIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
OpClaimIssue: {
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
CodeBusy, CodeDBUnavailable, CodeInternal,

View file

@ -313,6 +313,9 @@ func rolesConfig(cfg Config) Config {
if cfg.Querier == nil {
cfg.Querier = &roleQuerier{}
}
if cfg.Sweeper == nil {
cfg.Sweeper = &roleSweeper{}
}
return cfg
}
@ -347,6 +350,36 @@ func (d *roleCycleDetector) DetectCycles(_ context.Context, req issueops.DetectC
return d.report, nil
}
// roleSweeper is the store-shaped source's bulk-clearance role. Like the
// others it answers with whatever a case configured, so every configured-roles
// case can hand Listen a COMPLETE source without deciding what a sweep of its
// fixture should do — which matters more here than for the reads, because the
// alternative to a complete source is a server that binds and then
// nil-dereferences on the one request that deletes beads.
type roleSweeper struct {
result issueops.SweepResult
err error
mu sync.Mutex
calls []issueops.SweepRequest
}
func (s *roleSweeper) Sweep(_ context.Context, req issueops.SweepRequest) (issueops.SweepResult, error) {
s.mu.Lock()
s.calls = append(s.calls, req)
s.mu.Unlock()
if s.err != nil {
return issueops.SweepResult{}, s.err
}
return s.result, nil
}
func (s *roleSweeper) requests() []issueops.SweepRequest {
s.mu.Lock()
defer s.mu.Unlock()
return append([]issueops.SweepRequest(nil), s.calls...)
}
// countedPage is the fixture both database sources answer with, so a body
// difference between them can only come from the construction.
func countedPage() []*types.IssueWithCounts {
@ -441,6 +474,25 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
cfg: rolesConfigWithout(func(c *Config) { c.Querier = nil }),
wantErr: "no database source",
},
{
// The newest role, and the one whose absence would be worst: a
// Config written against the previous release binds, advertises
// issues.sweep in its own capability list, and nil-dereferences on
// the first request that deletes beads.
name: "no sweeper",
cfg: rolesConfigWithout(func(c *Config) { c.Sweeper = nil }),
wantErr: "no database source",
},
{
name: "a sweeper alone",
cfg: Config{Sweeper: &roleSweeper{}},
wantErr: "no database source",
},
{
name: "a provider and a sweeper",
cfg: Config{Provider: &fakeProvider{}, Sweeper: &roleSweeper{}},
wantErr: "exactly one database source",
},
{
name: "a cycle detector alone",
cfg: Config{CycleDetector: &roleCycleDetector{}},
@ -822,16 +874,7 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
// package.
func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
t.Run("a missing issue is 404", func(t *testing.T) {
ts := newTestServer(t, Config{
Reader: &roleReader{err: fmt.Errorf("get bd-404: %w", storage.ErrNotFound)},
Claimer: &roleClaimer{},
Settings: &roleSettings{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
ts := newTestServer(t, rolesConfig(Config{Reader: &roleReader{err: fmt.Errorf("get bd-404: %w", storage.ErrNotFound)}}))
resp := ts.get(t, "/v0/beads/issues/bd-404")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
@ -845,16 +888,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
// The builders run INSIDE the role on this path, so their refusal
// arrives at the handler exactly as it does from a unit-of-work reader —
// and must still be mapped to its parameter rather than to a 500.
ts := newTestServer(t, Config{
Reader: &roleReader{err: errors.New("invalid status bogus")},
Claimer: &roleClaimer{},
Settings: &roleSettings{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
ts := newTestServer(t, rolesConfig(Config{Reader: &roleReader{err: errors.New("invalid status bogus")}}))
resp := ts.get(t, "/v0/beads/issues?status=bogus")
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
@ -866,21 +900,14 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
})
t.Run("a foreign holder is 409 with its state", func(t *testing.T) {
ts := newTestServer(t, Config{
Reader: &roleReader{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ts := newTestServer(t, rolesConfig(Config{
Claimer: &roleClaimer{err: &issueops.ClaimConflictError{
IssueID: "bd-1",
Assignee: "bob",
Status: types.StatusInProgress,
Err: fmt.Errorf("claim bd-1: %w", storage.ErrAlreadyClaimed),
}},
Settings: &roleSettings{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
}))
resp := ts.claim(t, claimPath, `{"actor":"alice"}`)
if resp.StatusCode != http.StatusConflict {
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
@ -895,16 +922,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
})
t.Run("a role failure is the generic 500", func(t *testing.T) {
ts := newTestServer(t, Config{
Reader: &roleReader{err: errors.New("backend is unreachable")},
Claimer: &roleClaimer{},
Settings: &roleSettings{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
ts := newTestServer(t, rolesConfig(Config{Reader: &roleReader{err: errors.New("backend is unreachable")}}))
resp := ts.get(t, "/v0/beads/ready")
if resp.StatusCode != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500: %s", resp.StatusCode, readAll(t, resp))
@ -1001,16 +1019,7 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
// tell a broken role from an absent issue.
t.Run("a reader with no detail view is the documented miss", func(t *testing.T) {
silent := newTestServer(t, rolesConfig(Config{}))
missed := newTestServer(t, Config{
Reader: &roleReader{err: fmt.Errorf("get bd-1: %w", storage.ErrNotFound)},
Claimer: &roleClaimer{},
Settings: &roleSettings{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
missed := newTestServer(t, rolesConfig(Config{Reader: &roleReader{err: fmt.Errorf("get bd-1: %w", storage.ErrNotFound)}}))
got := silent.get(t, "/v0/beads/issues/bd-1")
want := missed.get(t, "/v0/beads/issues/bd-1")
@ -1033,16 +1042,9 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
// fault reaches the log as a stack trace instead of as an error, and the
// panic path writes no request_error line for an operator to alert on.
t.Run("a claimer with no issue is the generic failure", func(t *testing.T) {
ts := newTestServer(t, Config{
Reader: &roleReader{},
Claimer: &roleClaimer{result: issueops.ClaimResult{Changed: true}},
Settings: &roleSettings{},
Stats: &roleStats{},
CycleDetector: &roleCycleDetector{},
EdgeReader: &roleEdgeReader{},
ReadyCounter: &roleReadyCounter{},
Querier: &roleQuerier{},
})
ts := newTestServer(t, rolesConfig(Config{
Claimer: &roleClaimer{result: issueops.ClaimResult{Changed: true}},
}))
resp := ts.claim(t, claimPath, `{"actor":"alice"}`)
if resp.StatusCode != http.StatusInternalServerError {

View file

@ -181,6 +181,25 @@ var routeTable = []route{
implemented: true,
handler: (*Server).handleClaim,
},
{
op: OpSweepIssues,
method: http.MethodPost,
// A collection-level custom method, spelled the way countReadyWork's
// is and needing no specPath declaration for the same reason: the
// segment is a LITERAL. Only a WILDCARD segment is inexpressible as a
// ServeMux pattern, which is what makes the claim route the one
// exception.
//
// It is registered AFTER the claim's `/v0/beads/issues/{idop}`, and
// ServeMux precedence is by specificity rather than by order, so the
// literal wins over the wildcard for this exact path. That is what
// keeps a sweep from being parsed as a claim of an issue called
// ":sweep"; TestSweepPathReachesItsHandler drives the documented path.
pattern: "/v0/beads/issues:sweep",
capability: "issues.sweep",
implemented: true,
handler: (*Server).handleSweep,
},
}
// specPathOf is the document path for a route, defaulting to the router

View file

@ -207,6 +207,12 @@ type Config struct {
EdgeReader issueops.EdgeReader
ReadyCounter issueops.ReadyCounter
Querier issueops.Querier
// Sweeper is the DESTRUCTIVE one, and it is required on the same terms as
// every other role rather than opt-in. A Config that could omit it would
// be a Config that quietly decides whether this build erases beads, which
// is a decision that belongs to the operator who chose to run bd serve at
// all — not to whether a caller remembered a field.
Sweeper issueops.Sweeper
// Workspace is the startup snapshot GET /v0/beads/context answers from.
// Only the allowlisted fields are ever serialized — see contextResponse,
// which names the whole set and the reasons for the exclusions.
@ -250,6 +256,7 @@ type Server struct {
issueEdges issueops.EdgeReader
issueReadyCounter issueops.ReadyCounter
issueQuerier issueops.Querier
issueSweeper issueops.Sweeper
listener net.Listener
http *http.Server
@ -354,6 +361,7 @@ func Listen(cfg Config) (*Server, error) {
issueEdges: cfg.EdgeReader,
issueReadyCounter: cfg.ReadyCounter,
issueQuerier: cfg.Querier,
issueSweeper: cfg.Sweeper,
sem: make(chan struct{}, maxInflight),
semTimeout: semAcquireTimeout,
@ -457,12 +465,12 @@ func Listen(cfg Config) (*Server, error) {
// as this check is concerned, exactly as it was when the check was a hand-
// written boolean per role.
func sourceRoles(cfg Config) []any {
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.ReadyCounter, cfg.Querier}
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper}
}
// roleSourceNames spells sourceRoles for the refusal message, in the same
// order, so a caller reading the error learns the whole set it must pass.
const roleSourceNames = "Reader, Claimer, Settings, Stats, CycleDetector, EdgeReader, ReadyCounter and Querier"
const roleSourceNames = "Reader, Claimer, Settings, Stats, CycleDetector, EdgeReader, ReadyCounter, Querier and Sweeper"
func anyRoleSet(cfg Config) bool {
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
@ -720,6 +728,25 @@ func (s *Server) querier(r *http.Request) (issueops.Querier, error) {
return src.Querier()
}
// sweeper returns the guarded bulk-clearance surface for one request.
//
// The same two sources as every role above, for the same reasons, and held by
// INTERFACE so uow.SweeperSource is load-bearing rather than decorative. It
// goes out unwrapped for the reason readyCounter does: SweepResult is a VALUE,
// so there is no pointer for a caller-supplied role to hand back nil in.
//
// The role this returns is the ONLY thing standing between a POST body and a
// mass delete — the require-a-filter gate, the pinned protection and the
// closed_at recheck are all inside it — which is why the Config field it comes
// from is required rather than optional.
func (s *Server) sweeper(r *http.Request) (issueops.Sweeper, error) {
if s.provider == nil {
return s.issueSweeper, nil
}
var src uow.SweeperSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
return src.Sweeper()
}
// WithUOW runs fn inside one unit of work and guarantees the rollback.
//
// The close context is DETACHED on purpose. Close sends ROLLBACK on the pinned

View file

@ -578,8 +578,8 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
}
want := []string{
"config.get", "config.list", "dependencies.cycles", "dependencies.list",
"issues.claim", "issues.get", "issues.list", "issues.query", "ready.count",
"ready.list", "stats.get",
"issues.claim", "issues.get", "issues.list", "issues.query",
"issues.sweep", "ready.count", "ready.list", "stats.get",
}
if !slices.Equal(got, want) {
t.Errorf("capabilities = %v, want %v", got, want)

View file

@ -57,12 +57,12 @@ info:
Operations with no parameters at all (`GET /healthz`,
`GET /v0/beads/context`, `GET /v0/beads/dependencies/cycles`,
`GET /v0/beads/issues/{id}`, `POST /v0/beads/issues/{id}:claim`,
`GET /v0/beads/config`, `GET /v0/beads/config/{key}`) reject every query
key the same way.
`POST /v0/beads/issues:sweep`, `GET /v0/beads/config`,
`GET /v0/beads/config/{key}`) reject every query key the same way.
Both are uniform rules, reachable on EVERY route including `GET /healthz`,
and are stated here instead of being repeated on all twelve operations. The
and are stated here instead of being repeated on every operation. The
per-operation `responses` below therefore list what an operation produces
BEYOND these two: a generated client must treat `400 invalid_argument` as
possible everywhere, including on the operations whose documented statuses
@ -1145,6 +1145,91 @@ paths:
'503':
$ref: '#/components/responses/Unavailable'
/v0/beads/issues:sweep:
post:
operationId: sweepIssues
summary: Delete closed beads in bulk
description: >-
Bulk clearance of CLOSED beads from ONE tier: the operation behind
`bd purge` (`tier: ephemeral`) and `bd prune` (`tier: durable`). It is
the only DESTRUCTIVE operation on this surface, and nothing it deletes
comes back.
A collection-level custom method rather than `DELETE
/v0/beads/issues?...`: this describes a SET and acts on it, and a
`DELETE` with a filtering query string is the shape where a dropped
parameter widens what is erased. Sending a body makes every narrowing
term a member the server refuses by name if it does not know it.
## What it selects, in order
The closed rows of `tier`, then `pattern`, then the two protections —
pinned beads are never swept and `protect_referenced` holds back beads
another live bead cites. The ORDER is part of the answer: `skipped`
counts what the request actually reached, so a pinned bead the pattern
excluded is not counted as protected.
## The safety gate is the ROLE'S, not this handler's
A `durable` sweep with neither `closed_before` nor `pattern` is
refused with `400` / `invalid_argument`. That refusal comes from the
same library surface `bd prune` calls, not from a check written here,
which is what makes this endpoint incapable of erasing every closed
bead in a workspace by omission. A caller that really means everything
closed sends `pattern: "*"`.
## One transaction
The selection and the deletion share one transaction, so the set the
response describes IS the set that was deleted. The cost is that a
sweep is all-or-nothing: one large enough to exceed the backend's write
timeout fails whole and deletes nothing. Narrow the request rather than
expecting progress.
`dry_run: true` answers the same question and changes nothing —
including history. Ask it first.
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/SweepRequest'
responses:
'200':
description: >-
The sweep ran (or, under `dry_run`, was costed). A request that
matched nothing is a 200 with `swept: 0`, not a 404 — an empty set
of closed beads is the steady state of a swept workspace.
content:
application/json:
schema:
$ref: '#/components/schemas/SweepResult'
'400':
description: >-
Invalid request: an unparseable or oversized body, an unknown body
member, a `tier` outside the enum, a malformed `pattern`, an
unparseable `closed_before`, an `actor` that is empty after
trimming or carries control characters — or an unfiltered
`durable` sweep, which the library surface refuses as a safety
invariant.
x-bd-codes: [invalid_argument]
content:
application/problem+json:
schema:
$ref: '#/components/schemas/Problem'
'500':
$ref: '#/components/responses/InternalError'
'503':
$ref: '#/components/responses/Unavailable'
/v0/beads/config:
get:
operationId: listSettings
@ -2175,6 +2260,7 @@ components:
The operations this server actually implements, derived from its
route table. v0's vocabulary is `ready.list`, `ready.count`,
`issues.list`, `issues.query`, `issues.get`, `issues.claim`,
`issues.sweep`,
`stats.get`, `config.list`, `config.get`, `dependencies.cycles`,
`dependencies.list`; it grows additively, and an operation never
appears here unless it is fully implemented. This is how a client
@ -2209,6 +2295,172 @@ components:
pinning would weld this body to a CLI presentation type instead of
preventing a drift.
SweepRequest:
type: object
additionalProperties: false
required: [tier]
description: >-
Which closed beads to clear. The predicate is FIXED at "closed beads of
one tier" and the two narrowing members only narrow it: there is no
status, no assignee, no label and no free-text query here, because
every one of those would be another way to spell a destructive
selection that a caller could get subtly wrong.
`additionalProperties: false`, so an unknown member is a `400` naming
the member — the same posture the query-parameter rule takes, and for
the same reason: on this operation a silently ignored narrowing term
widens what is erased.
properties:
tier:
type: string
enum: [ephemeral, durable]
description: >-
Which plane to clear. `ephemeral` is the wisp tier (`bd purge`) and
`durable` is the issue tier (`bd prune`). The two are DISJOINT: a
sweep of one can never touch a bead of the other. Required, with no
default — a caller handed the wrong tier has nothing to notice
until the beads are gone.
actor:
type: string
minLength: 1
maxLength: 256
pattern: '^[^\u0000-\u001F\u007F]+$'
description: >-
Caller-asserted attribution for wherever the backend records it,
under the same rules and for the same reasons as `ClaimRequest`'s
`actor`: trimmed, refused when empty after trimming, over 256
BYTES, or carrying any control character. Optional — a deleted bead
leaves no row to attribute the deletion on.
closed_before:
type: string
format: date-time
description: >-
Keep only beads closed STRICTLY BEFORE this instant (RFC 3339). A
bead closed exactly at it is kept, which is the half-open interval
every other time bound on this surface uses. `bd prune
--older-than 30d` resolves the duration itself and sends the
resulting instant.
pattern:
type: string
description: >-
Keep only beads whose id matches this shell glob (`*`, `?`,
`[...]`, `\` escapes; `*` also crosses `-` and `.`, since an id is
not a path). Absent matches every bead in the tier. A MALFORMED
glob is a `400`, never a pattern that matches nothing.
protect_referenced:
type: boolean
default: false
description: >-
Skip candidates whose id is CITED — as a literal, at word
boundaries — in the description, notes or comments of any bead that
is not done, so a decision trail a live bead still points at is not
deleted out from under it. It costs a full scan of the not-done set
and its comments, which is why it is asked for rather than always
on. `bd prune` asks unless `--ignore-references`; `bd purge` never
does.
dry_run:
type: boolean
default: false
description: >-
Report what the sweep WOULD do and delete nothing. The counts, the
skips and the refusals are the same ones the real sweep would
produce, computed against the same snapshot — and nothing is
recorded in history either.
SweepResult:
type: object
required: [dry_run, swept, dependencies, labels, events, skipped]
description: >-
What one sweep did. Every number describes the SAME snapshot, because
the selection and the deletion ran in one transaction.
It is NOT `x-go-type`-pinned, for the reason `ReadyCount` is not: there
is no canonical Go struct whose JSON encoding is this contract. The CLI
publishes these numbers under its own per-command keys (`purged_count`,
`pruned_count`), which are a stdout presentation rather than a wire
type, so pinning would weld this body to one of them.
properties:
dry_run:
type: boolean
description: >-
Echoes the request, so a result carries whether its numbers
describe beads that are gone or beads that would go.
swept:
type: integer
description: How many beads were deleted, or under `dry_run` would be.
dependencies:
type: integer
description: >-
Dependency edge rows removed with them. Reported because a sweep's
visible effect is much larger than its bead count.
labels:
type: integer
description: Label rows removed with the swept beads.
events:
type: integer
description: Event rows removed with the swept beads.
skipped:
$ref: '#/components/schemas/SweepSkips'
referenced_ids:
type: array
description: >-
A BOUNDED SAMPLE of the ids `skipped.referenced` counts — at most
100, in the order the candidate query returned them. It is a
sample, not the set: compare its length against 100 to tell a
truncated one from a complete one. Absent when nothing was
protected.
items:
type: string
SweepSkips:
type: object
required:
- pinned
- referenced
- not_closed
- unknown_closed_at
- closed_at_or_after_cutoff
- unreadable
description: >-
The candidates a sweep declined to delete, bucketed by WHY. They are
separate counters rather than one number because they mean different
things: the first two are PROTECTIONS, and the last four are the sweep
declining to trust its own input.
properties:
pinned:
type: integer
description: >-
Candidates protected by the pinned flag. No request member
overrides it — a caller who wants a pinned bead gone unpins it
first.
referenced:
type: integer
description: >-
Candidates protected by `protect_referenced`. Always 0 when that
member is false or absent, so a 0 read without having asked says
nothing about whether beads are cited.
not_closed:
type: integer
description: >-
Candidates the tier query returned that the recheck found were not
closed. A NON-ZERO VALUE HERE IS A DEFENSE FIRING, not a normal
outcome: the query asked for exactly the beads this excludes.
unknown_closed_at:
type: integer
description: Closed candidates carrying no close timestamp. See `not_closed`.
closed_at_or_after_cutoff:
type: integer
description: >-
Candidates whose close timestamp did not satisfy `closed_before`.
See `not_closed`.
unreadable:
type: integer
description: >-
Rows the tier query returned as nothing at all. A defense of the
same kind, on a shape rather than a value.
ReadyPage:
type: object
required: [items, has_more]

264
internal/httpapi/sweep.go Normal file
View file

@ -0,0 +1,264 @@
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/steveyegge/beads/internal/httpapi/apigen"
"github.com/steveyegge/beads/issueops"
)
// The request body's member vocabulary. The schema is
// additionalProperties: false, so anything else is refused BY NAME — the same
// posture the unknown-query-parameter rule takes, and on this operation for a
// sharper reason: a narrowing term the server silently ignored would widen
// what is erased.
const (
sweepTierMember = "tier"
sweepActorMember = "actor"
sweepClosedBeforeMember = "closed_before"
sweepPatternMember = "pattern"
sweepProtectReferencedMember = "protect_referenced"
sweepDryRunMember = "dry_run"
)
// sweepMembers is the whole vocabulary, in one place, so the unknown-member
// refusal and the decoding below cannot come to disagree about what this
// operation accepts.
var sweepMembers = []string{
sweepTierMember,
sweepActorMember,
sweepClosedBeforeMember,
sweepPatternMember,
sweepProtectReferencedMember,
sweepDryRunMember,
}
// handleSweep answers POST /v0/beads/issues:sweep — the one DESTRUCTIVE
// operation on this surface.
//
// WHAT THIS HANDLER DOES NOT DO is the whole point of it. It does not decide
// which beads are closed, does not match the glob, does not recheck closed_at,
// does not protect pinned beads, and — the one that matters most — does not
// implement the require-a-filter safety gate. All of that is
// issueops.Sweeper, the same library surface `bd prune` calls, so this
// endpoint could not erase every closed bead in a workspace by omission even
// if a future edit here forgot the rule existed. That is the reason the gate
// was moved INTO the role rather than left in the CLI handler that historically
// owned it: without it, a second front door is one handler away from an
// unguarded mass delete.
//
// Everything above the role here is argument validation: the media type, the
// body shape, and the six members the document publishes.
//
// NO ACTOR IS INFERRED, for the reason the claim gives: the server's own
// identity is meaningless to a remote caller. Unlike the claim, the actor is
// OPTIONAL here — a deleted bead leaves no row to attribute the deletion on —
// and it is validated by the same rules when present, because it reaches the
// same commit-message interpolation.
func (s *Server) handleSweep(w http.ResponseWriter, r *http.Request) {
if !s.requireNoQuery(w, r) {
return
}
if !s.requireJSONContent(w, r) {
return
}
request, ok := s.sweepRequest(w, r)
if !ok {
return
}
sweeper, err := s.sweeper(r)
if err != nil {
s.failErr(w, r, err)
return
}
result, err := sweeper.Sweep(r.Context(), request)
if err != nil {
s.failSweepErr(w, r, err)
return
}
writeJSON(w, sweepResponse(result))
}
// sweepRequest decodes the body into the role's request, member by member.
//
// Member by member rather than straight into apigen.SweepRequest so that every
// refusal can NAME the member it is about: unmarshaling the generated struct
// reports a type mismatch only inside an error string, and this endpoint
// exists so clients can stop parsing prose.
func (s *Server) sweepRequest(w http.ResponseWriter, r *http.Request) (issueops.SweepRequest, bool) {
members, res := decodeJSONObjectBody(w, r)
if res != nil {
s.fail(w, r, *res)
return issueops.SweepRequest{}, false
}
var unknown []string
for name := range members {
if !slices.Contains(sweepMembers, name) {
unknown = append(unknown, name)
}
}
if len(unknown) > 0 {
// One offender, chosen deterministically so a client dispatching on
// `param` never sees it depend on map order.
offender := slices.Min(unknown)
requestInfo(r.Context()).refuse(offender)
s.fail(w, r, InvalidArgument(offender, ReasonUnknownParameter,
"this operation's request body carries "+sweepMemberList()+" and nothing else"))
return issueops.SweepRequest{}, false
}
var request issueops.SweepRequest
raw, ok := members[sweepTierMember]
if !ok {
s.fail(w, r, InvalidArgument(sweepTierMember, ReasonInvalidValue,
"`"+sweepTierMember+"` is required and has no default"))
return issueops.SweepRequest{}, false
}
var tier *string
if err := json.Unmarshal(raw, &tier); err != nil || tier == nil {
s.fail(w, r, InvalidArgument(sweepTierMember, ReasonInvalidValue,
"`"+sweepTierMember+"` must be a string"))
return issueops.SweepRequest{}, false
}
// The enum check uses the GENERATED validator, which is derived from the
// document rather than a second hand-written copy of the vocabulary. The
// role refuses an unrecognized tier too — this is here so the refusal can
// name the member, not because the role's is in doubt.
if !apigen.SweepRequestTier(*tier).Valid() {
s.fail(w, r, InvalidArgument(sweepTierMember, ReasonInvalidValue,
"`"+sweepTierMember+"` must be \"ephemeral\" or \"durable\""))
return issueops.SweepRequest{}, false
}
request.Tier = issueops.SweepTier(*tier)
if raw, ok := members[sweepActorMember]; ok {
var value *string
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
s.fail(w, r, InvalidArgument(sweepActorMember, ReasonInvalidValue,
"`"+sweepActorMember+"` must be a string"))
return issueops.SweepRequest{}, false
}
// The claim's rules, unchanged: trim, then refuse empty, over-long and
// any control character. `param` reads "actor" there too, which is what
// makes the two operations one vocabulary for a client.
trimmed, res := validateActor(*value)
if res != nil {
s.fail(w, r, *res)
return issueops.SweepRequest{}, false
}
request.Actor = trimmed
}
if raw, ok := members[sweepClosedBeforeMember]; ok {
var value *time.Time
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
s.fail(w, r, InvalidArgument(sweepClosedBeforeMember, ReasonInvalidValue,
"`"+sweepClosedBeforeMember+"` must be an RFC 3339 timestamp"))
return issueops.SweepRequest{}, false
}
request.ClosedBefore = value
}
if raw, ok := members[sweepPatternMember]; ok {
var value *string
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
s.fail(w, r, InvalidArgument(sweepPatternMember, ReasonInvalidValue,
"`"+sweepPatternMember+"` must be a string"))
return issueops.SweepRequest{}, false
}
// A malformed glob is NOT refused here. The role refuses it, and
// routing it through the role is what keeps one definition of what a
// pattern is: filepath.Match's, matched in Go on both front doors.
request.IDPattern = *value
}
for _, flag := range []struct {
member string
dest *bool
}{
{sweepProtectReferencedMember, &request.ProtectReferenced},
{sweepDryRunMember, &request.DryRun},
} {
raw, ok := members[flag.member]
if !ok {
continue
}
var value *bool
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
s.fail(w, r, InvalidArgument(flag.member, ReasonInvalidValue,
"`"+flag.member+"` must be a boolean"))
return issueops.SweepRequest{}, false
}
*flag.dest = *value
}
return request, true
}
func sweepMemberList() string {
quoted := make([]string, len(sweepMembers))
for i, name := range sweepMembers {
quoted[i] = "`" + name + "`"
}
return strings.Join(quoted, ", ")
}
// failSweepErr answers a failed sweep.
//
// issueops.ErrValidation is a 400 HERE and nowhere else yet, and that is
// deliberate rather than an oversight in ClassifyError: this is the first
// operation whose ROLE performs request validation the handler does not
// duplicate — the require-a-filter gate, the tier vocabulary and the glob are
// all refused below the wire — so it is the first place a role's refusal must
// reach the client as its own fault instead of as a 500. Widening
// ClassifyError would change what every other operation returns for an error
// it has never produced, which is a bigger claim than this commit is making.
func (s *Server) failSweepErr(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, issueops.ErrValidation) {
// No `param`: the refusal is about the REQUEST rather than one member
// of it — an unfiltered durable sweep is two absent members at once —
// and the document's `param` is documented absent on exactly that
// case. The detail carries the role's own sentence, which names what
// to send instead.
s.fail(w, r, InvalidArgument("", ReasonInvalidValue, err.Error()))
return
}
s.failErr(w, r, err)
}
// sweepResponse projects the role's result onto the wire type. It is a field
// list rather than an alias because SweepResult is deliberately not
// x-go-type-pinned: there is no canonical Go struct whose JSON encoding is
// this body (see the schema's own description), so the projection is where the
// two shapes are held together and TestSweepResponseCarriesEveryRoleField is
// what keeps a new result field from being dropped here in silence.
func sweepResponse(result issueops.SweepResult) apigen.SweepResult {
body := apigen.SweepResult{
DryRun: result.DryRun,
Swept: result.Swept,
Dependencies: result.Dependencies,
Labels: result.Labels,
Events: result.Events,
Skipped: apigen.SweepSkips{
Pinned: result.Skipped.Pinned,
Referenced: result.Skipped.Referenced,
NotClosed: result.Skipped.NotClosed,
UnknownClosedAt: result.Skipped.UnknownClosedAt,
ClosedAtOrAfterCutoff: result.Skipped.ClosedAtOrAfterCutoff,
Unreadable: result.Skipped.Unreadable,
},
}
if len(result.ReferencedIDs) > 0 {
ids := append([]string(nil), result.ReferencedIDs...)
body.ReferencedIds = &ids
}
return body
}

View file

@ -0,0 +1,313 @@
package httpapi
import (
"net/http"
"reflect"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/issueops"
)
// The pins for POST /v0/beads/issues:sweep. The role is the surface under
// scrutiny everywhere else in this package's storage tests; what is asserted
// here is the WIRE EDGE — that the handler decodes the document's six members
// into the role's request faithfully, refuses what the document refuses, and
// does not re-implement anything the role owns.
const sweepPath = "/v0/beads/issues:sweep"
func (ts *testServer) sweep(t *testing.T, body string) *http.Response {
t.Helper()
return ts.claimRequest(t, sweepPath, "application/json", body)
}
// TestSweepPathReachesItsHandler is the routing assertion the claim row's twin
// makes: the sweep path is a LITERAL segment registered beside the claim's
// wildcard `/v0/beads/issues/{idop}`, and ServeMux precedence is by specificity
// rather than by registration order. A 404 or a claim-shaped refusal here would
// mean the sweep is being parsed as a claim of an issue named ":sweep".
func TestSweepPathReachesItsHandler(t *testing.T) {
sweeper := &roleSweeper{result: issueops.SweepResult{Swept: 3}}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if len(sweeper.requests()) != 1 {
t.Fatalf("the sweep role was called %d times, want 1 — the path reached another handler",
len(sweeper.requests()))
}
}
// TestSweepForwardsEveryDocumentedMember is the operation's central pin: each
// of the six body members reaches the role's request unchanged.
//
// It is asserted on the REQUEST the role received rather than on the response,
// because a body carrying the right numbers says nothing about which set was
// swept — this is the operation where the handler dropping a narrowing member
// widens what is erased.
func TestSweepForwardsEveryDocumentedMember(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{
"tier": "durable",
"actor": " alice ",
"closed_before": "2026-03-01T12:00:00Z",
"pattern": "bd-old-*",
"protect_referenced": true,
"dry_run": true
}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := sweeper.requests()
if len(reqs) != 1 {
t.Fatalf("%d sweeps, want 1", len(reqs))
}
got := reqs[0]
want := issueops.SweepRequest{
Tier: issueops.SweepDurable,
// TRIMMED, by the same rule and the same function the claim's actor
// goes through: it reaches the same commit-message interpolation.
Actor: "alice",
IDPattern: "bd-old-*",
ProtectReferenced: true,
DryRun: true,
}
cutoff := time.Date(2026, 3, 1, 12, 0, 0, 0, time.UTC)
want.ClosedBefore = &cutoff
if got.ClosedBefore == nil || !got.ClosedBefore.Equal(cutoff) {
t.Errorf("ClosedBefore = %v, want %v", got.ClosedBefore, cutoff)
}
got.ClosedBefore, want.ClosedBefore = nil, nil
if !reflect.DeepEqual(got, want) {
t.Errorf("request = %+v, want %+v", got, want)
}
}
// TestSweepDefaultsTheOptionalMembers: a body carrying only `tier` reaches the
// role as an unfiltered request of that tier, and NOT as a dry run.
//
// The dry-run default is the one worth pinning. `dry_run` absent must mean
// false — that is what the document says — and a handler that defaulted it the
// safe-looking way would make the endpoint silently incapable of deleting
// anything, which is a worse failure than it sounds: a caller would retry.
func TestSweepDefaultsTheOptionalMembers(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
if resp := ts.sweep(t, `{"tier":"ephemeral"}`); resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
reqs := sweeper.requests()
if len(reqs) != 1 {
t.Fatalf("%d sweeps, want 1", len(reqs))
}
if want := (issueops.SweepRequest{Tier: issueops.SweepEphemeral}); reqs[0] != want {
t.Errorf("request = %+v, want %+v", reqs[0], want)
}
}
// TestSweepPublishesTheWholeResult pins the projection, which exists because
// SweepResult is deliberately not x-go-type-pinned: there is no compile-time
// tie between the role's result and this body, so a field added to the role and
// forgotten here would vanish from the wire in silence.
func TestSweepPublishesTheWholeResult(t *testing.T) {
sweeper := &roleSweeper{result: issueops.SweepResult{
DryRun: true,
Swept: 7,
Dependencies: 3,
Labels: 2,
Events: 11,
Skipped: issueops.SweepSkips{
Pinned: 1, Referenced: 2, NotClosed: 3,
UnknownClosedAt: 4, ClosedAtOrAfterCutoff: 5, Unreadable: 6,
},
ReferencedIDs: []string{"bd-1", "bd-2"},
}}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, `{"tier":"durable","pattern":"*","dry_run":true}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
for _, want := range []struct {
key string
val any
}{
{"dry_run", true},
{"swept", float64(7)},
{"dependencies", float64(3)},
{"labels", float64(2)},
{"events", float64(11)},
} {
if body[want.key] != want.val {
t.Errorf("%s = %v, want %v", want.key, body[want.key], want.val)
}
}
skipped, ok := body["skipped"].(map[string]any)
if !ok {
t.Fatalf("skipped = %v, want an object", body["skipped"])
}
for key, want := range map[string]float64{
"pinned": 1, "referenced": 2, "not_closed": 3,
"unknown_closed_at": 4, "closed_at_or_after_cutoff": 5, "unreadable": 6,
} {
if skipped[key] != want {
t.Errorf("skipped.%s = %v, want %v", key, skipped[key], want)
}
}
ids, ok := body["referenced_ids"].([]any)
if !ok || len(ids) != 2 || ids[0] != "bd-1" {
t.Errorf("referenced_ids = %v, want the role's sample", body["referenced_ids"])
}
}
// TestSweepOmitsAnEmptyReferencedSample: the member is documented ABSENT when
// nothing was protected, so a client can tell "nothing cited" from "the
// protection was not asked for" without a second field.
func TestSweepOmitsAnEmptyReferencedSample(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Sweeper: &roleSweeper{}}))
resp := ts.sweep(t, `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
if _, present := decodeBody(t, resp)["referenced_ids"]; present {
t.Error("referenced_ids is present with nothing protected; the document says absent")
}
}
// TestSweepRefusesTheDocumentedBodies walks the 400 table. Every case names the
// member it is about in `param`, which is the whole reason the handler decodes
// member by member instead of unmarshaling the generated struct.
func TestSweepRefusesTheDocumentedBodies(t *testing.T) {
for _, test := range []struct {
name string
body string
param string
}{
{"no tier", `{"pattern":"*"}`, "tier"},
{"tier is not a string", `{"tier":3}`, "tier"},
{"tier is null", `{"tier":null}`, "tier"},
{"tier outside the enum", `{"tier":"wisps"}`, "tier"},
{"unknown member", `{"tier":"durable","scope":"all"}`, "scope"},
{"actor is not a string", `{"tier":"ephemeral","actor":7}`, "actor"},
{"actor is blank", `{"tier":"ephemeral","actor":" "}`, "actor"},
{"closed_before is not a timestamp", `{"tier":"ephemeral","closed_before":"yesterday"}`, "closed_before"},
{"pattern is not a string", `{"tier":"ephemeral","pattern":true}`, "pattern"},
{"dry_run is not a boolean", `{"tier":"ephemeral","dry_run":"yes"}`, "dry_run"},
{"protect_referenced is not a boolean", `{"tier":"ephemeral","protect_referenced":1}`, "protect_referenced"},
} {
t.Run(test.name, func(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.sweep(t, test.body)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if body["param"] != test.param {
t.Errorf("param = %v, want %q", body["param"], test.param)
}
// A refused body must never reach the role: the sweep is
// destructive, and "refused after acting" is the one failure shape
// worth ruling out at every edge.
if got := len(sweeper.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused body, want 0", got)
}
})
}
}
// TestSweepPublishesTheRolesRefusalAsA400 is the reason failSweepErr exists.
//
// The require-a-filter gate, the tier vocabulary and the glob are all refused
// BELOW the wire, by issueops.Sweeper — that is what makes this endpoint
// incapable of an unguarded mass delete. A role refusal reaching the client as
// a 500 would tell it the server was broken when the request was, and would
// hide the one sentence that says what to send instead.
func TestSweepPublishesTheRolesRefusalAsA400(t *testing.T) {
// The sentinel has to MATCH, not merely be mentioned in the text.
sweeper := &roleSweeper{err: wrapValidation("a durable sweep requires a closed-before cutoff or an id pattern")}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
// A body the HANDLER accepts and the ROLE refuses: the durable tier with no
// narrowing member is exactly that request, which is the point.
resp := ts.sweep(t, `{"tier":"durable"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["code"] != string(CodeInvalidArgument) {
t.Errorf("code = %v, want %s", body["code"], CodeInvalidArgument)
}
if detail, _ := body["detail"].(string); !strings.Contains(detail, "closed-before cutoff") {
t.Errorf("detail = %q, want the role's own sentence: it is what says what to send instead", detail)
}
// No `param`: the refusal is about two absent members at once, and the
// document declares `param` absent on exactly that case.
if _, present := body["param"]; present {
t.Errorf("param = %v, want it absent for a whole-request refusal", body["param"])
}
}
// TestSweepRefusesAForeignMediaType: the CSRF control the claim documents
// applies here for a sharper reason. A JSON content type is not CORS-"simple",
// so a cross-origin sweep always triggers a preflight this server never
// approves; accepting text/plain would let an attacker's page drive a mass
// delete from any browser on the host.
func TestSweepRefusesAForeignMediaType(t *testing.T) {
sweeper := &roleSweeper{}
ts := newTestServer(t, rolesConfig(Config{Sweeper: sweeper}))
resp := ts.claimRequest(t, sweepPath, "text/plain", `{"tier":"ephemeral"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
if body := decodeBody(t, resp); body["param"] != "Content-Type" {
t.Errorf("param = %v, want Content-Type", body["param"])
}
if got := len(sweeper.requests()); got != 0 {
t.Errorf("the role was called %d times for a refused media type, want 0", got)
}
}
// TestSweepPublishesNoQueryParameters: this operation's whole vocabulary is its
// body, so a query key is version skew rather than a bad value.
func TestSweepPublishesNoQueryParameters(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Sweeper: &roleSweeper{}}))
resp := ts.claimRequest(t, sweepPath+"?tier=durable", "application/json", `{"tier":"durable","pattern":"*"}`)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if body["param"] != "tier" || body["reason"] != string(ReasonUnknownParameter) {
t.Errorf("body = %v, want unknown_parameter on param tier", body)
}
}
// wrapValidation builds an error that MATCHES issueops.ErrValidation while
// reading like the role's own refusal, which is what failSweepErr keys on.
func wrapValidation(detail string) error {
return &validationError{detail: detail}
}
type validationError struct{ detail string }
func (e *validationError) Error() string { return issueops.ErrValidation.Error() + ": " + e.detail }
func (e *validationError) Unwrap() error { return issueops.ErrValidation }

View file

@ -682,6 +682,10 @@ func (s *configStore) ReadyCounter() (issueops.ReadyCounter, error) {
func (s *configStore) Querier() (issueops.Querier, error) {
return nil, &storage.ErrUnsupported{Op: "Querier", Backend: "jira-config-stub"}
}
func (s *configStore) Sweeper() (issueops.Sweeper, error) {
return nil, &storage.ErrUnsupported{Op: "Sweeper", Backend: "jira-config-stub"}
}
func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil }
func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil }
func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) {

View file

@ -0,0 +1,101 @@
package dolt
import (
"context"
"database/sql"
"fmt"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// Sweeper returns the guarded bulk-clearance surface for this store.
func (s *DoltStore) Sweeper() (issueops.Sweeper, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "Sweeper", Backend: "nil"}
}
return &sweeper{store: s}, nil
}
// sweeper clears closed rows from one tier inside ONE transaction.
//
// There is no shared constructor package for this role, for the reason
// cycleDetector gives: the work is a candidate query, a recheck, an optional
// reference scan and a delete that must all see one snapshot, and a
// transaction is not reachable through storage.DoltStorage. The sharing
// happens one level down instead — this body and the embedded store's are a
// few lines each around issueops.SweepInTx — and two wrappers over one body is
// still ONE vote, which the conformance contract says out loud.
//
// A front door cannot construct this: the type is unexported and the accessor
// is the only door.
type sweeper struct{ store *DoltStore }
var _ issueops.Sweeper = (*sweeper)(nil)
// Sweep clears the request's tier.
//
// VALIDATION HAPPENS BEFORE THE TRANSACTION, so a refused request costs no
// database work — which is what makes issueops.Sweeper's "a refusal changes
// nothing" true of the connection as well as of the rows.
//
// A DRY RUN TAKES A READ TRANSACTION. It writes nothing by construction, so
// giving it a write transaction and an empty commit would make the preview
// look like a mutation to everything watching the store.
//
// THE VERSION-CONTROL ENTRY IS ONE PER SWEEP, recorded here rather than in the
// shared body because only this backend records one at all: the embedded store
// commits outside the SQL transaction and the unit-of-work provider labels its
// own. An ephemeral sweep touches only the wisp tables, which this plane
// ignores, so DOLT_COMMIT finds nothing to commit and the sweep records no
// entry — the "at most one" the role promises, not "exactly one".
func (s *sweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (issueops.SweepResult, error) {
if err := workapi.ValidateSweepRequest(req); err != nil {
return issueops.SweepResult{}, err
}
var result issueops.SweepResult
run := func(tx *sql.Tx) error {
var err error
result, err = storeops.SweepInTx(ctx, tx, req)
return err
}
if req.DryRun {
if err := s.store.withReadTx(ctx, run); err != nil {
return issueops.SweepResult{}, err
}
return result, nil
}
if err := s.store.withWriteTx(ctx, func(tx *sql.Tx) error {
if err := run(tx); err != nil {
return err
}
if result.Swept == 0 {
return nil
}
for _, table := range sweptTables {
_ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table)
}
msg := fmt.Sprintf("bd: sweep %d %s bead(s)", result.Swept, req.Tier)
if err := schema.DrainCall(ctx, tx, "CALL DOLT_COMMIT('-m', ?, '--author', ?)",
msg, s.store.commitAuthorString()); err != nil && !isDoltNothingToCommit(err) {
return fmt.Errorf("dolt commit: %w", err)
}
return nil
}); err != nil {
return issueops.SweepResult{}, err
}
return result, nil
}
// sweptTables are the versioned tables a sweep can touch, staged before the
// commit. It is the same list DeleteIssues stages, because a sweep IS a
// delete of a selected set.
var sweptTables = []string{
"issues", "dependencies", "labels", "comments", "events",
"child_counters", "issue_snapshots", "compaction_snapshots",
}

View file

@ -0,0 +1,82 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestSweeperContract runs the Sweeper contract against the server-backed
// store, which reaches internal/storage/issueops.SweepInTx through its own
// write transaction and is the ONE wiring that records a version-control entry
// for a sweep.
//
// The cases are subtests of one parent so the whole role suite shares one
// store and one copy-on-write branch. That sharing is what makes the id
// pattern in every case load-bearing rather than tidy: a sweep is asked of a
// whole TIER, so a case that swept without one would delete the next case's
// seeds. setupTestStore already marks the PARENT parallel; no subtest here
// calls t.Parallel, and RecordsAtMostOneHistoryEntry takes a before/after
// delta that is only meaningful while they run sequentially.
func TestSweeperContract(t *testing.T) {
fixture, ctx, cleanup := newDoltSweeperFixture(t, "swp")
defer cleanup()
t.Run("RefusesAnUnfilteredDurableSweep", func(t *testing.T) {
conformance.RunSweeperRefusesAnUnfilteredDurableSweep(t, ctx, fixture)
})
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
conformance.RunSweeperRefusesAMalformedRequest(t, ctx, fixture)
})
t.Run("ClearsOneTierAndLeavesTheOther", func(t *testing.T) {
conformance.RunSweeperClearsOneTierAndLeavesTheOther(t, ctx, fixture)
})
t.Run("ProtectsPinnedRows", func(t *testing.T) {
conformance.RunSweeperProtectsPinnedRows(t, ctx, fixture)
})
t.Run("HonorsTheCutoffAndThePattern", func(t *testing.T) {
conformance.RunSweeperHonorsTheCutoffAndThePattern(t, ctx, fixture)
})
t.Run("DryRunChangesNothing", func(t *testing.T) {
conformance.RunSweeperDryRunChangesNothing(t, ctx, fixture)
})
t.Run("ProtectsCitedRows", func(t *testing.T) {
conformance.RunSweeperProtectsCitedRows(t, ctx, fixture)
})
t.Run("EmptyMatchIsZeroAndNil", func(t *testing.T) {
conformance.RunSweeperEmptyMatchIsZeroAndNil(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunSweeperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
conformance.RunSweeperDoesNotMutateTheCallerRequest(t, ctx, fixture)
})
}
// newDoltSweeperFixture composes the frozen role kit with this backend's
// accessor.
func newDoltSweeperFixture(t *testing.T, prefix string) (conformance.SweeperFixture, context.Context, func()) {
t.Helper()
store, storeCleanup := setupTestStore(t)
ctx, cancel := testContext(t)
stop := func() {
cancel()
storeCleanup()
}
sweeper, err := store.Sweeper()
if err != nil {
stop()
t.Fatalf("Sweeper(): %v", err)
}
kit := newDoltRoleFixtureKit(store, prefix)
return conformance.SweeperFixture{
IssuePrefix: kit.IssuePrefix,
Sweeper: sweeper,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
}, ctx, stop
}

View file

@ -0,0 +1,53 @@
//go:build cgo
package embeddeddolt
import (
"context"
"database/sql"
"github.com/steveyegge/beads/internal/storage"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// Sweeper returns the guarded bulk-clearance surface for this store.
func (s *EmbeddedDoltStore) Sweeper() (issueops.Sweeper, error) {
if s == nil {
return nil, &storage.ErrUnsupported{Op: "Sweeper", Backend: "nil"}
}
return &sweeper{store: s}, nil
}
// sweeper clears closed rows from one tier inside one connection's
// transaction.
//
// It is a sibling of the server-backed store's body rather than a shared
// package for the reason that one gives: the work needs a TRANSACTION, which
// storage.DoltStorage does not publish, so the sharing happens below both of
// them at issueops.SweepInTx. The two stores differ here only in how they
// reach a transaction and in whether they record a version-control entry —
// this one's commit runs outside the SQL transaction, so it records none.
type sweeper struct{ store *EmbeddedDoltStore }
var _ issueops.Sweeper = (*sweeper)(nil)
// Sweep clears the request's tier. Validation happens before the connection is
// opened, so a refused request costs no database work.
func (s *sweeper) Sweep(ctx context.Context, req issueops.SweepRequest) (issueops.SweepResult, error) {
if err := workapi.ValidateSweepRequest(req); err != nil {
return issueops.SweepResult{}, err
}
var result issueops.SweepResult
// commit = !DryRun: a preview writes nothing, so it must not take the
// committing path — the same distinction DeleteIssues draws here.
if err := s.store.withConn(ctx, !req.DryRun, func(tx *sql.Tx) error {
var err error
result, err = storeops.SweepInTx(ctx, tx, req)
return err
}); err != nil {
return issueops.SweepResult{}, err
}
return result, nil
}

View file

@ -0,0 +1,73 @@
//go:build cgo
package embeddeddolt_test
import (
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestSweeperContract runs the Sweeper contract against the embedded store,
// which hands back the SAME body the server-backed store does
// (internal/storage/issueops.SweepInTx) and differs only in how it reaches a
// transaction and in that its commit runs outside one. That is what this
// wiring catches; it is not an independent vote on the body.
//
// One environment for the whole suite: booting an embedded engine per case
// would dominate the runtime, every case scopes itself to prefix-namespaced
// ids, and the history delta needs the subtests sequential anyway.
func TestSweeperContract(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "swp")
ctx := t.Context()
fixture := newEmbeddedSweeperFixture(t, te, "swp")
t.Run("RefusesAnUnfilteredDurableSweep", func(t *testing.T) {
conformance.RunSweeperRefusesAnUnfilteredDurableSweep(t, ctx, fixture)
})
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
conformance.RunSweeperRefusesAMalformedRequest(t, ctx, fixture)
})
t.Run("ClearsOneTierAndLeavesTheOther", func(t *testing.T) {
conformance.RunSweeperClearsOneTierAndLeavesTheOther(t, ctx, fixture)
})
t.Run("ProtectsPinnedRows", func(t *testing.T) {
conformance.RunSweeperProtectsPinnedRows(t, ctx, fixture)
})
t.Run("HonorsTheCutoffAndThePattern", func(t *testing.T) {
conformance.RunSweeperHonorsTheCutoffAndThePattern(t, ctx, fixture)
})
t.Run("DryRunChangesNothing", func(t *testing.T) {
conformance.RunSweeperDryRunChangesNothing(t, ctx, fixture)
})
t.Run("ProtectsCitedRows", func(t *testing.T) {
conformance.RunSweeperProtectsCitedRows(t, ctx, fixture)
})
t.Run("EmptyMatchIsZeroAndNil", func(t *testing.T) {
conformance.RunSweeperEmptyMatchIsZeroAndNil(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunSweeperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
conformance.RunSweeperDoesNotMutateTheCallerRequest(t, ctx, fixture)
})
}
func newEmbeddedSweeperFixture(t *testing.T, te *testEnv, prefix string) conformance.SweeperFixture {
t.Helper()
sweeper, err := te.store.Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
kit := newEmbeddedRoleFixtureKit(te, prefix)
return conformance.SweeperFixture{
IssuePrefix: kit.IssuePrefix,
Sweeper: sweeper,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
}
}

View file

@ -0,0 +1,29 @@
package storage
import (
"github.com/steveyegge/beads/issueops"
)
// Sweeper returns the inner store's bulk-clearance surface.
//
// IT RECURSES UNWRAPPED, and this is the one WRITE role that does. The
// read roles recurse because nothing completed; this one completes plenty and
// still has no hook to fire, for two reasons that are both about the hook
// vocabulary rather than about the sweep:
//
// - there is no on_delete hook. internal/hooks publishes on_create,
// on_update and on_close, and a sweep is none of them. Firing on_update
// for a row that no longer exists would hand a user's script an id it
// cannot read back.
// - a hook script is handed an ISSUE, and a sweep's result carries counts
// rather than rows — deliberately, because a sweep of ten thousand wisps
// that materialized all ten thousand to fire a subprocess each would be a
// new failure mode rather than a feature.
//
// So the accessor EXISTS on this decorator — declared, never inherited, which
// the reflection test in role_accessor_decorator_test.go asserts — and adds no
// layer. If a delete event ever joins the hook vocabulary, this file is where
// it lands.
func (h *HookFiringStore) Sweeper() (issueops.Sweeper, error) {
return h.inner.Sweeper()
}

View file

@ -0,0 +1,135 @@
package issueops
import (
"context"
"database/sql"
"fmt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
publicops "github.com/steveyegge/beads/issueops"
)
// SweepInTx is the store-backed body behind issueops.Sweeper: the whole of
// `bd purge` and `bd prune` from candidate query to deletion, inside ONE
// transaction.
//
// It lives here rather than in an importable internal/workapi/store<role>
// package for the reason DetectCycleReportInTx does: the work is several reads
// and a write that must see one snapshot, and storage.DoltStorage publishes
// methods, not transactions. The two Dolt-backed stores share this body and
// differ only in how they reach a transaction, so they are ONE vote and the
// unit-of-work provider is the second. There is nothing here a front door
// could construct — the function takes a transaction — so no depguard entry is
// needed to keep it out of cmd/bd.
//
// It assumes a request already refused by workapi.ValidateSweepRequest. The
// accessors validate BEFORE opening a transaction, so a refusal costs no
// database work and, as issueops.Sweeper promises, changes nothing.
//
// ONE TRANSACTION IS THE POINT. The direct CLI route this replaces searched in
// one transaction and deleted in another, so a row closed, unpinned or cited
// between the two was reported as one thing and treated as another. It is also
// what this gives up: the server-backed store's own DeleteIssues splits large
// wisp deletions into batched transactions to stay inside Dolt's write
// timeout, and a sweep cannot both do that and promise that the set it counted
// is the set it deleted. It promises the latter.
func SweepInTx(ctx context.Context, tx *sql.Tx, req publicops.SweepRequest) (publicops.SweepResult, error) {
result := publicops.SweepResult{DryRun: req.DryRun}
candidates, err := SearchIssuesInTx(ctx, tx, "", workapi.BuildSweepCandidateFilter(req))
if err != nil {
return publicops.SweepResult{}, fmt.Errorf("listing sweep candidates: %w", err)
}
kept, skips := workapi.FilterSweepCandidates(candidates, req.IDPattern, req.ClosedBefore)
result.Skipped = skips
if req.ProtectReferenced {
referenced, err := sweepReferencedInTx(ctx, tx, kept)
if err != nil {
return publicops.SweepResult{}, err
}
var count int
kept, count, result.ReferencedIDs = workapi.PartitionSweepReferenced(kept, referenced)
result.Skipped.Referenced = count
}
if len(kept) == 0 {
return result, nil
}
ids := make([]string, len(kept))
for i, issue := range kept {
ids[i] = issue.ID
}
// cascade=false, force=true: a sweep deletes what it selected and ORPHANS
// dependents outside the selection, which is what the direct route has
// always done for a real run. The DRY RUN passes the same flags rather
// than the force=false the route used to pass, so a preview reports what
// the sweep would do instead of refusing over dependents the sweep would
// have orphaned — the old dry run could fail where the real run succeeded,
// and the CLI answered that failure with zeros.
deleted, err := DeleteIssuesInTx(ctx, tx, ids, false, true, req.DryRun)
if err != nil {
return publicops.SweepResult{}, err
}
result.Swept = deleted.DeletedCount
result.Dependencies = deleted.DependenciesCount
result.Labels = deleted.LabelsCount
result.Events = deleted.EventsCount
return result, nil
}
// sweepReferencedInTx returns which of the candidates are cited by a row that
// is not done, reading the not-done set and its comments on the SAME
// transaction the candidates came off.
//
// Reading the workspace's custom statuses is required rather than
// best-effort: an error propagates and aborts the sweep, because a scan that
// silently missed a custom active status would under-protect and delete a bead
// a live bead still cites (issueops.SweepRequest.ProtectReferenced).
func sweepReferencedInTx(ctx context.Context, tx *sql.Tx, candidates []*types.Issue) (map[string]bool, error) {
if len(candidates) == 0 {
return nil, nil
}
candidateIDs := make(map[string]bool, len(candidates))
for _, issue := range candidates {
candidateIDs[issue.ID] = true
}
matcher := workapi.NewCandidateIDMatcher(candidateIDs)
custom, err := ResolveCustomStatusesDetailedInTx(ctx, tx)
if err != nil {
return nil, fmt.Errorf("reading custom statuses for reference scan: %w", err)
}
notDone, err := SearchIssuesInTx(ctx, tx, "", workapi.BuildSweepReferenceScanFilter(custom))
if err != nil {
return nil, fmt.Errorf("scanning open beads for references: %w", err)
}
notDoneIDs := make([]string, 0, len(notDone))
for _, issue := range notDone {
if issue != nil {
notDoneIDs = append(notDoneIDs, issue.ID)
}
}
comments, err := GetCommentsForIssuesInTx(ctx, tx, notDoneIDs)
if err != nil {
return nil, fmt.Errorf("scanning open beads for references: %w", err)
}
referenced := make(map[string]bool)
for _, issue := range notDone {
if issue == nil {
continue
}
matcher.FindAll(issue.Description, referenced)
matcher.FindAll(issue.Notes, referenced)
for _, c := range comments[issue.ID] {
matcher.FindAll(c.Text, referenced)
}
}
return referenced, nil
}

View file

@ -11,9 +11,9 @@ import (
"github.com/steveyegge/beads/issueops"
)
// roleAccessorNames is the fourteen-strong capability surface every storage
// roleAccessorNames is the sixteen-strong capability surface every storage
// decorator has to answer for. It is written out rather than derived so that
// adding a fifteenth role to DoltStorage without deciding what each decorator
// adding a seventeenth role to DoltStorage without deciding what each decorator
// does with it is a compile-or-test failure somewhere, not silence.
var roleAccessorNames = []string{
"IssueLifecycle",
@ -27,6 +27,7 @@ var roleAccessorNames = []string{
"CycleDetector",
"ReadyCounter",
"Querier",
"Sweeper",
"Commenter",
"ReadyClaimer",
"BatchCloser",
@ -68,9 +69,9 @@ func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) {
}
}
// roleAccessorStore is a DoltStorage whose only real methods are the fourteen role
// accessors, each answering with a distinguishable sentinel so a test can tell
// a decorated surface from a passed-through one.
// roleAccessorStore is a DoltStorage whose only real methods are the sixteen
// role accessors, each answering with a distinguishable sentinel so a test can
// tell a decorated surface from a passed-through one.
type roleAccessorStore struct {
DoltStorage
lifecycle issueops.Lifecycle
@ -88,6 +89,7 @@ type roleAccessorStore struct {
editor issueops.DependencyEditor
readyCounter issueops.ReadyCounter
querier issueops.Querier
sweeper issueops.Sweeper
err error
}
@ -109,6 +111,7 @@ func newRoleAccessorStore() *roleAccessorStore {
editor: sentinel,
readyCounter: sentinel,
querier: sentinel,
sweeper: sentinel,
}
}
@ -135,6 +138,9 @@ func (s *roleAccessorStore) ReadyCounter() (issueops.ReadyCounter, error) {
return s.readyCounter, s.err
}
func (s *roleAccessorStore) Querier() (issueops.Querier, error) { return s.querier, s.err }
func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
return s.sweeper, s.err
}
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
return s.claimer, s.err
}
@ -143,7 +149,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error
return s.editor, s.err
}
// roleAccessorSentinel implements all fourteen roles at once. Nothing calls its
// roleAccessorSentinel implements all sixteen roles at once. Nothing calls its
// methods; identity is the whole point.
type roleAccessorSentinel struct{}
@ -216,6 +222,10 @@ func (*roleAccessorSentinel) CountReady(context.Context, issueops.ReadyRequest)
func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) {
return issueops.IssuePage{}, nil
}
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
return issueops.SweepResult{}, nil
}
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
return issueops.AddCommentResult{}, nil
}
@ -276,6 +286,11 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
{"CycleDetector", func() (any, error) { return store.CycleDetector() }, inner.cycles, false},
{"ReadyCounter", func() (any, error) { return store.ReadyCounter() }, inner.readyCounter, false},
{"Querier", func() (any, error) { return store.Querier() }, inner.querier, false},
// The one WRITE role in the unwrapped column, and the reason is the
// hook vocabulary rather than the role: there is no on_delete hook to
// fire and a swept row is gone, so hook_sweeper.go recurses. Asserting
// it here is what keeps that a decision.
{"Sweeper", func() (any, error) { return store.Sweeper() }, inner.sweeper, false},
} {
t.Run(test.name, func(t *testing.T) {
surface, err := test.got()
@ -321,6 +336,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
{"CycleDetector", func() (any, error) { return store.CycleDetector() }},
{"ReadyCounter", func() (any, error) { return store.ReadyCounter() }},
{"Querier", func() (any, error) { return store.Querier() }},
{"Sweeper", func() (any, error) { return store.Sweeper() }},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := test.got(); !errors.Is(err, want) {

View file

@ -217,6 +217,18 @@ type Storage interface {
// CONJUNCTION — every field narrows — and no arrangement of its fields
// expresses a disjunction. Reads fire no hooks, as for IssueReader.
Querier() (issueops.Querier, error)
// Sweeper returns the guarded bulk-clearance surface for this store —
// `bd purge` and `bd prune`, which are one capability over two disjoint
// tiers rather than two. Its own role because it describes a SET and then
// acts on it: no Lifecycle patch names a set, and composing a count with a
// delete would reopen the window this role exists to close.
//
// It is the one WRITE role whose hook decorator recurses UNWRAPPED, and
// that is a fact about the hook vocabulary rather than about the role:
// there is no on_delete hook to fire (internal/hooks publishes create,
// update and close), and the rows a sweep would name it with are gone.
// See hook_sweeper.go.
Sweeper() (issueops.Sweeper, error)
// Issue CRUD
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error

View file

@ -0,0 +1,174 @@
package uow
import (
"context"
"fmt"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/workapi"
publicops "github.com/steveyegge/beads/issueops"
)
// SweeperSource is the capability accessor a unit-of-work provider offers for
// the bulk-clearance role, the sibling of CounterSource and IssueReaderSource.
// A consumer holding a provider by interface asks for the role here instead of
// reaching for a constructor.
type SweeperSource interface {
Sweeper() (publicops.Sweeper, error)
}
// sweeper clears closed rows from one tier through a unit of work.
type sweeper struct {
provider UnitOfWorkProvider
}
// Sweeper returns the guarded bulk-clearance surface for this provider.
func (p *doltSQLProvider) Sweeper() (publicops.Sweeper, error) {
return NewSweeper(p)
}
// NewSweeper constructs a public sweeper backed by provider.
func NewSweeper(provider UnitOfWorkProvider) (publicops.Sweeper, error) {
if isNilUnitOfWorkProvider(provider) {
return nil, fmt.Errorf("new sweeper: unit-of-work provider must not be nil")
}
return &sweeper{provider: provider}, nil
}
var _ publicops.Sweeper = (*sweeper)(nil)
// Sweep clears the request's tier inside ONE unit of work.
//
// This is the genuinely separate body: the two store backends share
// issueops.SweepInTx, and this one reaches the same four questions through the
// domain use cases. What it must NOT do differently is which rows go — the
// selection, the pattern, the pinned and closed_at rechecks and the citation
// rule all run through the same internal/workapi functions the shared body
// runs, so the two implementations differ in their plumbing rather than in
// their answer.
//
// ONE UNIT OF WORK matters more here than it does for a read. The candidate
// query and the delete are on the same transaction, so a row closed, unpinned
// or cited between them cannot change what is deleted — the promise
// issueops.Sweeper.Sweep makes and the property the direct CLI route did not
// have before this role existed.
//
// A DRY RUN TAKES A READ-ONLY UNIT OF WORK: it writes nothing, so it must not
// take the committing path and leave a history entry describing a preview.
func (s *sweeper) Sweep(ctx context.Context, req publicops.SweepRequest) (publicops.SweepResult, error) {
if err := workapi.ValidateSweepRequest(req); err != nil {
return publicops.SweepResult{}, err
}
if req.DryRun {
return RunTxRead(ctx, s.provider, func(ctx context.Context, uw UnitOfWork) (publicops.SweepResult, error) {
return sweepInUOW(ctx, uw, req)
})
}
return RunTxResult(ctx, s.provider, func(ctx context.Context, uw UnitOfWork) (publicops.SweepResult, string, error) {
result, err := sweepInUOW(ctx, uw, req)
if err != nil || result.Swept == 0 {
// A sweep that deleted nothing labels nothing: the role promises
// at most one history entry per call and none for a no-op.
return result, "", err
}
return result, fmt.Sprintf("bd: sweep %d %s bead(s)", result.Swept, req.Tier), nil
})
}
// sweepInUOW is the whole sweep on one unit of work, shared by the preview
// path and the committing one so the two cannot answer differently.
func sweepInUOW(ctx context.Context, uw UnitOfWork, req publicops.SweepRequest) (publicops.SweepResult, error) {
result := publicops.SweepResult{DryRun: req.DryRun}
page, err := uw.IssueUseCase().SearchIssues(ctx, "", workapi.BuildSweepCandidateFilter(req))
if err != nil {
return publicops.SweepResult{}, fmt.Errorf("listing sweep candidates: %w", err)
}
kept, skips := workapi.FilterSweepCandidates(page.Items, req.IDPattern, req.ClosedBefore)
result.Skipped = skips
if req.ProtectReferenced {
referenced, err := sweepReferencedInUOW(ctx, uw, kept)
if err != nil {
return publicops.SweepResult{}, err
}
var count int
kept, count, result.ReferencedIDs = workapi.PartitionSweepReferenced(kept, referenced)
result.Skipped.Referenced = count
}
if len(kept) == 0 {
return result, nil
}
ids := make([]string, len(kept))
for i, issue := range kept {
ids[i] = issue.ID
}
deleted, err := uw.IssueUseCase().DeleteIssues(ctx, domain.DeleteIssuesParams{
IDs: ids,
DryRun: req.DryRun,
}, req.Actor)
if err != nil {
return publicops.SweepResult{}, err
}
result.Swept = deleted.DeletedCount
result.Dependencies = deleted.DependenciesCount
result.Labels = deleted.LabelsCount
result.Events = deleted.EventsCount
return result, nil
}
// sweepReferencedInUOW returns which of the candidates a not-done row cites,
// reading the not-done set and its comments on the same unit of work the
// candidates came off.
//
// It reads the comments of the whole not-done set in ONE batch rather than one
// query per row, which is what makes the protection affordable on the corpora
// `bd prune` runs over.
func sweepReferencedInUOW(ctx context.Context, uw UnitOfWork, candidates []*types.Issue) (map[string]bool, error) {
if len(candidates) == 0 {
return nil, nil
}
candidateIDs := make(map[string]bool, len(candidates))
for _, issue := range candidates {
candidateIDs[issue.ID] = true
}
matcher := workapi.NewCandidateIDMatcher(candidateIDs)
custom, err := uw.ConfigUseCase().GetCustomStatuses(ctx)
if err != nil {
return nil, fmt.Errorf("reading custom statuses for reference scan: %w", err)
}
page, err := uw.IssueUseCase().SearchIssues(ctx, "", workapi.BuildSweepReferenceScanFilter(custom))
if err != nil {
return nil, fmt.Errorf("scanning open beads for references: %w", err)
}
notDone := page.Items
notDoneIDs := make([]string, 0, len(notDone))
for _, issue := range notDone {
if issue != nil {
notDoneIDs = append(notDoneIDs, issue.ID)
}
}
comments, err := uw.CommentUseCase().GetCommentsForIssues(ctx, notDoneIDs)
if err != nil {
return nil, fmt.Errorf("scanning open beads for references: %w", err)
}
referenced := make(map[string]bool)
for _, issue := range notDone {
if issue == nil {
continue
}
matcher.FindAll(issue.Description, referenced)
matcher.FindAll(issue.Notes, referenced)
for _, c := range comments[issue.ID] {
matcher.FindAll(c.Text, referenced)
}
}
return referenced, nil
}

View file

@ -0,0 +1,80 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestSweeperContract runs the Sweeper contract against the unit-of-work
// provider — the one implementation that does not run
// internal/storage/issueops.SweepInTx, and the one that reaches the same four
// questions through the domain use cases. It is the SECOND of two votes, not
// the third: the two store backends share the other body.
//
// One provider for the whole suite (each newUOWRoleFixtureProvider boots a
// real Dolt sql-server) and NO t.Parallel: this backend has no per-test
// copy-on-write branch, so dolt_log and the issues table are database-global
// and a parallel subtest would delete another subtest's rows — which on this
// role is not a flake but the operation working as documented.
func TestSweeperContract(t *testing.T) {
ctx := context.Background()
fixture := newUOWSweeperFixture(t, ctx, "swp")
t.Run("RefusesAnUnfilteredDurableSweep", func(t *testing.T) {
conformance.RunSweeperRefusesAnUnfilteredDurableSweep(t, ctx, fixture)
})
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
conformance.RunSweeperRefusesAMalformedRequest(t, ctx, fixture)
})
t.Run("ClearsOneTierAndLeavesTheOther", func(t *testing.T) {
conformance.RunSweeperClearsOneTierAndLeavesTheOther(t, ctx, fixture)
})
t.Run("ProtectsPinnedRows", func(t *testing.T) {
conformance.RunSweeperProtectsPinnedRows(t, ctx, fixture)
})
t.Run("HonorsTheCutoffAndThePattern", func(t *testing.T) {
conformance.RunSweeperHonorsTheCutoffAndThePattern(t, ctx, fixture)
})
t.Run("DryRunChangesNothing", func(t *testing.T) {
conformance.RunSweeperDryRunChangesNothing(t, ctx, fixture)
})
t.Run("ProtectsCitedRows", func(t *testing.T) {
conformance.RunSweeperProtectsCitedRows(t, ctx, fixture)
})
t.Run("EmptyMatchIsZeroAndNil", func(t *testing.T) {
conformance.RunSweeperEmptyMatchIsZeroAndNil(t, ctx, fixture)
})
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
conformance.RunSweeperRecordsAtMostOneHistoryEntry(t, ctx, fixture)
})
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
conformance.RunSweeperDoesNotMutateTheCallerRequest(t, ctx, fixture)
})
}
func newUOWSweeperFixture(t *testing.T, ctx context.Context, prefix string) conformance.SweeperFixture {
t.Helper()
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
// Through the capability accessor, not NewSweeper: a provider that stopped
// offering the role is the regression, and a constructor call would hide
// it.
source, ok := provider.(SweeperSource)
if !ok {
t.Fatalf("provider %T does not offer the Sweeper accessor", provider)
}
sweeper, err := source.Sweeper()
if err != nil {
t.Fatalf("Sweeper(): %v", err)
}
kit := newUOWRoleFixtureKit(provider, prefix)
return conformance.SweeperFixture{
IssuePrefix: kit.IssuePrefix,
Sweeper: sweeper,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
}
}

View file

@ -12,7 +12,7 @@ import (
"github.com/steveyegge/beads/issueops"
)
// roleAccessorNames is the fourteen-strong capability surface every storage
// roleAccessorNames is the sixteen-strong capability surface every storage
// decorator has to answer for. It is duplicated from the sibling test in
// internal/storage rather than shared because that package cannot import this
// one and this one's test helpers cannot be exported back.
@ -28,6 +28,7 @@ var roleAccessorNames = []string{
"CycleDetector",
"ReadyCounter",
"Querier",
"Sweeper",
"Commenter",
"ReadyClaimer",
"BatchCloser",
@ -58,8 +59,8 @@ func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) {
}
}
// roleAccessorStore is a DoltStorage whose only real methods are the fourteen role
// accessors, each answering with a distinguishable sentinel so a test can tell
// roleAccessorStore is a DoltStorage whose only real methods are the sixteen
// role accessors, each answering with a distinguishable sentinel so a test can tell
// an instrumented surface from a passed-through one.
type roleAccessorStore struct {
storage.DoltStorage
@ -90,6 +91,9 @@ func (s *roleAccessorStore) ReadyCounter() (issueops.ReadyCounter, error) {
return s.surface, s.err
}
func (s *roleAccessorStore) Querier() (issueops.Querier, error) { return s.surface, s.err }
func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
return s.surface, s.err
}
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
return s.surface, s.err
}
@ -98,7 +102,7 @@ func (s *roleAccessorStore) DependencyEditor() (issueops.DependencyEditor, error
return s.surface, s.err
}
// roleAccessorSentinel implements all fourteen roles at once. Nothing calls its
// roleAccessorSentinel implements all sixteen roles at once. Nothing calls its
// methods; identity is the whole point.
type roleAccessorSentinel struct{}
@ -171,6 +175,10 @@ func (*roleAccessorSentinel) CountReady(context.Context, issueops.ReadyRequest)
func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issueops.IssuePage, error) {
return issueops.IssuePage{}, nil
}
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
return issueops.SweepResult{}, nil
}
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
return issueops.AddCommentResult{}, nil
}
@ -193,7 +201,7 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe
// DoltStorage, and silently drops every span and timing on that role.
//
// Unlike the hook decorator, this one has no read-role exemption: telemetry
// spans reads as well as writes, so ALL THIRTEEN must come back wrapped. Only
// spans reads as well as writes, so ALL FOURTEEN must come back wrapped. Only
// IssueLifecycle and IssueReader had a recursion pin of their own before this
// test; the rest had no test at all.
func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
@ -220,6 +228,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
{"CycleDetector", func() (any, error) { return wrapped.CycleDetector() }},
{"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }},
{"Querier", func() (any, error) { return wrapped.Querier() }},
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
@ -263,6 +272,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
{"CycleDetector", func() (any, error) { return wrapped.CycleDetector() }},
{"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }},
{"Querier", func() (any, error) { return wrapped.Querier() }},
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},

View file

@ -0,0 +1,38 @@
package telemetry
import (
"context"
"github.com/steveyegge/beads/issueops"
)
// Sweeper returns the inner store's bulk-clearance surface wrapped in this
// layer's instrumentation. It recurses instead of delegating: a blind
// delegation would return the inner sweeper unspanned and untimed — and this
// is the longest-running write on the surface, so it is the one whose span
// matters most.
func (s *InstrumentedStorage) Sweeper() (issueops.Sweeper, error) {
inner, err := s.Unwrap().Sweeper()
if err != nil {
return nil, err
}
return s.WrapSweeper(inner), nil
}
// WrapSweeper instruments guarded bulk clearance with this storage layer's
// existing telemetry meter and tracer.
func (s *InstrumentedStorage) WrapSweeper(inner issueops.Sweeper) issueops.Sweeper {
return &instrumentedSweeper{storage: s, inner: inner}
}
type instrumentedSweeper struct {
storage *InstrumentedStorage
inner issueops.Sweeper
}
func (c *instrumentedSweeper) Sweep(ctx context.Context, request issueops.SweepRequest) (result issueops.SweepResult, err error) {
ctx, span, started := c.storage.op(ctx, "Sweeper.Sweep")
result, err = c.inner.Sweep(ctx, request)
c.storage.done(ctx, span, started, err)
return result, err
}

View file

@ -0,0 +1,6 @@
//go:build !race
package workapi
// raceEnabled is false in non-race builds; see race_detector_on_test.go.
const raceEnabled = false

View file

@ -0,0 +1,11 @@
//go:build race
package workapi
// raceEnabled reports whether the test binary was built with the race
// detector (-race). Wall-clock performance budgets are unreliable under race
// instrumentation (it adds multi-x overhead), so timing-sensitive benches
// consult this flag before enforcing a duration bound. It is a sibling of the
// pair in cmd/bd, which is where the sweep's large-fixture budget used to
// live.
const raceEnabled = true

274
internal/workapi/sweep.go Normal file
View file

@ -0,0 +1,274 @@
package workapi
import (
"fmt"
"path/filepath"
"sort"
"strings"
"time"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The shared, DATABASE-FREE half of issueops.Sweeper: what a sweep request
// means, which candidates survive the recheck, and what counts as a citation.
// Every implementation of the role runs these, so `bd purge` and `bd prune`
// have one definition rather than one per backend, and the parts that decide
// what the answer MEANS are pinned in sweep_test.go in milliseconds.
//
// What is NOT here is the sweep itself. Selecting rows and deleting them needs
// one transaction (issueops.Sweeper.Sweep), which no interface above a store
// publishes; the bodies live in internal/storage/issueops/sweep.go and in the
// unit-of-work provider.
// ValidateSweepRequest applies the request rules every Sweeper implementation
// shares, before anything is read.
//
// The require-a-filter refusal for the durable tier is the one that matters,
// and it is HERE rather than in a CLI handler on purpose: it is a safety
// invariant, so a second front door inherits it by calling the role rather
// than by remembering to re-implement it. See issueops.SweepRequest.
func ValidateSweepRequest(in issueops.SweepRequest) error {
switch in.Tier {
case issueops.SweepEphemeral, issueops.SweepDurable:
case "":
return fmt.Errorf("%w: sweep requires a tier (%q or %q), and has no default",
issueops.ErrValidation, issueops.SweepEphemeral, issueops.SweepDurable)
default:
return fmt.Errorf("%w: %q is not a sweep tier; use %q or %q",
issueops.ErrValidation, in.Tier, issueops.SweepEphemeral, issueops.SweepDurable)
}
if in.IDPattern != "" {
// filepath.Match reports a malformed pattern on any subject, so one
// probe against the empty string classifies the pattern itself. The
// front doors used to discard this error, which turned `--pattern '['`
// into "nothing matched" on a command whose job is to delete matches.
if _, err := filepath.Match(in.IDPattern, ""); err != nil {
return fmt.Errorf("%w: --pattern %q is not a valid glob: %v",
issueops.ErrValidation, in.IDPattern, err)
}
}
if in.Tier == issueops.SweepDurable && in.ClosedBefore == nil && in.IDPattern == "" {
return fmt.Errorf("%w: a durable sweep requires a closed-before cutoff or an id pattern; "+
"pass the pattern \"*\" to sweep every closed issue deliberately",
issueops.ErrValidation)
}
return nil
}
// BuildSweepCandidateFilter turns a sweep request into the storage-level
// filter that selects its CANDIDATES: the closed rows of one tier, bounded by
// the cutoff.
//
// The pattern is deliberately NOT in the filter. Globs are matched in Go
// (MatchesSweepPattern) because the storage seam has no glob predicate and a
// LIKE translation would silently disagree with filepath.Match on `[...]` and
// on the escape rules — a disagreement that, on this operation, decides which
// rows are deleted.
//
// Call ValidateSweepRequest first; this builder assumes a validated request
// and does not re-refuse one.
func BuildSweepCandidateFilter(in issueops.SweepRequest) types.IssueFilter {
closed := types.StatusClosed
ephemeral := in.Tier == issueops.SweepEphemeral
filter := types.IssueFilter{
Status: &closed,
Ephemeral: &ephemeral,
}
if in.ClosedBefore != nil {
cutoff := *in.ClosedBefore
filter.ClosedBefore = &cutoff
}
return filter
}
// MatchesSweepPattern reports whether an id is admitted by a request's
// IDPattern. An empty pattern admits everything.
//
// A malformed pattern reports false here; ValidateSweepRequest is what refuses
// it, so this function is never the place a bad glob is discovered.
func MatchesSweepPattern(pattern, id string) bool {
if pattern == "" {
return true
}
ok, err := filepath.Match(pattern, id)
return err == nil && ok
}
// FilterSweepCandidates applies the pattern and then the two protections that
// hold a candidate back before any reference scan: the pinned flag, and the
// closed_at recheck.
//
// THE ORDER IS PART OF THE ANSWER, and issueops.Sweeper.Sweep states it: the
// pattern narrows first, so a pinned row the pattern excluded is not counted
// as protected — it was never a candidate. The three closed_at buckets are
// defenses against the tier query returning a row it was not asked for, and
// they are counted rather than dropped so a disagreement between the query and
// the recheck is visible instead of silent.
//
// cutoff is the request's ClosedBefore; a nil cutoff performs the presence
// checks and skips the comparison.
func FilterSweepCandidates(issues []*types.Issue, pattern string, cutoff *time.Time) ([]*types.Issue, issueops.SweepSkips) {
kept := make([]*types.Issue, 0, len(issues))
var skips issueops.SweepSkips
for _, issue := range issues {
if issue == nil {
skips.Unreadable++
continue
}
if !MatchesSweepPattern(pattern, issue.ID) {
continue
}
switch {
case issue.Pinned:
skips.Pinned++
case issue.Status != types.StatusClosed:
skips.NotClosed++
case issue.ClosedAt == nil:
skips.UnknownClosedAt++
case cutoff != nil && !issue.ClosedAt.Before(*cutoff):
skips.ClosedAtOrAfterCutoff++
default:
kept = append(kept, issue)
}
}
return kept, skips
}
// SweepDefenseSkips is how many candidates the recheck rejected as
// self-inconsistent — the three closed_at buckets plus the unreadable row.
// It is separate from the two PROTECTIONS (pinned, referenced) because a
// non-zero value here is a defense firing rather than a normal outcome, and
// the front doors warn on exactly that.
func SweepDefenseSkips(s issueops.SweepSkips) int {
return s.Unreadable + s.NotClosed + s.UnknownClosedAt + s.ClosedAtOrAfterCutoff
}
// NotDoneStatusesForSweep is the status vocabulary a reference scan asks:
// every built-in status that is not "closed", plus every configured custom
// status whose category is not "done".
//
// It is an explicit LIST rather than a not-closed exclusion because that is
// what the storage seam takes reliably on both planes (a Statuses set, not an
// ExcludeStatus). Reading the workspace's custom statuses is required, not
// best-effort: a scan that missed a custom active status would under-protect
// and delete a bead a live bead still cites — see
// issueops.SweepRequest.ProtectReferenced.
func NotDoneStatusesForSweep(custom []types.CustomStatus) []types.Status {
statuses := []types.Status{
types.StatusOpen,
types.StatusInProgress,
types.StatusBlocked,
types.StatusDeferred,
types.StatusPinned,
types.StatusHooked,
}
for _, cs := range custom {
if cs.Category != types.CategoryDone {
statuses = append(statuses, types.Status(cs.Name))
}
}
return statuses
}
// BuildSweepReferenceScanFilter selects the rows a reference scan reads: the
// not-done set, and nothing else about them.
func BuildSweepReferenceScanFilter(custom []types.CustomStatus) types.IssueFilter {
return types.IssueFilter{Statuses: NotDoneStatusesForSweep(custom)}
}
// CandidateIDMatcher finds literal, word-bounded occurrences of a candidate id
// set in arbitrary text. It is the whole of what "cited" means for
// issueops.SweepRequest.ProtectReferenced.
//
// It is bucketed by FIRST BYTE and each bucket sorted longest-first, because
// the scan is run over every not-done bead's description, notes and comments:
// a naive strings.Contains per candidate is O(candidates x text) and the
// reference protection exists on the command that runs over the largest
// corpora. Longest-first inside a bucket is what makes `be-1.1` win over
// `be-1` where both are candidates and both start at the same offset.
type CandidateIDMatcher struct {
byFirstByte map[byte][]string
}
// NewCandidateIDMatcher builds a matcher over a candidate id set. Empty ids
// are dropped: they would match at every boundary.
func NewCandidateIDMatcher(candidateIDs map[string]bool) CandidateIDMatcher {
byFirstByte := make(map[byte][]string)
for id := range candidateIDs {
if id == "" {
continue
}
byFirstByte[id[0]] = append(byFirstByte[id[0]], id)
}
for first := range byFirstByte {
ids := byFirstByte[first]
sort.Slice(ids, func(i, j int) bool {
if len(ids[i]) == len(ids[j]) {
return ids[i] < ids[j]
}
return len(ids[i]) > len(ids[j])
})
byFirstByte[first] = ids
}
return CandidateIDMatcher{byFirstByte: byFirstByte}
}
// FindAll adds every candidate id occurring in text at ASCII word boundaries
// to found.
func (m CandidateIDMatcher) FindAll(text string, found map[string]bool) {
for i := 0; i < len(text); i++ {
ids := m.byFirstByte[text[i]]
if len(ids) == 0 || !isWordBoundaryAt(text, i) {
continue
}
for _, id := range ids {
end := i + len(id)
if end <= len(text) && strings.HasPrefix(text[i:], id) && isWordBoundaryAt(text, end) {
found[id] = true
break
}
}
}
}
func isWordBoundaryAt(s string, idx int) bool {
var before, after byte
if idx > 0 {
before = s[idx-1]
}
if idx < len(s) {
after = s[idx]
}
return isASCIIWordByte(before) != isASCIIWordByte(after)
}
func isASCIIWordByte(b byte) bool {
return b == '_' ||
('0' <= b && b <= '9') ||
('A' <= b && b <= 'Z') ||
('a' <= b && b <= 'z')
}
// PartitionSweepReferenced splits candidates into the ones no not-done row
// cites and the ones some row does, and returns the bounded sample
// issueops.SweepResult.ReferencedIDs carries.
//
// The kept slice preserves the candidate order, and so does the sample, so two
// runs over one snapshot report the same ids.
func PartitionSweepReferenced(candidates []*types.Issue, referenced map[string]bool) (kept []*types.Issue, referencedCount int, sample []string) {
kept = make([]*types.Issue, 0, len(candidates))
for _, issue := range candidates {
if referenced[issue.ID] {
referencedCount++
if len(sample) < issueops.SweepReferencedSampleLimit {
sample = append(sample, issue.ID)
}
continue
}
kept = append(kept, issue)
}
return kept, referencedCount, sample
}

View file

@ -0,0 +1,352 @@
package workapi
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// The DATABASE-FREE half of issueops.Sweeper, pinned in milliseconds: what a
// request means, which candidates survive the recheck, and what counts as a
// citation. The conformance contract is left to assert what only a real
// backend can show.
func TestValidateSweepRequestRequiresATier(t *testing.T) {
for _, test := range []struct {
name string
tier issueops.SweepTier
}{
{"unset", ""},
{"unrecognized", issueops.SweepTier("wisps")},
} {
t.Run(test.name, func(t *testing.T) {
err := ValidateSweepRequest(issueops.SweepRequest{Tier: test.tier, IDPattern: "*"})
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("ValidateSweepRequest(tier=%q) error = %v, want ErrValidation", test.tier, err)
}
})
}
}
// TestValidateSweepRequestGatesTheDurableTier is the safety invariant Q9 moved
// below the front doors: an unfiltered DURABLE sweep is a refusal, and the
// same request on the ephemeral tier is not.
func TestValidateSweepRequestGatesTheDurableTier(t *testing.T) {
cutoff := time.Now()
for _, test := range []struct {
name string
request issueops.SweepRequest
refused bool
}{
{"durable, no filter", issueops.SweepRequest{Tier: issueops.SweepDurable}, true},
{"durable, cutoff", issueops.SweepRequest{Tier: issueops.SweepDurable, ClosedBefore: &cutoff}, false},
{"durable, pattern", issueops.SweepRequest{Tier: issueops.SweepDurable, IDPattern: "*"}, false},
// The deliberate keystroke the refusal points at: "*" is how a caller
// says "everything closed" on purpose.
{"durable, star", issueops.SweepRequest{Tier: issueops.SweepDurable, IDPattern: "*"}, false},
{"ephemeral, no filter", issueops.SweepRequest{Tier: issueops.SweepEphemeral}, false},
} {
t.Run(test.name, func(t *testing.T) {
err := ValidateSweepRequest(test.request)
if got := errors.Is(err, issueops.ErrValidation); got != test.refused {
t.Fatalf("ValidateSweepRequest() error = %v, want refused=%v", err, test.refused)
}
})
}
}
// TestValidateSweepRequestRefusesAMalformedPattern pins the defect fix: both
// front doors used to discard filepath.Match's error, so a bad glob reported
// "nothing matched" on a command whose job is to delete what it matched.
func TestValidateSweepRequestRefusesAMalformedPattern(t *testing.T) {
err := ValidateSweepRequest(issueops.SweepRequest{Tier: issueops.SweepDurable, IDPattern: "[bad"})
if !errors.Is(err, issueops.ErrValidation) {
t.Fatalf("ValidateSweepRequest(pattern=%q) error = %v, want ErrValidation", "[bad", err)
}
if !strings.Contains(err.Error(), "[bad") {
t.Fatalf("refusal %q does not quote the pattern the caller sent", err)
}
}
func TestBuildSweepCandidateFilterSelectsOneClosedTier(t *testing.T) {
cutoff := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
for _, test := range []struct {
tier issueops.SweepTier
ephemeral bool
}{
{issueops.SweepEphemeral, true},
{issueops.SweepDurable, false},
} {
t.Run(string(test.tier), func(t *testing.T) {
filter := BuildSweepCandidateFilter(issueops.SweepRequest{Tier: test.tier, ClosedBefore: &cutoff})
if filter.Status == nil || *filter.Status != types.StatusClosed {
t.Fatalf("filter.Status = %v, want closed", filter.Status)
}
if filter.Ephemeral == nil || *filter.Ephemeral != test.ephemeral {
t.Fatalf("filter.Ephemeral = %v, want %v", filter.Ephemeral, test.ephemeral)
}
if filter.ClosedBefore == nil || !filter.ClosedBefore.Equal(cutoff) {
t.Fatalf("filter.ClosedBefore = %v, want %v", filter.ClosedBefore, cutoff)
}
})
}
}
// TestBuildSweepCandidateFilterCopiesTheCutoff pins the no-mutation promise on
// the one pointer the request carries.
func TestBuildSweepCandidateFilterCopiesTheCutoff(t *testing.T) {
cutoff := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
filter := BuildSweepCandidateFilter(issueops.SweepRequest{Tier: issueops.SweepDurable, ClosedBefore: &cutoff})
if filter.ClosedBefore == &cutoff {
t.Fatal("filter shares the caller's *time.Time; a builder must not hand back an alias of a request field")
}
}
// TestFilterSweepCandidatesRechecksClosedAtCutoff is the recheck's own table,
// moved here from cmd/bd when the role took it below both front doors.
func TestFilterSweepCandidatesRechecksClosedAtCutoff(t *testing.T) {
cutoff := time.Date(2026, 3, 27, 20, 1, 44, 0, time.UTC)
oldClosedAt := cutoff.Add(-time.Second)
recentClosedAt := cutoff.Add(time.Second)
candidates := []*types.Issue{
{ID: "old-closed", Status: types.StatusClosed, ClosedAt: &oldClosedAt},
{ID: "recent-closed", Status: types.StatusClosed, ClosedAt: &recentClosedAt},
{ID: "missing-closed-at", Status: types.StatusClosed},
{ID: "open-with-old-closed-at", Status: types.StatusOpen, ClosedAt: &oldClosedAt},
{ID: "pinned-old", Status: types.StatusClosed, ClosedAt: &oldClosedAt, Pinned: true},
nil,
}
filtered, skips := FilterSweepCandidates(candidates, "", &cutoff)
if len(filtered) != 1 || filtered[0].ID != "old-closed" {
t.Fatalf("filtered IDs = %v, want only old-closed", sweepCandidateIDs(filtered))
}
for _, check := range []struct {
name string
got int
}{
{"Pinned", skips.Pinned},
{"ClosedAtOrAfterCutoff", skips.ClosedAtOrAfterCutoff},
{"UnknownClosedAt", skips.UnknownClosedAt},
{"NotClosed", skips.NotClosed},
{"Unreadable", skips.Unreadable},
} {
if check.got != 1 {
t.Errorf("skips.%s = %d, want 1", check.name, check.got)
}
}
}
func TestFilterSweepCandidatesWithoutCutoffStillRequiresClosedAt(t *testing.T) {
closedAt := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
candidates := []*types.Issue{
{ID: "closed", Status: types.StatusClosed, ClosedAt: &closedAt},
{ID: "closed-missing-time", Status: types.StatusClosed},
}
filtered, skips := FilterSweepCandidates(candidates, "", nil)
if len(filtered) != 1 || filtered[0].ID != "closed" {
t.Fatalf("filtered IDs = %v, want only closed", sweepCandidateIDs(filtered))
}
if skips.UnknownClosedAt != 1 {
t.Fatalf("skips.UnknownClosedAt = %d, want 1", skips.UnknownClosedAt)
}
if skips.ClosedAtOrAfterCutoff != 0 {
t.Fatalf("skips.ClosedAtOrAfterCutoff = %d, want 0 without a cutoff", skips.ClosedAtOrAfterCutoff)
}
}
// TestFilterSweepCandidatesNarrowsByPatternBeforeProtecting pins the ORDER
// issueops.Sweeper.Sweep states: a pinned row the pattern excluded is not
// counted as protected, because it was never a candidate.
func TestFilterSweepCandidatesNarrowsByPatternBeforeProtecting(t *testing.T) {
closedAt := time.Date(2026, 4, 26, 18, 30, 18, 0, time.UTC)
candidates := []*types.Issue{
{ID: "keep-1", Status: types.StatusClosed, ClosedAt: &closedAt},
{ID: "keep-pinned", Status: types.StatusClosed, ClosedAt: &closedAt, Pinned: true},
{ID: "other-pinned", Status: types.StatusClosed, ClosedAt: &closedAt, Pinned: true},
}
filtered, skips := FilterSweepCandidates(candidates, "keep-*", nil)
if len(filtered) != 1 || filtered[0].ID != "keep-1" {
t.Fatalf("filtered IDs = %v, want only keep-1", sweepCandidateIDs(filtered))
}
if skips.Pinned != 1 {
t.Fatalf("skips.Pinned = %d, want 1 — only the pinned row the pattern ADMITTED is a protection", skips.Pinned)
}
}
func TestMatchesSweepPatternAdmitsEverythingWhenEmpty(t *testing.T) {
if !MatchesSweepPattern("", "anything-at-all") {
t.Fatal("an empty pattern must admit every id")
}
if MatchesSweepPattern("[bad", "anything") {
t.Fatal("a malformed pattern must not match; ValidateSweepRequest is what refuses it")
}
}
// TestNotDoneStatusesForSweepIncludesActiveCustomStatuses is the clause
// issueops.SweepRequest.ProtectReferenced calls required rather than
// best-effort: a workspace's own active status has to protect what it cites.
func TestNotDoneStatusesForSweepIncludesActiveCustomStatuses(t *testing.T) {
statuses := NotDoneStatusesForSweep([]types.CustomStatus{
{Name: "reviewing", Category: types.CategoryActive},
{Name: "shipped", Category: types.CategoryDone},
})
found := map[types.Status]bool{}
for _, s := range statuses {
found[s] = true
}
if !found["reviewing"] {
t.Error("an active custom status must be scanned for citations")
}
if found["shipped"] {
t.Error("a done custom status must not be scanned: it is not a live bead")
}
if !found[types.StatusOpen] || !found[types.StatusInProgress] {
t.Error("the built-in active statuses must always be scanned")
}
}
func TestCandidateIDMatcherWordBoundaries(t *testing.T) {
candidates := map[string]bool{
"be-ref-001": true,
"be-ref-001.1": true,
"be-ref-002": true,
}
matcher := NewCandidateIDMatcher(candidates)
found := make(map[string]bool)
matcher.FindAll("see (be-ref-001), be-ref-001.1 and xbe-ref-002 but not be-ref-002x", found)
if !found["be-ref-001"] {
t.Fatal("expected be-ref-001 to match at punctuation boundaries")
}
if !found["be-ref-001.1"] {
t.Fatal("expected be-ref-001.1 to match at punctuation boundaries")
}
if found["be-ref-002"] {
t.Fatal("did not expect be-ref-002 to match inside word boundaries")
}
}
// TestPartitionSweepReferencedBoundsTheSample pins the published cap: the
// sample is at most issueops.SweepReferencedSampleLimit long while the COUNT
// is the whole protected set, so a caller can tell a truncated sample from a
// complete one.
func TestPartitionSweepReferencedBoundsTheSample(t *testing.T) {
const protected = issueops.SweepReferencedSampleLimit + 25
candidates := make([]*types.Issue, 0, protected+1)
referenced := make(map[string]bool, protected)
for i := 0; i < protected; i++ {
id := fmt.Sprintf("be-ref-%03d", i)
candidates = append(candidates, &types.Issue{ID: id})
referenced[id] = true
}
candidates = append(candidates, &types.Issue{ID: "be-free"})
kept, count, sample := PartitionSweepReferenced(candidates, referenced)
if len(kept) != 1 || kept[0].ID != "be-free" {
t.Fatalf("kept = %v, want only the uncited candidate", sweepCandidateIDs(kept))
}
if count != protected {
t.Fatalf("referenced count = %d, want %d — the COUNT is the whole set", count, protected)
}
if len(sample) != issueops.SweepReferencedSampleLimit {
t.Fatalf("sample length = %d, want the published cap %d", len(sample), issueops.SweepReferencedSampleLimit)
}
if sample[0] != "be-ref-000" {
t.Fatalf("sample[0] = %q, want the first candidate — the sample keeps candidate order", sample[0])
}
}
// TestCandidateIDMatcherLargeFixture is the NFR-02 budget from be-5sn, moved
// here with the scan itself: 10K bodies of ~5KB each, matched against 100
// candidates, in under five seconds. It is the matcher that made the old
// per-candidate substring scan unaffordable, so the matcher is what the budget
// is written against — the store round trips it used to include measured the
// fixture, not the algorithm.
func TestCandidateIDMatcherLargeFixture(t *testing.T) {
if testing.Short() {
t.Skip("skipping large fixture bench")
}
const (
bodyCount = 10_000
candidateCount = 100
seededRefCount = 20
bodyPadding = 5_000 // bytes of filler per bead
maxDurationSeconds = 5
)
candidates := make(map[string]bool, candidateCount)
for i := 0; i < candidateCount; i++ {
candidates[fmt.Sprintf("be-ref-%03d", i)] = true
}
seeded := make([]string, seededRefCount)
i := 0
for id := range candidates {
if i >= seededRefCount {
break
}
seeded[i] = id
i++
}
// Padding text that does NOT contain any candidate ID substring.
pad := strings.Repeat("x", bodyPadding)
bodies := make([]string, bodyCount)
seededIdx := 0
for j := 0; j < bodyCount; j++ {
bodies[j] = pad
if seededIdx < seededRefCount && j%500 == 0 {
bodies[j] = fmt.Sprintf("%s %s %s", pad[:100], seeded[seededIdx], pad[100:])
seededIdx++
}
}
matcher := NewCandidateIDMatcher(candidates)
found := make(map[string]bool)
start := time.Now()
for _, body := range bodies {
matcher.FindAll(body, found)
}
elapsed := time.Since(start)
// The race detector adds multi-x overhead that invalidates a wall-clock
// budget, so only enforce the bound in non-race builds. The correctness
// assertions below still run under -race, which is where the large-fixture
// pass earns its keep as a data-race check.
if !raceEnabled && elapsed > maxDurationSeconds*time.Second {
t.Errorf("scan took %v; must complete in <%ds on a %d-body fixture", elapsed, maxDurationSeconds, bodyCount)
}
if len(found) != seededIdx {
t.Errorf("expected %d referenced IDs, got %d", seededIdx, len(found))
}
for _, id := range seeded[:seededIdx] {
if !found[id] {
t.Errorf("expected %s to be in the reference set but it was not", id)
}
}
}
func sweepCandidateIDs(issues []*types.Issue) []string {
ids := make([]string, len(issues))
for i, issue := range issues {
ids[i] = issue.ID
}
return ids
}

View file

@ -425,3 +425,36 @@ func TestQuerierExposesTypedUnsupportedError(t *testing.T) {
t.Fatalf("Querier() error = %v, want *beads.ErrUnsupported", err)
}
}
// TestSweeperKeepsTelemetryOutermost is the bulk-clearance role's version of
// the same pin, and it is the ONE WRITE role that answers the way the reads
// do: there is no on_delete hook to fire (internal/storage/hook_sweeper.go), so
// the hook decorator adds no layer and the outermost surface a caller gets is
// the instrumented one. Pinning it here is what keeps that a decision rather
// than a wrapper someone forgot to write.
func TestSweeperKeepsTelemetryOutermost(t *testing.T) {
t.Setenv("BD_OTEL_STDOUT", "true")
instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage)
if !ok {
t.Fatal("WrapStorage() did not create InstrumentedStorage")
}
sweeper, err := storage.NewHookFiringStore(instrumented, nil).Sweeper()
if err != nil {
t.Fatalf("Sweeper() error = %v", err)
}
if got := reflect.TypeOf(sweeper).String(); got != "*telemetry.instrumentedSweeper" {
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
}
}
func TestSweeperExposesTypedUnsupportedError(t *testing.T) {
sweeper, err := (*dolt.DoltStore)(nil).Sweeper()
if sweeper != nil {
t.Fatalf("Sweeper() sweeper = %T, want nil", sweeper)
}
var unsupported *beads.ErrUnsupported
if !errors.As(err, &unsupported) {
t.Fatalf("Sweeper() error = %v, want *beads.ErrUnsupported", err)
}
}

View file

@ -469,14 +469,14 @@ type IssuePage struct {
// types.WorkFilter there at all, so no filter is writable there either — both
// are directory-scoped with no per-file exception, so a file added to that
// package tomorrow is covered the moment it exists. That same forbidigo rule
// covers cmd/bd deny-by-default with 61 named exceptions, so the files
// covers cmd/bd deny-by-default with 59 named exceptions, so the files
// implementing `bd list` and `bd show` cannot write a filter, and neither can
// a file they are split or renamed into unless the new name lands on that
// list. NOT ENFORCED: the rule forbids NAMING those types, not holding a
// value, so the property is "no filter is written there", not "every filter
// there came from a builder"; test files are exempt from both rules, because
// the oracles hold filters in order to inspect them; `bd ready`'s files are
// among the 61, since its listing and --claim are handed the filter itself and
// among the 59, since its listing and --claim are handed the filter itself and
// the blocked-issue views in those files name one directly, so it is guarded by
// the builder and the golden files and not by the linter;
// GET /healthz and GET /v0/beads/context are not issue queries and are on no

281
issueops/sweeper.go Normal file
View file

@ -0,0 +1,281 @@
package issueops
import (
"context"
"time"
)
// SweepTier names which of the two planes a sweep clears. It is REQUIRED on
// every request and has no default, for the reason RelatedRequest.Direction
// has none: the two tiers are disjoint sets of rows reached by one operation,
// and a caller handed the wrong one has nothing to notice until the rows are
// gone.
//
// The two are DISJOINT by construction — a sweep of one tier can never touch a
// row of the other — which is what lets `bd purge` and `bd prune` be one
// capability with a parameter rather than two capabilities that resemble each
// other.
type SweepTier string
const (
// SweepEphemeral clears CLOSED rows of the wisp tier: `bd purge`.
// Ephemeral rows accumulate fast, carry no long-term value once closed,
// and live in tables the version-control plane ignores.
SweepEphemeral SweepTier = "ephemeral"
// SweepDurable clears CLOSED rows of the issue tier: `bd prune`. This is
// the tier a workspace's real history lives in, which is why it — and only
// it — carries the require-a-filter refusal SweepRequest.ClosedBefore
// describes.
SweepDurable SweepTier = "durable"
)
// SweepRequest describes one bulk clearance of closed rows: which tier, which
// of its closed rows, and whether to do it or only report it.
//
// IT IS NOT A FILTER-SHAPED READ REQUEST with a delete attached. The predicate
// is FIXED at "closed rows of one tier" and the two fields below only narrow
// it; there is no status, no assignee, no label and no free-text query,
// because every one of those would be a way to spell a destructive selection
// that no front door asks for and that a caller could get subtly wrong. What
// this request can express is exactly what `bd purge` and `bd prune` expose,
// and widening it is a decision rather than an omission to be filled in.
//
// Implementations never mutate caller-owned request values: ClosedBefore is
// read, never written through.
type SweepRequest struct {
// Actor attributes the sweep wherever the backend records attribution. It
// is not an authorization boundary — nothing here checks who the caller
// is — and an empty Actor is accepted, because the deletion of a row
// leaves no row to attribute it on.
Actor string
// Tier selects the plane. It is REQUIRED: the zero value is ErrValidation
// rather than a default, and an unrecognized value is ErrValidation rather
// than a sweep that matches nothing.
Tier SweepTier
// ClosedBefore keeps only rows closed STRICTLY BEFORE this instant. A row
// whose stored closed_at is exactly this instant is kept, which is the
// half-open interval every other time bound in this package uses.
//
// It is one half of the DURABLE TIER'S SAFETY GATE: a SweepDurable request
// with neither ClosedBefore nor IDPattern set is ErrValidation, never an
// unfiltered mass delete. That refusal lives HERE, below every front door,
// rather than in the CLI handler that historically owned it. The gate is a
// safety invariant and not presentation: a second front door — an HTTP
// operation, a library embedder — that inherited the capability without
// the guard would be one handler away from erasing every closed issue in a
// workspace, and a guard that each caller must remember is a guard that
// one caller will not. A caller that really does mean "everything closed"
// says so with IDPattern "*", which is a deliberate keystroke rather than
// an omitted one.
//
// The EPHEMERAL tier carries no such gate: an unfiltered sweep of closed
// wisps is the ordinary use of `bd purge`, and the tier is transient by
// definition.
ClosedBefore *time.Time
// IDPattern keeps only rows whose ID matches this shell glob, in the
// syntax of path/filepath.Match (`*`, `?`, `[...]`, `\` escapes; `*` also
// crosses `-` and `.`, since an id is not a path). Empty matches every row
// in the tier.
//
// A MALFORMED PATTERN IS ErrValidation, not a pattern that matches
// nothing. Both front doors previously discarded filepath.Match's error,
// so `--pattern '['` reported "no beads to prune" — indistinguishable from
// a correct pattern over an empty set, on a command whose whole job is to
// delete what it matched.
//
// It is the other half of the durable tier's gate: see ClosedBefore.
IDPattern string
// ProtectReferenced skips candidates whose ID is CITED by a row that is
// not done — in its description, its notes, or any of its comments — so a
// decision trail a live bead still points at is not deleted out from under
// it.
//
// WHAT COUNTS AS A CITATION is a literal occurrence of the id at ASCII
// word boundaries: `be-1` matches in "see (be-1)." and does not match
// inside `xbe-1` or `be-12`. It is a text scan, not a link: an id spelled
// in prose protects, and a stored dependency edge does not (a sweep
// removes edges pointing at what it deletes — see SweepResult).
//
// WHICH ROWS ARE ASKED is every row whose status is not a done one: the
// built-in active statuses plus every configured custom status whose
// category is not "done". Enumerating the workspace's custom statuses is
// REQUIRED rather than best-effort, because a failure to read them would
// under-scan and delete a bead a live custom-status bead still cites; an
// implementation that cannot read them fails the sweep instead.
//
// It costs a full scan of the not-done set and of that set's comments, so
// it is opt-in per request rather than always-on. `bd prune` asks for it;
// `bd purge` does not, because a wisp's citations are as transient as the
// wisp.
ProtectReferenced bool
// DryRun reports what the sweep WOULD do and deletes nothing. The result
// is otherwise the same result — the same counts, the same skips, the same
// refusals — computed against the same snapshot the real sweep would have
// used, which is what makes a preview worth reading.
DryRun bool
}
// SweepSkips reports the candidates a sweep declined to delete, bucketed by
// WHY. Every bucket is a row the tier's predicate admitted and the sweep then
// held back, so the buckets and SweepResult.Swept describe one candidate set.
//
// They are separate counters rather than one number because they mean
// different things to the person reading them: Pinned and Referenced are
// PROTECTIONS a user can override or re-express, and the other three are the
// sweep declining to trust its own input.
type SweepSkips struct {
// Pinned counts candidates protected by the pinned flag. Pinning is the
// workspace's own "never sweep this", and no request field overrides it —
// a caller that wants a pinned row gone unpins it first.
Pinned int
// Referenced counts candidates skipped by ProtectReferenced. It is always
// 0 when that field is false; a caller that reads a 0 without having asked
// for the protection has learned nothing about whether rows are cited.
Referenced int
// NotClosed, UnknownClosedAt and ClosedAtOrAfterCutoff count candidates
// the tier's own query returned and the sweep rechecked and rejected: a
// status that is not closed, a closed row with no closed_at stamp at all,
// and a closed_at that does not satisfy ClosedBefore.
//
// A NON-ZERO VALUE IN ANY OF THESE THREE IS A DEFENSE FIRING, not a normal
// outcome, because the query was asked for exactly the rows they exclude.
// They are published rather than silently dropped so an operator can see
// that a delete-everything-closed query and a delete-everything-closed
// recheck disagreed, which is the state in which nothing should be
// deleted on trust.
NotClosed int
UnknownClosedAt int
ClosedAtOrAfterCutoff int
// Unreadable counts rows the tier's query returned as nothing at all. It
// is a defense of the same kind, on a shape rather than a value.
Unreadable int
}
// SweepResult reports one sweep.
//
// EVERY NUMBER DESCRIBES THE SAME SNAPSHOT, because the whole sweep — the
// candidate query, the recheck, the reference scan and the deletion — runs in
// ONE transaction. See Sweeper.Sweep.
type SweepResult struct {
// DryRun echoes the request. It is here so a result value carries whether
// its numbers describe rows that are gone or rows that would go, without
// the caller having to keep the request beside it.
DryRun bool
// Swept is how many rows were deleted, or — under DryRun — would be.
Swept int
// Dependencies, Labels and Events count the ROWS OF ASSOCIATED DATA the
// sweep removed with them: edges pointing at or out of a swept row, its
// labels, and its recorded events. They are reported because a sweep's
// visible effect is much larger than its row count, and because they are
// the number that explains a large storage reclaim from a small Swept.
Dependencies int
Labels int
Events int
// Skipped reports the candidates the sweep held back and why.
Skipped SweepSkips
// ReferencedIDs is a BOUNDED SAMPLE of the ids Skipped.Referenced counts —
// at most SweepReferencedSampleLimit of them, in the order the candidate
// query returned them. It is a sample and not the set: a caller that needs
// every protected id re-runs with ProtectReferenced false and a DryRun to
// see the difference, or narrows the request.
//
// It is empty when nothing was protected, and never longer than the count
// beside it.
ReferencedIDs []string
}
// SweepReferencedSampleLimit bounds SweepResult.ReferencedIDs. It is published
// so a caller can tell a truncated sample from a complete one by comparing the
// slice's length against it, rather than against a number copied out of an
// implementation.
const SweepReferencedSampleLimit = 100
// Sweeper describes bulk clearance of CLOSED rows — the capability behind
// `bd purge` (the ephemeral tier) and `bd prune` (the durable one) — and, like
// every other capability here, a role with its own accessor. A new capability
// gets a new role interface and its own accessor; never append a method here.
//
// ONE CAPABILITY, NOT TWO. purge and prune name one operation over two
// disjoint tiers: the same candidate query, the same pinned protection, the
// same closed_at recheck, the same deletion. The tier is a REQUEST FIELD
// because that is what it is — a selection — and splitting it into two roles
// would have produced two interfaces over one body, which is the accretion the
// governing rule exists to prevent in the other direction. What genuinely
// differs between them is expressed as request fields too: the durable tier's
// require-a-filter refusal keys on Tier, and the reference protection is
// asked for rather than implied.
//
// IT IS A DIFFERENT QUESTION FROM ITS NEIGHBORS.
//
// - Reader answers with rows. This answers with an EFFECT, and its
// result is a tally of what it did — there is no page of it, no cursor
// into it, and asking twice does not answer twice.
// - Counter answers "how many match". A sweep matches and then ACTS, and
// the two cannot be composed by a caller without reintroducing exactly the
// window this role closes: count, then delete what you counted, is two
// transactions.
// - Lifecycle patches ONE issue the caller names. A sweep names none: it
// describes a set and the implementation resolves it. That is the whole
// reason the safety gate can live here at all — there is a selection to
// refuse.
//
// WRITES, AND THE ONLY DESTRUCTIVE ROLE IN THIS PACKAGE. A sweep deletes rows
// and everything that hangs off them, and nothing it deletes comes back. Its
// completion fires the hook the front doors already fire for a bulk change;
// its refusals change nothing at all.
//
// Deterministic request-validation failures match ErrValidation. Result values
// are unspecified when error is non-nil, with one deliberate exception stated
// on Sweep.
type Sweeper interface {
// Sweep deletes the closed rows of req.Tier that req's two narrowing
// fields admit, and reports what it did.
//
// IT IS ONE TRANSACTION, and that is the central promise of this role
// rather than an implementation note. The candidate query, the pinned and
// closed_at rechecks, the reference scan and the deletion all see one
// snapshot, so:
//
// the set this result describes IS the set it deleted
//
// A row created, closed, unpinned or cited between the selection and the
// deletion cannot change which rows go. The direct CLI route did not have
// that property before this role existed — it selected in one transaction
// and deleted in another, so a bead closed in the window was reported and
// not deleted, and a bead pinned in the window was deleted after being
// judged unpinned.
//
// WHAT THAT COSTS, said out loud because it is a real trade and not a free
// win: a sweep is ALL OR NOTHING. A sweep large enough to exceed a
// backend's write timeout fails whole and deletes nothing, where a
// batching implementation would have deleted some of it. That is the
// better of the two failures — the partial one previously reported a
// deleted count of zero while having deleted rows — but a caller sweeping
// a very large set narrows the request rather than expecting progress.
//
// THE ORDER THE NARROWING HAPPENS IN IS PART OF THE ANSWER, because the
// skip counters are counted along the way: the tier's closed rows, then
// IDPattern, then the pinned and closed_at rechecks, then the reference
// protection. A pinned row excluded by the pattern is therefore NOT
// counted in Skipped.Pinned — it was never a candidate — and the counters
// describe the set the request actually reached.
//
// REFUSALS, all ErrValidation and all before anything is read:
//
// - an unset or unrecognized Tier;
// - a SweepDurable request with neither ClosedBefore nor IDPattern (see
// SweepRequest.ClosedBefore for why this lives here);
// - an IDPattern that is not a well-formed glob.
//
// A REQUEST THAT MATCHES NOTHING IS A ZERO RESULT AND A NIL ERROR, not a
// not-found: an empty set of closed rows is the steady state of a swept
// workspace, and it is the answer a scheduled sweep gets every time it
// runs after the first.
//
// A DRY RUN CHANGES NOTHING, including history: an implementation that
// records a version-control entry for a sweep records none for a dry run
// and none for a sweep that deleted nothing. Where an implementation
// versions at all, one sweep records AT MOST ONE entry — the deletion is
// one act, not one per row.
Sweep(ctx context.Context, req SweepRequest) (SweepResult, error)
}