* 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>
359 lines
15 KiB
Go
359 lines
15 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"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/issueops"
|
|
)
|
|
|
|
func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
|
if len(args) == 0 {
|
|
return HandleErrorRespectJSON("no issue ID provided")
|
|
}
|
|
|
|
in, err := gatherUpdateInput(ctx, cmd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if isUpdateInputNoop(in) {
|
|
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
|
|
// success output and the failure report never disagree on format within one
|
|
// invocation. This matches the non-proxied path in update.go.
|
|
jsonOut := jsonOutput
|
|
var updated []*types.Issue
|
|
// failures accumulates every requested ID that could not be updated —
|
|
// generic per-ID errors as well as a lost --claim race. In a mixed batch a
|
|
// later winner must NOT flip the exit code back to success and hide the
|
|
// failed IDs from exit-code automation; report them all and exit non-zero,
|
|
// mirroring the non-proxied path in update.go (beads audit finding #10).
|
|
var failures []updateIDFailure
|
|
|
|
for _, id := range args {
|
|
issue, fail, err := applyUpdateProxiedOne(ctx, id, in)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if fail != nil {
|
|
failures = append(failures, *fail)
|
|
continue
|
|
}
|
|
if jsonOut {
|
|
updated = append(updated, issue)
|
|
} else {
|
|
fmt.Printf("%s Updated issue: %s\n", ui.RenderPass("✓"), formatFeedbackID(issue.ID, issue.Title))
|
|
}
|
|
}
|
|
|
|
if jsonOut && len(updated) > 0 {
|
|
_ = outputJSON(updated)
|
|
}
|
|
if len(failures) > 0 {
|
|
return reportUpdateFailures(failures, len(args))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// proxiedIssueLifecycle asks the unit-of-work provider for the write role, the
|
|
// same way proxiedIssueReader asks it for the read one.
|
|
func proxiedIssueLifecycle() (issueops.Lifecycle, error) {
|
|
if uowProvider == nil {
|
|
return nil, errors.New("proxied-server UOW provider not initialized")
|
|
}
|
|
src, ok := uowProvider.(uow.IssueLifecycleSource)
|
|
if !ok {
|
|
return nil, fmt.Errorf("proxied-server provider %T does not offer the issue-lifecycle surface", uowProvider)
|
|
}
|
|
return src.IssueLifecycle()
|
|
}
|
|
|
|
// applyUpdateProxiedOne applies one issue's update — plain or --claim —
|
|
// through issueops.Lifecycle. What stays here is this surface's own protocol:
|
|
// the advisory reassign pre-read, the per-id failure taxonomy the multi-id
|
|
// batch needs (a template refusal is one of its verdicts; the guard itself is
|
|
// the role's) and the notes-overwrite warning. Hooks are NOT among them: they
|
|
// fire from the write plumbing now (the notifying provider wired in main.go),
|
|
// which is what makes an update fire the same events here as it does on the
|
|
// embedded path.
|
|
//
|
|
// Provenance carries the commit message this path has always written, so `bd
|
|
// dolt log` reads the same after the move as before it. The plane is
|
|
// deliberately NOT restricted: `bd update` has always resolved a wisp id,
|
|
// unlike the HTTP claim endpoint, which serves durable issues only.
|
|
//
|
|
// The pre-read is a read of its own, one transaction earlier than the
|
|
// mutation, so the guards it applies are ADVISORY. The mutation's own guards
|
|
// are all inside the contract's transaction, including the fence and the close
|
|
// policy.
|
|
func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) {
|
|
ops, err := proxiedIssueLifecycle()
|
|
if err != nil {
|
|
return nil, nil, HandleError("%v", err)
|
|
}
|
|
before, fail, err := proxiedUpdateTarget(ctx, id, in)
|
|
if err != nil || fail != nil {
|
|
return nil, fail, err
|
|
}
|
|
patch, err := proxiedUpdatePatch(in, before)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
|
|
return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)}, nil
|
|
}
|
|
notesOverwritten := replacesExistingNotes(before.Notes, in.fields)
|
|
|
|
var expectedStatus *issueops.Status
|
|
if in.ifStatus != nil {
|
|
// gatherUpdateInput refuses --if-assignee/--if-status alongside
|
|
// --claim, which is also what the request contract requires of a claim,
|
|
// so a claim reaches the contract with both guards nil by construction.
|
|
expected := issueops.Status(*in.ifStatus)
|
|
expectedStatus = &expected
|
|
}
|
|
result, err := runCommandUpdateMutation(ctx, ops, commandUpdateMutation{
|
|
actor: currentActor(),
|
|
issueID: id,
|
|
patch: patch,
|
|
claim: in.claim,
|
|
force: in.force,
|
|
expectedAssignee: in.ifAssignee,
|
|
expectedStatus: expectedStatus,
|
|
expectedVersion: in.ifRevision,
|
|
provenance: fmt.Sprintf("bd: update %s", id),
|
|
})
|
|
if err != nil {
|
|
// Cancellation is not a verdict on this issue — SIGINT cancels bd's
|
|
// root context, and every remaining id in the batch would fail the same
|
|
// way, so abort the batch. A commit that itself failed with a context
|
|
// error is indistinguishable from a cancellation between attempts;
|
|
// aborting is the right call for both.
|
|
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, in.ifRevision); ok {
|
|
return nil, nil, reported
|
|
}
|
|
}
|
|
return nil, proxiedUpdateFailure(id, in.claim, err), nil
|
|
}
|
|
updated := result.Issue
|
|
if updated == nil {
|
|
fmt.Fprintf(os.Stderr, "Error updating %s: the update reported no issue\n", id)
|
|
return nil, &updateIDFailure{ID: id, Error: "updating: no issue returned"}, nil
|
|
}
|
|
// `bd update` has never printed dependency records; the direct route drops
|
|
// them for the same reason.
|
|
updated.Dependencies = nil
|
|
if in.claim {
|
|
// A CLAIM answers an already-published surface, and that surface is the
|
|
// bare row: issueops.ClaimResult omits labels, dependency records and
|
|
// comments, but routing this path through Lifecycle hydrates labels.
|
|
// Stripping them keeps `bd update --claim --json` byte-identical to the
|
|
// v0 claim response, which TestProxiedServerServeClaim asserts with an
|
|
// EMPTY allowlist. A plain update carries labels, as the direct route
|
|
// does.
|
|
updated.Labels = nil
|
|
updated.Comments = nil
|
|
}
|
|
|
|
// Post-commit reporting: the write has landed, so these run exactly once no
|
|
// matter how many attempts the contract's conflict retry burned.
|
|
if notesOverwritten {
|
|
warnNotesReplacement(id)
|
|
}
|
|
return updated, nil, nil
|
|
}
|
|
|
|
// proxiedUpdateTarget reads the row an update is about through the query role,
|
|
// for the things the mutation's own result cannot answer: whether an unguarded
|
|
// assignee edit is about to take the issue from a live foreign holder, whether
|
|
// --notes is about to replace existing notes, and whether --defer="" should
|
|
// also clear a deferred status. It no longer reads the pre-state to decide a
|
|
// hook: a status-crossing update fires on_update and nothing else, from the
|
|
// plumbing, exactly as it does on the embedded path. The error is non-nil
|
|
// only for an --if-revision guard outcome it has already reported, which the
|
|
// caller returns as the command's exit error.
|
|
func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) {
|
|
rd, err := proxiedIssueReader()
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
|
|
return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}, nil
|
|
}
|
|
details, err := rd.Get(ctx, issueops.GetRequest{ID: id})
|
|
if err != nil {
|
|
// A guarded update that lost to a concurrent `bd delete` committing
|
|
// before this pre-read is the same lost race as one committing inside
|
|
// the guarded write: report it through the guard envelope.
|
|
if reported, ok := reportIfRevisionTargetGone("updating", id, err, in.ifRevision); ok {
|
|
return nil, nil, reported
|
|
}
|
|
if errors.Is(err, issueops.ErrNotFound) {
|
|
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
|
|
return nil, &updateIDFailure{ID: id, Error: "issue not found"}, nil
|
|
}
|
|
fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err)
|
|
return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}, nil
|
|
}
|
|
current := &details.Issue
|
|
// The template guard is the role's, enforced inside the mutation;
|
|
// proxiedUpdateFailure prints its refusal as this route always did.
|
|
// bd-98s5c: an unguarded assignee update must not silently overwrite
|
|
// another actor's live claim. Skipped under --if-assignee, whose CAS names
|
|
// the holder explicitly (park stays possible without --force), and under
|
|
// --claim, whose CAS is itself the anti-steal gate. The contract fences the
|
|
// same transfer inside the mutation with ErrAlreadyClaimed; this pre-read is
|
|
// what keeps the advice a user reads identical on both routes. A policy
|
|
// refusal: terminal per-issue failure, exit 1, never GuardMismatch/13.
|
|
// mc-zndi7.74: also skipped when this pre-read is already stale against an
|
|
// active --if-revision guard — see ifRevisionAlreadyStale's doc.
|
|
if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim && !ifRevisionAlreadyStale(current, in.ifRevision) {
|
|
if err := validateIssueReassignable(id, current, currentActor(), newAssignee,
|
|
proxiedClaimPoolAliases(ctx), in.force); err != nil {
|
|
fmt.Fprintf(os.Stderr, "%s\n", err)
|
|
return nil, &updateIDFailure{ID: id, Error: err.Error()}, nil
|
|
}
|
|
}
|
|
return current, nil, nil
|
|
}
|
|
|
|
// proxiedClaimPoolAliases is uowClaimPoolAliases for a caller that owns no unit
|
|
// of work: the pre-read fence's claim.pools lookup opens a short-lived unit of
|
|
// work of its own, and only when the fence is otherwise about to refuse, which
|
|
// is what the thunk is for. A read that fails yields no aliases, the same
|
|
// fail-closed answer its siblings give.
|
|
func proxiedClaimPoolAliases(ctx context.Context) func() []string {
|
|
return func() []string {
|
|
if uowProvider == nil {
|
|
return nil
|
|
}
|
|
uw, err := uowProvider.NewUOW(ctx)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
defer uw.Close(ctx)
|
|
return uowClaimPoolAliases(ctx, uw)()
|
|
}
|
|
}
|
|
|
|
// proxiedUpdateFailure sorts a refused update into the per-id verdicts. A guard
|
|
// refusal sets GuardMismatch so the batch exits 13 rather than 1.
|
|
//
|
|
// A refused claim reads as the generic update failure, as it does on the direct
|
|
// route: the external claim guard ignores --force but shares ErrCloseBlocked
|
|
// with the close policy, so the hint could name an override that cannot work.
|
|
//
|
|
// The one verdict it cannot reproduce is stage attribution: "opening unit of
|
|
// work" and "committing" were told apart by watching the provider this path no
|
|
// longer owns, so both now read as the generic update failure. The id still
|
|
// fails, loudly and non-zero.
|
|
func proxiedUpdateFailure(id string, claim bool, err error) *updateIDFailure {
|
|
if refusal, ok := templateReadOnlyRefusal(id, err); ok {
|
|
fmt.Fprintf(os.Stderr, "%s\n", refusal)
|
|
return &updateIDFailure{ID: id, Error: refusal.Error()}
|
|
}
|
|
switch {
|
|
case errors.Is(err, storage.ErrNotFound):
|
|
fmt.Fprintf(os.Stderr, "Issue %s not found\n", id)
|
|
return &updateIDFailure{ID: id, Error: "issue not found"}
|
|
case errors.Is(err, storage.ErrAlreadyClaimed), errors.Is(err, storage.ErrNotClaimable):
|
|
fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err)
|
|
return &updateIDFailure{ID: id, Error: fmt.Sprintf("claiming issue: %v", err)}
|
|
case errors.Is(err, storage.ErrCloseOpenChildren):
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
return &updateIDFailure{ID: id, Error: err.Error()}
|
|
case errors.Is(err, storage.ErrCloseBlocked) && !claim:
|
|
fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err)
|
|
return &updateIDFailure{ID: id, Error: fmt.Sprintf("%v (use --force to override)", err)}
|
|
case errors.Is(err, storage.ErrNotesOverwrite):
|
|
// The contract's AuthorizeNotesOverwrite fence refused inside the
|
|
// mutation transaction. Print the advice, not the raw sentinel.
|
|
refusal := errNotesOverwriteRefusal(id)
|
|
fmt.Fprintf(os.Stderr, "%s\n", refusal)
|
|
return &updateIDFailure{ID: id, Error: refusal.Error()}
|
|
case uow.IsSerializationError(err):
|
|
// The contract spent its retry budget losing Dolt's commit-time merge.
|
|
// The write did NOT land; fail loudly instead of exiting 0.
|
|
fmt.Fprintf(os.Stderr, "Error updating %s: retries exhausted on write conflicts: %v\n", id, err)
|
|
return &updateIDFailure{ID: id, Error: fmt.Sprintf("retries exhausted on write conflicts: %v", err)}
|
|
case isGuardMismatch(err):
|
|
// bd-wsqvw guard verdict: the precondition no longer holds, nothing was
|
|
// written. Loud and non-zero, never collapsed to success —
|
|
// GuardMismatch routes the batch to ExitGuardMismatch.
|
|
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
|
|
return &updateIDFailure{ID: id, Error: fmt.Sprintf("precondition failed: %v", err), GuardMismatch: true}
|
|
default:
|
|
fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err)
|
|
return &updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)}
|
|
}
|
|
}
|
|
|
|
// proxiedUpdatePatch reshapes gathered CLI input into the contract's typed
|
|
// patch. The field map goes through the same builder the direct route uses; the
|
|
// edits this input keeps beside that map (labels, reparent, the merge-shaped
|
|
// note and metadata edits) are folded in here, so both routes end up describing
|
|
// the same mutation.
|
|
//
|
|
// The merge-shaped edits stay merge-shaped: the contract resolves them against
|
|
// the row re-read inside the mutation transaction. Pre-merging them against
|
|
// `before` is what silently erased keys a concurrent writer had committed.
|
|
func proxiedUpdatePatch(in *updateInput, before *types.Issue) (issueops.IssuePatch, error) {
|
|
patch, err := buildUpdatePatch(in.fields)
|
|
if err != nil {
|
|
return issueops.IssuePatch{}, err
|
|
}
|
|
patch.Labels.Add = in.addLabels
|
|
patch.Labels.Remove = in.removeLabels
|
|
if in.setLabels != nil {
|
|
patch.Labels.Replace = setField(*in.setLabels)
|
|
}
|
|
if in.reparent != nil {
|
|
patch.ParentID = setField(*in.reparent)
|
|
}
|
|
if in.hasAppendNotes {
|
|
patch.AppendNotes = setField(in.appendNotes)
|
|
}
|
|
if len(in.mergeMetadataIn) > 0 {
|
|
patch.Metadata.Merge = setField(in.mergeMetadataIn)
|
|
}
|
|
if len(in.setMetadata) > 0 {
|
|
set, err := parseSetMetadataFlags(in.setMetadata)
|
|
if err != nil {
|
|
return issueops.IssuePatch{}, err
|
|
}
|
|
patch.Metadata.Set = set
|
|
}
|
|
if len(in.unsetMetadata) > 0 {
|
|
patch.Metadata.Unset = in.unsetMetadata
|
|
}
|
|
// GH#3233: --defer="" restores ready visibility only if the issue was
|
|
// actually deferred, exactly as the direct route decides it.
|
|
if in.clearDeferStatus && before.Status == types.StatusDeferred {
|
|
patch.Status = setField(types.StatusOpen)
|
|
}
|
|
return patch, nil
|
|
}
|