diff --git a/CHANGELOG.md b/CHANGELOG.md index 91b77d72e..a3e8bee22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,6 +184,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 Tracker sync-pull always forces (remote state is authoritative). `bd batch close` remains unchecked, as before. +- **Public `beads.Storage` interface gained a required `IssueClaimer()` method** + (bd-serve claim role). `IssueClaimer() (issueops.Claimer, error)` returns the + guarded atomic claim: `Claim(ctx, issueops.ClaimRequest) (issueops.ClaimResult, + error)`, one compare-and-set that sets assignee and status only while the + issue is claimable, reports the idempotent re-claim as `Changed: false` with + nothing written, and refuses a lost CAS with a wrapped `ErrAlreadyClaimed` or + `ErrNotClaimable`. When the refusing state was readable in the same + transaction the refusal is an `*issueops.ClaimConflictError` carrying the + assignee and status — so a client classifies a conflict from typed fields + instead of matching substrings in the message, while `errors.Is` and the + refusal's exact prose are unchanged. `POST /v0/beads/issues/{id}:claim` now + runs on the role; the CLI's `bd update --claim` is not on it yet. It is a role + of its own rather than a fifth verb on `issueops.Lifecycle` — a capability + that role does not cover gets its own accessor. Consumers that only *call* the + interface are unaffected; any external type that *implements* it (a custom + store, mock, or proxy) must add the method to compile. A decorator must + implement it by recursing into the store it wraps, the way `IssueLifecycle()` + does. `ClaimResult.Issue` is the post-state issue ROW — deliberately without + labels, dependency records or comments, unlike `UpdateResult` — because that + is what the already-published v0 claim response and `bd update --claim --json` + both report today. + - **Public `beads.Storage` interface gained a required `IssueReader()` method** (bd-serve reader role). `IssueReader() (issueops.Reader, error)` is the read counterpart of `IssueLifecycle()`: one accessor returning a role that answers diff --git a/internal/httpapi/claim.go b/internal/httpapi/claim.go index 1ec92ce8a..334d30628 100644 --- a/internal/httpapi/claim.go +++ b/internal/httpapi/claim.go @@ -14,8 +14,6 @@ import ( "unicode/utf8" "github.com/steveyegge/beads/internal/httpapi/apigen" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/issueops" @@ -64,8 +62,14 @@ const ( // fire (a user-controlled subprocess per mutation is an unbounded latency // multiplier and an orphaned child at shutdown), and the per-command // auto-commit machinery never runs. The only durable effect is the single -// storage commit RunTxResult makes inside the claim's own transaction — which -// is exactly what a proxied CLI write does today. +// storage commit the claim role makes inside its own transaction — which is +// exactly what a proxied CLI write does today. +// +// Everything above the role here is argument validation: the path split, the +// media type, the body shape and the actor rules. The claim itself — the CAS, +// the eligibility rules, the claim pools, the transaction retry and the +// refusal vocabulary — belongs to issueops.Claimer, reached through the +// provider's own accessor. func (s *Server) handleClaim(w http.ResponseWriter, r *http.Request) { id, ok := s.claimTarget(w, r) if !ok { @@ -82,18 +86,21 @@ func (s *Server) handleClaim(w http.ResponseWriter, r *http.Request) { return } - rec := requestInfo(r.Context()) - out, err := uow.RunTxResult(r.Context(), timedProvider{inner: s.provider, rec: rec}, - func(ctx context.Context, uw uow.UnitOfWork) (claimOutcome, string, error) { - return claimOnUOW(ctx, uw, id, actor) - }) + claimer, err := s.claimer(r) if err != nil { s.failClaim(w, r, err) return } + result, err := claimer.Claim(r.Context(), issueops.ClaimRequest{IssueID: id, Actor: actor}) + if err != nil { + s.failClaim(w, r, err) + return + } + // `already_claimed` is the wire's name for the idempotent re-claim, which + // is exactly the case the role reports as an unchanged result. writeJSON(w, apigen.ClaimResponse{ - Issue: *out.issue, - AlreadyClaimed: out.alreadyClaimed, + Issue: *result.Issue, + AlreadyClaimed: !result.Changed, }) } @@ -289,7 +296,7 @@ func validateActor(actor string) (string, *Result) { // This is deliberately WIDER than the schema's pattern, which excludes only C0 // and DEL. The document's prose is what governs here — it promises refusal of // "any control character including newline" — and C1 qualifies: U+0085 is NEL, -// a line break on a VT-conformant terminal, so "alicebd serve: claim bd-9 +// a line break on a VT-conformant terminal, so "alicebd: claim bd-9 // by mallory" forges exactly the audit-trail line the C0 check exists to // prevent once the actor reaches the storage commit message. U+009B is the // one-byte CSI introducer, which makes an unfiltered actor an escape-sequence @@ -300,120 +307,16 @@ func isControlChar(r rune) bool { return unicode.IsControl(r) || r == '\u2028' || r == '\u2029' } -// claimOutcome is what one successful attempt produces: the row as it stands -// after the CAS, and whether the caller already held it. -type claimOutcome struct { - issue *types.Issue - alreadyClaimed bool -} - -// claimOnUOW is ONE attempt over one open unit of work: the CAS, then a fresh -// read of the row it just wrote. No retry and no commit of its own — the caller -// owns both, and uow.RunTxResult is the single implementation of that protocol -// (the proxied CLI's claim runs through the same one). Copying the retry -// protocol in here would be the second implementation that rule exists to -// prevent. -// -// WHY THIS SHARES NO FUNCTION WITH `bd update --claim`, recorded here rather -// than left as an oversight for someone to rediscover. -// -// The claim itself already IS one implementation, one level below both -// surfaces: domain issueUseCaseImpl.claim holds the CAS, the eligibility -// rules, the claim-pool case and the exact text of both refusals, and -// ClaimIssue below and ApplyUpdate's spec.Claim arm — which is what the CLI -// reaches — are two names for that one call. There is no claim logic above it -// to extract. -// -// What sits above it on each surface is that surface's own protocol, and the -// two have almost nothing in common. The CLI's is a batch over N ids that -// accumulates a per-id failure list so a later winner cannot flip the exit code -// and hide the ones that lost, resolves issue-or-wisp, applies guard -// preconditions and merge-shaped field edits in the same attempt, fires hooks -// after the write lands, and sorts its failures into an exit-code taxonomy -// (ExitGuardMismatch is not exit 1). This one takes a single id, refuses wisps -// outright, and answers a typed 409 carrying the assignee and status read back -// inside the losing transaction so that a client never has to classify a -// refusal by parsing its prose. A "shared claim function" spanning those would -// be the batch loop and the problem-details shaping welded together, which is -// not a claim and would have exactly one caller for each half. -// -// If that assessment stops holding it will be because a role appears — a claim -// role beside issueops.Lifecycle, with its own accessor — and then both -// surfaces move onto it. Until then they meet at uow.RunTxResult and at the -// domain use case, which is where the correctness actually lives. -// -// WISPS ARE NOT CLAIMABLE OVER v0. This dispatches to the issues table only, so -// a wisp id answers 404 — the wisp-aware resolve the CLI's `bd update --claim` -// performs is the shared read path the detail slice introduces, and inventing a -// private copy of it here is exactly the drift this design forbids. -func claimOnUOW(ctx context.Context, uw uow.UnitOfWork, id, actor string) (claimOutcome, string, error) { - uc := uw.IssueUseCase() - - res, err := uc.ClaimIssue(ctx, id, actor) - if err != nil { - return claimOutcome{}, "", claimRefusal(ctx, uc, id, err) - } - - // Read back INSIDE this transaction, so the body is the row this CAS wrote - // and not a later writer's. It is also the same call `bd update --claim` - // re-fetches with (the tail of domain ApplyUpdate), which is what keeps the - // two surfaces from answering with differently shaped issues. - issue, err := uc.GetIssue(ctx, id) - if err != nil { - return claimOutcome{}, "", err - } - if issue == nil { - // A miss with a nil error is the other shape a not-found takes at this - // seam; normalize it rather than dereferencing nil. - return claimOutcome{}, "", fmt.Errorf("%w: issue %s", storage.ErrNotFound, id) - } - - if res.AlreadyClaimed { - // The idempotent re-claim by the current holder: the CAS matched no row - // because there was nothing to change. An empty commit message tells - // RunTxResult to skip the commit, so a polling client cannot mint an - // empty storage commit per call. - return claimOutcome{issue: issue, alreadyClaimed: true}, "", nil - } - return claimOutcome{issue: issue}, fmt.Sprintf("bd serve: claim %s by %s", id, actor), nil -} - -// claimConflict is a lost CAS carrying the state that lost it, read back in the -// SAME transaction. It wraps the sentinel rather than replacing it, so -// ClassifyError's errors.Is mapping keeps producing the 409 unedited. -type claimConflict struct { - assignee string - status string - err error -} - -func (c *claimConflict) Error() string { return c.err.Error() } -func (c *claimConflict) Unwrap() error { return c.err } - -// claimRefusal attaches the conflicting state to a lost CAS. -// -// The re-read is the whole point: the 409's `assignee` and `issue_status` -// members come from a query in this transaction, never from parsing fragments -// out of the sentinel's message ("already assigned to", "claimed by"). That -// substring classification is what a client adopting this endpoint gets to -// delete, and it can only delete it if the server never does it either. -func claimRefusal(ctx context.Context, uc domain.IssueUseCase, id string, err error) error { - if !errors.Is(err, storage.ErrAlreadyClaimed) && !errors.Is(err, storage.ErrNotClaimable) { - return err - } - issue, readErr := uc.GetIssue(ctx, id) - if readErr != nil || issue == nil { - // The refusal stands; it just cannot carry the extensions. Reporting - // the read's failure instead would replace a precise 409 with a 500. - return err - } - return &claimConflict{assignee: issue.Assignee, status: string(issue.Status), err: err} -} - // failClaim answers a failed claim, adding the extension members a typed 409 // carries. +// +// The extensions come from issueops.ClaimConflictError, which the role fills +// from a query inside the transaction that lost the CAS — never from parsing +// fragments out of the sentinel's message ("already assigned to", "claimed +// by"). That substring classification is what a client adopting this endpoint +// gets to delete, and it can only delete it if the server never does it either. func (s *Server) failClaim(w http.ResponseWriter, r *http.Request, err error) { - var conflict *claimConflict + var conflict *issueops.ClaimConflictError if !errors.As(err, &conflict) { s.failErr(w, r, err) return @@ -422,11 +325,11 @@ func (s *Server) failClaim(w http.ResponseWriter, r *http.Request, err error) { // `assignee` is documented with already_claimed only: an issue refused for // its STATUS may well carry a stale assignee, and publishing it there would // tell a client someone holds work they do not. - if res.Problem.Code == string(CodeAlreadyClaimed) && conflict.assignee != "" { - res = res.WithAssignee(conflict.assignee) + if res.Problem.Code == string(CodeAlreadyClaimed) && conflict.Assignee != "" { + res = res.WithAssignee(conflict.Assignee) } - if conflict.status != "" { - res = res.WithIssueStatus(conflict.status) + if conflict.Status != "" { + res = res.WithIssueStatus(string(conflict.Status)) } s.fail(w, r, res) } @@ -443,14 +346,17 @@ type timedProvider struct { rec *reqInfo } -// timedProvider carries the capability accessor, so a read handler asks the +// timedProvider carries the capability accessors, so a handler asks the // provider it holds for the role — the same two-step a CLI command performs on // a store — instead of reaching past it to a constructor. -var _ uow.IssueReaderSource = timedProvider{} +var ( + _ uow.IssueReaderSource = timedProvider{} + _ uow.IssueClaimerSource = timedProvider{} +) // IssueReader builds the reader OVER THIS WRAPPER rather than delegating to the -// wrapped provider's own accessor, and that is the one place in this slice -// where a constructor is the right call: the whole purpose of the wrapper is +// wrapped provider's own accessor, and this and IssueClaimer below are the two +// places where a constructor is the right call: the whole purpose of the wrapper is // that every unit of work the reader opens goes through NewUOW below and lands // in this request's uow_ms. `p.inner.IssueReader()` would return a reader // bound to the untimed provider and the measurement would silently read zero. @@ -472,6 +378,15 @@ func (p timedProvider) IssueReader() (issueops.Reader, error) { return uow.NewIssueReader(p) } +// IssueClaimer builds the claimer OVER THIS WRAPPER, for the same reason and +// with the same hazard as IssueReader above: the role's units of work must go +// through NewUOW below or the one write on this surface reports uow_ms=0.000. +// TestAClaimTimesTheUnitsOfWorkItsClaimerOpens is the assertion that fails +// instead of the recursion looking correct. +func (p timedProvider) IssueClaimer() (issueops.Claimer, error) { + return uow.NewIssueClaimer(p) +} + func (p timedProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) { start := time.Now() uw, err := p.inner.NewUOW(ctx) diff --git a/internal/httpapi/claim_test.go b/internal/httpapi/claim_test.go index a62bd3604..ead9aef8a 100644 --- a/internal/httpapi/claim_test.go +++ b/internal/httpapi/claim_test.go @@ -41,6 +41,9 @@ type fakeIssues struct { claims []claimCall // claim answers the CAS. Default: the caller wins it. claim func(id, actor string) (domain.ClaimResult, error) + // wispCAS records every CAS attempt against the WISP plane. It must stay + // empty: v0 claims issues only. + wispCAS []claimCall // issue is what the same-transaction read returns; get overrides it. issue *types.Issue get func(id string) (*types.Issue, error) @@ -65,12 +68,25 @@ func (f *fakeIssues) GetIssue(_ context.Context, id string) (*types.Issue, error return f.issue, nil } +func (f *fakeIssues) ClaimWisp(_ context.Context, id, actor string) (domain.ClaimResult, error) { + f.mu.Lock() + f.wispCAS = append(f.wispCAS, claimCall{id, actor}) + f.mu.Unlock() + return domain.ClaimResult{}, nil +} + func (f *fakeIssues) claimed() []claimCall { f.mu.Lock() defer f.mu.Unlock() return slices.Clone(f.claims) } +func (f *fakeIssues) wispClaims() []claimCall { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.wispCAS) +} + func seededIssue(id, assignee string, status types.Status) *types.Issue { return &types.Issue{ ID: id, @@ -158,8 +174,8 @@ func TestClaimWritesOnceAndAnswersWithTheRowItWrote(t *testing.T) { if len(uows) != 1 { t.Fatalf("opened %d units of work, want 1", len(uows)) } - if got := uows[0].commitMessages(); len(got) != 1 || got[0] != "bd serve: claim bd-1 by alice" { - t.Errorf("commit messages = %q, want exactly [bd serve: claim bd-1 by alice]", got) + if got := uows[0].commitMessages(); len(got) != 1 || got[0] != "bd: claim bd-1 by alice" { + t.Errorf("commit messages = %q, want exactly [bd: claim bd-1 by alice]", got) } // The observability floor holds for the write too: a claim that waited on @@ -471,7 +487,7 @@ func TestClaimTrimsTheActor(t *testing.T) { t.Errorf("CAS actor = %v, want the trimmed value", got) } uows := provider.openedUOWs() - if got := uows[0].commitMessages(); len(got) != 1 || got[0] != "bd serve: claim bd-1 by alice" { + if got := uows[0].commitMessages(); len(got) != 1 || got[0] != "bd: claim bd-1 by alice" { t.Errorf("commit messages = %q, want the trimmed actor", got) } } @@ -696,6 +712,59 @@ func TestClaimTakesADatabaseSlot(t *testing.T) { t.Fatalf("no %s row in the route table", OpClaimIssue) } +// TestClaimNeverReachesTheWispPlane pins as a test what was prose until the +// claim became a role: this surface addresses the issues table only, so a wisp +// id names no row it can see and answers 404 rather than claiming the wisp. The +// fake's ClaimWisp records rather than panicking, so the assertion is "it was +// never called" instead of "the test crashed". +func TestClaimNeverReachesTheWispPlane(t *testing.T) { + issues := &fakeIssues{claim: func(string, string) (domain.ClaimResult, error) { + // What the issues-plane CAS reports for an id whose row lives in the + // wisp tables: the pre-image read finds nothing. + return domain.ClaimResult{}, fmt.Errorf("db: Claim bd-w1: read old issue: %w", sql.ErrNoRows) + }} + ts, _ := newClaimServer(t, issues) + + resp := ts.claim(t, "/v0/beads/issues/bd-w1:claim", `{"actor":"alice"}`) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp)) + } + if body := decodeBody(t, resp); body["code"] != string(CodeNotFound) { + t.Errorf("code = %v, want %s", body["code"], CodeNotFound) + } + if got := issues.wispClaims(); len(got) != 0 { + t.Errorf("the claim fell back to the wisp plane: %v", got) + } +} + +// TestAClaimTimesTheUnitsOfWorkItsClaimerOpens is the write-side twin of +// TestAReadRouteTimesTheUnitsOfWorkItsReaderOpens, and it exists for the same +// tempting edit: `p.inner.IssueClaimer()` — "add the layer by recursion, like +// every other decorator". This decorator's layer is on NewUOW, which only a +// claimer holding THIS wrapper can reach, so recursion hands back a claimer +// bound to the untimed provider. It compiles, and the one write on this +// surface reports uow_ms=0.000 forever. +func TestAClaimTimesTheUnitsOfWorkItsClaimerOpens(t *testing.T) { + issues := &fakeIssues{issue: seededIssue("bd-1", "alice", types.StatusInProgress)} + provider := &fakeProvider{issues: issues, delay: 5 * time.Millisecond} + ts := newTestServer(t, Config{Provider: provider}) + + if resp := ts.claim(t, claimPath, `{"actor":"alice"}`); resp.StatusCode != http.StatusOK { + t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp)) + } + if n := len(provider.openedUOWs()); n != 1 { + t.Fatalf("opened %d units of work, want 1", n) + } + + line := findLogLine(t, ts.stderr.String(), "op="+OpClaimIssue) + if !strings.Contains(line, "uow_ms=") { + t.Fatalf("claim request line has no uow_ms field:\n%s", line) + } + if strings.Contains(line, "uow_ms=0.000") { + t.Errorf("claim request line reports no unit-of-work time though the provider took 5ms; the claimer is bound to the untimed provider:\n%s", line) + } +} + func jsonBody(t *testing.T, v any) string { t.Helper() b, err := json.Marshal(v) diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 62bfe1381..6b661658a 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -364,6 +364,19 @@ func (s *Server) reader(r *http.Request) (issueops.Reader, error) { return src.IssueReader() } +// claimer returns the guarded atomic-claim surface for one request, obtained +// from the provider's own capability accessor. +// +// It is the write-side twin of reader above, for all the same reasons: built +// per request so its units of work are timed into THIS request's log line, and +// held by INTERFACE so uow.IssueClaimerSource is load-bearing rather than +// decorative. Config keeps holding a provider rather than a role — a claimer +// on Config could not be bound to the request's own timing wrapper. +func (s *Server) claimer(r *http.Request) (issueops.Claimer, error) { + var src uow.IssueClaimerSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())} + return src.IssueClaimer() +} + // 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 diff --git a/internal/jira/tracker_test.go b/internal/jira/tracker_test.go index 0b490befe..77d7e1ae6 100644 --- a/internal/jira/tracker_test.go +++ b/internal/jira/tracker_test.go @@ -636,6 +636,9 @@ func (s *configStore) IssueLifecycle() (issueops.Lifecycle, error) { func (s *configStore) IssueReader() (issueops.Reader, error) { return nil, &storage.ErrUnsupported{Op: "IssueReader", Backend: "jira-config-stub"} } +func (s *configStore) IssueClaimer() (issueops.Claimer, error) { + return nil, &storage.ErrUnsupported{Op: "IssueClaimer", 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) { diff --git a/internal/storage/dolt/issue_claimer.go b/internal/storage/dolt/issue_claimer.go new file mode 100644 index 000000000..ea0d32b3e --- /dev/null +++ b/internal/storage/dolt/issue_claimer.go @@ -0,0 +1,48 @@ +package dolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// IssueClaimer returns the guarded atomic-claim surface for this store. +func (s *DoltStore) IssueClaimer() (issueops.Claimer, error) { + return NewIssueClaimer(s) +} + +// NewIssueClaimer returns the guarded atomic claim backed by store. +func NewIssueClaimer(store *DoltStore) (issueops.Claimer, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueClaimer", Backend: "nil"} + } + return &issueClaimer{store: store}, nil +} + +type issueClaimer struct{ store *DoltStore } + +// Claim runs the compare-and-set under claim-family verify-after-write +// (bd-zccb9): under a degraded server the write's exit status is not truth in +// either direction, and a phantom claim is a duplicated implementation. Replay +// is safe because the CAS is re-checked inside the replayed transaction. +func (c *issueClaimer) Claim(ctx context.Context, request issueops.ClaimRequest) (issueops.ClaimResult, error) { + var result issueops.ClaimResult + write := func() error { + return c.store.runIssueOperationTx(ctx, storageissueops.ClaimCommitMessage(request.IssueID, request.Actor), + func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteClaim(ctx, tx, request) + return tables, err + }) + } + if err := c.store.verifiedClaimWrite(ctx, request.IssueID, claimedBy(request.Actor), write); err != nil { + return issueops.ClaimResult{}, err + } + return result, nil +} + +var _ issueops.Claimer = (*issueClaimer)(nil) diff --git a/internal/storage/embeddeddolt/issue_claimer.go b/internal/storage/embeddeddolt/issue_claimer.go new file mode 100644 index 000000000..e65ad68d2 --- /dev/null +++ b/internal/storage/embeddeddolt/issue_claimer.go @@ -0,0 +1,44 @@ +//go:build cgo + +package embeddeddolt + +import ( + "context" + "database/sql" + + "github.com/steveyegge/beads/internal/storage" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/issueops" +) + +// IssueClaimer returns the guarded atomic-claim surface for this store. +func (s *EmbeddedDoltStore) IssueClaimer() (issueops.Claimer, error) { + return NewIssueClaimer(s) +} + +// NewIssueClaimer returns the guarded atomic claim backed by store. +func NewIssueClaimer(store *EmbeddedDoltStore) (issueops.Claimer, error) { + if store == nil { + return nil, &storage.ErrUnsupported{Op: "NewIssueClaimer", Backend: "nil"} + } + return &issueClaimer{store: store}, nil +} + +type issueClaimer struct{ store *EmbeddedDoltStore } + +func (c *issueClaimer) Claim(ctx context.Context, request issueops.ClaimRequest) (issueops.ClaimResult, error) { + var result issueops.ClaimResult + err := c.store.runIssueOperationTx(ctx, storageissueops.ClaimCommitMessage(request.IssueID, request.Actor), + func(tx *sql.Tx) (storageissueops.ChangedTables, error) { + var err error + var tables storageissueops.ChangedTables + result, tables, err = storageissueops.ExecuteClaim(ctx, tx, request) + return tables, err + }) + if err != nil { + return issueops.ClaimResult{}, err + } + return result, nil +} + +var _ issueops.Claimer = (*issueClaimer)(nil) diff --git a/internal/storage/hook_issue_claimer.go b/internal/storage/hook_issue_claimer.go new file mode 100644 index 000000000..2e29cc36f --- /dev/null +++ b/internal/storage/hook_issue_claimer.go @@ -0,0 +1,38 @@ +package storage + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// IssueClaimer returns the inner store's claimer with this decorator's +// completion hooks layered over it. +// +// It recurses for the same reason IssueLifecycle does: a claim is a write, and +// a blind delegation would hand back the inner store's claimer unchanged and +// silently drop the hook every landed claim owes. +func (h *HookFiringStore) IssueClaimer() (issueops.Claimer, error) { + inner, err := h.inner.IssueClaimer() + if err != nil { + return nil, err + } + return &hookIssueClaimer{inner: inner, hooks: h}, nil +} + +type hookIssueClaimer struct { + inner issueops.Claimer + hooks issueOperationHooks +} + +// Claim fires the update hook for a claim that persisted a mutation, and +// suppresses it for the idempotent re-claim — the same no-op suppression +// Reopen applies. Without it an agent polling its own claim would run the +// user's hook script once per poll for a write that never happened. +func (c *hookIssueClaimer) Claim(ctx context.Context, request issueops.ClaimRequest) (issueops.ClaimResult, error) { + result, err := c.inner.Claim(ctx, request) + if err == nil && result.Changed { + c.hooks.CompleteIssueOperationUpdate(result.Issue) + } + return result, err +} diff --git a/internal/storage/hook_issue_claimer_test.go b/internal/storage/hook_issue_claimer_test.go new file mode 100644 index 000000000..7cd485a23 --- /dev/null +++ b/internal/storage/hook_issue_claimer_test.go @@ -0,0 +1,108 @@ +package storage + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" +) + +// fakeIssueClaimer records every call and answers with whatever the test set. +type fakeIssueClaimer struct { + calls int + changed bool + err error +} + +func (f *fakeIssueClaimer) Claim(context.Context, issueops.ClaimRequest) (issueops.ClaimResult, error) { + f.calls++ + return issueops.ClaimResult{Issue: &types.Issue{ID: "bd-1"}, Changed: f.changed}, f.err +} + +// claimerStore is a DoltStorage whose only real method is IssueClaimer. +type claimerStore struct { + DoltStorage + claimer issueops.Claimer + err error +} + +func (s claimerStore) IssueClaimer() (issueops.Claimer, error) { return s.claimer, s.err } + +// TestHookFiringStoreIssueClaimerLayersHooksOverInner pins the recursion. A +// claim is a write, so this accessor answers the way IssueLifecycle does and +// not the way IssueReader does: delegating to the inner store would compile, +// satisfy Storage, and silently stop firing the hook every claim owes. +func TestHookFiringStoreIssueClaimerLayersHooksOverInner(t *testing.T) { + inner := &fakeIssueClaimer{} + store := &HookFiringStore{inner: claimerStore{claimer: inner}} + + claimer, err := store.IssueClaimer() + if err != nil { + t.Fatalf("IssueClaimer() error = %v", err) + } + hooked, ok := claimer.(*hookIssueClaimer) + if !ok { + t.Fatalf("IssueClaimer() = %T, want *hookIssueClaimer", claimer) + } + if hooked.inner != issueops.Claimer(inner) { + t.Fatalf("hook layer wraps %#v, want the inner store's claimer", hooked.inner) + } + if hooked.hooks != issueOperationHooks(store) { + t.Fatalf("hook layer fires into %#v, want the decorator itself", hooked.hooks) + } +} + +func TestHookFiringStoreIssueClaimerPropagatesInnerError(t *testing.T) { + want := errors.New("inner refused") + store := &HookFiringStore{inner: claimerStore{err: want}} + + claimer, err := store.IssueClaimer() + if !errors.Is(err, want) { + t.Fatalf("IssueClaimer() error = %v, want %v", err, want) + } + if claimer != nil { + t.Fatalf("IssueClaimer() = %T, want nil", claimer) + } +} + +// TestHookIssueClaimerFiresOnlyOnAPersistedClaim: the idempotent re-claim wrote +// nothing, so it must not fire an update hook — the same no-op suppression +// Reopen already applies, and the reason it matters here is that a polling +// agent re-claiming its own issue would otherwise run the user's hook script +// once per poll. +func TestHookIssueClaimerFiresOnlyOnAPersistedClaim(t *testing.T) { + for _, tc := range []struct { + name string + changed bool + err error + want []string + }{ + {name: "claim landed", changed: true, want: []string{"update"}}, + {name: "idempotent re-claim", changed: false}, + {name: "refused", changed: true, err: errors.New("refused")}, + } { + t.Run(tc.name, func(t *testing.T) { + inner := &fakeIssueClaimer{changed: tc.changed, err: tc.err} + recorder := &recordingIssueOperationHooks{} + claimer := &hookIssueClaimer{inner: inner, hooks: recorder} + + _, err := claimer.Claim(context.Background(), issueops.ClaimRequest{Actor: "alice", IssueID: "bd-1"}) + if !errors.Is(err, tc.err) { + t.Fatalf("Claim() error = %v, want %v", err, tc.err) + } + if inner.calls != 1 { + t.Errorf("inner claimer called %d times, want 1", inner.calls) + } + if len(recorder.completions) != len(tc.want) { + t.Fatalf("hooks fired = %v, want %v", recorder.completions, tc.want) + } + for i, want := range tc.want { + if recorder.completions[i] != want { + t.Errorf("hook %d = %q, want %q", i, recorder.completions[i], want) + } + } + }) + } +} diff --git a/internal/storage/issueops/claim.go b/internal/storage/issueops/claim.go index 29e328bfc..3d4dd71e5 100644 --- a/internal/storage/issueops/claim.go +++ b/internal/storage/issueops/claim.go @@ -120,18 +120,10 @@ func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*Cla } if rowsAffected == 0 { - // Query current state inside the same transaction for consistency. - var currentAssignee sql.NullString - var currentStatus types.Status - err := tx.QueryRowContext(ctx, fmt.Sprintf( - `SELECT assignee, status FROM %s WHERE id = ?`, issueTable), id).Scan(¤tAssignee, ¤tStatus) + assignee, currentStatus, err := readClaimStateInTx(ctx, tx, issueTable, id) if err != nil { return nil, fmt.Errorf("failed to get current claim state: %w", err) } - assignee := "" - if currentAssignee.Valid { - assignee = currentAssignee.String - } // Idempotent: if already claimed in_progress by the same actor, treat as success. // This supports agent retry workflows where claim may be called multiple // times after transient failures (GH#8). @@ -190,6 +182,22 @@ func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*Cla return &ClaimResult{OldIssue: oldIssue, IsWisp: isWisp}, nil } +// readClaimStateInTx reads one row's coordination columns inside tx — the +// state a lost compare-and-set reports. Shared by the CAS itself and by the +// public claim role, so the two cannot disagree about what "the state that +// refused this claim" means. +// +//nolint:gosec // G201: issueTable comes from WispTableRouting (hardcoded constants) +func readClaimStateInTx(ctx context.Context, tx DBTX, issueTable, id string) (string, types.Status, error) { + var assignee sql.NullString + var status types.Status + if err := tx.QueryRowContext(ctx, fmt.Sprintf( + `SELECT assignee, status FROM %s WHERE id = ?`, issueTable), id).Scan(&assignee, &status); err != nil { + return "", "", err + } + return assignee.String, status, nil +} + // ClaimReadyIssueInTx claims the first currently ready issue matching filter in // the same transaction that computes readiness. It returns nil when no matching // ready issue can be claimed. diff --git a/internal/storage/issueops/public_claim.go b/internal/storage/issueops/public_claim.go new file mode 100644 index 000000000..3b19eaeab --- /dev/null +++ b/internal/storage/issueops/public_claim.go @@ -0,0 +1,81 @@ +package issueops + +import ( + "context" + "database/sql" + "errors" + "fmt" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// ClaimCommitMessage names the claimed issue and its claimant in the storage +// commit. It lives here so every implementation of the claim role spells it +// identically and `bd dolt log` reads the same on all of them. The actor is in +// it because that line IS the audit trail — which is why every surface +// reaching the role validates the actor before calling it. +func ClaimCommitMessage(issueID, actor string) string { + return fmt.Sprintf("bd: claim %s by %s", issueID, actor) +} + +// ExecuteClaim applies a guarded claim in tx and reports durable tables changed. +func ExecuteClaim(ctx context.Context, tx *sql.Tx, request publicops.ClaimRequest) (publicops.ClaimResult, ChangedTables, error) { + if request.Actor == "" || request.IssueID == "" { + return publicops.ClaimResult{}, nil, fmt.Errorf("%w: claim requires actor and issue ID", storage.ErrValidation) + } + // ClaimIssueInTx routes a wisp id to the wisp tables and claims it there. + // The role deliberately does not: the wisp plane is not claimable through + // it, and the refusal lands here — before the pre-image read, and before + // any write the enclosing transaction would have to roll back. + if IsActiveWispInTx(ctx, tx, request.IssueID) { + return publicops.ClaimResult{}, nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, request.IssueID) + } + claimed, err := ClaimIssueInTx(ctx, tx, request.IssueID, request.Actor) + if err != nil { + return publicops.ClaimResult{}, nil, classifyClaimRefusalInTx(ctx, tx, request.IssueID, err) + } + // The CAS matches no row when the actor already holds the issue in + // progress, and ClaimIssueInTx reports that as success. The pre-image is + // what tells the two apart, and staging nothing for the idempotent case is + // what keeps a polling caller from minting empty version-control commits. + tables := ChangedTables{} + changed := claimed.OldIssue.Status != types.StatusInProgress || claimed.OldIssue.Assignee != request.Actor + if changed { + issueTable, _, eventTable, _ := WispTableRouting(claimed.IsWisp) + tables.Add(issueTable, eventTable) + } + issue, err := GetIssueInTx(ctx, tx, request.IssueID) + if err != nil { + return publicops.ClaimResult{}, nil, err + } + // The relations are dropped deliberately, and this is the one place in the + // facade family where that is true. GetIssueInTx hydrates labels on its + // way past; the snapshot this role promises is the BARE post-state row, + // because that is what the frozen v0 claim response carries and what + // `bd update --claim --json` prints beside it — verified against a labeled + // issue, which neither surface reports labels for. Hydrating here would + // change an already-published body. + issue.Labels = nil + issue.Dependencies = nil + issue.Comments = nil + return publicops.ClaimResult{Issue: issue, Changed: changed}, tables, nil +} + +// classifyClaimRefusalInTx attaches the state that lost a compare-and-set to a +// claim refusal, reading it inside the same transaction that lost it. Anything +// that is not a refusal passes through untouched, and so does a refusal whose +// state could not be re-read: the refusal itself is never downgraded to the +// read's failure. The table is the durable one because ExecuteClaim has +// already refused every wisp id by the time a refusal can reach here. +func classifyClaimRefusalInTx(ctx context.Context, tx DBTX, id string, err error) error { + if !errors.Is(err, storage.ErrAlreadyClaimed) && !errors.Is(err, storage.ErrNotClaimable) { + return err + } + assignee, status, readErr := readClaimStateInTx(ctx, tx, "issues", id) + if readErr != nil { + return err + } + return &publicops.ClaimConflictError{IssueID: id, Assignee: assignee, Status: status, Err: err} +} diff --git a/internal/storage/issueops/public_claim_test.go b/internal/storage/issueops/public_claim_test.go new file mode 100644 index 000000000..828ce95a5 --- /dev/null +++ b/internal/storage/issueops/public_claim_test.go @@ -0,0 +1,262 @@ +package issueops + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "regexp" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/sqlbuild" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +const claimActor = "alice" + +// claimIssueRow builds one mocked issues row carrying the coordination fields +// the claim CAS reads back. +func claimIssueRow(id, assignee string, status types.Status) *sqlmock.Rows { + values := make([]driver.Value, 0, len(issueColumns())) + for _, col := range issueColumns() { + switch col { + case "id": + values = append(values, id) + case "title": + values = append(values, "claim me") + case "description", "design", "acceptance_criteria", "notes": + values = append(values, "") + case "status": + values = append(values, string(status)) + case "assignee": + values = append(values, assignee) + case "priority": + values = append(values, 1) + case "issue_type": + values = append(values, string(types.TypeTask)) + case "compaction_level": + values = append(values, 0) + default: + values = append(values, nil) + } + } + return issueRows().AddRow(values...) +} + +// expectClaimableRead mocks everything ClaimIssueInTx reads before its +// conditional UPDATE: the wisp routing probe, the pre-image, and the two +// config lookups that widen the CAS predicate. +func expectClaimableRead(mock sqlmock.Sqlmock, id, assignee string, status types.Status) { + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnError(sql.ErrNoRows) + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(claimIssueRow(id, assignee, status)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + // One row is enough to make custom-status resolution authoritative, so it + // never falls through to the legacy config string. + mock.ExpectQuery(regexp.QuoteMeta("SELECT name, category FROM custom_statuses ORDER BY name")). + WillReturnRows(sqlmock.NewRows([]string{"name", "category"}).AddRow("archived", string(types.CategoryDone))) + mock.ExpectQuery(regexp.QuoteMeta("SELECT value FROM config WHERE `key` = ?")). + WithArgs("claim.pools"). + WillReturnError(sql.ErrNoRows) +} + +// expectClaimStateRead mocks the same-transaction read of the coordination +// columns — the one ClaimIssueInTx makes when the CAS matches no row. +func expectClaimStateRead(mock sqlmock.Sqlmock, id, assignee string, status types.Status) { + mock.ExpectQuery(regexp.QuoteMeta("SELECT assignee, status FROM issues WHERE id = ?")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"assignee", "status"}).AddRow(assignee, string(status))) +} + +// TestExecuteClaimRefusesWispIDsBeforeAnyWork pins the deliberate inversion of +// ClaimIssueInTx, which routes a wisp id to the wisp tables and claims it. The +// role does not: the wisp plane is not claimable through it, and the refusal +// lands on the routing probe, before a pre-image is even read. +func TestExecuteClaimRefusesWispIDsBeforeAnyWork(t *testing.T) { + _, mock, tx := beginMockTx(t) + + const id = "bd-wisp" + mock.ExpectQuery(regexp.QuoteMeta("SELECT 1 FROM wisps WHERE id = ? LIMIT 1")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"1"}).AddRow(1)) + + result, tables, err := ExecuteClaim(context.Background(), tx, publicops.ClaimRequest{Actor: claimActor, IssueID: id}) + if !errors.Is(err, storage.ErrNotFound) { + t.Fatalf("err = %v, want ErrNotFound for a wisp id", err) + } + if result.Issue != nil || result.Changed || len(tables) != 0 { + t.Errorf("a refused wisp claim reported result %+v and tables %v", result, tables) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("a wisp id reached further than the routing probe: %v", err) + } +} + +// TestExecuteClaimReportsTheStateThatLostTheCAS: the refusal keeps its sentinel +// and its exact prose, and gains the assignee and status read inside the same +// transaction — so a caller classifies the conflict from typed fields instead +// of matching substrings in the message. +func TestExecuteClaimReportsTheStateThatLostTheCAS(t *testing.T) { + for _, tc := range []struct { + name string + assignee string + status types.Status + sentinel error + // wantAssignee is what the conflict must publish. A status refusal + // still carries the holder it read; only the wire decides whether to + // publish it. + wantAssignee string + }{ + { + name: "held by another actor", assignee: "bob", status: types.StatusOpen, + sentinel: storage.ErrAlreadyClaimed, wantAssignee: "bob", + }, + { + name: "not in a claimable state", assignee: "", status: types.StatusClosed, + sentinel: storage.ErrNotClaimable, + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, mock, tx := beginMockTx(t) + + const id = "bd-1" + expectClaimableRead(mock, id, tc.assignee, tc.status) + mock.ExpectExec(`(?s)UPDATE issues\s+SET assignee`).WillReturnResult(sqlmock.NewResult(0, 0)) + expectClaimStateRead(mock, id, tc.assignee, tc.status) + // The role's own re-read, which is what carries the state out. + expectClaimStateRead(mock, id, tc.assignee, tc.status) + + _, tables, err := ExecuteClaim(context.Background(), tx, publicops.ClaimRequest{Actor: claimActor, IssueID: id}) + if !errors.Is(err, tc.sentinel) { + t.Fatalf("err = %v, want it to match %v", err, tc.sentinel) + } + var conflict *publicops.ClaimConflictError + if !errors.As(err, &conflict) { + t.Fatalf("err = %v, want a *ClaimConflictError carrying the losing state", err) + } + if conflict.IssueID != id || conflict.Assignee != tc.wantAssignee || conflict.Status != tc.status { + t.Errorf("conflict = %#v, want assignee %q status %q", conflict, tc.wantAssignee, tc.status) + } + if got := conflict.Error(); got != conflict.Err.Error() { + t.Errorf("Error() = %q, want the refusal unedited (%q)", got, conflict.Err.Error()) + } + if len(tables) != 0 { + t.Errorf("a refused claim staged %v", tables) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } + }) + } +} + +// TestExecuteClaimIdempotentReclaimStagesNothing: the holder re-claiming its +// own in-progress issue is a success that wrote nothing, so it must stage no +// table — an empty set is what tells the store to skip the version-control +// commit, and a polling client must not be able to mint empty ones. +func TestExecuteClaimIdempotentReclaimStagesNothing(t *testing.T) { + _, mock, tx := beginMockTx(t) + + const id = "bd-1" + expectClaimableRead(mock, id, claimActor, types.StatusInProgress) + mock.ExpectExec(`(?s)UPDATE issues\s+SET assignee`).WillReturnResult(sqlmock.NewResult(0, 0)) + expectClaimStateRead(mock, id, claimActor, types.StatusInProgress) + // The post-state snapshot the result carries. + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(claimIssueRow(id, claimActor, types.StatusInProgress)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + + result, tables, err := ExecuteClaim(context.Background(), tx, publicops.ClaimRequest{Actor: claimActor, IssueID: id}) + if err != nil { + t.Fatalf("ExecuteClaim: %v", err) + } + if result.Changed { + t.Error("a re-claim by the holder reported a persisted mutation") + } + if len(tables) != 0 { + t.Errorf("a re-claim by the holder staged %v; nothing changed, so nothing may be committed", tables) + } + if result.Issue == nil || result.Issue.Assignee != claimActor || result.Issue.Status != types.StatusInProgress { + t.Errorf("result issue = %+v, want the post-state row", result.Issue) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +// TestExecuteClaimStagesTheRowAndEventItWrote: a claim that wins the CAS is a +// history-worthy mutation, so it stages the issues and events tables — the +// lease grant rides the ephemeral table and is deliberately not staged. +func TestExecuteClaimStagesTheRowAndEventItWrote(t *testing.T) { + _, mock, tx := beginMockTx(t) + + const id = "bd-1" + expectClaimableRead(mock, id, "", types.StatusOpen) + mock.ExpectExec(`(?s)UPDATE issues\s+SET assignee`).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`(?s)INSERT INTO leases`).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(`(?s)SELECT id FROM events`).WillReturnRows(sqlmock.NewRows([]string{"id"})) + mock.ExpectExec(`(?s)INSERT INTO events`).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT " + IssueSelectColumns + " FROM issues " + sqlbuild.LeaseJoin("issues") + " WHERE id = ?")). + WithArgs(id). + WillReturnRows(claimIssueRow(id, claimActor, types.StatusInProgress)) + mock.ExpectQuery(regexp.QuoteMeta("SELECT label FROM labels WHERE issue_id = ? ORDER BY label")). + WithArgs(id). + WillReturnRows(sqlmock.NewRows([]string{"label"})) + + result, tables, err := ExecuteClaim(context.Background(), tx, publicops.ClaimRequest{Actor: claimActor, IssueID: id}) + if err != nil { + t.Fatalf("ExecuteClaim: %v", err) + } + if !result.Changed { + t.Error("a won CAS reported no persisted mutation") + } + if !tables["issues"] || !tables["events"] { + t.Errorf("staged %v, want the issues row and the claim event", tables) + } + if tables["leases"] { + t.Error("the ephemeral lease grant was staged for the version-control commit") + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet SQL expectations: %v", err) + } +} + +// TestExecuteClaimRefusesIncompleteRequestsBeforeAnySQL: a request missing an +// actor or an id is a deterministic validation failure, and it must not cost a +// round trip to discover. +func TestExecuteClaimRefusesIncompleteRequestsBeforeAnySQL(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.ClaimRequest + }{ + {"no actor", publicops.ClaimRequest{IssueID: "bd-1"}}, + {"no issue", publicops.ClaimRequest{Actor: claimActor}}, + } { + t.Run(tc.name, func(t *testing.T) { + _, mock, tx := beginMockTx(t) + + _, tables, err := ExecuteClaim(context.Background(), tx, tc.request) + if !errors.Is(err, storage.ErrValidation) { + t.Fatalf("err = %v, want ErrValidation", err) + } + if len(tables) != 0 { + t.Errorf("a refused request staged %v", tables) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("an invalid request reached the database: %v", err) + } + }) + } +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go index 8eaa2dd4c..bd9a551f2 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -100,6 +100,13 @@ type Storage interface { // reason about decorator-by-decorator is not a seam. IssueReader() (issueops.Reader, error) + // IssueClaimer returns the guarded atomic-claim surface for this store: + // its own role beside IssueLifecycle and IssueReader rather than a fifth + // verb on the lifecycle. Like the other two accessors, every decorator in + // a store's chain answers for itself and layers its own behavior onto the + // inner result. + IssueClaimer() (issueops.Claimer, error) + // Issue CRUD CreateIssue(ctx context.Context, issue *types.Issue, actor string) error CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error diff --git a/internal/storage/uow/issue_claimer.go b/internal/storage/uow/issue_claimer.go new file mode 100644 index 000000000..1375303e5 --- /dev/null +++ b/internal/storage/uow/issue_claimer.go @@ -0,0 +1,109 @@ +package uow + +import ( + "context" + "errors" + "fmt" + + "github.com/steveyegge/beads/internal/storage/dberrors" + "github.com/steveyegge/beads/internal/storage/domain" + storageissueops "github.com/steveyegge/beads/internal/storage/issueops" + publicops "github.com/steveyegge/beads/issueops" +) + +// IssueClaimerSource is the capability accessor a unit-of-work provider offers +// for the guarded atomic claim. It is named here for the same reason +// IssueReaderSource is: a consumer holding a provider by interface asks it for +// the role instead of reaching for a constructor, and a provider that cannot +// answer says so with an error rather than being wired around. +type IssueClaimerSource interface { + IssueClaimer() (publicops.Claimer, error) +} + +// issueClaimer runs the public claim through a unit of work. +type issueClaimer struct { + provider UnitOfWorkProvider +} + +// IssueClaimer returns the guarded atomic-claim surface for this provider. A +// unit of work is not a special case: callers reach the claim through the same +// accessor they use on a store. +func (p *doltSQLProvider) IssueClaimer() (publicops.Claimer, error) { + return NewIssueClaimer(p) +} + +// NewIssueClaimer constructs the public claim backed by provider. +func NewIssueClaimer(provider UnitOfWorkProvider) (publicops.Claimer, error) { + if isNilUnitOfWorkProvider(provider) { + return nil, fmt.Errorf("new issue claimer: unit-of-work provider must not be nil") + } + return &issueClaimer{provider: provider}, nil +} + +var _ publicops.Claimer = (*issueClaimer)(nil) + +// Claim runs the compare-and-set in a retried unit-of-work transaction. +// +// RETRY LIVES HERE, not in the caller. RunTxResult redoes the WHOLE attempt in +// a FRESH unit of work when one loses Dolt's commit-time merge, because +// re-committing a session the server already rolled back is a lost write. That +// is the same place every other verb on this seam keeps it, and it is what +// lets the role promise that a lost merge is retried rather than surfaced. +func (c *issueClaimer) Claim(ctx context.Context, request publicops.ClaimRequest) (publicops.ClaimResult, error) { + if request.Actor == "" || request.IssueID == "" { + return publicops.ClaimResult{}, validationError(fmt.Errorf("claim: actor and issue ID must not be empty")) + } + return RunTxResult(ctx, c.provider, func(ctx context.Context, uw UnitOfWork) (publicops.ClaimResult, string, error) { + uc := uw.IssueUseCase() + claimed, err := uc.ClaimIssue(ctx, request.IssueID, request.Actor) + if err != nil { + return publicops.ClaimResult{}, "", classifyClaimError(ctx, uc, request.IssueID, err) + } + // Read back INSIDE this transaction, so the result describes the row + // this CAS wrote and not a later writer's. + issue, err := uc.GetIssue(ctx, request.IssueID) + if err != nil { + return publicops.ClaimResult{}, "", err + } + if issue == nil { + // A miss with a nil error is the other shape a not-found takes at + // this seam; normalize it rather than dereferencing nil. + return publicops.ClaimResult{}, "", fmt.Errorf("%w: issue %s", publicops.ErrNotFound, request.IssueID) + } + if claimed.AlreadyClaimed { + // The idempotent re-claim: the CAS matched no row because there + // was nothing to change. An empty commit message tells + // RunTxResult to skip the commit, so a polling caller cannot mint + // an empty storage commit per call. + return publicops.ClaimResult{Issue: issue}, "", nil + } + return publicops.ClaimResult{Issue: issue, Changed: true}, storageissueops.ClaimCommitMessage(request.IssueID, request.Actor), nil + }) +} + +// classifyClaimError normalizes what a lost or impossible claim reports. +// +// A refusal gains the assignee and status read in THIS transaction, so a +// caller classifies the conflict from typed fields instead of matching +// substrings in the message; when that read fails the refusal stands +// unadorned, because reporting the read's failure would replace a precise +// conflict with an opaque one. A missing row arrives here as a wrapped +// sql.ErrNoRows and leaves as ErrNotFound, which is what the role promises and +// what its store-backed sibling already answers with — a wisp id takes exactly +// that route, since the CAS only ever addresses the issues table. +func classifyClaimError(ctx context.Context, uc domain.IssueUseCase, id string, err error) error { + switch { + case errors.Is(err, publicops.ErrAlreadyClaimed), errors.Is(err, publicops.ErrNotClaimable): + issue, readErr := uc.GetIssue(ctx, id) + if readErr != nil || issue == nil { + return err + } + return &publicops.ClaimConflictError{IssueID: id, Assignee: issue.Assignee, Status: issue.Status, Err: err} + case errors.Is(err, publicops.ErrNotFound): + return err + case dberrors.IsNoRows(err): + return fmt.Errorf("%w: issue %s", publicops.ErrNotFound, id) + default: + return err + } +} diff --git a/internal/storage/uow/issue_claimer_test.go b/internal/storage/uow/issue_claimer_test.go new file mode 100644 index 000000000..4d42ad1a5 --- /dev/null +++ b/internal/storage/uow/issue_claimer_test.go @@ -0,0 +1,231 @@ +package uow + +import ( + "context" + "database/sql" + "errors" + "fmt" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" + publicops "github.com/steveyegge/beads/issueops" +) + +// claimerIssues answers the two calls the claim makes: the CAS and the +// same-transaction read-back. Everything else panics rather than returning a +// zero value. +type claimerIssues struct { + domain.IssueUseCase + actors []string + result domain.ClaimResult + err error + issue *types.Issue + getErr error +} + +func (f *claimerIssues) ClaimIssue(_ context.Context, _, actor string) (domain.ClaimResult, error) { + f.actors = append(f.actors, actor) + return f.result, f.err +} + +func (f *claimerIssues) GetIssue(context.Context, string) (*types.Issue, error) { + return f.issue, f.getErr +} + +func newClaimer(t *testing.T, issues *claimerIssues) (publicops.Claimer, *mockUnitOfWork, *mockUnitOfWorkProvider) { + t.Helper() + uw := &mockUnitOfWork{issueUseCase: issues} + provider := &mockUnitOfWorkProvider{uows: []*mockUnitOfWork{uw}} + claimer, err := NewIssueClaimer(provider) + if err != nil { + t.Fatalf("NewIssueClaimer: %v", err) + } + return claimer, uw, provider +} + +// TestClaimerCommitsAWonCASForAnyActor is the happy path and the ruling that +// goes with it: eligibility is decided by the issue's state alone, so an actor +// with no prior relationship to the issue — a guest — wins the CAS like any +// other. The actor is caller-asserted provenance, not authenticated identity. +func TestClaimerCommitsAWonCASForAnyActor(t *testing.T) { + issues := &claimerIssues{issue: &types.Issue{ID: "bd-1", Assignee: "guest-42", Status: types.StatusInProgress}} + claimer, uw, provider := newClaimer(t, issues) + + result, err := claimer.Claim(context.Background(), publicops.ClaimRequest{Actor: "guest-42", IssueID: "bd-1"}) + if err != nil { + t.Fatalf("Claim: %v", err) + } + if !result.Changed { + t.Error("a won CAS reported no persisted mutation") + } + if result.Issue == nil || result.Issue.Assignee != "guest-42" { + t.Errorf("result issue = %+v, want the row the CAS wrote", result.Issue) + } + if len(issues.actors) != 1 || issues.actors[0] != "guest-42" { + t.Errorf("CAS actors = %v, want one attempt by guest-42", issues.actors) + } + if uw.commitCount != 1 { + t.Errorf("commits = %d, want exactly one", uw.commitCount) + } + if provider.newUOWCalls != 1 { + t.Errorf("opened %d units of work, want 1", provider.newUOWCalls) + } +} + +// TestClaimerIdempotentReclaimCommitsNothing: the holder re-claiming its own +// in-progress issue changed nothing, so nothing may be committed — a polling +// client must not be able to fill the storage history with empty commits. +func TestClaimerIdempotentReclaimCommitsNothing(t *testing.T) { + issues := &claimerIssues{ + result: domain.ClaimResult{AlreadyClaimed: true, PriorAssignee: "alice"}, + issue: &types.Issue{ID: "bd-1", Assignee: "alice", Status: types.StatusInProgress}, + } + claimer, uw, _ := newClaimer(t, issues) + + result, err := claimer.Claim(context.Background(), publicops.ClaimRequest{Actor: "alice", IssueID: "bd-1"}) + if err != nil { + t.Fatalf("Claim: %v", err) + } + if result.Changed { + t.Error("a re-claim by the holder reported a persisted mutation") + } + if uw.commitCount != 0 { + t.Errorf("a no-op re-claim committed %d times", uw.commitCount) + } +} + +// TestClaimerReportsTheStateThatLostTheCAS: the refusal keeps its sentinel and +// its prose and gains the state read inside the same transaction, so a caller +// classifies the conflict from typed fields rather than by matching substrings. +func TestClaimerReportsTheStateThatLostTheCAS(t *testing.T) { + for _, tc := range []struct { + name string + sentinel error + issue *types.Issue + }{ + { + name: "held by another actor", sentinel: storage.ErrAlreadyClaimed, + issue: &types.Issue{ID: "bd-1", Assignee: "bob", Status: types.StatusInProgress}, + }, + { + name: "not in a claimable state", sentinel: storage.ErrNotClaimable, + issue: &types.Issue{ID: "bd-1", Assignee: "bob", Status: types.StatusClosed}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + refusal := fmt.Errorf("claim bd-1: %w: refused", tc.sentinel) + issues := &claimerIssues{err: refusal, issue: tc.issue} + claimer, uw, _ := newClaimer(t, issues) + + _, err := claimer.Claim(context.Background(), publicops.ClaimRequest{Actor: "alice", IssueID: "bd-1"}) + if !errors.Is(err, tc.sentinel) { + t.Fatalf("err = %v, want it to match %v", err, tc.sentinel) + } + var conflict *publicops.ClaimConflictError + if !errors.As(err, &conflict) { + t.Fatalf("err = %v, want a *ClaimConflictError", err) + } + if conflict.IssueID != "bd-1" || conflict.Assignee != tc.issue.Assignee || conflict.Status != tc.issue.Status { + t.Errorf("conflict = %#v, want the state the transaction read", conflict) + } + if got := conflict.Error(); got != refusal.Error() { + t.Errorf("Error() = %q, want the refusal unedited (%q)", got, refusal.Error()) + } + if uw.commitCount != 0 { + t.Errorf("a refused claim committed %d times", uw.commitCount) + } + }) + } +} + +// TestClaimerRefusalSurvivesAnUnreadableRow: the state is a courtesy, the +// refusal is not. A failed re-read must leave the refusal exactly as it was +// rather than replacing a precise conflict with the read's error. +// +// The fake hands back a row AND an error, which is the case a nil-check alone +// gets wrong: publishing that row would publish state the transaction never +// successfully read. +func TestClaimerRefusalSurvivesAnUnreadableRow(t *testing.T) { + refusal := fmt.Errorf("claim bd-1: %w", storage.ErrAlreadyClaimed) + issues := &claimerIssues{ + err: refusal, + issue: &types.Issue{ID: "bd-1", Assignee: "bob", Status: types.StatusInProgress}, + getErr: errors.New("read failed"), + } + claimer, _, _ := newClaimer(t, issues) + + _, err := claimer.Claim(context.Background(), publicops.ClaimRequest{Actor: "alice", IssueID: "bd-1"}) + if !errors.Is(err, storage.ErrAlreadyClaimed) { + t.Fatalf("err = %v, want the refusal to stand", err) + } + var conflict *publicops.ClaimConflictError + if errors.As(err, &conflict) { + t.Errorf("err = %#v, want the bare refusal when the state could not be read", conflict) + } +} + +// TestClaimerNormalizesAMissingRow: the CAS reports a miss as a wrapped +// sql.ErrNoRows, but the role promises ErrNotFound — and its store-backed +// sibling answers with exactly that, so a caller must not have to know which +// implementation it holds. A wisp id arrives here the same way: the CAS only +// ever addresses the issues table. +func TestClaimerNormalizesAMissingRow(t *testing.T) { + for _, tc := range []struct { + name string + err error + }{ + {"wrapped ErrNoRows", fmt.Errorf("db: Claim bd-404: read old issue: %w", sql.ErrNoRows)}, + {"already normalized", fmt.Errorf("claim bd-404: %w", storage.ErrNotFound)}, + } { + t.Run(tc.name, func(t *testing.T) { + issues := &claimerIssues{err: tc.err} + claimer, _, _ := newClaimer(t, issues) + + _, err := claimer.Claim(context.Background(), publicops.ClaimRequest{Actor: "alice", IssueID: "bd-404"}) + if !errors.Is(err, publicops.ErrNotFound) { + t.Fatalf("err = %v, want it to match ErrNotFound", err) + } + }) + } +} + +// TestClaimerRefusesIncompleteRequestsBeforeOpeningAUOW: a request missing an +// actor or an id is a deterministic validation failure and must not cost a +// database connection to discover. +func TestClaimerRefusesIncompleteRequestsBeforeOpeningAUOW(t *testing.T) { + for _, tc := range []struct { + name string + request publicops.ClaimRequest + }{ + {"no actor", publicops.ClaimRequest{IssueID: "bd-1"}}, + {"no issue", publicops.ClaimRequest{Actor: "alice"}}, + } { + t.Run(tc.name, func(t *testing.T) { + provider := &mockUnitOfWorkProvider{newUOWErr: errors.New("unexpected unit-of-work open")} + claimer, err := NewIssueClaimer(provider) + if err != nil { + t.Fatalf("NewIssueClaimer: %v", err) + } + if _, err := claimer.Claim(context.Background(), tc.request); !errors.Is(err, publicops.ErrValidation) { + t.Fatalf("err = %v, want ErrValidation", err) + } + if provider.newUOWCalls != 0 { + t.Errorf("an invalid request opened %d units of work", provider.newUOWCalls) + } + }) + } +} + +// TestNewIssueClaimerRefusesANilProvider: a claimer over no provider would +// panic on first use, so the accessor says so instead. +func TestNewIssueClaimerRefusesANilProvider(t *testing.T) { + if _, err := NewIssueClaimer(nil); err == nil { + t.Fatal("NewIssueClaimer(nil) returned no error") + } + var typed *doltSQLProvider + if _, err := NewIssueClaimer(typed); err == nil { + t.Fatal("NewIssueClaimer of a typed-nil provider returned no error") + } +} diff --git a/internal/telemetry/issue_claimer.go b/internal/telemetry/issue_claimer.go new file mode 100644 index 000000000..88881dc25 --- /dev/null +++ b/internal/telemetry/issue_claimer.go @@ -0,0 +1,36 @@ +package telemetry + +import ( + "context" + + "github.com/steveyegge/beads/issueops" +) + +// IssueClaimer returns the inner store's claimer wrapped in this layer's +// instrumentation. It recurses instead of delegating: a blind delegation would +// return the inner claimer unspanned and untimed. +func (s *InstrumentedStorage) IssueClaimer() (issueops.Claimer, error) { + inner, err := s.Unwrap().IssueClaimer() + if err != nil { + return nil, err + } + return s.WrapIssueClaimer(inner), nil +} + +// WrapIssueClaimer instruments the guarded public claim with this storage +// layer's existing telemetry meter and tracer. +func (s *InstrumentedStorage) WrapIssueClaimer(inner issueops.Claimer) issueops.Claimer { + return &instrumentedIssueClaimer{storage: s, inner: inner} +} + +type instrumentedIssueClaimer struct { + storage *InstrumentedStorage + inner issueops.Claimer +} + +func (c *instrumentedIssueClaimer) Claim(ctx context.Context, request issueops.ClaimRequest) (result issueops.ClaimResult, err error) { + ctx, span, started := c.storage.op(ctx, "IssueClaimer.Claim") + result, err = c.inner.Claim(ctx, request) + c.storage.done(ctx, span, started, err) + return result, err +} diff --git a/internal/telemetry/issue_claimer_test.go b/internal/telemetry/issue_claimer_test.go new file mode 100644 index 000000000..7e6eefdf8 --- /dev/null +++ b/internal/telemetry/issue_claimer_test.go @@ -0,0 +1,87 @@ +package telemetry + +import ( + "context" + "errors" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/issueops" +) + +type fakeIssueClaimer struct { + calls int + err error +} + +func (f *fakeIssueClaimer) Claim(context.Context, issueops.ClaimRequest) (issueops.ClaimResult, error) { + f.calls++ + return issueops.ClaimResult{}, f.err +} + +// claimerDoltStore is a DoltStorage whose only real method is IssueClaimer, so +// a test can see which claimer the instrumented layer recursed into. +type claimerDoltStore struct { + storage.DoltStorage + claimer issueops.Claimer + err error +} + +func (s *claimerDoltStore) IssueClaimer() (issueops.Claimer, error) { return s.claimer, s.err } + +// TestInstrumentedStorageIssueClaimerInstrumentsInner pins the recursion, the +// same way its lifecycle and reader siblings do: `return +// s.Unwrap().IssueClaimer()` compiles, satisfies Storage, passes every other +// test, and leaves the one write on this role unspanned forever. +func TestInstrumentedStorageIssueClaimerInstrumentsInner(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + inner := &fakeIssueClaimer{} + wrapped := WrapStorage(&claimerDoltStore{claimer: inner}).(*InstrumentedStorage) + + claimer, err := wrapped.IssueClaimer() + if err != nil { + t.Fatalf("IssueClaimer() error = %v", err) + } + instrumented, ok := claimer.(*instrumentedIssueClaimer) + if !ok { + t.Fatalf("IssueClaimer() = %T, want *instrumentedIssueClaimer", claimer) + } + if instrumented.inner != issueops.Claimer(inner) { + t.Fatalf("telemetry layer wraps %#v, want the inner store's claimer", instrumented.inner) + } +} + +func TestInstrumentedStorageIssueClaimerPropagatesInnerError(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + want := errors.New("inner refused") + wrapped := WrapStorage(&claimerDoltStore{err: want}).(*InstrumentedStorage) + + claimer, err := wrapped.IssueClaimer() + if !errors.Is(err, want) { + t.Fatalf("IssueClaimer() error = %v, want %v", err, want) + } + if claimer != nil { + t.Fatalf("IssueClaimer() = %T, want nil", claimer) + } +} + +// TestInstrumentedIssueClaimerForwardsEveryCallOnce: the span wrapper must not +// swallow, duplicate or reorder the claim, on either outcome. +func TestInstrumentedIssueClaimerForwardsEveryCallOnce(t *testing.T) { + t.Setenv("BD_OTEL_STDOUT", "true") + base := WrapStorage(&fakeDoltStore{}).(*InstrumentedStorage) + + t.Run("success", func(t *testing.T) { + fake := &fakeIssueClaimer{} + if _, err := base.WrapIssueClaimer(fake).Claim(context.Background(), issueops.ClaimRequest{}); err != nil || fake.calls != 1 { + t.Fatalf("err=%v calls=%d", err, fake.calls) + } + }) + t.Run("failure", func(t *testing.T) { + want := errors.New("inner refused") + fake := &fakeIssueClaimer{err: want} + if _, err := base.WrapIssueClaimer(fake).Claim(context.Background(), issueops.ClaimRequest{}); !errors.Is(err, want) || fake.calls != 1 { + t.Fatalf("err=%v calls=%d", err, fake.calls) + } + }) +} diff --git a/issueops/claimer.go b/issueops/claimer.go new file mode 100644 index 000000000..a0faecccd --- /dev/null +++ b/issueops/claimer.go @@ -0,0 +1,66 @@ +package issueops + +import "context" + +// ClaimRequest describes one atomic compare-and-set claim. +type ClaimRequest struct { + // Actor is the claimant. It becomes the issue's assignee and is recorded in + // the operation's audit trail. + Actor string + // IssueID names the issue to claim. + IssueID string +} + +// ClaimResult reports the post-claim issue as a detached post-state snapshot. +// +// The snapshot is the issue ROW: labels, dependency records and comments are +// all omitted. That is deliberate, and it is the one place this family differs +// from UpdateResult, CloseResult and ReopenResult, which all carry labels and +// dependency records. The reason is that this role answers an already-published +// surface — the v0 claim response and `bd update --claim --json` both report +// the bare row, verified against an issue that does carry labels — so +// hydrating here would change what a shipped body returns. Enriching it is a +// decision for the next revision window, not a side effect of moving the +// operation onto a role. +type ClaimResult struct { + // Issue is a detached post-state snapshot of the issue row, without + // labels, dependency records, or comments. + Issue *Issue + // Changed reports whether the claim persisted a semantic mutation. It is + // false exactly for the idempotent re-claim: Actor already held the issue + // in StatusInProgress, so nothing was written and nothing was committed. + Changed bool +} + +// Claimer describes the guarded atomic claim. It is its own role beside +// Lifecycle and Reader, reached by its own accessor; a new capability gets a +// new role interface and its own accessor, so never append a method here. +// +// Implementations never mutate caller-owned request values. Result values are +// unspecified when error is non-nil. +type Claimer interface { + // Claim validates and commits the complete request as one atomic + // compare-and-set mutation: it sets Assignee to Actor and Status to + // StatusInProgress only while the issue's status is built-in StatusOpen or + // a configured active status and the issue is unassigned, assigned to + // Actor, or assigned to a configured claim pool. StatusInProgress held by + // the same Actor is an idempotent success with Changed false and no + // persisted mutation. + // + // A foreign holder refuses with a wrapped ErrAlreadyClaimed and an + // ineligible status with a wrapped ErrNotClaimable; when the refusing state + // was readable in the same transaction, the refusal is a + // *ClaimConflictError carrying it. Any actor may claim — the actor is + // caller-asserted provenance, not authenticated identity, and eligibility + // is decided by the issue's state alone. + // + // Refusals and deterministic validation failures leave persistent state + // unchanged. Implementations own transaction retry: a claim that loses a + // commit-time merge is retried, never surfaced. Other operational or + // commit-finalization errors can have an indeterminate durable outcome; + // callers must reread state before retrying. + // + // A wisp id is ErrNotFound: the wisp plane is not claimable through this + // role. + Claim(context.Context, ClaimRequest) (ClaimResult, error) +} diff --git a/issueops/claimer_external_test.go b/issueops/claimer_external_test.go new file mode 100644 index 000000000..498ba4052 --- /dev/null +++ b/issueops/claimer_external_test.go @@ -0,0 +1,91 @@ +package issueops_test + +import ( + "context" + "errors" + "fmt" + "reflect" + "testing" + + "github.com/steveyegge/beads/issueops" +) + +// TestClaimerIsItsOwnRoleWithOneMethod pins the shape claim was given rather +// than the one it could have had: a role beside Lifecycle and Reader, reached +// by its own accessor, instead of a fifth verb on Lifecycle. The method count +// is part of that — the NEXT capability must not be appended here either. +func TestClaimerIsItsOwnRoleWithOneMethod(t *testing.T) { + var _ issueops.Claimer = claimerProbe{} + + role := reflect.TypeFor[issueops.Claimer]() + if got := role.NumMethod(); got != 1 { + t.Fatalf("Claimer declares %d methods, want exactly one; a new capability gets a new role", got) + } + if got := role.Method(0).Name; got != "Claim" { + t.Errorf("Claimer's method = %q, want Claim", got) + } + if _, found := reflect.TypeFor[issueops.Lifecycle]().MethodByName("Claim"); found { + t.Error("Lifecycle grew a Claim method; claim is its own role") + } +} + +// TestClaimRequestAndResultHaveUsefulZeroValues: a zero request names nobody +// and a zero result reports no mutation, so a caller that forgets a field gets +// a refusal rather than a claim by the empty actor. +func TestClaimRequestAndResultHaveUsefulZeroValues(t *testing.T) { + var request issueops.ClaimRequest + if request.Actor != "" || request.IssueID != "" { + t.Errorf("zero ClaimRequest carries a value: %#v", request) + } + var result issueops.ClaimResult + if result.Issue != nil || result.Changed { + t.Errorf("zero ClaimResult reports a mutation: %#v", result) + } +} + +// TestClaimConflictErrorWrapsTheRefusalItReports is the whole design of the +// typed conflict: it ADDS the losing state without replacing anything. The +// sentinel still matches, and the message is byte-for-byte the refusal's — the +// carefully-worded copy that deliberately names no release command, and the +// fragments beads.ParseClaimConflict still parses. +func TestClaimConflictErrorWrapsTheRefusalItReports(t *testing.T) { + for _, tc := range []struct { + name string + sentinel error + status issueops.Status + }{ + {"already claimed", issueops.ErrAlreadyClaimed, issueops.StatusInProgress}, + {"not claimable", issueops.ErrNotClaimable, issueops.StatusClosed}, + } { + t.Run(tc.name, func(t *testing.T) { + refusal := fmt.Errorf("claim bd-1: %w: already assigned to %q", tc.sentinel, "bob") + var err error = &issueops.ClaimConflictError{ + IssueID: "bd-1", + Assignee: "bob", + Status: tc.status, + Err: refusal, + } + + if !errors.Is(err, tc.sentinel) { + t.Fatalf("ClaimConflictError does not match its sentinel: %v", err) + } + if got := err.Error(); got != refusal.Error() { + t.Errorf("Error() = %q, want the wrapped refusal byte-for-byte (%q)", got, refusal.Error()) + } + + var conflict *issueops.ClaimConflictError + if !errors.As(err, &conflict) { + t.Fatalf("errors.As did not recover the conflict from %v", err) + } + if conflict.IssueID != "bd-1" || conflict.Assignee != "bob" || conflict.Status != tc.status { + t.Errorf("conflict = %#v, want the state read inside the losing transaction", conflict) + } + }) + } +} + +type claimerProbe struct{} + +func (claimerProbe) Claim(context.Context, issueops.ClaimRequest) (issueops.ClaimResult, error) { + return issueops.ClaimResult{}, nil +} diff --git a/issueops/errors.go b/issueops/errors.go index f5c5d7db6..4112839aa 100644 --- a/issueops/errors.go +++ b/issueops/errors.go @@ -14,6 +14,33 @@ var ErrAlreadyClaimed = errors.New("issue already claimed") // same actor owning the claim. var ErrNotClaimable = errors.New("issue not claimable") +// ClaimConflictError reports the state that refused a claim — the current +// assignee and status, read inside the same transaction that lost the +// compare-and-set. It wraps the refusal rather than replacing it, so the +// sentinel still matches, the refusal's carefully-worded prose survives +// byte-for-byte, and a caller can classify the conflict from typed fields +// instead of parsing that prose. +// +// Err is set by every implementation that returns this type; a Claimer whose +// same-transaction re-read fails returns the bare refusal instead. +type ClaimConflictError struct { + // IssueID names the issue that refused the claim. + IssueID string + // Assignee is the holder observed by the losing transaction. It is empty + // when the refusal was about the status rather than a foreign holder. + Assignee string + // Status is the status observed by the losing transaction. + Status Status + // Err is the wrapped refusal. It matches ErrAlreadyClaimed or + // ErrNotClaimable. + Err error +} + +func (e *ClaimConflictError) Error() string { return e.Err.Error() } + +// Unwrap makes ClaimConflictError match the refusal it carries. +func (e *ClaimConflictError) Unwrap() error { return e.Err } + // ErrAssigneeMismatch is returned by UnclaimIssueIfAssignee when the issue's // current assignee does not match the expected assignee (including when the // issue is no longer assigned at all). The caller's view of the claim was