From 17f4235260aed329e5197d0447ea51d3f388085e Mon Sep 17 00:00:00 2001 From: CI Bot Date: Wed, 5 Aug 2026 04:23:20 +0000 Subject: [PATCH] feat(update): put the plain proxied update on issueops.Lifecycle (bd-xt6de) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bd update` was believed to be converged. It was not. Only the direct route and the proxied `--claim` were on issueops.Lifecycle; the proxied PLAIN update ran a read-merge-write of its own in cmd/bd — resolve the id across both planes, apply the assignee fence, build a domain.UpdateSpec by hand, call ApplyUpdate, drive uow.RunTxResultWithin, commit, and attribute the resulting error to a stage by watching a decorated provider. Every one of those had a second implementation. This deletes it: 339 lines out of update_proxied_server.go for 113 in, and the plain path now makes the same Lifecycle.Update call the claim already made. WHAT STAYS IN cmd/bd, because none of it is an update: the template guard, the advisory reassign pre-read, the per-id failure taxonomy the multi-id batch needs, the notes-overwrite warning and the completion hooks. The HTTP surface has none of them, which is the test for whether something belongs to the command or to the contract. WHAT THE MOVE CHANGES, all of it converging proxied onto the direct route: - PERSISTENCE IS NOW AN AGGREGATE MOVE. This is the one nobody predicted. `--ephemeral` / `--no-history` went through the hand-built spec as fields["wisp"]=true — a column UPDATE on whichever table the row already sat in. So a proxied `bd update --ephemeral` left the row in `issues` carrying ephemeral=1: still durable, still versioned, still replicated, invisible to every wisp-plane read. The direct route has always sent IssuePatch.Persistence, which moves the aggregate, retargets inbound edges and drops the lease in one transaction, exactly as the leaf promises ("Ephemeral and NoHistory select wisp retention modes, never durable unversioned storage. Every aggregate move is atomic."). Both routes now do that. Two assertions in TestProxiedServerUpdate2 read `issues` directly to pin the old column flip and now pin the move. Recorded for the owner's batch as Q13; NO MIGRATION repairs rows the old path already produced. - STAGE ATTRIBUTION IS GONE. "opening unit of work" and "committing" were told apart by watching a provider this path no longer owns; both now read as the generic update failure. The claim path paid the same price when it moved. The id still fails, loudly and non-zero. - A COMMIT THAT FAILS WITH A CONTEXT ERROR now aborts the batch rather than recording one per-id verdict, because it is no longer distinguishable from a cancellation between retries. Again the claim path's existing choice. - --json CARRIES LABELS on a plain update, which the direct route and the protocol corpus already publish. A claim still strips them, so `bd update --claim --json` stays byte-identical to the v0 claim response. WHAT IT DOES NOT CHANGE: the commit message (`bd: update `, carried as Provenance), the wisp-id resolve, the exit codes including ExitGuardMismatch, and the conflict-retry semantics — the whole-attempt retry and the nothing-to-commit tolerance the bespoke loop reproduced are RunTxResultWithin's own, reached now through the contract instead of alongside it. THE CONTRACT GAINS ONE CASE, at all three backends with no parks: RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits. ExpectedAssignee and ExpectedStatus were pinned only beside a fenced transfer, where the case is about the ORDER two guards resolve in. Gating an ORDINARY field edit — which is how `--if-status` / `--if-assignee` actually reach the contract, and what the proxied route newly delegates — was untested. A refusal that leaked a partial write would exit 13, telling scripts nothing was written, while having written. No HTTP handler is rewired: `bd serve` exposes no update operation. Its POST /v0/beads/issues/{id}:claim already reaches Lifecycle.Update, and the Tier-1 spec is not extended here. Verified: build, vet, gofmt, golangci-lint (0 issues); the new contract case green at dolt, embeddeddolt and uow; the proxied update integration suites and the protocol corpus green under BEADS_TEST_PROXIED_SERVER=1 and BEADS_TEST_EMBEDDED_DOLT=1. --- .../conformance/issue_operations_contract.go | 105 ++++ ...e_close_policy_proxied_integration_test.go | 33 +- cmd/bd/update_close_policy_test.go | 29 +- cmd/bd/update_proxied_integration_test.go | 48 +- cmd/bd/update_proxied_server.go | 452 ++++---------- cmd/bd/update_proxied_server_test.go | 577 +++++++----------- .../dolt/issue_operations_contract_test.go | 6 + .../issue_operations_contract_test.go | 7 + .../uow/issue_operations_contract_test.go | 5 + 9 files changed, 521 insertions(+), 741 deletions(-) diff --git a/backend/conformance/issue_operations_contract.go b/backend/conformance/issue_operations_contract.go index 8538eab05..0f0a8f975 100644 --- a/backend/conformance/issue_operations_contract.go +++ b/backend/conformance/issue_operations_contract.go @@ -6,6 +6,7 @@ import ( "errors" "reflect" "sort" + "strconv" "strings" "testing" "time" @@ -1709,6 +1710,110 @@ func RunIssueOperationsUpdatePersistentPreservesUnversionedClass(t *testing.T, c assertIssueOperationsRowCount(t, ctx, fixture, "wisps", id, 0) } +// RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits pins the two +// compare-and-set preconditions as PRECONDITIONS ON A PLAIN EDIT, which is not +// the same question the assignee-transfer case above asks of them. There they +// appear beside a fenced transfer, to pin the ORDER the two guards resolve in; +// here they gate an ordinary field update that no fence would touch, which is +// how `bd update --if-status`/`--if-assignee` actually reach the contract. +// +// The clauses: ExpectedAssignee "requires the current assignee to match" and +// ExpectedStatus "requires the current status to match" +// (issueops/issueops.go:250-256), under Lifecycle's standing promise that a +// "refusal or validation error leaves persistent state unchanged" +// (issueops/issueops.go:406-408). The SENTINELS the two refusals wear are not +// named by those clauses; they are named by the contract, which already pins +// ErrVersionMismatch/ErrStatusMismatch for the same fields on a fenced request +// (this file, RunIssueOperationsUpdateAssigneeTransferFence), so asserting them +// here extends an established promise rather than inventing one. +// +// Both routes of `bd update` now send these guards to this contract instead of +// applying them beside their own read: the direct one always did, and the +// proxied one joined it when its hand-rolled read-merge-write was deleted +// (bd-xt6de). A refusal that leaked a partial write would exit 13 — "another +// actor won the race, nothing was written, do not retry" — while having +// written. +func RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T, ctx context.Context, fixture IssueOperationsStagingFixture) { + t.Helper() + + id := fixture.IssuePrefix + "-guardgate" + seedClosePolicyIssue(t, ctx, fixture, id, publicops.CreateRequest{}) + events := newIssueOperationsEventCounter(t, ctx, fixture, id) + + priorityEdit := func(priority int) publicops.UpdateRequest { + return publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Priority: publicops.Field[int]{Set: true, Value: priority}, + }} + } + assertPriority := func(label string, want int) { + t.Helper() + assertIssueOperationsScalarValue(t, ctx, fixture, label, strconv.Itoa(want), + "SELECT priority FROM issues WHERE id = ?", []any{id}) + } + + // The seeded row is open and unassigned, so the empty string is a real + // "expected unassigned" guard rather than the absence of one — the + // distinction `--if-assignee ''` depends on. + unassigned := "" + matching := priorityEdit(1) + matching.ExpectedAssignee = &unassigned + openStatus := types.StatusOpen + matching.ExpectedStatus = &openStatus + if result, err := fixture.Operations.Update(ctx, matching); err != nil || !result.Changed { + t.Fatalf("guarded edit with both preconditions holding = %#v, %v; want the edit applied", result, err) + } + assertPriority("priority after a satisfied guard", 1) + events.assert(t, "satisfied guard", 1, nil) + + // A stale status refuses, and the refusal writes nothing — not the field + // the request carried, not an event. + staleStatus := types.StatusInProgress + staleStatusEdit := priorityEdit(0) + staleStatusEdit.ExpectedStatus = &staleStatus + if _, err := fixture.Operations.Update(ctx, staleStatusEdit); !errors.Is(err, publicops.ErrStatusMismatch) { + t.Fatalf("edit guarded on a stale status: err = %v, want ErrStatusMismatch", err) + } + assertPriority("priority after a stale status guard", 1) + events.assert(t, "stale status guard", 0, nil) + + // A stale assignee refuses the same way, including when the status guard + // beside it still holds: both preconditions must hold, not either. + staleAssignee := "nobody" + staleAssigneeEdit := priorityEdit(0) + staleAssigneeEdit.ExpectedAssignee = &staleAssignee + staleAssigneeEdit.ExpectedStatus = &openStatus + if _, err := fixture.Operations.Update(ctx, staleAssigneeEdit); !errors.Is(err, publicops.ErrAssigneeMismatch) { + t.Fatalf("edit guarded on a stale assignee: err = %v, want ErrAssigneeMismatch", err) + } + assertPriority("priority after a stale assignee guard", 1) + events.assert(t, "stale assignee guard", 0, nil) + + // The guard tracks the row rather than the request that set it: once an + // assignee lands, the empty-string guard that just held is the stale one. + assign := publicops.UpdateRequest{Actor: "writer", IssueID: id, Patch: publicops.IssuePatch{ + Assignee: publicops.Field[string]{Set: true, Value: "holder"}, + }} + if _, err := fixture.Operations.Update(ctx, assign); err != nil { + t.Fatalf("assign %s: %v", id, err) + } + events.assert(t, "assign", 1, nil) + nowStale := priorityEdit(0) + nowStale.ExpectedAssignee = &unassigned + if _, err := fixture.Operations.Update(ctx, nowStale); !errors.Is(err, publicops.ErrAssigneeMismatch) { + t.Fatalf("edit guarded on unassigned after an assignment: err = %v, want ErrAssigneeMismatch", err) + } + assertPriority("priority after the once-current guard went stale", 1) + events.assert(t, "once-current guard", 0, nil) + + holder := "holder" + nowCurrent := priorityEdit(0) + nowCurrent.ExpectedAssignee = &holder + if result, err := fixture.Operations.Update(ctx, nowCurrent); err != nil || !result.Changed { + t.Fatalf("edit guarded on the current holder = %#v, %v; want the edit applied", result, err) + } + assertPriority("priority after a guard naming the current holder", 0) +} + // seedIssueOperationsLabeledIssue creates one open task at an explicit ID // carrying labels, through the store seed hook rather than the guarded create, // so the labels are already durable state when the case under test runs. diff --git a/cmd/bd/update_close_policy_proxied_integration_test.go b/cmd/bd/update_close_policy_proxied_integration_test.go index 79670f067..b6b6983dd 100644 --- a/cmd/bd/update_close_policy_proxied_integration_test.go +++ b/cmd/bd/update_close_policy_proxied_integration_test.go @@ -9,10 +9,10 @@ import ( "github.com/steveyegge/beads/internal/types" ) -// countAttemptRefusals counts the refusals printed by one read-merge-write -// ATTEMPT, not the run's failure summary. applyUpdateProxiedAttempt prints the -// policy error flush left; reportUpdateFailures reprints the same text indented -// behind the issue ID, so "unindented" separates the two. +// countAttemptRefusals counts the refusals printed for one issue, not the run's +// failure summary. proxiedUpdateFailure prints the policy error flush left; +// reportUpdateFailures reprints the same text indented behind the issue ID, so +// "unindented" separates the two. func countAttemptRefusals(out string) int { n := 0 for _, line := range strings.Split(out, "\n") { @@ -28,22 +28,23 @@ func countAttemptRefusals(out string) int { // // It exists because the two halves of this behavior were written against each // other's stale shape. #5206 added the policy and its two proxied refusal arms -// while applyUpdateProxiedAttempt still ran a bespoke backoff loop and returned -// four values; bd-m2u had meanwhile collapsed that function onto -// uow.RunTxResultWithin, whose attempt returns three. Git merged the two -// cleanly, and the only proxied coverage #5206 shipped was a unit test on -// buildUpdateSpecForIssue — which passes whether or not the refusal ever -// reaches a user. +// while this path still ran a bespoke read-merge-write of its own, and the only +// proxied coverage it shipped was a unit test on the spec that path built — +// which passes whether or not the refusal ever reaches a user. The +// read-merge-write is gone now, but the assertions still earn their keep: they +// are the only proxied close-policy coverage that watches a user-visible +// boundary rather than an internal request. // // So the assertions here are end-to-end and deliberately narrow: // -// - the sentinels still match through ApplyUpdate's wrapping, so the boundary -// prints the close-path copy rather than the generic "Error updating" arm; +// - the sentinels still match through the contract's wrapping, so the +// boundary prints the close-path copy rather than the generic +// "Error updating" arm; // - the refusal is TERMINAL, printed exactly once. A policy error is not a -// serialization failure, so failedUpdateAttempt hands the retry loop a nil -// error and an empty commit message: no commit, no retry. If a later change -// let it propagate as a retryable error instead, the backoff would redo the -// attempt for its whole budget and this count would climb; +// serialization failure, so the contract's retry loop wraps it Permanent: +// no commit, no retry. If a later change let it propagate as a retryable +// error instead, the backoff would redo the attempt for its whole budget +// and this count would climb; // - it exits 1, never ExitGuardMismatch/13, which is reserved for a stale // --if-assignee/--if-status precondition; // - nothing is written; and --force overrides, on the same path. diff --git a/cmd/bd/update_close_policy_test.go b/cmd/bd/update_close_policy_test.go index 4c7be9b6f..394dd72ed 100644 --- a/cmd/bd/update_close_policy_test.go +++ b/cmd/bd/update_close_policy_test.go @@ -140,28 +140,7 @@ func TestUpdateClosePolicyBatchGrammarForceToken(t *testing.T) { } } -// TestUpdateClosePolicyProxiedSpecCarriesForce pins the proxied path's -// translation of `--force`. An earlier attempt was reverted for exactly this -// missing mapping: the proxied caller built a spec that never carried the -// override, so a shared policy check refused the close with no way for the -// user to say otherwise. The spec must carry it, and must not invent it. -func TestUpdateClosePolicyProxiedSpecCarriesForce(t *testing.T) { - current := &types.Issue{ID: "test-ucpp", Status: types.StatusOpen} - - forced := buildUpdateSpecForIssue(current, &updateInput{ - fields: map[string]any{"status": string(types.StatusClosed)}, force: true, - }) - if got := forced.Fields[issueops.OpForceClosePolicy]; got != true { - t.Errorf("spec.Fields[%q] = %v, want true", issueops.OpForceClosePolicy, got) - } - if got := forced.Fields["status"]; got != string(types.StatusClosed) { - t.Errorf("spec.Fields[status] = %v, want closed", got) - } - - unforced := buildUpdateSpecForIssue(current, &updateInput{ - fields: map[string]any{"status": string(types.StatusClosed)}, - }) - if _, ok := unforced.Fields[issueops.OpForceClosePolicy]; ok { - t.Errorf("spec.Fields carries %q without --force", issueops.OpForceClosePolicy) - } -} +// The proxied path's own translation of `--force` is pinned in +// update_proxied_server_test.go (TestProxiedUpdateCarriesForce), against the +// UpdateRequest that path now hands issueops.Lifecycle — the spec it used to +// build by hand is gone. diff --git a/cmd/bd/update_proxied_integration_test.go b/cmd/bd/update_proxied_integration_test.go index 27b72f5b0..61b76c13c 100644 --- a/cmd/bd/update_proxied_integration_test.go +++ b/cmd/bd/update_proxied_integration_test.go @@ -537,14 +537,18 @@ func TestProxiedServerUpdate2(t *testing.T) { db := openProxiedDB(t, p) bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--no-history") - var noHistory int - if err := db.QueryRowContext(context.Background(), - "SELECT no_history FROM issues WHERE id = ?", issue.ID).Scan(&noHistory); err != nil { - t.Fatalf("read no_history: %v", err) - } - if noHistory != 1 { - t.Errorf("no_history: got %d, want 1 after --no-history", noHistory) + // --no-history selects a WISP RETENTION MODE, so the aggregate moves to + // the ephemeral plane rather than flipping a column on the durable row: + // issueops.IssuePatch.Persistence says "Ephemeral and NoHistory select + // wisp retention modes, never durable unversioned storage" and "every + // aggregate move is atomic". The direct route has always done this; the + // proxied route flipped the column in place until it joined the + // contract, which left a durable row that the wisp-plane reads could + // not see (bd-xt6de). + if got := readPersistenceFlag(t, db, "wisps", "no_history", issue.ID); got != 1 { + t.Errorf("wisps.no_history: got %d, want 1 after --no-history", got) } + assertRowAbsent(t, db, "issues", issue.ID) }) t.Run("update_persistent", func(t *testing.T) { @@ -574,14 +578,12 @@ func TestProxiedServerUpdate2(t *testing.T) { db := openProxiedDB(t, p) bdProxiedUpdateOne(t, bd, p.dir, issue.ID, "--ephemeral") - var ephemeral int - if err := db.QueryRowContext(context.Background(), - "SELECT ephemeral FROM issues WHERE id = ?", issue.ID).Scan(&ephemeral); err != nil { - t.Fatalf("read ephemeral: %v", err) - } - if ephemeral != 1 { - t.Errorf("ephemeral: got %d, want 1 after --ephemeral", ephemeral) + // The demotion moves the aggregate to the wisp plane; see + // update_no_history above for the clause and the history. + if got := readPersistenceFlag(t, db, "wisps", "ephemeral", issue.ID); got != 1 { + t.Errorf("wisps.ephemeral: got %d, want 1 after --ephemeral", got) } + assertRowAbsent(t, db, "issues", issue.ID) }) t.Run("reopen_reblocks_dependents", func(t *testing.T) { @@ -1236,6 +1238,19 @@ func TestProxiedServerUpdateWisp(t *testing.T) { }) } +// readPersistenceFlag reads one persistence column off whichever plane the row +// lives on. A persistence change is an aggregate MOVE, so the column and the +// table it is read from are one assertion, not two. +func readPersistenceFlag(t *testing.T, db *sql.DB, table, column, id string) int { + t.Helper() + var got int + q := "SELECT " + column + " FROM " + table + " WHERE id = ?" + if err := db.QueryRowContext(context.Background(), q, id).Scan(&got); err != nil { + t.Fatalf("read %s.%s for %s: %v", table, column, id, err) + } + return got +} + func assertRowExists(t *testing.T, db *sql.DB, table, id string) { t.Helper() var count int @@ -1363,12 +1378,13 @@ func TestProxiedServerUpdateConcurrentClaim(t *testing.T) { // the SAME issue. Every writer that exits 0 must have its key in the final // metadata, and the seed key must survive. // -// Before the fix this route lost writes two ways: buildUpdateSpecForIssue +// Before the fix this route lost writes two ways: the spec it built by hand // merged metadata from the unit of work's MVCC snapshot (erasing keys a // concurrent writer committed after the snapshot), and when Dolt's commit-time // merge rolled the loser back, uow.CommitWithRetries re-committed the // now-empty session — Dolt said "nothing to commit", the handler swallowed it, -// printed "✓ Updated", and exited 0 with the write gone. +// printed "✓ Updated", and exited 0 with the write gone. Both fixes now belong +// to issueops.Lifecycle, which is what this route calls. func TestProxiedServerUpdateConcurrentMetadata(t *testing.T) { requireProxiedServerEnv(t) bd := buildEmbeddedBD(t) diff --git a/cmd/bd/update_proxied_server.go b/cmd/bd/update_proxied_server.go index d359762c2..c9d7cfc34 100644 --- a/cmd/bd/update_proxied_server.go +++ b/cmd/bd/update_proxied_server.go @@ -11,20 +11,13 @@ import ( "github.com/steveyegge/beads/internal/hooks" "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/fs" - storageissueops "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/issueops" ) -// proxiedUpdateRetryMaxElapsed bounds the whole-attempt retry loop for one -// issue's update. A var so tests can shrink it when exercising conflict -// exhaustion; it tracks the shared default rather than restating it. -var proxiedUpdateRetryMaxElapsed = uow.DefaultTxRetryMaxElapsed - func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { if len(args) == 0 { return HandleErrorRespectJSON("no issue ID provided") @@ -77,129 +70,6 @@ func runUpdateProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri return nil } -// proxiedUpdateAttempt is what one read-merge-write attempt hands back to the -// shared retry loop. Exactly one of issue and fail is set; before and -// notesOverwritten feed the reporting that must run once per landed write -// rather than once per attempt. -type proxiedUpdateAttempt struct { - issue *types.Issue - before *types.Issue - fail *updateIDFailure - notesOverwritten bool -} - -// uowStageProvider records the errors the two stages the shared retry loop -// owns — opening the unit of work and committing it — hand back on the most -// recent attempt, so applyUpdateProxiedOne can attribute the error it gets -// from uow.RunTxResultWithin to the stage that produced it. The bespoke loop -// this replaced attributed errors inline, at the site that produced them; the -// recorded errors put attribution back on identity rather than on guesswork -// about what an error looks like. Both fields are reset on every NewUOW, so -// they describe the final attempt only. -type uowStageProvider struct { - uow.UnitOfWorkProvider - newUOWErr error - commitErr error -} - -func (p *uowStageProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) { - uw, err := p.UnitOfWorkProvider.NewUOW(ctx) - p.newUOWErr, p.commitErr = err, nil - if err != nil { - return uw, err - } - return &uowStageRecorder{UnitOfWork: uw, provider: p}, nil -} - -type uowStageRecorder struct { - uow.UnitOfWork - provider *uowStageProvider -} - -func (u *uowStageRecorder) Commit(ctx context.Context, message string) error { - err := u.UnitOfWork.Commit(ctx, message) - u.provider.commitErr = err - return err -} - -// applyUpdateProxiedOne applies one issue's update through uow.RunTxResultWithin, -// which redoes the WHOLE read-merge-write in a fresh unit of work when Dolt -// reports a serialization failure. It is the retry/commit implementation every -// unit-of-work write path shares: uow.RunTx and uow.RunTxResult both delegate -// to it. -// -// The retry must wrap the whole attempt, never just the commit: a -// serialization failure means the server already rolled the transaction back, -// so re-committing the same session (the old uow.CommitWithRetries call) can -// only ever produce "nothing to commit" — which the old code swallowed, -// printing "✓ Updated" and exiting 0 for a write that was silently lost. -// Redoing the attempt re-reads the winner's committed row, so merge -// operations (metadata edits, note appends) resolve against authoritative -// state instead of erasing it. -func applyUpdateProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) { - if uowProvider == nil { - return nil, nil, HandleError("proxied-server UOW provider not initialized") - } - if in.claim { - return applyClaimProxiedOne(ctx, id, in) - } - - provider := &uowStageProvider{UnitOfWorkProvider: uowProvider} - attempt, err := uow.RunTxResultWithin(ctx, provider, proxiedUpdateRetryMaxElapsed, - func(ctx context.Context, uw uow.UnitOfWork) (proxiedUpdateAttempt, string, error) { - return applyUpdateProxiedAttempt(ctx, uw, id, in) - }) - if err != nil { - // The retry loop hands back the error a stage returned, unchanged - // (backoff unwraps its Permanent envelope), so the errors recorded by - // provider identify the stage by identity. The one error no stage - // produced is the context's own: backoff substitutes ctx.Err() when - // cancellation cuts the loop short between attempts. - switch { - case provider.newUOWErr != nil && errors.Is(err, provider.newUOWErr): - fmt.Fprintf(os.Stderr, "Error opening unit of work for %s: %v\n", id, err) - return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("opening unit of work: %v", err)}, nil - case uow.IsSerializationError(err): - // Retries exhausted while 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 nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("retries exhausted on write conflicts: %v", err)}, nil - case provider.commitErr != nil && errors.Is(err, provider.commitErr): - fmt.Fprintf(os.Stderr, "Error committing %s: %v\n", id, err) - return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("committing: %v", err)}, nil - case errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): - // Cancellation cut the retry loop short between attempts (SIGINT - // cancels bd's root context). That is not a per-issue verdict: - // abort the whole batch, as the loop this replaced did. A commit - // that itself failed with a context error is NOT this case — it is - // a per-ID commit failure, caught by the arm above. - return nil, nil, err - default: - // Unreachable today: the attempt returns terminal per-issue - // failures as an attempt result, never as an error, so the only - // errors it can produce are serialization failures. Attribute - // anything new it grows to the update, which is where it came from. - fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) - return nil, &updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)}, nil - } - } - if attempt.fail != nil { - return nil, attempt.fail, nil - } - - // Post-commit reporting: the write has landed (or was the legitimately - // empty working set of a wisp-only update, which RunTxResultWithin - // tolerates), so these run exactly once no matter how many attempts the - // conflict retry burned. - if attempt.notesOverwritten { - warnNotesReplacement(id) - } - if err := fireProxiedUpdateHooks(ctx, attempt.before, attempt.issue); err != nil { - fmt.Fprintf(os.Stderr, "warning: %s: %v\n", id, err) - } - return attempt.issue, nil, nil -} - // proxiedIssueLifecycle asks the unit-of-work provider for the write role, the // same way proxiedIssueReader asks it for the read one. The accessor is the // door: a provider that cannot answer says so rather than being wired around. @@ -214,34 +84,40 @@ func proxiedIssueLifecycle() (issueops.Lifecycle, error) { return src.IssueLifecycle() } -// applyClaimProxiedOne applies one issue's --claim update through -// issueops.Lifecycle rather than through a hand-rolled attempt. +// applyUpdateProxiedOne applies one issue's update — plain or --claim — +// through issueops.Lifecycle rather than through a hand-rolled attempt. // -// THE CLAIM IS NOT IMPLEMENTED HERE, and that is the point. The CAS, the -// eligibility rules, the claim-pool case, the issue-or-wisp resolve, the -// whole-attempt retry, the commit and the exact text of both refusals belong to -// the contract, which `bd serve`'s claim endpoint now reaches through the same -// call. What stays here is this surface's own protocol: the template guard, the -// per-id failure taxonomy the multi-id batch needs, the notes-overwrite warning -// and the completion hooks — none of which the HTTP surface has, and none of -// which is a claim. +// THE UPDATE IS NOT IMPLEMENTED HERE, and that is the point. The read-merge-write, +// the merge-shaped metadata and note edits resolved against the row re-read +// inside the mutation transaction, the assignee fence, the close policy, the +// conditional-update compare-and-set, the claim's own CAS and eligibility +// rules, the issue-or-wisp resolve, the whole-attempt conflict retry and the +// commit all belong to the contract. Every one of them had a second +// implementation in this file until this commit; the claim already answered to +// the contract, and now the plain update does too. +// +// What stays here is this surface's own protocol: the template guard, the +// advisory reassign pre-read, the per-id failure taxonomy the multi-id batch +// needs, the notes-overwrite warning and the completion hooks — none of which +// the HTTP surface has, and none of which is an update. // // 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 --claim` has always resolved a wisp -// id, unlike the HTTP endpoint, which serves durable issues only. +// 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 claim, so -// the template guard is advisory in a way it was not when this file did the -// read itself. It guards a command-shaped policy, not an invariant — the -// mutation's own guards are all inside the contract's transaction — and paying -// for it is what lets the claim itself have exactly one implementation. -func applyClaimProxiedOne(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure, error) { +// The pre-read is a read of its own, one transaction earlier than the +// mutation, so the guards it applies are advisory in a way they were not when +// this file did the read itself. They guard command-shaped policy, not +// invariants — the mutation's own guards are all inside the contract's +// transaction, including the fence and the close policy — and paying for it is +// what lets the update itself have exactly one implementation. +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 := proxiedClaimTarget(ctx, id) + before, fail := proxiedUpdateTarget(ctx, id, in) if fail != nil { return nil, fail, nil } @@ -252,51 +128,59 @@ func applyClaimProxiedOne(ctx context.Context, id string, in *updateInput) (*typ } 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: actor, - issueID: id, - patch: patch, - claim: true, - force: in.force, - // The guards are nil by construction: gatherUpdateInput refuses - // --if-assignee/--if-status alongside --claim, which is also what the - // request contract requires of a claim. - provenance: fmt.Sprintf("bd: update %s", id), + actor: actor, + issueID: id, + patch: patch, + claim: in.claim, + force: in.force, + expectedAssignee: in.ifAssignee, + expectedStatus: expectedStatus, + 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. Abort the batch, as the non-claim path above still does. The - // contract owns the unit of work now, so a commit that itself failed - // with a context error is indistinguishable from a cancellation between - // attempts; aborting is the right call for both. + // way. Abort the batch, as the loop this replaced did. The contract owns + // the unit of work now, so 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 } - return nil, proxiedClaimFailure(id, err), nil + return nil, proxiedUpdateFailure(id, err), nil } updated := result.Issue if updated == nil { - fmt.Fprintf(os.Stderr, "Error updating %s: the claim reported no issue\n", id) + 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 - // A CLAIM answers an already-published surface, and that surface is the - // bare row. issueops.ClaimResult says so outright — labels, dependency - // records and comments omitted, and "enriching it is a decision for the - // next revision window, not a side effect of moving the operation onto a - // role." Routing this path through Lifecycle hydrates labels, which is - // exactly that side effect, so they come back off here. - // - // This is what keeps `bd update --claim --json` byte-identical to the v0 - // claim response, which TestProxiedServerServeClaim asserts with an EMPTY - // allowlist: any difference at all between the two surfaces is a real - // divergence. The non-claim update path above is untouched and still - // carries labels. - updated.Labels = nil - updated.Comments = nil + if in.claim { + // A CLAIM answers an already-published surface, and that surface is the + // bare row. issueops.ClaimResult says so outright — labels, dependency + // records and comments omitted, and "enriching it is a decision for the + // next revision window, not a side effect of moving the operation onto a + // role." Routing this path through Lifecycle hydrates labels, which is + // exactly that side effect, so they come back off here. + // + // This is what keeps `bd update --claim --json` byte-identical to the v0 + // claim response, which TestProxiedServerServeClaim asserts with an EMPTY + // allowlist: any difference at all between the two surfaces is a real + // divergence. A plain update carries labels, as the direct route's 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. @@ -309,11 +193,13 @@ func applyClaimProxiedOne(ctx context.Context, id string, in *updateInput) (*typ return updated, nil, nil } -// proxiedClaimTarget reads the row a claim is about through the query role, for -// the three things the claim's own result cannot answer: whether the target is -// a template, whether --notes is about to replace existing notes, and whether +// proxiedUpdateTarget reads the row an update is about through the query role, +// for the things the mutation's own result cannot answer: whether the target is +// a template, whether an unguarded assignee edit is about to take the issue +// from a live foreign holder, whether --notes is about to replace existing +// notes, whether --defer="" should also clear a deferred status, and whether // the update closes an open issue (which fires a second hook). -func proxiedClaimTarget(ctx context.Context, id string) (*types.Issue, *updateIDFailure) { +func proxiedUpdateTarget(ctx context.Context, id string, in *updateInput) (*types.Issue, *updateIDFailure) { rd, err := proxiedIssueReader() if err != nil { fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) @@ -333,19 +219,57 @@ func proxiedClaimTarget(ctx context.Context, id string) (*types.Issue, *updateID fmt.Fprintf(os.Stderr, "%s\n", err) return nil, &updateIDFailure{ID: id, Error: err.Error()} } + // bd-98s5c: an unguarded assignee update must not silently overwrite + // another actor's live claim. Skipped under --if-assignee: that CAS names + // the holder explicitly (park stays possible without --force). Also skipped + // under --claim: the claim CAS is itself the anti-steal gate (a foreign live + // claim fails it with the canonical "already claimed" copy), and an assignee + // edit that rides a WON claim only ever touches the actor's own fresh claim. + // 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, exactly as update.go's own pre-read does. + // A policy refusal: terminal per-issue failure, exit 1, never + // GuardMismatch/13. + if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim { + if err := validateIssueReassignable(id, current, actor, newAssignee, + proxiedClaimPoolAliases(ctx), in.force); err != nil { + fmt.Fprintf(os.Stderr, "%s\n", err) + return nil, &updateIDFailure{ID: id, Error: err.Error()} + } + } return current, nil } -// proxiedClaimFailure sorts a refused claim into the same per-id verdicts, with -// the same copy, the hand-rolled attempt below produces. A guard refusal sets -// GuardMismatch so the batch exits 13 rather than 1. +// proxiedClaimPoolAliases is uowClaimPoolAliases for a caller that owns no unit +// of work. The mutation's transaction belongs to the contract now, so 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, with +// the same copy, the hand-rolled attempt this file used to run produced. A +// guard refusal sets GuardMismatch so the batch exits 13 rather than 1. // // 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. That is the // price of the contract owning the transaction, and it costs a word in the // message, not a verdict — the id still fails, loudly and non-zero. -func proxiedClaimFailure(id string, err error) *updateIDFailure { +func proxiedUpdateFailure(id string, err error) *updateIDFailure { switch { case errors.Is(err, storage.ErrNotFound): fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) @@ -365,6 +289,9 @@ func proxiedClaimFailure(id string, err error) *updateIDFailure { 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: @@ -419,109 +346,6 @@ func proxiedUpdatePatch(in *updateInput, before *types.Issue) (issueops.IssuePat return patch, nil } -// applyUpdateProxiedAttempt runs one full read-merge-write attempt in the fresh -// unit of work handed to it. It returns a serialization failure verbatim so the -// shared retry loop redoes the whole attempt — the server-side rollback -// guarantees nothing landed. Terminal per-issue failures (not found, claim -// conflicts, guard mismatches) print to stderr and come back as a non-nil fail -// with an empty commit message, so nothing is committed, the multi-ID loop -// records the failed ID, keeps going, and still exits non-zero — matching the -// non-proxied path. A guard refusal sets fail.GuardMismatch so the exit code -// distinguishes it (ExitGuardMismatch vs 1). -func applyUpdateProxiedAttempt(ctx context.Context, uw uow.UnitOfWork, id string, in *updateInput) (proxiedUpdateAttempt, string, error) { - issueUC := uw.IssueUseCase() - current, err := issueUC.GetIssue(ctx, id) - if err != nil || current == nil { - wispCurrent, wispErr := issueUC.GetWisp(ctx, id) - if wispErr == nil && wispCurrent != nil { - current = wispCurrent - } else if err != nil { - fmt.Fprintf(os.Stderr, "Error resolving %s: %v\n", id, err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: fmt.Sprintf("resolving issue: %v", err)}) - } else { - fmt.Fprintf(os.Stderr, "Issue %s not found\n", id) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: "issue not found"}) - } - } - if err := validateIssueUpdatable(id, current); err != nil { - fmt.Fprintf(os.Stderr, "%s\n", err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: err.Error()}) - } - - // bd-98s5c: an unguarded assignee update must not silently overwrite - // another actor's live claim. Skipped under --if-assignee: that CAS names - // the holder explicitly (park stays possible without --force). Also - // skipped under --claim: the claim CAS is itself the anti-steal gate (a - // foreign live claim fails it with the canonical "already claimed" copy), - // and an assignee edit that rides a WON claim only ever touches the - // actor's own fresh claim. The proxied-server path is where cross-actor - // collisions actually happen — every shared-dolt-server clone writes - // through here. A policy refusal: terminal per-issue failure, exit 1, - // never GuardMismatch/13. - if newAssignee, ok := in.fields["assignee"].(string); ok && in.ifAssignee == nil && !in.claim { - if err := validateIssueReassignable(id, current, actor, newAssignee, - uowClaimPoolAliases(ctx, uw), in.force); err != nil { - fmt.Fprintf(os.Stderr, "%s\n", err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: err.Error()}) - } - } - - spec := buildUpdateSpecForIssue(current, in) - notesOverwritten := replacesExistingNotes(current.Notes, in.fields) - - updated, err := issueUC.ApplyUpdate(ctx, id, spec, actor) - if err != nil { - if uow.IsSerializationError(err) { - return proxiedUpdateAttempt{}, "", err - } - if errors.Is(err, storage.ErrAlreadyClaimed) || errors.Is(err, storage.ErrNotClaimable) { - fmt.Fprintf(os.Stderr, "Error claiming %s: %v\n", id, err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: fmt.Sprintf("claiming issue: %v", err)}) - } - // Close policy refused the status change. Same copy the proxied close - // prints for the same two refusals, so the boundary reads identically - // whichever verb a script reached it through. A policy refusal is a - // terminal per-issue failure — exit 1, never GuardMismatch/13. - if errors.Is(err, storage.ErrCloseOpenChildren) { - fmt.Fprintf(os.Stderr, "%v\n", err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: err.Error()}) - } - if errors.Is(err, storage.ErrCloseBlocked) { - fmt.Fprintf(os.Stderr, "%v (use --force to override)\n", err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: fmt.Sprintf("%v (use --force to override)", err)}) - } - if 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 failedUpdateAttempt(&updateIDFailure{ID: id, Error: fmt.Sprintf("precondition failed: %v", err), GuardMismatch: true}) - } - fmt.Fprintf(os.Stderr, "Error updating %s: %v\n", id, err) - return failedUpdateAttempt(&updateIDFailure{ID: id, Error: fmt.Sprintf("updating: %v", err)}) - } - - // The commit belongs to RunTxResultWithin: it retries the whole attempt on a - // serialization failure (Dolt rolled the transaction back server-side, so - // nothing landed) and tolerates "nothing to commit", the legitimately-empty - // working set of a wisp-only update — those live in dolt_ignored tables, so a - // successful ApplyUpdate can leave the Dolt commit layer with nothing to do. - // The lost-write flavor of nothing-to-commit — re-committing a rolled-back - // session — cannot arise, because each attempt commits its own fresh unit of - // work exactly once. - return proxiedUpdateAttempt{ - issue: updated, - before: current, - notesOverwritten: notesOverwritten, - }, fmt.Sprintf("bd: update %s", id), nil -} - -// failedUpdateAttempt returns a terminal per-issue failure with no commit -// message, so the shared retry loop skips the commit and stops retrying. -func failedUpdateAttempt(fail *updateIDFailure) (proxiedUpdateAttempt, string, error) { - return proxiedUpdateAttempt{fail: fail}, "", nil -} - func fireProxiedUpdateHooks(ctx context.Context, before, after *types.Issue) error { if after == nil { return nil @@ -561,53 +385,3 @@ func proxiedHookRunner(ctx context.Context) (*hooks.Runner, error) { } return hooks.NewRunner(filepath.Join(resolution.BeadsDir, "hooks")), nil } - -// buildUpdateSpecForIssue translates gathered CLI input into a domain -// UpdateSpec. It never pre-merges row state: merge-shaped edits are passed as -// operation keys and resolved by the repository inside the mutation -// transaction. -func buildUpdateSpecForIssue(current *types.Issue, in *updateInput) domain.UpdateSpec { - fields := make(map[string]any, len(in.fields)) - for k, v := range in.fields { - fields[k] = v - } - - if in.clearDeferStatus && current.Status == types.StatusDeferred { - fields["status"] = string(types.StatusOpen) - } - // Metadata edits and note appends pass through as merge OPERATIONS: the - // repository resolves them against the row re-read inside the mutation - // transaction (issueops.ResolveMergeOps via the domain/db Update path). - // Merging here against `current` — a read from this unit of work's MVCC - // snapshot — silently erased keys a concurrent writer committed after our - // snapshot was taken: both processes exited 0, one write vanished. - if in.hasAppendNotes { - fields[storageissueops.OpAppendNotes] = in.appendNotes - } - if len(in.mergeMetadataIn) > 0 { - fields[storageissueops.OpMergeMetadata] = in.mergeMetadataIn - } - if len(in.setMetadata) > 0 { - fields[storageissueops.OpSetMetadata] = in.setMetadata - } - if len(in.unsetMetadata) > 0 { - fields[storageissueops.OpUnsetMetadata] = in.unsetMetadata - } - // --force means both of its halves here too. The assignee half is applied - // above by validateIssueReassignable; this is the close-policy half, which - // the repository pops before it validates fields. - if in.force { - fields[storageissueops.OpForceClosePolicy] = true - } - - return domain.UpdateSpec{ - Fields: fields, - Claim: in.claim, - AddLabels: in.addLabels, - RemoveLabels: in.removeLabels, - SetLabels: in.setLabels, - Reparent: in.reparent, - ExpectedAssignee: in.ifAssignee, - ExpectedStatus: in.ifStatus, - } -} diff --git a/cmd/bd/update_proxied_server_test.go b/cmd/bd/update_proxied_server_test.go index 891825147..ccd3439a1 100644 --- a/cmd/bd/update_proxied_server_test.go +++ b/cmd/bd/update_proxied_server_test.go @@ -4,160 +4,24 @@ import ( "context" "encoding/json" "errors" + "fmt" "io" "os" "strings" - "sync/atomic" "testing" - "time" mysql "github.com/go-sql-driver/mysql" - "github.com/steveyegge/beads/internal/hooks" - "github.com/steveyegge/beads/internal/storage/domain" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/issueops" ) -// TestBuildUpdateSpecForIssue_RoutesMergeOpsAsOperations locks in the -// lost-update fix on the proxied-server route: metadata edits and note -// appends must flow into spec.Fields as merge OPERATION keys, never as values -// pre-merged from `current` (a read from this unit of work's MVCC snapshot — -// merging there erased keys a concurrent writer committed after the snapshot). -func TestBuildUpdateSpecForIssue_RoutesMergeOpsAsOperations(t *testing.T) { - current := &types.Issue{ - ID: "bd-spec-1", - Status: types.StatusOpen, - Notes: "existing notes", - Metadata: json.RawMessage(`{"existing":"yes"}`), - } - - t.Run("append_notes", func(t *testing.T) { - in := &updateInput{ - fields: map[string]any{}, - hasAppendNotes: true, - appendNotes: "appended", - } - spec := buildUpdateSpecForIssue(current, in) - if got, ok := spec.Fields[issueops.OpAppendNotes]; !ok || got != "appended" { - t.Errorf("Fields[%s] = %v (ok=%v), want the raw append text", issueops.OpAppendNotes, got, ok) - } - if merged, ok := spec.Fields["notes"]; ok { - t.Errorf("Fields[notes] = %v: notes must NOT be pre-merged from the snapshot", merged) - } - }) - - t.Run("merge_metadata", func(t *testing.T) { - in := &updateInput{ - fields: map[string]any{}, - mergeMetadataIn: json.RawMessage(`{"new":"key"}`), - } - spec := buildUpdateSpecForIssue(current, in) - raw, ok := spec.Fields[issueops.OpMergeMetadata].(json.RawMessage) - if !ok || string(raw) != `{"new":"key"}` { - t.Errorf("Fields[%s] = %v, want the raw incoming JSON", issueops.OpMergeMetadata, spec.Fields[issueops.OpMergeMetadata]) - } - if merged, ok := spec.Fields["metadata"]; ok { - t.Errorf("Fields[metadata] = %v: metadata must NOT be pre-merged from the snapshot", merged) - } - }) - - t.Run("set_and_unset_metadata", func(t *testing.T) { - in := &updateInput{ - fields: map[string]any{}, - setMetadata: []string{"tier=gold"}, - unsetMetadata: []string{"existing"}, - } - spec := buildUpdateSpecForIssue(current, in) - set, _ := spec.Fields[issueops.OpSetMetadata].([]string) - unset, _ := spec.Fields[issueops.OpUnsetMetadata].([]string) - if len(set) != 1 || set[0] != "tier=gold" { - t.Errorf("Fields[%s] = %v, want [tier=gold]", issueops.OpSetMetadata, spec.Fields[issueops.OpSetMetadata]) - } - if len(unset) != 1 || unset[0] != "existing" { - t.Errorf("Fields[%s] = %v, want [existing]", issueops.OpUnsetMetadata, spec.Fields[issueops.OpUnsetMetadata]) - } - if merged, ok := spec.Fields["metadata"]; ok { - t.Errorf("Fields[metadata] = %v: metadata must NOT be pre-merged from the snapshot", merged) - } - }) - - t.Run("clear_defer_status_still_resolved_from_current", func(t *testing.T) { - deferred := &types.Issue{ID: "bd-spec-2", Status: types.StatusDeferred} - in := &updateInput{fields: map[string]any{}, clearDeferStatus: true} - spec := buildUpdateSpecForIssue(deferred, in) - if got := spec.Fields["status"]; got != string(types.StatusOpen) { - t.Errorf("Fields[status] = %v, want open (clearDeferStatus on a deferred issue)", got) - } - }) -} - -// --- fakes for the whole-attempt retry tests --- - -type fakeUpdateIssueUC struct { - domain.IssueUseCase // unimplemented methods panic; the attempt path must not call them - issue *types.Issue -} - -func (f *fakeUpdateIssueUC) GetIssue(ctx context.Context, id string) (*types.Issue, error) { - return f.issue, nil -} - -func (f *fakeUpdateIssueUC) ApplyUpdate(ctx context.Context, id string, spec domain.UpdateSpec, actor string) (*types.Issue, error) { - return f.issue, nil -} - -type fakeUOW struct { - issueUC domain.IssueUseCase - commit func() error -} - -func (f *fakeUOW) Close(ctx context.Context) {} -func (f *fakeUOW) Commit(ctx context.Context, message string) error { return f.commit() } -func (f *fakeUOW) SwitchDatabase(ctx context.Context, database string) error { return nil } -func (f *fakeUOW) ConfigUseCase() domain.ConfigUseCase { return nil } -func (f *fakeUOW) DoltRemoteUseCase() domain.DoltRemoteUseCase { return nil } -func (f *fakeUOW) BootstrapUseCase() domain.BootstrapUseCase { return nil } -func (f *fakeUOW) IssueUseCase() domain.IssueUseCase { return f.issueUC } -func (f *fakeUOW) DependencyUseCase() domain.DependencyUseCase { return nil } -func (f *fakeUOW) LabelUseCase() domain.LabelUseCase { return nil } -func (f *fakeUOW) CommentUseCase() domain.CommentUseCase { return nil } -func (f *fakeUOW) RawSQLUseCase() domain.RawSQLUseCase { return nil } - -type fakeUOWProvider struct { - uows atomic.Int64 - newUOW func(attempt int64) error - commit func(attempt int64) error - issue *types.Issue -} - -func (p *fakeUOWProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) { - n := p.uows.Add(1) - if p.newUOW != nil { - if err := p.newUOW(n); err != nil { - return nil, err - } - } - return &fakeUOW{ - issueUC: &fakeUpdateIssueUC{issue: p.issue}, - commit: func() error { return p.commit(n) }, - }, nil -} - -func (p *fakeUOWProvider) Close(ctx context.Context) error { return nil } - -func withFakeProxiedUpdateEnv(t *testing.T, p *fakeUOWProvider) { - t.Helper() - oldProvider := uowProvider - oldHookRunner := hookRunner - uowProvider = p - hookRunner = hooks.NewRunner(t.TempDir()) // no hooks installed: RunSync no-ops - t.Cleanup(func() { - uowProvider = oldProvider - hookRunner = oldHookRunner - }) -} +// The plain proxied update joined the claim on issueops.Lifecycle, so these pin +// the same three things its sibling in update_claim_proxied_test.go pins: the +// request this surface makes, the roles it reaches them through, and the fact +// that it opens no unit of work of its own. The update's behaviour against real +// Dolt is the integration suite's job. func captureStderrDuring(t *testing.T, fn func()) string { t.Helper() @@ -185,241 +49,264 @@ func serializationFailure() error { return &mysql.MySQLError{Number: 1213, Message: "serialization failure, transaction rolled back"} } -// TestApplyUpdateProxiedOne_RetriesWholeAttemptOnConflict proves a Dolt -// serialization failure at commit time redoes the WHOLE read-merge-write in a -// fresh unit of work — not just the commit. Re-committing the rolled-back -// session was the old behavior; the server had already discarded the writes, -// so the retry could only report "nothing to commit" and the update vanished. -func TestApplyUpdateProxiedOne_RetriesWholeAttemptOnConflict(t *testing.T) { - issue := &types.Issue{ID: "bd-retry-1", Status: types.StatusOpen} - provider := &fakeUOWProvider{ - issue: issue, - commit: func(attempt int64) error { - if attempt <= 2 { - return serializationFailure() - } - return nil - }, - } - withFakeProxiedUpdateEnv(t, provider) +func TestProxiedUpdateRunsOnTheLifecycleContract(t *testing.T) { + before := &types.Issue{ID: "bd-1", Status: types.StatusOpen, Title: "Original"} + after := &types.Issue{ID: "bd-1", Status: types.StatusOpen, Title: "Renamed", Labels: []string{"keep"}} + p := claimRoleFixture(t, before, issueops.UpdateResult{Issue: after, Changed: true}, nil) - in := &updateInput{fields: map[string]any{"title": "renamed"}} - got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-retry-1", in) - if err != nil { - t.Fatalf("applyUpdateProxiedOne: %v", err) + oldActor := actor + actor = "agent" + t.Cleanup(func() { actor = oldActor }) + + in := &updateInput{fields: map[string]any{"title": "Renamed"}} + got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-1", in) + if err != nil || fail != nil { + t.Fatalf("applyUpdateProxiedOne: err = %v, fail = %+v", err, fail) } - if fail != nil { - t.Fatalf("expected update to succeed after conflict retries, got failure: %s", fail.Error) + if got == nil || got.Title != "Renamed" { + t.Fatalf("updated issue = %+v, want the renamed row", got) } - if got == nil || got.ID != "bd-retry-1" { - t.Fatalf("updated issue = %v, want bd-retry-1", got) + // Only the claim strips labels, to keep its published response shape; a + // plain update carries them, as the direct route's does. + if len(got.Labels) != 1 || got.Labels[0] != "keep" { + t.Errorf("labels = %v, wanted the contract's hydrated labels kept on a plain update", got.Labels) } - if n := provider.uows.Load(); n != 3 { - t.Errorf("unit-of-work attempts = %d, want 3 (each conflict must redo the whole read-merge-write)", n) + + req := p.lifecycle.request + if req.Claim { + t.Error("a plain update reached the contract as a claim") + } + if req.Actor != "agent" || req.IssueID != "bd-1" || !req.Patch.Title.Set || req.Patch.Title.Value != "Renamed" { + t.Errorf("request = %+v, want a title edit of bd-1 by agent", req) + } + // The commit message this path has always written, carried on the request + // instead of being spelled at the commit site. + if req.Provenance != "bd: update bd-1" { + t.Errorf("Provenance = %q, want the message the proxied update has always written", req.Provenance) + } + // A CLI update resolves either plane; only the HTTP surface restricts it. + if req.IssuePlaneOnly { + t.Error("the CLI update restricted the plane; `bd update` has always resolved a wisp id") + } + if p.uows != 0 { + t.Errorf("the update path opened %d units of work; the contract owns the transaction", p.uows) } } -// TestApplyUpdateProxiedOne_ExhaustedConflictsFailLoudly proves a write that -// never lands cannot exit as a success: when every attempt loses Dolt's -// commit-time merge, the command reports the failure instead of printing -// "✓ Updated" (a non-empty failReason suppresses the success line and drives -// the non-zero exit via reportUpdateFailures in runUpdateProxiedServer). -func TestApplyUpdateProxiedOne_ExhaustedConflictsFailLoudly(t *testing.T) { - oldMax := proxiedUpdateRetryMaxElapsed - proxiedUpdateRetryMaxElapsed = 150 * time.Millisecond - t.Cleanup(func() { proxiedUpdateRetryMaxElapsed = oldMax }) - - issue := &types.Issue{ID: "bd-retry-2", Status: types.StatusOpen} - provider := &fakeUOWProvider{ - issue: issue, - commit: func(int64) error { return serializationFailure() }, +// TestProxiedUpdatePatchRoutesMergeOpsAsOperations locks in the lost-update fix +// on the proxied-server route: metadata edits and note appends must reach the +// contract as merge OPERATIONS, never as values pre-merged from the pre-read +// row (a read from an earlier transaction — merging there erased keys a +// concurrent writer committed after it). +func TestProxiedUpdatePatchRoutesMergeOpsAsOperations(t *testing.T) { + current := &types.Issue{ + ID: "bd-spec-1", + Status: types.StatusOpen, + Notes: "existing notes", + Metadata: json.RawMessage(`{"existing":"yes"}`), } - withFakeProxiedUpdateEnv(t, provider) - var got *types.Issue - var fail *updateIDFailure - var err error + t.Run("append_notes", func(t *testing.T) { + patch := mustProxiedUpdatePatch(t, &updateInput{ + fields: map[string]any{}, + hasAppendNotes: true, + appendNotes: "appended", + }, current) + if !patch.AppendNotes.Set || patch.AppendNotes.Value != "appended" { + t.Errorf("AppendNotes = %+v, want the raw append text", patch.AppendNotes) + } + if patch.Notes.Set { + t.Errorf("Notes = %+v: notes must NOT be pre-merged from the pre-read row", patch.Notes) + } + }) + + t.Run("merge_metadata", func(t *testing.T) { + patch := mustProxiedUpdatePatch(t, &updateInput{ + fields: map[string]any{}, + mergeMetadataIn: json.RawMessage(`{"new":"key"}`), + }, current) + if !patch.Metadata.Merge.Set || string(patch.Metadata.Merge.Value) != `{"new":"key"}` { + t.Errorf("Metadata.Merge = %+v, want the raw incoming JSON", patch.Metadata.Merge) + } + if patch.Metadata.Replace.Set { + t.Errorf("Metadata.Replace = %+v: metadata must NOT be pre-merged from the pre-read row", patch.Metadata.Replace) + } + }) + + t.Run("set_and_unset_metadata", func(t *testing.T) { + patch := mustProxiedUpdatePatch(t, &updateInput{ + fields: map[string]any{}, + setMetadata: []string{"tier=gold"}, + unsetMetadata: []string{"existing"}, + }, current) + if got := string(patch.Metadata.Set["tier"]); got != `"gold"` { + t.Errorf("Metadata.Set[tier] = %s, want the JSON string value", got) + } + if len(patch.Metadata.Unset) != 1 || patch.Metadata.Unset[0] != "existing" { + t.Errorf("Metadata.Unset = %v, want [existing]", patch.Metadata.Unset) + } + if patch.Metadata.Replace.Set { + t.Errorf("Metadata.Replace = %+v: metadata must NOT be pre-merged from the pre-read row", patch.Metadata.Replace) + } + }) + + t.Run("clear_defer_status_resolved_from_the_pre_read_row", func(t *testing.T) { + deferred := &types.Issue{ID: "bd-spec-2", Status: types.StatusDeferred} + patch := mustProxiedUpdatePatch(t, &updateInput{fields: map[string]any{}, clearDeferStatus: true}, deferred) + if !patch.Status.Set || patch.Status.Value != types.StatusOpen { + t.Errorf("Status = %+v, want open (clearDeferStatus on a deferred issue)", patch.Status) + } + open := &types.Issue{ID: "bd-spec-3", Status: types.StatusBlocked} + if patch := mustProxiedUpdatePatch(t, &updateInput{fields: map[string]any{}, clearDeferStatus: true}, open); patch.Status.Set { + t.Errorf("Status = %+v, want unset: --defer=\"\" must not clobber a non-deferred status", patch.Status) + } + }) +} + +func mustProxiedUpdatePatch(t *testing.T, in *updateInput, before *types.Issue) issueops.IssuePatch { + t.Helper() + patch, err := proxiedUpdatePatch(in, before) + if err != nil { + t.Fatalf("proxiedUpdatePatch: %v", err) + } + return patch +} + +// TestProxiedUpdateCarriesForce pins the proxied path's translation of +// `--force`. An earlier attempt was reverted for exactly this missing mapping: +// the proxied caller built a request that never carried the override, so a +// shared policy check refused the close with no way for the user to say +// otherwise. One flag, two overrides — and the assignee half only applies to an +// assignee edit, so `--force -s closed` asks for the close-policy half alone. +func TestProxiedUpdateCarriesForce(t *testing.T) { + closing := map[string]any{"status": string(types.StatusClosed)} + + forced := recordProxiedUpdateRequest(t, &updateInput{fields: closing, force: true}) + if !forced.ForceClosePolicy { + t.Error("ForceClosePolicy = false with --force") + } + if forced.ForceAssigneeTransfer { + t.Error("ForceAssigneeTransfer = true without an assignee edit to authorize") + } + + unforced := recordProxiedUpdateRequest(t, &updateInput{fields: closing}) + if unforced.ForceClosePolicy { + t.Error("ForceClosePolicy = true without --force") + } + + transfer := recordProxiedUpdateRequest(t, &updateInput{ + fields: map[string]any{"assignee": "thief"}, force: true, + }) + if !transfer.ForceAssigneeTransfer || !transfer.ForceClosePolicy { + t.Errorf("request = %+v, want --force to carry both halves on an assignee edit", transfer) + } +} + +// TestProxiedUpdateCarriesConditionalGuards pins the bd-wsqvw guards onto the +// request. They used to be applied by this file's own read-merge-write; the +// contract now runs the compare-and-set inside the mutation transaction, which +// is the only place it can be atomic with the write it gates. +func TestProxiedUpdateCarriesConditionalGuards(t *testing.T) { + holder, status := "alice", string(types.StatusInProgress) + req := recordProxiedUpdateRequest(t, &updateInput{ + fields: map[string]any{"priority": 0}, + ifAssignee: &holder, + ifStatus: &status, + }) + if req.ExpectedAssignee == nil || *req.ExpectedAssignee != "alice" { + t.Errorf("ExpectedAssignee = %v, want alice", req.ExpectedAssignee) + } + if req.ExpectedStatus == nil || *req.ExpectedStatus != types.StatusInProgress { + t.Errorf("ExpectedStatus = %v, want in_progress", req.ExpectedStatus) + } +} + +func recordProxiedUpdateRequest(t *testing.T, in *updateInput) issueops.UpdateRequest { + t.Helper() + before := &types.Issue{ID: "bd-1", Status: types.StatusOpen} + p := claimRoleFixture(t, before, issueops.UpdateResult{Issue: before, Changed: true}, nil) + if _, fail, err := applyUpdateProxiedOne(context.Background(), "bd-1", in); err != nil || fail != nil { + t.Fatalf("applyUpdateProxiedOne: err = %v, fail = %+v", err, fail) + } + return p.lifecycle.request +} + +// TestProxiedUpdateExhaustedConflictsFailLoudly proves a write that never lands +// cannot exit as a success: when the contract spends its retry budget losing +// Dolt's commit-time merge, the command reports the failure instead of printing +// "✓ Updated" (a recorded failure suppresses the success line and drives the +// non-zero exit via reportUpdateFailures in runUpdateProxiedServer). +func TestProxiedUpdateExhaustedConflictsFailLoudly(t *testing.T) { + before := &types.Issue{ID: "bd-retry-2", Status: types.StatusOpen} + claimRoleFixture(t, before, issueops.UpdateResult{}, serializationFailure()) + + var ( + got *types.Issue + fail *updateIDFailure + err error + ) stderr := captureStderrDuring(t, func() { in := &updateInput{fields: map[string]any{"title": "never lands"}} got, fail, err = applyUpdateProxiedOne(context.Background(), "bd-retry-2", in) }) if err != nil { - t.Fatalf("applyUpdateProxiedOne returned hard error: %v", err) + t.Fatalf("applyUpdateProxiedOne returned a hard error: %v", err) } if fail == nil || got != nil { t.Fatalf("fail=%v issue=%v: a write that never landed must be reported as a failure", fail, got) } if fail.GuardMismatch { - t.Errorf("exhausted conflicts must not masquerade as a guard mismatch (that would exit 13 and tell scripts not to retry)") + t.Error("exhausted conflicts must not masquerade as a guard mismatch (that would exit 13 and tell scripts not to retry)") } if !strings.Contains(stderr, "retries exhausted") { t.Errorf("stderr = %q, want a loud retries-exhausted failure", stderr) } - if n := provider.uows.Load(); n < 2 { - t.Errorf("unit-of-work attempts = %d, want at least 2 before giving up", n) - } } -// TestApplyUpdateProxiedOne_NothingToCommitWithoutConflictSucceeds preserves -// the one legitimate nothing-to-commit case: wisp-only updates write to -// dolt_ignored tables, so a successful ApplyUpdate can leave the Dolt commit -// layer with nothing to do. That is a success, not a lost write — no -// serialization failure preceded it. -func TestApplyUpdateProxiedOne_NothingToCommitWithoutConflictSucceeds(t *testing.T) { - issue := &types.Issue{ID: "bd-retry-3", Status: types.StatusOpen} - provider := &fakeUOWProvider{ - issue: issue, - commit: func(int64) error { return errors.New("nothing to commit") }, - } - withFakeProxiedUpdateEnv(t, provider) +// TestProxiedUpdateGuardMismatchExitsThirteen keeps the one failure class that +// gets its own exit code: a stale --if-assignee/--if-status wrote nothing and +// retrying is pointless, so the batch must exit 13 rather than 1. +func TestProxiedUpdateGuardMismatchExitsThirteen(t *testing.T) { + before := &types.Issue{ID: "bd-guard-1", Status: types.StatusOpen} + claimRoleFixture(t, before, issueops.UpdateResult{}, + fmt.Errorf("%w: bd-guard-1 has status %q, expected %q", storage.ErrStatusMismatch, "open", "in_progress")) - in := &updateInput{fields: map[string]any{"title": "wisp-shaped"}} - got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-retry-3", in) - if err != nil { - t.Fatalf("applyUpdateProxiedOne: %v", err) - } - if fail != nil || got == nil { - t.Fatalf("fail=%v issue=%v: empty-working-set commit on an unconflicted attempt is a success", fail, got) - } - if n := provider.uows.Load(); n != 1 { - t.Errorf("unit-of-work attempts = %d, want 1 (nothing-to-commit must not trigger retries)", n) - } -} - -// TestApplyUpdateProxiedOne_NewUOWFailureIsPerIDFailure pins the stage the -// error came from when the provider cannot hand out a unit of work at all: -// the attempt never ran, so the ID fails with an "opening unit of work" -// verdict and NO hard error — a multi-ID batch keeps going and still exits -// non-zero through reportUpdateFailures. Returning a hard error here instead -// would abort the batch and drop the failures already collected. -func TestApplyUpdateProxiedOne_NewUOWFailureIsPerIDFailure(t *testing.T) { - provider := &fakeUOWProvider{ - issue: &types.Issue{ID: "bd-uow-1", Status: types.StatusOpen}, - newUOW: func(int64) error { return errors.New("dial dolt: connection refused") }, - } - withFakeProxiedUpdateEnv(t, provider) - - var got *types.Issue + stale := string(types.StatusInProgress) var fail *updateIDFailure - var err error stderr := captureStderrDuring(t, func() { - in := &updateInput{fields: map[string]any{"title": "no session"}} - got, fail, err = applyUpdateProxiedOne(context.Background(), "bd-uow-1", in) + _, fail, _ = applyUpdateProxiedOne(context.Background(), "bd-guard-1", &updateInput{ + fields: map[string]any{"priority": 0}, ifStatus: &stale, + }) }) - if err != nil { - t.Fatalf("applyUpdateProxiedOne returned hard error %v: a provider failure is a per-ID verdict, not a batch abort", err) + if fail == nil || !fail.GuardMismatch { + t.Fatalf("fail = %+v, want a guard-mismatch verdict", fail) } - if fail == nil || got != nil { - t.Fatalf("fail=%v issue=%v: an update that never opened a unit of work must be reported as a failure", fail, got) + if !strings.Contains(fail.Error, "precondition failed") { + t.Errorf("fail.Error = %q, want it named as a precondition failure", fail.Error) } - if !strings.Contains(fail.Error, "opening unit of work") { - t.Errorf("fail.Error = %q, want it attributed to opening the unit of work", fail.Error) - } - if fail.GuardMismatch { - t.Error("a provider failure must not masquerade as a guard mismatch (that would exit 13 and tell scripts not to retry)") - } - if !strings.Contains(stderr, "Error opening unit of work for bd-uow-1") { - t.Errorf("stderr = %q, want the provider failure named on stderr", stderr) - } - if n := provider.uows.Load(); n != 1 { - t.Errorf("unit-of-work attempts = %d, want 1 (a permanent provider failure must not be retried)", n) + if !strings.Contains(stderr, "status mismatch") { + t.Errorf("stderr = %q, want the machine-greppable sentinel text", stderr) } } -// TestApplyUpdateProxiedOne_CommitFailureIsPerIDFailure pins the other -// terminal stage: a commit that fails for a reason that is neither a -// serialization conflict nor an empty working set. The write did not land, so -// the ID fails with a "committing" verdict, once — no retry, no batch abort. -func TestApplyUpdateProxiedOne_CommitFailureIsPerIDFailure(t *testing.T) { - provider := &fakeUOWProvider{ - issue: &types.Issue{ID: "bd-commit-1", Status: types.StatusOpen}, - commit: func(int64) error { return errors.New("dolt: disk full") }, - } - withFakeProxiedUpdateEnv(t, provider) +// TestProxiedUpdateAbortsTheBatchOnCancellation is the plain-update half of the +// claim's own cancellation rule: SIGINT cancels bd's root context, every +// remaining id would fail the same way, so the loop aborts instead of recording +// one "context canceled" failure per id. +func TestProxiedUpdateAbortsTheBatchOnCancellation(t *testing.T) { + for _, cancellation := range []error{context.Canceled, context.DeadlineExceeded} { + t.Run(cancellation.Error(), func(t *testing.T) { + before := &types.Issue{ID: "bd-1", Status: types.StatusOpen} + claimRoleFixture(t, before, issueops.UpdateResult{}, fmt.Errorf("update bd-1: %w", cancellation)) - var got *types.Issue - var fail *updateIDFailure - var err error - stderr := captureStderrDuring(t, func() { - in := &updateInput{fields: map[string]any{"title": "never commits"}} - got, fail, err = applyUpdateProxiedOne(context.Background(), "bd-commit-1", in) - }) - if err != nil { - t.Fatalf("applyUpdateProxiedOne returned hard error %v: a commit failure is a per-ID verdict, not a batch abort", err) - } - if fail == nil || got != nil { - t.Fatalf("fail=%v issue=%v: a write whose commit failed must be reported as a failure", fail, got) - } - if !strings.Contains(fail.Error, "committing:") { - t.Errorf("fail.Error = %q, want it attributed to the commit", fail.Error) - } - if !strings.Contains(stderr, "Error committing bd-commit-1") { - t.Errorf("stderr = %q, want the commit failure named on stderr", stderr) - } - if n := provider.uows.Load(); n != 1 { - t.Errorf("unit-of-work attempts = %d, want 1 (a permanent commit failure must not be retried)", n) - } -} - -// TestApplyUpdateProxiedOne_CommitCanceledStaysPerIDFailure guards the seam -// between "the commit failed" and "the retry loop was cut short". Both surface -// as a context error, but they are different verdicts: a commit that fails -// while the process is tearing down on SIGINT is still one ID's commit -// failure, and must be recorded as one so reportUpdateFailures still runs for -// the whole batch — including any earlier guard mismatch, whose exit 13 tells -// scripts not to retry. Only cancellation BETWEEN attempts aborts the batch. -func TestApplyUpdateProxiedOne_CommitCanceledStaysPerIDFailure(t *testing.T) { - provider := &fakeUOWProvider{ - issue: &types.Issue{ID: "bd-commit-2", Status: types.StatusOpen}, - commit: func(int64) error { return context.Canceled }, - } - withFakeProxiedUpdateEnv(t, provider) - - var got *types.Issue - var fail *updateIDFailure - var err error - stderr := captureStderrDuring(t, func() { - in := &updateInput{fields: map[string]any{"title": "commit interrupted"}} - got, fail, err = applyUpdateProxiedOne(context.Background(), "bd-commit-2", in) - }) - if err != nil { - t.Fatalf("applyUpdateProxiedOne returned hard error %v: a commit that failed with a context error is still a per-ID verdict", err) - } - if fail == nil || got != nil { - t.Fatalf("fail=%v issue=%v: a write whose commit failed must be reported as a failure", fail, got) - } - if !strings.Contains(fail.Error, "committing:") { - t.Errorf("fail.Error = %q, want it attributed to the commit", fail.Error) - } - if !strings.Contains(stderr, "Error committing bd-commit-2") { - t.Errorf("stderr = %q, want the commit failure named on stderr", stderr) - } -} - -// TestApplyUpdateProxiedOne_CanceledBetweenAttemptsAbortsBatch is the other -// side of that seam: when cancellation lands between two conflict retries the -// retry loop reports the context's own error, no stage failed, and no verdict -// was reached for this ID. Abort the batch rather than inventing a per-ID -// failure for a write whose outcome nobody observed. -func TestApplyUpdateProxiedOne_CanceledBetweenAttemptsAbortsBatch(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - provider := &fakeUOWProvider{ - issue: &types.Issue{ID: "bd-cancel-1", Status: types.StatusOpen}, - commit: func(int64) error { - cancel() // SIGINT lands while this attempt is losing Dolt's merge - return serializationFailure() - }, - } - withFakeProxiedUpdateEnv(t, provider) - - in := &updateInput{fields: map[string]any{"title": "interrupted"}} - got, fail, err := applyUpdateProxiedOne(ctx, "bd-cancel-1", in) - if !errors.Is(err, context.Canceled) { - t.Fatalf("err = %v, want the context error so the batch aborts", err) - } - if fail != nil || got != nil { - t.Fatalf("fail=%v issue=%v: an unobserved outcome is not a per-ID verdict", fail, got) + got, fail, err := applyUpdateProxiedOne(context.Background(), "bd-1", + &updateInput{fields: map[string]any{"title": "interrupted"}}) + if !errors.Is(err, cancellation) { + t.Fatalf("err = %v, want %v returned so the batch aborts", err, cancellation) + } + if got != nil || fail != nil { + t.Errorf("issue = %+v, fail = %+v: cancellation is not a per-id verdict", got, fail) + } + }) } } diff --git a/internal/storage/dolt/issue_operations_contract_test.go b/internal/storage/dolt/issue_operations_contract_test.go index 4d2a36d51..29344b833 100644 --- a/internal/storage/dolt/issue_operations_contract_test.go +++ b/internal/storage/dolt/issue_operations_contract_test.go @@ -49,6 +49,12 @@ func TestIssueOperationsUpdateAssigneeTransferFence(t *testing.T) { conformance.RunIssueOperationsUpdateAssigneeTransferFence(t, ctx, fixture) } +func TestIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T) { + fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) + defer cleanup() + conformance.RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, fixture) +} + func TestIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { fixture, ctx, cleanup := newDoltIssueOperationsFixture(t) defer cleanup() diff --git a/internal/storage/embeddeddolt/issue_operations_contract_test.go b/internal/storage/embeddeddolt/issue_operations_contract_test.go index 5b8121433..08b65b261 100644 --- a/internal/storage/embeddeddolt/issue_operations_contract_test.go +++ b/internal/storage/embeddeddolt/issue_operations_contract_test.go @@ -59,6 +59,13 @@ func TestEmbeddedIssueOperationsUpdateAssigneeTransferFence(t *testing.T) { conformance.RunIssueOperationsUpdateAssigneeTransferFence(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "xferfence")) } +func TestEmbeddedIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T) { + skipUnlessEmbeddedDolt(t) + te := newTestEnv(t, "guardgate") + ctx := t.Context() + conformance.RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, newEmbeddedIssueOperationsFixture(t, ctx, te, "guardgate")) +} + func TestEmbeddedIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { skipUnlessEmbeddedDolt(t) te := newTestEnv(t, "closedfields") diff --git a/internal/storage/uow/issue_operations_contract_test.go b/internal/storage/uow/issue_operations_contract_test.go index b40b2bee8..91ef6836a 100644 --- a/internal/storage/uow/issue_operations_contract_test.go +++ b/internal/storage/uow/issue_operations_contract_test.go @@ -47,6 +47,11 @@ func TestIssueOperationsUpdateAssigneeTransferFence(t *testing.T) { conformance.RunIssueOperationsUpdateAssigneeTransferFence(t, ctx, newUOWIssueOperationsFixture(t, ctx)) } +func TestIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t *testing.T) { + ctx := context.Background() + conformance.RunIssueOperationsUpdateConditionalGuardsGateOrdinaryEdits(t, ctx, newUOWIssueOperationsFixture(t, ctx)) +} + func TestIssueOperationsUpdateClosedFieldsMatchClose(t *testing.T) { ctx := context.Background() conformance.RunIssueOperationsUpdateClosedFieldsMatchClose(t, ctx, newUOWIssueOperationsFixture(t, ctx))