From 21f1390859d2446853ac73daa1d300f5e23f6144 Mon Sep 17 00:00:00 2001 From: Julian Knutsen Date: Tue, 6 Oct 2026 04:27:26 +0000 Subject: [PATCH] fix(cmd/bd): classify every guarded verb's pre-flight not-found as precondition_failed #7256 fixed bd delete's single-id path only. The other guarded verbs resolve the row before their guarded write too, so a same-token --if-revision racer that loses can find it gone there and still got an unclassified exit 1 "not found" instead of exit 13 precondition_failed: - bd assign, bd update and the guarded direct bd close, at their resolveAndGetIssueForMutation pre-read; - proxied bd assign, whose pre-read returned "issue %s not found" without wrapping storage.ErrNotFound, so the caller's reportIfRevisionFailure could not match it; - proxied bd update, whose proxiedUpdateTarget pre-read turned the miss into a batch "issue not found" verdict; - bd delete --cascade (and so any guarded deleteBatch call), whose own pre-flight loop returned a bare fmt.Errorf (#7258). reportIfRevisionPreflightGone reports storage.ErrNotFound through reportIfRevisionFailure when --if-revision is set, and the direct sites and delete's single-id path now share it. It passes the literal sentinel, as #7256 did, because isNotFoundErr also accepts ResolvePartialID's unwrapped "no issue found matching" text. proxiedAssign wraps the sentinel with "issue %s %w", which keeps the printed text ("issue not found") that TestProxiedLookupReportsMissingIssue pins. deleteBatch wraps it only when ifRevision is set. Without --if-revision every path keeps its exit 1 and message. Tests: - TestIfRevisionPreflightGoneEveryVerb (embedded CLI): assign, update, close and delete --cascade with --if-revision on a deleted id exit 13 with "code":"precondition_failed"; without the flag each keeps exit 1 and today's text. - TestProxiedAssignIfRevisionPreflightGone and TestProxiedUpdateIfRevisionPreflightGone: the proxied pre-reads classify a guarded miss, and a backend failure stays unclassified. All of them fail on main, and reverting any one production file fails its verb's test. Closes #7276 Closes #7258 Agent-Signature: claude-agent-sdk-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) --- cmd/bd/assign.go | 10 ++++ cmd/bd/close_if_revision.go | 10 ++++ cmd/bd/delete.go | 29 +++++------ cmd/bd/if_revision.go | 17 +++++++ cmd/bd/if_revision_embedded_test.go | 71 +++++++++++++++++++++++++++ cmd/bd/mutate_proxied_server.go | 5 +- cmd/bd/proxied_lookup_failure_test.go | 48 ++++++++++++++++++ cmd/bd/update.go | 15 +++++- cmd/bd/update_claim_proxied_test.go | 41 ++++++++++++++++ cmd/bd/update_proxied_server.go | 27 ++++++---- 10 files changed, 243 insertions(+), 30 deletions(-) diff --git a/cmd/bd/assign.go b/cmd/bd/assign.go index ba3a72e97..c350a7fe7 100644 --- a/cmd/bd/assign.go +++ b/cmd/bd/assign.go @@ -58,17 +58,27 @@ Examples: ctx := rootCtx + // mc-zndi7.82: a guarded miss here is a lost race, not a typo; see + // reportIfRevisionPreflightGone. result, err := resolveAndGetIssueForMutation(ctx, store, id) if err != nil { if result != nil { result.Close() } + if isNotFoundErr(err) { + if reported, ok := reportIfRevisionPreflightGone("assigning", id, ifRevision); ok { + return reported + } + } return HandleErrorRespectJSON("resolving %s: %v", id, err) } if result == nil || result.Issue == nil { if result != nil { result.Close() } + if reported, ok := reportIfRevisionPreflightGone("assigning", id, ifRevision); ok { + return reported + } return HandleErrorRespectJSON("issue %s not found", id) } defer result.Close() diff --git a/cmd/bd/close_if_revision.go b/cmd/bd/close_if_revision.go index ac5bfda1a..de3977750 100644 --- a/cmd/bd/close_if_revision.go +++ b/cmd/bd/close_if_revision.go @@ -27,13 +27,23 @@ import ( // already refused more than one id by the time this runs, so there is no // batch to preserve here. func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool, session string, expectedVersion int64) error { + // mc-zndi7.82: a miss here is a lost race, not a typo; see + // reportIfRevisionPreflightGone. result, err := resolveAndGetIssueForMutation(ctx, store, id) if err != nil { + if isNotFoundErr(err) { + if reported, ok := reportIfRevisionPreflightGone("closing", id, &expectedVersion); ok { + return reported + } + } fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) return &exitError{Code: 1} } defer result.Close() if result.Issue == nil { + if reported, ok := reportIfRevisionPreflightGone("closing", id, &expectedVersion); ok { + return reported + } fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) return &exitError{Code: 1} } diff --git a/cmd/bd/delete.go b/cmd/bd/delete.go index d48de774a..45f022fb5 100644 --- a/cmd/bd/delete.go +++ b/cmd/bd/delete.go @@ -126,24 +126,10 @@ Force: Delete and orphan dependents routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID) if err != nil { if isNotFoundErr(err) { - // mc-zndi7.81: this pre-flight existence check runs before - // deleter.Delete() and the per-id lock fence #7244 added, so a - // same-token --if-revision racer that loses the fence sees the - // row disappear right here instead of inside the guarded - // write below. That is the same outcome classifyIfRevisionFailure - // already gives storage.ErrNotFound (mc-zndi7.73's comment on - // that case anticipated exactly this gap): the exact revision - // the caller named is gone, so report precondition_failed/ - // ExitGuardMismatch like every other loser, not an unclassified - // exit 1. Passing the literal sentinel rather than err itself - // because classifyIfRevisionFailure matches via errors.Is, and - // this package's own isNotFoundErr also accepts - // ResolvePartialID's unwrapped "no issue found matching" text, - // which errors.Is would not recognize. - if ifRevision != nil { - if reported, ok := reportIfRevisionFailure("deleting", issueID, storage.ErrNotFound, ifRevision); ok { - return reported - } + // mc-zndi7.81: this pre-flight check runs before deleter.Delete() + // and the per-id lock fence #7244 added. + if reported, ok := reportIfRevisionPreflightGone("deleting", issueID, ifRevision); ok { + return reported } return HandleError("issue %s not found", issueID) } @@ -364,6 +350,13 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c defer func() { _ = routedStore.Close() }() } if len(notFound) > 0 { + // mc-zndi7.83: under --if-revision (exactly one id, per + // requireSingleIfRevisionID) wrap the sentinel so the caller's + // reportIfRevisionFailure classifies the miss. The unguarded error, + // which deleteBatch's other callers also see, is left as it was. + if ifRevision != nil { + return fmt.Errorf("issues not found: %s: %w", strings.Join(notFound, ", "), storage.ErrNotFound) + } return fmt.Errorf("issues not found: %s", strings.Join(notFound, ", ")) } batchStore := store diff --git a/cmd/bd/if_revision.go b/cmd/bd/if_revision.go index bd76d6106..8c1f329e5 100644 --- a/cmd/bd/if_revision.go +++ b/cmd/bd/if_revision.go @@ -175,3 +175,20 @@ func reportIfRevisionFailure(action, id string, err error, ifRevision *int64) (r } return &exitError{Code: 1}, true } + +// reportIfRevisionPreflightGone reports a guarded write whose pre-flight +// resolve found no row: reportIfRevisionFailure with storage.ErrNotFound when +// ifRevision is set, ok=false otherwise so the caller's plain not-found +// handling runs unchanged. The verbs resolve the id before their guarded +// write, so a same-token --if-revision racer that loses can see the row +// vanish there instead of inside the guard; that is the same outcome the +// guard gives storage.ErrNotFound (mc-zndi7.81, .82). The caller passes no +// error because isNotFoundErr also accepts ResolvePartialID's unwrapped "no +// issue found matching" text, which classifyIfRevisionFailure's errors.Is +// would miss. +func reportIfRevisionPreflightGone(action, id string, ifRevision *int64) (reportedErr error, ok bool) { + if ifRevision == nil { + return nil, false + } + return reportIfRevisionFailure(action, id, storage.ErrNotFound, ifRevision) +} diff --git a/cmd/bd/if_revision_embedded_test.go b/cmd/bd/if_revision_embedded_test.go index eab6138fa..ec24b80e8 100644 --- a/cmd/bd/if_revision_embedded_test.go +++ b/cmd/bd/if_revision_embedded_test.go @@ -4,6 +4,7 @@ package main import ( "encoding/json" + "fmt" "os" "os/exec" "strconv" @@ -245,6 +246,76 @@ func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) { } } +// TestIfRevisionPreflightGoneEveryVerb pins mc-zndi7.82 and mc-zndi7.83: the +// other guarded verbs share delete's pre-flight gap +// (TestIfRevisionDeletePreflightGoneIsPreconditionFailed). assign, update and +// the guarded direct close each resolve the row before their guarded write, +// and delete --cascade resolves it in deleteBatch's own existence loop, so a +// losing same-token racer finds the row gone there. Each must report +// precondition_failed / ExitGuardMismatch, in the JSON body gascity decodes +// too. Without --if-revision the same miss keeps today's exit 1 and text. +func TestIfRevisionPreflightGoneEveryVerb(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, _, _ := bdInit(t, bd, "--prefix", "pv") + + verbs := []struct { + name string + args func(id string) []string + // plain is the error text the unguarded miss has always printed. + plain string + }{ + {"assign", func(id string) []string { return []string{"assign", id, "worker"} }, "resolving %s: no issue found matching"}, + {"update", func(id string) []string { return []string{"update", id, "--priority", "3"} }, "Error resolving %s: no issue found matching"}, + {"close", func(id string) []string { return []string{"close", id} }, "no issue found matching"}, + {"delete_cascade", func(id string) []string { return []string{"delete", id, "--cascade", "--force"} }, "issues not found: %s"}, + } + for _, v := range verbs { + t.Run(v.name, func(t *testing.T) { + issue := bdCreate(t, bd, dir, "Preflight gone "+v.name, "--type", "task") + rev0 := bdShowRevision(t, bd, dir, issue.ID) + // Stand in for the winning racer. + bdDelete(t, bd, dir, issue.ID, "--force") + bdShowFail(t, bd, dir, issue.ID) + + args := append(v.args(issue.ID), "--if-revision", revStr(rev0), "--json") + out, code := bdRunFailCode(t, bd, dir, args...) + if code != ExitGuardMismatch { + t.Errorf("preflight-gone --if-revision %s exit code = %d, want %d\n%s", v.name, code, ExitGuardMismatch, out) + } + if !strings.Contains(out, "precondition failed") { + t.Errorf("preflight-gone %s should say \"precondition failed\", got:\n%s", v.name, out) + } + if !strings.Contains(out, `"code":"precondition_failed"`) { + t.Errorf("preflight-gone %s JSON body lacks code precondition_failed, got:\n%s", v.name, out) + } + if strings.Contains(out, "not found") { + t.Errorf("preflight-gone %s leaked the unclassified \"not found\" error:\n%s", v.name, out) + } + + // Regression pin: no guard, no classification. + out, code = bdRunFailCode(t, bd, dir, v.args(issue.ID)...) + if code != 1 { + t.Errorf("unguarded %s on a missing id exit code = %d, want 1\n%s", v.name, code, out) + } + plain := v.plain + if strings.Contains(plain, "%s") { + plain = fmt.Sprintf(plain, issue.ID) + } + if !strings.Contains(out, plain) { + t.Errorf("unguarded %s on a missing id should still say %q, got:\n%s", v.name, plain, out) + } + if strings.Contains(out, "precondition failed") { + t.Errorf("unguarded %s on a missing id was classified as a guard outcome:\n%s", v.name, out) + } + }) + } +} + // TestIfRevisionCascadeDelete pins mc-zndi7.76 (gap 4): a single named id with // --cascade takes the SAME deleteBatch path a multi-id delete does // (cmd/bd/delete.go:105, "len(issueIDs) > 1 || cascade"), which is the only diff --git a/cmd/bd/mutate_proxied_server.go b/cmd/bd/mutate_proxied_server.go index 7008e9a41..d6c9cd3f2 100644 --- a/cmd/bd/mutate_proxied_server.go +++ b/cmd/bd/mutate_proxied_server.go @@ -82,7 +82,10 @@ func proxiedAssign(ctx context.Context, id, assignee string, force bool, ifRevis _, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, error) { current, _, rerr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id) if errors.Is(rerr, storage.ErrNotFound) { - return struct{}{}, fmt.Errorf("issue %s not found", id) + // mc-zndi7.82: wrapped so runAssignProxiedServer's + // reportIfRevisionFailure classifies a guarded miss; the text + // ("issue not found") is unchanged. + return struct{}{}, fmt.Errorf("issue %s %w", id, storage.ErrNotFound) } if rerr != nil { return struct{}{}, fmt.Errorf("resolving %s: %w", id, rerr) diff --git a/cmd/bd/proxied_lookup_failure_test.go b/cmd/bd/proxied_lookup_failure_test.go index 5aa7d1e9f..36f79492a 100644 --- a/cmd/bd/proxied_lookup_failure_test.go +++ b/cmd/bd/proxied_lookup_failure_test.go @@ -464,3 +464,51 @@ func TestUOWMolReaderLookupFailure(t *testing.T) { } }) } + +// TestProxiedAssignIfRevisionPreflightGone pins mc-zndi7.82 on the proxied +// route: proxiedAssign's pre-read runs before the guarded write, so a +// same-token --if-revision racer that loses can find the row gone there. That +// miss must reach reportIfRevisionFailure as storage.ErrNotFound and report +// precondition_failed / ExitGuardMismatch like every other loser, while a +// backend failure under the same guard stays an ordinary error. +func TestProxiedAssignIfRevisionPreflightGone(t *testing.T) { + rev := int64(7) + + t.Run("absent id is precondition_failed", func(t *testing.T) { + withStubbedProxiedLookup(t, nil) + jsonOutput = true + + var err error + stderr := captureStderrDuring(t, func() { + err = runAssignProxiedServer(context.Background(), []string{stubMissingID, "someone"}, false, &rev) + }) + var ee *exitError + if !errors.As(err, &ee) || ee.Code != ExitGuardMismatch { + t.Fatalf("err = %#v, want *exitError{Code: %d}\nstderr:\n%s", err, ExitGuardMismatch, stderr) + } + body := decodeIfRevisionBody(t, lastJSONLine(t, stderr), false) + if body["code"] != ifRevisionCodePreconditionFailed { + t.Errorf("code = %v, want %q\nstderr:\n%s", body["code"], ifRevisionCodePreconditionFailed, stderr) + } + if body["expected_revision"] != float64(rev) { + t.Errorf("expected_revision = %v, want %d", body["expected_revision"], rev) + } + }) + + t.Run("backend failure is not a guard outcome", func(t *testing.T) { + withStubbedProxiedLookup(t, errors.New(stubBackendError)) + + var err error + stderr := captureStderrDuring(t, func() { + err = runAssignProxiedServer(context.Background(), []string{stubMissingID, "someone"}, false, &rev) + }) + var ee *exitError + if errors.As(err, &ee) && ee.Code == ExitGuardMismatch { + t.Fatalf("backend failure classified as a guard mismatch:\n%s", stderr) + } + want := "Error: assign bd-missing: resolving bd-missing: " + stubBackendError + if got := strings.TrimSpace(stderr); got != want { + t.Errorf("stderr = %q, want %q", got, want) + } + }) +} diff --git a/cmd/bd/update.go b/cmd/bd/update.go index 1510b8c78..887d0de9b 100644 --- a/cmd/bd/update.go +++ b/cmd/bd/update.go @@ -472,12 +472,21 @@ pointless).`, pendingCloseResults = nil } for _, id := range args { - // Resolve and get issue with routing (e.g., gt-xyz routes to another rig) + // Resolve and get issue with routing (e.g., gt-xyz routes to another rig). + // mc-zndi7.82: a guarded miss here is a lost race, not a typo; see + // reportIfRevisionPreflightGone. requireSingleIfRevisionID makes + // this the only id, so returning here skips no other id. result, err := resolveAndGetIssueForMutation(ctx, store, id) if err != nil { if result != nil { result.Close() } + if isNotFoundErr(err) { + if reported, ok := reportIfRevisionPreflightGone("updating", id, ifRevision); ok { + closePendingResults() + return reported + } + } fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) recordFailure(id, fmt.Sprintf("resolving issue: %v", err)) continue @@ -486,6 +495,10 @@ pointless).`, if result != nil { result.Close() } + if reported, ok := reportIfRevisionPreflightGone("updating", id, ifRevision); ok { + closePendingResults() + return reported + } fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) recordFailure(id, "issue not found") continue diff --git a/cmd/bd/update_claim_proxied_test.go b/cmd/bd/update_claim_proxied_test.go index bc05b7e9a..81ed8c4bc 100644 --- a/cmd/bd/update_claim_proxied_test.go +++ b/cmd/bd/update_claim_proxied_test.go @@ -203,3 +203,44 @@ func TestProxiedClaimReportsAMissingIssue(t *testing.T) { t.Error("a missing issue still reached the contract") } } + +// TestProxiedUpdateIfRevisionPreflightGone pins mc-zndi7.82 on the proxied +// route: proxiedUpdateTarget's pre-read runs before the guarded write, so a +// same-token --if-revision racer that loses can find the row gone there. With +// the guard set that miss reports precondition_failed / ExitGuardMismatch +// through the conditional-write envelope, not the batch's "issue not found" +// verdict TestProxiedClaimReportsAMissingIssue pins for the unguarded case. +func TestProxiedUpdateIfRevisionPreflightGone(t *testing.T) { + p := &claimRoleProvider{ + lifecycle: &recordingLifecycle{}, + readErr: issueops.ErrNotFound, + } + withClaimRoleProvider(t, p) + oldJSON := jsonOutput + jsonOutput = true + t.Cleanup(func() { jsonOutput = oldJSON }) + + rev := int64(7) + var fail *updateIDFailure + var err error + stderr := captureStderrDuring(t, func() { + _, fail, err = applyUpdateProxiedOne(context.Background(), "bd-404", &updateInput{ + fields: map[string]any{"priority": 3}, + ifRevision: &rev, + }) + }) + if fail != nil { + t.Fatalf("fail = %+v, want the guard envelope instead of a batch verdict\nstderr:\n%s", fail, stderr) + } + var ee *exitError + if !errors.As(err, &ee) || ee.Code != ExitGuardMismatch { + t.Fatalf("err = %#v, want *exitError{Code: %d}\nstderr:\n%s", err, ExitGuardMismatch, stderr) + } + body := decodeIfRevisionBody(t, lastJSONLine(t, stderr), false) + if body["code"] != ifRevisionCodePreconditionFailed { + t.Errorf("code = %v, want %q\nstderr:\n%s", body["code"], ifRevisionCodePreconditionFailed, stderr) + } + if p.lifecycle.request.IssueID != "" { + t.Error("a missing issue still reached the contract") + } +} diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index fee3e9225..b8d004caf 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -107,9 +107,9 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty if err != nil { return nil, nil, HandleError("%v", err) } - before, fail := proxiedUpdateTarget(ctx, id, in) - if fail != nil { - return nil, fail, nil + before, fail, err := proxiedUpdateTarget(ctx, id, in) + if err != nil || fail != nil { + return nil, fail, err } patch, err := proxiedUpdatePatch(in, before) if err != nil { @@ -196,25 +196,32 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty // longer reads the pre-state to decide a hook: a status-crossing update fires // on_update and nothing else, from the plumbing, exactly as it does on the // embedded path. -func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure) { +// +// The error return carries only a guarded miss's already-reported exit +// (mc-zndi7.82): under --if-revision a row gone at this pre-read is a lost +// race, not a typo; see reportIfRevisionPreflightGone. +func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) { rd, err := proxiedIssueReader() if err != nil { fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) - return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)} + return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}, nil } details, err := rd.Get(ctx, issueops.GetRequest{ID: id}) if err != nil { if errors.Is(err, issueops.ErrNotFound) { + if reported, ok := reportIfRevisionPreflightGone("updating", id, in.ifRevision); ok { + return nil, nil, reported + } fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) - return nil, &updateIDFailure{ID: id, Error: "issue not found"} + return nil, &updateIDFailure{ID: id, Error: "issue not found"}, nil } fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) - return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)} + return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}, nil } current := &details.Issue if err := validateIssueUpdatable(id, current); err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) - return nil, &updateIDFailure{ID: id, Error: err.Error()} + return nil, &updateIDFailure{ID: id, Error: err.Error()}, nil } // bd-98s5c: an unguarded assignee update must not silently overwrite // another actor's live claim. Skipped under --if-assignee, whose CAS names @@ -229,10 +236,10 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type if err := validateIssueReassignable(id, current, actor, newAssignee, proxiedClaimPoolAliases(ctx), in.force); err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) - return nil, &updateIDFailure{ID: id, Error: err.Error()} + return nil, &updateIDFailure{ID: id, Error: err.Error()}, nil } } - return current, nil + return current, nil, nil } // proxiedClaimPoolAliases is uowClaimPoolAliases for a caller that owns no unit