beads/cmd/bd/unclaim_conditional_parity_test.go
Steve Yegge 4b1d9c875f
feat(unclaim,batch): port --if-assignee CAS and bd batch to proxied-server mode (bd-tb0yi) (#5364)
* feat(unclaim): port --if-assignee to proxied-server mode (bd-tb0yi)

`bd unclaim --if-assignee` was refused outright under
BEADS_DOLT_PROXIED_SERVER ("not supported in proxied-server mode"); it now
runs the compare-and-swap release, and runs the SAME one the embedded
backend runs.

No new SQL is written for this port, and that is what holds the bar. The
conditional release reaches the classic implementation exactly as the
unconditional one already does: domain.IssueUseCase.UnclaimIfAssignee ->
IssueSQLRepository.UnclaimIssueIfAssignee ->
issueops.UnclaimIssueIfAssigneeInTx, the twin of the Unclaim ->
UnclaimIssue -> UnclaimIssueInTx chain beside it. So a conditional release
applies the same transition (assignee cleared, status reopened, started_at
cleared, lease row dropped, row_lock rewritten), records the same
"unclaimed" event, routes a wisp's claim to the wisp tables the same way,
and refuses with the same storage.ErrAssigneeMismatch naming the current
holder. Routing it instead through Lifecycle.Update + ExpectedAssignee
would have written the row correctly but recorded a generic update event
in place of the release, and diverged from the unconditional path inside
the same command.

The CLI passes the expectation as a plain string because the flag has only
two states here: `--if-assignee ""` is rejected in unclaim.go before any
issue is touched (an unset shell variable must never silently downgrade a
CAS to an unconditional release), so empty unambiguously means
unconditional.

EXIT CONTRACT, unchanged and deliberately not "improved": a mismatched
holder writes nothing and exits 1 on BOTH paths. `bd unclaim` has never had
`bd update`'s ExitGuardMismatch (13) verdict — its help says so outright
("1 when any release failed (including an --if-assignee mismatch)") — and
minting one on the proxied path only would be the exact divergence this
lane exists to prevent. If unclaim should adopt 13, it adopts it in both
modes, as its own change.

TestProxiedServerUnclaimIfAssigneeParity is the cross-mode oracle: six
steps (stale guard, matching guard, repeat release, `--if-assignee ""`
rejection, --force/--if-assignee rejection) run against an embedded
workspace and a proxied one, and every observable — exit code, post-step
row state, whether the refusal names the holder — must match, with each
mode also checked against the contract itself so parity with a shared bug
still fails. It rides a new cross-mode harness
(cross_mode_parity_harness_test.go): one initialized workspace per backend,
the same argv against both, outcomes compared field by field and never by
id.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014zUQg5iF119KbGeYuhXQ5Y

* feat(batch): port bd batch to proxied-server mode (bd-tb0yi)

`bd batch` was refused outright under BEADS_DOLT_PROXIED_SERVER; it now
runs, with the property that is its entire reason to exist intact: N
operations, ONE transaction, ONE commit, and whole-batch rollback on the
first failing line.

The split between the modes is exactly the command's own seam. The
grammar, the tokenizer, the arity checks, the dry-run echo, the
empty-input no-op, the default commit message and every byte of output
stay shared in batch.go — a batch script means the same thing whichever
backend runs it, and a script the parser rejects is rejected before either
backend is reached. What is per-mode is the transaction primitive and the
verbs the ops dispatch against: uow.RunTxResult + the unit of work's use
cases here, `transact` + storage.Transaction there. runBatchOpUOW mirrors
runBatchOp op for op, including its error strings.

RunTxResult, not RunTxEphemeral: a batch writes versioned tables, and the
ephemeral form commits with no Dolt commit (its whole point for the leases
table), which would persist these writes while bypassing Dolt history. The
retry it brings redoes the WHOLE batch in a fresh unit of work on a
serialization failure — re-executed against the winner's committed rows,
never re-committed on a session the server already rolled back — and the
per-attempt result slice means a retried batch reports the attempt that
actually committed.

Plane routing is explicit because it has to be: the classic transaction
methods route an id to the issues or wisps tables themselves, while the
domain exposes the planes as separate verbs. close/update resolve through
workapi.GetIssueOrWisp inside the transaction and call the matching verb;
dep add/remove use the source-routed AddDependencies /
RemoveDependencyBySource, which land each edge in the plane its own source
lives in. `close` is deliberately the UNCHECKED close, matching the classic
batch: `close <id>` in a batch applies no close policy, while an `update`
that crosses into done does — an asymmetry the command's help documents.

TestProxiedServerBatchParity is the cross-mode oracle, on the F0-style
harness: the same script runs against an embedded workspace and a proxied
one, and exit codes, the summary line, the per-line report, and the rows
left behind must match — including the two transactional cases that are
the point (a failing last line undoing the successful lines before it, and
a grammar error writing nothing at all).

TWO KNOWN DIVERGENCES are named at their sites and left for their own
change, because neither changes the rows a batch lands and both are
classic-batch inconsistencies with the CLI verbs rather than artifacts of
the port: an out-of-range `priority=5` is written by the classic batch and
refused by the proxied one (the domain update funnel validates the range,
issueops' transaction path does not; `bd update --priority 5` is refused on
both), and a batched `dep add`/`dep remove` records a dependency history
event here and not there (every domain edge verb emits, the classic batch's
bare transaction method does not — and `bd dep add` at the CLI emits on
both backends, which is what makes the classic batch the outlier).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014zUQg5iF119KbGeYuhXQ5Y

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 12:11:56 -07:00

190 lines
8.2 KiB
Go

//go:build cgo
package main
import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// unclaimGuardOutcome is everything a caller of `bd unclaim --if-assignee` can
// observe, recorded once per backend. Comparing two of these IS the parity
// assertion: exit codes, the row state each step left behind, and whether the
// refusal named the actual holder (the machine-greppable half of the contract).
type unclaimGuardOutcome struct {
staleCode int
staleNamesHolder bool
staleAssignee string
staleStatus types.Status
matchCode int
matchAssignee string
matchStatus types.Status
repeatCode int
emptyGuardCode int
emptyGuardRejected bool
emptyGuardAssignee string
emptyGuardStatus types.Status
forceComboCode int
forceComboRejected bool
forceComboAssignee string
forceComboStatus types.Status
}
// TestProxiedServerUnclaimIfAssigneeParity is the cross-mode oracle for the
// conditional release ported to proxied-server mode: the same six steps run
// against a classic embedded workspace and a proxied one, and every observable
// must match.
//
// The compare-and-swap is the point. A supervisor returning a specific worker's
// bead must never clobber a claim that has since moved on, so the refusal has
// to leave the row EXACTLY as it found it — asserted here on both backends, in
// the same test, rather than inferred from two suites that could drift apart.
//
// EXIT CODE, deliberately pinned: a stale guard exits 1 on both paths. `bd
// unclaim` has never had `bd update`'s ExitGuardMismatch (13) verdict — its
// help says so outright ("1 when any release failed (including an
// --if-assignee mismatch)") — and this port does not invent one for the proxied
// path, because a proxied exit code that differs from the embedded one for the
// same refusal is precisely the divergence this lane exists to prevent. If
// unclaim ever adopts 13 it must adopt it in BOTH modes, and this assertion
// changes once, deliberately.
func TestProxiedServerUnclaimIfAssigneeParity(t *testing.T) {
requireSharedProxiedServer(t)
t.Parallel()
bd := buildEmbeddedBD(t)
envs := newCrossModeEnvs(t, bd, "ucc", "ucp")
outcomes := make(map[string]unclaimGuardOutcome, len(envs))
for _, env := range envs {
var got unclaimGuardOutcome
// A live claim held by alice.
held := env.create(t, "Conditional release")
env.mustRun(t, "update", held, "--assignee", "alice", "--status", "in_progress")
// 1. Stale expectation: refuses, names the holder, writes nothing.
stdout, stderr, code := env.run(t, "unclaim", held, "--if-assignee", "bob")
got.staleCode = code
got.staleNamesHolder = strings.Contains(stdout+stderr, "alice")
row := env.show(t, held)
got.staleAssignee, got.staleStatus = row.Assignee, row.Status
// 2. Matching expectation: releases.
_, _, code = env.run(t, "unclaim", held, "--if-assignee", "alice")
got.matchCode = code
row = env.show(t, held)
got.matchAssignee, got.matchStatus = row.Assignee, row.Status
// 3. Releasing an already-released issue is a distinct failure, not a
// silent success — the exactly-once property a release-if-current
// supervisor depends on.
_, _, got.repeatCode = env.run(t, "unclaim", held, "--if-assignee", "alice")
// 4. An explicitly empty --if-assignee (an unset variable that expanded
// into the flag) must be REJECTED, not silently downgraded to an
// unconditional release. Run as the holder, so the pre-fix behavior
// would actually have released the claim.
second := env.create(t, "Empty expectation")
env.mustRun(t, "update", second, "--assignee", "alice", "--status", "in_progress")
stdout, stderr, code = env.run(t, "unclaim", second, "--if-assignee", "", "--actor", "alice")
got.emptyGuardCode = code
got.emptyGuardRejected = strings.Contains(stdout+stderr, "if-assignee requires a non-empty assignee")
row = env.show(t, second)
got.emptyGuardAssignee, got.emptyGuardStatus = row.Assignee, row.Status
// 5. --force and --if-assignee encode contradictory intent and are
// mutually exclusive; the combination writes nothing.
stdout, stderr, code = env.run(t, "unclaim", second, "--force", "--if-assignee", "alice")
got.forceComboCode = code
combined := stdout + stderr
got.forceComboRejected = strings.Contains(combined, "force") && strings.Contains(combined, "if-assignee")
row = env.show(t, second)
got.forceComboAssignee, got.forceComboStatus = row.Assignee, row.Status
outcomes[env.mode] = got
// Per-mode absolute expectations. Parity with a shared bug is still a
// bug, so each mode is also checked against the contract itself.
if got.staleCode == 0 {
t.Errorf("[%s] stale --if-assignee must fail, got exit 0", env.mode)
}
if got.staleCode != 1 {
t.Errorf("[%s] stale --if-assignee exit = %d, want 1 (bd unclaim does not use ExitGuardMismatch=%d)",
env.mode, got.staleCode, ExitGuardMismatch)
}
if !got.staleNamesHolder {
t.Errorf("[%s] stale --if-assignee error must name the current holder alice", env.mode)
}
if got.staleAssignee != "alice" || got.staleStatus != types.StatusInProgress {
t.Errorf("[%s] stale --if-assignee touched the row: assignee=%q status=%q, want alice/in_progress",
env.mode, got.staleAssignee, got.staleStatus)
}
if got.matchCode != 0 {
t.Errorf("[%s] matching --if-assignee exit = %d, want 0", env.mode, got.matchCode)
}
if got.matchAssignee != "" || got.matchStatus != types.StatusOpen {
t.Errorf("[%s] after matching --if-assignee: assignee=%q status=%q, want empty/open",
env.mode, got.matchAssignee, got.matchStatus)
}
if got.repeatCode == 0 {
t.Errorf("[%s] re-releasing an already-released issue must fail, got exit 0", env.mode)
}
if got.emptyGuardCode == 0 || !got.emptyGuardRejected {
t.Errorf("[%s] --if-assignee '' must be rejected (exit=%d rejected=%v)",
env.mode, got.emptyGuardCode, got.emptyGuardRejected)
}
if got.emptyGuardAssignee != "alice" || got.emptyGuardStatus != types.StatusInProgress {
t.Errorf("[%s] --if-assignee '' released the claim: assignee=%q status=%q",
env.mode, got.emptyGuardAssignee, got.emptyGuardStatus)
}
if got.forceComboCode == 0 || !got.forceComboRejected {
t.Errorf("[%s] --force with --if-assignee must be rejected (exit=%d rejected=%v)",
env.mode, got.forceComboCode, got.forceComboRejected)
}
if got.forceComboAssignee != "alice" || got.forceComboStatus != types.StatusInProgress {
t.Errorf("[%s] --force --if-assignee released the claim: assignee=%q status=%q",
env.mode, got.forceComboAssignee, got.forceComboStatus)
}
}
assertUnclaimGuardParity(t, outcomes["classic"], outcomes["proxied"])
}
// assertUnclaimGuardParity reports every field on which the two backends
// disagree, rather than one opaque struct diff.
func assertUnclaimGuardParity(t *testing.T, classic, proxied unclaimGuardOutcome) {
t.Helper()
type field struct {
name string
classic, proxied any
}
for _, f := range []field{
{"stale exit code", classic.staleCode, proxied.staleCode},
{"stale names holder", classic.staleNamesHolder, proxied.staleNamesHolder},
{"stale assignee", classic.staleAssignee, proxied.staleAssignee},
{"stale status", classic.staleStatus, proxied.staleStatus},
{"match exit code", classic.matchCode, proxied.matchCode},
{"match assignee", classic.matchAssignee, proxied.matchAssignee},
{"match status", classic.matchStatus, proxied.matchStatus},
{"repeat exit code", classic.repeatCode, proxied.repeatCode},
{"empty-guard exit code", classic.emptyGuardCode, proxied.emptyGuardCode},
{"empty-guard rejected", classic.emptyGuardRejected, proxied.emptyGuardRejected},
{"empty-guard assignee", classic.emptyGuardAssignee, proxied.emptyGuardAssignee},
{"empty-guard status", classic.emptyGuardStatus, proxied.emptyGuardStatus},
{"force-combo exit code", classic.forceComboCode, proxied.forceComboCode},
{"force-combo rejected", classic.forceComboRejected, proxied.forceComboRejected},
{"force-combo assignee", classic.forceComboAssignee, proxied.forceComboAssignee},
{"force-combo status", classic.forceComboStatus, proxied.forceComboStatus},
} {
if f.classic != f.proxied {
t.Errorf("cross-mode divergence on %s: classic=%v proxied=%v", f.name, f.classic, f.proxied)
}
}
}