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

169 lines
5.9 KiB
Go

package main
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/audit"
"github.com/steveyegge/beads/internal/storage/uow"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/workapi"
"github.com/steveyegge/beads/issueops"
)
// reopenProxiedTarget is one id that resolved, carrying the status it sat at
// before the reopens ran.
type reopenProxiedTarget struct {
id string
// status is the prior status, and it feeds the audit sidecar's old_value and
// nothing else. The role's result is a post-state snapshot with no prior
// status, and a constant "closed" is now wrong: a configured done status
// reopens here too.
status types.Status
}
// runReopenProxiedServer reopens each id through issueops.Lifecycle — the same
// role, reached through the same kind of accessor, that the direct route calls.
// Nothing here decides what a reopen means.
//
// A CONFIGURED DONE STATUS NOW REOPENS. This route used to compare the current
// status against literal StatusClosed and report "already <status>" for
// anything else, so an issue parked on a custom done status could not be
// reopened on a team server while the same command worked locally. The role
// speaks in terms of the configured done CATEGORY
// (issueops/issueops.go:417-420).
//
// ONE CALL PER ID, so one transaction and one history entry per id, where this
// route used to run every id in one unit of work under a hand-composed
// "bd: reopen a, b" message.
func runReopenProxiedServer(cmd *cobra.Command, ctx context.Context, args []string, ifRevision *int64) error {
if len(args) == 0 {
return HandleErrorRespectJSON("no issue ID provided")
}
reason, _ := cmd.Flags().GetString("reason")
jsonOut, _ := cmd.Flags().GetBool("json")
targets, hasError, err := reopenProxiedResolve(ctx, args, ifRevision)
if err != nil {
if isReportedExit(err) {
// The --if-revision guard outcome reopenProxiedResolve has
// already reported; re-wrapping would print a second Error line.
return err
}
return HandleErrorRespectJSON("%v", err)
}
if len(targets) == 0 {
if hasError {
return SilentExit()
}
return nil
}
lifecycle, err := proxiedIssueLifecycle()
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
reopenedIssues := []*types.Issue{}
for _, target := range targets {
result, err := lifecycle.Reopen(ctx, issueops.ReopenRequest{
Actor: currentActor(),
IssueID: target.id,
Reason: reason,
ExpectedVersion: ifRevision,
// The label the direct route spells, so one reopen reads the same
// in `bd dolt log` whichever route served it.
Provenance: "bd: reopen " + target.id,
})
if err != nil {
// Guarded only, as on the direct route: an unguarded reopen that
// loses a race with a delete is a lookup failure, not a refusal.
if ifRevision != nil {
if reported, ok := reportIfRevisionFailure("reopening", target.id, err, ifRevision); ok {
return reported
}
}
reportIssueLookupFailure("reopening", target.id, err)
hasError = true
continue
}
if !result.Changed {
// Read off the result rather than off the pre-read: the status the
// reopen left in place is the one the operation saw inside its own
// transaction.
fmt.Fprintln(os.Stderr, reopenNoOpMessage(target.id, reopenStatusOf(result.Issue, nil)))
continue
}
audit.LogFieldChange(target.id, "status", string(target.status), string(types.StatusOpen), currentActor(), reason)
if jsonOut {
if issue := result.Issue; issue != nil {
// `bd reopen` has never printed dependency records, on either
// route.
issue.Dependencies = nil
reopenedIssues = append(reopenedIssues, issue)
}
continue
}
suffix := ""
if reason != "" {
suffix = ": " + reason
}
fmt.Printf("%s Reopened %s%s\n", ui.RenderAccent("↻"), target.id, suffix)
}
if jsonOut && len(reopenedIssues) > 0 {
_ = outputJSON(reopenedIssues)
}
if hasError {
return SilentExit()
}
return nil
}
// reopenProxiedResolve resolves every id in ONE read-only unit of work and
// reports the ones that did not resolve, returning the survivors with the
// status each sat at.
//
// It exists for the two things the role's result cannot supply: the audit
// sidecar's old_value, and the difference between an absent id and a backend
// that failed to answer.
//
// It decides NOTHING about the reopen. A resolved id goes to the role whatever
// status it is at, including a status this route used to refuse; every guard
// that matters is inside the role's own transaction. The one outcome it reports
// on the role's behalf is a guarded id that is already gone: that is the lost
// delete race the role would otherwise classify, so the error is then the
// --if-revision guard outcome it has already reported, which the caller
// returns as the command's exit error.
func reopenProxiedResolve(ctx context.Context, ids []string, ifRevision *int64) ([]reopenProxiedTarget, bool, error) {
var targets []reopenProxiedTarget
failed := false
_, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, error) {
source := workapi.NewUOWDetailSource(uw)
for _, id := range ids {
issue, _, err := workapi.GetIssueOrWisp(ctx, source, id)
if err != nil {
// A guarded reopen that lost to a concurrent `bd delete`
// committing before this read is the same lost race as one
// committing inside lifecycle.Reopen: report it through the
// guard envelope. requireSingleIfRevisionID guarantees this
// is the only id, so nothing is pending.
if reported, ok := reportIfRevisionTargetGone("reopening", id, err, ifRevision); ok {
return struct{}{}, reported
}
reportIssueLookupFailure("resolving", id, err)
failed = true
continue
}
targets = append(targets, reopenProxiedTarget{id: id, status: issue.Status})
}
return struct{}{}, nil
})
return targets, failed, err
}