beads/cmd/bd/assign.go
Julian Knutsen 1b7bf9b191
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>
2026-10-10 16:33:19 +00:00

169 lines
5.1 KiB
Go

package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/issueops"
)
var assignCmd = &cobra.Command{
Use: "assign <id> <name>",
GroupID: "issues",
Short: "Assign an issue to someone",
Long: `Assign an issue to someone.
Shorthand for 'bd update <id> --assignee <name>'.
Refuses to overwrite another actor's live in_progress claim without --force
(bd-98s5c); issues assigned to a claim.pools alias are exempt, matching
--claim. For a holder-aware transfer prefer
'bd update <id> --if-assignee <holder> -a <new>'.
Examples:
bd assign bd-123 alice
bd assign bd-123 "" # unassign`,
Args: cobra.ExactArgs(2),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
CheckReadonly("assign")
evt := metrics.NewCommandEvent("assign")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
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, ifRevision)
}
id := args[0]
assignee := args[1]
ctx := rootCtx
result, err := resolveAndGetIssueForMutation(ctx, store, id)
if err != nil {
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 {
if result != nil {
result.Close()
}
return HandleErrorRespectJSON("issue %s not found", id)
}
defer result.Close()
issueStore := result.Store
// The template guard is the role's (issueops.Lifecycle.Update); its
// refusal is printed below as this command always printed it.
// bd-98s5c: bd assign is shorthand for an unguarded assignee update —
// same live-claim fence as bd update -a. mc-zndi7.74: skipped when this
// pre-read is already stale against an active --if-revision guard, so a
// lost race reports precondition_failed from the guarded write below
// instead of this policy refusal — see ifRevisionAlreadyStale's doc.
if !ifRevisionAlreadyStale(result.Issue, ifRevision) {
if err := validateIssueReassignable(id, result.Issue, currentActor(), assignee,
storeClaimPoolAliases(ctx, issueStore), force); err != nil {
return HandleErrorRespectJSON("%s", err)
}
}
// 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)
}
opsCtx, err := issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
mutationResult, err := runCommandUpdateMutation(opsCtx, ops, commandUpdateMutation{
actor: currentActor(),
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, ifRevision); ok {
return reported
}
}
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
return HandleErrorRespectJSON("%s", refusal)
}
return HandleErrorRespectJSON("updating %s: %v", id, err)
}
if err := commitPendingIfEmbedded(ctx, issueStore, currentActor(), doltAutoCommitParams{
Command: "assign",
IssueIDs: []string{result.ResolvedID},
}); err != nil {
return HandleErrorRespectJSON("failed to commit: %v", err)
}
SetLastTouchedID(result.ResolvedID)
updatedIssue := mutationResult.Issue
title := ""
if updatedIssue != nil {
title = updatedIssue.Title
}
if jsonOutput {
if updatedIssue != nil {
if err := outputJSON(updatedIssue); err != nil {
return err
}
}
} else {
if assignee == "" {
fmt.Printf("%s Unassigned %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, title))
} else {
fmt.Printf("%s Assigned %s to %s\n", ui.RenderPass("✓"), formatFeedbackID(result.ResolvedID, title), assignee)
}
}
return nil
},
}
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)
}