beads/cmd/bd/reclaim_embedded_test.go
Julian Knutsen 470ec832b5
feat(roles): LeaseReclaimer role, POST issues:reclaim, and bd reclaim on both routes (S9) (#7412)
* feat(roles): LeaseReclaimer role and POST issues:reclaim (S9)

Adds issueops.LeaseReclaimer.Reclaim(ReclaimRequest{Actor, OlderThan,
Filter}) -> ReclaimResult{Reclaimed []ReclaimedLease{ID, PreviousOwner,
Revision}}, the stale-lease sweep behind `bd reclaim`, on every leg:

- dolt, embedded dolt and the unit-of-work provider all run one body,
  internal/storage/issueops.ExecuteReclaimInTx over
  ReclaimExpiredLeasesInTx, and record one version commit per sweep that
  reverted anything through the issue-operation funnel (so a deferred
  version commit on the context is honored);
- each reverted row's fresh row_lock is published as its revision, so a
  former holder's guarded write fails with ErrVersionMismatch;
- an id that is not a stale lease (absent, live, unheld) is left out of
  Reclaimed, never an error; the id scope is capped at 1000
  (*TooManyReclaimIDsError, counted as sent);
- the hook decorator fires on_update once per reverted row (and the
  proxied notifying provider records one update per row); telemetry
  wraps it like every role.

bd serve publishes it as POST /v0/beads/issues:reclaim behind the new
issues.reclaim capability (httpapi.Config.LeaseReclaimer, required like
every role). Spec, apigen and the wire-shape golden are regenerated;
the change is additive and wire_revision is unchanged. The HTTP client
leg dials it (wire vocabulary, capability preflight, local validation
in the role's order).

Conformance: RunLeaseReclaimer* (12 cases: revert post-state, the
revision race, live lease, grace window, id scope with absent/live ids,
empty answer, assignee/label scopes re-homed from reclaim_scope.go,
recovery event attribution, on_update once per row, refusals, the cap
boundary, no request mutation) wired on dolt, embeddeddolt, uow and the
served http leg, and so held by the leg lock. Handler tests cover the
member mapping, the projection, every handler refusal by name and the
role's refusals reaching the wire.

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

* feat(bd): bd reclaim runs the LeaseReclaimer role on both routes (S9)

`bd reclaim` takes issueops.LeaseReclaimer off the decorated store on the
direct route (so a connected HTTP workspace dials issues:reclaim instead
of refusing) and off the proxied provider's own accessor on the proxied
route, replacing the raw ReclaimExpiredLeases calls and
runReclaimProxiedServer. Visible changes: --json entries carry the
reverted row's new `revision`, the workspace's on_update hook fires once
per reverted row, and the version commit is the role's own
("bd: reclaim N expired lease(s)", honoring dolt.auto-commit through the
context the way bd prune does).

Tests: an embedded direct-route CLI test (scoped sweep with a live and an
absent id, revision, one version commit, on_update once) and the proxied
reclaim integration test now asserts the revision.

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

* fix(roles): S9 review LOWs: one validator, field attribution, overflow bound

- The library's ValidateReclaimRequest is the one definition of a valid
  reclaim: it now also refuses a blank assignee/label/label-any/exclude
  entry, and every refusal but the id cap is a *issueops.ReclaimFieldError
  naming its field. The httpapi handler no longer checks blank entries
  itself; failReclaimErr names the member the role's error is about
  (`ids` for the cap) instead of blaming `ids` for every validation. The
  HTTP client's restatement matches, pinned field by field.
- older_than_seconds is refused at >= MaxInt64/1e9: that float rounds to
  2^63 ns, which wrapped negative under the old > check.
- New contract case RunLeaseReclaimerRefusesABlankScopeEntry on all four
  legs; handler tests for field attribution and the overflow boundary.
- CHANGELOG names the 1000-id cap on bd reclaim --id and is rewrapped; the
  client's grace-window precision comment no longer claims exactness.

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

* fix(roles): S9 review: regenerate the unsupported shell, cgo-tag the embedded contract, one actor spelling

- go generate ./internal/httpclient: the new accessor moves the partial-shell
  trailer to 145 of 200.
- lease_reclaimer_contract_test.go gets //go:build cgo like its siblings, so
  the pure-Go lane compiles.
- The library trims the actor before attributing, matching the handler, so
  " alice " is attributed the same on every route.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(roles): S9 review minors: bound the reclaim actor on every leg, pin any_replica, validate before the uow

Review minors on #7412, each in code this PR adds.

- The reclaim actor lands on every reverted row's recovery event, in a
  VARCHAR(255) column, but ValidateReclaimRequest never bounded it: a
  256-character actor passed validation on the dolt, embedded-dolt and
  unit-of-work legs and failed the sweep with the backend's own
  "Error 1105: string '...' is too large for column 'actor'" on the first
  row it would have reverted (all three legs answer exactly that with the
  bound below removed). The shared validator now holds the trimmed actor to
  types.MaxFieldLen, as claimIssueInTx does, so it is a *ReclaimFieldError
  for `actor` on every leg. The HTTP client restates the rule, and the parity
  test covers both sides of it. bd serve already refused it through the
  claim's name rules. The role's Actor and REFUSALS docs name the bound, and
  the conformance case runs it on all four legs.
- ValidateReclaimRequest's doc no longer says bd serve's handler leaves every
  rule to it: it names the three wire rules the handler adds of its own.
- TestReclaimSendsAnyReplicaOnlyWhenAsked pins the one filter member that
  widens a sweep: the client sends any_replica only when the caller set it.
- The unit-of-work leg validates before opening its unit of work, as the dolt
  and embedded-dolt legs do; TestLeaseReclaimerRefusesBeforeOpeningAUOW pins
  it.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:56:32 +00:00

133 lines
4.7 KiB
Go

//go:build cgo
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// TestEmbeddedReclaimRunsTheLeaseReclaimerRole drives `bd reclaim` on the
// direct route, where it now runs issueops.LeaseReclaimer off the decorated
// store: the stale lease it names is reverted with a fresh revision, a live
// lease and an absent id it names are left out without an error, the sweep
// records its own version commit, and the workspace's on_update hook fires once
// for the reverted row.
func TestEmbeddedReclaimRunsTheLeaseReclaimerRole(t *testing.T) {
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt integration tests")
}
t.Parallel()
bd := buildEmbeddedBD(t)
dir, beadsDir, _ := bdInit(t, bd, "--prefix", "rc")
hookLog := filepath.Join(t.TempDir(), "on_update.log")
hooksDir := filepath.Join(beadsDir, "hooks")
if err := os.MkdirAll(hooksDir, 0o755); err != nil {
t.Fatalf("mkdir hooks: %v", err)
}
script := "#!/bin/sh\necho \"$1\" >> " + hookLog + "\n"
if err := os.WriteFile(filepath.Join(hooksDir, "on_update"), []byte(script), 0o755); err != nil { //nolint:gosec // G306: a hook must be executable to run at all
t.Fatalf("plant on_update: %v", err)
}
stale := bdCreate(t, bd, dir, "Stale lease", "--type", "task")
live := bdCreate(t, bd, dir, "Live lease", "--type", "task")
bdUpdate(t, bd, dir, stale.ID, "--claim")
bdUpdate(t, bd, dir, live.ID, "--claim")
cfg, _ := configfile.Load(beadsDir)
database := ""
if cfg != nil {
database = cfg.GetDoltDatabase()
}
dataDir := filepath.Join(beadsDir, "embeddeddolt")
withDB := func(fn func(exec func(string, ...any))) {
t.Helper()
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer func() { _ = cleanup() }()
fn(func(query string, args ...any) {
t.Helper()
if _, err := db.ExecContext(t.Context(), query, args...); err != nil {
t.Fatalf("%s: %v", query, err)
}
})
}
countCommits := func() int {
t.Helper()
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), dataDir, database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer func() { _ = cleanup() }()
var n int
if err := db.QueryRowContext(t.Context(), "SELECT COUNT(*) FROM dolt_log WHERE message LIKE 'bd: reclaim%'").Scan(&n); err != nil {
t.Fatalf("count reclaim commits: %v", err)
}
return n
}
withDB(func(exec func(string, ...any)) {
exec("UPDATE leases SET lease_expires_at = ? WHERE issue_id = ?", time.Now().UTC().Add(-time.Hour), stale.ID)
})
before := countCommits()
out, err := bdRunWithFlockRetry(t, bd, dir, "reclaim", "--older-than", "0s", "--json",
"--id", stale.ID, "--id", live.ID, "--id", "rc-absent")
if err != nil {
t.Fatalf("bd reclaim: %v\n%s", err, out)
}
var got struct {
Count int `json:"count"`
Scoped bool `json:"scoped"`
Reclaimed []types.ReclaimedLease `json:"reclaimed"`
}
if err := json.Unmarshal(out, &got); err != nil {
t.Fatalf("unmarshal: %v\n%s", err, out)
}
if got.Count != 1 || len(got.Reclaimed) != 1 || got.Reclaimed[0].ID != stale.ID || !got.Scoped {
t.Fatalf("reclaim answered %+v, want exactly %s, scoped", got, stale.ID)
}
if _, err := types.ParseRevisionToken(got.Reclaimed[0].Revision); err != nil || got.Reclaimed[0].Revision == "" {
t.Fatalf("reclaimed revision %q is not a revision token: %v", got.Reclaimed[0].Revision, err)
}
if after := countCommits(); after != before+1 {
t.Fatalf("reclaim version commits %d -> %d, want exactly one more", before, after)
}
if iss := bdShow(t, bd, dir, stale.ID); iss.Status != types.StatusOpen || iss.Assignee != "" {
t.Fatalf("%s after reclaim: status=%s assignee=%q, want open and unassigned", stale.ID, iss.Status, iss.Assignee)
}
if iss := bdShow(t, bd, dir, live.ID); iss.Status != types.StatusInProgress {
t.Fatalf("%s after reclaim: status=%s, want it still in_progress", live.ID, iss.Status)
}
deadline := time.Now().Add(15 * time.Second)
for {
data, _ := os.ReadFile(hookLog) // #nosec G304 -- this test's own temp file
fired := map[string]int{}
for _, line := range strings.Fields(string(data)) {
fired[line]++
}
// The claims fired on_update for both ids already; the reclaim adds
// one more for the reverted id and none for the live one.
if fired[stale.ID] == 2 && fired[live.ID] == 1 {
break
}
if time.Now().After(deadline) {
t.Fatalf("on_update fired %v, want %s twice (claim, reclaim) and %s once (claim)", fired, stale.ID, live.ID)
}
time.Sleep(50 * time.Millisecond)
}
}