beads/cmd/bd/mutate_proxied_server.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

272 lines
10 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/validation"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
func proxiedMutateIssue(ctx context.Context, id, commitMsg string, mutate func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error) (*types.Issue, error) {
if uowProvider == nil {
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
}
var updated *types.Issue
err := uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) {
issue, isWisp, rerr := workapi.GetIssueOrWisp(ctx, workapi.NewUOWDetailSource(uw), id)
if errors.Is(rerr, storage.ErrNotFound) {
return "", fmt.Errorf("issue %s not found", id)
}
if rerr != nil {
return "", fmt.Errorf("resolving %s: %w", id, rerr)
}
if err := validateIssueUpdatable(id, issue); err != nil {
return "", err
}
if err := mutate(ctx, uw, issue, isWisp); err != nil {
return "", err
}
if isWisp {
updated, _ = uw.IssueUseCase().GetWisp(ctx, issue.ID)
} else {
updated, _ = uw.IssueUseCase().GetIssue(ctx, issue.ID)
}
return commitMsg, nil
})
if err != nil {
return nil, err
}
commandDidWrite.Store(true)
return updated, nil
}
// force applies only to assignee updates: it bypasses the live-claim reassign
// fence (bd-98s5c). Callers whose updates never carry "assignee" pass false.
func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates map[string]any, force bool) (*types.Issue, error) {
return proxiedMutateIssue(ctx, id, commitMsg, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error {
// bd-98s5c: an unguarded assignee update (bd assign via the proxied
// server) must not silently overwrite another actor's live claim.
if newAssignee, ok := updates["assignee"].(string); ok {
if err := validateIssueReassignable(id, issue, currentActor(), newAssignee,
uowClaimPoolAliases(ctx, uw), force); err != nil {
return err
}
}
if isWisp {
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, currentActor())
}
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, currentActor())
})
}
// 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) {
// Wrapped, not flattened, so runAssignProxiedServer classifies a
// guarded assign that lost to a concurrent delete as
// precondition_failed (reportIfRevisionFailure).
return struct{}{}, fmt.Errorf("issue %s %w", id, storage.ErrNotFound) // "issue <id> not found", as before
}
if rerr != nil {
return struct{}{}, fmt.Errorf("resolving %s: %w", id, rerr)
}
// The template guard is the role's, enforced by the Lifecycle.Update
// below; runAssignProxiedServer prints its refusal as before.
// 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(current, ifRevision) {
if verr := validateIssueReassignable(id, current, currentActor(), 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: currentActor(),
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 := proxiedAssign(ctx, id, assignee, force, 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 {
err = refusal
}
return HandleErrorRespectJSON("assign %s: %v", id, err)
}
if jsonOutput {
if updated != nil {
return outputJSON(updated)
}
return nil
}
title := issueTitleOrEmpty(updated)
if assignee == "" {
fmt.Printf("%s Unassigned %s\n", ui.RenderPass("✓"), formatFeedbackID(id, title))
} else {
fmt.Printf("%s Assigned %s to %s\n", ui.RenderPass("✓"), formatFeedbackID(id, title), assignee)
}
return nil
}
func runPriorityProxiedServer(ctx context.Context, args []string) error {
id := args[0]
priority, err := validation.ValidatePriority(args[1])
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
updated, err := proxiedUpdateIssueFields(ctx, id, "bd: priority "+id, map[string]any{"priority": priority}, false)
if err != nil {
return HandleErrorRespectJSON("priority %s: %v", id, err)
}
if jsonOutput {
if updated != nil {
return outputJSON(updated)
}
return nil
}
fmt.Printf("%s Set priority of %s to P%d\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(updated)), priority)
return nil
}
func runNoteProxiedServer(ctx context.Context, id, noteText string) error {
updated, err := proxiedMutateIssue(ctx, id, "bd: note "+id, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error {
combined := issue.Notes
if combined != "" {
combined += "\n"
}
combined += noteText
updates := map[string]any{"notes": combined}
if isWisp {
return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, currentActor())
}
return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, currentActor())
})
if err != nil {
return HandleErrorRespectJSON("note %s: %v", id, err)
}
if jsonOutput {
if updated != nil {
return outputJSON(updated)
}
return nil
}
fmt.Printf("%s Note added to %s\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(updated)))
return nil
}
// runTagProxiedServer is `bd tag` on the proxied-server route, and it is the
// one verb in this file that does NOT go through proxiedMutateIssue.
//
// It cannot, and that is the point. proxiedMutateIssue hands its callback a
// unit of work and an isWisp boolean, which is an invitation to pick a plane —
// and the tag callback accepted it, choosing between AddWispLabel and AddLabel
// exactly the way cmd/bd/label_proxied_server.go used to before ga-26w10.
// A label edit is a patch, and issueops.Lifecycle is what applies one:
// UpdateRequest.IssuePlaneOnly stays false, so the role resolves the plane
// inside its own transaction and there is no boolean here to get backwards.
//
// The read it still makes is front-door work rather than plumbing: the role
// takes an exact id by contract, and issueops.Reader.Get's issue-then-wisp
// lookup supplies one. The template guard is the role's: Lifecycle.Update
// refuses a template inside its own transaction.
// The label arrives already normalized: tag.go does that before choosing a
// route, so this path and the direct one cannot disagree about what was stored.
func runTagProxiedServer(ctx context.Context, id, label string) error {
reader, err := openIssueReader()
if err != nil {
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
details, err := reader.Get(ctx, issueops.GetRequest{ID: id})
if errors.Is(err, storage.ErrNotFound) {
return HandleErrorRespectJSON("tag %s: issue %s not found", id, id)
}
if err != nil {
return HandleErrorRespectJSON("tag %s: resolving %s: %v", id, id, err)
}
// The template guard is the role's, enforced by the Lifecycle.Update
// below, whose refusal prints as this route always printed it.
lifecycle, err := openIssueLifecycle()
if err != nil {
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
// The role commits its own Dolt version inside the storage layer, so
// `--dolt-auto-commit batch` is deferred on the context rather than by
// blanking a commit message — see applyLabelEdit in cmd/bd/label.go.
ctx, err = issueOpsContext(ctx)
if err != nil {
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
result, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: currentActor(),
IssueID: details.ID,
Patch: issueops.IssuePatch{Labels: issueops.LabelPatch{Add: []string{label}}},
})
if err != nil {
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
err = refusal
}
return HandleErrorRespectJSON("tag %s: %v", id, err)
}
commandDidWrite.Store(true)
if jsonOutput {
if result.Issue != nil {
return outputJSON(result.Issue)
}
return nil
}
fmt.Printf("%s Added label %q to %s\n", ui.RenderPass("✓"), label, formatFeedbackID(id, issueTitleOrEmpty(result.Issue)))
return nil
}