fix(cmd/bd): guarded close/update/assign that lose to a delete at pre-flight report precondition_failed (#7465)

* fix(cmd/bd): guarded close/update/assign that lose to a delete at pre-flight report precondition_failed

A --if-revision close, update or assign racing a `bd delete` can observe
the winning delete at two points: inside its guarded write (classified
precondition_failed / exit 13 via classifyIfRevisionFailure's
storage.ErrNotFound branch) or at its pre-flight resolution
(resolveAndGetIssueForMutation on the direct route, the advisory pre-read
on the proxied update/assign routes), which returned an unclassified
"no issue found matching" exit 1. Which one a loser hits depends only on
whether the delete commits before or after it resolves the id, so
TestSharedServerDeleteIfRevisionSingleWinner/delete_vs_close and
delete_vs_update flaked under load. mc-zndi7.81 (#7256) closed the same
gap for delete's own pre-flight only.

reportIfRevisionTargetGone now maps a pre-flight not-found under an active
--if-revision guard to the guard envelope on every verb and route (delete
refactored onto it); unguarded commands keep their not-found exit 1.

Fixes ga-vnycm2.10.

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

* test(cmd/bd): name the proxied target-gone test into the proxied lane's TestProxiedServer* prefix

TestProxiedIfRevisionTargetGoneIsPreconditionFailed skips unless
BEADS_TEST_PROXIED_SERVER=1, which only the proxied lane sets, and that
lane selects TestProxiedServer*/TestServerMode* by name: as named it ran in
no CI lane (ga-vnycm2.43). Renamed and placed in the 34-shard manifest block.

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

* fix(cmd/bd): classify pre-flight-gone reopen and cascade-delete targets

Review fixes for #7465, review-loop iteration 1.

The PR makes a guarded write whose pre-flight resolution finds the row
already deleted report precondition_failed (exit 13) on close, update and
assign, and documents that rule for every guarded verb. Two guarded paths
still turned the lost delete race into an unclassified exit 1:

- `bd reopen --if-revision`, on both routes. The direct loop's
  resolveAndGetIssueForMutation failure and the proxied
  reopenProxiedResolve pre-read now go through reportIfRevisionTargetGone,
  as the other verbs do. The proxied caller returns the already-reported
  exit error unchanged (isReportedExit), so the outcome prints once.
- `bd delete --cascade --if-revision` on the direct route. deleteBatch
  built its missing-id error with fmt.Errorf("issues not found: ..."),
  which carries no sentinel, so the caller's reportIfRevisionFailure could
  not classify it. It now returns issueops.NotFoundError, the error the
  delete role's own existence probe returns (delete_role.go). The text is
  identical, and the error unwraps to storage.ErrNotFound. This reuses the
  existing typed error instead of adding a guarded-only wrap.

ifRevisionFlagHelp's comment and reportIfRevisionTargetGone's doc now name
all five guarded verbs and the cascade path.

Tests:

- Rename TestIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb to
  TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb. The
  embedded lane only discovers `func TestEmbedded*`
  (.github/scripts/embedded-test-shard.sh), so under the old name it
  skipped in every CI lane. It is added to embedded-cmd-test-shards.txt
  (100 65), and the manifest generator's --check passes at 100.
- The embedded table and its proxied twin,
  TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed, gain reopen,
  delete and delete_cascade rows. The embedded table also gains an
  unguarded cascade-delete row that pins the unchanged "issues not found:
  <id>" text at exit 1. The deterministic cascade case lives in this
  CI-run table rather than in TestIfRevisionCascadeDelete, which the
  embedded lane does not discover; that test's doc points here.
- The proxied table now asserts that no raw "not found" text leaks past
  the guard envelope. A new unguarded_assign_still_not_found subtest pins
  the proxied assign pre-read's unguarded wording and exit 1.

Each code fix was mutation-checked. Reverting reopen.go,
reopen_proxied_server.go or delete.go to the PR head fails exactly one
row of its table (embedded reopen, proxied reopen and embedded
delete_cascade respectively), and every other row still passes. The fixed
build passes both full tables locally, the proxied one against a local
dolt 2.2.0 sql-server. A manual --json smoke of the direct reopen and
cascade-delete paths exits 13 with the standard precondition_failed body,
expected_revision included.

PR body corrections for finalize (description only, no code):
- The rule now covers five verbs (delete, close, update, assign, reopen)
  plus delete --cascade, not four.
- The embedded test is now
  TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb.
- The proxied test is
  TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed (renamed in
  009b9b629b), and it runs in //cmd/bd:bd_proxied_test shard 7 of 34. The
  coverage-gap note's "(the new test included)" no longer applies to it.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-10 16:33:19 +00:00 • committed by GitHub
commit 1b7bf9b191
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 356 additions and 49 deletions

View file

@ -310,6 +310,7 @@
100 64 TestEmbeddedGateWaiterCheckLifecycle
100 65 TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb
100 65 TestEmbeddedSupersede
100 66 TestEmbeddedCloseBasicIsolatedStores

View file

@ -308,6 +308,7 @@
34 7 TestProxiedServerDeleteIfRevisionSingleWinner
34 7 TestProxiedServerExternalCreate
34 7 TestProxiedServerIfRevisionGuardDelete
34 7 TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed
34 7 TestProxiedServerLabelC
34 7 TestProxiedServerTypesAgreeWithCreate

View file

@ -63,6 +63,12 @@ Examples:
if result != nil {
result.Close()
}
// A concurrent `bd delete` that commits before this resolution
// is the same lost race as one that commits inside the guarded
// write below.
if reported, ok := reportIfRevisionTargetGone("assigning", id, err, ifRevision); ok {
return reported
}
return HandleErrorRespectJSON("resolving %s: %v", id, err)
}
if result == nil || result.Issue == nil {

View file

@ -29,6 +29,11 @@ import (
func runCloseDirectIfRevision(ctx context.Context, id, reason string, force bool, session string, expectedVersion int64) error {
result, err := resolveAndGetIssueForMutation(ctx, store, id)
if err != nil {
// A concurrent `bd delete` that commits before this resolution is
// the same lost race as one that commits inside ops.Close below.
if reported, ok := reportIfRevisionTargetGone("closing", id, err, &expectedVersion); ok {
return reported
}
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
return &exitError{Code: 1}
}

View file

@ -125,26 +125,15 @@ Force: Delete and orphan dependents
// one place a convenience is not.
routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID)
if err != nil {
// 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 — see reportIfRevisionTargetGone.
if reported, ok := reportIfRevisionTargetGone("deleting", issueID, err, ifRevision); ok {
return reported
}
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
}
}
return HandleError("issue %s not found", issueID)
}
return HandleError("%v", err)
@ -364,7 +353,15 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
defer func() { _ = routedStore.Close() }()
}
if len(notFound) > 0 {
return fmt.Errorf("issues not found: %s", strings.Join(notFound, ", "))
// The role's own existence probe reports a missing id with this same
// error, and its text is the flat list every caller has always
// printed. What it adds is the storage.ErrNotFound sentinel, which
// lets the guarded `bd delete --cascade` caller's
// reportIfRevisionFailure report a target that a concurrent `bd
// delete` removed before this resolution as the same lost race as one
// removed inside deleter.Delete below: precondition_failed, not exit 1
// (see reportIfRevisionTargetGone).
return &issueops.NotFoundError{IDs: notFound}
}
batchStore := store
if routedStore != nil {

View file

@ -15,8 +15,8 @@ import (
)
// ifRevisionFlagHelp is the shared half of --if-revision's --help text across
// `bd update`, `bd close`, `bd assign` and `bd delete`: the value syntax, the
// one-id rule and the exit-code contract. Each verb appends what is specific
// `bd update`, `bd close`, `bd assign`, `bd delete` and `bd reopen`: the value
// syntax, the one-id rule and the exit-code contract. Each verb appends what is specific
// to it (close has no other guards to compose with; update composes with
// --if-assignee/--if-status).
const ifRevisionFlagHelp = "Apply the write only if the issue's current revision equals this value (the decimal int64 from `bd show --json`'s \"revision\" field). One id only: refused before any write when combined with more than one issue id. A mismatch writes nothing and exits 13 (vs 1 for other failures)."
@ -82,18 +82,18 @@ func classifyIfRevisionFailure(err error, ifRevision *int64) (code, reason strin
case errors.As(err, &vme):
return ifRevisionCodePreconditionFailed, "revision mismatch", &vme.Expected, &vme.Current, true
case errors.Is(err, storage.ErrNotFound):
// The row named by a single-id --if-revision write no longer exists.
// The plain CLI routes refuse a genuine typo earlier, via
// resolveAndGetIssueForMutation, before this guard ever runs — so in
// practice this fires either on a route with no such pre-check (the
// proxied routes) or, for a guarded delete racing an identical delete
// on a Dolt sql-server (mc-zndi7.73), on the same-token loser that
// re-checks after the winner's delete has already landed. Both are
// the same precondition failure from this guard's point of view:
// the exact revision the caller named is gone, so there is nothing
// left to compare it against. current is omitted (nothing to
// report); expected falls back to the caller's own --if-revision
// value, same as the bare storage.ErrVersionMismatch case below.
// The row named by a single-id --if-revision write no longer exists:
// a guarded write that lost to a concurrent delete (mc-zndi7.73),
// observed either inside the guarded write or at the verb's
// pre-flight resolution (reportIfRevisionTargetGone). Both are the
// same precondition failure from this guard's point of view: the
// exact revision the caller named is gone, so there is nothing left
// to compare it against. A mistyped id under --if-revision reports
// the same way — the CLI cannot tell "never existed" from "deleted
// a moment ago", and either way the named revision is not current.
// current is omitted (nothing to report); expected falls back to the
// caller's own --if-revision value, same as the bare
// storage.ErrVersionMismatch case below.
return ifRevisionCodePreconditionFailed, "issue no longer exists", ifRevision, nil, true
case errors.Is(err, storage.ErrAssigneeMismatch):
return ifRevisionCodePreconditionFailed, "assignee mismatch", nil, nil, true
@ -112,6 +112,33 @@ func classifyIfRevisionFailure(err error, ifRevision *int64) (code, reason strin
return "", "", nil, nil, false
}
// reportIfRevisionTargetGone reports a single-id --if-revision write whose
// pre-flight resolution (resolveAndGetIssueForMutation on the direct route,
// the advisory pre-read on the proxied route) found no row. Every guarded
// verb resolves the row BEFORE its guarded write, so a racer that loses to a
// concurrent `bd delete` sees the row vanish either here or inside the guarded
// write, depending only on which side of the delete's commit its resolution
// lands (mc-zndi7.81 for delete, ga-vnycm2.10 for close/update/assign/reopen).
// Both are the same outcome — the revision the caller named is gone — so both
// report precondition_failed / ExitGuardMismatch with the reason "issue no
// longer exists". With no --if-revision there is no guard to report through,
// and any other resolution failure is not a guard outcome; ok is false for
// both and the caller's ordinary failure handling applies unchanged. `bd
// delete --cascade` resolves through deleteBatch instead: its not-found error
// keeps the storage.ErrNotFound sentinel, so the caller's
// reportIfRevisionFailure classifies it the same way.
//
// err is matched with isNotFoundErr, which also accepts ResolvePartialID's
// unwrapped "no issue found matching" text, and reported as the literal
// storage.ErrNotFound sentinel classifyIfRevisionFailure matches via
// errors.Is.
func reportIfRevisionTargetGone(action, id string, err error, ifRevision *int64) (reportedErr error, ok bool) {
if ifRevision == nil || !isNotFoundErr(err) {
return nil, false
}
return reportIfRevisionFailure(action, id, storage.ErrNotFound, ifRevision)
}
// ifRevisionFailureBody is the machine JSON this CLI attaches to a refused
// --if-revision write, decoded by gascity's bdConditionalErrorBody
// (bdstore_conditional.go). ExpectedRevision/CurrentRevision are pointers so

View file

@ -245,6 +245,102 @@ func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) {
}
}
// TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb pins
// ga-vnycm2.10, the close/update/assign/reopen half of mc-zndi7.81: `bd
// close`, `bd update`, `bd assign` and `bd reopen` each resolve the row with
// resolveAndGetIssueForMutation BEFORE their guarded write, exactly as `bd
// delete` does (and `bd delete --cascade`, through deleteBatch). A guarded
// write that races a winning `bd delete` on a real Dolt sql-server
// (TestSharedServerDeleteIfRevisionSingleWinner/delete_vs_close and
// delete_vs_update) finds the row already gone right there and, pre-fix,
// exited 1 with an unclassified "no issue found matching" instead of the
// ExitGuardMismatch (13) precondition_failed the same loser gets when the
// delete lands one step later, inside its guarded write. The deterministic
// reproduction is the delete test's: delete the row out from under a
// --if-revision token, then present that token.
//
// TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed
// (if_revision_proxied_close_delete_test.go) is this test's proxied-server-leg
// twin. The TestEmbedded name is what puts this test in a CI lane
// (.github/scripts/embedded-test-shard.sh); under any other name it skips
// everywhere.
func TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb(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")
for _, tc := range []struct {
verb string
args func(id, rev string) []string
}{
{"close", func(id, rev string) []string { return []string{"close", id, "--if-revision", rev, "--reason", "gone"} }},
{"update", func(id, rev string) []string {
return []string{"update", id, "--if-revision", rev, "--spec-id", "gone"}
}},
{"assign", func(id, rev string) []string { return []string{"assign", id, "someone", "--if-revision", rev} }},
{"reopen", func(id, rev string) []string { return []string{"reopen", id, "--if-revision", rev} }},
{"delete", func(id, rev string) []string { return []string{"delete", id, "--force", "--if-revision", rev} }},
{"delete_cascade", func(id, rev string) []string {
return []string{"delete", id, "--cascade", "--force", "--if-revision", rev}
}},
} {
t.Run(tc.verb, func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Preflight gone "+tc.verb, "--type", "task")
rev0 := bdShowRevision(t, bd, dir, issue.ID)
// Stand in for the winning delete racer.
bdDelete(t, bd, dir, issue.ID, "--force")
bdShowFail(t, bd, dir, issue.ID)
out, code := bdRunFailCode(t, bd, dir, tc.args(issue.ID, revStr(rev0))...)
if code != ExitGuardMismatch {
t.Errorf("preflight-gone --if-revision %s exit code = %d, want %d\n%s", tc.verb, code, ExitGuardMismatch, out)
}
if !strings.Contains(out, "precondition failed: issue no longer exists") {
t.Errorf("preflight-gone %s should say \"precondition failed: issue no longer exists\", got:\n%s", tc.verb, out)
}
// Every verb's own not-found wording: "no issue found matching"
// (the direct resolution), "issue <id> not found" (delete's
// fallback), "issues not found: <id>" (deleteBatch).
if strings.Contains(out, "no issue found matching") || strings.Contains(out, "not found") {
t.Errorf("preflight-gone %s leaked the raw, unclassified resolution error instead of the guard envelope:\n%s", tc.verb, out)
}
})
}
// Without --if-revision there is no guard to report through: a missing
// id stays the ordinary not-found failure (exit 1), unchanged.
t.Run("unguarded_close_still_not_found", func(t *testing.T) {
out, code := bdRunFailCode(t, bd, dir, "close", "pv-doesnotexist", "--reason", "gone")
if code != 1 {
t.Errorf("unguarded close of a missing id exit code = %d, want 1\n%s", code, out)
}
if strings.Contains(out, "precondition failed") {
t.Errorf("unguarded close of a missing id must not report a guard outcome:\n%s", out)
}
})
// deleteBatch's not-found error now carries the storage.ErrNotFound
// sentinel the guarded cascade classifies; unguarded, it still prints the
// same flat list.
t.Run("unguarded_cascade_delete_still_not_found", func(t *testing.T) {
out, code := bdRunFailCode(t, bd, dir, "delete", "pv-doesnotexist", "--cascade", "--force")
if code != 1 {
t.Errorf("unguarded cascade delete of a missing id exit code = %d, want 1\n%s", code, out)
}
if !strings.Contains(out, "issues not found: pv-doesnotexist") {
t.Errorf("unguarded cascade delete of a missing id should say \"issues not found: pv-doesnotexist\", got:\n%s", out)
}
if strings.Contains(out, "precondition failed") {
t.Errorf("unguarded cascade delete of a missing id must not report a guard outcome:\n%s", 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
@ -254,7 +350,10 @@ func TestIfRevisionDeletePreflightGoneIsPreconditionFailed(t *testing.T) {
// here). A stale guard must refuse the WHOLE cascade — the dependent survives
// right alongside the named parent — on both the real run and the unconfirmed
// --dry-run preview, which reports the same conditional-write envelope rather
// than falling through to the generic preview-with-error path.
// than falling through to the generic preview-with-error path. A target that a
// concurrent delete removed before deleteBatch resolves it is
// TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb's
// delete_cascade row.
func TestIfRevisionCascadeDelete(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")

View file

@ -98,3 +98,86 @@ func TestProxiedServerIfRevisionDeleteMatchAndMismatch(t *testing.T) {
assertRowAbsent(t, db, "issues", issue.ID)
})
}
// TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed is the proxied-route
// twin of TestEmbeddedIfRevisionPreflightGoneIsPreconditionFailedOnEveryVerb
// (ga-vnycm2.10): a guarded close, update, assign, reopen or delete whose row
// a concurrent `bd delete` already removed must report precondition_failed /
// ExitGuardMismatch, whichever step (the advisory pre-read or the guarded
// write) first observes the row gone — never an unclassified "not found"
// exit 1. TestProxiedServerDeleteIfRevisionSingleWinner's delete_vs_close and
// delete_vs_update race exactly this; here the winning delete runs first, so
// the outcome is deterministic.
func TestProxiedServerIfRevisionTargetGoneIsPreconditionFailed(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
p := newSharedProxiedProject(t, bd, "ivtg")
for _, tc := range []struct {
verb string
args func(id, rev string) []string
}{
{"close", func(id, rev string) []string { return []string{"close", id, "--if-revision", rev, "--reason", "gone"} }},
{"update", func(id, rev string) []string {
return []string{"update", id, "--if-revision", rev, "--spec-id", "gone"}
}},
{"assign", func(id, rev string) []string { return []string{"assign", id, "someone", "--if-revision", rev} }},
{"reopen", func(id, rev string) []string { return []string{"reopen", id, "--if-revision", rev} }},
{"delete", func(id, rev string) []string { return []string{"delete", id, "--force", "--if-revision", rev} }},
{"delete_cascade", func(id, rev string) []string {
return []string{"delete", id, "--cascade", "--force", "--if-revision", rev}
}},
} {
t.Run(tc.verb, func(t *testing.T) {
t.Parallel()
issue := bdProxiedCreate(t, bd, p.dir, "Proxied guarded "+tc.verb+" vs deleted row")
rev0 := bdProxiedShowRevision(t, bd, p.dir, issue.ID)
bdProxiedDelete(t, bd, p.dir, issue.ID, "--force")
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, tc.args(issue.ID, proxiedRevStr(rev0))...)
if err == nil {
t.Fatalf("--if-revision %s of a deleted row should have failed, got:\nstdout:\n%s\nstderr:\n%s", tc.verb, stdout, stderr)
}
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("--if-revision %s of a deleted row failed without an exit code: %v", tc.verb, err)
}
out := stdout + stderr
if ee.ExitCode() != ExitGuardMismatch {
t.Errorf("--if-revision %s of a deleted row exit code = %d, want %d\n%s", tc.verb, ee.ExitCode(), ExitGuardMismatch, out)
}
if !strings.Contains(out, "precondition failed: issue no longer exists") {
t.Errorf("--if-revision %s of a deleted row should say \"precondition failed: issue no longer exists\", got:\n%s", tc.verb, out)
}
// Every route's own not-found wording: "Issue <id> not found"
// (reportIssueLookupFailure), "issue <id> not found" (assign's
// pre-read), "issues not found: <id>" (the delete role).
if strings.Contains(out, "not found") {
t.Errorf("--if-revision %s of a deleted row leaked the raw, unclassified lookup error instead of the guard envelope:\n%s", tc.verb, out)
}
})
}
// Without --if-revision there is no guard to report through. The assign
// pre-read wraps storage.ErrNotFound for the guarded case; unguarded, its
// rendered text must stay the "issue <id> not found" it always printed.
t.Run("unguarded_assign_still_not_found", func(t *testing.T) {
t.Parallel()
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "assign", "ivtg-doesnotexist", "someone")
var ee *exec.ExitError
if !errors.As(err, &ee) {
t.Fatalf("unguarded assign of a missing id should exit non-zero, got err=%v\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
out := stdout + stderr
if ee.ExitCode() != 1 {
t.Errorf("unguarded assign of a missing id exit code = %d, want 1\n%s", ee.ExitCode(), out)
}
if !strings.Contains(out, "issue ivtg-doesnotexist not found") {
t.Errorf("unguarded assign of a missing id should say \"issue ivtg-doesnotexist not found\", got:\n%s", out)
}
if strings.Contains(out, "precondition failed") {
t.Errorf("unguarded assign of a missing id must not report a guard outcome:\n%s", out)
}
})
}

View file

@ -3,6 +3,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"testing"
@ -286,6 +287,44 @@ func TestClassifyIfRevisionFailureNotFoundSentinel(t *testing.T) {
}
}
// TestReportIfRevisionTargetGone pins ga-vnycm2.10's pre-flight mapping: a
// verb's resolution failing with not-found (the storage sentinel, or
// ResolvePartialID's unwrapped "no issue found matching" text) reports as
// precondition_failed / ExitGuardMismatch only under an active --if-revision
// guard; with no guard, or for any other resolution failure, it is not a
// guard outcome and the caller's own handling applies.
func TestReportIfRevisionTargetGone(t *testing.T) {
ifRevision := int64(3)
for _, tc := range []struct {
name string
err error
ifRevision *int64
wantOK bool
}{
{"sentinel_guarded", fmt.Errorf("resolving: %w", storage.ErrNotFound), &ifRevision, true},
{"partial_id_text_guarded", errors.New(`no issue found matching "bd-x"`), &ifRevision, true},
{"sentinel_unguarded", storage.ErrNotFound, nil, false},
{"other_error_guarded", errors.New("connection refused"), &ifRevision, false},
} {
t.Run(tc.name, func(t *testing.T) {
reported, ok := reportIfRevisionTargetGone("closing", "bd-x", tc.err, tc.ifRevision)
if ok != tc.wantOK {
t.Fatalf("reportIfRevisionTargetGone ok = %v, want %v", ok, tc.wantOK)
}
if !ok {
if reported != nil {
t.Errorf("reported = %v, want nil when not a guard outcome", reported)
}
return
}
ee, isExitErr := reported.(*exitError)
if !isExitErr || ee.Code != ExitGuardMismatch {
t.Fatalf("reported error = %#v, want *exitError{Code: %d}", reported, ExitGuardMismatch)
}
})
}
}
// TestClassifyIfRevisionFailureTypedBeforeSentinel pins ordering: a typed
// *issueops.VersionMismatchError (which also satisfies errors.Is against the
// same ErrVersionMismatch sentinel via Unwrap) must still report its OWN

View file

@ -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)
// Wrapped, not flattened, so runAssignProxiedServer classifies a
// guarded assign that lost to a concurrent delete as
// precondition_failed (reportIfRevisionFailure).
return struct{}{}, fmt.Errorf("issue %s %w", id, storage.ErrNotFound) // "issue <id> not found", as before
}
if rerr != nil {
return struct{}{}, fmt.Errorf("resolving %s: %w", id, rerr)

View file

@ -69,6 +69,13 @@ another actor won the race, so retrying the same guard is pointless).`,
// Resolve with prefix routing (supports cross-rig reopens like `bd reopen xe-5ls`)
result, err := resolveAndGetIssueForMutation(ctx, store, id)
if err != nil {
// A concurrent `bd delete` that commits before this
// resolution is the same lost race as one that commits
// inside ops.Reopen below. requireSingleIfRevisionID
// guarantees this is the only id, so nothing is pending.
if reported, ok := reportIfRevisionTargetGone("reopening", id, err, ifRevision); ok {
return reported
}
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
hasError = true
continue

View file

@ -47,8 +47,13 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
reason, _ := cmd.Flags().GetString("reason")
jsonOut, _ := cmd.Flags().GetBool("json")
targets, hasError, err := reopenProxiedResolve(ctx, args)
targets, hasError, err := reopenProxiedResolve(ctx, args, ifRevision)
if err != nil {
if isReportedExit(err) {
// The --if-revision guard outcome reopenProxiedResolve has
// already reported; re-wrapping would print a second Error line.
return err
}
return HandleErrorRespectJSON("%v", err)
}
if len(targets) == 0 {
@ -131,8 +136,12 @@ func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
//
// It decides NOTHING about the reopen. A resolved id goes to the role whatever
// status it is at, including a status this route used to refuse; every guard
// that matters is inside the role's own transaction.
func reopenProxiedResolve(ctx context.Context, ids []string) ([]reopenProxiedTarget, bool, error) {
// that matters is inside the role's own transaction. The one outcome it reports
// on the role's behalf is a guarded id that is already gone: that is the lost
// delete race the role would otherwise classify, so the error is then the
// --if-revision guard outcome it has already reported, which the caller
// returns as the command's exit error.
func reopenProxiedResolve(ctx context.Context, ids []string, ifRevision *int64) ([]reopenProxiedTarget, bool, error) {
var targets []reopenProxiedTarget
failed := false
_, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, error) {
@ -140,6 +149,14 @@ func reopenProxiedResolve(ctx context.Context, ids []string) ([]reopenProxiedTar
for _, id := range ids {
issue, _, err := workapi.GetIssueOrWisp(ctx, source, id)
if err != nil {
// A guarded reopen that lost to a concurrent `bd delete`
// committing before this read is the same lost race as one
// committing inside lifecycle.Reopen: report it through the
// guard envelope. requireSingleIfRevisionID guarantees this
// is the only id, so nothing is pending.
if reported, ok := reportIfRevisionTargetGone("reopening", id, err, ifRevision); ok {
return struct{}{}, reported
}
reportIssueLookupFailure("resolving", id, err)
failed = true
continue

View file

@ -42,6 +42,13 @@ const sharedServerDeleteIfRevisionRacers = 10
// Error 1213 rather than being retried and reclassified as a version
// mismatch. This test pins the single-winner, precondition_failed outcome
// for all three pairings.
//
// A close/update loser can observe a winning delete at either of two points:
// inside its guarded write (the delete commits after it resolved the id) or
// at its pre-flight resolution (the delete commits first, so the racers never
// overlap at the storage layer). Both are the same lost race and both must
// report precondition_failed / exit 13 — whichever point the scheduler
// happens to pick (ga-vnycm2.10; reportIfRevisionTargetGone).
func TestSharedServerDeleteIfRevisionSingleWinner(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("not supported on Windows")

View file

@ -478,6 +478,13 @@ pointless).`,
if result != nil {
result.Close()
}
// A concurrent `bd delete` that commits before this
// resolution is the same lost race as one that commits
// inside the guarded write below. requireSingleIfRevisionID
// guarantees this is the only id, so nothing is pending.
if reported, ok := reportIfRevisionTargetGone("updating", id, err, ifRevision); ok {
return reported
}
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
recordFailure(id, fmt.Sprintf("resolving issue: %v", err))
continue

View file

@ -108,9 +108,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 {
@ -195,21 +195,29 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
// --notes is about to replace existing notes, and whether --defer="" should
// also clear a deferred status. It no 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) {
// plumbing, exactly as it does on the embedded path. The error is non-nil
// only for an --if-revision guard outcome it has already reported, which the
// caller returns as the command's exit error.
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 {
// A guarded update that lost to a concurrent `bd delete` committing
// before this pre-read is the same lost race as one committing inside
// the guarded write: report it through the guard envelope.
if reported, ok := reportIfRevisionTargetGone("updating", id, err, in.ifRevision); ok {
return nil, nil, reported
}
if errors.Is(err, issueops.ErrNotFound) {
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
// The template guard is the role's, enforced inside the mutation;
@ -227,10 +235,10 @@ func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*type
if err := validateIssueReassignable(id, current, currentActor(), 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