feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete (#7203)

* feat(cli): add --if-revision compare-and-swap guard to update/close/assign/delete

Adds --if-revision <int64> to `bd update`, `bd close`, `bd assign` and
`bd delete`, reusing the existing opaque row_lock token published as
IssueDetails.Revision and the library's own ExpectedVersion compare-and-swap
support. A mismatch writes nothing and exits 13 (ExitGuardMismatch); with
--json the stderr envelope carries integer expected_revision/current_revision
fields deployed callers decode directly, never a quoted string. An
unsupported backend reports conditional_write_unsupported and exits 1
instead of silently dropping the guard. The guard composes with
--if-assignee/--if-status (every guard must hold) and is refused alongside
label or parent edits and alongside more than one id, matching the existing
--if-assignee rules. `bd assign` is newly routed through the checked
Lifecycle path to gain CAS support it previously had none of at all.

Implements Item 4 (compare-and-swap through the CLI, gastownhall/beads#4682)
from the BEADS-JOURNAL-PLAN.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(bazel): regenerate cmd/bd BUILD.bazel for if_revision/close_if_revision

gazelle hadn't picked up if_revision.go, close_if_revision.go,
if_revision_test.go, and if_revision_embedded_test.go, so Bazel's bd_lib
and bd_test targets failed to build with "undefined: parseIfRevisionFlag"
and friends while plain `go build`/`go test` worked fine. Ran `make
bazel-sync` (bazel run //:gazelle; go_srcs.py; bazel mod tidy) to pick up
the new files; only cmd/bd/BUILD.bazel's srcs lists changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(cli): update update-guard parity strings for --if-revision

TestParityUpdateGuardsRequireFieldUpdate and TestParityUpdateGuardsRejectClaim
pinned the exact stderr text of update.go's pre-write guard short-circuits.
Adding --if-revision to those guard messages (update.go/update_input.go)
changed "--if-assignee/--if-status" to "--if-assignee/--if-status/--if-revision"
in both, which this PR's own change to the guard text had not updated here —
caught by CI's dolt-server tier, not by the targeted if_revision* test runs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Julian Knutsen 2026-10-04 13:38:01 -07:00 • committed by GitHub
commit 37acca96db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
30 changed files with 1484 additions and 70 deletions

View file

@ -4,8 +4,10 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"sync"
"testing"
"time"
@ -905,6 +907,99 @@ func RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T, ctx cont
maskedEvents.assert(t, "guard masked by the one before it", 0)
}
// RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency pins A8's
// (gastownhall/beads#4682) headline claim about Lifecycle.Update's
// ExpectedVersion guard, for `bd update/close/assign/delete --if-revision`:
// the compare and the write are ONE atomic operation, not a read-then-write a
// concurrent writer can slip between (T4.4, BEADS-JOURNAL-PLAN.md Item 4). N
// goroutines race the SAME token — the row's version as of before any of them
// run — against the same row; exactly one may apply it, every other goroutine
// must see ErrVersionMismatch (never a second silent success), and the row
// that is left behind must be exactly the single winner's content, never a
// torn write belonging to neither the seed nor any one racer.
//
// THIS IS A GENUINE CONCURRENCY TEST, not N sequential attempts dressed up as
// parallel ones. cmd/bd's embedded-mode backend admits only one `bd` process
// at a time (an exclusive flock — see acquireEmbeddedLock in
// cmd/bd/store_factory.go), which would make "exactly one winner" trivially
// true even of a buggy read-then-write implementation with no atomicity at
// all, because no second process could ever observe the first one's
// in-flight state. That is why the CLI-level --if-revision tests
// (cmd/bd/if_revision_embedded_test.go) assert the match/mismatch CONTRACT
// sequentially and leave the race to this fixture: goroutines sharing one
// already-open Lifecycle are the one shape in this suite that can actually
// interleave at the transaction level, independent of whatever process-level
// serialization a given CLI backend layers on top.
func RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t *testing.T, ctx context.Context, fixture LifecycleUpdateFixture) {
t.Helper()
const racers = 16
id := fixture.IssuePrefix + "-lup-singlewinner"
seedLifecycleUpdateIssue(t, ctx, fixture, lifecycleUpdateIssue(id))
seed := lifecycleUpdateRow(t, ctx, fixture, id)
racedToken := seed.RowVersion
// Priority is a small enum (0-4, see validation.ValidatePriority); each
// racer's own index would overflow it past four racers, so the index rides
// in Notes instead (free-text, nothing else writes it in this test) and
// priority merely alternates, giving the final-state check two independent
// columns that must agree on which one racer actually landed.
var wg sync.WaitGroup
won := make([]bool, racers)
errs := make([]error, racers)
wg.Add(racers)
for i := 0; i < racers; i++ {
i := i
go func() {
defer wg.Done()
version := racedToken
result, err := fixture.Lifecycle.Update(ctx, publicops.UpdateRequest{
Actor: "racer",
IssueID: id,
Patch: publicops.IssuePatch{
Priority: publicops.Field[int]{Set: true, Value: i % 5},
Notes: publicops.Field[string]{Set: true, Value: fmt.Sprintf("racer-%d", i)},
},
ExpectedVersion: &version,
})
errs[i] = err
won[i] = err == nil && result.Changed
}()
}
wg.Wait()
winners := 0
winner := -1
for i, win := range won {
if win {
winners++
winner = i
continue
}
if !errors.Is(errs[i], storage.ErrVersionMismatch) {
t.Errorf("racer %d: err = %v, want nil (won) or ErrVersionMismatch (lost the race)", i, errs[i])
}
}
if winners != 1 {
t.Fatalf("%d racers shared one --if-revision token %d; got %d winners, want exactly 1 (errs=%v)",
racers, racedToken, winners, errs)
}
final := lifecycleUpdateRow(t, ctx, fixture, id)
wantNotes := fmt.Sprintf("racer-%d", winner)
if final.Notes != wantNotes {
t.Errorf("final notes = %q, want the single winner's %q — a torn or lost write", final.Notes, wantNotes)
}
if final.Priority != winner%5 {
t.Errorf("final priority = %d, want the single winner's %d — a torn or lost write", final.Priority, winner%5)
}
if final.RowVersion == racedToken {
t.Errorf("final row version = %d, want it to have advanced past the raced token %d", final.RowVersion, racedToken)
}
}
// RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee pins the
// ga-5ksp5 fix beside RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits
// above rather than inside it: that test's later "order-dependent composition"

View file

@ -451,6 +451,7 @@ var roleContractCases = []roleContract{
RunLifecycleUpdateRefusesUnknownIDsAndActorlessRequests,
RunLifecycleUpdateRefusalWritesNoMemberOfThePatch,
RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits,
RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency,
RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee,
RunLifecycleUpdateMetadataPatchOrdersMergeSetUnset,
RunLifecycleUpdateClosePolicy,

View file

@ -39,6 +39,7 @@ go_library(
"cleanup.go",
"close.go",
"close_direct.go",
"close_if_revision.go",
"close_proxied_server.go",
"closed_delete_candidates.go",
"codex_hook.go",
@ -157,6 +158,7 @@ go_library(
"hooks.go",
"human.go",
"human_proxied_server.go",
"if_revision.go",
"import.go",
"import_path.go",
"import_proxied_server.go",
@ -808,6 +810,8 @@ go_test(
"identity_preview_gate_cgo_test.go",
"identity_preview_gate_test.go",
"identity_preview_refusal_test.go",
"if_revision_embedded_test.go",
"if_revision_test.go",
"import_chunking_embedded_test.go",
"import_chunking_test.go",
"import_embedded_test.go",

View file

@ -7,6 +7,7 @@ import (
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
var assignCmd = &cobra.Command{
@ -40,8 +41,16 @@ Examples:
force, _ := cmd.Flags().GetBool("force")
// A8 (beads#4682): assign takes exactly two positional args (id, name),
// so "one id only" always holds; no separate check is needed the way
// update/close/delete need one.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if usesProxiedServer() {
return runAssignProxiedServer(rootCtx, args, force)
return runAssignProxiedServer(rootCtx, args, force, ifRevision)
}
id := args[0]
@ -77,10 +86,33 @@ Examples:
return HandleErrorRespectJSON("%s", err)
}
updates := map[string]interface{}{
"assignee": assignee,
// A8 (beads#4682): routed through issueops.Lifecycle.Update (via the
// shared commandUpdateMutation helper update.go uses) rather than the
// store's raw UpdateIssue, so --if-revision has a checked write to
// guard — bd assign had no compare-and-set surface at all before this.
ops, err := writeOps(issueStore)
if err != nil {
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
if err := issueStore.UpdateIssue(ctx, result.ResolvedID, updates, actor); err != nil {
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
mutationResult, err := runCommandUpdateMutation(opsCtx, ops, commandUpdateMutation{
actor: actor,
issueID: result.ResolvedID,
patch: issueops.IssuePatch{
Assignee: issueops.Field[string]{Set: true, Value: assignee},
},
force: force,
expectedVersion: ifRevision,
})
if err != nil {
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("assigning", id, err); ok {
return reported
}
}
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
@ -93,7 +125,7 @@ Examples:
SetLastTouchedID(result.ResolvedID)
updatedIssue, _ := issueStore.GetIssue(ctx, result.ResolvedID)
updatedIssue := mutationResult.Issue
title := ""
if updatedIssue != nil {
title = updatedIssue.Title
@ -117,6 +149,8 @@ Examples:
func init() {
assignCmd.Flags().Bool("force", false, "Allow overwriting another actor's live in_progress claim (use only for abandoned claims — crashed agent, expired lease; prefer bd reclaim)")
// A8 (beads#4682)
assignCmd.Flags().String("if-revision", "", ifRevisionFlagHelp)
assignCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(assignCmd)
}

View file

@ -176,7 +176,7 @@ SEE ALSO:
fmt.Println()
}
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, "cleanup"); err != nil {
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, nil, "cleanup"); err != nil {
return HandleError("%v", err)
}
return nil

View file

@ -95,6 +95,28 @@ the flags appear in the command line.`,
}
ctx := rootCtx
// A8 (beads#4682): a single-id compare-and-swap close bypasses the
// batch below entirely -- see close_if_revision.go for why
// BatchCloseItem cannot carry this guard.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if err := requireSingleIfRevisionID(ifRevision, args); err != nil {
return err
}
if ifRevision != nil {
// The bypass below never looks at these three post-close flags, so
// honoring them would mean silently dropping what the caller asked
// for. Refuse instead of guessing, the same way --continue and
// --suggest-next already refuse a multi-id batch below.
if continueFlag || suggestNext || claimNext {
return HandleErrorRespectJSON("--if-revision does not support --continue, --suggest-next, or --claim-next")
}
return runCloseDirectIfRevision(ctx, args[0], reasonForCloseIndex(reasons, 0), force, session, *ifRevision)
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
@ -495,6 +517,8 @@ func init() {
closeCmd.Flags().Bool("suggest-next", false, "Show newly unblocked issues after closing")
closeCmd.Flags().Bool("claim-next", false, "Automatically claim the next highest priority available issue")
closeCmd.Flags().String("session", "", "Claude Code session ID (or set CLAUDE_SESSION_ID env var)")
// A8 (beads#4682): bypasses the N-id batch above for a single guarded close.
closeCmd.Flags().String("if-revision", "", ifRevisionFlagHelp)
closeCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(closeCmd)
}

144
cmd/bd/close_if_revision.go Normal file
View file

@ -0,0 +1,144 @@
package main
import (
"context"
"errors"
"fmt"
"os"
"github.com/steveyegge/beads/internal/audit"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
// runCloseDirectIfRevision closes exactly one issue under an active
// --if-revision guard (A8, beads#4682) on the non-proxied route, bypassing
// `bd close`'s batch architecture entirely.
//
// issueops.BatchCloseItem carries no per-item ExpectedVersion —
// batchcloser.go's own CloseBatchRequest.Force doc states that is
// unimplemented by design ("no batch item carries [a lifecycle precondition]
// today") — so a guarded close cannot ride BatchCloser at all. It goes
// through issueops.Lifecycle.Close instead, the single-id primitive
// CloseRequest.ExpectedVersion was built for. requireSingleIfRevisionID has
// 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 {
result, err := resolveAndGetIssueForMutation(ctx, store, id)
if err != nil {
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
return &exitError{Code: 1}
}
defer result.Close()
if result.Issue == nil {
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
return &exitError{Code: 1}
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
ops, err := writeOps(result.Store)
if err != nil {
fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", id, err)
return &exitError{Code: 1}
}
preCloseStatus := string(result.Issue.Status)
closeResult, closeErr := ops.Close(opsCtx, issueops.CloseRequest{
Actor: actor,
IssueID: result.ResolvedID,
Reason: reason,
Session: session,
Force: force,
ExpectedVersion: &expectedVersion,
})
if closeErr != nil {
if reported, ok := reportIfRevisionFailure("closing", id, closeErr); ok {
return reported
}
fmt.Fprintln(os.Stderr, closeDirectRefusal(id, closeErr))
return &exitError{Code: 1}
}
if err := commitPendingIfEmbedded(ctx, result.Store, actor, doltAutoCommitParams{
Command: "close",
IssueIDs: []string{result.ResolvedID},
}); err != nil {
return HandleErrorRespectJSON("failed to commit: %v", err)
}
SetLastTouchedID(result.ResolvedID)
reportClosedIfRevisionResult(result.ResolvedID, reason, preCloseStatus, closeResult)
return nil
}
// runCloseProxiedIfRevision is runCloseDirectIfRevision's proxied-server twin:
// the same single-id bypass, reached through issueops.Lifecycle via
// proxiedIssueLifecycle rather than a routed store.
func runCloseProxiedIfRevision(ctx context.Context, id, reason string, force bool, session string, expectedVersion int64) error {
ops, err := proxiedIssueLifecycle()
if err != nil {
return HandleError("%v", err)
}
// Pre-close snapshot for the audit entry's old status, mirroring
// proxiedUpdateTarget's advisory pre-read. Best effort: a read failure
// here does not block the close, which reports not-found uniformly on its
// own if the id is bad.
preCloseStatus := "open"
if rd, rerr := proxiedIssueReader(); rerr == nil {
if details, gerr := rd.Get(ctx, issueops.GetRequest{ID: id}); gerr == nil {
preCloseStatus = string(details.Issue.Status)
}
}
closeResult, closeErr := ops.Close(ctx, issueops.CloseRequest{
Actor: actor,
IssueID: id,
Reason: reason,
Session: session,
Force: force,
ExpectedVersion: &expectedVersion,
})
if closeErr != nil {
if errors.Is(closeErr, context.Canceled) || errors.Is(closeErr, context.DeadlineExceeded) {
return closeErr
}
if reported, ok := reportIfRevisionFailure("closing", id, closeErr); ok {
return reported
}
fmt.Fprintln(os.Stderr, closeProxiedRefusal(id, closeErr))
return &exitError{Code: 1}
}
SetLastTouchedID(id)
reportClosedIfRevisionResult(id, reason, preCloseStatus, closeResult)
return nil
}
// reportClosedIfRevisionResult is the one-id success report shared by both
// --if-revision close routes: the audit entry (suppressed for an idempotent
// re-close, matching close.go's batch behavior) and the human/--json output.
func reportClosedIfRevisionResult(id, reason, preCloseStatus string, closeResult issueops.CloseResult) {
closedIssue := closeResult.Issue
if closedIssue != nil {
closedIssue.Dependencies = nil
}
if closeResult.Changed {
audit.LogFieldChange(id, "status", preCloseStatus, "closed", actor, reason)
}
if jsonOutput {
if closedIssue != nil {
_ = outputJSON([]*types.Issue{closedIssue})
}
return
}
title := ""
if closedIssue != nil {
title = closedIssue.Title
}
debug.PrintNormal("%s Closed %s: %s\n", ui.RenderPass("✓"), formatFeedbackID(id, title), reason)
}

View file

@ -91,6 +91,27 @@ func runCloseProxiedServer(cmd *cobra.Command, ctx context.Context, args []strin
in := gatherCloseProxiedInput(cmd)
// A8 (beads#4682): a single-id compare-and-swap close bypasses the batch
// below entirely -- see close_if_revision.go for why BatchCloseItem
// cannot carry this guard.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if err := requireSingleIfRevisionID(ifRevision, args); err != nil {
return err
}
if ifRevision != nil {
// The bypass below never looks at these three post-close flags, so
// honoring them would mean silently dropping what the caller asked
// for. Refuse instead of guessing, the same way --continue and
// --suggest-next already refuse a multi-id batch below.
if in.continueOn || in.suggestNext || in.claimNext {
return HandleErrorRespectJSON("--if-revision does not support --continue, --suggest-next, or --claim-next")
}
return runCloseProxiedIfRevision(ctx, args[0], reasonForCloseIndex(reasons, 0), in.force, in.session, *ifRevision)
}
if in.continueOn && len(args) > 1 {
return HandleErrorRespectJSON("--continue only works when closing a single issue")
}

View file

@ -83,6 +83,19 @@ Force: Delete and orphan dependents
}
issueIDs = uniqueStrings(issueIDs)
// A8 (beads#4682): issueops.DeleteRequest.ExpectedVersion already refuses
// (ErrValidation) a non-nil token beside more than one distinct id, but
// that refusal reads differently from the other three verbs' —
// requireSingleIfRevisionID gives this one the same wording and the same
// "before any write" timing as update/close/assign.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if err := requireSingleIfRevisionID(ifRevision, issueIDs); err != nil {
return err
}
if store == nil {
if err := ensureStoreActive(); err != nil {
return HandleError("%v", err)
@ -90,7 +103,12 @@ Force: Delete and orphan dependents
}
if len(issueIDs) > 1 || cascade {
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false); err != nil {
if err := deleteBatch(cmd, issueIDs, force, dryRun, cascade, jsonOutput, false, ifRevision); err != nil {
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("deleting", issueIDs[0], err); ok {
return reported
}
}
if _, ok := exitCodeFromError(err); ok {
return err
}
@ -126,10 +144,11 @@ Force: Delete and orphan dependents
// rewrite runs INSIDE the transaction that deletes, because it is the
// role's.
request := issueops.DeleteRequest{
Actor: actor,
IDs: []string{issueID},
Force: force,
DryRun: dryRun || !force,
Actor: actor,
IDs: []string{issueID},
Force: force,
DryRun: dryRun || !force,
ExpectedVersion: ifRevision,
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
@ -138,6 +157,15 @@ Force: Delete and orphan dependents
result, err := deleter.Delete(opsCtx, request)
if request.DryRun {
if err != nil {
// A8 (beads#4682): a guard mismatch is reported through the
// dedicated conditional-write envelope instead of the generic
// preview-with-error below — same split delete's real run makes,
// so --dry-run and the real run answer a stale token identically.
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("deleting", issueID, err); ok {
return reported
}
}
if previewErr := outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, nil, err, jsonOutput); previewErr != nil {
return previewErr
}
@ -152,6 +180,11 @@ Force: Delete and orphan dependents
return renderSingleDeletePreview(ctx, activeStore, issueID, issue, dryRun, result)
}
if err != nil {
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("deleting", issueID, err); ok {
return reported
}
}
return HandleError("deleting issue: %v", err)
}
@ -274,8 +307,12 @@ func deleteIssue(ctx context.Context, issueID string) error {
// cross-repository routing, which issueops.DeleteRequest deliberately does not
// do - and hands the RESOLVED ids to the role.
//
// ifRevision is non-nil only via `bd delete`'s own --if-revision (beads#4682);
// its other three callers always pass nil, and requireSingleIfRevisionID has
// already refused this path if it were asked to guard more than one id.
//
//nolint:unparam // cmd parameter required for potential future use
func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, _ ...string) error {
func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, ifRevision *int64, _ ...string) error {
if store == nil {
if err := ensureStoreActive(); err != nil {
return err
@ -322,11 +359,12 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
// --force is the confirmation as well as the orphan mode, so an unconfirmed
// run asks the role what it WOULD do; see the single-id path.
request := issueops.DeleteRequest{
Actor: actor,
IDs: resolvedIDs,
Cascade: cascade,
Force: force,
DryRun: dryRun || !force,
Actor: actor,
IDs: resolvedIDs,
Cascade: cascade,
Force: force,
DryRun: dryRun || !force,
ExpectedVersion: ifRevision,
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
@ -335,6 +373,17 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
result, err := deleter.Delete(opsCtx, request)
if request.DryRun {
if err != nil {
// A8 (beads#4682): let the caller's dedicated conditional-write
// envelope report a guard mismatch instead of the generic
// preview-with-error below -- see the single-id path's identical
// split. classifyIfRevisionFailure, not a bare ifRevision!=nil check,
// because an unrelated dry-run failure (not-found, bad request) on a
// guarded call still belongs to the generic preview path.
if ifRevision != nil {
if _, _, _, _, ok := classifyIfRevisionFailure(err); ok {
return err
}
}
if previewErr := outputDeletionPreview(resolvedIDs, issues, cascade, dryRun, nil, err, jsonOutput); previewErr != nil {
return previewErr
}
@ -501,6 +550,8 @@ func init() {
deleteCmd.Flags().String("from-file", "", "Read issue IDs from file (one per line)")
deleteCmd.Flags().Bool("dry-run", false, "Preview what would be deleted without making changes")
deleteCmd.Flags().Bool("cascade", false, "Recursively delete all dependent issues")
// A8 (beads#4682)
deleteCmd.Flags().String("if-revision", "", ifRevisionFlagHelp)
deleteCmd.ValidArgsFunction = issueIDCompletion
rootCmd.AddCommand(deleteCmd)
}

View file

@ -22,6 +22,10 @@ type deleteInput struct {
dryRun bool
jsonOutput bool
quiet bool
// ifRevision is A8's --if-revision guard (beads#4682). requireSingleIfRevisionID
// refuses it alongside more than one id before gatherDeleteInput's caller ever
// reaches the role.
ifRevision *int64
}
func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error) {
@ -76,6 +80,20 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
return HandleError("no issue IDs provided")
}
// A8 (beads#4682): parsed directly rather than inside gatherDeleteInput, so
// a refusal here returns straight through -- requireSingleIfRevisionID's
// error is already a fully reported HandleErrorRespectJSON result, and
// wrapping it a second time (the way gatherDeleteInput's other errors are
// wrapped above) would print it twice.
ifRevision, err := parseIfRevisionFlag(cmd)
if err != nil {
return err
}
if err := requireSingleIfRevisionID(ifRevision, in.ids); err != nil {
return err
}
in.ifRevision = ifRevision
deleter, err := proxiedDeleter()
if err != nil {
return HandleError("%v", err)
@ -84,13 +102,24 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
// --force is the confirmation as well as the orphan mode, exactly as on the
// direct route, so an unconfirmed run asks the role what it WOULD do.
request := issueops.DeleteRequest{
Actor: actor,
IDs: in.ids,
Cascade: in.cascade,
Force: in.force,
DryRun: in.dryRun || !in.force,
Actor: actor,
IDs: in.ids,
Cascade: in.cascade,
Force: in.force,
DryRun: in.dryRun || !in.force,
ExpectedVersion: ifRevision,
}
result, err := deleter.Delete(ctx, request)
// A8 (beads#4682): a guard mismatch is reported through the dedicated
// conditional-write envelope, win or lose on DryRun alike -- it is checked
// before the "blocked" special case below because a stale token means the
// caller is not yet in a position to read a dependents refusal it may not
// even still apply to.
if ifRevision != nil && err != nil {
if reported, ok := reportIfRevisionFailure("deleting", in.ids[0], err); ok {
return reported
}
}
// THE GUARD REFUSAL IS NOT A BARE ERROR HERE. Classic renders the preview
// and THEN the refusal, which is what tells the caller both what would go
// and how to proceed; returning early would print the second half only.

View file

@ -76,7 +76,7 @@ func TestDeleteBatchDryRunHonorsForce(t *testing.T) {
store, rootCtx, jsonOutput, quietFlag = s, ctx, false, true
t.Cleanup(func() { store, rootCtx, jsonOutput, quietFlag = oldStore, oldRootCtx, oldJSON, oldQuiet })
if err := deleteBatch(nil, []string{parent.ID}, true, true, false, false, false); err != nil {
if err := deleteBatch(nil, []string{parent.ID}, true, true, false, false, false, nil); err != nil {
t.Fatalf("forced dry-run rejected a dependent issue: %v", err)
}
if issue, err := s.GetIssue(ctx, parent.ID); err != nil || issue == nil {

147
cmd/bd/if_revision.go Normal file
View file

@ -0,0 +1,147 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// 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
// 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)."
// parseIfRevisionFlag reads --if-revision with presence detected via
// Changed(), matching --if-assignee/--if-status's idiom, and parses it with
// types.ParseRevisionToken — the one encoding bd uses for a revision token on
// the wire, so a value copied from `bd show --json`'s "revision" field always
// parses and a typo is refused before any write rather than silently never
// matching.
func parseIfRevisionFlag(cmd *cobra.Command) (*int64, error) {
if !cmd.Flags().Changed("if-revision") {
return nil, nil
}
raw, _ := cmd.Flags().GetString("if-revision")
v, err := types.ParseRevisionToken(strings.TrimSpace(raw))
if err != nil {
return nil, HandleErrorRespectJSON("invalid --if-revision %q: must be the decimal int64 revision from `bd show --json` (%v)", raw, err)
}
return &v, nil
}
// requireSingleIfRevisionID enforces A8's "one id only" rule: --if-revision
// names a single row's token, so more than one id is refused before any
// write rather than applying the one token to every id in the batch (T4.8).
func requireSingleIfRevisionID(ifRevision *int64, ids []string) error {
if ifRevision == nil || len(ids) <= 1 {
return nil
}
return HandleErrorRespectJSON("--if-revision guards one issue only; %d ids were given — send one guarded request per issue", len(ids))
}
// Machine body codes this CLI emits for a refused --if-revision write, shared
// verbatim with gascity's bdstore_conditional.go classifier, which switches on
// `code` rather than the exit code.
const (
ifRevisionCodePreconditionFailed = "precondition_failed"
ifRevisionCodeUnsupported = "conditional_write_unsupported"
)
// classifyIfRevisionFailure maps err to the machine code and human reason
// gascity's bdstore_conditional.go classifier expects from a single-id write
// guarded by --if-revision: "precondition_failed" for a stale --if-revision,
// --if-assignee or --if-status guard (T4.5 requires all three to report
// through the one envelope when --if-revision is present), or
// "conditional_write_unsupported" for a backend that cannot honor
// ExpectedVersion at all. ok is false for any other failure, which the
// caller's own (unrelated) failure handling reports unchanged.
func classifyIfRevisionFailure(err error) (code, reason string, expected, current *int64, ok bool) {
var vme *issueops.VersionMismatchError
switch {
case errors.As(err, &vme):
return ifRevisionCodePreconditionFailed, "revision mismatch", &vme.Expected, &vme.Current, true
case errors.Is(err, storage.ErrAssigneeMismatch):
return ifRevisionCodePreconditionFailed, "assignee mismatch", nil, nil, true
case errors.Is(err, storage.ErrStatusMismatch):
return ifRevisionCodePreconditionFailed, "status mismatch", nil, nil, true
}
var unsupported *issueops.ErrUnsupported
if errors.As(err, &unsupported) {
return ifRevisionCodeUnsupported, "", nil, nil, true
}
return "", "", nil, nil, false
}
// 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
// an absent field (assignee/status guard, or unsupported) is distinguishable
// from a legitimate zero revision, and they marshal as JSON INTEGERS — never
// strings, unlike `bd show --json`'s "revision" — because gascity decodes them
// straight into *int64 and a string there makes its json.Decoder fail closed
// on the whole object (bdstore_conditional.go:134-139).
type ifRevisionFailureBody struct {
Error string `json:"error"`
Code string `json:"code"`
ID string `json:"id"`
ExpectedRevision *int64 `json:"expected_revision,omitempty"`
CurrentRevision *int64 `json:"current_revision,omitempty"`
}
// reportIfRevisionFailure reports a single-id write refused under an active
// --if-revision guard (alone or composed with --if-assignee/--if-status) and
// returns the exit error the CLI contract promises: ExitGuardMismatch (13)
// for a stale guard, 1 for a backend that cannot honor ExpectedVersion at
// all. action is the gerund for the human line ("updating", "closing",
// "assigning", "deleting"), matching this file's existing "Error <gerund>
// <id>: <reason>" convention. ok is false when err is not a guard outcome at
// all, in which case the caller's existing failure handling applies
// unchanged and nothing is printed here.
//
// In --json mode the JSON body is the LAST line on stderr, flat or under
// `data` per jsonEnvelopeEnabled — mirroring reportUpdateFailures — and the
// human "error" text always contains "precondition failed" so gascity's
// code-less fallback (bdstore_conditional.go:320-327) still matches if a
// caller ever loses the `code` field.
func reportIfRevisionFailure(action, id string, err error) (reportedErr error, ok bool) {
code, reason, expected, current, ok := classifyIfRevisionFailure(err)
if !ok {
return nil, false
}
humanErr := "backend does not support --if-revision (conditional write unsupported)"
if code == ifRevisionCodePreconditionFailed {
humanErr = "precondition failed: " + reason
}
fmt.Fprintf(os.Stderr, "Error %s %s: %s\n", action, id, humanErr)
if jsonOutput {
body := ifRevisionFailureBody{Error: humanErr, Code: code, ID: id, ExpectedRevision: expected, CurrentRevision: current}
var payload interface{}
if jsonEnvelopeEnabled() {
payload = map[string]interface{}{"schema_version": JSONSchemaVersion, "data": body}
} else {
payload = struct {
ifRevisionFailureBody
SchemaVersion int `json:"schema_version"`
}{body, JSONSchemaVersion}
}
if data, merr := json.Marshal(payload); merr == nil {
fmt.Fprintln(os.Stderr, string(data))
}
}
if code == ifRevisionCodePreconditionFailed {
return &exitError{Code: ExitGuardMismatch}, true
}
return &exitError{Code: 1}, true
}

View file

@ -0,0 +1,475 @@
//go:build cgo
package main
import (
"encoding/json"
"os"
"os/exec"
"strconv"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// bdShowRevision runs "bd show <id> --json" and returns the issue's current
// revision as an int64, decoded the same way --if-revision expects a caller
// to supply it (types.ParseRevisionToken on the wire "revision" string).
//
// "bd show --json" always wraps its result in a JSON array (cmd/bd/show.go's
// allDetails accumulator), even for a single id, so this parses the first
// JSON object the same trailing-content-tolerant way parseIssueJSON does
// (json.Unmarshal first, falling back to a json.Decoder that safely ignores
// the trailing "]" by reading exactly one JSON value) rather than
// json.Unmarshal-ing the whole array into a struct.
func bdShowRevision(t *testing.T, bd, dir, id string) int64 {
t.Helper()
cmd := exec.Command(bd, "show", id, "--json")
cmd.Dir = dir
cmd.Env = bdEnv(dir)
stdout, stderr, err := runCommandBuffers(t, cmd)
if err != nil {
t.Fatalf("bd show %s --json failed: %v\nstdout:\n%s\nstderr:\n%s", id, err, stdout.String(), stderr.String())
}
s := stdout.String()
start := strings.Index(s, "{")
if start < 0 {
t.Fatalf("no JSON object found in bd show %s --json output:\n%s", id, s)
}
var details struct {
Revision string `json:"revision"`
}
if err := json.Unmarshal([]byte(s[start:]), &details); err != nil {
dec := json.NewDecoder(strings.NewReader(s[start:]))
if decErr := dec.Decode(&details); decErr != nil {
t.Fatalf("failed to parse revision from bd show %s --json: %v\nraw: %s", id, decErr, s[start:])
}
}
rev, perr := types.ParseRevisionToken(details.Revision)
if perr != nil {
t.Fatalf("bd show %s --json returned an unparseable revision %q: %v", id, details.Revision, perr)
}
return rev
}
func revStr(rev int64) string { return strconv.FormatInt(rev, 10) }
// TestIfRevisionAdvertisedOnFourVerbs pins T4.1: --if-revision is a real,
// documented flag on all four verbs A8 adds it to, not an undocumented side
// channel a caller has to discover by reading source.
func TestIfRevisionAdvertisedOnFourVerbs(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", "h4")
for _, verb := range []string{"update", "close", "assign", "delete"} {
t.Run(verb, func(t *testing.T) {
out := bdRunOK(t, bd, dir, verb, "--help")
if !strings.Contains(out, "--if-revision") {
t.Errorf("bd %s --help does not advertise --if-revision:\n%s", verb, out)
}
})
}
}
// TestIfRevisionMatchAndMismatch pins T4.2 across all four verbs: a stale
// --if-revision token exits ExitGuardMismatch (13) and writes nothing at all
// (not the field, not the revision itself); the same token, once it is the
// issue's CURRENT revision, applies the write and the revision moves again.
func TestIfRevisionMatchAndMismatch(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", "mm")
t.Run("update", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Guarded update", "--type", "task", "--priority", "2")
rev0 := bdShowRevision(t, bd, dir, issue.ID)
// Bump the revision via an unguarded edit so rev0 is now stale.
bdUpdate(t, bd, dir, issue.ID, "--notes", "bump")
rev1 := bdShowRevision(t, bd, dir, issue.ID)
if rev1 == rev0 {
t.Fatalf("unguarded update did not change the revision")
}
out, code := bdUpdateFailCode(t, bd, dir, issue.ID, "--if-revision", revStr(rev0), "--priority", "3")
if code != ExitGuardMismatch {
t.Errorf("stale --if-revision exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if !strings.Contains(out, "revision mismatch") {
t.Errorf("mismatch error should say \"revision mismatch\", got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Priority != 2 {
t.Errorf("stale --if-revision update still applied: priority = %d, want 2", got.Priority)
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev1 {
t.Errorf("stale --if-revision update still advanced the revision: %d, want unchanged %d", got, rev1)
}
bdUpdate(t, bd, dir, issue.ID, "--if-revision", revStr(rev1), "--priority", "3")
if got := bdShow(t, bd, dir, issue.ID); got.Priority != 3 {
t.Errorf("matching --if-revision update did not apply: priority = %d, want 3", got.Priority)
}
if got := bdShowRevision(t, bd, dir, issue.ID); got == rev1 {
t.Errorf("matching --if-revision update did not advance the revision")
}
})
t.Run("close", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Guarded close", "--type", "task")
rev0 := bdShowRevision(t, bd, dir, issue.ID)
bdUpdate(t, bd, dir, issue.ID, "--notes", "bump")
rev1 := bdShowRevision(t, bd, dir, issue.ID)
out, code := bdRunFailCode(t, bd, dir, "close", issue.ID, "--if-revision", revStr(rev0))
if code != ExitGuardMismatch {
t.Errorf("stale --if-revision close exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if !strings.Contains(out, "revision mismatch") {
t.Errorf("mismatch error should say \"revision mismatch\", got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Status == types.StatusClosed {
t.Errorf("stale --if-revision close still closed the issue")
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev1 {
t.Errorf("stale --if-revision close still advanced the revision: %d, want unchanged %d", got, rev1)
}
bdRunOK(t, bd, dir, "close", issue.ID, "--if-revision", revStr(rev1))
if got := bdShow(t, bd, dir, issue.ID); got.Status != types.StatusClosed {
t.Errorf("matching --if-revision close did not apply: status = %s, want closed", got.Status)
}
})
t.Run("assign", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Guarded assign", "--type", "task")
rev0 := bdShowRevision(t, bd, dir, issue.ID)
bdUpdate(t, bd, dir, issue.ID, "--notes", "bump")
rev1 := bdShowRevision(t, bd, dir, issue.ID)
out, code := bdRunFailCode(t, bd, dir, "assign", issue.ID, "worker", "--if-revision", revStr(rev0))
if code != ExitGuardMismatch {
t.Errorf("stale --if-revision assign exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if !strings.Contains(out, "revision mismatch") {
t.Errorf("mismatch error should say \"revision mismatch\", got:\n%s", out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "" {
t.Errorf("stale --if-revision assign still applied: assignee = %q, want unassigned", got.Assignee)
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev1 {
t.Errorf("stale --if-revision assign still advanced the revision: %d, want unchanged %d", got, rev1)
}
bdRunOK(t, bd, dir, "assign", issue.ID, "worker", "--if-revision", revStr(rev1))
if got := bdShow(t, bd, dir, issue.ID); got.Assignee != "worker" {
t.Errorf("matching --if-revision assign did not apply: assignee = %q, want worker", got.Assignee)
}
})
t.Run("delete", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Guarded delete", "--type", "task")
rev0 := bdShowRevision(t, bd, dir, issue.ID)
bdUpdate(t, bd, dir, issue.ID, "--notes", "bump")
rev1 := bdShowRevision(t, bd, dir, issue.ID)
out, code := bdRunFailCode(t, bd, dir, "delete", issue.ID, "--if-revision", revStr(rev0), "--force")
if code != ExitGuardMismatch {
t.Errorf("stale --if-revision delete exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if !strings.Contains(out, "revision mismatch") {
t.Errorf("mismatch error should say \"revision mismatch\", got:\n%s", out)
}
// The row must still exist: `bd show` must still succeed.
bdShow(t, bd, dir, issue.ID)
bdRunOK(t, bd, dir, "delete", issue.ID, "--if-revision", revStr(rev1), "--force")
bdShowFail(t, bd, dir, issue.ID)
})
}
// TestIfRevisionComposesWithIfAssigneeIfStatus pins T4.5: on `bd update`,
// --if-revision composes with --if-assignee/--if-status as a conjunction —
// every guard present must hold, not just one of them, regardless of which
// guard happens to be the stale one.
func TestIfRevisionComposesWithIfAssigneeIfStatus(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", "cp")
issue := bdCreate(t, bd, dir, "Compose guards", "--type", "task")
bdUpdate(t, bd, dir, issue.ID, "--assignee", "alice")
rev := bdShowRevision(t, bd, dir, issue.ID)
t.Run("revision_and_assignee_match_but_status_does_not_still_refuses", func(t *testing.T) {
out, code := bdUpdateFailCode(t, bd, dir, issue.ID,
"--if-revision", revStr(rev), "--if-assignee", "alice", "--if-status", "in_progress",
"--priority", "3")
if code != ExitGuardMismatch {
t.Errorf("exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Priority == 3 {
t.Errorf("composed guard with one stale member still applied the write")
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev {
t.Errorf("composed guard refusal advanced the revision: %d, want unchanged %d", got, rev)
}
})
t.Run("assignee_and_status_match_but_revision_does_not_still_refuses", func(t *testing.T) {
out, code := bdUpdateFailCode(t, bd, dir, issue.ID,
"--if-revision", revStr(rev+1_000_000), "--if-assignee", "alice", "--if-status", "open",
"--priority", "3")
if code != ExitGuardMismatch {
t.Errorf("exit code = %d, want %d\n%s", code, ExitGuardMismatch, out)
}
if got := bdShow(t, bd, dir, issue.ID); got.Priority == 3 {
t.Errorf("composed guard with a stale revision still applied the write")
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev {
t.Errorf("composed guard refusal advanced the revision: %d, want unchanged %d", got, rev)
}
})
t.Run("all_three_guards_hold_applies", func(t *testing.T) {
bdUpdate(t, bd, dir, issue.ID,
"--if-revision", revStr(rev), "--if-assignee", "alice", "--if-status", "open",
"--priority", "3")
if got := bdShow(t, bd, dir, issue.ID); got.Priority != 3 {
t.Errorf("fully-matching composed guard did not apply: priority = %d, want 3", got.Priority)
}
})
}
// TestIfRevisionRejectsLabelAndParentEdits pins T4.6: `bd update --if-revision`
// (alone or composed with --if-assignee/--if-status) refuses when the ONLY
// edit riding with it is a label or parent change, because those edits do not
// run inside the guarded issues-row write. Refused before any write, exit 1
// (a flag-validation refusal, never 13 — 13 is reserved for an actual stale
// guard).
func TestIfRevisionRejectsLabelAndParentEdits(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", "lp")
issue := bdCreate(t, bd, dir, "Label/parent guard", "--type", "task")
rev := bdShowRevision(t, bd, dir, issue.ID)
t.Run("label_only_edit_rejected", func(t *testing.T) {
out, code := bdUpdateFailCode(t, bd, dir, issue.ID, "--if-revision", revStr(rev), "--add-label", "x")
if code != 1 {
t.Errorf("exit code = %d, want 1 (flag validation, not a guard mismatch)\n%s", code, out)
}
if !strings.Contains(out, "field update") {
t.Errorf("expected the field-update requirement in the error, got:\n%s", out)
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev {
t.Errorf("rejected label-only edit still wrote: revision = %d, want unchanged %d", got, rev)
}
})
t.Run("parent_only_edit_rejected", func(t *testing.T) {
parent := bdCreate(t, bd, dir, "Would-be parent", "--type", "task")
out, code := bdUpdateFailCode(t, bd, dir, issue.ID, "--if-revision", revStr(rev), "--parent", parent.ID)
if code != 1 {
t.Errorf("exit code = %d, want 1\n%s", code, out)
}
if !strings.Contains(out, "field update") {
t.Errorf("expected the field-update requirement in the error, got:\n%s", out)
}
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev {
t.Errorf("rejected parent-only edit still wrote: revision = %d, want unchanged %d", got, rev)
}
})
}
// TestIfRevisionMultiIDRejected pins T4.8 on the three verbs that accept more
// than one id (assign is cobra.ExactArgs(2): id + assignee, so it can never
// carry a second id). A single --if-revision token names one row's version;
// refused before any write rather than applying it to only the first id a
// batch happens to resolve.
func TestIfRevisionMultiIDRejected(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", "mi")
t.Run("update", func(t *testing.T) {
a := bdCreate(t, bd, dir, "Multi A", "--type", "task")
b := bdCreate(t, bd, dir, "Multi B", "--type", "task")
revA, revB := bdShowRevision(t, bd, dir, a.ID), bdShowRevision(t, bd, dir, b.ID)
out, code := bdUpdateFailCode(t, bd, dir, a.ID, b.ID, "--if-revision", revStr(revA), "--priority", "3")
if code != 1 {
t.Errorf("multi-id --if-revision update exit code = %d, want 1\n%s", code, out)
}
if !strings.Contains(out, "one issue only") {
t.Errorf("expected the one-id rule named in the error, got:\n%s", out)
}
if got := bdShowRevision(t, bd, dir, a.ID); got != revA {
t.Errorf("rejected multi-id update still wrote to %s", a.ID)
}
if got := bdShowRevision(t, bd, dir, b.ID); got != revB {
t.Errorf("rejected multi-id update still wrote to %s", b.ID)
}
})
t.Run("close", func(t *testing.T) {
a := bdCreate(t, bd, dir, "Multi close A", "--type", "task")
b := bdCreate(t, bd, dir, "Multi close B", "--type", "task")
rev := bdShowRevision(t, bd, dir, a.ID)
out, code := bdRunFailCode(t, bd, dir, "close", a.ID, b.ID, "--if-revision", revStr(rev))
if code != 1 {
t.Errorf("multi-id --if-revision close exit code = %d, want 1\n%s", code, out)
}
if !strings.Contains(out, "one issue only") {
t.Errorf("expected the one-id rule named in the error, got:\n%s", out)
}
if got := bdShow(t, bd, dir, a.ID); got.Status == types.StatusClosed {
t.Errorf("rejected multi-id close still closed %s", a.ID)
}
if got := bdShow(t, bd, dir, b.ID); got.Status == types.StatusClosed {
t.Errorf("rejected multi-id close still closed %s", b.ID)
}
})
t.Run("delete", func(t *testing.T) {
a := bdCreate(t, bd, dir, "Multi delete A", "--type", "task")
b := bdCreate(t, bd, dir, "Multi delete B", "--type", "task")
rev := bdShowRevision(t, bd, dir, a.ID)
out, code := bdRunFailCode(t, bd, dir, "delete", a.ID, b.ID, "--if-revision", revStr(rev), "--force")
if code != 1 {
t.Errorf("multi-id --if-revision delete exit code = %d, want 1\n%s", code, out)
}
if !strings.Contains(out, "one issue only") {
t.Errorf("expected the one-id rule named in the error, got:\n%s", out)
}
bdShow(t, bd, dir, a.ID)
bdShow(t, bd, dir, b.ID)
})
}
// TestRevisionRemintMatrix pins T4.10: the revision is a token over the
// issues-row write, not over "anything happened to this id". A field update,
// a metadata edit, a close and a reopen must each mint a fresh revision (so a
// caller who read one of those as "no-op" cannot keep replaying a now-stale
// --if-revision); a label edit, a dependency edit and the derived is_blocked
// flag must NOT, because none of those touch the issues-row write the token
// guards.
func TestRevisionRemintMatrix(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", "rm")
t.Run("field_update_changes_revision", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Field update", "--type", "task")
rev := bdShowRevision(t, bd, dir, issue.ID)
bdUpdate(t, bd, dir, issue.ID, "--priority", "1")
if got := bdShowRevision(t, bd, dir, issue.ID); got == rev {
t.Errorf("field update did not change the revision")
}
})
t.Run("metadata_edit_changes_revision", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Metadata edit", "--type", "task")
rev := bdShowRevision(t, bd, dir, issue.ID)
bdUpdate(t, bd, dir, issue.ID, "--set-metadata", "k=v")
if got := bdShowRevision(t, bd, dir, issue.ID); got == rev {
t.Errorf("metadata edit did not change the revision")
}
})
t.Run("close_changes_revision", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Close remint", "--type", "task")
rev := bdShowRevision(t, bd, dir, issue.ID)
bdClose(t, bd, dir, issue.ID)
if got := bdShowRevision(t, bd, dir, issue.ID); got == rev {
t.Errorf("close did not change the revision")
}
})
t.Run("reopen_changes_revision", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Reopen remint", "--type", "task")
bdClose(t, bd, dir, issue.ID)
rev := bdShowRevision(t, bd, dir, issue.ID)
bdReopen(t, bd, dir, issue.ID)
if got := bdShowRevision(t, bd, dir, issue.ID); got == rev {
t.Errorf("reopen did not change the revision")
}
})
t.Run("label_edit_does_not_change_revision", func(t *testing.T) {
issue := bdCreate(t, bd, dir, "Label no-remint", "--type", "task")
rev := bdShowRevision(t, bd, dir, issue.ID)
bdLabel(t, bd, dir, "add", issue.ID, "x")
if got := bdShowRevision(t, bd, dir, issue.ID); got != rev {
t.Errorf("label edit changed the revision: %d, want unchanged %d", got, rev)
}
})
t.Run("dependency_and_is_blocked_do_not_change_revision", func(t *testing.T) {
blocker := bdCreate(t, bd, dir, "Blocker", "--type", "task")
blocked := bdCreate(t, bd, dir, "Blocked", "--type", "task")
rev := bdShowRevision(t, bd, dir, blocked.ID)
bdDep(t, bd, dir, "add", blocked.ID, blocker.ID)
if got := bdShowRevision(t, bd, dir, blocked.ID); got != rev {
t.Errorf("adding a dependency changed the dependent's revision: %d, want unchanged %d", got, rev)
}
// "bd blocked" is the derived is_blocked view (blocked_by/blocked_by_count
// are computed over the dependency graph): confirms the dependency
// actually produced the blocking relationship this subtest is about,
// independent of whichever column or query answers it.
if entries := bdBlockedJSON(t, bd, dir); !blockedJSONContains(entries, blocked.ID) {
t.Fatalf("expected %s to appear in \"bd blocked\" once it depends on an open issue: %v", blocked.ID, entries)
}
if gotRev := bdShowRevision(t, bd, dir, blocked.ID); gotRev != rev {
t.Errorf("becoming blocked changed the revision: %d, want unchanged %d", gotRev, rev)
}
bdClose(t, bd, dir, blocker.ID)
if entries := bdBlockedJSON(t, bd, dir); blockedJSONContains(entries, blocked.ID) {
t.Fatalf("expected %s to drop out of \"bd blocked\" once its dependency closed: %v", blocked.ID, entries)
}
if gotRev := bdShowRevision(t, bd, dir, blocked.ID); gotRev != rev {
t.Errorf("becoming unblocked changed the dependent's revision: %d, want unchanged %d", gotRev, rev)
}
})
}
// blockedJSONContains reports whether id appears among bdBlockedJSON's
// entries (each a marshaled types.BlockedIssue, so "id" is Issue.ID's own
// json tag, not BlockedIssue's).
func blockedJSONContains(entries []map[string]interface{}, id string) bool {
for _, e := range entries {
if got, _ := e["id"].(string); got == id {
return true
}
}
return false
}

223
cmd/bd/if_revision_test.go Normal file
View file

@ -0,0 +1,223 @@
package main
import (
"encoding/json"
"errors"
"os"
"strings"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/issueops"
)
// lastJSONLine returns the final non-empty line of out, which is where
// reportIfRevisionFailure writes its machine body (the human line comes
// first; see reportIfRevisionFailure's own doc comment).
func lastJSONLine(t *testing.T, out string) string {
t.Helper()
lines := strings.Split(strings.TrimRight(out, "\n"), "\n")
for i := len(lines) - 1; i >= 0; i-- {
if strings.TrimSpace(lines[i]) != "" {
return lines[i]
}
}
t.Fatalf("no non-empty line in output:\n%s", out)
return ""
}
// decodeIfRevisionBody decodes line as either the flat shape (schema_version
// beside the body's own fields) or the BD_JSON_ENVELOPE=1 shape
// ({"schema_version":N,"data":{...}}), returning the body fields as a plain
// map so a test can assert JSON TYPES (float64 for a number, never a string)
// without fighting a typed struct's own unmarshal coercion.
func decodeIfRevisionBody(t *testing.T, line string, enveloped bool) map[string]interface{} {
t.Helper()
var whole map[string]interface{}
if err := json.Unmarshal([]byte(line), &whole); err != nil {
t.Fatalf("decode JSON line: %v\nline: %s", err, line)
}
if !enveloped {
return whole
}
data, ok := whole["data"].(map[string]interface{})
if !ok {
t.Fatalf("enveloped line has no \"data\" object: %s", line)
}
return data
}
// TestIfRevisionEnvelopeGascityContract pins T4.3: the stderr JSON a refused
// --if-revision write emits, in both the flat and the BD_JSON_ENVELOPE=1
// shapes, must carry integer revisions and a `code` field exactly as
// gascity's bdstore_conditional.go classifier decodes them. A string
// revision -- the most tempting "it's just a big number" mistake -- makes
// gascity's json.Decoder fail closed on the WHOLE object
// (bdstore_conditional.go:134-139), discarding even the `code` beside it.
func TestIfRevisionEnvelopeGascityContract(t *testing.T) {
oldJSON := jsonOutput
t.Cleanup(func() { jsonOutput = oldJSON })
jsonOutput = true
runCase := func(t *testing.T, enveloped bool) {
t.Helper()
oldEnv, had := os.LookupEnv("BD_JSON_ENVELOPE")
t.Cleanup(func() {
if had {
os.Setenv("BD_JSON_ENVELOPE", oldEnv)
} else {
os.Unsetenv("BD_JSON_ENVELOPE")
}
})
if enveloped {
os.Setenv("BD_JSON_ENVELOPE", "1")
} else {
os.Unsetenv("BD_JSON_ENVELOPE")
}
t.Run("stale_revision_carries_integer_expected_and_current", func(t *testing.T) {
var reported error
out := captureStderr(t, func() {
reported, _ = reportIfRevisionFailure("updating", "bd-1", &issueops.VersionMismatchError{Expected: 5, Current: 7})
})
ee, ok := reported.(*exitError)
if !ok || ee.Code != ExitGuardMismatch {
t.Fatalf("reported error = %#v, want *exitError{Code: %d}", reported, ExitGuardMismatch)
}
if !strings.Contains(out, "precondition failed") {
t.Errorf("human line must contain gascity's code-less-fallback phrase \"precondition failed\", got:\n%s", out)
}
body := decodeIfRevisionBody(t, lastJSONLine(t, out), enveloped)
if body["code"] != ifRevisionCodePreconditionFailed {
t.Errorf("code = %v, want %q", body["code"], ifRevisionCodePreconditionFailed)
}
if body["id"] != "bd-1" {
t.Errorf("id = %v, want bd-1", body["id"])
}
expected, ok := body["expected_revision"].(float64)
if !ok {
t.Fatalf("expected_revision is %T (%v), want a JSON number -- a string here makes gascity's decoder fail closed on the whole object", body["expected_revision"], body["expected_revision"])
}
if expected != 5 {
t.Errorf("expected_revision = %v, want 5", expected)
}
current, ok := body["current_revision"].(float64)
if !ok {
t.Fatalf("current_revision is %T (%v), want a JSON number", body["current_revision"], body["current_revision"])
}
if current != 7 {
t.Errorf("current_revision = %v, want 7", current)
}
// The raw bytes must never show a quoted number either -- a
// correct float64 decode does not rule out "5" (json.Unmarshal
// happily coerces neither direction here, but a regression that
// switched the struct field to string would still decode into
// interface{} as a string, which the type assertion above already
// catches; this is the belt to that suspenders).
if strings.Contains(lastJSONLine(t, out), `"expected_revision":"`) {
t.Errorf("expected_revision is quoted in the raw JSON, want a bare integer:\n%s", out)
}
})
t.Run("stale_assignee_or_status_carries_no_revision_fields", func(t *testing.T) {
var reported error
out := captureStderr(t, func() {
reported, _ = reportIfRevisionFailure("updating", "bd-2", storage.ErrAssigneeMismatch)
})
ee, ok := reported.(*exitError)
if !ok || ee.Code != ExitGuardMismatch {
t.Fatalf("reported error = %#v, want *exitError{Code: %d}", reported, ExitGuardMismatch)
}
body := decodeIfRevisionBody(t, lastJSONLine(t, out), enveloped)
if body["code"] != ifRevisionCodePreconditionFailed {
t.Errorf("code = %v, want %q", body["code"], ifRevisionCodePreconditionFailed)
}
if _, present := body["expected_revision"]; present {
t.Errorf("expected_revision must be absent (omitempty) for a non-revision guard, got %v", body["expected_revision"])
}
if _, present := body["current_revision"]; present {
t.Errorf("current_revision must be absent (omitempty) for a non-revision guard, got %v", body["current_revision"])
}
})
t.Run("schema_version_is_present_and_an_integer", func(t *testing.T) {
out := captureStderr(t, func() {
_, _ = reportIfRevisionFailure("updating", "bd-3", &issueops.VersionMismatchError{Expected: 1, Current: 2})
})
var whole map[string]interface{}
if err := json.Unmarshal([]byte(lastJSONLine(t, out)), &whole); err != nil {
t.Fatalf("decode: %v", err)
}
sv, ok := whole["schema_version"].(float64)
if !ok || sv != float64(JSONSchemaVersion) {
t.Errorf("schema_version = %v, want %d", whole["schema_version"], JSONSchemaVersion)
}
})
}
t.Run("flat", func(t *testing.T) { runCase(t, false) })
t.Run("enveloped_BD_JSON_ENVELOPE", func(t *testing.T) { runCase(t, true) })
}
// TestIfRevisionUnsupportedBackendCode pins T4.9: a backend whose Lifecycle
// cannot honor ExpectedVersion at all (issueops.ErrUnsupported) must report
// "conditional_write_unsupported" and exit 1 -- never ExitGuardMismatch,
// which promises callers "a racer won, do not retry", and never a silent
// unconditional fallback that drops the guard on the floor.
func TestIfRevisionUnsupportedBackendCode(t *testing.T) {
oldJSON := jsonOutput
t.Cleanup(func() { jsonOutput = oldJSON })
jsonOutput = true
var reported error
var ok bool
out := captureStderr(t, func() {
reported, ok = reportIfRevisionFailure("deleting", "bd-9", &issueops.ErrUnsupported{Op: "Delete.ExpectedVersion", Backend: "stub"})
})
if !ok {
t.Fatalf("reportIfRevisionFailure did not recognize issueops.ErrUnsupported as a guard outcome")
}
ee, isExitErr := reported.(*exitError)
if !isExitErr || ee.Code != 1 {
t.Fatalf("reported error = %#v, want *exitError{Code: 1}", reported)
}
if !strings.Contains(out, "conditional write unsupported") {
t.Errorf("human line should say the write is unsupported, got:\n%s", out)
}
body := decodeIfRevisionBody(t, lastJSONLine(t, out), false)
if body["code"] != ifRevisionCodeUnsupported {
t.Errorf("code = %v, want %q", body["code"], ifRevisionCodeUnsupported)
}
if _, present := body["expected_revision"]; present {
t.Errorf("expected_revision must be absent for an unsupported-backend refusal, got %v", body["expected_revision"])
}
// classifyIfRevisionFailure is reportIfRevisionFailure's own classifier;
// pinned directly too so a future refactor that bypasses the report
// function still has this assertion on the mapping itself.
code, _, expected, current, classified := classifyIfRevisionFailure(&issueops.ErrUnsupported{Op: "x", Backend: "y"})
if !classified || code != ifRevisionCodeUnsupported {
t.Errorf("classifyIfRevisionFailure(ErrUnsupported) = %q, %v, want %q, true", code, classified, ifRevisionCodeUnsupported)
}
if expected != nil || current != nil {
t.Errorf("classifyIfRevisionFailure(ErrUnsupported) revisions = %v, %v, want nil, nil", expected, current)
}
}
// TestClassifyIfRevisionFailureUnrelatedError pins ok=false for an error that
// is neither a guard outcome nor an unsupported-backend signal: the caller's
// own (unrelated) failure handling must run unchanged, and nothing here may
// claim the error as its own.
func TestClassifyIfRevisionFailureUnrelatedError(t *testing.T) {
if _, _, _, _, ok := classifyIfRevisionFailure(nil); ok {
t.Errorf("classifyIfRevisionFailure(nil) ok = true, want false")
}
if _, _, _, _, ok := classifyIfRevisionFailure(errUnrelatedForIfRevisionTest); ok {
t.Errorf("classifyIfRevisionFailure(unrelated error) ok = true, want false")
}
if reported, ok := reportIfRevisionFailure("updating", "bd-4", errUnrelatedForIfRevisionTest); ok || reported != nil {
t.Errorf("reportIfRevisionFailure(unrelated error) = %v, %v, want nil, false", reported, ok)
}
}
var errUnrelatedForIfRevisionTest = errors.New("boom: unrelated failure")

View file

@ -217,7 +217,7 @@ func burnMultipleMolecules(ctx context.Context, moleculeIDs []string, dryRun, fo
issueIDs = append(issueIDs, issue.ID)
}
if err := deleteBatch(nil, issueIDs, true, false, false, false, false, "mol burn"); err != nil {
if err := deleteBatch(nil, issueIDs, true, false, false, false, false, nil, "mol burn"); err != nil {
return HandleErrorRespectJSON("%v", err)
}
batchResult.TotalDeleted += len(issueIDs)
@ -366,7 +366,7 @@ func burnPersistentMolecule(ctx context.Context, resolvedID string, dryRun, forc
}
}
if err := deleteBatch(nil, issueIDs, true, false, false, jsonOutput, false, "mol burn"); err != nil {
if err := deleteBatch(nil, issueIDs, true, false, false, jsonOutput, false, nil, "mol burn"); err != nil {
return HandleErrorRespectJSON("%v", err)
}
return nil

View file

@ -66,11 +66,71 @@ func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates
})
}
func runAssignProxiedServer(ctx context.Context, args []string, force bool) error {
// proxiedAssign is bd assign's proxied-server write. A8 (beads#4682) routes
// the write through issueops.Lifecycle.Update — the same role the direct
// route's writeOps call uses — instead of the raw
// proxiedUpdateIssueFields/UpdateIssue path, so --if-revision has a checked
// write to guard (bd assign had no compare-and-set surface at all before
// this). The pre-read and the live-claim reassign fence (bd-98s5c) still run
// first over the same UnitOfWorkProvider surface proxiedMutateIssue always
// used, rather than the separate issue-query role's accessor, so this verb's
// capability footprint is unchanged.
func proxiedAssign(ctx context.Context, id, assignee string, force bool, ifRevision *int64) (*types.Issue, error) {
if uowProvider == nil {
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
}
_, 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)
}
if rerr != nil {
return struct{}{}, fmt.Errorf("resolving %s: %w", id, rerr)
}
if verr := validateIssueUpdatable(id, current); verr != nil {
return struct{}{}, verr
}
if verr := validateIssueReassignable(id, current, actor, assignee,
uowClaimPoolAliases(ctx, uw), force); verr != nil {
return struct{}{}, verr
}
return struct{}{}, nil
})
if err != nil {
return nil, err
}
ops, err := proxiedIssueLifecycle()
if err != nil {
return nil, err
}
result, err := runCommandUpdateMutation(ctx, ops, commandUpdateMutation{
actor: actor,
issueID: id,
patch: issueops.IssuePatch{
Assignee: issueops.Field[string]{Set: true, Value: assignee},
},
force: force,
expectedVersion: ifRevision,
provenance: "bd: assign " + id,
})
if err != nil {
return nil, err
}
commandDidWrite.Store(true)
return result.Issue, nil
}
func runAssignProxiedServer(ctx context.Context, args []string, force bool, ifRevision *int64) error {
id := args[0]
assignee := args[1]
updated, err := proxiedUpdateIssueFields(ctx, id, "bd: assign "+id, map[string]any{"assignee": assignee}, force)
updated, err := proxiedAssign(ctx, id, assignee, force, ifRevision)
if err != nil {
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("assigning", id, err); ok {
return reported
}
}
return HandleErrorRespectJSON("assign %s: %v", id, err)
}
if jsonOutput {

View file

@ -326,7 +326,7 @@ var proxiedLookupCommands = []struct {
{
name: "assign",
run: func(ctx context.Context) error {
return runAssignProxiedServer(ctx, []string{stubMissingID, "someone"}, false)
return runAssignProxiedServer(ctx, []string{stubMissingID, "someone"}, false, nil)
},
wantNotFound: "Error: assign bd-missing: issue bd-missing not found",
wantHardErr: "Error: assign bd-missing: resolving bd-missing: connection reset by peer",

View file

@ -40,6 +40,10 @@ type commandUpdateMutation struct {
force bool
expectedAssignee *string
expectedStatus *issueops.Status
// expectedVersion is the A8 --if-revision guard (beads#4682 design doc
// item 4): nil disables the check; a non-nil value composes with
// expectedAssignee/expectedStatus, all of which must hold.
expectedVersion *int64
// provenance names the history entry the write records. Empty takes the
// backend's default, which is what the direct route wants; the proxied
// route spells the message it has always written.
@ -66,6 +70,7 @@ func runCommandUpdateMutation(ctx context.Context, updater commandIssueUpdater,
ForceNotesOverwrite: mutation.force && mutation.patch.Notes.Set,
ExpectedAssignee: mutation.expectedAssignee,
ExpectedStatus: mutation.expectedStatus,
ExpectedVersion: mutation.expectedVersion,
Provenance: mutation.provenance,
})
}
@ -398,14 +403,20 @@ pointless).`,
return nil
}
// Conditional-update guards (bd-wsqvw): validated against the same
// status set as --status, mutually exclusive with --claim (which is
// its own compare-and-set), and only meaningful with a field update
// to ride on.
ifAssignee, ifStatus, err := updateGuardsFromFlags(cmd, claimFlag, updates)
// Conditional-update guards (bd-wsqvw, and A8's --if-revision,
// beads#4682): validated against the same status set as --status,
// mutually exclusive with --claim (which is its own compare-and-set),
// and only meaningful with a field update to ride on.
ifAssignee, ifStatus, ifRevision, err := updateGuardsFromFlags(cmd, claimFlag, updates)
if err != nil {
return err
}
// A8: "one id only" (T4.8) — a single --if-revision token names one
// row's version, so applying it to every id in a multi-id batch would
// guard only the first write the batch happened to resolve.
if err := requireSingleIfRevisionID(ifRevision, args); err != nil {
return err
}
var expectedStatus *issueops.Status
if ifStatus != nil {
expected := issueops.Status(*ifStatus)
@ -548,8 +559,23 @@ pointless).`,
force: forceFlag,
expectedAssignee: ifAssignee,
expectedStatus: expectedStatus,
expectedVersion: ifRevision,
})
if updateErr != nil {
// A8 (beads#4682): an active --if-revision guard reports
// through gascity's dedicated conditional-write envelope
// instead of the generic per-ID batch report below —
// requireSingleIfRevisionID already guarantees args has
// exactly one id when ifRevision is set, so reporting and
// returning here is equivalent to falling through to
// reportUpdateFailures for this one failure.
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("updating", id, updateErr); ok {
closeIfUnmutated(result)
closePendingResults()
return reported
}
}
failureText := fmt.Sprintf("updating issue: %v", updateErr)
if errors.Is(updateErr, issueops.ErrNotesOverwrite) {
// The contract's AuthorizeNotesOverwrite fence refused
@ -840,20 +866,25 @@ func warnNotesReplacement(id string) {
}
// ExitGuardMismatch is the exit code when a `bd update` run failed solely
// because --if-assignee/--if-status guards did not match: the precondition no
// longer held, nothing was written, and retrying is pointless — another actor
// won the race. Scripts branch on it to tell "racer won, skip gracefully"
// (13) from infra failure (1, retry/abort). Mixed batches — any failure that
// is NOT a guard mismatch — exit 1, the conservative "something needs a
// retry" verdict. The stderr line carries the machine-greppable sentinel
// text ("assignee mismatch" / "status mismatch") either way.
// because --if-assignee/--if-status/--if-revision guards did not match: the
// precondition no longer held, nothing was written, and retrying is
// pointless — another actor won the race. Scripts branch on it to tell
// "racer won, skip gracefully" (13) from infra failure (1, retry/abort).
// Mixed batches — any failure that is NOT a guard mismatch — exit 1, the
// conservative "something needs a retry" verdict. The stderr line carries the
// machine-greppable sentinel text ("assignee mismatch" / "status mismatch" /
// "revision mismatch") either way. `bd close`, `bd assign` and `bd delete`
// reuse this same constant for their own --if-revision guard (A8, beads#4682).
const ExitGuardMismatch = 13
// isGuardMismatch reports whether err is a bd-wsqvw conditional-update guard
// refusal (stale --if-assignee/--if-status), the failure class that exits
// isGuardMismatch reports whether err is a conditional-write guard refusal —
// bd-wsqvw's stale --if-assignee/--if-status, or A8's stale --if-revision
// (storage.ErrVersionMismatch) — the failure class that exits
// ExitGuardMismatch instead of 1.
func isGuardMismatch(err error) bool {
return errors.Is(err, storage.ErrAssigneeMismatch) || errors.Is(err, storage.ErrStatusMismatch)
return errors.Is(err, storage.ErrAssigneeMismatch) ||
errors.Is(err, storage.ErrStatusMismatch) ||
errors.Is(err, storage.ErrVersionMismatch)
}
// updateIDFailure records one issue ID that could not be updated and why.
@ -953,16 +984,18 @@ func toJSONValue(s string) json.RawMessage {
}
// updateGuardsFromFlags reads the bd-wsqvw conditional-update guards
// (--if-assignee/--if-status) with presence detected via Changed(), so
// `--if-assignee ""` is a real guard meaning "expected unassigned" rather than
// "no guard" (the unclaim.go idiom). It rejects combining guards with --claim
// (--claim is its own compare-and-set with claim-pool semantics; the guards
// would silently duplicate or contradict it) and guards with no regular field
// update to ride on (the CAS applies to the issues-row UPDATE; label and
// parent edits run outside it and would not be guarded). An --if-status value
// is validated against the same built-in + custom status set as --status, so a
// typo fails fast instead of mismatching forever.
func updateGuardsFromFlags(cmd *cobra.Command, claimFlag bool, updates map[string]interface{}) (ifAssignee, ifStatus *string, err error) {
// (--if-assignee/--if-status) and A8's --if-revision (beads#4682) with
// presence detected via Changed(), so `--if-assignee ""` is a real guard
// meaning "expected unassigned" rather than "no guard" (the unclaim.go
// idiom). It rejects combining any guard with --claim (--claim is its own
// compare-and-set with claim-pool semantics; the guards would silently
// duplicate or contradict it) and guards with no regular field update to ride
// on (the CAS applies to the issues-row UPDATE; label and parent edits run
// outside it and would not be guarded). An --if-status value is validated
// against the same built-in + custom status set as --status, so a typo fails
// fast instead of mismatching forever; --if-revision is validated as a
// decimal int64 the same way.
func updateGuardsFromFlags(cmd *cobra.Command, claimFlag bool, updates map[string]interface{}) (ifAssignee, ifStatus *string, ifRevision *int64, err error) {
if cmd.Flags().Changed("if-assignee") {
v, _ := cmd.Flags().GetString("if-assignee")
ifAssignee = &v
@ -976,15 +1009,19 @@ func updateGuardsFromFlags(cmd *cobra.Command, claimFlag bool, updates map[strin
}
}
if !types.Status(v).IsValidWithCustom(customStatuses) {
return nil, nil, HandleErrorRespectJSON("invalid --if-status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", v)
return nil, nil, nil, HandleErrorRespectJSON("invalid --if-status %q (built-in: open, in_progress, blocked, deferred, closed, pinned, hooked; or configure custom statuses via 'bd config set status.custom')", v)
}
ifStatus = &v
}
if ifAssignee == nil && ifStatus == nil {
return nil, nil, nil
ifRevision, err = parseIfRevisionFlag(cmd)
if err != nil {
return nil, nil, nil, err
}
if ifAssignee == nil && ifStatus == nil && ifRevision == nil {
return nil, nil, nil, nil
}
if claimFlag {
return nil, nil, HandleErrorRespectJSON("cannot combine --if-assignee/--if-status with --claim (--claim is already an atomic compare-and-set)")
return nil, nil, nil, HandleErrorRespectJSON("cannot combine --if-assignee/--if-status/--if-revision with --claim (--claim is already an atomic compare-and-set)")
}
hasFieldUpdate := false
for k := range updates {
@ -995,9 +1032,9 @@ func updateGuardsFromFlags(cmd *cobra.Command, claimFlag bool, updates map[strin
}
}
if !hasFieldUpdate {
return nil, nil, HandleErrorRespectJSON("--if-assignee/--if-status require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard")
return nil, nil, nil, HandleErrorRespectJSON("--if-assignee/--if-status/--if-revision require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard")
}
return ifAssignee, ifStatus, nil
return ifAssignee, ifStatus, ifRevision, nil
}
func init() {
@ -1043,6 +1080,9 @@ func init() {
// Conditional (compare-and-set) update guards (bd-wsqvw)
updateCmd.Flags().String("if-assignee", "", "Apply the update only if the current assignee equals this value (--if-assignee '' requires unassigned); a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim")
updateCmd.Flags().String("if-status", "", "Apply the update only if the current status equals this value; a mismatch writes nothing and exits 13 (vs 1 for other failures). Requires a field update; cannot combine with --claim")
// A8 (beads#4682): composes with --if-assignee/--if-status above — all
// guards present must hold, or nothing is written.
updateCmd.Flags().String("if-revision", "", ifRevisionFlagHelp+" Composes with --if-assignee/--if-status: all guards present must hold.")
// --force and --if-assignee are NOT mutually exclusive: --force still
// drives the close-policy and notes-overwrite halves (runCommandUpdateMutation),
// and the contract itself refuses ForceAssigneeTransfer alongside

View file

@ -35,6 +35,9 @@ type updateInput struct {
// guard).
ifAssignee *string
ifStatus *string
// A8's --if-revision guard (beads#4682); composes with ifAssignee/ifStatus
// above, all of which must hold.
ifRevision *int64
// bd-98s5c: --force bypasses the live-claim reassign fence only when no
// --if-assignee guard rides the command; it also opts into the notes
// overwrite and close-policy bypasses (runCommandUpdateMutation).
@ -272,12 +275,19 @@ func gatherUpdateInput(ctx context.Context, cmd *cobra.Command) (*updateInput, e
}
in.ifStatus = &v
}
if in.ifAssignee != nil || in.ifStatus != nil {
// A8's --if-revision guard (beads#4682), same Changed()-detected presence
// idiom and validated as the decimal int64 types.ParseRevisionToken
// expects, mirroring the non-proxied path's updateGuardsFromFlags.
in.ifRevision, err = parseIfRevisionFlag(cmd)
if err != nil {
return nil, err
}
if in.ifAssignee != nil || in.ifStatus != nil || in.ifRevision != nil {
if in.claim {
return nil, HandleErrorRespectJSON("cannot combine --if-assignee/--if-status with --claim (--claim is already an atomic compare-and-set)")
return nil, HandleErrorRespectJSON("cannot combine --if-assignee/--if-status/--if-revision with --claim (--claim is already an atomic compare-and-set)")
}
if len(in.fields) == 0 && !in.hasAppendNotes && len(in.mergeMetadataIn) == 0 && len(in.setMetadata) == 0 && len(in.unsetMetadata) == 0 {
return nil, HandleErrorRespectJSON("--if-assignee/--if-status require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard")
return nil, HandleErrorRespectJSON("--if-assignee/--if-status/--if-revision require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard")
}
}
return in, nil

View file

@ -28,6 +28,11 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
fmt.Println("No updates specified")
return nil
}
// A8 (beads#4682): "one id only" (T4.8), mirroring the direct route's
// requireSingleIfRevisionID call in update.go.
if err := requireSingleIfRevisionID(in.ifRevision, args); err != nil {
return err
}
// Derive success-output format from the global JSON decision (--json OR
// --format json OR config), the same signal reportUpdateFailures uses, so
@ -129,6 +134,7 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
force: in.force,
expectedAssignee: in.ifAssignee,
expectedStatus: expectedStatus,
expectedVersion: in.ifRevision,
provenance: fmt.Sprintf("bd: update %s", id),
})
if err != nil {
@ -140,6 +146,18 @@ func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*ty
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, nil, err
}
// A8: an active --if-revision guard reports through gascity's
// dedicated conditional-write envelope instead of the generic
// updateIDFailure batch shape — requireSingleIfRevisionID already
// guarantees args has exactly one id, so returning the reported exit
// error here (which the caller's `if err != nil { return err }`
// propagates straight out) is equivalent to the generic path for this
// one id.
if in.ifRevision != nil {
if reported, ok := reportIfRevisionFailure("updating", id, err); ok {
return nil, nil, reported
}
}
return nil, proxiedUpdateFailure(id, in.claim, err), nil
}
updated := result.Issue

View file

@ -816,7 +816,7 @@ func runWispGC(cmd *cobra.Command, args []string) error {
// protection is only enforced in the pre-filter; cascade bypasses it).
// Without cascade the list is deleted exactly as filtered and live
// dependents are orphaned (edges dropped, is_blocked recomputed).
if err := deleteBatch(nil, ids, true, false, false, jsonOutput, false, "wisp gc"); err != nil {
if err := deleteBatch(nil, ids, true, false, false, jsonOutput, false, nil, "wisp gc"); err != nil {
return HandleError("%v", err)
}
return nil
@ -986,7 +986,7 @@ func runWispPurgeClosed(ctx context.Context, dryRun bool, force bool, excludeTyp
// Without cascade, closed wisps are deleted and live dependents are
// orphaned (edges dropped, is_blocked recomputed) — the same semantics as
// a plain `bd delete`.
if err := deleteBatch(nil, ids, force, dryRun, false, jsonOutput, false, "wisp gc --closed"); err != nil {
if err := deleteBatch(nil, ids, force, dryRun, false, jsonOutput, false, nil, "wisp gc --closed"); err != nil {
return HandleError("%v", err)
}

View file

@ -1159,7 +1159,7 @@ func TestParityUpdateGuardsRequireFieldUpdate(t *testing.T) {
if res.exitCode != 1 {
t.Fatalf("exit = %d, want 1; stderr=%s", res.exitCode, res.stderr)
}
const want = "Error: --if-assignee/--if-status require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard\n"
const want = "Error: --if-assignee/--if-status/--if-revision require at least one field update (e.g. -a, -s); label and parent edits are not covered by the guard\n"
if res.stderr != want {
t.Errorf("stderr = %q, want %q", res.stderr, want)
}
@ -1184,7 +1184,7 @@ func TestParityUpdateGuardsRejectClaim(t *testing.T) {
if res.exitCode != 1 {
t.Fatalf("exit = %d, want 1; stderr=%s", res.exitCode, res.stderr)
}
const want = "Error: cannot combine --if-assignee/--if-status with --claim (--claim is already an atomic compare-and-set)\n"
const want = "Error: cannot combine --if-assignee/--if-status/--if-revision with --claim (--claim is already an atomic compare-and-set)\n"
if res.stderr != want {
t.Errorf("stderr = %q, want %q", res.stderr, want)
}

View file

@ -51,6 +51,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})

View file

@ -708,7 +708,7 @@ func (u *issueUseCaseImpl) ApplyUpdate(ctx context.Context, id string, spec Upda
return nil, fmt.Errorf("%w: issue %s", storage.ErrNotFound, id)
}
if spec.ExpectedVersion != nil && current.RowVersion != *spec.ExpectedVersion {
return nil, fmt.Errorf("%w: expected %d, got %d", storage.ErrVersionMismatch, *spec.ExpectedVersion, current.RowVersion)
return nil, &storage.VersionMismatchError{Expected: *spec.ExpectedVersion, Current: current.RowVersion}
}
if spec.ExpectedAssignee != nil && !validation.ActorMatches(current.Assignee, *spec.ExpectedAssignee) {
return nil, fmt.Errorf("%w: %s is held by %q, expected %q",

View file

@ -52,6 +52,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})

View file

@ -42,7 +42,7 @@ func CheckVersionInTx(ctx context.Context, tx DBTX, id string, expected int64) e
return fmt.Errorf("failed to read row version for %s: %w", id, err)
}
if current.Int64 != expected {
return fmt.Errorf("%w: expected %d, got %d", storage.ErrVersionMismatch, expected, current.Int64)
return &storage.VersionMismatchError{Expected: expected, Current: current.Int64}
}
return nil
}

View file

@ -44,6 +44,10 @@ var (
// guarded close. See issueops.CloseOpenChildrenError.
type CloseOpenChildrenError = issueops.CloseOpenChildrenError
// VersionMismatchError reports the expected and current row versions that
// refused a guarded write. See issueops.VersionMismatchError.
type VersionMismatchError = issueops.VersionMismatchError
// ErrNotOwner is returned when an actor tries to unclaim an issue that is claimed
// by a different actor. Releasing another actor's claim requires the force
// escape hatch (bd unclaim --force), reserved for admin/reaper use.

View file

@ -129,8 +129,7 @@ func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest
// duplicates before either ran.
if req.ExpectedVersion != nil {
if current := present[req.IDs[0]].RowVersion; current != *req.ExpectedVersion {
return publicops.DeleteResult{}, fmt.Errorf("%w: expected %d, got %d",
publicops.ErrVersionMismatch, *req.ExpectedVersion, current)
return publicops.DeleteResult{}, &publicops.VersionMismatchError{Expected: *req.ExpectedVersion, Current: current}
}
}

View file

@ -53,6 +53,9 @@ func TestLifecycleUpdateContract(t *testing.T) {
t.Run("ConditionalGuardsGateOrdinaryEdits", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture)
})
t.Run("ExpectedVersionSingleWinnerUnderConcurrency", func(t *testing.T) {
conformance.RunLifecycleUpdateExpectedVersionSingleWinnerUnderConcurrency(t, ctx, fixture)
})
t.Run("ConditionalGuardAcceptsRespelledAssignee", func(t *testing.T) {
conformance.RunLifecycleUpdateConditionalGuardAcceptsRespelledAssignee(t, ctx, fixture)
})

View file

@ -290,6 +290,32 @@ func (e *AlreadyIdentifiedError) Unwrap() error { return ErrAlreadyIdentified }
// precondition from other errors.
var ErrVersionMismatch = errors.New("version mismatch")
// VersionMismatchError reports the expected and current row versions that
// refused a guarded write, read inside the same transaction the guard
// checked. It wraps ErrVersionMismatch rather than replacing it — the
// ClaimConflictError arrangement — so errors.Is(err, ErrVersionMismatch)
// still matches and the message stays byte-identical to the historical
// "version mismatch: expected %d, got %d", while a caller that reports the
// refusal elsewhere (a command's --json envelope, the HTTP surface) reads the
// typed pair instead of parsing that prose.
//
// Both fields are the opaque row_lock token: compared for equality only,
// carrying no order.
type VersionMismatchError struct {
// Expected is the version the caller required.
Expected int64
// Current is the version the guard found instead, read inside the same
// transaction as the check — never a post-rollback re-read.
Current int64
}
func (e *VersionMismatchError) Error() string {
return fmt.Sprintf("%v: expected %d, got %d", ErrVersionMismatch, e.Expected, e.Current)
}
// Unwrap makes VersionMismatchError match ErrVersionMismatch.
func (e *VersionMismatchError) Unwrap() error { return ErrVersionMismatch }
// ErrStatusMismatch is returned by UpdateIssueChecked given an ExpectedStatus
// that no longer matches the issue's current status. The caller's view of the
// issue was stale; the issue is left untouched. The assignee analog is