Four-leg no-op conformance case for #5898: duplicate dep add and absent dep remove mint no version on any leg (#6650)

* test(feat): red — Phase 0: conformance suite (history, expectedRevision R16.1, epochs R20) - gastownhall/beads#6133 (refs be-hs42e.1)

* feat: green — Phase 0 conformance suite (history, R16.1, R20 epochs) (refs be-hs42e.1)

Implements the 32 in-process RunXxx contract cases from be-hs42e.1 §4
(gastownhall/beads#6133): expectedRevision CAS + refusal (R16/R17, 10 cases),
the cross-record-invariant boundary (R16.1, 7 cases), and retention/epoch
semantics (R20, 15 cases). All hooks nil in every backend's fixture kit per
architecture §12 — ships disabled by default, zero behavior change.

Also fixes a role-tier coverage-gate false positive: role_bundle_test.go's
TestRoleContractCasesCoverEveryContractCase matched any Run*(t, ctx,
XxxFixture) function in the package with no scoping, incorrectly sweeping in
these new history-semantics functions. Scoped via roleTierFixtureNames()
(reflection over RoleContractBundle's field types) so only functions whose
Fixture type is an actual bundle field count as role-tier cases.

* feat: green — Review: Phase 0: conformance suite (history, expectedRevision R16.1, epochs R20) - gastownhall/beads#6133 (refs be-zv3ob)

Wire the 32 new R16/R16.1/R20 role-contract entrypoints (expected_revision,
cross_record_invariant, retention, epoch) into all three storage legs so
TestEveryLegWiresEveryRoleContract passes on dolt, embeddeddolt, and uow —
fixing the round-1 review's blocking finding (gastownhall/beads#6133).

Each new per-leg _test.go file follows the existing wiring convention (one
TestXxxContract per role, one t.Run per case, calling conformance.RunXxx)
with the same all-nil Phase 0 fixtures used everywhere else this phase, so
every case skips by name until Phase 3 gives it a non-nil hook.

Also corrects a stale comment in versioned_history_wiring_test.go that
argued against per-leg wiring files exactly like the ones this commit adds.

No other behavior change: wiring only, no new dependency, no scope beyond
the reviewer's named blocking issue.

* chore: release gate PASS for Phase 0 conformance suite (be-e0w8y)

Review: be-g8mp3 (PASS). Deploy bead: be-e0w8y.
Refs be-e0w8y, be-g8mp3, be-hs42e.1, be-zv3ob.

* feat: green — Review round 2: Phase 0 conformance suite (bounds assertion, RetentionAnswer fields) - gastownhall/beads#6147 (refs be-ekp0w)

Fix bee-ghosttrack's round-2 MERGE-AFTER-FIXES review on PR #6147
(comment 5504085482):

- RunAHoldPreventsRemovalAndReportsInRetainedBounds now asserts BOTH
  refusal (ErrRetentionHeld) AND that the held Address shows up
  positively in the reported RetainedWindow bounds, not merely inferred
  from the absence of a Gone restriction (R20-h).

- RetentionAnswer gains Attribution *ChangeAttribution and Epoch *int.
  RunForcingAHeldRemovalRecordsWhoWhenWhy now asserts real attribution
  content (R20-h2) instead of accepting it only as a parameter.
  RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed now asserts
  Restriction=GoneReorganization AND the current epoch is named (R20-n).

Reviewer-sanctioned, taken in the same pass:

- RetentionFixture gains a Mint hook (analogous to
  EpochFixture.MintUnderEpoch); every retention case that needs a real,
  resolvable Address now mints one instead of relying on the retired
  "fabricated address defaults to Live" convention. The one exception,
  RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone, keeps the old
  fabricated-address helper on purpose: Unknown specifically means an
  Address no store ever minted.

- RunStoreInvariantTransactionScopesExactlyTheSpanningRecords adds a
  post-refusal read-back via CountHistoryForSubject, pinning that a
  refused cross-record batch is atomic (leaves no trace on either
  record), as an inline nil-check rather than a t.Skip.

- Refusal's doc comment now states the fixture kit is the translation
  boundary between whatever shape a real backend ships and the one
  shape this suite asserts against — not a mandate banning a native
  typed-error refusal shape at the backend level.

- Package doc comment in expected_revision_contract.go records four
  reviewer-named deferrals verbatim (unretained/disclosure-gating as a
  future authorization axis rather than a sixth Restriction state;
  invariant-declaration discoverability; lease TTL self-expiry; R20-j
  durability-across-restart) and notes the "_attribution" patch-key
  convention as canonical for Phase 3 hook docs.

§4a's choice-vs-transcription table (this file's package doc comment)
already marks choices 2 and 3 DIED as of this round; no separate
callout-row table exists elsewhere in the repo.

No other behavior change: all touched Run* entrypoints still skip by
name under Phase 0's all-nil fixtures on every leg (confirmed via
TestVersionedHistoryPhase0RunsInFullSkipMode and
TestEveryLegWiresEveryRoleContract), no new dependency, no scope beyond
the reviewer's named findings.

* feat: green — Review round 3: Phase 0 conformance suite (nil-hook logging, retained-bounds assertion, stale comment) - gastownhall/beads#6147 (refs be-gw08e)

bee-ghosttrack round-2 review (2026-09-03T01:03Z, MERGE-AFTER-FIXES):

- cross_record_invariant_contract.go:158,178 — log which half of the
  atomicity read-back goes unverified when CountHistoryForSubject is nil,
  matching the file's existing skip-by-name convention (:327-328).
- retention_epoch_contract.go:511 — RunAHoldPreventsRemovalAndReportsInRetainedBounds
  asserted both RetainedWindow bounds equal the held Address, on the
  assumption nothing else was ever minted in this store. That assumption
  doesn't hold: IssuePrefix is a static per-package string
  (internal/storage/uow/retention_epoch_contract_test.go:17), not
  randomized per run, so a persistent backend's second run would fail
  this for the wrong reason. Weakened to at-least-one-bound.
- retention_epoch_contract.go:60-61 — fixed a stale "those two cases
  still use" comment; retentionAddress's own doc comment already names
  RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone as sole caller.

PR body's choice-vs-transcription callout table updated separately
(ten -> eight rows; the R20-h2 and R20-baseline rows described choices
this same review round already marked DIED in source).

* test(feat): red — Implement Phase 2 dual-write history behind flag - gastownhall/beads#6135 (refs be-0uifx)

* feat: green — Implement Phase 2 dual-write history behind flag - gastownhall/beads#6135 (refs be-0uifx)

* test(issueops): red — Phase 2 dual-write: re-seat builder/be-0uifx onto the merged base + add attribution_status (§16.4) — preempt the known review bounce (refs be-v33pa)

* fix(issueops): green — Phase 2 dual-write: re-seat builder/be-0uifx onto the merged base + add attribution_status (§16.4) — preempt the known review bounce (refs be-v33pa)

Migration 0068 step 6 only (VARCHAR(20) NOT NULL on issue_versions);
RecordVersionInTx derives it from the actor string it already receives
via attributionStatusForActor (non-empty -> supplied, empty ->
undetermined; not_supplied/imported are schema-valid but unreached by
any of the 7 current call sites). CLI-bundle direct-DDL override added
per dolthub/dolt#11345. Two pre-existing raw-SQL issue_versions
fixtures updated for the new NOT NULL column.

* chore(release-gates): add be-764ey deploy gate record (Phase 2 dual-write)

Factory release gate for be-764ey / gastownhall/beads#6135, PR #6358
(supersedes draft #6354). 7/7 PASS, no waivers — independent full-suite
run (97 packages ok, 0 FAIL, 0 SKIP), gofmt/vet clean, two pre-existing
non-blocking lint/policy findings attributed to be-2l6n8/be-xzg59.

* chore(ci): no-op commit to retrigger checks — code identical to 4179638; the macOS lane failed on runner disk I/O errors (see PR #6358 discussion)

* fix(history): attribution_status is claimed|unknown (BDP-aligned); document ordinals as local and the flag as single-writer-only

Per donnabox's review on #6358 items 1-3: align issue_versions.attribution_status to bdp#18's carried-attribution vocabulary (claimed | unknown), drop the unreachable not_supplied and the provenance-not-assertion imported; state that current_revision/revision are local ordinals and version_id is the only durable address; document VersionedHistoryConfigurer as single-writer-only until 0068 steps 1-3 land.

* fix(history): durable_state is LONGBLOB holding the RFC 8785 canonical form

Per donnabox's review on #6358 item 4: Dolt's JSON type renormalizes numbers, so a JSON column cannot keep the verbatim-bytes promise (R5.1) or back a content-derived token. Migration 0068 step 7 retypes issue_versions.durable_state to LONGBLOB (guarded PREPARE, CLI-bundle override extended), RecordVersionInTx stores the JCS canonical bytes of the marshalled issue so sha256(stored) is a stable token, and the all-migrations shape test pins longblob.

* build(nix): bump vendorHash for github.com/gowebpki/jcs v1.0.1

The JCS canonicalizer added on this branch changes go.sum, so the
fixed-output go-modules derivation hash moves.

Recomputed on the rebase onto main at 71c4cd08b. The merged module graph
is main's v1.3.0 dependency and toolchain bumps (#6047) plus this
branch's gowebpki/jcs v1.0.1, so neither side's pre-rebase hash applies:
main's was computed without jcs, and this branch's was computed against
the older dependency set. The value here was extracted from nix's own
hash-mismatch report and then verified by a clean nix build .#default.

* style(history): marshaled, not marshalled (misspell lint)

* fix(history): mint a version on every accepted issue-plane mutation, last in the transaction, on every leg

Per the write-path inventory on #6135 (donnabox's item 5 on #6358): the seam was reached from 3 of 57 journaled entry points. Close, reopen, claim, unclaim/release, lease reclaim, defer wake, label add/remove, promote and persistence moves now mint; update's label/parent patches and batch-create edges are applied before the mint so durable_state carries them; dependency add/remove mint at the lowest helper on all legs (uow and legacy verbs included) with the editor's duplicate call removed. version_completeness_test.go pins the set.

* docs(history): issue-plane write-path inventory with Phase 2 dispositions

The table donnabox asked for on #6358 (item 5), derived from the code rather than the design's count, with the dispositions that changed after a14f48b17 and the caveats that remain.

* docs(history): write-path doc: the seam has 27 call sites after a14f48b17, not "exactly six"

The sentence "is reached from exactly six call sites" described the tree at
321a79278 in the present tense, in a doc whose header already says those
rows changed after the completeness fix. It now scopes the six to that
commit and points at a new section listing the 27 sites (18 in issueops,
9 in domain/db) verified with grep over non-test files at d484b809d, with
the enclosing function for each. The "29 sites" figure quoted in the PR
thread was an over-count; 27 is the measured number.

The unchanged-re-import caveat now records that the journal seam sits in
the same position: RecordEventInTx(EventCreate) at create.go:207 runs on
every accepted upsert (only the events-table write behind the isNew gate
at create.go:171 is skipped), so a field-level no-op gate belongs in front
of both seams, not the version seam alone.

Doc only; no Go change.

* fix(history): seed store_epoch once per store, state the fail-closed canonicalization policy, and say single writer means one at a time

From bee-ghosttrack's round-1 review of #6358.

- store_epoch (nit): RecordVersionInTx ran INSERT IGNORE INTO store_epoch
  on every mint, putting one shared row (id = 1) into every write
  transaction's footprint. It now reads first and seeds only when the row
  is absent, so the seed happens once per store. Same result, one fewer
  write per versioned mutation.
- canonicalDurableState (MINOR-4): the comment now states the two
  properties a hand-rolled canonicalizer would get wrong -- jcs.Transform
  normalizes away encoding/json's HTML escaping, so the token is a function
  of content, not of Go's escaping policy; and a snapshot that cannot be
  canonicalized deliberately fails the mutation. Duplicate keys in an
  issue's metadata (a json.RawMessage, reachable via bd sql or a hand-
  written JSONL import) make the seam return an error with the flag on.
  Fail-closed is the policy for now; normalizing first, or finding such rows
  with bd doctor, is gastownhall/beads#6379 item 3.
- Single writer (MINOR-5): the constraint in version_history.go,
  storage.go and the 0068 header now says one writer AT A TIME per store,
  not merely one clone -- MAX(revision)+1 is not a safe allocator for two
  concurrent transactions in one store either, and no contract case runs
  concurrent writers. gastownhall/beads#6379 item 4.
- RecordVersionInTx doc (nit): IsWisp is Ephemeral || NoHistory, so a
  promoted no-history bead is also never versioned; stated as what
  no-history means rather than as an FR-8 wisp rule.

No behaviour change beyond the one fewer INSERT. Gates: gofmt, go build,
go vet, golangci-lint v2.10.1 (0 issues), issueops, the five embedded-Dolt
version suites, scripts/check-migration-hygiene.sh.

* docs(history): restate the write-path doc at this head; keep the 321a79278 inventory under a dated heading

bee-ghosttrack's MINOR-2 on #6358: the table and notes were written in
the present tense against 321a79278, so as merged the doc said close was
OUT OF CONTRACT and that no completeness test existed, beside the code
that ships both.

The doc now has two parts. "Dispositions at this head" carries a table of
every row whose disposition changed after a14f48b17 (rows 13-23, 25, 27,
34) with the mechanism and line for each, the counts at this head (21
VERSIONED, 13 OUT OF CONTRACT, 5 no-op gates), the deferred items, the
seam call sites, and notes that are true now. "As found at 321a79278" keeps
the original table and notes verbatim as the record of what the review
found, with a sentence saying which rows it no longer describes.

Also: row 13 now says wisp or promoted no-history bead (nit); the flag-off
sentence says behaviourally a no-op at the seam but not literally zero
added work (nit); the flag-on prerequisites point at gastownhall/beads#6379.

* test(history): a call passing mintVersion=false is not a minting edge (reviewer MINOR-1)

The versioned-history guard's fixpoint treated "textually calls
RecordVersionInTx, directly or transitively" as the mint predicate, so a
call to a helper with mintVersion=false still counted as a minting edge.
Reviewer Probe 2 on #6358 showed the consequence: deleting ExecuteUpdate's
own final `if changedAny { RecordVersionInTx(...) }` block left the whole
issueops package green, because the fixpoint credited ExecuteUpdate with
the mints of the very constituents it had told not to mint.

journalscan now records each function's parameter names and each call's
reduced argument list (bare identifier or literal per argument), and
exposes CallsOnlyWithLiteralFalse(fns, f, callee, gate): true only when
every call f makes to callee passes the predeclared false for callee's
parameter named gate. A call passing true, a variable, the caller's own
parameter, or too few arguments keeps its edge, as does a callee without
the parameter. Existing callers (IdentCalls, SelCalls, Fixpoint) are
unchanged; the resolve closure is merely lifted to a package function.

versionMintEdges drops the switched-off edges, and a new
TestCompositeMutationsCarryTheirOwnMint pins that ExecuteUpdate,
applyLabelPatch and applyParentPatch each call the seam themselves and
that none of their remaining edges reaches it.

Verified: full issueops package green on the unmodified tree. Probe 2
(delete ExecuteUpdate's final mint block) now fails
TestCompositeMutationsCarryTheirOwnMint, TestEveryVersionedEntryPointMints
and TestEveryBeadMutatorMintsOrIsExempt, all naming ExecuteUpdate; the
same probe against the previous guard stays green. Probe 1 (delete the
close mint) still fails TestEveryVersionedEntryPointMints and
TestEveryBeadMutatorMintsOrIsExempt naming CloseIssueInTx,
CloseIssueWithoutEventInTx, CloseIssueCheckedInTx and ExecuteClose. The
exemption tables are untouched.

* test(history): pin the uow leg's 1+N+M create divergence as a red-when-fixed test (reviewer MINOR-3)

TestDualWriteContract's Mutate closure creates an issue with no labels and
no dependencies, so its "exactly one version row per accepted mutation"
case cannot see what a fuller create does on the uow leg:
domain.IssueUseCase.CreateIssue inserts the row and then persists each
label and each edge through its own repository (domain/db label.go,
dependency.go), and every one of those writes reaches
issueops.RecordVersionInTx on its own. The direct legs mint exactly one
row for the same shape (CreateIssuesInTxWithContext mints once per issue
after the creation-time edges land).

TestUOWCreateWithLabelAndEdgeMintsPerRepositoryWrite_KnownDivergence
creates an issue through the uow leg with exactly one label and one
blocks edge and asserts the MEASURED count of issue_versions rows:
3 (1 issue + 1 label + 1 edge), matching the 1+N+M prediction. It also
checks the label and edge actually landed, and that the bare-shape target
seeded through the same leg holds exactly 1 row, so the two extra rows
are attributable to the label and the edge. A t.Log line and the doc
comment name the follow-up as gastownhall/beads#<FOLLOWUP-ISSUE> (to be
substituted before push) and state that the test is expected to FLIP to
1 when it lands.

The provider boot + flag enablement is lifted out of
newUOWDualWriteFixture into newUOWVersionedHistoryProvider so the new
test shares it; the existing contract cases and the fixture closures are
unchanged. Runs on the same backend and skips as its neighbours (a real
dolt sql-server, gated by testutil.RequireDoltBinary; no extra env
needed).

Verified: go test -count=1 -run 'TestDualWrite|TestUOWCreateWithLabelAndEdge' ./internal/storage/uow/ passes.

* test(history): pin canonicalDurableState to the RFC 8785 vectors, key order, HTML escapes and duplicate keys

TestCanonicalDurableStateIsJCS covered only number forms. It is now
table-driven over:

- the ten RFC 8785 test vectors that ship with github.com/gowebpki/jcs
  v1.0.1 (Apache-2.0), copied verbatim to
  internal/storage/issueops/testdata/jcs/{input,expected} with a README.md
  recording their provenance (upstream's "output" directory is named
  "expected" here because the repository's .gitignore drops any output/
  tree); the count is pinned so an emptied directory cannot pass as a
  vacuous table;
- a unicode/astral key-ordering case: {"b":1,"a":2,"é":3,"A":4,"😀":5}
  canonicalizes to {"A":4,"a":2,"b":1,"é":3,"😀":5} (UTF-16 code-unit
  order, so the astral key sorts after "é");
- an HTML-escape case: a string value <a>&"'</a> comes out as
  "<a>&\"'</a>" with no <-style escaping, plus a companion subtest
  proving plain json.Marshal DOES emit </& so the normalization
  is demonstrably jcs.Transform's work;
- a fixed-point check, canonical(canonical(x)) == canonical(x), for every
  table case;
- a duplicate-key input {"k":1,"k":2}, which must fail with an error
  containing "Duplicate key" rather than store whichever value wins.

The existing number-form assertions are kept as they were.

Verified: go test -count=1 -run 'CanonicalDurableState' ./internal/storage/issueops/ passes (16 subtests).

* ci: no-op retrigger after a known flake in internal/metrics

Run 34173415291 on 0645e7827 failed only TestStartDetachedReapsExitedChild
("child pid became a zombie; startDetached did not reap"), the residual
child-process reap race tracked as beads be-w5rdt; #5933's fix is already
on this branch. Nothing in this PR touches internal/metrics. Empty commit
to re-run CI, since the PR author cannot re-run jobs in this repository.

* ci: no-op retrigger after a package-level timeout in the differential regression lane

Run 34174581104 on d81157b7d: 124 of 125 checks green; "Differential
Regression (v0.49.6 baseline)" panicked with "test timed out after 20m0s"
in the middle of TestRapidLabelAddRemoveStability, after the earlier
scenarios in the same package ran at several times their d484b809d
durations (TestListAllOverridesLimitWithLabel 87.9s; the whole lane took
11m0s on d484b809d). The regression suite never enables versioned history,
so nothing in this PR is on its path. Empty commit to re-run CI.

* docs(history): drop the stale head sha from the current-part heading; cite the seam by function, not line (bee round 2)

* test(history): make the mintVersion=false guard's claims exact (shadowed false, ambiguous names, method constituents)

Three reviewer nits on the versioned-history completeness guard
(gastownhall/beads#6358), each closing a gap between what the guard
claimed and what it checked. Detection is only ever strengthened.

Shadowed false. CallsOnlyWithLiteralFalse matched the NAME false, and
Go lets a local, a parameter or a package-level declaration take that
name, so a shadow read as a switch-off. journalscan now reads a false
or true as the predeclared identifier only when the parser's per-file
resolution (ParsePackage's mode 0, now pinned) attaches no declaration
to it AND no file of the package declares the name at package level
(per-file resolution cannot see the cross-file case; ParsePackage folds
each file's package scope in). Any shadow reduces to "", an unknown
expression, so the edge stays live. TestFalseIsNotShadowedInIssueops
independently walks every declaration position in issueops (test files
included) and fails on any true/false, so the reading is exact there,
not merely conservative.

Ambiguous names. Resolution is name-based, so a literal-false call to a
name shared by a gated function and an ungated one dropped the
fixpoint's edge to both. Resolve's semantics are unchanged;
TestLiteralFalseCalleesResolveUnambiguously requires every callee of a
mintVersion=false call to resolve to one function or to only functions
that declare the gate, naming the ambiguous name otherwise.

Method constituents. TestCompositeMutationsCarryTheirOwnMint looked up
mints[callee] by bare name while the fixpoint keys methods Recv.Name,
so that half only bit for free functions. The check now resolves each
live edge through the scanner's own Resolve (exported for this, with a
stable order); TestCompositeCheckSeesMethodConstituents proves it on a
synthetic package whose constituent is a method.

Reviewer probes re-run: deleting the close mint, deleting
ExecuteUpdate's final mint block, and flipping its
moveIssuePersistenceInTx call to mintVersion=true each still fail the
guard.

* chore: remove leaked internal release-gate docs from PR branch

  release-gates/be-764ey-gate.md
  release-gates/be-e0w8y-phase0-conformance-suite-gate.md

Tracked our internal gc-management/beads-rig release-gate checklist and
should never have been committed to this upstream branch -- it's process
residue from our deploy tooling, not part of the change itself.

Per maintainer bee-ghosttrack's request during review of PR #6571. The
root cause (our deploy tooling auto-committing this file) is already fixed
as of gm-qatxl1; this branch predates that fix, so this commit is cleanup
only -- no other content on this branch is touched.

Ref: be-lk7o3

* test(feat): red — same-type dep re-add double-journals (refs be-58eip)

Adds bd_events_journal assertions to the existing SameTypeReAddIsIdempotent
and RemoveIsIdempotent conformance cases, across all three DependencyEditor
backends (dolt, embeddeddolt, uow). The journal has no deduplication of its
own, so a same-type re-add that gates on TYPE alone (never the stored
metadata VALUE) journals a dep_add that never happened — RED on all three
legs today. The remove side already holds (confirmatory pin).

Refs gastownhall/beads#5898, #6358.

* fix(feat): green — same-type dep re-add is a true no-op when metadata is unchanged (refs be-58eip)

addDependencyInTx (embedded/proxied-server legs) and the uow leg's
DependencySQLRepository.Insert both gated the same-type re-add branch on
TYPE equality alone, so a duplicate add with identical metadata still
rewrote the metadata column and journaled a dep_add via
RecordDepEventInTx even though nothing changed. Both now also compare the
existing stored metadata against the requested value: identical metadata
returns immediately with no write and no journal entry, and only a genuine
metadata change still updates the row and journals the replacement edge.

Makes RunDependencyEditorSameTypeReAddIsIdempotent green on all three
DependencyEditor backends (dolt, embeddeddolt, uow); full contract suites
and TestEventsJournal_UOWDependencySnapshotsFollowBlockedState (a real
metadata change must still journal) remain green.

Refs gastownhall/beads#5898, #6358.

* test(feat): red — same-type dep re-add with changed metadata leaves it unminted (refs be-ejoty, #5898 leg 2)

Round-1 review on be-58eip found leg 2 of #5898 comment 5561794917
unimplemented, not merely untested: a same-type dependency re-add whose
metadata actually changed is a real durable-state mutation of the source
issue, so it must mint exactly one version — but neither backend's
same-type branch called the mint seam, and no test in the suite
constructed the changed-metadata case (RunDependencyEditorSameTypeReAddIsIdempotent
reuses one identical request for both calls, so existingMetadata==metadata
on every run).

Adds RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion,
driven through fixture.AddDependency (the role's own DependencyEdge
carries no metadata field). Reads issue_versions directly via a new
SetVersionedHistoryEnabled fixture hook rather than CountHistory/dolt_log:
AddDependency writes through the backend's raw store path, and on at
least one backend only the role's own transaction wrapper issues the
version-control commit CountHistory observes.

Currently red: the production same-type branches update the row and
journal the replacement edge, then return without minting.

* fix(feat): green — same-type dep re-add mints one version when metadata actually changed (refs be-ejoty, #5898 leg 2)

Completes #5898 comment 5561794917's leg 2. A same-type re-add that
changes metadata is a real durable-state mutation of the source issue,
so it mints on the same terms as a genuinely new edge — only a
change-free re-add (identical type and metadata) mints nothing.

addDependencyInTx's same-type branch (dolt/embeddeddolt shared path)
now calls the existing mintDependencyVersion seam after journaling the
replacement edge. dependencySQLRepositoryImpl.Insert (uow/domain
backend) now calls issueops.RecordVersionInTx at the equivalent point.

Without this, any caller that sets non-default dep.Metadata (e.g.
types.NewWaitsForDependency's gate JSON, used by graph-plan apply and
batch_apply.go) re-adding the same (issue,target,type) pair with a
different gate value would silently rewrite it with zero version-history
trail.

* fix(deps): canonicalize both sides of the change-free re-add gate

Maintainer review fixup for #6650.

The change-free re-add gate compared the caller's raw metadata string
against bytes read back out of a native JSON column. Dolt renormalizes
what it stores -- spacing, key order, number form -- so a semantically
identical re-add was misclassified as "changed": it journaled a false
dep_add replacement entry (the #5898 R3 defect this PR exists to
remove) and, new versus base, minted a version row on a path base never
minted on. The no-op held only for metadata already in Dolt-normal
form, which is not the form hand-authored or struct-marshaled metadata
arrives in.

Both gate sites now compare through issueops.DependencyMetadataEqual
(RFC 8785 / JCS), falling back to a byte compare when either side does
not parse. The widened SELECTs also scan metadata via sql.NullString
and read SQL-NULL as "{}", so a row carrying an explicit NULL -- the
column is nullable -- stays idempotent instead of hard-failing with
"converting NULL to string is unsupported" on a path base handled fine.

RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp covers the
boundary the four-leg matrix never exercised, identical NON-EMPTY
metadata, in two sub-cases: the compact spelling the caller already
sent, and the same fields with their keys reordered. Wired on all three
backends. Red before this commit on both write planes -- embedded dolt
fails both sub-cases, because the renormalization happens on storage
and breaks even byte-identical caller input, and the uow/serve-mode
plane fails ReorderedKeys. Unit pins for the comparison rule and for
the NULL scan live in issueops/dependencies_test.go, and the serve-mode
scan has its own sqlmock twin in
domain/db/dependency_null_metadata_test.go, so reverting either plane's
scan has something red to catch it rather than only one of the two.

Every production and conformance hunk here is byte-identical to stacked
successor #6693, which implements the same repair, so folding it in
leaves that PR a clean drop rather than a conflict to adjudicate.

Addresses review findings 1 (major), 2 and 3 (minor), plus the
iteration-2 test-evidence minor: the NULL repair landed on two planes
but was pinned on one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Jim Wordelman 2026-09-26 14:48:30 -07:00 • committed by GitHub
commit da6263374d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
93 changed files with 7190 additions and 150 deletions

View file

@ -0,0 +1,156 @@
# Versioned Beads: issue-plane write paths and their Phase 2 disposition
This document has two parts. **Dispositions at this head** is the current inventory: every row whose disposition changed after the completeness fix a14f48b17 (merged as 5098ec85f), the seam's call sites at this head, and notes that are true now. **As found at 321a79278** is the review artifact this PR started from — the table donnabox's item 5 on #6358 asked for, derived before the completeness fix — kept verbatim under a dated heading because it is the record of what the review found. Wherever the two parts differ, the current part wins; a reader citing a row number should cite it from the current part.
## Dispositions at this head
Status after a14f48b17 (merged as 5098ec85f on `deploy/be-764ey-gate`): the table below was derived from the tree at 321a79278, before the completeness fix, and is kept as the record of what the review found. Since that commit the following rows changed disposition:
- Rows 17-23, 25 and 27 (close, reopen, claim, unclaim/release, lease reclaim, defer wake, label add/remove, promote, persistence move) are now **VERSIONED**: each mints once, after its row write and event, gated on a row actually changing.
- Rows 14-16 (legacy `AddDependency`/`RemoveDependency` verbs, the uow dependency repository, batch-apply structural adds) are now **VERSIONED** through the lowest-level helpers `addDependencyInTx`/`removeDependencyInTx` (mint gated on the row insert/delete); the publicops editor's own mint call was removed so no leg double-mints.
- Ordering: `ExecuteUpdate` mints once, after field, label, parent and persistence patches; batch create mints per issue after its creation-time edges are persisted, so the first version carries the outgoing edge set.
- `version_completeness_test.go` (46 must-mint entry points, exemption table with reasons, never-mints inverse guard) and `embeddeddolt/version_completeness_behaviour_test.go` pin the set at runtime.
The seam is `issueops.RecordVersionInTx` in internal/storage/issueops/version_history.go (line 87 at 321a79278; cite the function rather than a line at later heads, since comment edits move it), which sits beside the events-journal seam `issueops.RecordEventInTx` (journal.go:309). At 321a79278 it was reached from exactly six call sites: create.go:196, update.go:547, dependency_editor.go:181 and :272, and domain/db/issue.go:87/:102 (`Insert`) and :339 (`Update`); after a14f48b17 it is reached from 27 (18 in issueops, 9 in domain/db), listed in the section "Seam call sites after the completeness fix" below. Dispositions: **VERSIONED** = reaches `RecordVersionInTx` and mints an `issue_versions` row plus the `current_revision` bump; **NO-OP** = discarded before the seam (`DiscardNoopIssueUpdates`, the dependency editor's `eventWritten` gate, create's early returns, or the wisp exclusion); **OUT OF CONTRACT** = mutates an issue-plane row (issues, wisps, dependencies, labels, comments and wisp_* twins) without ever calling the seam. Paths are under `internal/storage/` unless they start with `cmd/`, `internal/compact/` or `backend/`. Checkout: /var/tmp/mayor-beads-phase2 @ deploy/be-764ey-gate; all line numbers are against commit 321a79278, the HEAD when this inventory was read (see the last note on drift).
### Rows whose disposition changed after a14f48b17
Row numbers are the historical table's. Line numbers in this table are against the Go tree at this head (unchanged since 5098ec85f).
| # | Path | Version seam at this head | Disposition | Mechanism |
|---|---|---|---|---|
| 13 | any of rows 1-8 whose target row is a wisp **or a promoted no-history bead** | no | NO-OP | `RecordVersionInTx` returns on `IsWisp`, which is `Ephemeral \|\| NoHistory` (helpers.go:36-41): wisps per FR-8, and a promoted no-history bead — a durable issues-plane row with `NoHistory=true` — because no-history means no history. Wording only; the code did not change. |
| 14 | dependencies.go:`addDependencyInTx` via `AddDependencyInTx` from the store verbs, `ApplyParentPatch`, `applyBatchRun.applyDepAdd` | yes | VERSIONED | mint moved into `addDependencyInTx` (`mintDependencyVersion`, dependencies.go:393), gated on the row insert rather than on `eventWritten`; the publicops editor's own mint call was removed so no leg double-mints |
| 15 | domain/db/dependency.go:`dependencySQLRepositoryImpl.Insert` (uow `AddDependencies`, create-time edges) | yes | VERSIONED | seam at dependency.go:228 and :240 after the insert |
| 16 | dependencies.go:`removeDependencyInTx` via `RemoveDependencyInTx` and domain/db/dependency.go:`Delete` | yes | VERSIONED | gated on the row delete; dependency.go:409 on the uow leg |
| 17 | close.go:`closeIssueInTx` (all close variants; `ExecuteCloseBatch` loops it; domain/db `Close`/`CloseChecked`) | yes | VERSIONED | close.go:394, after the row write and event, gated on the row changing |
| 18 | reopen.go:`reopenIssueInTx` | yes | VERSIONED | reopen.go:126 |
| 19 | claim.go:`claimIssueInTx` and domain/db/issue.go:`Claim` | yes | VERSIONED | claim.go:239 and issue.go:551; `ExecuteUpdate`'s Claim flag passes `mintVersion=false` and mints once at its own end |
| 20 | unclaim.go:`finishUnclaimInTx` (unclaim, release) | yes | VERSIONED | unclaim.go:137 |
| 21 | lease.go:`ReclaimExpiredLeasesInTx` | yes | VERSIONED | lease.go:786 |
| 22 | wake_defers.go:`wakeExpiredDefersInTable` | yes | VERSIONED | wake_defers.go:143 |
| 23 | labels.go:`addLabelInTx` / `removeLabelInTx` and domain/db/label.go:`Insert` / `Delete` | yes | VERSIONED | labels.go:190 and :239 gated on `RowsAffected() > 0`; label.go:91 and :130; `applyLabelPatch` (aggregate.go:360) mints only when called outside `ExecuteUpdate` |
| 25 | promote.go:`PromoteFromEphemeralInTx` | yes | VERSIONED | promote.go:141, after the label, dependency and comment copies |
| 27 | persistence.go:`moveIssuePersistenceInTx` | yes | VERSIONED | persistence.go:76 and :153; `ExecuteUpdate` passes `mintVersion=false` and mints once at its own end |
| 34 | batch_apply.go:`applyBatchRun` | yes, per item | VERSIONED | its create/update/close items reach rows 1/2, 5/6 and 17; its dep-add items reach `addDependencyInTx`, which now mints (row 14) |
Rows not listed keep the disposition shown in the historical table: rows 1-8 VERSIONED; rows 9-12 NO-OP gates inside them; rows 24, 26, 28-33 and 35-39 OUT OF CONTRACT; row 40 writes no issue-plane row; row 41 is Phase 3.
### Counts at this head
Of the 34 live issue-plane write paths (rows 1-8 and 14-39), **21 are VERSIONED** (rows 1-8, 14-23, 25, 27, 34) and **13 are OUT OF CONTRACT** (rows 24, 26, 28-33, 35-39); rows 9-13 are the no-op gates inside the versioned ones. The out-of-contract set is what the design puts out of contract: comments (not part of the snapshot), is_blocked flips, delete, rename and demote (Phase 3's deleted-Versioned-Bead guarantee), compaction bookkeeping and restore, migrations, merge-settle, doctor fixes and raw SQL.
### Still deferred
Still true and deliberately out of contract or deferred: an unchanged re-import of an existing row mints a version (create has no field-level no-op gate — and the journal seam sits in the same position: `RecordEventInTx(EventCreate)` at create.go:207 runs on every accepted upsert, only the events-table write behind the `isNew` gate at create.go:171 is skipped, so a no-op gate belongs in front of both seams, not the version seam alone); the uow leg mints per repository write, so a domain create with N labels and M edges yields 1+N+M versions where the direct legs yield one (each a distinct accepted state; follow-up); demote-to-wisp and delete/rename strand version rows because `issue_versions` has no FK to `issues` (Phase 3's deleted-Versioned-Bead guarantee); compaction bookkeeping, restore, migrations, merge-settle, doctor fixes and `bd sql` remain out of contract by design. The flag-off contract is behaviourally a no-op at the seam (`RecordVersionInTx` returns before any query) but not literally zero added work: labels.go's `RowsAffected` gate and the per-transaction `sync.Map` entry run with the flag off; the differential harness that would prove the stronger claim is not in this PR. The items that become live the first time the flag is on — the uow leg's 1+N+M, the re-import no-op gate on both seams, duplicate-key metadata, the single-writer allocator, and the `attribution_status` vocabulary being enforced only in Go — are tracked together in gastownhall/beads#6379.
### Seam call sites at this head
Verified with `grep -rn 'RecordVersionInTx(' internal/ --include='*.go'` over non-test files at d484b809d (the Go tree is unchanged between the merge of a14f48b17 as 5098ec85f and this note): **27 call sites** reach the seam, 18 on the direct legs in `issueops/` and 9 on the uow leg in `domain/db/`. The figure of 29 quoted in the PR thread was an over-count; this table is the correction. Line numbers are against that tree. The 46 "must-mint entry points" pinned by `version_completeness_test.go` are a different count by design: they are the public entry functions whose call graph must reach the seam, not the seam's own call sites.
Direct legs, `internal/storage/issueops/` (18):
| File:line | Function | Mutation |
|---|---|---|
| aggregate.go:360 | `applyLabelPatch` | label patch (mints only when used outside `ExecuteUpdate`, which passes `mintVersion=false`) |
| aggregate.go:423 | `applyParentPatch` | parent patch (same rule) |
| claim.go:239 | `claimIssueInTx` | claim |
| close.go:394 | `closeIssueInTx` | close, all variants; `ExecuteCloseBatch` loops it |
| create.go:216 | `CreateIssueInTxWithResult` | singular create and import upsert |
| create.go:384 | `CreateIssuesInTxWithContext` | batch create, per issue, after its creation-time edges (`DeferVersionMint`) |
| dependencies.go:393 | `mintDependencyVersion` | from `addDependencyInTx` / `removeDependencyInTx`: legacy verbs, the publicops editor, batch-apply |
| execution.go:269 | `ExecuteUpdate` | once, after field, label, parent and persistence patches |
| labels.go:190 | `addLabelInTx` | label add |
| labels.go:239 | `removeLabelInTx` | label remove |
| lease.go:786 | `ReclaimExpiredLeasesInTx` | lease reclaim |
| persistence.go:76, :153 | `moveIssuePersistenceInTx` | persistence move (two sites in the one function) |
| promote.go:141 | `PromoteFromEphemeralInTx` | promote from ephemeral |
| reopen.go:126 | `reopenIssueInTx` | reopen |
| unclaim.go:137 | `finishUnclaimInTx` | unclaim / release |
| update.go:555 | `updateIssueInTx` | update |
| wake_defers.go:143 | `wakeExpiredDefersInTable` | defer wake |
uow leg, `internal/storage/domain/db/` (9):
| File:line | Method | Mutation |
|---|---|---|
| issue.go:87, :102 | issue repository `Insert` | create (two sites in the one method) |
| issue.go:339 | issue repository `Update` | update |
| issue.go:551 | issue repository `Claim` | claim |
| label.go:91 | label repository `Insert` | label add |
| label.go:130 | label repository `Delete` | label remove |
| dependency.go:228, :240 | dependency repository `Insert` | edge add (two sites in the one method) |
| dependency.go:409 | dependency repository `Delete` | edge remove |
### Notes at this head
- **What actually versions:** every accepted issue-plane mutation on every leg — create (singular, batch, import), update (and everything that reaches `updateIssueInTx`: metadata merge/delete/CAS, deleted-reference rewrite, compaction's content rewrite), dependency add and remove (editor, legacy verbs, uow repository, batch-apply), close, reopen, claim, unclaim/release, lease reclaim, defer wake, label add and remove, promote, persistence move. `version_completeness_test.go` pins 46 must-mint entry points with an exemption table (a reason per row) and an inverse never-mints guard; `embeddeddolt/version_completeness_behaviour_test.go` pins the runtime deltas.
- **Cross-leg symmetry on dependencies:** resolved. The dolt and embeddeddolt editors, the legacy store verbs and the uow repository all reach the seam through `addDependencyInTx` / `removeDependencyInTx`, gated on the row insert or delete.
- **Ordering inside a versioned call:** the mint is the last durable-state write. `ExecuteUpdate` mints once after its field, label, parent and persistence patches; batch create mints per issue after `PersistDependenciesWithOptionsResult`, so the first version carries the creation-time edge set.
- **Count vs design:** 21 VERSIONED, 13 OUT OF CONTRACT, 5 no-op gates (see Counts at this head). The design's "eighteen" is still not reconcilable item by item from this checkout.
- **Import upsert:** an unchanged re-import of an existing row still mints, and it also journals — `RecordEventInTx(EventCreate)` at create.go:207 runs on every accepted upsert — so the no-op gate belongs in front of both seams (gastownhall/beads#6379, item 2).
- **No FK from issue_versions to issues** (0067), so delete, rename and demote strand version rows under ids that no longer exist in `issues` — Phase 3 (gastownhall/beads#6379, item 6).
- **Non-canonicalizable snapshots fail the mutation** by policy: duplicate keys in an issue's `metadata` (a `json.RawMessage`) make `canonicalDurableState` return an error and abort the transaction with the flag on (gastownhall/beads#6379, item 3).
- **Single writer means one writer at a time per store,** not merely one clone: `MAX(revision)+1` is not a safe allocator for two concurrent transactions in one store either, and no contract case runs concurrent writers (gastownhall/beads#6379, item 4).
- **Exemption tables that name the seam:** journal_completeness_test.go `beadDMLExemptions` and row_lock_guard_test.go `funcNameExemptions` both list `RecordVersionInTx` as bookkeeping for an already-journaled mutation; unchanged.
## As found at 321a79278 (historical; superseded above wherever the two parts differ)
The table and notes below are the inventory as derived from the tree at 321a79278, the HEAD when it was read, and all line numbers in this part are against that commit. It is kept verbatim as the record of what the review found. Rows 13-23, 25, 27 and 34 are superseded by the current table above; the notes below that contradict the notes above are superseded too.
| # | Path (file:function) | Writes | Events seam | Version seam | Disposition | Why |
|---|---|---|---|---|---|---|
| 1 | issueops/create.go:`CreateIssueInTxWithResult` (`CreateIssueInTx`; execution.go:`ExecuteCreate`; dolt/issues.go:`createIssue`; dolt/transaction.go and embeddeddolt/transaction.go `CreateIssue`) | issues or wisps row via `InsertIssueIfNew` (ON DUPLICATE KEY UPDATE upsert) + labels + comments | yes | yes | VERSIONED | both seams run once after labels/comments persist (create.go:193-197); an existing-row upsert (`isNew=false`) still mints — create has no field-level no-op gate |
| 2 | domain/db/issue.go:`issueSQLRepositoryImpl.Insert` (`InsertBatch` loops it; domain `IssueUseCase.CreateIssue`/`CreateWisp` from uow/issue_operations.go, uow/batch_creator.go, uow/batch_applier.go) | issues or wisps via `issueops.InsertIssueStrictInTx` | yes | yes | VERSIONED | uow leg; `RecordVersionInTx` directly after `RecordEventInTx` in both branches (issue.go:84-87, 99-102) |
| 3 | issueops/create.go:`CreateIssuesInTxWithContext` / `CreateIssuesInTxWithResult` (create_batch.go:`ExecuteCreateBatch`; store `CreateIssuesWithFullOptions` on both direct legs) | row 1 per issue, then `PersistDependenciesWithOptionsResult` | yes (per issue, plus dep events) | yes (per issue) | VERSIONED | per-issue loop (create.go:309); creation-time edges are inserted AFTER each issue's version row, so they are neither in that row's `durable_state` nor versioned themselves |
| 4 | Import: uow/importer.go:`importer.ImportBatch`; embeddeddolt/store.go:`ImportJSONLData`; embeddeddolt/transaction.go:`CreateIssueImport`; cmd/bd/import_shared.go via `store.CreateIssuesWithFullOptions` | as row 3 | yes | yes | VERSIONED | import is not a separate write path — it funnels into rows 1/3; at 321a79278 rows get `attribution_status` supplied/undetermined and `imported` is only reserved (version_history.go:57-61); 56b2199d4, which landed mid-session, collapses the values to claimed/unknown with no `imported` at all |
| 5 | issueops/update.go:`updateIssueInTx` (`UpdateIssueInTx`, `UpdateIssueWithoutEventInTx`; execution.go:`ExecuteUpdate`; metadata.go:`writeMergedMetadataInTx` from `MergeMetadataInTx`/`DeleteMetadataInTx`/metadata_cas.go:`CompareAndSetMetadataKeyInTx`; delete_role.go:`RewriteDeletedReferencesInTx`; compaction's content rewrite via `store.UpdateIssue`) | UPDATE issues or wisps SET fields, row_lock | yes | yes | VERSIONED | seams at update.go:544-547, after `DiscardNoopIssueUpdates` (:391) and NOT inside `if recordEvent` — `UpdateIssueWithoutEventInTx` still versions |
| 6 | domain/db/issue.go:`issueSQLRepositoryImpl.Update` (domain `IssueUseCase.ApplyUpdate` from uow/issue_operations.go, uow/batch_applier.go) | UPDATE issues or wisps | yes | yes | VERSIONED | uow leg; same no-op gate (issue.go:212-219), seams at :336-339 |
| 7 | issueops/dependency_editor.go:`addDependencyEdgeInTx` (`ExecuteAddDependencies` from dolt/dependency_editor.go, embeddeddolt/dependency_editor.go) | INSERT dependencies or wisp_dependencies via `AddDependencyInTx` (+ is_blocked marks) | yes (`RecordDepEventInTx` inside `addDependencyInTx`) | yes, iff `eventWritten` | VERSIONED | versions the referencing (source) issue only when a row was recorded (dependency_editor.go:180-183) |
| 8 | issueops/dependency_editor.go:`ExecuteRemoveDependency` (from dolt/dependency_editor.go, embeddeddolt/dependency_editor.go) | DELETE dependencies or wisp_dependencies via `RemoveDependencyInTx` | yes | yes, iff `eventWritten` | VERSIONED | returns `Removed:false` before the seam when no row matched (:263-274) |
| 9 | update.go:`updateIssueInTx` / domain/db/issue.go:`Update` when `DiscardNoopIssueUpdates` leaves no field | nothing | no | no | NO-OP | returns before the UPDATE (update.go:391-397; issue.go:212-219) — the FR-2 contract case |
| 10 | dependency_editor.go:`addDependencyEdgeInTx` on a same-type re-add | UPDATE dependencies SET metadata (dependencies.go:274) | yes (dependencies.go:281) | no | NO-OP | `addDependencyInTx` returns `eventWritten=false` on the existing-edge branch, so the seam is skipped although metadata is rewritten and journaled |
| 11 | dependency_editor.go:`ExecuteRemoveDependency` on an absent edge | nothing | no | no | NO-OP | `removeDependencyInTx` reports `eventWritten=false`; editor returns at :267 |
| 12 | create.go:`CreateIssueInTxWithResult` on collision-skip, `ConflictSkip` or `RejectStaleUpserts` hit | nothing | no | no | NO-OP | early returns at create.go:126-128, 135-143 precede both seams |
| 13 | any of rows 1-8 whose target row is a wisp | as per row | yes | no | NO-OP | `RecordVersionInTx` returns nil on `IsWisp` (version_history.go:96, FR-8); wisps.current_revision stays at its default |
| 14 | dependencies.go:`addDependencyInTx` via `AddDependencyInTx` from the store verbs — dolt/dependencies.go:`addDependencyWithOptions`, dolt/transaction.go and embeddeddolt/transaction.go `AddDependencyWithOptions`, embeddeddolt/dependencies.go, dolt/wisps.go:`addWispDependency`, batch_apply.go:`applyBatchRun.applyDepAdd`, aggregate.go:`ApplyParentPatch` | INSERT dependencies or wisp_dependencies | yes | no | OUT OF CONTRACT | same DML as row 7 but no caller invokes `RecordVersionInTx`; only the publicops editor role versions |
| 15 | domain/db/dependency.go:`dependencySQLRepositoryImpl.Insert` (domain `DependencyUseCase.AddDependencies` from uow/dependency_editor.go and uow/batch_applier.go; `IssueUseCase` create-time edges, domain/issue.go:980,1041,1053) | INSERT dependencies or wisp_dependencies | yes | no | OUT OF CONTRACT | the uow leg's dependency add never reaches the seam — only `Insert`/`Update` in domain/db/issue.go do |
| 16 | dependencies.go:`removeDependencyInTx` via `RemoveDependencyInTx` from store verbs (dolt/dependencies.go and both transactions `RemoveDependencyWithOptions`, `ApplyParentPatch`) and domain/db/dependency.go:`Delete` (uow `RemoveDependencyBySource`) | DELETE dependencies or wisp_dependencies | yes (when EmitEvent) | no | OUT OF CONTRACT | as row 14 |
| 17 | close.go:`closeIssueInTx` (`CloseIssueInTx`, `CloseIssueWithoutEventInTx`, `CloseIssueCheckedInTx`; execution.go:`ExecuteClose`; close_batch.go:`ExecuteCloseBatch` loops `ExecuteClose`; domain/db `Close`/`CloseChecked`) | UPDATE issues or wisps SET status, closed_at, close_reason, closed_by_session, row_lock (close.go:340) | yes (EventClose, close.go:387, not gated by `recordEvent`) | no | OUT OF CONTRACT | direct UPDATE; never calls `RecordVersionInTx`, so a close is invisible to issue_versions |
| 18 | reopen.go:`reopenIssueInTx` (`ReopenIssueInTx`; execution.go:`ExecuteReopen`; domain/db `Reopen`) | UPDATE status/closed_at (reopen.go:64) | yes | no | OUT OF CONTRACT | as row 17 |
| 19 | claim.go:`ClaimIssueInTx` (public_claim.go:`ExecuteClaim`; `ClaimReadyIssueInTx` from claim_next.go:`ExecuteClaimNext`; `ExecuteUpdate`'s Claim flag) and domain/db/issue.go:`Claim` (uow) | UPDATE assignee/status/started_at (claim.go:115,124; issue.go:478,488) | yes | no | OUT OF CONTRACT | a claim-only request mints nothing; `ExecuteUpdate` versions only if other fields also change (execution.go: `ClaimIssueInTx` then `if len(updates) > 0`) |
| 20 | unclaim.go:`UnclaimIssueInTx` / `UnclaimIssueIfAssigneeInTx` via `finishUnclaimInTx`; release_role.go:`ReleaseIssueInTx` wraps them (domain/db `UnclaimIssue`/`ReleaseIssue`) | UPDATE assignee/status (unclaim.go:80,197) | yes | no | OUT OF CONTRACT | direct UPDATE |
| 21 | lease.go:`ReclaimExpiredLeasesInTx` (dolt/issues.go:473, embeddeddolt/issues.go:134, domain/db `ReclaimExpiredLeases`) | UPDATE issues assignee/status revert (lease.go:758) + DELETE leases | yes | no | OUT OF CONTRACT | `HeartbeatIssueInTx` writes only `leases` and is not an issue-record write |
| 22 | wake_defers.go:`wakeExpiredDefersInTable` (`WakeExpiredDefersInTx`; dolt/queries.go:63, embeddeddolt/queries.go:33, domain/db `WakeExpiredDefers`) | UPDATE status (wake_defers.go:116) | yes (actor `DeferWakeActor`) | no | OUT OF CONTRACT | scheduled status flip outside the seam |
| 23 | labels.go:`AddLabelInTx` / `RemoveLabelInTx` (dolt/labels.go, embeddeddolt/labels.go, both transactions, aggregate.go:`ApplyLabelPatch` from `ExecuteUpdate`) and domain/db/label.go:`Insert` / `Delete` (uow `LabelUseCase`) | INSERT IGNORE / DELETE labels or wisp_labels | yes (EventUpdate) | no | OUT OF CONTRACT | labels ARE in `durable_state` (get_issue.go:59 hydrates them) but a label change mints nothing; in `ExecuteUpdate` the label patch runs after `UpdateIssueInTx`'s mint, so a same-call field+label edit records the old label set |
| 24 | comments.go:`addIssueCommentInTx` (`AddIssueCommentInTx`, `ImportIssueCommentInTx`, commenter.go:`ExecuteAddComment`); dolt/transaction.go:`AddComment` / `ImportIssueComment` (`InsertDerivedEventReturningID` / `InsertDerivedComment`); domain/db/comment.go:`InsertRecord` (uow `CommentUseCase`); create.go:`PersistComments` | INSERT comments or wisp_comments (dolt tx `AddComment` writes an events-table comment row) | yes (`RecordCommentEventInTx`) | no | OUT OF CONTRACT | comments are not in `durable_state` either (`GetIssueInTx` joins labels, not comments) |
| 25 | promote.go:`PromoteFromEphemeralInTx` (dolt/ephemeral_routing.go:205, embeddeddolt/store.go:1003, domain/db `PromoteFromEphemeral`) | INSERT issues (+ label/dep/comment copies), DELETE wisps | yes | no | OUT OF CONTRACT | promoted row lands with current_revision default 1 and no version row |
| 26 | dolt/ephemeral_routing.go:`DoltStore.demoteToWispInTx` | `UpdateIssueWithoutEventInTx` (row 5), then raw aux copies + DELETE FROM issues (:303) | yes | yes (update half only) | OUT OF CONTRACT | mints a version row for an issue the same tx then deletes; issue_versions has no FK to issues (0067), so the row strands |
| 27 | persistence.go:`MoveIssuePersistenceInTx` (`ExecuteUpdate` persistence patch; domain/db `MovePersistence`) | `InsertIssueStrictInTx` into the target plane, copy aux, DELETE source (persistence.go:70,106) | yes (twice) | no | OUT OF CONTRACT | plane move bypasses both the create and update seams |
| 28 | delete.go:`deleteIssueRowInTx` / `DeleteIssuesInTx` / `DeleteResolvedSetInTx`; delete_role.go:`DeleteInTx`; sweep.go:`SweepInTx`; dolt/wisps.go:`deleteWisp` / `deleteWispBatchTx`; domain/db/issue.go:`Delete` / `DeleteByIDs` (+ label/dependency/events `DeleteAllForIDs`, domain/issue_delete.go) | DELETE issues or wisps + aux + leases | yes (`RecordDeleteInTx`) | no | OUT OF CONTRACT | no surviving row; the deleted-Versioned-Bead guarantee is Phase 3 (PR #6358); orphaned issue_versions rows remain. delete_role.go:`RewriteDeletedReferencesInTx` then goes through row 5, so neighbours DO mint versions |
| 29 | bulk_ops.go:`DeleteIssuesBySourceRepoInTx` (dolt/issues.go:946, embeddeddolt/store.go:987) | bulk DELETE issues WHERE source_repo = ? | yes (per id) | no | OUT OF CONTRACT | bulk path |
| 30 | bulk_ops.go:`UpdateIssueIDInTx` via `updateIssueIDInTx` / `updateWispIDInTx` (dolt/rename.go:14, embeddeddolt/store.go:995) | UPDATE issues SET id = ? + dependency rekey | yes (dep-remove, delete old, create new, dep-add via `recordRenameInJournal`) | no | OUT OF CONTRACT | history stays keyed to the old issue_id; the new id carries current_revision with no matching rows |
| 31 | compaction.go:`ApplyCompactionInTx` (dolt/compact.go:52, embeddeddolt/store.go:1179) | UPDATE issues SET compaction_level, compacted_at, compacted_at_commit, original_size, updated_at | no (`beadDMLExemptions`) | no | OUT OF CONTRACT | the content rewrite that precedes it (internal/compact/compactor.go:147, cmd/bd/compact.go:702 via `store.UpdateIssue`) IS row 5, so compaction mints exactly one version for the summary while its own columns land unversioned |
| 32 | compaction.go:`RestoreFromSnapshotInTx` (dolt/compact.go:82, embeddeddolt/store.go:1203) | UPDATE issues content from snapshot (compaction.go:173,181) | no | no | OUT OF CONTRACT | restore's CAS composition is Phase 3 (PR #6358) |
| 33 | blocked_state.go mark/unmark templates via `RecomputeIsBlocked*` / `MarkIsBlockedInTx`; dependencies.go:`markDirectBlockingDependencySourceInTx`; domain/db/dependency.go:`markDirectBlockedSource` | UPDATE issues or wisps SET is_blocked | yes, flips only (journal.go:`recordBlockedJournalChanges`, actorless) | no | OUT OF CONTRACT | derived state; is_blocked is not hydrated into `durable_state` |
| 34 | batch_apply.go:`applyBatchRun` (`ApplyBatch`; uow/batch_applier.go) | per item: create rows 1/2, update rows 5/6, close row 17, dep add rows 14/15 | per item | per item | OUT OF CONTRACT (mixed) | dep-add items call `AddDependencyInTx` / `DependencyUseCase.AddDependencies`, never the versioned editor |
| 35 | schema/cli_migrations.go:`cliMigration0053RepairRigWisps` (INSERT IGNORE INTO issues, UPDATE issues, DELETE FROM wisps); schema/migration_repairs.go and schema/wisp_dep_forward_repair.go (dependencies rewrites) | migration DML | no | no | OUT OF CONTRACT | 0067/0068 themselves are DDL only (ADD COLUMN ... DEFAULT 1; no row backfill) |
| 36 | versioncontrolops/automerge.go:`resolveIssuesFieldMerge` (UPDATE `issues`); versioncontrolops/mergesettle.go:`TryRepairFKCascadeViolations` (`fkCascadeRepairDeletes` on dependencies/labels/comments) | merge-settle rewrites and orphan deletes | no | no | OUT OF CONTRACT | raw connection during merge settlement |
| 37 | dolt/federation.go:`deleteExcludedIssues` (from `stageFilteredBranch`) | DELETE FROM issues WHERE ephemeral = 1 / issue_type = ? on the staging branch | no | no | OUT OF CONTRACT | raw conn on a filtered-push branch |
| 38 | cmd/bd/doctor/fix/validation.go:`OrphanedDependencies` / `ChildParentDependencies` / `CrossTableDuplicates` | `tx.Exec` DELETE FROM dependencies / issues | no | no | OUT OF CONTRACT | raw doctor fixes |
| 39 | cmd/bd/sql.go (`storage.RawDBAccessor.UnderlyingDB` then `db.ExecContext`); cmd/bd/sql_proxied_server.go via uow `RawSQLUseCase().Exec` to domain/db/raw_sql.go | arbitrary SQL | no | no | OUT OF CONTRACT | the proxied variant runs inside a uow tx with the version scope bound (uow/dolt_sql_provider.go:178) but raw SQL never calls the seam |
| 40 | issueops/bootstrap.go:`BootstrapInTx` (uow/bootstrapper.go, hook_bootstrapper.go) | config + metadata tables only (`SetConfigInTx`, `SetMetadataInTx`) | no | no | OUT OF CONTRACT (n/a) | writes no issue-plane row at all |
| 41 | PLANNED 18th: `fk_dep_issue_target` ON DELETE CASCADE (schema/cli_migrations.go:284,311; migrations 0041/0043) | DB-level cascade deleting dependencies rows when their target issues row is deleted; no Go call site | no | no | Phase 3 (planned) | PR #6358 body: "Phase 3 items by design: the `fk_dep_issue_target` cascade (the 18th path)"; today it fires silently underneath rows 28-29 |
### Notes as found at 321a79278
- **Count vs design.** Grouping by leaf mutation function, the code has **34 live issue-plane write paths** (rows 1-8 and 14-39; row 40 excluded because it writes no issue row; rows 9-13 are gates inside rows 1-8) plus the planned FK cascade — not eighteen. Of the 34, **8 are VERSIONED, 26 OUT OF CONTRACT**, and 5 NO-OP gates sit inside the versioned ones. The design's own list (be-hs42e.3) is not resolvable from this checkout or `bd show`; only PR #6358's "the 18th path" line was found, so the eighteen could not be reconciled item by item.
- **What actually versions:** create, update (and their uow twins in domain/db/issue.go) and the publicops dependency editor. Every other journaled mutation — close, reopen, claim, unclaim/release, lease reclaim, defer wake, labels, comments, promote, persistence move, delete, rename — reaches `RecordEventInTx` but never `RecordVersionInTx`, even though version_history.go:20-27 describes the seam as living "inside the same already-short-circuited functions that call RecordEventInTx". journal_completeness_test.go pins 57 `mutationEntryPoints` for the journal; the version seam is wired into 3 of them, and no equivalent completeness test exists for it.
- **Cross-leg asymmetry on dependencies:** the dolt and embeddeddolt DependencyEditor roles version (rows 7-8); the uow DependencyEditor role goes through domain/db dependency `Insert`/`Delete` and does not (rows 15-16). The legacy store verbs `AddDependency`/`RemoveDependency` do not on any leg (rows 14, 16).
- **Versioned only via a helper:** `MergeMetadataInTx`, `DeleteMetadataInTx`, `CompareAndSetMetadataKeyInTx`, `RewriteDeletedReferencesInTx`, compaction's content rewrite and `demoteToWispInTx` version solely because they call `UpdateIssueInTx` / `UpdateIssueWithoutEventInTx`.
- **Per-issue loops:** batch create, import, uow `InsertBatch` (versioned per issue); `ExecuteCloseBatch` loops `ExecuteClose` (row 17, unversioned per issue); `DeleteIssuesInTx` (unversioned).
- **Ordering inside a versioned call:** batch-create edges (row 3) and `ExecuteUpdate`'s label/parent patches (rows 23, 14) land after the mint, so the minted `durable_state` predates them.
- **Import upsert:** an unchanged re-import of an existing row (`isNew=false`, stale check not tripped) mints a version because create has no field-level no-op gate — unlike update's FR-2 behaviour (row 9).
- **No FK from issue_versions to issues** (migration 0067 creates the table without one), so delete, rename and demote (rows 26, 28, 30) strand version rows under ids that no longer exist in issues.
- **Exemption tables that name the seam:** journal_completeness_test.go `beadDMLExemptions` and row_lock_guard_test.go `funcNameExemptions` both list `RecordVersionInTx` as bookkeeping for an already-journaled mutation.
- **Drift during this session (2026-09-07 13:31-13:33):** the branch advanced to 56b2199d4 (`attribution_status` renamed to claimed|unknown, ordinals documented as local) and the working tree then carried further uncommitted edits by another agent — version_history.go (RFC 8785 canonical `durable_state` via `jcs`, with go.mod/go.sum), cli_migrations.go, the 0068 up/down SQL, three schema tests and an untracked version_history_durable_state_test.go. Neither adds or removes a `RecordVersionInTx` call site (the six above were re-verified against 321a79278 and the live tree) and no disposition changes; this inventory is against 321a79278 and does not cover them.

View file

@ -0,0 +1,372 @@
package conformance
import (
"context"
"testing"
"time"
)
// This file holds the contract for R16.1 (gastownhall/beads#6133,
// be-hs42e.1 §5-§7, FR-02, FR-03): enforcement that spans more than one
// record, which ExpectedRevisionFixture's per-record CompareAndSetVersion
// structurally cannot see.
//
// GuardedWrite AND ExpectedRevisionFixture.CompareAndSetVersion SHARE THE
// EXACT SAME TYPE, PerRecordCASWrite, declared once in
// expected_revision_contract.go. R16.1-a's boundary claim is literally that
// the second is the first, called twice against records that individually
// pass but jointly violate a store invariant — sharing the type makes that
// claim structural, checked by the compiler, rather than merely asserted in
// a doc comment.
//
// TWO CONCRETE SUBJECTS ARE REQUIRED BY FR-02 RATHER THAN INVENTED HERE:
// Memory key/alias uniqueness (#5877 R2) and graph-edge
// MaximumEndpointMultiplicity. MemoryKeyAliasWrite and GraphEdgeWrite exist
// so the cases named for them construct a REAL joint violation in each
// subject's own vocabulary, rather than a synthetic one this file made up.
//
// EVERY HOOK BELOW IS INDEPENDENTLY NILABLE — see the package-level note in
// expected_revision_contract.go. Every case nil-checks every hook it uses
// and SKIPS BY NAME when one is missing.
// RecordWrite is one record's half of a multi-record write submitted to
// EnforceCrossRecordInvariant.
type RecordWrite struct {
ID string
Expected *Address
Patch map[string]any
}
// InvariantResult is the outcome of a call to EnforceCrossRecordInvariant.
type InvariantResult struct {
Accepted bool
InvariantRefusal *InvariantRefusal
}
// InvariantRefusal names the specific store invariant a multi-record write
// violated (R16.1-c) — never a bare boolean, so a caller (and a test) can
// tell which invariant fired.
type InvariantRefusal struct {
InvariantName string
}
// LeaseHandle is an advisory lease over subject. It is observed by
// convention only (FR-03): holding one does not, by itself, change what any
// per-record or invariant-enforcing write accepts.
type LeaseHandle struct {
Subject string
ExpiresAt time.Time
// Release ends the lease early. A nil Release means the fixture expects
// the lease to simply expire; cases treat a nil Release as optional
// cleanup, not a required call.
Release func(ctx context.Context) error
}
// CrossRecordInvariantFixture supplies the capabilities under test for
// R16.1: enforcement that spans more than one record, and the advisory
// lease primitive FR-03 says is insufficient on its own to provide it.
type CrossRecordInvariantFixture struct {
IssuePrefix string
// GuardedWrite is a per-record CAS write over the SAME type as
// ExpectedRevisionFixture.CompareAndSetVersion (PerRecordCASWrite) — see
// this file's package doc comment for why. A nil hook means this
// backend exposes no per-record guard to construct the boundary case
// against, and cases that need one skip with that reason.
GuardedWrite PerRecordCASWrite
// EnforceCrossRecordInvariant evaluates writes as one joint operation
// and refuses the whole batch, with a named InvariantRefusal, if
// accepting it would violate a store invariant spanning more than one
// of the given records. A nil hook means this backend has not wired
// store-invariant enforcement yet, and cases that need one skip with
// that reason.
EnforceCrossRecordInvariant func(ctx context.Context, writes []RecordWrite) (InvariantResult, error)
// AcquireAdvisoryLease acquires a convention-only lease over subject for
// up to ttl. A nil hook means this backend has no lease primitive to
// test as an insufficient guard, and cases that need one skip with that
// reason.
AcquireAdvisoryLease func(ctx context.Context, subject string, ttl time.Duration) (LeaseHandle, error)
// CountHistoryForSubject reports how many durable history entries exist
// for subject. A nil hook means this backend cannot observe history by
// subject, and cases that need one skip with that reason.
CountHistoryForSubject func(ctx context.Context, subject string) (int, error)
// MemoryKeyAliasWrite writes memoryID's key/alias pair unconditionally,
// in the shape of a per-record write (FR-02's first named subject,
// #5877 R2). A nil hook means this backend exposes no Memory key/alias
// write to probe, and the case that needs it skips with that reason.
MemoryKeyAliasWrite func(ctx context.Context, memoryID, key, alias string) (ExpectedRevisionResult, error)
// GraphEdgeWrite writes a graph edge unconditionally, in the shape of a
// per-record write (FR-02's second named subject,
// MaximumEndpointMultiplicity). A nil hook means this backend exposes no
// graph edge write to probe, and the case that needs it skips with that
// reason.
GraphEdgeWrite func(ctx context.Context, fromID, toID, edgeType string) (ExpectedRevisionResult, error)
}
// RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards pins R16.1-a's
// boundary claim directly: two writes, each individually valid under
// GuardedWrite (== CompareAndSetVersion), that JOINTLY violate a store
// invariant neither call's own precondition can see. Both must be Accepted
// through GuardedWrite alone — the whole point of R16.1 is that this
// per-record guard cannot catch what only spans records.
func RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.GuardedWrite == nil {
t.Skip("this backend exposes no per-record guard to construct the boundary case against (GuardedWrite is nil)")
}
shared := fixture.IssuePrefix + "-crossrec-shared-alias"
first, err := fixture.GuardedWrite(ctx, fixture.IssuePrefix+"-crossrec-a", nil, map[string]any{"alias": shared})
if err != nil {
t.Fatalf("GuardedWrite(a): %v", err)
}
if !first.Accepted {
t.Fatalf("GuardedWrite(a) claiming alias %q was refused (Refusal=%+v), want Accepted: a per-record guard cannot see a joint violation", shared, first.Refusal)
}
second, err := fixture.GuardedWrite(ctx, fixture.IssuePrefix+"-crossrec-b", nil, map[string]any{"alias": shared})
if err != nil {
t.Fatalf("GuardedWrite(b): %v", err)
}
if !second.Accepted {
t.Fatalf("GuardedWrite(b) claiming the SAME alias %q was refused (Refusal=%+v), want Accepted (R16.1-a: per-record CAS structurally cannot catch a cross-record conflict)", shared, second.Refusal)
}
}
// RunStoreInvariantTransactionScopesExactlyTheSpanningRecords pins R16.1-b:
// EnforceCrossRecordInvariant refuses a batch that jointly violates an
// invariant, and — checked against an unrelated, non-conflicting write in
// the same call shape — must not refuse more broadly than the records that
// actually span the violation.
func RunStoreInvariantTransactionScopesExactlyTheSpanningRecords(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.EnforceCrossRecordInvariant == nil {
t.Skip("this backend has not wired store-invariant enforcement yet (EnforceCrossRecordInvariant is nil)")
}
shared := fixture.IssuePrefix + "-crossrec-scope-alias"
spanning := []RecordWrite{
{ID: fixture.IssuePrefix + "-crossrec-scope-a", Patch: map[string]any{"alias": shared}},
{ID: fixture.IssuePrefix + "-crossrec-scope-b", Patch: map[string]any{"alias": shared}},
}
var beforeA, beforeB int
if fixture.CountHistoryForSubject != nil {
var err error
beforeA, err = fixture.CountHistoryForSubject(ctx, spanning[0].ID)
if err != nil {
t.Fatalf("CountHistoryForSubject(%s) before the refused batch: %v", spanning[0].ID, err)
}
beforeB, err = fixture.CountHistoryForSubject(ctx, spanning[1].ID)
if err != nil {
t.Fatalf("CountHistoryForSubject(%s) before the refused batch: %v", spanning[1].ID, err)
}
} else {
t.Logf("this backend cannot observe history by subject (CountHistoryForSubject is nil): the before-batch history counts for %s and %s go uncaptured", spanning[0].ID, spanning[1].ID)
}
result, err := fixture.EnforceCrossRecordInvariant(ctx, spanning)
if err != nil {
t.Fatalf("EnforceCrossRecordInvariant(spanning): %v", err)
}
if result.Accepted {
t.Fatal("EnforceCrossRecordInvariant accepted two writes that jointly violate the shared-alias invariant")
}
if fixture.CountHistoryForSubject != nil {
afterA, err := fixture.CountHistoryForSubject(ctx, spanning[0].ID)
if err != nil {
t.Fatalf("CountHistoryForSubject(%s) after the refused batch: %v", spanning[0].ID, err)
}
afterB, err := fixture.CountHistoryForSubject(ctx, spanning[1].ID)
if err != nil {
t.Fatalf("CountHistoryForSubject(%s) after the refused batch: %v", spanning[1].ID, err)
}
if afterA != beforeA || afterB != beforeB {
t.Errorf("a refused batch left a trace: history count for %s went %d->%d, for %s went %d->%d; a refusal must be atomic — the whole batch takes no effect, not just the record that individually triggered it", spanning[0].ID, beforeA, afterA, spanning[1].ID, beforeB, afterB)
}
} else {
t.Logf("this backend cannot observe history by subject (CountHistoryForSubject is nil): the refused batch's atomicity (no partial trace left behind for %s or %s) goes unverified", spanning[0].ID, spanning[1].ID)
}
unrelated := []RecordWrite{
{ID: fixture.IssuePrefix + "-crossrec-scope-unrelated", Patch: map[string]any{"alias": fixture.IssuePrefix + "-crossrec-scope-unrelated-alias"}},
}
independent, err := fixture.EnforceCrossRecordInvariant(ctx, unrelated)
if err != nil {
t.Fatalf("EnforceCrossRecordInvariant(unrelated): %v", err)
}
if !independent.Accepted {
t.Fatalf("EnforceCrossRecordInvariant refused an unrelated, non-conflicting write (InvariantRefusal=%+v); the invariant transaction must scope exactly the spanning records, not more", independent.InvariantRefusal)
}
}
// RunInvariantRefusalNamesTheViolatedInvariant pins R16.1-c: a refused batch
// carries an InvariantRefusal naming the specific invariant that fired, not
// a bare boolean.
func RunInvariantRefusalNamesTheViolatedInvariant(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.EnforceCrossRecordInvariant == nil {
t.Skip("this backend has not wired store-invariant enforcement yet (EnforceCrossRecordInvariant is nil)")
}
shared := fixture.IssuePrefix + "-crossrec-named-alias"
result, err := fixture.EnforceCrossRecordInvariant(ctx, []RecordWrite{
{ID: fixture.IssuePrefix + "-crossrec-named-a", Patch: map[string]any{"alias": shared}},
{ID: fixture.IssuePrefix + "-crossrec-named-b", Patch: map[string]any{"alias": shared}},
})
if err != nil {
t.Fatalf("EnforceCrossRecordInvariant: %v", err)
}
if result.Accepted {
t.Fatal("EnforceCrossRecordInvariant accepted a joint violation; cannot check the refusal's InvariantName")
}
if result.InvariantRefusal == nil {
t.Fatal("InvariantRefusal = nil on a non-accepted result")
}
if result.InvariantRefusal.InvariantName == "" {
t.Error("InvariantRefusal.InvariantName is empty, want a specific invariant name (R16.1-c)")
}
}
// RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS pins FR-02's first
// required subject: Memory key/alias uniqueness (#5877 R2) is a STORE
// invariant, not row-level CAS, so two memories independently claiming the
// same alias each succeed when checked one at a time through a
// per-record-shaped call.
func RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.MemoryKeyAliasWrite == nil {
t.Skip("this backend exposes no Memory key/alias write to probe (MemoryKeyAliasWrite is nil)")
}
alias := fixture.IssuePrefix + "-crossrec-memalias"
first, err := fixture.MemoryKeyAliasWrite(ctx, fixture.IssuePrefix+"-crossrec-mem-a", "key-a", alias)
if err != nil {
t.Fatalf("MemoryKeyAliasWrite(a): %v", err)
}
if !first.Accepted {
t.Fatalf("MemoryKeyAliasWrite(a) was refused (Refusal=%+v), want Accepted", first.Refusal)
}
second, err := fixture.MemoryKeyAliasWrite(ctx, fixture.IssuePrefix+"-crossrec-mem-b", "key-b", alias)
if err != nil {
t.Fatalf("MemoryKeyAliasWrite(b): %v", err)
}
if !second.Accepted {
t.Fatalf("MemoryKeyAliasWrite(b) claiming the SAME alias %q was refused (Refusal=%+v); alias uniqueness (#5877 R2) is a store invariant, so a per-record write cannot enforce it and must be Accepted here", alias, second.Refusal)
}
}
// RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS pins FR-02's second
// required subject: MaximumEndpointMultiplicity is a STORE invariant, not
// row-level CAS, so two edges independently claiming the same endpoint each
// succeed when checked one at a time through a per-record-shaped call.
func RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.GraphEdgeWrite == nil {
t.Skip("this backend exposes no graph edge write to probe (GraphEdgeWrite is nil)")
}
from := fixture.IssuePrefix + "-crossrec-edge-from"
first, err := fixture.GraphEdgeWrite(ctx, from, fixture.IssuePrefix+"-crossrec-edge-to-a", "depends-on")
if err != nil {
t.Fatalf("GraphEdgeWrite(a): %v", err)
}
if !first.Accepted {
t.Fatalf("GraphEdgeWrite(a) was refused (Refusal=%+v), want Accepted", first.Refusal)
}
second, err := fixture.GraphEdgeWrite(ctx, from, fixture.IssuePrefix+"-crossrec-edge-to-b", "depends-on")
if err != nil {
t.Fatalf("GraphEdgeWrite(b): %v", err)
}
if !second.Accepted {
t.Fatalf("GraphEdgeWrite(b) from the SAME endpoint %q was refused (Refusal=%+v); MaximumEndpointMultiplicity is a store invariant, so a per-record write cannot enforce it and must be Accepted here", from, second.Refusal)
}
}
// RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation pins FR-03's
// negative case: an advisory lease is observed BY CONVENTION ONLY, so
// holding one over the shared subject does not, by itself, stop the same
// per-record violation RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards
// constructs.
func RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.AcquireAdvisoryLease == nil {
t.Skip("this backend has no lease primitive to test as an insufficient guard (AcquireAdvisoryLease is nil)")
}
if fixture.GuardedWrite == nil {
t.Skip("this backend exposes no per-record guard to construct the boundary case against (GuardedWrite is nil)")
}
shared := fixture.IssuePrefix + "-crossrec-leased-alias"
crossRecordInvariantAcquireLease(t, ctx, fixture, shared, time.Minute)
first, err := fixture.GuardedWrite(ctx, fixture.IssuePrefix+"-crossrec-leased-a", nil, map[string]any{"alias": shared})
if err != nil {
t.Fatalf("GuardedWrite(a) under a held lease: %v", err)
}
second, err := fixture.GuardedWrite(ctx, fixture.IssuePrefix+"-crossrec-leased-b", nil, map[string]any{"alias": shared})
if err != nil {
t.Fatalf("GuardedWrite(b) under a held lease: %v", err)
}
if !first.Accepted || !second.Accepted {
t.Fatalf("holding an advisory lease changed a per-record GuardedWrite's own verdict (first.Accepted=%v second.Accepted=%v); the lease is observed by convention only and GuardedWrite must not consult it (FR-03)", first.Accepted, second.Accepted)
}
}
// RunLeaseAcquisitionRecordsNoHistoryEntry mirrors
// RunMetadataCASAWispSwapRecordsNoDurableHistory's delta-around-the-call
// shape (metadata_cas_contract.go, history_matching.go): acquiring an
// advisory lease is bookkeeping, not a durable state change, so it must
// record no history entry for its subject.
func RunLeaseAcquisitionRecordsNoHistoryEntry(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture) {
t.Helper()
if fixture.AcquireAdvisoryLease == nil {
t.Skip("this backend has no lease primitive to test (AcquireAdvisoryLease is nil)")
}
if fixture.CountHistoryForSubject == nil {
t.Skip("this backend cannot observe history by subject (CountHistoryForSubject is nil)")
}
subject := fixture.IssuePrefix + "-crossrec-lease-history"
before, err := fixture.CountHistoryForSubject(ctx, subject)
if err != nil {
t.Fatalf("CountHistoryForSubject(before): %v", err)
}
crossRecordInvariantAcquireLease(t, ctx, fixture, subject, time.Minute)
after, err := fixture.CountHistoryForSubject(ctx, subject)
if err != nil {
t.Fatalf("CountHistoryForSubject(after): %v", err)
}
if got := after - before; got != 0 {
t.Errorf("acquiring an advisory lease recorded %d history entries for %q, want none", got, subject)
}
}
// --- fixture helpers -------------------------------------------------------
// crossRecordInvariantAcquireLease acquires an advisory lease and registers
// its Release (when the fixture provides one) as a test cleanup, so a case
// does not have to thread a defer through its own body. No caller needs the
// handle itself — both cases only need a lease held over the subject — so
// this does not return one.
func crossRecordInvariantAcquireLease(t *testing.T, ctx context.Context, fixture CrossRecordInvariantFixture, subject string, ttl time.Duration) {
t.Helper()
lease, err := fixture.AcquireAdvisoryLease(ctx, subject, ttl)
if err != nil {
t.Fatalf("AcquireAdvisoryLease(%s): %v", subject, err)
}
if lease.Release != nil {
t.Cleanup(func() {
if err := lease.Release(ctx); err != nil {
t.Errorf("releasing the advisory lease on %q: %v", subject, err)
}
})
}
}

View file

@ -2,10 +2,12 @@ package conformance
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
storeops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
publicops "github.com/steveyegge/beads/issueops"
)
@ -60,6 +62,33 @@ type DependencyEditorFixture struct {
// the cases that need it then skip with that reason rather than pass
// quietly. It is non-nil on all three backends today.
CountHistory func(context.Context) (int, error)
// SetJournalEnabled turns on durable journaling for the workspace under
// test (storage.EventsJournalConfigurer) — the same operator switch
// JournalFixture.SetJournalEnabled wires, and off by default for the same
// reason: a workspace that never opted in records nothing in
// bd_events_journal while every other write still succeeds normally.
//
// The idempotency cases need it on because bd_events_journal has no
// deduplication of its own (issueops.RecordDepEventInTx always inserts):
// a same-type re-add or an absent removal is a no-op only if nothing
// downstream of the role recorded a change, and the journal is the one
// place that is not otherwise observable through this fixture. It is
// non-nil on all three backends.
SetJournalEnabled func(enabled bool)
// SetVersionedHistoryEnabled turns on dual-write issue-version history
// (storage.VersionedHistoryConfigurer) — off by default for the same
// reason SetJournalEnabled is.
//
// It exists for one case: the metadata-changed re-add, which can only be
// driven through AddDependency (the role's own request type carries no
// metadata). That hook writes through the backend's raw store path rather
// than the role's transaction wrapper, and on at least one backend only
// the latter issues the underlying VCS commit CountHistory observes — so
// a case reached through AddDependency cannot tell a mint happened by
// watching CountHistory the way the role-driven history cases do. It has
// to read issue_versions directly instead, which only advances when this
// switch is on. It is non-nil on all three backends.
SetVersionedHistoryEnabled func(enabled bool)
}
// RunDependencyEditorRoutesWispSourcedEdgeToTheWispPlane is the regression pin
@ -252,8 +281,18 @@ func RunDependencyEditorAddedEchoesTheRequestOrder(t *testing.T, ctx context.Con
// promises a dependency_added entry for a GENUINELY NEW edge, so a backend
// that re-emitted on the no-op would leave a history of work that did not
// happen even where the row count could not tell.
//
// bd_events_journal is the fourth, and the one none of the others catch:
// unlike the events table it has no deduplication of its own
// (issueops.RecordDepEventInTx always inserts), so a same-type re-add that
// gates on TYPE alone — never the stored metadata VALUE — journals a change
// that never happened even while the row count, the events table and the
// history delta all read as a clean no-op. This is #5898's R3 case: a
// change-free write must create no version and must not journal one either.
func RunDependencyEditorSameTypeReAddIsIdempotent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) {
t.Helper()
fixture.SetJournalEnabled(true)
t.Cleanup(func() { fixture.SetJournalEnabled(false) })
source := fixture.IssuePrefix + "-idem-source"
target := fixture.IssuePrefix + "-idem-target"
seedDependencyEditorIssue(t, ctx, fixture, source)
@ -267,6 +306,7 @@ func RunDependencyEditorSameTypeReAddIsIdempotent(t *testing.T, ctx context.Cont
t.Fatalf("AddDependencies first: %v", err)
}
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd))
assertHistoryDelta := dependencyEditorHistoryProbe(t, ctx, fixture)
result, err := fixture.Editor.AddDependencies(ctx, request)
@ -279,9 +319,218 @@ func RunDependencyEditorSameTypeReAddIsIdempotent(t *testing.T, ctx context.Cont
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1)
assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(publicops.DepBlocks), 1)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd))
assertHistoryDelta(0, "every edge of the request already existed with the requested type, so nothing was written and nothing is versioned")
}
// RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion pins the
// other half of the same-type re-add clause from
// RunDependencyEditorSameTypeReAddIsIdempotent: same TYPE is not the whole
// idempotency test, because the row also carries metadata, and a re-add that
// changes it is a real mutation of the source issue rather than a no-op that
// happens to share a type. The leaf updates the stored metadata and mints
// EXACTLY ONE version carrying the new state — the same terms as a genuinely
// new edge — because from the source issue's point of view a metadata change
// is as real as the edge appearing in the first place (#5898 leg 2).
//
// It drives the re-add through fixture.AddDependency rather than
// fixture.Editor.AddDependencies because publicops.DependencyEdge carries no
// metadata for the role API to change — the same reason
// RunDependencyEditorClosedChildAddSatisfiesAnAnyChildrenGate reaches past
// the role for a waits-for gate.
//
// bd_events_journal is asserted at TWO, not one: unlike the change-free
// re-add, this path still calls issueops.RecordDepEventInTx — dependencies.go
// calls it "an observable graph mutation" and journals the complete
// replacement edge for replay — so the second write adds its own journal
// entry even though it adds no second row to "dependencies" and no second
// dependency_added row to "events", because those two describe the STORED
// ROW and the AUDIT TRAIL, neither of which duplicates on a metadata-only
// change.
func RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) {
t.Helper()
if fixture.AddDependency == nil {
t.Skip("fixture has no AddDependency hook: metadata is not settable through publicops.DependencyEdge")
}
fixture.SetJournalEnabled(true)
t.Cleanup(func() { fixture.SetJournalEnabled(false) })
fixture.SetVersionedHistoryEnabled(true)
t.Cleanup(func() { fixture.SetVersionedHistoryEnabled(false) })
source := fixture.IssuePrefix + "-idemmeta-source"
target := fixture.IssuePrefix + "-idemmeta-target"
seedDependencyEditorIssue(t, ctx, fixture, source)
seedDependencyEditorIssue(t, ctx, fixture, target)
first := &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepBlocks, Metadata: `{"note":"v1"}`}
if err := fixture.AddDependency(ctx, first, "writer"); err != nil {
t.Fatalf("AddDependency first: %v", err)
}
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1)
assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(types.DepBlocks), 1)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd))
versionsBefore := countDependencyEditorIssueVersions(t, ctx, fixture, source)
second := &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepBlocks, Metadata: `{"note":"v2"}`}
if err := fixture.AddDependency(ctx, second, "writer"); err != nil {
t.Fatalf("re-adding the same edge with changed metadata refused: %v", err)
}
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1)
assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(types.DepBlocks), 1)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
var journalCount int
if err := fixture.QueryScalar(ctx,
"SELECT COUNT(*) FROM bd_events_journal WHERE issue_id = ? AND op = ?",
[]any{source, string(storeops.EventDepAdd)}, &journalCount); err != nil {
t.Fatalf("count bd_events_journal dep_add rows for %s: %v", source, err)
}
if journalCount != 2 {
t.Errorf("bd_events_journal dep_add rows for %s = %d, want 2: the metadata-changed re-add must journal its own replacement-edge entry", source, journalCount)
}
var storedMetadata string
if err := fixture.QueryScalar(ctx,
"SELECT metadata FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?",
[]any{source, target}, &storedMetadata); err != nil {
t.Fatalf("read stored metadata for %s -> %s: %v", source, target, err)
}
// Compared after re-encoding rather than byte-for-byte: a native JSON
// column is free to re-canonicalize what it stores (e.g. inserting the
// space after ':' Dolt's does), and that is not the thing this case is
// about. canonicalizeForContract has no numeric blind spot here because
// this fixture's metadata values never carry a bare JSON number.
storedCanon, err := canonicalizeForContract(json.RawMessage(storedMetadata))
if err != nil {
t.Fatalf("canonicalize stored metadata for %s -> %s: %v", source, target, err)
}
wantCanon, err := canonicalizeForContract(json.RawMessage(second.Metadata))
if err != nil {
t.Fatalf("canonicalize want metadata for %s -> %s: %v", source, target, err)
}
if storedCanon != wantCanon {
t.Errorf("stored metadata = %s, want %s: the re-add must persist the NEW metadata, not keep the old", storedCanon, wantCanon)
}
// Not dependencyEditorHistoryProbe/CountHistory: AddDependency seeds this
// edge out of band of the role, through the backend's raw store path, and
// on at least one backend that path never issues the version-control
// commit CountHistory counts — only the role's own transaction wrapper
// does. issue_versions is the seam both paths mint through, so it is the
// one signal that is meaningful for a write reached this way.
if delta := countDependencyEditorIssueVersions(t, ctx, fixture, source) - versionsBefore; delta != 1 {
t.Errorf("issue_versions rows for %s went %d -> %d (delta %d), want a delta of 1: the metadata genuinely changed, so the re-add is a real mutation of the source issue and must mint exactly one version (#5898 leg 2)", source, versionsBefore, versionsBefore+delta, delta)
}
}
// countDependencyEditorIssueVersions reports how many issue_versions rows
// exist for the given issue. Shared by every case here that asserts a
// version DELTA rather than an absolute count: the fixture's issues accrue
// versions from more than this one seam, so the relative change across an
// operation is the only thing a case can rely on.
func countDependencyEditorIssueVersions(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, id string) int {
t.Helper()
var count int
if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count); err != nil {
t.Fatalf("count issue_versions rows for %s: %v", id, err)
}
return count
}
// RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp pins the leg of
// the same-type re-add clause that
// RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion
// deliberately does not cover: metadata that is byte-different but
// SEMANTICALLY IDENTICAL to what is already stored. A native JSON column is
// free to re-canonicalize what it persists — Dolt's inserts a space after
// ':', sorts object keys, and narrows a bare integral float to an int — so a
// comparison written against the raw bytes the caller last sent, rather than
// a canonical form of what is actually stored, reports a change that never
// happened and mints a version for a write that changed nothing (#6650).
//
// Two sub-cases pin the two distinct ways "byte-different" can still mean
// "the same value", using the same real-world shape
// (internal/types.WaitsForMeta, which is what a waits-for edge's metadata
// actually is):
// - CompactSpelling re-adds the exact compact spelling
// json.Marshal(types.WaitsForMeta{Gate: "any-children"}) already
// produced. The caller sends identical bytes both times; only Dolt's own
// storage-side renormalization of the FIRST write can make the stored
// form disagree with them.
// - ReorderedKeys re-adds the same fields with their keys spelled in a
// different order — a caller-side difference no byte comparison
// survives, but the same JSON value all the same.
//
// Both must be a no-op by the same signals
// RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion checks
// for a real change: the stored row, the events table, the journal, and the
// issue_versions delta all have to read as "nothing happened."
func RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) {
t.Helper()
if fixture.AddDependency == nil {
t.Skip("fixture has no AddDependency hook: metadata is not settable through publicops.DependencyEdge")
}
compact, err := json.Marshal(types.WaitsForMeta{Gate: "any-children"})
if err != nil {
t.Fatalf("marshal compact WaitsForMeta: %v", err)
}
for _, sub := range []struct {
name string
tag string
first string
readd string
}{
{
name: "CompactSpelling",
tag: "idemmetasame-compact",
first: string(compact),
readd: string(compact),
},
{
name: "ReorderedKeys",
tag: "idemmetasame-reorder",
first: `{"gate":"any-children","spawner_id":"src-1"}`,
readd: `{"spawner_id":"src-1","gate":"any-children"}`,
},
} {
t.Run(sub.name, func(t *testing.T) {
fixture.SetJournalEnabled(true)
t.Cleanup(func() { fixture.SetJournalEnabled(false) })
fixture.SetVersionedHistoryEnabled(true)
t.Cleanup(func() { fixture.SetVersionedHistoryEnabled(false) })
source := fixture.IssuePrefix + "-" + sub.tag + "-source"
target := fixture.IssuePrefix + "-" + sub.tag + "-target"
seedDependencyEditorIssue(t, ctx, fixture, source)
seedDependencyEditorIssue(t, ctx, fixture, target)
first := &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepBlocks, Metadata: sub.first}
if err := fixture.AddDependency(ctx, first, "writer"); err != nil {
t.Fatalf("AddDependency first: %v", err)
}
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1)
assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(types.DepBlocks), 1)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd))
versionsBefore := countDependencyEditorIssueVersions(t, ctx, fixture, source)
second := &types.Dependency{IssueID: source, DependsOnID: target, Type: types.DepBlocks, Metadata: sub.readd}
if err := fixture.AddDependency(ctx, second, "writer"); err != nil {
t.Fatalf("re-adding the same edge with semantically identical metadata refused: %v", err)
}
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 1)
assertDependencyEdgeTypedCount(t, ctx, fixture, "dependencies", source, target, string(types.DepBlocks), 1)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyAdded, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepAdd))
if delta := countDependencyEditorIssueVersions(t, ctx, fixture, source) - versionsBefore; delta != 0 {
t.Errorf("issue_versions rows for %s went %d -> %d (delta %d), want a delta of 0: the re-add's metadata is semantically identical to what is already stored (byte differences aside), so nothing changed and nothing should be versioned (#6650)", source, versionsBefore, versionsBefore+delta, delta)
}
})
}
}
// RunDependencyEditorRepeatsWithinOneRequestCollapse pins the clause that
// answers a request naming ONE PAIR TWICE. The same-type re-add rule is stated
// for the pair rather than for the call, so the second occurrence inside a
@ -454,8 +703,17 @@ func RunDependencyEditorRefusalWritesNothing(t *testing.T, ctx context.Context,
// missing edge is Removed false with a NIL error, not ErrNotFound, because an
// agent replaying its own teardown should not have to classify an error to
// discover it already ran.
// bd_events_journal is checked alongside the events table for the same
// reason RunDependencyEditorSameTypeReAddIsIdempotent checks it: the journal
// has no deduplication of its own, so a removal that finds nothing must not
// journal a dep_remove either. This side of #5898's R3 case is expected to
// already hold — RemoveDependencyInTx only records when it actually deleted a
// row — but it is pinned here so a future regression on this leg is caught
// alongside the add-side one rather than only on the leg that is broken today.
func RunDependencyEditorRemoveIsIdempotent(t *testing.T, ctx context.Context, fixture DependencyEditorFixture) {
t.Helper()
fixture.SetJournalEnabled(true)
t.Cleanup(func() { fixture.SetJournalEnabled(false) })
source := fixture.IssuePrefix + "-rm-source"
target := fixture.IssuePrefix + "-rm-target"
seedDependencyEditorIssue(t, ctx, fixture, source)
@ -478,6 +736,7 @@ func RunDependencyEditorRemoveIsIdempotent(t *testing.T, ctx context.Context, fi
}
assertDependencyEditorOutgoingCount(t, ctx, fixture, "dependencies", source, 0)
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyRemoved, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepRemove))
removed, err = fixture.Editor.RemoveDependency(ctx, request)
if err != nil {
@ -487,6 +746,7 @@ func RunDependencyEditorRemoveIsIdempotent(t *testing.T, ctx context.Context, fi
t.Error("Removed = true, want false for an edge that was already gone")
}
assertDependencyEditorEventCount(t, ctx, fixture, "events", source, types.EventDependencyRemoved, 1)
assertDependencyEditorJournalCountIsOne(t, ctx, fixture, source, string(storeops.EventDepRemove))
}
// RunDependencyEditorAppliesParentChildBeforeBlockingEdges pins
@ -2179,6 +2439,26 @@ func assertDependencyEditorEventCount(t *testing.T, ctx context.Context, fixture
}
}
// assertDependencyEditorJournalCountIsOne asserts exactly one bd_events_journal
// row exists for one issue and op — the same shape as
// assertDependencyEditorEventCount, against the table that has no
// deduplication of its own and so is the one an unconditional journal write on
// a no-op would actually show up in. Every call site pins the count at one
// (the single genuine write); there is no idempotency case that expects zero
// or more than one, so unlike assertDependencyEditorEventCount this does not
// take a want.
func assertDependencyEditorJournalCountIsOne(t *testing.T, ctx context.Context, fixture DependencyEditorFixture, issueID, op string) {
t.Helper()
var got int
query := "SELECT COUNT(*) FROM bd_events_journal WHERE issue_id = ? AND op = ?"
if err := fixture.QueryScalar(ctx, query, []any{issueID, op}, &got); err != nil {
t.Fatalf("count bd_events_journal %s rows for %s: %v", op, issueID, err)
}
if got != 1 {
t.Errorf("bd_events_journal %s rows for %s = %d, want 1", op, issueID, got)
}
}
// assertDependencyEditorEventActor reads the actor off the one event of a
// given type for one issue. It reads the DURABLE stream only: the attribution
// clause is about who is recorded, and the plane that record lands in is

View file

@ -0,0 +1,344 @@
package conformance
import (
"context"
"testing"
)
// This file holds the contract Phase 2's dual-write history mechanism must
// satisfy: FR-1, FR-2, FR-3, FR-5 and FR-7 of be-hs42e.3 (gastownhall/beads#6135)
// directly, plus FR-6 per leg (see below). FR-4 and FR-8 are this phase's
// requirements too but are not testable through this fixture's five closures
// — see the exclusion list below for why. FR-9 is deliberately NOT this
// file's job: it is the differential test harness task 4 builds separately
// (flag-off-vs-recorded-baseline plus flag-on-perturbs-nothing-but-
// current_revision), not a property a per-mutation fixture case can express.
// This is the phase that starts populating
// issue_versions/current_revision/store_epoch behind
// storage.VersionedHistoryConfigurer while every read path still answers from
// the durable issues/wisps rows exactly as before. Nothing here asserts that a
// dual-written value is ever READ back through a query surface — that CAS
// enforcement and read-path switch is Phase 3/4 (#6136), unbuilt at this
// phase — only that the write side mints what it promises, and only when it
// promises to.
//
// WHY THIS IS A DEDICATED FIXTURE RATHER THAN AN EXTENSION OF AN EXISTING ONE.
// An earlier design iteration proposed folding these cases into the
// pre-existing RetentionFixture/CrossRecordInvariantFixture pair. That
// approach was withdrawn (be-q0w1q) after review surfaced a version-row
// identity gap those fixtures' cases would have exercised before it was
// resolved: (issue_id, revision) was the only key issue_versions had, which
// cannot express a third write racing the same revision the way a
// content-addressed or generated identity can. be-hs42e.3 design §15
// resolves the identity question with a dedicated version_id (migration
// 0068, landing after this contract exists — see the task-1 half of this
// bead), and this contract is written against §15's resolved shape, not the
// one the withdrawn approach would have extended.
//
// THE FIXTURE'S FIVE CLOSURES ARE THE OBSERVABLE SURFACE, NOT THE SCHEMA. A
// case here never reads issue_versions or store_epoch directly — that would
// make the contract a second copy of one leg's SQL rather than a promise
// every leg keeps in its own idiom (raw SQL against the dolt leg's own
// *sql.DB, an exported accessor on the embedded store, RawSQLUseCase through
// a unit of work). Mutate and MutateAsNoOp drive the same front door every
// other conformance fixture in this package drives — CreateIssue and
// UpdateIssue, or their unit-of-work equivalents — never the version table:
// emission lives at the RecordVersionInTx seam beneath all of them, so a
// closure that inserted a row directly would be asserting that this test can
// write a row, not that the engine does.
//
// WHAT THIS CONTRACT DELIBERATELY DOES NOT PIN, and the reason, so a later
// reader does not mistake the gap for an oversight:
//
// - THE EXACT BYTES OF durable_state. Design §15's R5.1 artifact is a
// verbatim marshal of the mutated issue, and its shape is pinned where it
// is produced, not here: a byte-for-byte assertion in a cross-leg
// contract would break every time a field is added to types.Issue for
// reasons that have nothing to do with dual-write correctness. What IS
// pinned (RunDualWriteAttributionIsRecordedWithTheMutation) is that a row
// exists and its attribution columns are populated the moment the
// mutation that produced it returns — the externally observable proxy
// for "atomic with the mutation" a black-box fixture can actually check.
// - store_epoch AND issue_versions.epoch (FR-6, "stamped, never bumped").
// None of this fixture's five closures can see either: CurrentRevision
// reads issues.current_revision, and VersionRowCount and
// LatestVersionAttribution read issue_versions but never its epoch
// column. Adding a sixth closure just to reach one column — one two of
// three legs would have to invent white-box access for — would make the
// shared surface bespoke to a single requirement. FR-6 is instead pinned
// per leg, where a leg already has (or can cheaply grow) the access: see
// the dolt leg's TestDualWriteStampsTheCurrentStoreEpochOnEachVersionRow.
// - PARTICIPATION-GENERATION GATING (design §16.2b). Whether an
// update-shaped mutation on a legacy (participation_generation IS NULL)
// row is correctly skipped is Phase 2 behavior this bead also owns, but
// it depends on migration 0068's participation_generation column, which
// does not exist when this contract is first written (0068 lands last in
// this bead's build order, by the mayor's explicit sequencing). It gets
// its own dedicated cases once 0068 lands, beside this file rather than
// inside it.
// - CONCURRENT WRITERS. Every case here is one writer, one issue, one
// mutation at a time — the same restriction journal_contract.go states
// for the same reason: a single-threaded case cannot exercise what only
// concurrency can break, and faking it with sleeps buys a flaky suite
// instead of a guarantee.
// - FR-4 ("attribution is metadata: never compared when deciding whether
// two versions' durable state differs, never included in any future
// digest/equality check"). This is a constraint on code that does not
// exist in Phase 2 — no digest or equality check over durable_state is
// built by this phase — so there is nothing yet for a case to run
// against. FR-4 has no dedicated case here for that reason, not because
// it was missed.
// - FR-8 (`wisps.current_revision`/`wisps.participation_generation` are
// never read or written by this phase). None of this fixture's five
// closures can express it: Mutate's front door is CreateIssue against
// the issues table, so this fixture has no wisp-routed id to check in
// the first place. FR-8 is a routing exclusion, not a property of a
// mutated issue's own version history, and belongs beside the explicit
// test design §9 item 5 already calls for (task 1's responsibility, not
// this contract's).
//
// SEEDING DISCIPLINE: EVERY CASE CREATES ITS OWN ISSUE. Unlike the journal —
// append-only and workspace-global, so every case rebaselines off the live
// head — a version history is PER ISSUE, and Mutate's front door is create,
// which cannot run twice against the same id. So every case mints its own id
// from fixture.IssuePrefix plus a marker naming the case, and no case may
// assume anything about another id's history.
type DualWriteFixture struct {
// IssuePrefix namespaces the id each case mints. Ids are global to a
// workspace, so two cases sharing one would read each other's version
// history.
IssuePrefix string
// Mutate performs one ACCEPTED mutation against a not-yet-existing id:
// the fixture's chosen front door for "a mutation this phase must
// version" is CreateIssue (or its unit-of-work equivalent), because
// create is one of the call sites RecordVersionInTx wires into and the
// one every leg can drive without first needing a row to exist.
Mutate func(ctx context.Context, id string) error
// MutateAsNoOp performs a mutation against an id Mutate already created
// that existing production code (issueops.DiscardNoopIssueUpdates)
// recognizes as a no-op before it ever reaches RecordVersionInTx — the
// fixture's chosen shape is an update that re-sets a field to the value
// Mutate already gave it. It is a DIFFERENT call than Mutate on purpose:
// FR-2 is a claim about the engine's no-op skip, and a fixture that used
// the same closure for both could not tell a real skip from Mutate
// simply never having run.
MutateAsNoOp func(ctx context.Context, id string) error
// CurrentRevision reads issues.current_revision for id.
CurrentRevision func(ctx context.Context, id string) (int64, error)
// VersionRowCount reads how many issue_versions rows exist for id.
VersionRowCount func(ctx context.Context, id string) (int, error)
// LatestVersionAttribution reads change_actor, change_agent and
// change_message off the highest-revision issue_versions row for id.
// Columns the schema allows NULL come back as "": this fixture answers
// "what did the mutation record", and a leg that recorded nothing for a
// column answers that question with an empty string, not a sentinel a
// case would have to special-case around.
LatestVersionAttribution func(ctx context.Context, id string) (actor, agent, message string, err error)
}
// RunDualWriteMintsOneVersionRowPerAcceptedMutation pins FR-1: an accepted
// mutation mints EXACTLY one issue_versions row, not zero and not more than
// one.
//
// Zero would mean the phase built the flag and never wired the seam behind
// it — every other case in this file would still read a functioning store,
// because nothing about ordinary issue mutation depends on versioning
// existing. More than one is the other silent failure this phase has to
// avoid: a seam invoked twice for one caller-visible mutation (once from the
// front door's own transaction and once from a retry or a decorator wrapping
// it a second time) would double the history of every issue in the store
// without a single ordinary read ever noticing, since nothing reads
// issue_versions yet.
func RunDualWriteMintsOneVersionRowPerAcceptedMutation(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-mints-one"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
count, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s: %v", id, err)
}
if count != 1 {
t.Errorf("version row count for %s = %d, want exactly 1: one accepted mutation mints one row, "+
"not zero (the seam never fired) and not more than one (it fired twice for a single "+
"caller-visible mutation)", id, count)
}
}
// RunDualWriteNoOpMutationMintsNoRow pins FR-2: a mutation
// issueops.DiscardNoopIssueUpdates already discards before it reaches any
// write mints NO version row.
//
// This is the inheritance the task-1 design calls for explicitly:
// RecordVersionInTx sits inside the same already-short-circuited function
// bodies as RecordEventInTx, so a no-op never reaches it, and this case is
// what would catch a future refactor that moved the call ABOVE that
// short-circuit — versioning an update that changed nothing, which would
// make current_revision (and FR-5's identity between it and the row count)
// diverge from "the number of times this issue's durable state actually
// changed" for every issue anyone re-saves without editing.
func RunDualWriteNoOpMutationMintsNoRow(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-noop-mints-none"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
before, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s before the no-op: %v", id, err)
}
if err := fixture.MutateAsNoOp(ctx, id); err != nil {
t.Fatalf("no-op mutating %s: %v", id, err)
}
after, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s after the no-op: %v", id, err)
}
if after != before {
t.Errorf("version row count for %s went from %d to %d across a no-op mutation, want unchanged: "+
"a mutation the engine already discards as a no-op must never reach RecordVersionInTx",
id, before, after)
}
}
// RunDualWriteAttributionIsRecordedWithTheMutation pins FR-3 and FR-4: the
// version row minted for an accepted mutation carries that mutation's
// attribution, visible the instant the mutation's own call returns.
//
// "Visible the instant the call returns" is the load-bearing half: this
// contract cannot see two writes land in the same database transaction, but
// it CAN see whether a caller has to do anything extra — flush, commit
// separately, poll — before the attribution it just supplied shows up beside
// the row it mutated. A dual-write seam that recorded the version
// asynchronously, or in a transaction of its own committed after the
// caller's, would still pass every other case in this file and fail this one.
func RunDualWriteAttributionIsRecordedWithTheMutation(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-attribution"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
actor, _, _, err := fixture.LatestVersionAttribution(ctx, id)
if err != nil {
t.Fatalf("reading attribution for %s immediately after the mutation that must have minted it: %v", id, err)
}
if actor == "" {
t.Errorf("change_actor for %s is empty immediately after an accepted mutation: FR-3/FR-4 require "+
"the version row to carry the mutation's attribution, and an actor is the one attribution "+
"input every leg's Mutate closure supplies", id)
}
}
// RunDualWriteCurrentRevisionMatchesTheNewVersionRow pins FR-5: after any
// accepted mutation, issues.current_revision agrees with how many version
// rows the issue actually has.
//
// This restates the bead's task-1 description — bump current_revision by a
// plain +1 on the row already carrying the mutation, in the same transaction
// as the version row it accompanies — as something a black-box fixture can
// check without seeing either write: current_revision IS a count of the
// version rows RecordVersionInTx has minted for this issue, never ahead of
// it and never behind. Divergence in either direction is a real bug this
// phase must not ship: current_revision racing ahead of the row count would
// tell Phase 3/4's future CAS check to expect a revision that was never
// durably recorded, and falling behind would let a second writer believe it
// observed the latest version when a row past it already exists.
func RunDualWriteCurrentRevisionMatchesTheNewVersionRow(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-revision-matches"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
revision, err := fixture.CurrentRevision(ctx, id)
if err != nil {
t.Fatalf("reading current_revision for %s: %v", id, err)
}
count, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s: %v", id, err)
}
if revision != int64(count) {
t.Errorf("current_revision for %s = %d but it has %d version row(s): the two must always agree — "+
"current_revision is nothing but a count of the rows RecordVersionInTx has minted for this "+
"issue", id, revision, count)
}
}
// RunDualWriteFlagOffProducesNoVersionRows pins FR-7: with
// storage.VersionedHistoryConfigurer left off, an otherwise-identical
// mutation mints no version row and leaves current_revision at its untouched
// schema default.
//
// This is the phase's core safety property, restated from the write side:
// every store this bead ships to already runs with the flag off, so a
// dual-write engine that fired regardless of the switch would start writing
// issue_versions rows nobody asked for, in every workspace, the moment this
// PR merges. The fixture this case is called against must be constructed
// with the flag OFF from the start — see each leg's flag-off constructor —
// so the case cannot pass by accident against a fixture that happens to
// share state with a flag-on one.
func RunDualWriteFlagOffProducesNoVersionRows(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-flag-off"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s with the flag off: %v", id, err)
}
count, err := fixture.VersionRowCount(ctx, id)
if err != nil {
t.Fatalf("counting version rows for %s: %v", id, err)
}
if count != 0 {
t.Errorf("version row count for %s = %d with storage.VersionedHistoryConfigurer OFF, want 0: a "+
"disabled flag must produce byte-identical writes to the pre-Phase-2 engine, and a row minted "+
"anyway means every existing workspace starts accumulating history nobody enabled", id, count)
}
revision, err := fixture.CurrentRevision(ctx, id)
if err != nil {
t.Fatalf("reading current_revision for %s: %v", id, err)
}
if revision != 1 {
t.Errorf("current_revision for %s = %d with the flag off, want 1 (the column's own schema "+
"default, untouched): a flag-off store must never execute the bump half of RecordVersionInTx "+
"either", id, revision)
}
}
// RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed strengthens
// FR-2 from the one angle RunDualWriteNoOpMutationMintsNoRow does not reach:
// that case pins that a no-op mints no NEW row; this pins that a no-op does
// not silently rewrite the row already there.
//
// A dual-write seam that mistakenly ran an UPDATE instead of an
// insert-or-skip — reusing the prior row's primary key because the no-op
// path recomputed "the current version" instead of being skipped before it
// got there — would pass RunDualWriteNoOpMutationMintsNoRow outright: the row
// count never changes when an UPDATE overwrites in place. Comparing the
// attribution byte-for-byte across the no-op is what catches that failure
// mode instead.
func RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed(t *testing.T, ctx context.Context, fixture DualWriteFixture) {
t.Helper()
id := fixture.IssuePrefix + "-noop-unperturbed"
if err := fixture.Mutate(ctx, id); err != nil {
t.Fatalf("mutating %s: %v", id, err)
}
beforeActor, beforeAgent, beforeMessage, err := fixture.LatestVersionAttribution(ctx, id)
if err != nil {
t.Fatalf("reading attribution for %s before the no-op: %v", id, err)
}
if err := fixture.MutateAsNoOp(ctx, id); err != nil {
t.Fatalf("no-op mutating %s: %v", id, err)
}
afterActor, afterAgent, afterMessage, err := fixture.LatestVersionAttribution(ctx, id)
if err != nil {
t.Fatalf("reading attribution for %s after the no-op: %v", id, err)
}
if beforeActor != afterActor || beforeAgent != afterAgent || beforeMessage != afterMessage {
t.Errorf("attribution for %s changed across a no-op mutation, (%q,%q,%q) -> (%q,%q,%q): a mutation "+
"that mints no new row must also leave the existing one exactly as the accepted mutation "+
"before it left it, not silently rewritten in place",
id, beforeActor, beforeAgent, beforeMessage, afterActor, afterAgent, afterMessage)
}
}

View file

@ -0,0 +1,599 @@
package conformance
import (
"context"
"errors"
"fmt"
"testing"
"time"
)
// This file holds the vocabulary every one of the three new versioned-history
// contract files shares (Address, ChangeAttribution, Restriction,
// RetainedWindow, the PerRecordCASWrite hook shape, and the sentinel errors),
// plus the contract for R16/R17 (gastownhall/beads#6133, be-hs42e.1 §5-§7):
// the whole-of-state expectedRevision CAS write and its typed Refusal.
//
// THE SHARED VOCABULARY LIVES HERE, NOT IN A FOURTH FILE. All three contract
// files declare `package conformance`, so Go same-package visibility already
// gives cross-file access with no import; the architecture doc names exactly
// three contract files and does not say where their shared types live. This
// file's own §4a choice is to keep them beside R16/R17 rather than split out
// a vocabulary-only file with no tests of its own — R16/R17 is the first
// contract that needs them, so a reader asking "what is an Address" starts
// here.
//
// EVERY HOOK ON EVERY FIXTURE IN ALL THREE NEW FILES IS INDEPENDENTLY
// NILABLE — unlike metadata_cas_contract.go, where MetadataCAS itself is
// required and only two hooks are optional. Phase 0 ships zero real
// implementations of any of these capabilities in any backend's fixture kit
// (architecture §12: "every new hook is nil in every backend's fixture
// kit"), so every case below nil-checks every hook it uses and SKIPS BY NAME
// when one is missing — the same idiom history_matching.go uses for
// CountHistoryMatching.
//
// THIS SUITE DEFINES INTERFACES AND TESTS ONLY. Nothing introduced by this
// phase implements real CAS, invariant, retention, or epoch enforcement. The
// positive-path body of every Run function below is a complete, realistic
// assertion of what Phase 3's real hooks must do — because this suite IS the
// spec Phase 3 implements against (NFR-03) — but none of it runs today,
// since versioned_history_wiring_test.go wires every hook nil.
//
// RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset (R16-c) IS EXPECTED
// TO FAIL the moment a real backend wires CompareAndSetVersion, unless that
// backend has independently closed the row_lock partial-coverage gap the
// architecture doc's own §10 risk table names. That is deliberate — see the
// function's own doc comment — not a bug to relax the assertion around.
//
// DEFERRALS RECORDED HERE, NOT ACTED ON IN PHASE 0 (bee-ghosttrack's PR
// #6147 round-1 review; kept as ONE note so a later phase does not have to
// reconstruct these from PR comment history):
//
// - UNRETAINED AND DISCLOSURE-GATING ARE A FUTURE AUTHORIZATION AXIS, NOT A
// SIXTH Restriction VALUE. R11's bounded-window edge (an Address old
// enough to have fallen outside a retention window, distinct from Gone)
// and disclosure-gating (a store that presents a Gone or Unretained
// Address as Unknown to a caller not authorized to learn it existed at
// all) both layer an AUTHORIZATION dimension over the five states this
// file already defines — WHO is asking, not WHAT the store knows. Adding
// either as a sixth Restriction constant would conflate those two
// dimensions; a later phase should model authorization as an orthogonal
// axis instead.
// - INVARIANT-DECLARATION DISCOVERABILITY: nothing in this suite lets a
// caller enumerate which store invariants EnforceCrossRecordInvariant
// knows about ahead of a refusal — InvariantRefusal.InvariantName is
// only ever observed reactively. Deferred to whatever phase gives
// invariants a first-class registry.
// - LEASE TTL SELF-EXPIRY: LeaseHandle carries ExpiresAt
// (cross_record_invariant_contract.go) but nothing in this suite
// exercises a lease actually expiring on its own — only explicit
// Release. Deferred until a real lease primitive exists to observe
// timing against.
// - R20-j's DURABILITY IS NOT PROVEN ACROSS A RESTART in this suite —
// RunAStoreThatRemovesStateStillAnswersGoneDurably (retention_epoch_
// contract.go) reads twice in the same process, which cannot
// distinguish real durability from an in-memory cache that merely
// outlives two calls. Deferred to the E2E tier, which can actually
// restart a backend between reads.
// - ERASURE'S GONE-RECORD TOKEN RETENTION (R5.1 machinery) is out of
// scope here: RunErasureMintsACorrectedVersionRatherThanEditingInPlace
// (retention_epoch_contract.go) checks that the original resolves
// GoneErasure and the correction resolves Live, not what token or
// tombstone content backs that GoneErasure answer. Deferred to the
// later phase that specifies R5.1's erasure-record shape.
//
// THE "_attribution" PATCH-KEY CONVENTION (expectedRevisionAttributionPatch,
// this file) IS THE CANONICAL WAY TO THREAD A ChangeAttribution THROUGH A
// PerRecordCASWrite's generic patch parameter. Phase 3's hook documentation
// should point implementers at this convention explicitly, so no backend
// invents a second one.
// Address opaquely identifies one Version. It names no physical column — per
// be-hs42e.1 §5, this is conceptual vocabulary that any future backend's hook
// translates to and from whatever it actually stores.
type Address string
// ChangeAttribution is who/what/why/when produced a Version, as observed by
// the transaction that produced it (be-hs42e.1 §5). Actor, Agent, and
// Message are independently nullable.
type ChangeAttribution struct {
Actor *string
Agent *string
Message *string
At time.Time
}
// Restriction is one of the five states a store may report for an Address
// (be-hs42e.1 §5, FR-05). Gone and Unknown are deliberately distinct values,
// never conflated: Gone means the store once held this Version and no longer
// does; Unknown means the store has no knowledge of the lineage at all
// (FR-06) — e.g. it never synced far enough back to have an opinion.
type Restriction int
const (
RestrictionLive Restriction = iota
RestrictionGoneRetention
RestrictionGoneErasure
RestrictionGoneReorganization
RestrictionUnknown
)
func (r Restriction) String() string {
switch r {
case RestrictionLive:
return "live"
case RestrictionGoneRetention:
return "gone-retention"
case RestrictionGoneErasure:
return "gone-erasure"
case RestrictionGoneReorganization:
return "gone-reorganization"
case RestrictionUnknown:
return "unknown"
default:
return fmt.Sprintf("Restriction(%d)", int(r))
}
}
// RetainedWindow is the surviving range a store reports once some Addresses
// within a lineage have gone (be-hs42e.1 §5, R20-c/h).
type RetainedWindow struct {
LowerBound Address
UpperBound Address
}
// PerRecordCASWrite is the shape every per-record whole-of-state CAS write
// takes. ExpectedRevisionFixture.CompareAndSetVersion and
// CrossRecordInvariantFixture.GuardedWrite share this EXACT type on purpose:
// R16.1-a's boundary claim is literally that the second is the first, called
// twice — sharing the type makes that claim structural, not just asserted.
type PerRecordCASWrite func(ctx context.Context, id string, expected *Address, patch map[string]any) (ExpectedRevisionResult, error)
// ExpectedRevisionResult is the outcome of a PerRecordCASWrite call. Accepted
// and Refusal are mutually exclusive: read Refusal only when Accepted is
// false, read NewVersion only when it is true.
type ExpectedRevisionResult struct {
Accepted bool
NewVersion Address
Refusal *Refusal
}
// Refusal is R17's typed, machine-readable outcome for a write that named a
// version no longer current — never a generic error, never indistinguishable
// from an accepted write (R17-c/d1).
//
// THE FIXTURE KIT IS THE TRANSLATION BOUNDARY, NOT A SHAPE MANDATE ON REAL
// BACKENDS: R17 itself permits either of two shipped refusal shapes — a
// (result, nil-error) pair carrying a populated Refusal, or a typed native
// error a backend already returns for this case. ExpectedRevisionFixture's
// CompareAndSetVersion hook normalizes whichever shape a real backend ships
// to this ONE Refusal-populated-result shape for the suite to assert
// against uniformly. Nothing here should be read as banning a native
// typed-error refusal shape at the backend level — only as saying the
// fixture adapter that wires a backend into this suite must translate it
// into this shape before handing it back.
type Refusal struct {
// RefusingVersion is the Address that was actually current when the
// write was evaluated (R17-a).
RefusingVersion Address
// Attribution is RefusingVersion's ChangeAttribution, as observed by the
// refusing transaction (R17-b).
Attribution ChangeAttribution
}
// ErrRevisionNotFound means the write named an id with no current version at
// all — distinct from a Refusal, which requires a current version to refuse
// against (R17-d2).
var ErrRevisionNotFound = errors.New("expected-revision: id has no current version")
// ErrRevisionValidation means the write itself was malformed, independent of
// whether its expectation held (R17-d3).
var ErrRevisionValidation = errors.New("expected-revision: request is invalid")
// ExpectedRevisionFixture supplies the whole-of-state CAS capability under
// test (R16, R17): a write that names the Version it expects to be current,
// accepted only while that expectation holds, refused with a typed Refusal
// otherwise.
type ExpectedRevisionFixture struct {
IssuePrefix string
// CompareAndSetVersion performs a whole-of-state CAS write: it is
// accepted only while expected (nil meaning "no version named", i.e. an
// unconditional write, R16-b) names the currently-current Address. A nil
// hook means this backend does not yet implement expectedRevision CAS,
// and every case in this file SKIPS with that reason.
CompareAndSetVersion PerRecordCASWrite
// CurrentVersion reports the Address currently current for id. A nil
// hook means this backend cannot independently confirm the current
// Address, and cases that need one skip with that reason.
CurrentVersion func(ctx context.Context, id string) (Address, error)
// MutateOutsideExpectedRevision writes to id through a path R16-c
// specifically targets: one NOT gated by the whole-of-state precondition
// (the architecture doc names row_lock's documented partial-coverage gap
// as the concrete probe — see §7 risk, §10 risk table). A nil hook means
// this backend exposes no such out-of-band path, and the one case that
// needs it skips with that reason.
MutateOutsideExpectedRevision func(ctx context.Context, id string, field, value string) error
}
// RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion pins R16's
// baseline: a write naming the Address that is actually current must be
// accepted.
func RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
if fixture.CurrentVersion == nil {
t.Skip("this backend cannot independently confirm the current Address (CurrentVersion is nil)")
}
id, seeded := expectedRevisionSeed(t, ctx, fixture, "current", map[string]any{"phase": "start"})
current, err := fixture.CurrentVersion(ctx, id)
if err != nil {
t.Fatalf("CurrentVersion(%s): %v", id, err)
}
if current != seeded.NewVersion {
t.Fatalf("CurrentVersion(%s) = %s, want the seed's NewVersion %s", id, current, seeded.NewVersion)
}
result, err := fixture.CompareAndSetVersion(ctx, id, &current, map[string]any{"phase": "advanced"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s, expected=current): %v", id, err)
}
if !result.Accepted {
t.Fatalf("CompareAndSetVersion naming the true current Address was refused (Refusal=%+v), want Accepted (R16: a write naming the current Version must be accepted)", result.Refusal)
}
}
// RunExpectedRevisionAcceptsAWriteNamingNoVersion pins R16-b's paraphrase: a
// nil expectation means an unconditional write, not "the key must be
// absent" — the unconditional path must still exist over a record that
// already has a current Version.
func RunExpectedRevisionAcceptsAWriteNamingNoVersion(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
id, _ := expectedRevisionSeed(t, ctx, fixture, "unconditional", map[string]any{"phase": "start"})
result, err := fixture.CompareAndSetVersion(ctx, id, nil, map[string]any{"phase": "overwritten"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s, expected=nil) over an existing record: %v", id, err)
}
if !result.Accepted {
t.Fatal("CompareAndSetVersion(expected=nil) over an existing record was refused, want Accepted (R16-b: nil means an unconditional write, not \"must be absent\")")
}
}
// RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset pins R16's
// whole-of-state promise against the concrete gap the architecture doc names
// (§7 risk, §10 risk table): row_lock's documented partial-coverage leaves
// some fields writable without reminting the Version those fields belong to.
// A write through MutateOutsideExpectedRevision must still count as a change
// against the expectation — otherwise a caller's CAS can silently observe a
// stale precondition as current.
//
// THIS CASE IS EXPECTED TO FAIL the moment a real backend wires
// CompareAndSetVersion, UNLESS that backend has independently closed the
// row_lock gap first (architecture §10 risk table: "this suite existing and
// failing loudly against that gap IS THE POINT"). It is not a bug in this
// test if it starts failing against a real hook — it is the suite doing its
// job. Do not weaken this assertion to make a real backend pass; close the
// gap instead.
func RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
if fixture.MutateOutsideExpectedRevision == nil {
t.Skip("this backend exposes no out-of-band mutation path to probe the whole-of-state boundary with (MutateOutsideExpectedRevision is nil)")
}
id, seeded := expectedRevisionSeed(t, ctx, fixture, "outofband", map[string]any{"phase": "start"})
staleExpected := seeded.NewVersion
if err := fixture.MutateOutsideExpectedRevision(ctx, id, "side_channel", "changed"); err != nil {
t.Fatalf("MutateOutsideExpectedRevision(%s): %v", id, err)
}
result, err := fixture.CompareAndSetVersion(ctx, id, &staleExpected, map[string]any{"phase": "advanced"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s, expected=pre-mutation version): %v", id, err)
}
if result.Accepted {
t.Fatal("CompareAndSetVersion naming the pre-mutation Address was accepted after an out-of-band field write; " +
"R16's whole-of-state precondition must cover fields outside any single watched subset")
}
}
// RunRefusalReportsTheRefusingVersionAddress pins R17-a: a Refusal names the
// Address that was actually current when the write was evaluated, read here
// independently via CurrentVersion rather than trusted from the caller's own
// stale value.
func RunRefusalReportsTheRefusingVersionAddress(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
if fixture.CurrentVersion == nil {
t.Skip("this backend cannot independently confirm the current Address (CurrentVersion is nil)")
}
id, stale := expectedRevisionSeedStale(t, ctx, fixture, "refaddr")
result, err := fixture.CompareAndSetVersion(ctx, id, &stale, map[string]any{"phase": "clobber"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s, stale expected): %v", id, err)
}
if result.Accepted || result.Refusal == nil {
t.Fatalf("CompareAndSetVersion over a stale expectation = %+v, want a Refusal", result)
}
real, err := fixture.CurrentVersion(ctx, id)
if err != nil {
t.Fatalf("CurrentVersion(%s): %v", id, err)
}
if result.Refusal.RefusingVersion != real {
t.Errorf("Refusal.RefusingVersion = %s, want the real current Address %s (R17-a)", result.Refusal.RefusingVersion, real)
}
}
// RunRefusalReportsTheRefusingVersionsChangeAttribution pins R17-b: a
// Refusal carries the ChangeAttribution the refusing transaction observed
// for the version that beat the caller.
//
// §4a: PerRecordCASWrite's patch is a generic map[string]any with no
// dedicated attribution field, so this case threads a ChangeAttribution
// through the documented patch["_attribution"] convention
// (expectedRevisionAttributionPatch) — this file's own choice, since the
// architecture doc does not pin how a caller supplies attribution on a
// per-record write, only that the backend must observe and later report it.
func RunRefusalReportsTheRefusingVersionsChangeAttribution(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
actor := "cas-winner"
wantAttribution := ChangeAttribution{Actor: &actor, At: time.Now().UTC()}
id, seeded := expectedRevisionSeed(t, ctx, fixture, "refattr", map[string]any{"phase": "start"})
staleAddr := seeded.NewVersion
advanced, err := fixture.CompareAndSetVersion(ctx, id, &staleAddr,
expectedRevisionAttributionPatch(map[string]any{"phase": "moved-on"}, wantAttribution))
if err != nil {
t.Fatalf("advancing %s with a known attribution: %v", id, err)
}
if !advanced.Accepted {
t.Fatalf("advancing %s with a known attribution was refused", id)
}
result, err := fixture.CompareAndSetVersion(ctx, id, &staleAddr, map[string]any{"phase": "clobber"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s, stale expected): %v", id, err)
}
if result.Accepted || result.Refusal == nil {
t.Fatalf("CompareAndSetVersion over a stale expectation = %+v, want a Refusal", result)
}
if !sameAttribution(result.Refusal.Attribution, wantAttribution) {
t.Errorf("Refusal.Attribution = %+v, want %+v (R17-b: the attribution the refusing transaction observed)", result.Refusal.Attribution, wantAttribution)
}
}
// RunRefusalIsATypedOutcomeNotAGenericError pins R17-c/d1: a stale
// expectation comes back as a populated Refusal with a nil error, never as a
// generic Go error.
func RunRefusalIsATypedOutcomeNotAGenericError(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
id, stale := expectedRevisionSeedStale(t, ctx, fixture, "typedoutcome")
result, err := fixture.CompareAndSetVersion(ctx, id, &stale, map[string]any{"phase": "clobber"})
if err != nil {
t.Fatalf("a stale expectation returned error = %v, want nil: R17 reports a refusal, not an error (R17-c)", err)
}
if result.Accepted {
t.Fatal("a stale expectation was accepted")
}
if result.Refusal == nil {
t.Fatal("Refusal = nil on a non-accepted result, want a populated Refusal (R17-d1)")
}
}
// RunRefusalIsDistinguishableFromAnAcceptedWrite runs an accepted and a
// refused case side by side and pins that Accepted is the only signal a
// caller needs: Refusal and NewVersion are never both populated, and never
// both empty.
func RunRefusalIsDistinguishableFromAnAcceptedWrite(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
for _, test := range []struct {
name string
prepare func(t *testing.T) (string, Address)
}{
{"accepted", func(t *testing.T) (string, Address) {
id, seeded := expectedRevisionSeed(t, ctx, fixture, "distinguish-accept", map[string]any{"phase": "start"})
return id, seeded.NewVersion
}},
{"refused", func(t *testing.T) (string, Address) {
return expectedRevisionSeedStale(t, ctx, fixture, "distinguish-refuse")
}},
} {
t.Run(test.name, func(t *testing.T) {
id, expected := test.prepare(t)
result, err := fixture.CompareAndSetVersion(ctx, id, &expected, map[string]any{"phase": "attempt"})
if err != nil {
t.Fatalf("CompareAndSetVersion(%s): %v", id, err)
}
if result.Accepted && result.Refusal != nil {
t.Fatalf("result = %+v, want Refusal populated only when Accepted is false", result)
}
if !result.Accepted && result.Refusal == nil {
t.Fatalf("result = %+v, want Refusal populated when Accepted is false", result)
}
if result.Accepted && result.NewVersion == "" {
t.Error("Accepted = true but NewVersion is empty")
}
})
}
}
// RunRefusalIsDistinguishableFromNotFound pins R17-d2: an id with no current
// version at all is ErrRevisionNotFound, never a Refusal — a Refusal
// requires a current version to refuse against.
func RunRefusalIsDistinguishableFromNotFound(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
ghost := Address("ghost-version")
id := fixture.IssuePrefix + "-exprev-neverseeded"
result, err := fixture.CompareAndSetVersion(ctx, id, &ghost, map[string]any{"phase": "attempt"})
if !errors.Is(err, ErrRevisionNotFound) {
t.Fatalf("CompareAndSetVersion on a never-seeded id error = %v, want ErrRevisionNotFound (R17-d2)", err)
}
if result.Accepted || result.Refusal != nil {
t.Errorf("result = %+v, want neither Accepted nor a Refusal for a not-found id", result)
}
}
// RunRefusalIsDistinguishableFromValidationFailure pins R17-d3: a malformed
// request is ErrRevisionValidation, independent of whether its expectation
// would have held.
func RunRefusalIsDistinguishableFromValidationFailure(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
result, err := fixture.CompareAndSetVersion(ctx, "", nil, map[string]any{"phase": "attempt"})
if !errors.Is(err, ErrRevisionValidation) {
t.Fatalf("CompareAndSetVersion with an empty id error = %v, want ErrRevisionValidation (R17-d3)", err)
}
if result.Accepted || result.Refusal != nil {
t.Errorf("result = %+v, want neither Accepted nor a Refusal for a malformed request", result)
}
}
// RunRefusalNeverSilentlyPicksAWinner pins the race shape underneath R17:
// two writes competing over the same stale expectation must produce exactly
// one Accepted and one real Refusal — never both accepted, never a merged or
// silently overwritten result — and the Address left current afterward must
// be the winner's, read independently.
func RunRefusalNeverSilentlyPicksAWinner(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture) {
t.Helper()
if fixture.CompareAndSetVersion == nil {
t.Skip("this backend does not implement expectedRevision CAS (CompareAndSetVersion is nil)")
}
if fixture.CurrentVersion == nil {
t.Skip("this backend cannot independently confirm the current Address (CurrentVersion is nil)")
}
id, seeded := expectedRevisionSeed(t, ctx, fixture, "competing", map[string]any{"phase": "start"})
shared := seeded.NewVersion
first, err := fixture.CompareAndSetVersion(ctx, id, &shared, map[string]any{"phase": "writer-a"})
if err != nil {
t.Fatalf("writer A: CompareAndSetVersion(%s): %v", id, err)
}
second, err := fixture.CompareAndSetVersion(ctx, id, &shared, map[string]any{"phase": "writer-b"})
if err != nil {
t.Fatalf("writer B: CompareAndSetVersion(%s): %v", id, err)
}
if first.Accepted == second.Accepted {
t.Fatalf("two competing writes against the same expectation both reported Accepted=%v, want exactly one to win", first.Accepted)
}
winner, loser := first, second
if second.Accepted {
winner, loser = second, first
}
if loser.Refusal == nil {
t.Fatal("the losing write carries no Refusal")
}
real, err := fixture.CurrentVersion(ctx, id)
if err != nil {
t.Fatalf("CurrentVersion(%s): %v", id, err)
}
if real != winner.NewVersion {
t.Errorf("CurrentVersion(%s) = %s after the race, want the winner's NewVersion %s: a third value means the race was decided somewhere other than the two calls made here", id, real, winner.NewVersion)
}
}
// --- fixture helpers -------------------------------------------------------
// expectedRevisionSeed performs an unconditional (expected=nil) write to
// mint id's first Version, and fatals unless the fixture accepts it — every
// case in this file needs a live record to test a whole-of-state CAS
// against, and CompareAndSetVersion(expected=nil) is the only write path
// this fixture exposes to make one.
func expectedRevisionSeed(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture, tag string, patch map[string]any) (string, ExpectedRevisionResult) {
t.Helper()
id := fixture.IssuePrefix + "-exprev-" + tag
if patch == nil {
patch = map[string]any{}
}
result, err := fixture.CompareAndSetVersion(ctx, id, nil, patch)
if err != nil {
t.Fatalf("seeding %s: CompareAndSetVersion(expected=nil) error = %v", id, err)
}
if !result.Accepted {
t.Fatalf("seeding %s: CompareAndSetVersion(expected=nil) Accepted = false, want true (R16-b: an unconditional write to a fresh id must be accepted)", id)
}
return id, result
}
// expectedRevisionSeedStale seeds id, advances it once more, and returns the
// Address from BEFORE that second write — a caller naming this Address as
// Expected has a stale expectation, because the second write has since
// moved the current Version on.
func expectedRevisionSeedStale(t *testing.T, ctx context.Context, fixture ExpectedRevisionFixture, tag string) (string, Address) {
t.Helper()
id, seeded := expectedRevisionSeed(t, ctx, fixture, tag, map[string]any{"phase": "start"})
staleAddr := seeded.NewVersion
advanced, err := fixture.CompareAndSetVersion(ctx, id, &staleAddr, map[string]any{"phase": "moved-on"})
if err != nil {
t.Fatalf("advancing %s past the address a later case will treat as stale: %v", id, err)
}
if !advanced.Accepted {
t.Fatalf("advancing %s past the address a later case will treat as stale was refused", id)
}
return id, staleAddr
}
// expectedRevisionAttributionPatch adds attribution to patch under the
// "_attribution" key — the convention this file uses to thread a
// ChangeAttribution through PerRecordCASWrite's generic patch parameter. See
// RunRefusalReportsTheRefusingVersionsChangeAttribution's doc comment for
// why this convention exists.
func expectedRevisionAttributionPatch(patch map[string]any, attribution ChangeAttribution) map[string]any {
if patch == nil {
patch = map[string]any{}
}
patch["_attribution"] = attribution
return patch
}
// sameAttribution compares two ChangeAttribution values by content. It does
// not use reflect.DeepEqual: comparing time.Time by its internal
// representation is fragile (monotonic readings can differ for an otherwise
// equal instant), so At is compared with time.Time.Equal and the nullable
// string fields are compared by dereferenced value.
func sameAttribution(a, b ChangeAttribution) bool {
return samePtrString(a.Actor, b.Actor) &&
samePtrString(a.Agent, b.Agent) &&
samePtrString(a.Message, b.Message) &&
a.At.Equal(b.At)
}
func samePtrString(a, b *string) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}

View file

@ -0,0 +1,986 @@
package conformance
import (
"context"
"errors"
"fmt"
"testing"
"time"
)
// This file holds the contract for R20 (gastownhall/beads#6133, be-hs42e.1
// §5-§9): what a store reports about an Address once retention, erasure, or
// reorganization has stopped it resolving to live state (R20-a..R20-l), and
// the store-epoch generation counter that selectively voids addresses minted
// under an earlier one (R20-m/n).
//
// RESTRICTION AND RETAINEDWINDOW ARE DECLARED IN expected_revision_contract.go
// — see that file's package-level note on where this suite's shared
// vocabulary lives and why.
//
// GONE AND UNKNOWN ARE NEVER CONFLATED (FR-05, FR-06): Gone means the store
// once held this Version and no longer does; Unknown means the store has no
// lineage knowledge of the Address at all. Every RetentionAnswer names its
// PRODUCING STORE (R20-i) so a case can catch a backend that silently
// answers for the wrong store — this matters because R20 is explicitly a
// per-store promise, not a global one: a Reorganization can leave one store
// still serving an Address that another has moved past.
//
// THIS FILE ORIGINALLY MADE THREE §4a CHOICES THE ARCHITECTURE DOC DOES NOT
// PIN. Two have since DIED — retired by fixes made within this same PR,
// before merge, in response to review. Kept here, marked DIED, so a reader
// tracing why RetentionAnswer/RetentionFixture look the way they do does not
// have to reconstruct the history from git log or PR comments:
//
// 1. Remove/Commit's refusal under an active Hold is a typed error,
// ErrRetentionHeld, rather than a non-accepted-shaped RetentionAnswer —
// the doc names the promise ("must refuse ... unless forced", R20-h) but
// not its shape. An error was chosen because Commit's success path
// already returns a RetentionAnswer describing a Version that is now
// GONE; reusing that same shape for a refusal would make "the hold
// worked" and "the removal happened" look like the same kind of value.
// (R17's Refusal reasons about the same tradeoff the other way, because
// R17 already had a typed non-error outcome shape to reuse — Remove has
// no such sibling shape to reuse here.) STILL STANDS.
// 2. DIED. ForceRemove's attribution used to be asserted only for shape,
// not content, because RetentionAnswer carried no attribution field.
// RetentionAnswer.Attribution now carries it, and
// RunForcingAHeldRemovalRecordsWhoWhenWhy asserts real content — see
// that function's own doc comment.
// 3. DIED. An address that no operation had touched used to resolve
// RestrictionLive BY DEFAULT, purely by naming convention — a fabricated
// Address, from the retired retentionAddress helper, that no store had
// ever actually minted. Every case that needs a real, live Address now
// mints one for real via RetentionFixture.Mint (see retentionMint).
// RestrictionUnknown for a foreign store (FR-06) is UNCHANGED by this:
// RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone and
// RunGoneIsDistinguishableFromUnknown still test the Unknown case via a
// second, foreign storeID that genuinely never saw the Address — not via
// an untouched-but-fabricated address on the primary one, which is the
// part that died. retentionAddress itself survives as the one helper
// RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone still uses,
// precisely because Unknown requires an Address no store ever minted.
//
// EVERY HOOK ON BOTH FIXTURES BELOW IS INDEPENDENTLY NILABLE — see the
// package-level note in expected_revision_contract.go. Every case
// nil-checks every hook it uses and SKIPS BY NAME when one is missing.
// RetentionAnswer is what a store reports when asked about an Address.
type RetentionAnswer struct {
Restriction Restriction
// RetainedWindow is populated once some Addresses within the lineage
// have gone, naming the surviving range (R20-c) — AND, independently,
// whenever a Hold is protecting an Address from removal, naming that
// Address within the range it protects (R20-h). Nil means neither
// applies (e.g. Restriction is Live with no Hold in effect, or
// Unknown).
RetainedWindow *RetainedWindow
// ProducingStore names the store that produced this answer (R20-i).
ProducingStore string
// Attribution records who, when, and why produced this answer, for the
// operations that force their way past an ordinary refusal — currently
// just ForceRemove (R20-h2). Nil means this answer did not come from an
// attributed forcing operation (e.g. an ordinary Remove/Commit, or a
// Live/Unknown answer never touched by one).
Attribution *ChangeAttribution
// Epoch names the store-epoch generation this answer was evaluated
// under, so a caller can tell WHICH epoch a GoneReorganization answer
// belongs to, not just that reorganization is why the Address is gone
// (R20-n). Nil means this answer did not involve epoch reasoning (e.g.
// an ordinary Remove/Commit under R20-a..R20-l, evaluated by a store
// with no epoch concept at all).
Epoch *int
}
// RemovalReason is why an Address was removed: R20 requires the three
// reasons stay pairwise distinguishable in the Restriction they produce.
type RemovalReason int
const (
RemovalReasonRetention RemovalReason = iota
RemovalReasonErasure
RemovalReasonReorganization
)
func (r RemovalReason) String() string {
switch r {
case RemovalReasonRetention:
return "retention"
case RemovalReasonErasure:
return "erasure"
case RemovalReasonReorganization:
return "reorganization"
default:
return fmt.Sprintf("RemovalReason(%d)", int(r))
}
}
// RemovalPreview is Remove's enumerate-before-you-change half (R20-g): the
// Addresses about to be affected are reported before Commit makes the
// change real.
type RemovalPreview struct {
AffectedAddresses []Address
Commit func(ctx context.Context) (RetentionAnswer, error)
}
// ErrRetentionHeld means a RemovalPreview's Commit was refused because an
// active Hold covers the Address (R20-h). See this file's package doc
// comment, §4a choice 1, for why this is a typed error rather than a
// non-accepted-shaped RetentionAnswer.
var ErrRetentionHeld = errors.New("retention: address is held")
// RetentionResolve answers what a store currently reports for address. It is
// shared verbatim between RetentionFixture and EpochFixture: an epoch bump's
// effect on an Address (R20-n) is observed through the exact same read path
// as an ordinary removal's effect (R20-a..R20-l).
type RetentionResolve func(ctx context.Context, storeID string, address Address) (RetentionAnswer, error)
// RetentionFixture supplies the capabilities under test for R20's removal,
// hold, forced-removal, and erasure semantics.
type RetentionFixture struct {
IssuePrefix string
// Resolve reports storeID's current answer for address. A nil hook
// means this backend does not yet report retention state, and cases
// that need one skip with that reason.
Resolve RetentionResolve
// Remove reports the Addresses a removal is about to affect
// (RemovalPreview.AffectedAddresses) before Commit makes the change
// real (R20-g). A nil hook means this backend has no removal primitive,
// and cases that need one skip with that reason.
Remove func(ctx context.Context, storeID string, address Address, reason RemovalReason) (RemovalPreview, error)
// Hold prevents Remove/Commit from taking effect against address until
// released (R20-h). A nil hook means this backend has no hold
// primitive, and cases that need one skip with that reason.
Hold func(ctx context.Context, storeID string, address Address) error
// ForceRemove removes address despite an active Hold, recording who,
// when, and why in the resulting Gone record (R20-h2). A nil hook means
// this backend has no forced-removal primitive, and the cases that need
// one skip with that reason.
ForceRemove func(ctx context.Context, storeID string, address Address, attribution ChangeAttribution, reason string) (RetentionAnswer, error)
// Erase mints a corrected replacement Version for address rather than
// editing it in place (R20-l), returning the corrected Address. A nil
// hook means this backend has no erasure primitive, and the case that
// needs it skips with that reason.
Erase func(ctx context.Context, storeID string, address Address, correctedState string, attribution ChangeAttribution) (Address, error)
// Mint mints a fresh Version for id under storeID, returning its
// Address — analogous to EpochFixture.MintUnderEpoch, without an epoch
// to peg it to. A nil hook means this backend has no way to mint a
// real, resolvable Address to test retention against, and cases that
// need one skip with that reason. Replaces the retired convention that
// a fabricated, never-minted Address defaults to RestrictionLive (see
// this file's package doc comment, formerly §4a choice 3).
Mint func(ctx context.Context, storeID, id string) (Address, error)
}
// RunRemovalLeavesTheAddressAbleToAnswer pins R20-a/b: after a committed
// removal, the Address can still be resolved — it must answer, just not
// live.
func RunRemovalLeavesTheAddressAbleToAnswer(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "answerable")
address := retentionMint(t, ctx, fixture, store, "answerable")
preview, err := fixture.Remove(ctx, store, address, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s, %s): %v", store, address, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit removing %s: %v", address, err)
}
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s, %s) after removal: %v", store, address, err)
}
if answer.Restriction == RestrictionLive {
t.Fatalf("Resolve(%s) after Remove+Commit reports RestrictionLive, want a non-live Restriction: removal must leave the address able to answer, just not live", address)
}
}
// RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly pins R20-d:
// the three RemovalReasons produce pairwise-distinct Restrictions, so a
// caller can tell which kind of removal it is looking at from the answer
// alone.
func RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "reasons")
cases := []struct {
reason RemovalReason
want Restriction
}{
{RemovalReasonRetention, RestrictionGoneRetention},
{RemovalReasonErasure, RestrictionGoneErasure},
{RemovalReasonReorganization, RestrictionGoneReorganization},
}
seen := map[Restriction]bool{}
for _, c := range cases {
address := retentionMint(t, ctx, fixture, store, "reason-"+c.reason.String())
preview, err := fixture.Remove(ctx, store, address, c.reason)
if err != nil {
t.Fatalf("Remove(%s, reason=%s): %v", address, c.reason, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s, reason=%s): %v", address, c.reason, err)
}
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s) after Remove(reason=%s): %v", address, c.reason, err)
}
if answer.Restriction != c.want {
t.Errorf("Remove(reason=%s) then Resolve = %s, want %s", c.reason, answer.Restriction, c.want)
}
if seen[answer.Restriction] {
t.Errorf("Restriction %s was already reported for a different RemovalReason; the three reasons must map to pairwise-distinct Restrictions", answer.Restriction)
}
seen[answer.Restriction] = true
}
}
// RunRemovalReportsTheSurvivingRetainedWindow pins R20-c: a removal's answer
// carries a populated RetainedWindow naming the surviving range.
func RunRemovalReportsTheSurvivingRetainedWindow(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "window")
address := retentionMint(t, ctx, fixture, store, "window")
preview, err := fixture.Remove(ctx, store, address, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", address, err)
}
answer, err := preview.Commit(ctx)
if err != nil {
t.Fatalf("Commit(%s): %v", address, err)
}
if answer.RetainedWindow == nil {
t.Fatal("RetainedWindow = nil after a removal, want a populated window (R20-c)")
}
if answer.RetainedWindow.LowerBound == "" || answer.RetainedWindow.UpperBound == "" {
t.Errorf("RetainedWindow = %+v, want both bounds non-empty", answer.RetainedWindow)
}
}
// RunRemovalNeverReassignsASurvivingAddress pins R20-f: removing one Address
// must never alter or reassign a different, surviving Address's own answer.
func RunRemovalNeverReassignsASurvivingAddress(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "survivor")
removed := retentionMint(t, ctx, fixture, store, "survivor-removed")
survivor := retentionMint(t, ctx, fixture, store, "survivor-kept")
before, err := fixture.Resolve(ctx, store, survivor)
if err != nil {
t.Fatalf("Resolve(survivor) before removing its neighbor: %v", err)
}
preview, err := fixture.Remove(ctx, store, removed, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", removed, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s): %v", removed, err)
}
after, err := fixture.Resolve(ctx, store, survivor)
if err != nil {
t.Fatalf("Resolve(survivor) after removing its neighbor: %v", err)
}
if !sameRetentionAnswer(before, after) {
t.Errorf("removing a neighbor changed the survivor's own answer from %+v to %+v; removing one Address must never reassign or alter another", before, after)
}
}
// RunGoneIsDistinguishableFromUnknown pins FR-05's core claim: the SAME
// Address, asked of the store that removed it versus a store that never
// held it, must not resolve identically — Gone (once held, now removed) and
// Unknown (no lineage knowledge at all) are never conflated.
func RunGoneIsDistinguishableFromUnknown(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "gonevunknown")
strangerStore := retentionStore(fixture, "gonevunknown-stranger")
gone := retentionMint(t, ctx, fixture, store, "gonevunknown-gone")
preview, err := fixture.Remove(ctx, store, gone, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", gone, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s): %v", gone, err)
}
goneAnswer, err := fixture.Resolve(ctx, store, gone)
if err != nil {
t.Fatalf("Resolve(gone, its own store): %v", err)
}
unknownAnswer, err := fixture.Resolve(ctx, strangerStore, gone)
if err != nil {
t.Fatalf("Resolve(gone's address, a store that never held it): %v", err)
}
if goneAnswer.Restriction == RestrictionLive || unknownAnswer.Restriction == RestrictionLive {
t.Fatalf("Live leaked into a Gone/Unknown comparison: gone=%s unknown=%s", goneAnswer.Restriction, unknownAnswer.Restriction)
}
if goneAnswer.Restriction == unknownAnswer.Restriction {
t.Errorf("the SAME Address resolved identically (%s) whether asked of the store that removed it or a store that never held it; FR-05 requires Gone and Unknown stay distinct", goneAnswer.Restriction)
}
}
// RunAnAddressNeverResolvesToADifferentState guards against a mixed-up
// lookup key: two distinct Addresses on the same store, deliberately left
// in different Restrictions, must never have their answers cross-
// contaminate.
func RunAnAddressNeverResolvesToADifferentState(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "nomixup")
removedAddr := retentionMint(t, ctx, fixture, store, "nomixup-removed")
liveAddr := retentionMint(t, ctx, fixture, store, "nomixup-live")
preview, err := fixture.Remove(ctx, store, removedAddr, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", removedAddr, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s): %v", removedAddr, err)
}
removedAnswer, err := fixture.Resolve(ctx, store, removedAddr)
if err != nil {
t.Fatalf("Resolve(removed): %v", err)
}
liveAnswer, err := fixture.Resolve(ctx, store, liveAddr)
if err != nil {
t.Fatalf("Resolve(live): %v", err)
}
if liveAnswer.Restriction != RestrictionLive {
t.Fatalf("Resolve(an address nothing ever removed) = %s, want RestrictionLive", liveAnswer.Restriction)
}
if removedAnswer.Restriction == RestrictionLive {
t.Fatal("Resolve(a removed address) = RestrictionLive, want a Gone restriction")
}
if sameRetentionAnswer(removedAnswer, liveAnswer) {
t.Errorf("Resolve(%s) and Resolve(%s) returned identical answers %+v; a mixed-up lookup key would look exactly like this", removedAddr, liveAddr, removedAnswer)
}
}
// RunADestructiveOperationEnumeratesAffectedAddressesFirst pins R20-g:
// Remove reports the Addresses it is about to affect BEFORE anything
// changes. Checked by confirming that obtaining the preview alone — without
// calling Commit — leaves the address's own answer untouched, regardless of
// what that answer is.
func RunADestructiveOperationEnumeratesAffectedAddressesFirst(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "enumeratefirst")
address := retentionMint(t, ctx, fixture, store, "enumeratefirst")
before, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve before Remove: %v", err)
}
preview, err := fixture.Remove(ctx, store, address, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", address, err)
}
if len(preview.AffectedAddresses) == 0 {
t.Fatal("RemovalPreview.AffectedAddresses is empty, want the addresses this removal is about to affect (R20-g)")
}
// Commit is deliberately NOT called yet.
after, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve after Remove but before Commit: %v", err)
}
if !sameRetentionAnswer(before, after) {
t.Errorf("Resolve changed from %+v to %+v after Remove but before Commit; enumeration must precede the change, not cause it", before, after)
}
}
// RunAHoldPreventsRemovalAndReportsInRetainedBounds pins R20-h: an active
// Hold makes Remove/Commit refuse, AND the held Address must show up
// positively in the reported RetainedWindow bounds — not merely be inferred
// from the absence of a Gone restriction.
//
// §4a choice 1 (see this file's package doc comment): Commit's refusal is
// the typed ErrRetentionHeld rather than a non-accepted-shaped
// RetentionAnswer.
func RunAHoldPreventsRemovalAndReportsInRetainedBounds(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Hold == nil {
t.Skip("this backend has no hold primitive (Hold is nil)")
}
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "held")
address := retentionMint(t, ctx, fixture, store, "held")
if err := fixture.Hold(ctx, store, address); err != nil {
t.Fatalf("Hold(%s): %v", address, err)
}
preview, err := fixture.Remove(ctx, store, address, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s) under a hold: %v", address, err)
}
if _, err := preview.Commit(ctx); !errors.Is(err, ErrRetentionHeld) {
t.Fatalf("Commit(%s) under a hold error = %v, want ErrRetentionHeld", address, err)
}
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s) after a refused, held removal: %v", address, err)
}
if answer.Restriction == RestrictionGoneRetention || answer.Restriction == RestrictionGoneErasure || answer.Restriction == RestrictionGoneReorganization {
t.Errorf("Resolve(%s) reports %s after Commit was refused for being held, want it to remain out of any Gone restriction", address, answer.Restriction)
}
if answer.RetainedWindow == nil {
t.Fatalf("Resolve(%s) after a refused, held removal reports RetainedWindow = nil, want a populated window: R20-h's promise is that a Hold shows up IN the retained bounds, not merely as an absence of a Gone restriction", address)
}
if answer.RetainedWindow.LowerBound != address && answer.RetainedWindow.UpperBound != address {
t.Errorf("Resolve(%s).RetainedWindow = %+v, want at least one bound naming the held Address itself: R20-h's promise is that a Hold shows up IN the retained bounds, but this fixture's store name is not guaranteed fresh across runs on a persistent backend, so a prior run's Addresses may widen the window and only one edge is guaranteed to be exactly this Address", address, answer.RetainedWindow)
}
}
// RunForcingAHeldRemovalRecordsWhoWhenWhy pins R20-h2: ForceRemove crosses an
// active Hold and must record who, when, and why — read back via
// RetentionAnswer.Attribution, not just accepted as parameters (formerly
// §4a choice 2, now DIED; see this file's package doc comment).
func RunForcingAHeldRemovalRecordsWhoWhenWhy(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Hold == nil {
t.Skip("this backend has no hold primitive (Hold is nil)")
}
if fixture.ForceRemove == nil {
t.Skip("this backend has no forced-removal primitive (ForceRemove is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "forced")
address := retentionMint(t, ctx, fixture, store, "forced")
if err := fixture.Hold(ctx, store, address); err != nil {
t.Fatalf("Hold(%s): %v", address, err)
}
actor := "retention-operator"
message := "legal hold expired"
attribution := ChangeAttribution{Actor: &actor, Message: &message, At: time.Now().UTC()}
answer, err := fixture.ForceRemove(ctx, store, address, attribution, "hold-expired")
if err != nil {
t.Fatalf("ForceRemove(%s) despite an active hold: %v", address, err)
}
if answer.Restriction == RestrictionLive {
t.Errorf("ForceRemove(%s) reports RestrictionLive, want a Gone restriction", address)
}
if answer.ProducingStore != store {
t.Errorf("ForceRemove(%s).ProducingStore = %q, want %q", address, answer.ProducingStore, store)
}
if answer.Attribution == nil {
t.Fatalf("ForceRemove(%s).Attribution = nil, want the who/when/why recorded for this forced removal (R20-h2)", address)
}
if !sameAttribution(*answer.Attribution, attribution) {
t.Errorf("ForceRemove(%s).Attribution = %+v, want %+v (R20-h2: who/when/why must be recorded, not just accepted as parameters)", address, *answer.Attribution, attribution)
}
}
// RunEveryRetentionAnswerNamesItsProducingStore pins R20-i for both a live
// and a non-live answer: ProducingStore always names the store that
// actually produced the answer.
func RunEveryRetentionAnswerNamesItsProducingStore(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
storeA := retentionStore(fixture, "namesA")
storeB := retentionStore(fixture, "namesB")
liveAddr := retentionMint(t, ctx, fixture, storeA, "names-live")
goneAddr := retentionMint(t, ctx, fixture, storeB, "names-gone")
preview, err := fixture.Remove(ctx, storeB, goneAddr, RemovalReasonRetention)
if err != nil {
t.Fatalf("Remove(%s): %v", goneAddr, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s): %v", goneAddr, err)
}
liveAnswer, err := fixture.Resolve(ctx, storeA, liveAddr)
if err != nil {
t.Fatalf("Resolve(%s, %s): %v", storeA, liveAddr, err)
}
if liveAnswer.ProducingStore != storeA {
t.Errorf("Resolve(%s, ...).ProducingStore = %q, want %q (R20-i: live answer)", storeA, liveAnswer.ProducingStore, storeA)
}
goneAnswer, err := fixture.Resolve(ctx, storeB, goneAddr)
if err != nil {
t.Fatalf("Resolve(%s, %s): %v", storeB, goneAddr, err)
}
if goneAnswer.ProducingStore != storeB {
t.Errorf("Resolve(%s, ...).ProducingStore = %q, want %q (R20-i: non-live answer)", storeB, goneAnswer.ProducingStore, storeB)
}
}
// RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone pins FR-06: a store
// asked about a store/Address pair it has no lineage relationship with at
// all — never received it, never removed it — must answer Unknown, not one
// of the Gone restrictions.
func RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
store := retentionStore(fixture, "nolineage")
address := retentionAddress(fixture, "nolineage-nevertracked")
answer, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s, %s): %v", store, address, err)
}
if answer.Restriction != RestrictionUnknown {
t.Errorf("Resolve on a store/address pair with no lineage relationship = %s, want RestrictionUnknown (FR-06)", answer.Restriction)
}
}
// RunAStoreThatRemovesStateStillAnswersGoneDurably pins R20-j: a removed
// Address's Gone answer is durable — two successive reads must agree, not
// merely happen to agree once.
func RunAStoreThatRemovesStateStillAnswersGoneDurably(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Remove == nil {
t.Skip("this backend has no removal primitive (Remove is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "durable")
address := retentionMint(t, ctx, fixture, store, "durable")
preview, err := fixture.Remove(ctx, store, address, RemovalReasonErasure)
if err != nil {
t.Fatalf("Remove(%s): %v", address, err)
}
if _, err := preview.Commit(ctx); err != nil {
t.Fatalf("Commit(%s): %v", address, err)
}
first, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s), first read: %v", address, err)
}
second, err := fixture.Resolve(ctx, store, address)
if err != nil {
t.Fatalf("Resolve(%s), second read: %v", address, err)
}
if first.Restriction == RestrictionLive {
t.Fatalf("Resolve(%s) after removal = RestrictionLive, want a Gone restriction", address)
}
if !sameRetentionAnswer(first, second) {
t.Errorf("two successive Resolve(%s) calls disagreed: %+v vs %+v; a removal must answer Gone DURABLY, not from a cache that can revert", address, first, second)
}
}
// RunErasureMintsACorrectedVersionRatherThanEditingInPlace pins R20-l: Erase
// returns a NEW Address for the corrected state rather than editing the
// original in place — the original resolves GoneErasure, the corrected
// replacement resolves Live.
func RunErasureMintsACorrectedVersionRatherThanEditingInPlace(t *testing.T, ctx context.Context, fixture RetentionFixture) {
t.Helper()
if fixture.Erase == nil {
t.Skip("this backend has no erasure primitive (Erase is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.Mint == nil {
t.Skip("this backend has no way to mint a real Address to test retention against (Mint is nil)")
}
store := retentionStore(fixture, "erasure")
original := retentionMint(t, ctx, fixture, store, "erasure-original")
actor := "retention-operator"
attribution := ChangeAttribution{Actor: &actor, At: time.Now().UTC()}
corrected, err := fixture.Erase(ctx, store, original, `{"corrected":true}`, attribution)
if err != nil {
t.Fatalf("Erase(%s): %v", original, err)
}
if corrected == original {
t.Fatalf("Erase(%s) returned the SAME Address, want a NEW one (R20-l: erasure mints a corrected version rather than editing in place)", original)
}
originalAnswer, err := fixture.Resolve(ctx, store, original)
if err != nil {
t.Fatalf("Resolve(original): %v", err)
}
if originalAnswer.Restriction != RestrictionGoneErasure {
t.Errorf("Resolve(the erased original) = %s, want RestrictionGoneErasure", originalAnswer.Restriction)
}
correctedAnswer, err := fixture.Resolve(ctx, store, corrected)
if err != nil {
t.Fatalf("Resolve(corrected): %v", err)
}
if correctedAnswer.Restriction != RestrictionLive {
t.Errorf("Resolve(the corrected replacement) = %s, want RestrictionLive", correctedAnswer.Restriction)
}
}
// EpochBumpTrigger enumerates the only three events R20-m allows to advance
// a store's epoch.
type EpochBumpTrigger int
const (
EpochBumpTriggerRestore EpochBumpTrigger = iota
EpochBumpTriggerDestructiveReinit
EpochBumpTriggerTokenSchemeChange
)
func (tr EpochBumpTrigger) String() string {
switch tr {
case EpochBumpTriggerRestore:
return "restore"
case EpochBumpTriggerDestructiveReinit:
return "destructive-reinit"
case EpochBumpTriggerTokenSchemeChange:
return "token-scheme-change"
default:
return fmt.Sprintf("EpochBumpTrigger(%d)", int(tr))
}
}
// EpochFixture supplies the capabilities under test for R20-m/n: the
// store-epoch generation counter and its selective effect on addresses
// minted under an earlier epoch.
type EpochFixture struct {
IssuePrefix string
// CurrentEpoch reports storeID's current epoch generation. A nil hook
// means this backend has no epoch concept yet, and cases that need one
// skip with that reason.
CurrentEpoch func(ctx context.Context, storeID string) (int, error)
// BumpEpoch advances storeID's epoch for the given trigger, returning
// the new epoch. A nil hook means this backend has no epoch concept
// yet, and cases that need one skip with that reason.
BumpEpoch func(ctx context.Context, storeID string, trigger EpochBumpTrigger) (int, error)
// MintUnderEpoch mints a fresh Version for id under storeID's current
// epoch, returning its Address. A nil hook means this backend has no
// way to mint a Version under a known epoch, and cases that need one
// skip with that reason.
MintUnderEpoch func(ctx context.Context, storeID, id string) (Address, error)
// StillServes reports whether storeID still serves the Version named by
// a prior-epoch address, despite the epoch having moved on. A nil hook
// means this backend cannot report that, and the case that needs it
// skips with that reason.
StillServes func(ctx context.Context, storeID string, address Address) (bool, error)
// Resolve is the SAME RetentionResolve type RetentionFixture uses — an
// epoch bump's effect on an Address is observed through the identical
// read path as an ordinary removal. A nil hook means this backend does
// not yet report retention state, and cases that need one skip with
// that reason.
Resolve RetentionResolve
// CurrentAddressFor reports the Address a still-served, prior-epoch
// Version now resolves to under the new epoch. A nil hook means this
// backend cannot report that, and the case that needs it skips with
// that reason.
CurrentAddressFor func(ctx context.Context, storeID string, oldAddress Address) (Address, error)
}
// RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange pins R20-m: a
// store's epoch advances for exactly the three named triggers.
//
// THIS CASE CANNOT PROVE A FOURTH, UNINVITED TRIGGER NEVER BUMPS THE EPOCH
// in some real backend — enumerating "never" over an open set of possible
// call sites is not something an interface-level test can do. That is
// Phase 3's implementation discipline to hold, not something this suite can
// enforce (NFR-03's blind spot, mirroring canonicalizeForContract's stated
// blind spot in metadata_cas_contract.go).
func RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
if fixture.BumpEpoch == nil {
t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)")
}
if fixture.CurrentEpoch == nil {
t.Skip("this backend cannot report its current epoch (CurrentEpoch is nil)")
}
store := epochStore(fixture, "triggers")
for _, trigger := range []EpochBumpTrigger{
EpochBumpTriggerRestore,
EpochBumpTriggerDestructiveReinit,
EpochBumpTriggerTokenSchemeChange,
} {
before, err := fixture.CurrentEpoch(ctx, store)
if err != nil {
t.Fatalf("CurrentEpoch before %s: %v", trigger, err)
}
after, err := fixture.BumpEpoch(ctx, store, trigger)
if err != nil {
t.Fatalf("BumpEpoch(%s): %v", trigger, err)
}
if after <= before {
t.Errorf("BumpEpoch(%s) = %d, want an epoch greater than the pre-bump value %d", trigger, after, before)
}
observed, err := fixture.CurrentEpoch(ctx, store)
if err != nil {
t.Fatalf("CurrentEpoch after %s: %v", trigger, err)
}
if observed != after {
t.Errorf("CurrentEpoch after BumpEpoch(%s) = %d, want the bumped value %d", trigger, observed, after)
}
}
}
// RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed pins R20-n — "Rev7
// tightening... the clause most likely to be gotten wrong" in the
// architecture doc's own words. A prior-epoch Address goes
// GoneReorganization UNLESS the backend still serves that Version, in which
// case it must stay Live AND additionally report the Address it now
// resolves to under the new epoch.
//
// StillServes is an ORACLE here, not a control: this case cannot make a real
// backend keep serving one address and drop another, since Phase 0 wires no
// real backend. It asks StillServes what the fixture (once real) decided,
// and checks the rest of the contract's promise against that decision for
// both outcomes.
func RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t *testing.T, ctx context.Context, fixture EpochFixture) {
t.Helper()
if fixture.MintUnderEpoch == nil {
t.Skip("this backend has no way to mint a Version under a known epoch (MintUnderEpoch is nil)")
}
if fixture.BumpEpoch == nil {
t.Skip("this backend has no epoch concept yet (BumpEpoch is nil)")
}
if fixture.StillServes == nil {
t.Skip("this backend cannot report whether it still serves a prior-epoch Version (StillServes is nil)")
}
if fixture.Resolve == nil {
t.Skip("this backend does not yet report retention state (Resolve is nil)")
}
if fixture.CurrentAddressFor == nil {
t.Skip("this backend cannot report a still-served Version's new Address (CurrentAddressFor is nil)")
}
store := epochStore(fixture, "voids")
addrA, err := fixture.MintUnderEpoch(ctx, store, "record-a")
if err != nil {
t.Fatalf("MintUnderEpoch(record-a): %v", err)
}
addrB, err := fixture.MintUnderEpoch(ctx, store, "record-b")
if err != nil {
t.Fatalf("MintUnderEpoch(record-b): %v", err)
}
newEpoch, err := fixture.BumpEpoch(ctx, store, EpochBumpTriggerRestore)
if err != nil {
t.Fatalf("BumpEpoch: %v", err)
}
servesA, err := fixture.StillServes(ctx, store, addrA)
if err != nil {
t.Fatalf("StillServes(%s): %v", addrA, err)
}
servesB, err := fixture.StillServes(ctx, store, addrB)
if err != nil {
t.Fatalf("StillServes(%s): %v", addrB, err)
}
if servesA == servesB {
t.Skip("this scenario needs one still-served and one no-longer-served address to exercise both halves of R20-n; StillServes reported the same answer for both, so this fixture gives this case nothing to contrast")
}
stillServed, noLongerServed := addrA, addrB
if servesB && !servesA {
stillServed, noLongerServed = addrB, addrA
}
voidedAnswer, err := fixture.Resolve(ctx, store, noLongerServed)
if err != nil {
t.Fatalf("Resolve(no-longer-served): %v", err)
}
if voidedAnswer.Restriction != RestrictionGoneReorganization {
t.Errorf("Resolve(a prior-epoch Address no longer served) = %s, want RestrictionGoneReorganization (R20-n)", voidedAnswer.Restriction)
}
if voidedAnswer.Epoch == nil {
t.Fatal("Resolve(a prior-epoch Address no longer served).Epoch = nil, want the current epoch populated (R20-n: the answer must name the current epoch, not just Restriction alone)")
} else if *voidedAnswer.Epoch != newEpoch {
t.Errorf("Resolve(a prior-epoch Address no longer served).Epoch = %d, want the current epoch %d", *voidedAnswer.Epoch, newEpoch)
}
keptAnswer, err := fixture.Resolve(ctx, store, stillServed)
if err != nil {
t.Fatalf("Resolve(still-served): %v", err)
}
if keptAnswer.Restriction != RestrictionLive {
t.Errorf("Resolve(a prior-epoch Address the backend still serves) = %s, want RestrictionLive (R20-n's exception)", keptAnswer.Restriction)
}
newAddr, err := fixture.CurrentAddressFor(ctx, store, stillServed)
if err != nil {
t.Fatalf("CurrentAddressFor(%s): %v", stillServed, err)
}
if newAddr == "" {
t.Error("CurrentAddressFor(a still-served prior-epoch Address) returned an empty Address, want a real one under the new epoch")
}
}
// --- fixture helpers -------------------------------------------------------
// retentionStore names a storeID namespaced by the fixture's IssuePrefix and
// tag, so cases that need more than one store (e.g. to probe FR-06's
// no-lineage-knowledge case) get independent ones.
func retentionStore(fixture RetentionFixture, tag string) string {
return fixture.IssuePrefix + "-retention-store-" + tag
}
// retentionAddress builds a fresh, syntactically valid Address namespaced by
// the fixture's IssuePrefix and tag, WITHOUT ever giving it to any store.
// RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone is the only remaining
// caller: Unknown specifically means a store with no lineage knowledge of
// the Address at all (FR-06), so fabricating one that no store has ever
// seen is the correct construction here, not a shortcut — unlike every
// other case in this file, which now mints a real Address via
// fixture.Mint/retentionMint instead of relying on the retired
// Live-baseline convention (see this file's package doc comment, formerly
// §4a choice 3).
func retentionAddress(fixture RetentionFixture, tag string) Address {
return Address(fixture.IssuePrefix + "-retention-address-" + tag)
}
// retentionMint mints a fresh Address for tag on store via fixture.Mint,
// fataling the case if minting fails — analogous to how
// EpochFixture.MintUnderEpoch is called directly in this file's Epoch
// cases, without its own wrapper. Cases use this in place of the retired
// retentionAddress convention (formerly §4a choice 3, now DIED — see this
// file's package doc comment) for any Address that must resolve as a real,
// store-established Version.
func retentionMint(t *testing.T, ctx context.Context, fixture RetentionFixture, store, tag string) Address {
t.Helper()
address, err := fixture.Mint(ctx, store, tag)
if err != nil {
t.Fatalf("Mint(%s, %s): %v", store, tag, err)
}
return address
}
// epochStore names a storeID namespaced by the fixture's IssuePrefix and tag.
func epochStore(fixture EpochFixture, tag string) string {
return fixture.IssuePrefix + "-epoch-store-" + tag
}
// sameRetentionAnswer compares two RetentionAnswer values by content rather
// than identity, so a case can assert "this did not change" without
// depending on the concrete Restriction the backend happened to pick.
func sameRetentionAnswer(a, b RetentionAnswer) bool {
return a.Restriction == b.Restriction &&
a.ProducingStore == b.ProducingStore &&
sameRetainedWindow(a.RetainedWindow, b.RetainedWindow) &&
sameAttributionPtr(a.Attribution, b.Attribution) &&
sameIntPtr(a.Epoch, b.Epoch)
}
func sameAttributionPtr(a, b *ChangeAttribution) bool {
if a == nil || b == nil {
return a == b
}
return sameAttribution(*a, *b)
}
func sameIntPtr(a, b *int) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}
func sameRetainedWindow(a, b *RetainedWindow) bool {
if a == nil || b == nil {
return a == b
}
return *a == *b
}

View file

@ -89,6 +89,7 @@ type RoleContractBundle struct {
CycleDetector func(t *testing.T) *CycleDetectorFixture
Deleter func(t *testing.T) *DeleterFixture
DependencyEditor func(t *testing.T) *DependencyEditorFixture
DualWrite func(t *testing.T) *DualWriteFixture
EdgeReader func(t *testing.T) *EdgeReaderFixture
GraphCounter func(t *testing.T) *GraphCounterFixture
Importer func(t *testing.T) *ImporterFixture

View file

@ -245,6 +245,8 @@ var roleContractCases = []roleContract{
RunDependencyEditorRefusesCrossPlaneCycle,
RunDependencyEditorAddedEchoesTheRequestOrder,
RunDependencyEditorSameTypeReAddIsIdempotent,
RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion,
RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp,
RunDependencyEditorRepeatsWithinOneRequestCollapse,
RunDependencyEditorAttributesItsEventsToTheActor,
RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge,
@ -280,6 +282,24 @@ var roleContractCases = []roleContract{
RunDependencyEditorAcceptsBlockingAcrossIssueTypes,
),
// The accessor named here is not an accessor at all, alone among these
// rows except Journal: storage.VersionedHistoryConfigurer is reached by
// TYPE ASSERTION, either on a store (the dolt and embedded-dolt legs) or
// on a unit-of-work provider (the uow leg), because enabling dual-write
// history is engine configuration rather than an issue-shaped operation
// storage.Storage publishes. A backend that does not implement Phase 2's
// dual-write mechanism leaves this field nil; see
// dualwrite_history_contract.go's header.
roleCases("DualWrite", "the storage.VersionedHistoryConfigurer type assertion", oncePerRole,
func(b RoleContractBundle) func(t *testing.T) *DualWriteFixture { return b.DualWrite },
RunDualWriteMintsOneVersionRowPerAcceptedMutation,
RunDualWriteNoOpMutationMintsNoRow,
RunDualWriteAttributionIsRecordedWithTheMutation,
RunDualWriteCurrentRevisionMatchesTheNewVersionRow,
RunDualWriteFlagOffProducesNoVersionRows,
RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed,
),
roleCases("EdgeReader", "EdgeReader()", oncePerRole,
func(b RoleContractBundle) func(t *testing.T) *EdgeReaderFixture { return b.EdgeReader },
RunEdgeReaderAnswersOnePerAnchorInRequestOrder,

View file

@ -27,9 +27,16 @@ import (
// which is the same defect class as a test with correct assertions on a fixture
// that cannot fail, one level up. So the expected set is DERIVED from the
// package source rather than written down: every top-level func named Run* that
// takes (*testing.T, context.Context, <name>Fixture) is a role-tier case, and
// the entry points that take a Factory instead — RunAll, RunAudit and friends,
// RunPortableMethods, RunSearchPaging, RunDeferredReads — are not.
// takes (*testing.T, context.Context, <name>Fixture) where <name>Fixture is one
// of RoleContractBundle's own field types is a role-tier case. That bundle-field
// check is what keeps this scoped to the role tier specifically: the package
// also holds other conformance tiers (e.g. the history-semantics contracts that
// versioned_history_wiring_test.go wires directly, with no RoleContractBundle
// field of their own — see that file's header) whose Run*Fixture-shaped
// functions must NOT be swept in here, since nothing in RoleContractBundle ever
// calls them. The entry points that take a Factory instead — RunAll, RunAudit
// and friends, RunPortableMethods, RunSearchPaging, RunDeferredReads — are not
// role-tier cases either.
//
// The table's own half of the comparison is derived too: roleCases resolves
// each function VALUE back to its declared name (runFuncName), so a row cannot
@ -314,9 +321,13 @@ func runProbeChild(t *testing.T, mode string) (string, error) {
// parseRoleContractCases returns every role-tier case declared in this
// package's non-test sources, in filename then declaration order — the order
// roleContractCases is written in.
// roleContractCases is written in. A Run*Fixture-shaped function whose Fixture
// type is not one of RoleContractBundle's own field types belongs to a
// different conformance tier and is not a role-tier case; see
// roleTierFixtureNames.
func parseRoleContractCases(t *testing.T) []string {
t.Helper()
roleFixtures := roleTierFixtureNames()
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("runtime.Caller failed")
@ -341,7 +352,7 @@ func parseRoleContractCases(t *testing.T) []string {
if !ok || fn.Recv != nil || !strings.HasPrefix(fn.Name.Name, "Run") {
continue
}
if takesFixture(fn) {
if fixtureName, ok := takesFixture(fn); ok && roleFixtures[fixtureName] {
cases = append(cases, fn.Name.Name)
}
}
@ -350,22 +361,54 @@ func parseRoleContractCases(t *testing.T) []string {
return cases
}
// roleTierFixtureNames returns the pointee type name of every *XxxFixture a
// RoleContractBundle field produces. This is the role tier's actual membership
// test: a Run*Fixture-shaped function is a role-tier case only if its Fixture
// type appears here, because that is the only way RunRoleContracts could ever
// reach it. Other conformance tiers in this package (e.g. Phase 0's
// history-semantics contracts, wired directly by
// versioned_history_wiring_test.go rather than through this bundle) mint their
// own *Fixture types that intentionally never appear here.
func roleTierFixtureNames() map[string]bool {
names := map[string]bool{}
bundleType := reflect.TypeOf(RoleContractBundle{})
for i := range bundleType.NumField() {
field := bundleType.Field(i).Type
if field.Kind() != reflect.Func || field.NumOut() != 1 {
continue
}
out := field.Out(0)
if out.Kind() != reflect.Ptr {
continue
}
names[out.Elem().Name()] = true
}
return names
}
// takesFixture reports whether fn has the role-tier case signature:
// (t *testing.T, ctx context.Context, fixture <name>Fixture).
func takesFixture(fn *ast.FuncDecl) bool {
// (t *testing.T, ctx context.Context, fixture <name>Fixture), returning the
// Fixture type's name so the caller can check it against the role tier's
// actual membership (roleTierFixtureNames) rather than the signature shape
// alone — the shape is necessary but not sufficient, since other conformance
// tiers use it too.
func takesFixture(fn *ast.FuncDecl) (fixtureName string, ok bool) {
if fn.Type.Params == nil || len(fn.Type.Params.List) != 3 {
return false
return "", false
}
params := fn.Type.Params.List
star, ok := params[0].Type.(*ast.StarExpr)
if !ok || !isQualified(star.X, "testing", "T") {
return false
star, starOk := params[0].Type.(*ast.StarExpr)
if !starOk || !isQualified(star.X, "testing", "T") {
return "", false
}
if !isQualified(params[1].Type, "context", "Context") {
return false
return "", false
}
fixture, ok := params[2].Type.(*ast.Ident)
return ok && strings.HasSuffix(fixture.Name, "Fixture")
fixture, identOk := params[2].Type.(*ast.Ident)
if !identOk || !strings.HasSuffix(fixture.Name, "Fixture") {
return "", false
}
return fixture.Name, true
}
func isQualified(expr ast.Expr, pkg, name string) bool {

View file

@ -0,0 +1,133 @@
package conformance
import (
"context"
"testing"
)
// TestVersionedHistoryPhase0RunsInFullSkipMode is Phase 0's own wiring: it
// constructs each of the three new Fixtures with every hook nil — exactly
// the state every backend's real fixture kit is in as of this phase's merge
// (architecture §12: "every new hook is nil in every backend's fixture kit")
// — and runs every R16/R16.1/R17/R20 case once each, proving the whole suite
// compiles and skips cleanly under today's CI (NFR-01).
//
// Each leg under internal/storage wires these same entrypoints, with the same
// all-nil fixtures, so TestEveryLegWiresEveryRoleContract counts them; this
// local copy is not a substitute for those, it just proves the all-skip
// behavior once without needing to build all three legs to see it.
func TestVersionedHistoryPhase0RunsInFullSkipMode(t *testing.T) {
ctx := context.Background()
t.Run("ExpectedRevision", func(t *testing.T) {
fixture := ExpectedRevisionFixture{IssuePrefix: "vh0"}
t.Run("AcceptsAWriteNamingTheCurrentVersion", func(t *testing.T) {
RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t, ctx, fixture)
})
t.Run("AcceptsAWriteNamingNoVersion", func(t *testing.T) {
RunExpectedRevisionAcceptsAWriteNamingNoVersion(t, ctx, fixture)
})
t.Run("CoversFieldsOutsideAnyWatchedSubset", func(t *testing.T) {
RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionAddress", func(t *testing.T) {
RunRefusalReportsTheRefusingVersionAddress(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionsChangeAttribution", func(t *testing.T) {
RunRefusalReportsTheRefusingVersionsChangeAttribution(t, ctx, fixture)
})
t.Run("RefusalIsATypedOutcomeNotAGenericError", func(t *testing.T) {
RunRefusalIsATypedOutcomeNotAGenericError(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromAnAcceptedWrite", func(t *testing.T) {
RunRefusalIsDistinguishableFromAnAcceptedWrite(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromNotFound", func(t *testing.T) {
RunRefusalIsDistinguishableFromNotFound(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromValidationFailure", func(t *testing.T) {
RunRefusalIsDistinguishableFromValidationFailure(t, ctx, fixture)
})
t.Run("RefusalNeverSilentlyPicksAWinner", func(t *testing.T) {
RunRefusalNeverSilentlyPicksAWinner(t, ctx, fixture)
})
})
t.Run("CrossRecordInvariant", func(t *testing.T) {
fixture := CrossRecordInvariantFixture{IssuePrefix: "vh0"}
t.Run("SurvivesTwoPassingPerRecordGuards", func(t *testing.T) {
RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards(t, ctx, fixture)
})
t.Run("StoreInvariantTransactionScopesExactlyTheSpanningRecords", func(t *testing.T) {
RunStoreInvariantTransactionScopesExactlyTheSpanningRecords(t, ctx, fixture)
})
t.Run("InvariantRefusalNamesTheViolatedInvariant", func(t *testing.T) {
RunInvariantRefusalNamesTheViolatedInvariant(t, ctx, fixture)
})
t.Run("MemoryKeyAliasUniquenessIsAStoreInvariantNotACAS", func(t *testing.T) {
RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("MaximumEndpointMultiplicityIsAStoreInvariantNotACAS", func(t *testing.T) {
RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("AdvisoryLeaseAloneDoesNotPreventTheInvariantViolation", func(t *testing.T) {
RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation(t, ctx, fixture)
})
t.Run("LeaseAcquisitionRecordsNoHistoryEntry", func(t *testing.T) {
RunLeaseAcquisitionRecordsNoHistoryEntry(t, ctx, fixture)
})
})
t.Run("Retention", func(t *testing.T) {
fixture := RetentionFixture{IssuePrefix: "vh0"}
t.Run("RemovalLeavesTheAddressAbleToAnswer", func(t *testing.T) {
RunRemovalLeavesTheAddressAbleToAnswer(t, ctx, fixture)
})
t.Run("RemovalReasonIsRetentionErasureOrReorganizationDistinctly", func(t *testing.T) {
RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly(t, ctx, fixture)
})
t.Run("RemovalReportsTheSurvivingRetainedWindow", func(t *testing.T) {
RunRemovalReportsTheSurvivingRetainedWindow(t, ctx, fixture)
})
t.Run("RemovalNeverReassignsASurvivingAddress", func(t *testing.T) {
RunRemovalNeverReassignsASurvivingAddress(t, ctx, fixture)
})
t.Run("GoneIsDistinguishableFromUnknown", func(t *testing.T) {
RunGoneIsDistinguishableFromUnknown(t, ctx, fixture)
})
t.Run("AnAddressNeverResolvesToADifferentState", func(t *testing.T) {
RunAnAddressNeverResolvesToADifferentState(t, ctx, fixture)
})
t.Run("ADestructiveOperationEnumeratesAffectedAddressesFirst", func(t *testing.T) {
RunADestructiveOperationEnumeratesAffectedAddressesFirst(t, ctx, fixture)
})
t.Run("AHoldPreventsRemovalAndReportsInRetainedBounds", func(t *testing.T) {
RunAHoldPreventsRemovalAndReportsInRetainedBounds(t, ctx, fixture)
})
t.Run("ForcingAHeldRemovalRecordsWhoWhenWhy", func(t *testing.T) {
RunForcingAHeldRemovalRecordsWhoWhenWhy(t, ctx, fixture)
})
t.Run("EveryRetentionAnswerNamesItsProducingStore", func(t *testing.T) {
RunEveryRetentionAnswerNamesItsProducingStore(t, ctx, fixture)
})
t.Run("AStoreWithNoLineageKnowledgeAnswersUnknownNotGone", func(t *testing.T) {
RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone(t, ctx, fixture)
})
t.Run("AStoreThatRemovesStateStillAnswersGoneDurably", func(t *testing.T) {
RunAStoreThatRemovesStateStillAnswersGoneDurably(t, ctx, fixture)
})
t.Run("ErasureMintsACorrectedVersionRatherThanEditingInPlace", func(t *testing.T) {
RunErasureMintsACorrectedVersionRatherThanEditingInPlace(t, ctx, fixture)
})
})
t.Run("Epoch", func(t *testing.T) {
fixture := EpochFixture{IssuePrefix: "vh0"}
t.Run("AnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange", func(t *testing.T) {
RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t, ctx, fixture)
})
t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) {
RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture)
})
})
}

View file

@ -19,7 +19,7 @@ buildGoModule {
# proxyVendor avoids vendor/modules.txt consistency checks when the vendored
# tree lags go.mod/go.sum.
proxyVendor = true;
vendorHash = "sha256-DQdauEx5g48Xbxrz4wGLx4vkrQoYQX3FUx+7N/Y6YV4=";
vendorHash = "sha256-m+ADPJxU1PuVm5dAHOZGBkXbGIzEIiJMmpypvwiFKX4=";
# Match go.mod to the selected Nix Go toolchain. buildGoModule also builds
# vendored dependencies in the Nix sandbox, where toolchain downloads are not

1
go.mod
View file

@ -16,6 +16,7 @@ require (
github.com/dolthub/driver/v2 v2.2.0
github.com/dolthub/eventkit v0.0.0-20260611184414-99f5693e696a
github.com/go-sql-driver/mysql v1.10.0
github.com/gowebpki/jcs v1.0.1
github.com/invopop/jsonschema v0.14.0
github.com/mattn/go-sqlite3 v1.14.49
github.com/olebedev/when v1.1.0

2
go.sum
View file

@ -703,6 +703,8 @@ github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gowebpki/jcs v1.0.1 h1:Qjzg8EOkrOTuWP7DqQ1FbYtcpEbeTzUoTN9bptp8FOU=
github.com/gowebpki/jcs v1.0.1/go.mod h1:CID1cNZ+sHp1CCpAR8mPf6QRtagFBgPJE0FCUQ6+BrI=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=

View file

@ -0,0 +1,41 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestCrossRecordInvariantContract wires this leg into the R16.1
// cross-record invariant contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestCrossRecordInvariantContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.CrossRecordInvariantFixture{IssuePrefix: "xrec"}
t.Run("SurvivesTwoPassingPerRecordGuards", func(t *testing.T) {
conformance.RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards(t, ctx, fixture)
})
t.Run("StoreInvariantTransactionScopesExactlyTheSpanningRecords", func(t *testing.T) {
conformance.RunStoreInvariantTransactionScopesExactlyTheSpanningRecords(t, ctx, fixture)
})
t.Run("InvariantRefusalNamesTheViolatedInvariant", func(t *testing.T) {
conformance.RunInvariantRefusalNamesTheViolatedInvariant(t, ctx, fixture)
})
t.Run("MemoryKeyAliasUniquenessIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("MaximumEndpointMultiplicityIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("AdvisoryLeaseAloneDoesNotPreventTheInvariantViolation", func(t *testing.T) {
conformance.RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation(t, ctx, fixture)
})
t.Run("LeaseAcquisitionRecordsNoHistoryEntry", func(t *testing.T) {
conformance.RunLeaseAcquisitionRecordsNoHistoryEntry(t, ctx, fixture)
})
}

View file

@ -43,6 +43,18 @@ func TestDependencyEditorSameTypeReAddIsIdempotent(t *testing.T) {
conformance.RunDependencyEditorSameTypeReAddIsIdempotent(t, ctx, fixture)
}
func TestDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion(t *testing.T) {
fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "idemmeta")
defer cleanup()
conformance.RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion(t, ctx, fixture)
}
func TestDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t *testing.T) {
fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "idemmetasame")
defer cleanup()
conformance.RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t, ctx, fixture)
}
func TestDependencyEditorRepeatsWithinOneRequestCollapse(t *testing.T) {
fixture, ctx, cleanup := newDoltDependencyEditorFixture(t, "repeat")
defer cleanup()
@ -256,13 +268,15 @@ func newDoltDependencyEditorFixture(t *testing.T, prefix string) (conformance.De
}
kit := newDoltRoleFixtureKit(store, prefix)
fixture := conformance.DependencyEditorFixture{
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
SetJournalEnabled: store.SetEventsJournalEnabled,
SetVersionedHistoryEnabled: store.SetVersionedHistoryEnabled,
}
return fixture, ctx, func() {
cancel()

View file

@ -0,0 +1,226 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// TestDualWriteContract runs the dual-write history contract with
// storage.VersionedHistoryConfigurer ON. Like TestJournalContract, this is an
// engine check rather than an independent per-leg vote: all three legs share
// RecordVersionInTx, and the dolt leg is where a write that escaped its
// transaction, or a read that raced it, would have somewhere to go wrong.
func TestDualWriteContract(t *testing.T) {
fixture, ctx, cleanup := newDoltDualWriteFixture(t, "dwc", true)
defer cleanup()
t.Run("MintsOneVersionRowPerAcceptedMutation", func(t *testing.T) {
conformance.RunDualWriteMintsOneVersionRowPerAcceptedMutation(t, ctx, fixture)
})
t.Run("NoOpMutationMintsNoRow", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationMintsNoRow(t, ctx, fixture)
})
t.Run("AttributionIsRecordedWithTheMutation", func(t *testing.T) {
conformance.RunDualWriteAttributionIsRecordedWithTheMutation(t, ctx, fixture)
})
t.Run("CurrentRevisionMatchesTheNewVersionRow", func(t *testing.T) {
conformance.RunDualWriteCurrentRevisionMatchesTheNewVersionRow(t, ctx, fixture)
})
t.Run("NoOpMutationLeavesThePriorVersionRowUnperturbed", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed(t, ctx, fixture)
})
}
// TestDualWriteContractFlagOff runs FR-7 against a fixture constructed with
// the flag OFF from the start. It is a separate top-level test, not a subtest
// of TestDualWriteContract, because sharing one store between a flag-on and a
// flag-off case would make "flag off" mean "flag not yet turned on this
// session" rather than the thing FR-7 actually promises.
func TestDualWriteContractFlagOff(t *testing.T) {
fixture, ctx, cleanup := newDoltDualWriteFixture(t, "dwcoff", false)
defer cleanup()
t.Run("FlagOffProducesNoVersionRows", func(t *testing.T) {
conformance.RunDualWriteFlagOffProducesNoVersionRows(t, ctx, fixture)
})
}
// TestDualWriteFixtureKitIsWired is the explicit per-leg guardrail design
// §8.5 calls for in place of AST auto-discovery: DualWriteFixture's type name
// ends in "Fixture" like every other role fixture, so
// TestEveryLegWiresEveryRoleContract's scan of backend/conformance DOES
// enumerate its six RunDualWriteXxx functions as entrypoints — but that scan
// is satisfied the moment this leg's own test files reference all six by
// name, which TestDualWriteContract and TestDualWriteContractFlagOff already
// do between them. What that satisfied scan cannot catch is a fixture built
// with a nil closure that happens to never run in this leg's own case list —
// silent by construction, since a nil func field only panics the one time
// something calls it. This test exists to make that failure loud instead:
// it fails the moment any of the five closures is nil, independent of
// whether any case above happens to exercise it.
func TestDualWriteFixtureKitIsWired(t *testing.T) {
fixture, _, cleanup := newDoltDualWriteFixture(t, "dwk", true)
defer cleanup()
if fixture.Mutate == nil {
t.Error("DualWriteFixture.Mutate is nil")
}
if fixture.MutateAsNoOp == nil {
t.Error("DualWriteFixture.MutateAsNoOp is nil")
}
if fixture.CurrentRevision == nil {
t.Error("DualWriteFixture.CurrentRevision is nil")
}
if fixture.VersionRowCount == nil {
t.Error("DualWriteFixture.VersionRowCount is nil")
}
if fixture.LatestVersionAttribution == nil {
t.Error("DualWriteFixture.LatestVersionAttribution is nil")
}
}
// TestDualWriteStampsTheCurrentStoreEpochOnEachVersionRow pins FR-6, the one
// dual-write requirement DualWriteFixture cannot reach: every issue_versions
// row this phase inserts carries the CURRENT store_epoch.epoch value (design
// §16's "stamped"), and inserting that row must never itself change
// store_epoch.epoch (design's "never bumped" — that bump belongs to a later,
// unbuilt phase, not to RecordVersionInTx). This lives on the dolt leg only,
// not because the property is dolt-specific, but because none of
// DualWriteFixture's five closures expose either epoch column — see
// dualwrite_history_contract.go's "WHAT THIS CONTRACT DELIBERATELY DOES NOT
// PIN" — and the dolt leg is the one with a plain *sql.DB to read them from
// directly.
func TestDualWriteStampsTheCurrentStoreEpochOnEachVersionRow(t *testing.T) {
store, storeCleanup := setupTestStore(t)
defer storeCleanup()
ctx, cancel := testContext(t)
defer cancel()
configurer, ok := any(store).(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", store)
}
configurer.SetVersionedHistoryEnabled(true)
defer configurer.SetVersionedHistoryEnabled(false)
create := func(id string) error {
return store.CreateIssue(ctx, &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
}, "actor")
}
storeEpoch := func() (int, error) {
var epoch int
err := store.db.QueryRowContext(ctx, `SELECT epoch FROM store_epoch WHERE id = 1`).Scan(&epoch)
return epoch, err
}
versionEpoch := func(id string) (int, error) {
var epoch int
err := store.db.QueryRowContext(ctx,
`SELECT epoch FROM issue_versions WHERE issue_id = ? ORDER BY revision DESC LIMIT 1`, id).
Scan(&epoch)
return epoch, err
}
const first, second = "dwe-stamp-first", "dwe-stamp-second"
if err := create(first); err != nil {
t.Fatalf("creating %s: %v", first, err)
}
epochAfterFirst, err := storeEpoch()
if err != nil {
t.Fatalf("reading store_epoch after the first mutation: %v", err)
}
firstVersionEpoch, err := versionEpoch(first)
if err != nil {
t.Fatalf("reading issue_versions.epoch for %s: %v", first, err)
}
if firstVersionEpoch != epochAfterFirst {
t.Errorf("issue_versions.epoch for %s = %d, want the current store_epoch.epoch %d: FR-6 requires "+
"every version row to be stamped with the store's current epoch at the moment it is minted",
first, firstVersionEpoch, epochAfterFirst)
}
if err := create(second); err != nil {
t.Fatalf("creating %s: %v", second, err)
}
epochAfterSecond, err := storeEpoch()
if err != nil {
t.Fatalf("reading store_epoch after the second mutation: %v", err)
}
if epochAfterSecond != epochAfterFirst {
t.Errorf("store_epoch.epoch went from %d to %d across an ordinary accepted mutation, want "+
"unchanged: FR-6 requires RecordVersionInTx to stamp the epoch onto the version row, never "+
"to bump store_epoch.epoch itself — that bump belongs to a later, unbuilt phase",
epochAfterFirst, epochAfterSecond)
}
secondVersionEpoch, err := versionEpoch(second)
if err != nil {
t.Fatalf("reading issue_versions.epoch for %s: %v", second, err)
}
if secondVersionEpoch != epochAfterSecond {
t.Errorf("issue_versions.epoch for %s = %d, want the current store_epoch.epoch %d",
second, secondVersionEpoch, epochAfterSecond)
}
}
func newDoltDualWriteFixture(t *testing.T, prefix string, enabled bool) (conformance.DualWriteFixture, context.Context, func()) {
t.Helper()
store, storeCleanup := setupTestStore(t)
ctx, cancel := testContext(t)
// Through the type assertion `bd serve` makes, never the concrete method
// set: dual-write history is not on storage.DoltStorage, so publishing it
// IS implementing this interface, matching newDoltJournalFixture's own
// discipline for storage.EventsJournalCursor above.
configurer, ok := any(store).(storage.VersionedHistoryConfigurer)
if !ok {
cancel()
storeCleanup()
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", store)
}
configurer.SetVersionedHistoryEnabled(enabled)
fixture := conformance.DualWriteFixture{
IssuePrefix: prefix,
Mutate: func(ctx context.Context, id string) error {
return store.CreateIssue(ctx, &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
}, "actor")
},
MutateAsNoOp: func(ctx context.Context, id string) error {
// Re-sets title to the exact value Mutate already gave it, so
// issueops.DiscardNoopIssueUpdates discards it before it ever
// reaches RecordVersionInTx.
return store.UpdateIssue(ctx, id, map[string]any{"title": "t-" + id}, "actor")
},
CurrentRevision: func(ctx context.Context, id string) (int64, error) {
var revision int64
err := store.db.QueryRowContext(ctx, `SELECT current_revision FROM issues WHERE id = ?`, id).
Scan(&revision)
return revision, err
},
VersionRowCount: func(ctx context.Context, id string) (int, error) {
var count int
err := store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?`, id).
Scan(&count)
return count, err
},
LatestVersionAttribution: func(ctx context.Context, id string) (actor, agent, message string, err error) {
err = store.db.QueryRowContext(ctx, `
SELECT COALESCE(change_actor, ''), COALESCE(change_agent, ''), COALESCE(change_message, '')
FROM issue_versions
WHERE issue_id = ?
ORDER BY revision DESC
LIMIT 1`, id).Scan(&actor, &agent, &message)
return actor, agent, message, err
},
}
return fixture, ctx, func() {
// Dual-write is instance-scoped, and this store outlives the fixture
// in the shared-database harness. Leaving it on would version every
// mutation a later test in this package makes.
configurer.SetVersionedHistoryEnabled(false)
cancel()
storeCleanup()
}
}

View file

@ -0,0 +1,50 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestExpectedRevisionContract wires this leg into the R16/R17
// expected-revision contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestExpectedRevisionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.ExpectedRevisionFixture{IssuePrefix: "erev"}
t.Run("AcceptsAWriteNamingTheCurrentVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t, ctx, fixture)
})
t.Run("AcceptsAWriteNamingNoVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingNoVersion(t, ctx, fixture)
})
t.Run("CoversFieldsOutsideAnyWatchedSubset", func(t *testing.T) {
conformance.RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionAddress", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionAddress(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionsChangeAttribution", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionsChangeAttribution(t, ctx, fixture)
})
t.Run("RefusalIsATypedOutcomeNotAGenericError", func(t *testing.T) {
conformance.RunRefusalIsATypedOutcomeNotAGenericError(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromAnAcceptedWrite", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromAnAcceptedWrite(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromNotFound", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromNotFound(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromValidationFailure", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromValidationFailure(t, ctx, fixture)
})
t.Run("RefusalNeverSilentlyPicksAWinner", func(t *testing.T) {
conformance.RunRefusalNeverSilentlyPicksAWinner(t, ctx, fixture)
})
}

View file

@ -140,8 +140,8 @@ func TestMigration0067ReplaysIdempotentlyAsRawSQLThroughPR4107Harness(t *testing
t.Fatalf("seed current_revision: %v", err)
}
if _, err := store.db.ExecContext(ctx, `
INSERT INTO issue_versions (issue_id, revision, epoch, change_at)
VALUES ('mig0067-replay-subject', 42, 1, '2026-09-05 00:00:00')`); err != nil {
INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status)
VALUES ('mig0067-replay-subject', 42, 1, '2026-09-05 00:00:00', 'unknown')`); err != nil {
t.Fatalf("seed issue_versions row: %v", err)
}

View file

@ -0,0 +1,72 @@
package dolt
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestRetentionContract wires this leg into the R20 retention contract.
// Phase 0 leaves every hook nil in every backend's fixture kit (architecture
// §12), so each case below skips by name; this file exists so
// TestEveryLegWiresEveryRoleContract counts this leg, and so the cases start
// running for real the moment this leg's fixture kit grows a non-nil hook.
func TestRetentionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.RetentionFixture{IssuePrefix: "rete"}
t.Run("RemovalLeavesTheAddressAbleToAnswer", func(t *testing.T) {
conformance.RunRemovalLeavesTheAddressAbleToAnswer(t, ctx, fixture)
})
t.Run("RemovalReasonIsRetentionErasureOrReorganizationDistinctly", func(t *testing.T) {
conformance.RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly(t, ctx, fixture)
})
t.Run("RemovalReportsTheSurvivingRetainedWindow", func(t *testing.T) {
conformance.RunRemovalReportsTheSurvivingRetainedWindow(t, ctx, fixture)
})
t.Run("RemovalNeverReassignsASurvivingAddress", func(t *testing.T) {
conformance.RunRemovalNeverReassignsASurvivingAddress(t, ctx, fixture)
})
t.Run("GoneIsDistinguishableFromUnknown", func(t *testing.T) {
conformance.RunGoneIsDistinguishableFromUnknown(t, ctx, fixture)
})
t.Run("AnAddressNeverResolvesToADifferentState", func(t *testing.T) {
conformance.RunAnAddressNeverResolvesToADifferentState(t, ctx, fixture)
})
t.Run("ADestructiveOperationEnumeratesAffectedAddressesFirst", func(t *testing.T) {
conformance.RunADestructiveOperationEnumeratesAffectedAddressesFirst(t, ctx, fixture)
})
t.Run("AHoldPreventsRemovalAndReportsInRetainedBounds", func(t *testing.T) {
conformance.RunAHoldPreventsRemovalAndReportsInRetainedBounds(t, ctx, fixture)
})
t.Run("ForcingAHeldRemovalRecordsWhoWhenWhy", func(t *testing.T) {
conformance.RunForcingAHeldRemovalRecordsWhoWhenWhy(t, ctx, fixture)
})
t.Run("EveryRetentionAnswerNamesItsProducingStore", func(t *testing.T) {
conformance.RunEveryRetentionAnswerNamesItsProducingStore(t, ctx, fixture)
})
t.Run("AStoreWithNoLineageKnowledgeAnswersUnknownNotGone", func(t *testing.T) {
conformance.RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone(t, ctx, fixture)
})
t.Run("AStoreThatRemovesStateStillAnswersGoneDurably", func(t *testing.T) {
conformance.RunAStoreThatRemovesStateStillAnswersGoneDurably(t, ctx, fixture)
})
t.Run("ErasureMintsACorrectedVersionRatherThanEditingInPlace", func(t *testing.T) {
conformance.RunErasureMintsACorrectedVersionRatherThanEditingInPlace(t, ctx, fixture)
})
}
// TestEpochContract wires this leg into the R20 epoch contract. Same Phase 0
// all-nil state as TestRetentionContract above.
func TestEpochContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.EpochFixture{IssuePrefix: "epch"}
t.Run("AnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange", func(t *testing.T) {
conformance.RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t, ctx, fixture)
})
t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) {
conformance.RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture)
})
}

View file

@ -307,6 +307,7 @@ var _ storage.Compactor = (*DoltStore)(nil)
var _ storage.SchemaMigrator = (*DoltStore)(nil)
var _ storage.ExternalRefHistoryQuerier = (*DoltStore)(nil)
var _ storage.EventsJournalConfigurer = (*DoltStore)(nil)
var _ storage.VersionedHistoryConfigurer = (*DoltStore)(nil)
// DoltStore implements the Storage interface using Dolt
type DoltStore struct {
@ -318,12 +319,16 @@ type DoltStore struct {
// eventsJournalEnabled activates the durable events journal for THIS store
// instance only (storage.EventsJournalConfigurer); never process-global.
eventsJournalEnabled atomic.Bool
connStr string // Connection string for reconnection
cfg *Config // Config this store was opened with (rebuildPoolAfterMigration)
serverEndpoint string // Exact endpoint bound to bootstrap reset authority
mu sync.RWMutex // Protects concurrent access
readOnly bool // True if opened in read-only mode
credentialKey []byte // Random encryption key for federation credentials
// versionedHistoryEnabled activates dual-write issue-version history for
// THIS store instance only (storage.VersionedHistoryConfigurer); never
// process-global.
versionedHistoryEnabled atomic.Bool
connStr string // Connection string for reconnection
cfg *Config // Config this store was opened with (rebuildPoolAfterMigration)
serverEndpoint string // Exact endpoint bound to bootstrap reset authority
mu sync.RWMutex // Protects concurrent access
readOnly bool // True if opened in read-only mode
credentialKey []byte // Random encryption key for federation credentials
// localActiveDatabaseDir is the exact active database directory when this
// store instance has authoritative local filesystem access. It is resolved
@ -1236,6 +1241,8 @@ func (s *DoltStore) withWriteTx(ctx context.Context, fn func(tx *sql.Tx) error)
}
clearJournalScope := s.scopeEventsJournalTransaction(tx)
defer clearJournalScope()
clearVersionScope := s.scopeVersionedHistoryTransaction(tx)
defer clearVersionScope()
if err := fn(tx); err != nil {
return errors.Join(err, tx.Rollback())
}
@ -1254,6 +1261,16 @@ func (s *DoltStore) scopeEventsJournalTransaction(tx *sql.Tx) func() {
return issueops.ScopeEventsJournalTransaction(tx, s.eventsJournalEnabled.Load())
}
// SetVersionedHistoryEnabled activates dual-write issue-version history for
// this store instance only.
func (s *DoltStore) SetVersionedHistoryEnabled(enabled bool) {
s.versionedHistoryEnabled.Store(enabled)
}
func (s *DoltStore) scopeVersionedHistoryTransaction(tx *sql.Tx) func() {
return issueops.ScopeVersionedHistoryTransaction(tx, s.versionedHistoryEnabled.Load())
}
func (s *DoltStore) commitSQLTx(ctx context.Context, op string, tx *sql.Tx) error {
if err := tx.Commit(); err != nil {
return s.recordDoltPublicationFailure(ctx, wrapSQLCommitError(op, err))

View file

@ -110,14 +110,24 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep
table := pickDepTable(opts.UseWispsTable)
var existingType string
var existingMetadataNS sql.NullString
err := r.runner.QueryRowContext(ctx,
//nolint:gosec // G201: table and depTargetExpr are hardcoded constants
fmt.Sprintf("SELECT type FROM %s WHERE issue_id = ? AND %s = ?", table, depTargetExpr),
fmt.Sprintf("SELECT type, metadata FROM %s WHERE issue_id = ? AND %s = ?", table, depTargetExpr),
dep.IssueID, dep.DependsOnID,
).Scan(&existingType)
).Scan(&existingType, &existingMetadataNS)
switch {
case err == nil:
existingMetadata := existingMetadataNS.String
if !existingMetadataNS.Valid {
existingMetadata = "{}"
}
if existingType == string(dep.Type) {
if issueops.DependencyMetadataEqual(existingMetadata, metadata) {
// Same type, same metadata: a change-free write. Nothing is
// written and nothing is journaled (#5898 R3).
return nil
}
//nolint:gosec // G201: table and depTargetExpr are hardcoded constants
if _, err := r.runner.ExecContext(ctx,
fmt.Sprintf("UPDATE %s SET metadata = ? WHERE issue_id = ? AND %s = ?", table, depTargetExpr),
@ -127,7 +137,15 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep
}
// A same-type add refreshes edge metadata. It is an observable graph
// mutation, so emit the complete replacement edge for replay.
return issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
if err := issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return err
}
// The metadata genuinely changed, so this re-add is a real
// durable-state mutation of the source issue and mints on the
// same terms as a new edge (#5898 leg 2: "a same-type re-add
// whose metadata actually changed mints EXACTLY ONE version
// carrying the new state").
return issueops.RecordVersionInTx(ctx, r.runner, dep.IssueID, actor)
}
return &domain.DependencyTypeConflictError{
IssueID: dep.IssueID,
@ -219,15 +237,25 @@ func (r *dependencySQLRepositoryImpl) Insert(ctx context.Context, dep *types.Dep
return fmt.Errorf("db: DependencySQLRepository.Insert: recompute is_blocked: %w", err)
}
// Snapshot only after all derived blocked-state maintenance has completed.
return issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
if err := issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return err
}
// A new edge is durable state of the referencing issue: version it,
// as issueops.AddDependencyInTx does on the store legs. The same-type
// refresh returned above without minting.
return issueops.RecordVersionInTx(ctx, r.runner, dep.IssueID, actor)
}
if err := issueops.MarkIsBlockedInTx(ctx, r.runner, affectedIssues, affectedWisps); err != nil {
return fmt.Errorf("db: DependencySQLRepository.Insert: mark is_blocked (affected): %w", err)
}
// Snapshot only after all derived blocked-state maintenance has completed.
// Never gated on opts.EmitEvent: a structurally-wired edge is as real to a
// replaying consumer as one added by an explicit dep verb.
return issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
// replaying consumer as one added by an explicit dep verb — and neither is
// the version row minted beside it.
if err := issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, dep.IssueID, actor)
}
// classifyMissingEndpoint names the endpoint behind a foreign-key refusal,
@ -393,6 +421,12 @@ func (r *dependencySQLRepositoryImpl) Delete(ctx context.Context, issueID, depen
if err := issueops.RecordDepEventInTx(ctx, r.runner, issueops.EventDepRemove, issueID, depType, dependsOnID, depMetadata, actor); err != nil {
return domain.DepDeleteResult{}, err
}
// The Found:false return above keeps this actually-deleted-only, so the
// referencing issue is versioned for a real change, as
// issueops.RemoveDependencyInTx does on the store legs.
if err := issueops.RecordVersionInTx(ctx, r.runner, issueID, actor); err != nil {
return domain.DepDeleteResult{}, err
}
return domain.DepDeleteResult{Found: true, Type: dt, DependsOnID: dependsOnID}, nil
}

View file

@ -0,0 +1,57 @@
package db
import (
"regexp"
"testing"
sqlmock "github.com/DATA-DOG/go-sqlmock"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
func newMockDependencyRepo(t *testing.T) (sqlmock.Sqlmock, *dependencySQLRepositoryImpl) {
t.Helper()
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("sqlmock.New: %v", err)
}
t.Cleanup(func() { _ = db.Close() })
return mock, &dependencySQLRepositoryImpl{runner: db}
}
// TestDependencyInsertReadsNullStoredMetadataAsEmptyObject is the serve-mode
// twin of issueops.TestAddDependencyInTxReadsNullStoredMetadataAsEmptyObject.
// The change-free re-add gate widened this SELECT from `type` to `type,
// metadata` on both write planes, and `dependencies.metadata` is nullable
// (`JSON DEFAULT (JSON_OBJECT())`, no NOT NULL), so a row written out of band
// -- bd sql, an external tool, hand SQL -- can hold NULL. Scanning NULL into a
// plain string hard-fails with "converting NULL to string is unsupported",
// which would turn every subsequent re-add of that edge into an error on a
// path that used to be idempotently happy. NULL is the absent-metadata state,
// so it reads as `{}` and the change-free re-add of a metadata-free edge stays
// the no-op it was.
//
// The repair landed on both planes; without this the two planes are pinned
// asymmetrically and a revert of the serve-mode scan alone has nothing red to
// catch it.
func TestDependencyInsertReadsNullStoredMetadataAsEmptyObject(t *testing.T) {
mock, repo := newMockDependencyRepo(t)
mock.ExpectQuery(regexp.QuoteMeta("SELECT type, metadata FROM dependencies")).
WithArgs("dep-a", "dep-b").
WillReturnRows(sqlmock.NewRows([]string{"type", "metadata"}).AddRow(string(types.DepRelated), nil))
dep := &types.Dependency{IssueID: "dep-a", DependsOnID: "dep-b", Type: types.DepRelated}
// DepRelated is not a scheduling edge and the hierarchy check is declared
// done, so the widened gate SELECT is the only statement this call reaches.
err := repo.Insert(t.Context(), dep, "writer", domain.DepInsertOpts{HierarchyValidated: true})
if err != nil {
t.Fatalf("Insert(existing edge with NULL metadata) = %v, want nil: a change-free re-add is a no-op, not an error", err)
}
// Scripting only the one read means any UPDATE or journal write this path
// attempted would fail the run: the no-op is pinned, not merely the
// absence of an error.
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}

View file

@ -81,7 +81,10 @@ func (r *issueSQLRepositoryImpl) Insert(ctx context.Context, issue *types.Issue,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
return issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor)
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issue.ID, actor)
}
if err := insertIssueRow(ctx, r.runner, table, issue); err != nil {
return err
@ -93,7 +96,10 @@ func (r *issueSQLRepositoryImpl) Insert(ctx context.Context, issue *types.Issue,
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
return issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor)
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventCreate, issue.ID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issue.ID, actor)
}
func (r *issueSQLRepositoryImpl) InsertBatch(ctx context.Context, issues []*types.Issue, actor string, opts domain.InsertIssueOpts) error {
@ -327,7 +333,10 @@ func (r *issueSQLRepositoryImpl) Update(ctx context.Context, id string, updates
}
// Snapshot only after all derived blocked-state maintenance has completed.
// The no-op early returns above wrote nothing and journal nothing.
return issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, id, actor)
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, id, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, id, actor)
}
// CompareAndSetMetadataKey runs the SHARED compare-and-set body, unwrapped.
@ -534,10 +543,14 @@ func (r *issueSQLRepositoryImpl) Claim(ctx context.Context, id, actor string, op
return domain.ClaimRowResult{}, fmt.Errorf("db: Claim %s: record event: %w", id, err)
}
// A claim changes assignee and status; the lost-CAS path returns above
// without writing and journals nothing.
// without writing and journals nothing — nor mints anything. A claim that
// rewrote the row is versioned, as issueops.ClaimIssueInTx is.
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, id, actor); err != nil {
return domain.ClaimRowResult{}, err
}
if err := issueops.RecordVersionInTx(ctx, r.runner, id, actor); err != nil {
return domain.ClaimRowResult{}, err
}
return domain.ClaimRowResult{
Updated: true,

View file

@ -83,8 +83,12 @@ func (r *labelSQLRepositoryImpl) Insert(ctx context.Context, issueID, label, act
return err
}
// A label is part of the bead snapshot; the idempotent no-op path above
// returns without writing and journals nothing.
return issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, issueID, actor)
// returns without writing, journals nothing and mints nothing. An inserted
// row is a durable-state change and is versioned, as AddLabelInTx does.
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, issueID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issueID, actor)
}
func (r *labelSQLRepositoryImpl) Delete(ctx context.Context, issueID, label, actor string, opts domain.LabelOpts) error {
@ -118,7 +122,12 @@ func (r *labelSQLRepositoryImpl) Delete(ctx context.Context, issueID, label, act
}, domain.RecordEventOpts{UseWispsTable: opts.UseWispsTable}); err != nil {
return err
}
return issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, issueID, actor)
// The rows == 0 return above keeps this actually-deleted-only, so the
// version row is minted for a real change, as RemoveLabelInTx does.
if err := issueops.RecordEventInTx(ctx, r.runner, issueops.EventUpdate, issueID, actor); err != nil {
return err
}
return issueops.RecordVersionInTx(ctx, r.runner, issueID, actor)
}
func (r *labelSQLRepositoryImpl) List(ctx context.Context, issueID string, opts domain.LabelOpts) ([]string, error) {

View file

@ -0,0 +1,43 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestCrossRecordInvariantContract wires this leg into the R16.1
// cross-record invariant contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestCrossRecordInvariantContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.CrossRecordInvariantFixture{IssuePrefix: "xrec"}
t.Run("SurvivesTwoPassingPerRecordGuards", func(t *testing.T) {
conformance.RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards(t, ctx, fixture)
})
t.Run("StoreInvariantTransactionScopesExactlyTheSpanningRecords", func(t *testing.T) {
conformance.RunStoreInvariantTransactionScopesExactlyTheSpanningRecords(t, ctx, fixture)
})
t.Run("InvariantRefusalNamesTheViolatedInvariant", func(t *testing.T) {
conformance.RunInvariantRefusalNamesTheViolatedInvariant(t, ctx, fixture)
})
t.Run("MemoryKeyAliasUniquenessIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("MaximumEndpointMultiplicityIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("AdvisoryLeaseAloneDoesNotPreventTheInvariantViolation", func(t *testing.T) {
conformance.RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation(t, ctx, fixture)
})
t.Run("LeaseAcquisitionRecordsNoHistoryEntry", func(t *testing.T) {
conformance.RunLeaseAcquisitionRecordsNoHistoryEntry(t, ctx, fixture)
})
}

View file

@ -45,6 +45,18 @@ func TestEmbeddedDependencyEditorSameTypeReAddIsIdempotent(t *testing.T) {
conformance.RunDependencyEditorSameTypeReAddIsIdempotent(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "idem"))
}
func TestEmbeddedDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
conformance.RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "idemmeta"))
}
func TestEmbeddedDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
conformance.RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp(t, ctx, newEmbeddedDependencyEditorFixture(t, ctx, "idemmetasame"))
}
func TestEmbeddedDependencyEditorRepeatsWithinOneRequestCollapse(t *testing.T) {
skipUnlessEmbeddedDolt(t)
ctx := t.Context()
@ -255,12 +267,14 @@ func newEmbeddedDependencyEditorFixture(t *testing.T, ctx context.Context, prefi
}
kit := newEmbeddedRoleFixtureKit(te, prefix)
return conformance.DependencyEditorFixture{
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
SetJournalEnabled: te.store.SetEventsJournalEnabled,
SetVersionedHistoryEnabled: te.store.SetVersionedHistoryEnabled,
}
}

View file

@ -0,0 +1,113 @@
//go:build cgo
package embeddeddolt_test
import (
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// TestEmbeddedDependencyEditorVersionsOnlyARealAddOrRemove is the FOURTH
// ADDENDUM's own no-op-detection clause (design bead be-0uifx): the
// dependency editor is the one RecordVersionInTx caller not already
// short-circuited by DiscardNoopIssueUpdates, so it must draw its own R3
// exemption from the eventWritten signal AddDependencyInTx/
// RemoveDependencyInTx already return. This is an ENGINE CHECK on the shared
// internal/storage/issueops call sites (addDependencyEdgeInTx,
// ExecuteRemoveDependency) rather than a per-backend vote — see
// TestDualWriteContract's own doc comment for why one leg is proof for all
// three here, since dolt and uow route through the identical issueops
// functions.
//
// It asserts by DELTA against the source issue's own version-row count
// rather than an absolute value, so it stays correct regardless of how many
// rows the two CreateIssue seeds above it already minted.
func TestEmbeddedDependencyEditorVersionsOnlyARealAddOrRemove(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "depver")
ctx := t.Context()
configurer, ok := any(te.store).(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", te.store)
}
configurer.SetVersionedHistoryEnabled(true)
kit := newEmbeddedRoleFixtureKit(te, "depver")
source := kit.IssuePrefix + "-src"
target := kit.IssuePrefix + "-tgt"
for _, id := range []string{source, target} {
if err := kit.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "seed"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
}
editor, err := te.store.DependencyEditor()
if err != nil {
t.Fatalf("DependencyEditor(): %v", err)
}
versionRowCount := func(id string) int {
t.Helper()
var count int
if err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count); err != nil {
t.Fatalf("QueryScalar(issue_versions count for %s): %v", id, err)
}
return count
}
sourceBefore := versionRowCount(source)
targetBefore := versionRowCount(target)
if _, err := editor.AddDependencies(ctx, issueops.AddDependenciesRequest{
Actor: "actor",
Edges: []issueops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: issueops.DepBlocks}},
}); err != nil {
t.Fatalf("AddDependencies (real add): %v", err)
}
afterAdd := versionRowCount(source)
if afterAdd != sourceBefore+1 {
t.Fatalf("real add: source version rows = %d, want %d (before %d)", afterAdd, sourceBefore+1, sourceBefore)
}
if got := versionRowCount(target); got != targetBefore {
t.Fatalf("real add: target (non-referencing side) version rows = %d, want unchanged %d", got, targetBefore)
}
// Idempotent same-type re-add: AddDependencyInTx reports eventWritten
// false, so this must not mint a second row (R3).
if _, err := editor.AddDependencies(ctx, issueops.AddDependenciesRequest{
Actor: "actor",
Edges: []issueops.DependencyEdge{{IssueID: source, DependsOnID: target, Type: issueops.DepBlocks}},
}); err != nil {
t.Fatalf("AddDependencies (idempotent re-add): %v", err)
}
if got := versionRowCount(source); got != afterAdd {
t.Fatalf("idempotent re-add: source version rows = %d, want unchanged %d", got, afterAdd)
}
if _, err := editor.RemoveDependency(ctx, issueops.RemoveDependencyRequest{
Actor: "actor", IssueID: source, DependsOnID: target,
}); err != nil {
t.Fatalf("RemoveDependency (real remove): %v", err)
}
afterRemove := versionRowCount(source)
if afterRemove != afterAdd+1 {
t.Fatalf("real remove: source version rows = %d, want %d", afterRemove, afterAdd+1)
}
// Absent edge: RemoveDependencyInTx reports eventWritten false and
// Removed false, so this must not mint a third row (R3).
if _, err := editor.RemoveDependency(ctx, issueops.RemoveDependencyRequest{
Actor: "actor", IssueID: source, DependsOnID: target,
}); err != nil {
t.Fatalf("RemoveDependency (already-absent): %v", err)
}
if got := versionRowCount(source); got != afterRemove {
t.Fatalf("absent remove: source version rows = %d, want unchanged %d", got, afterRemove)
}
}

View file

@ -0,0 +1,133 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// TestDualWriteContract runs the dual-write history contract against the
// embedded store, which reaches issueops mutation entrypoints through its own
// per-operation connection. All three legs share RecordVersionInTx's one
// body, so this is an ENGINE CHECK rather than an independent vote — what it
// can actually catch here is a wrapper that loses the transaction the
// version row must land in, or a backend that stops implementing the seam
// at all.
func TestDualWriteContract(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "dwc")
ctx := t.Context()
fixture := newEmbeddedDualWriteFixture(t, te, "dwc", true)
t.Run("MintsOneVersionRowPerAcceptedMutation", func(t *testing.T) {
conformance.RunDualWriteMintsOneVersionRowPerAcceptedMutation(t, ctx, fixture)
})
t.Run("NoOpMutationMintsNoRow", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationMintsNoRow(t, ctx, fixture)
})
t.Run("AttributionIsRecordedWithTheMutation", func(t *testing.T) {
conformance.RunDualWriteAttributionIsRecordedWithTheMutation(t, ctx, fixture)
})
t.Run("CurrentRevisionMatchesTheNewVersionRow", func(t *testing.T) {
conformance.RunDualWriteCurrentRevisionMatchesTheNewVersionRow(t, ctx, fixture)
})
t.Run("NoOpMutationLeavesThePriorVersionRowUnperturbed", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed(t, ctx, fixture)
})
}
// TestDualWriteContractFlagOff runs FR-7 against an environment constructed
// with the flag OFF from the start — its own environment, not a shared one,
// so "flag off" means what FR-7 promises rather than "not yet turned on this
// session".
func TestDualWriteContractFlagOff(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "dwcoff")
ctx := t.Context()
fixture := newEmbeddedDualWriteFixture(t, te, "dwcoff", false)
t.Run("FlagOffProducesNoVersionRows", func(t *testing.T) {
conformance.RunDualWriteFlagOffProducesNoVersionRows(t, ctx, fixture)
})
}
// TestDualWriteFixtureKitIsWired is this leg's half of the explicit per-leg
// guardrail design §8.5 calls for in place of AST auto-discovery — see the
// dolt leg's TestDualWriteFixtureKitIsWired for why the guardrail is needed
// even though TestEveryLegWiresEveryRoleContract's scan already enumerates
// and confirms wiring for all six RunDualWriteXxx entrypoints.
func TestDualWriteFixtureKitIsWired(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "dwk")
fixture := newEmbeddedDualWriteFixture(t, te, "dwk", true)
if fixture.Mutate == nil {
t.Error("DualWriteFixture.Mutate is nil")
}
if fixture.MutateAsNoOp == nil {
t.Error("DualWriteFixture.MutateAsNoOp is nil")
}
if fixture.CurrentRevision == nil {
t.Error("DualWriteFixture.CurrentRevision is nil")
}
if fixture.VersionRowCount == nil {
t.Error("DualWriteFixture.VersionRowCount is nil")
}
if fixture.LatestVersionAttribution == nil {
t.Error("DualWriteFixture.LatestVersionAttribution is nil")
}
}
func newEmbeddedDualWriteFixture(t *testing.T, te *testEnv, prefix string, enabled bool) conformance.DualWriteFixture {
t.Helper()
store := te.store
// Through the type assertion `bd serve` makes, never the concrete method
// set: dual-write history is not on storage.DoltStorage, so publishing it
// IS implementing this interface, matching newEmbeddedJournalFixture's own
// discipline for storage.EventsJournalCursor above.
configurer, ok := any(store).(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", store)
}
configurer.SetVersionedHistoryEnabled(enabled)
kit := newEmbeddedRoleFixtureKit(te, prefix)
return conformance.DualWriteFixture{
IssuePrefix: prefix,
Mutate: func(ctx context.Context, id string) error {
return store.CreateIssue(ctx, &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
}, "actor")
},
MutateAsNoOp: func(ctx context.Context, id string) error {
// Re-sets title to the exact value Mutate already gave it, so
// issueops.DiscardNoopIssueUpdates discards it before it ever
// reaches RecordVersionInTx.
return store.UpdateIssue(ctx, id, map[string]any{"title": "t-" + id}, "actor")
},
CurrentRevision: func(ctx context.Context, id string) (int64, error) {
var revision int64
err := kit.QueryScalar(ctx, "SELECT current_revision FROM issues WHERE id = ?", []any{id}, &revision)
return revision, err
},
VersionRowCount: func(ctx context.Context, id string) (int, error) {
var count int
err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count)
return count, err
},
LatestVersionAttribution: func(ctx context.Context, id string) (actor, agent, message string, err error) {
err = kit.QueryScalar(ctx, `
SELECT COALESCE(change_actor, ''), COALESCE(change_agent, ''), COALESCE(change_message, '')
FROM issue_versions
WHERE issue_id = ?
ORDER BY revision DESC
LIMIT 1`, []any{id}, &actor, &agent, &message)
return actor, agent, message, err
},
}
}

View file

@ -0,0 +1,52 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestExpectedRevisionContract wires this leg into the R16/R17
// expected-revision contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestExpectedRevisionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.ExpectedRevisionFixture{IssuePrefix: "erev"}
t.Run("AcceptsAWriteNamingTheCurrentVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t, ctx, fixture)
})
t.Run("AcceptsAWriteNamingNoVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingNoVersion(t, ctx, fixture)
})
t.Run("CoversFieldsOutsideAnyWatchedSubset", func(t *testing.T) {
conformance.RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionAddress", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionAddress(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionsChangeAttribution", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionsChangeAttribution(t, ctx, fixture)
})
t.Run("RefusalIsATypedOutcomeNotAGenericError", func(t *testing.T) {
conformance.RunRefusalIsATypedOutcomeNotAGenericError(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromAnAcceptedWrite", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromAnAcceptedWrite(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromNotFound", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromNotFound(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromValidationFailure", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromValidationFailure(t, ctx, fixture)
})
t.Run("RefusalNeverSilentlyPicksAWinner", func(t *testing.T) {
conformance.RunRefusalNeverSilentlyPicksAWinner(t, ctx, fixture)
})
}

View file

@ -0,0 +1,74 @@
//go:build cgo
package embeddeddolt_test
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestRetentionContract wires this leg into the R20 retention contract.
// Phase 0 leaves every hook nil in every backend's fixture kit (architecture
// §12), so each case below skips by name; this file exists so
// TestEveryLegWiresEveryRoleContract counts this leg, and so the cases start
// running for real the moment this leg's fixture kit grows a non-nil hook.
func TestRetentionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.RetentionFixture{IssuePrefix: "rete"}
t.Run("RemovalLeavesTheAddressAbleToAnswer", func(t *testing.T) {
conformance.RunRemovalLeavesTheAddressAbleToAnswer(t, ctx, fixture)
})
t.Run("RemovalReasonIsRetentionErasureOrReorganizationDistinctly", func(t *testing.T) {
conformance.RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly(t, ctx, fixture)
})
t.Run("RemovalReportsTheSurvivingRetainedWindow", func(t *testing.T) {
conformance.RunRemovalReportsTheSurvivingRetainedWindow(t, ctx, fixture)
})
t.Run("RemovalNeverReassignsASurvivingAddress", func(t *testing.T) {
conformance.RunRemovalNeverReassignsASurvivingAddress(t, ctx, fixture)
})
t.Run("GoneIsDistinguishableFromUnknown", func(t *testing.T) {
conformance.RunGoneIsDistinguishableFromUnknown(t, ctx, fixture)
})
t.Run("AnAddressNeverResolvesToADifferentState", func(t *testing.T) {
conformance.RunAnAddressNeverResolvesToADifferentState(t, ctx, fixture)
})
t.Run("ADestructiveOperationEnumeratesAffectedAddressesFirst", func(t *testing.T) {
conformance.RunADestructiveOperationEnumeratesAffectedAddressesFirst(t, ctx, fixture)
})
t.Run("AHoldPreventsRemovalAndReportsInRetainedBounds", func(t *testing.T) {
conformance.RunAHoldPreventsRemovalAndReportsInRetainedBounds(t, ctx, fixture)
})
t.Run("ForcingAHeldRemovalRecordsWhoWhenWhy", func(t *testing.T) {
conformance.RunForcingAHeldRemovalRecordsWhoWhenWhy(t, ctx, fixture)
})
t.Run("EveryRetentionAnswerNamesItsProducingStore", func(t *testing.T) {
conformance.RunEveryRetentionAnswerNamesItsProducingStore(t, ctx, fixture)
})
t.Run("AStoreWithNoLineageKnowledgeAnswersUnknownNotGone", func(t *testing.T) {
conformance.RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone(t, ctx, fixture)
})
t.Run("AStoreThatRemovesStateStillAnswersGoneDurably", func(t *testing.T) {
conformance.RunAStoreThatRemovesStateStillAnswersGoneDurably(t, ctx, fixture)
})
t.Run("ErasureMintsACorrectedVersionRatherThanEditingInPlace", func(t *testing.T) {
conformance.RunErasureMintsACorrectedVersionRatherThanEditingInPlace(t, ctx, fixture)
})
}
// TestEpochContract wires this leg into the R20 epoch contract. Same Phase 0
// all-nil state as TestRetentionContract above.
func TestEpochContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.EpochFixture{IssuePrefix: "epch"}
t.Run("AnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange", func(t *testing.T) {
conformance.RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t, ctx, fixture)
})
t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) {
conformance.RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture)
})
}

View file

@ -32,6 +32,7 @@ var _ storage.Flattener = (*EmbeddedDoltStore)(nil)
var _ storage.Compactor = (*EmbeddedDoltStore)(nil)
var _ storage.SchemaMigrator = (*EmbeddedDoltStore)(nil)
var _ storage.EventsJournalConfigurer = (*EmbeddedDoltStore)(nil)
var _ storage.VersionedHistoryConfigurer = (*EmbeddedDoltStore)(nil)
var _ storage.ExternalRefHistoryQuerier = (*EmbeddedDoltStore)(nil)
// EmbeddedDoltStore implements storage.DoltStorage backed by the embedded Dolt engine.
@ -52,6 +53,10 @@ type EmbeddedDoltStore struct {
// eventsJournalEnabled activates the durable events journal for THIS store
// instance only (storage.EventsJournalConfigurer); never process-global.
eventsJournalEnabled atomic.Bool
// versionedHistoryEnabled activates dual-write issue-version history for
// THIS store instance only (storage.VersionedHistoryConfigurer); never
// process-global.
versionedHistoryEnabled atomic.Bool
// readOnly marks a store opened via OpenReadOnly or
// OpenForPreviewCommand: open-time mutations (CREATE DATABASE, schema
// migrations) were skipped and write transactions are refused
@ -392,6 +397,8 @@ func (s *EmbeddedDoltStore) withConn(ctx context.Context, commit bool, fn func(t
}
clearJournalScope := issueops.ScopeEventsJournalTransaction(tx, s.eventsJournalEnabled.Load())
defer clearJournalScope()
clearVersionScope := issueops.ScopeVersionedHistoryTransaction(tx, s.versionedHistoryEnabled.Load())
defer clearVersionScope()
if fnErr := fn(tx); fnErr != nil {
err = errors.Join(fnErr, tx.Rollback())
@ -416,6 +423,12 @@ func (s *EmbeddedDoltStore) SetEventsJournalEnabled(enabled bool) {
s.eventsJournalEnabled.Store(enabled)
}
// SetVersionedHistoryEnabled activates dual-write issue-version history for
// this store instance only.
func (s *EmbeddedDoltStore) SetVersionedHistoryEnabled(enabled bool) {
s.versionedHistoryEnabled.Store(enabled)
}
// commitEmbeddedTx classifies an unconfirmed SQL commit response as
// indeterminate: the engine may have applied it before the connection failed.
func commitEmbeddedTx(tx *sql.Tx) error {

View file

@ -0,0 +1,311 @@
//go:build cgo
package embeddeddolt_test
import (
"encoding/json"
"testing"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/issueops"
)
// These tests are the RUNTIME twin of issueops' version_completeness_test.go,
// which pins by static analysis that every issue-plane mutation reaches
// RecordVersionInTx. That guard cannot see whether the mint actually lands —
// that INSERT IGNORE reports zero affected rows for a duplicate label on this
// engine, that a closed row can still be snapshotted, that a batch create's
// deferred mint runs after its edges — so the law is exercised here once,
// flag on, on the in-process leg: every accepted mutation mints exactly one
// version row, a no-op mints none, and current_revision always equals the
// row count (FR-1, FR-2, FR-5 of #6135). It is an ENGINE CHECK on the shared
// issueops bodies, like TestEmbeddedDependencyEditorVersionsOnlyARealAddOrRemove
// beside it: the dolt and uow legs run the same functions.
//
// Every assertion is a DELTA against the issue's own version-row count, so
// the cases stay correct regardless of how many rows their seeds minted.
type versionProbe struct {
t *testing.T
kit roleFixtureKit
}
func newVersionProbe(t *testing.T, te *testEnv, prefix string) versionProbe {
t.Helper()
configurer, ok := any(te.store).(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("%T does not implement storage.VersionedHistoryConfigurer", te.store)
}
configurer.SetVersionedHistoryEnabled(true)
return versionProbe{t: t, kit: newEmbeddedRoleFixtureKit(te, prefix)}
}
func (p versionProbe) rows(id string) int {
p.t.Helper()
var count int
if err := p.kit.QueryScalar(p.t.Context(), "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count); err != nil {
p.t.Fatalf("count issue_versions for %s: %v", id, err)
}
return count
}
func (p versionProbe) currentRevision(id string) int {
p.t.Helper()
var revision int
if err := p.kit.QueryScalar(p.t.Context(), "SELECT current_revision FROM issues WHERE id = ?", []any{id}, &revision); err != nil {
p.t.Fatalf("read current_revision for %s: %v", id, err)
}
return revision
}
// latestState decodes the highest-revision durable_state for id.
func (p versionProbe) latestState(id string) map[string]any {
p.t.Helper()
var raw string
if err := p.kit.QueryScalar(p.t.Context(),
"SELECT durable_state FROM issue_versions WHERE issue_id = ? ORDER BY revision DESC LIMIT 1",
[]any{id}, &raw); err != nil {
p.t.Fatalf("read latest durable_state for %s: %v", id, err)
}
var state map[string]any
if err := json.Unmarshal([]byte(raw), &state); err != nil {
p.t.Fatalf("decode durable_state for %s: %v\n%s", id, err, raw)
}
return state
}
// expect asserts the version-row count of id moved from before by delta and
// returns the new count, so the steps of a scenario chain.
func (p versionProbe) expect(step, id string, before, delta int) int {
p.t.Helper()
got := p.rows(id)
if got != before+delta {
p.t.Fatalf("%s: version rows for %s = %d, want %d (before %d, delta %+d)", step, id, got, before+delta, before, delta)
}
return got
}
// revisionMatchesRows pins FR-5 for id: current_revision is nothing but the
// count of rows RecordVersionInTx has minted.
func (p versionProbe) revisionMatchesRows(id string) {
p.t.Helper()
if rev, n := p.currentRevision(id), p.rows(id); rev != n {
p.t.Fatalf("current_revision for %s = %d but it has %d version row(s)", id, rev, n)
}
}
func dependencyTargets(t *testing.T, state map[string]any) []string {
t.Helper()
raw, _ := state["dependencies"].([]any)
targets := make([]string, 0, len(raw))
for _, dep := range raw {
m, _ := dep.(map[string]any)
target, _ := m["depends_on_id"].(string)
targets = append(targets, target)
}
return targets
}
func labelsOf(state map[string]any) []string {
raw, _ := state["labels"].([]any)
labels := make([]string, 0, len(raw))
for _, l := range raw {
s, _ := l.(string)
labels = append(labels, s)
}
return labels
}
// TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion walks the
// lifecycle verbs the write-path inventory found unversioned — claim, release,
// label add/remove, the legacy dependency verbs, close and reopen — and pins
// one row per accepted change and none for each verb's no-op shape.
func TestEmbeddedEveryAcceptedLifecycleMutationMintsOneVersion(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "vermint")
ctx := t.Context()
p := newVersionProbe(t, te, "vermint")
store := te.store
a, b := p.kit.IssuePrefix+"-a", p.kit.IssuePrefix+"-b"
for _, id := range []string{a, b} {
if err := p.kit.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "seed"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
}
na := p.expect("seed", a, 0, 1)
nb := p.expect("seed", b, 0, 1)
// claim: one row for the CAS that wrote assignee/status/started_at; the
// idempotent re-claim by the same actor returns without writing.
if err := store.ClaimIssue(ctx, a, "worker"); err != nil {
t.Fatalf("ClaimIssue: %v", err)
}
na = p.expect("claim", a, na, 1)
if err := store.ClaimIssue(ctx, a, "worker"); err != nil {
t.Fatalf("ClaimIssue (idempotent re-claim): %v", err)
}
na = p.expect("idempotent re-claim", a, na, 0)
// release: assignee and status revert.
if err := store.UnclaimIssue(ctx, a, "worker", false); err != nil {
t.Fatalf("UnclaimIssue: %v", err)
}
na = p.expect("unclaim", a, na, 1)
// labels: INSERT IGNORE on an existing label and DELETE of an absent one
// are the no-op shapes.
if err := store.AddLabel(ctx, a, "l1", "actor"); err != nil {
t.Fatalf("AddLabel: %v", err)
}
na = p.expect("add label", a, na, 1)
if labels := labelsOf(p.latestState(a)); len(labels) != 1 || labels[0] != "l1" {
t.Fatalf("add label: latest durable_state labels = %v, want [l1]", labels)
}
if err := store.AddLabel(ctx, a, "l1", "actor"); err != nil {
t.Fatalf("AddLabel (duplicate): %v", err)
}
na = p.expect("duplicate add label", a, na, 0)
if err := store.RemoveLabel(ctx, a, "l1", "actor"); err != nil {
t.Fatalf("RemoveLabel: %v", err)
}
na = p.expect("remove label", a, na, 1)
if err := store.RemoveLabel(ctx, a, "l1", "actor"); err != nil {
t.Fatalf("RemoveLabel (absent): %v", err)
}
na = p.expect("absent remove label", a, na, 0)
// the legacy store dependency verbs (no DependencyEditor role): the
// referencing issue versions, the target does not.
if err := store.AddDependency(ctx, &types.Dependency{IssueID: a, DependsOnID: b, Type: types.DepBlocks}, "actor"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
na = p.expect("legacy dep add", a, na, 1)
nb = p.expect("legacy dep add (target)", b, nb, 0)
if targets := dependencyTargets(t, p.latestState(a)); len(targets) != 1 || targets[0] != b {
t.Fatalf("legacy dep add: latest durable_state dependencies = %v, want [%s]", targets, b)
}
if err := store.RemoveDependency(ctx, a, b, "actor"); err != nil {
t.Fatalf("RemoveDependency: %v", err)
}
na = p.expect("legacy dep remove", a, na, 1)
if targets := dependencyTargets(t, p.latestState(a)); len(targets) != 0 {
t.Fatalf("legacy dep remove: latest durable_state dependencies = %v, want none", targets)
}
// close, including the WithoutEvent-style idempotent already-closed
// return, then reopen.
if err := store.CloseIssue(ctx, a, "done", "actor", ""); err != nil {
t.Fatalf("CloseIssue: %v", err)
}
na = p.expect("close", a, na, 1)
if status, _ := p.latestState(a)["status"].(string); status != string(types.StatusClosed) {
t.Fatalf("close: latest durable_state status = %q, want closed", status)
}
if err := store.CloseIssue(ctx, a, "done", "actor", ""); err != nil {
t.Fatalf("CloseIssue (already closed): %v", err)
}
na = p.expect("already-closed close", a, na, 0)
if err := store.ReopenIssue(ctx, a, "", "actor"); err != nil {
t.Fatalf("ReopenIssue: %v", err)
}
p.expect("reopen", a, na, 1)
p.revisionMatchesRows(a)
p.revisionMatchesRows(b)
}
// TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges pins the
// batch-create ordering fix: the one version minted at creation is minted
// AFTER PersistDependenciesWithOptionsResult, so it carries the outgoing edge
// set, and the dependency pass mints nothing of its own.
func TestEmbeddedBatchCreateFirstVersionCarriesCreationTimeEdges(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "vercreate")
ctx := t.Context()
p := newVersionProbe(t, te, "vercreate")
src, tgt := p.kit.IssuePrefix+"-src", p.kit.IssuePrefix+"-tgt"
issues := []*types.Issue{
{ID: src, Title: src, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
Dependencies: []*types.Dependency{{IssueID: src, DependsOnID: tgt, Type: types.DepBlocks}}},
{ID: tgt, Title: tgt, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
if err := te.store.CreateIssues(ctx, issues, "actor"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
p.expect("batch create", src, 0, 1)
p.expect("batch create", tgt, 0, 1)
if targets := dependencyTargets(t, p.latestState(src)); len(targets) != 1 || targets[0] != tgt {
t.Fatalf("batch create: the first version's durable_state dependencies = %v, want [%s]: "+
"the mint must run after the creation-time edges are persisted", targets, tgt)
}
p.revisionMatchesRows(src)
p.revisionMatchesRows(tgt)
}
// TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches pins the ExecuteUpdate
// ordering fix: a guarded update carrying a field edit, a label patch and a
// parent patch mints ONE version, whose durable_state carries all three, and
// a guarded update that changes nothing mints none.
func TestEmbeddedGuardedUpdateMintsOnceAfterItsPatches(t *testing.T) {
skipUnlessEmbeddedDolt(t)
te := newTestEnv(t, "verupd")
ctx := t.Context()
p := newVersionProbe(t, te, "verupd")
child, parent := p.kit.IssuePrefix+"-child", p.kit.IssuePrefix+"-parent"
for _, id := range []string{child, parent} {
if err := p.kit.CreateIssue(ctx, &types.Issue{
ID: id, Title: id, Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask,
}, "seed"); err != nil {
t.Fatalf("CreateIssue(%s): %v", id, err)
}
}
lifecycle, err := te.store.IssueLifecycle()
if err != nil {
t.Fatalf("IssueLifecycle(): %v", err)
}
n := p.rows(child)
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "actor", IssueID: child,
Patch: issueops.IssuePatch{
Title: issueops.Field[string]{Set: true, Value: "renamed"},
Labels: issueops.LabelPatch{Add: []string{"patched"}},
ParentID: issueops.Field[string]{Set: true, Value: parent},
},
}); err != nil {
t.Fatalf("Lifecycle.Update: %v", err)
}
n = p.expect("guarded update with field + label + parent patches", child, n, 1)
state := p.latestState(child)
if title, _ := state["title"].(string); title != "renamed" {
t.Fatalf("guarded update: durable_state title = %q, want renamed", title)
}
if labels := labelsOf(state); len(labels) != 1 || labels[0] != "patched" {
t.Fatalf("guarded update: durable_state labels = %v, want [patched]: the label patch must land before the mint", labels)
}
if targets := dependencyTargets(t, state); len(targets) != 1 || targets[0] != parent {
t.Fatalf("guarded update: durable_state dependencies = %v, want [%s]: the parent patch must land before the mint", targets, parent)
}
// The same request again changes nothing: the field is a no-op, the label
// set already matches and the parent is already set.
if _, err := lifecycle.Update(ctx, issueops.UpdateRequest{
Actor: "actor", IssueID: child,
Patch: issueops.IssuePatch{
Title: issueops.Field[string]{Set: true, Value: "renamed"},
Labels: issueops.LabelPatch{Add: []string{"patched"}},
ParentID: issueops.Field[string]{Set: true, Value: parent},
},
}); err != nil {
t.Fatalf("Lifecycle.Update (no-op): %v", err)
}
p.expect("no-op guarded update", child, n, 0)
p.revisionMatchesRows(child)
p.revisionMatchesRows(parent)
}

View file

@ -286,7 +286,17 @@ func metadataChanged(current, next json.RawMessage) (bool, error) {
}
// ApplyLabelPatch applies ordered label edits and reports whether rows changed.
// A patch that changed the label set mints ONE version row for the issue,
// after every label row it wrote; a patch that leaves the set as it was mints
// nothing.
func ApplyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch publicops.LabelPatch, actor string) (bool, error) {
return applyLabelPatch(ctx, tx, current, patch, actor, true)
}
// applyLabelPatch is the body of ApplyLabelPatch. mintVersion controls whether
// the patch mints its own version row; ExecuteUpdate passes false and mints
// once for the whole guarded update after its last patch.
func applyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch publicops.LabelPatch, actor string, mintVersion bool) (bool, error) {
if !patch.Replace.Set && len(patch.Add) == 0 && len(patch.Remove) == 0 {
return false, nil
}
@ -333,13 +343,21 @@ func ApplyLabelPatch(ctx context.Context, tx DBTX, current *types.Issue, patch p
if !ok {
return false, fmt.Errorf("apply labels: transaction must be *sql.Tx")
}
// The per-label helpers run without minting: the patch is one mutation
// and is versioned once below, after the last row, so the version carries
// the complete post-patch set rather than one row per label.
for _, label := range stringSetDifference(existing, target) {
if err := RemoveLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil {
if err := removeLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor, false); err != nil {
return false, err
}
}
for _, label := range stringSetDifference(target, existing) {
if err := AddLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor); err != nil {
if err := addLabelInTx(ctx, sqlTx, "", "", current.ID, label, actor, false); err != nil {
return false, err
}
}
if mintVersion {
if err := RecordVersionInTx(ctx, tx, current.ID, actor); err != nil {
return false, err
}
}
@ -353,8 +371,17 @@ type ParentPatchResult struct {
WispRowsChanged bool
}
// ApplyParentPatch replaces the parent-child targets and reports concrete changes.
// ApplyParentPatch replaces the parent-child targets and reports concrete
// changes. A patch that rewired the parent edges mints ONE version row for the
// child (the referencing issue), after the last edge write; an unchanged
// parent set mints nothing.
func ApplyParentPatch(ctx context.Context, tx DBTX, current *types.Issue, parent publicops.Field[string], actor string) (ParentPatchResult, error) {
return applyParentPatch(ctx, tx, current, parent, actor, true)
}
// applyParentPatch is the body of ApplyParentPatch; mintVersion is
// applyLabelPatch's, for the same reason.
func applyParentPatch(ctx context.Context, tx DBTX, current *types.Issue, parent publicops.Field[string], actor string, mintVersion bool) (ParentPatchResult, error) {
if !parent.Set {
return ParentPatchResult{}, nil
}
@ -379,14 +406,21 @@ func ApplyParentPatch(ctx context.Context, tx DBTX, current *types.Issue, parent
if !ok {
return ParentPatchResult{}, fmt.Errorf("apply parent: transaction must be *sql.Tx")
}
// The edge helpers run without minting: the patch is one mutation of the
// child's edge set and is versioned once below, after the last edge.
var recomputed RecomputeIsBlockedResult
for _, parentID := range stringSetDifference(existing, target) {
if _, err := removeDependencyInTx(ctx, sqlTx, current.ID, parentID, actor, false, &recomputed); err != nil {
if _, err := removeDependencyInTx(ctx, sqlTx, current.ID, parentID, actor, false, &recomputed, false); err != nil {
return ParentPatchResult{}, err
}
}
for _, parentID := range stringSetDifference(target, existing) {
if _, err := addDependencyInTx(ctx, sqlTx, &types.Dependency{IssueID: current.ID, DependsOnID: parentID, Type: types.DepParentChild}, actor, AddDependencyOpts{}, &recomputed); err != nil {
if _, err := addDependencyInTx(ctx, sqlTx, &types.Dependency{IssueID: current.ID, DependsOnID: parentID, Type: types.DepParentChild}, actor, AddDependencyOpts{}, &recomputed, false); err != nil {
return ParentPatchResult{}, err
}
}
if mintVersion {
if err := RecordVersionInTx(ctx, tx, current.ID, actor); err != nil {
return ParentPatchResult{}, err
}
}

View file

@ -31,9 +31,21 @@ type ClaimResult struct {
// success (supports agent retry workflows).
// Routes to the correct table (issues/wisps) automatically.
// The caller is responsible for Dolt versioning (DOLT_ADD/COMMIT) if needed.
// A claim that wrote the row mints one version row (assignee, status and
// started_at are durable state); the idempotent re-claim mints nothing.
func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*ClaimResult, error) {
return claimIssueInTx(ctx, tx, id, actor, true)
}
// claimIssueInTx is the body of ClaimIssueInTx. mintVersion controls whether a
// successful claim mints its own version row: the exported entry point always
// does, while ExecuteUpdate — which may apply field, label, parent and
// persistence patches after the claim in the same call — passes false and
// mints exactly once after the last of them, so the version carries the final
// state and one guarded update never records two.
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*ClaimResult, error) {
func claimIssueInTx(ctx context.Context, tx DBTX, id string, actor string, mintVersion bool) (*ClaimResult, error) {
// The CAS below writes assignee = actor. actor is user-settable (--actor /
// BEADS_ACTOR), so bound it against the VARCHAR(255) assignee column up front
// and return a typed ErrFieldTooLong rather than a raw backend error.
@ -218,10 +230,16 @@ func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*Cla
// A claim changes assignee and status, so it journals as an update. The
// idempotent re-claim path returns above without writing and journals
// nothing.
// nothing — and mints nothing: the version row below is for a claim that
// actually rewrote the row.
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return nil, err
}
if mintVersion {
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return nil, err
}
}
return &ClaimResult{OldIssue: oldIssue, IsWisp: isWisp}, nil
}

View file

@ -383,10 +383,17 @@ func closeIssueInTx(ctx context.Context, tx DBTX, id string, reason, actor, sess
}
// Snapshot only after all derived blocked-state maintenance has completed.
// recordEvent gates the human audit event, never the journal.
// recordEvent gates the human audit event, never the journal — nor the
// version row: a close changes status, closed_at, close_reason and
// closed_by_session, all durable state, so it mints whether or not the
// audit event was suppressed (as update.go already does). The rows == 0
// return above (already closed) wrote nothing and mints nothing.
if err := RecordEventInTx(ctx, tx, EventClose, id, actor); err != nil {
return nil, err
}
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return nil, err
}
return &CloseResult{IsWisp: isWisp, IssueRowsChanged: !isWisp || recompute.IssueRowsChanged}, nil
}

View file

@ -31,6 +31,15 @@ type BatchContext struct {
// issue for a result the caller discards. Singular creates leave this
// false so they keep reconciling immediately, per-issue.
SkipChildCounterReconcile bool
// DeferVersionMint tells CreateIssueInTxWithResult NOT to mint the
// issue's version row itself but to report the deferral on its result.
// CreateIssuesInTxWithContext sets this because it persists the batch's
// creation-time dependency edges AFTER the per-issue loop, and the first
// version must carry that outgoing edge set: it mints once per accepted
// issue after the edges (and the blocked-state recompute) have landed.
// Singular creates leave this false and mint in place — they never run
// the dependency pass.
DeferVersionMint bool
}
// NewBatchContext reads config from the database and returns a BatchContext.
@ -76,6 +85,11 @@ type CreateIssueResult struct {
// up to the entry point so their journal rows land AFTER the create's. A
// consumer must never see a comment for a bead it has not been told about.
persistedComments []EventComment
// versionDeferred reports that this create reached the version seam but
// left the mint to the batch entry point (BatchContext.DeferVersionMint).
// Set only on the path that would otherwise have minted, so the batch
// mints for exactly the issues a singular create would have.
versionDeferred bool
}
type persistedDependency struct {
@ -193,6 +207,15 @@ func CreateIssueInTxWithResult(ctx context.Context, tx DBTX, bc *BatchContext, i
if err := RecordEventInTx(ctx, tx, EventCreate, issue.ID, actor); err != nil {
return result, err
}
// The version row is the create's LAST durable-state write. A batch
// create persists this issue's outgoing edges after this function returns,
// so it defers the mint to its own end (DeferVersionMint); a singular
// create has nothing after this point and mints here.
if bc.DeferVersionMint {
result.versionDeferred = true
} else if err := RecordVersionInTx(ctx, tx, issue.ID, actor); err != nil {
return result, err
}
// Creation-time comments (import/interchange carries them inline) are
// replayable content the create snapshot does NOT contain — issue hydration
// joins labels but not comments — so each inserted comment gets its own op,
@ -299,15 +322,24 @@ func CreateIssuesInTxWithContext(ctx context.Context, tx DBTX, bc *BatchContext,
// reconcile behavior.
batch := *bc
batch.SkipChildCounterReconcile = true
// The per-issue create leaves the version mint to this function: the
// creation-time edges below land after the per-issue loop, and the first
// version of each issue must carry them (one version per issue at
// creation, minted last).
batch.DeferVersionMint = true
result := CreateIssuesResult{}
accepted := issues[:0:0]
var toVersion []string
for _, issue := range issues {
issueResult, err := CreateIssueInTxWithResult(ctx, tx, &batch, issue, actor)
if err != nil {
return CreateIssuesResult{}, err
}
result.merge(issueResult.ChangedTables)
if issueResult.versionDeferred {
toVersion = append(toVersion, issue.ID)
}
if issueResult.StaleRejected {
continue // stale snapshot: keep its deps out of the batch too
}
@ -343,6 +375,16 @@ func CreateIssuesInTxWithContext(ctx context.Context, tx DBTX, bc *BatchContext,
if recomputed.WispRowsChanged {
result.markChanged("wisps")
}
// Mint each created issue's first version LAST — after its creation-time
// edges and the blocked-state recompute — so durable_state carries the
// outgoing edge set. PersistDependenciesWithOptionsResult writes the edge
// rows directly and mints nothing itself, so this is the one version per
// issue at creation. Wisps are excluded by the seam.
for _, id := range toVersion {
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return CreateIssuesResult{}, err
}
}
return result, nil
}

View file

@ -1,18 +1,37 @@
package issueops
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"strings"
"github.com/gowebpki/jcs"
"github.com/steveyegge/beads/internal/storage/depid"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/storage/sqlbuild"
"github.com/steveyegge/beads/internal/types"
)
// DependencyMetadataEqual reports whether two dependency metadata JSON
// strings are semantically equal per RFC 8785 (JCS), not merely byte-equal.
// Dolt's native JSON column re-canonicalizes stored text on write (spacing,
// key order, number form), so a byte compare between newly-supplied metadata
// and metadata just read back from the column falsely reports a change on
// every non-empty value (#6650). Both dependency re-add idempotency checks
// share this so they can't drift. Falls back to a byte compare if either
// side fails to parse as JSON.
func DependencyMetadataEqual(a, b string) bool {
aCanon, aErr := jcs.Transform([]byte(a))
bCanon, bErr := jcs.Transform([]byte(b))
if aErr != nil || bErr != nil {
return a == b
}
return bytes.Equal(aCanon, bCanon)
}
type DepTargetKind int
const (
@ -159,7 +178,8 @@ type DepTargetPrecheck struct {
// - Source/target existence validation
// - Hierarchy deadlock validation for blocking deps (GH#1495, bd-wg7ve)
// - Cycle detection via recursive CTE across both dependency tables
// - Idempotent same-type updates (metadata only)
// - Idempotent same-type re-adds: a metadata change updates it, a
// change-free re-add writes and journals nothing (#5898 R3)
// - Type conflict detection
//
// The caller is responsible for transaction lifecycle, dolt commits, and
@ -170,11 +190,23 @@ type DepTargetPrecheck struct {
// same-type re-add or a silent structural add. Callers that stage tables for a
// Dolt commit stage the events table only when an event row exists, so a
// no-event add cannot sweep unrelated pending rows into the commit (GH#2455).
//
// A genuinely new edge is a change to the referencing (source) issue's durable
// state, so it mints one version row for the source — on EVERY leg that reaches
// this helper (the dependency editor, the legacy store verbs, batch apply),
// whether or not an audit event was requested. A same-type re-add that changes
// metadata is the same kind of durable-state change and mints on the same
// terms; only a genuinely change-free re-add (identical type and metadata)
// mints nothing.
func AddDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, actor string, opts AddDependencyOpts) (bool, error) {
return addDependencyInTx(ctx, tx, dep, actor, opts, nil)
return addDependencyInTx(ctx, tx, dep, actor, opts, nil, true)
}
func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, actor string, opts AddDependencyOpts, recomputeResult *RecomputeIsBlockedResult) (bool, error) {
// addDependencyInTx is the body of AddDependencyInTx. mintVersion controls
// whether a new edge mints the source's version row here: the exported entry
// point always does, while a parent patch (applyParentPatch) rewires several
// edges for one caller-visible mutation and mints once after the last of them.
func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, actor string, opts AddDependencyOpts, recomputeResult *RecomputeIsBlockedResult, mintVersion bool) (bool, error) {
if strings.HasPrefix(dep.DependsOnID, "external:") && dep.Type == types.DepParentChild {
return false, fmt.Errorf("external capability dependencies cannot use parent-child edges")
}
@ -263,13 +295,24 @@ func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a
// target expression defensively so stale/reclassified rows in another typed
// target column cannot bypass the idempotency/conflict check.
var existingType string
var existingMetadataNS sql.NullString
//nolint:gosec // G201: writeTable from WispTableRouting; depTargetEquals has no user input.
err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT type FROM %s WHERE issue_id = ? AND %s`, writeTable, depTargetEquals("")),
dep.IssueID, dep.DependsOnID).Scan(&existingType)
err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT type, metadata FROM %s WHERE issue_id = ? AND %s`, writeTable, depTargetEquals("")),
dep.IssueID, dep.DependsOnID).Scan(&existingType, &existingMetadataNS)
if err == nil {
existingMetadata := existingMetadataNS.String
if !existingMetadataNS.Valid {
existingMetadata = "{}"
}
if existingType == string(dep.Type) {
// Same type — idempotent; update metadata. No event is written, so the
// caller must not stage the events table for this re-add.
if DependencyMetadataEqual(existingMetadata, metadata) {
// Same type, same metadata: a change-free write. Nothing is
// written and nothing is journaled (#5898 R3).
return false, nil
}
// Same type, different metadata — idempotent; update metadata. No
// event is written, so the caller must not stage the events table
// for this re-add.
//nolint:gosec // G201: writeTable from WispTableRouting; depTargetEquals has no user input.
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET metadata = ? WHERE issue_id = ? AND %s`, writeTable, depTargetEquals("")),
metadata, dep.IssueID, dep.DependsOnID); err != nil {
@ -278,7 +321,15 @@ func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a
// A same-type add refreshes edge metadata. It is an observable graph
// mutation, so emit the complete replacement edge for replay even
// though no audit event is written.
return false, RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
if err := RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return false, err
}
// The metadata genuinely changed, so — unlike the change-free
// branch above — this re-add is a real durable-state mutation of
// the source issue and mints on the same terms as a new edge
// (#5898 leg 2: "a same-type re-add whose metadata actually
// changed mints EXACTLY ONE version carrying the new state").
return false, mintDependencyVersion(ctx, tx, dep.IssueID, actor, mintVersion)
}
return false, &domain.DependencyTypeConflictError{
IssueID: dep.IssueID,
@ -351,15 +402,36 @@ func addDependencyInTx(ctx context.Context, tx *sql.Tx, dep *types.Dependency, a
}
mergeRecomputeIsBlockedResult(recomputeResult, recomputed)
// Snapshot only after all derived blocked-state maintenance has completed.
return eventWritten, RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
if err := RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return eventWritten, err
}
return eventWritten, mintDependencyVersion(ctx, tx, dep.IssueID, actor, mintVersion)
}
if err := MarkIsBlockedInTx(ctx, tx, affectedIssues, affectedWisps); err != nil {
return false, fmt.Errorf("mark is_blocked after add dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
// Snapshot only after all derived blocked-state maintenance has completed.
// The journal is never gated on opts.EmitEvent: a structurally-wired edge is
// as real to a replaying consumer as one added by an explicit dep verb.
return eventWritten, RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor)
// as real to a replaying consumer as one added by an explicit dep verb —
// and neither is the version row minted beside it.
if err := RecordDepEventInTx(ctx, tx, EventDepAdd, dep.IssueID, string(dep.Type), dep.DependsOnID, metadata, actor); err != nil {
return eventWritten, err
}
return eventWritten, mintDependencyVersion(ctx, tx, dep.IssueID, actor, mintVersion)
}
// mintDependencyVersion versions the referencing (source) issue of an edge that
// was actually inserted, deleted, or had its metadata refreshed by a same-type
// re-add: the version-history seam for every dependency write path, reached
// from addDependencyInTx and removeDependencyInTx only past a real row write —
// never from a genuinely change-free re-add or the absent-edge return, which
// mint nothing. mint false defers to a caller that mints once for a
// multi-edge mutation. A wisp source is excluded by the seam itself.
func mintDependencyVersion(ctx context.Context, tx DBTX, issueID, actor string, mint bool) error {
if !mint {
return nil
}
return RecordVersionInTx(ctx, tx, issueID, actor)
}
// RemoveSourceFromAffected drops the dep source from the affected-ID sets
@ -984,10 +1056,15 @@ func checkRenameTargetCollision(ctx context.Context, tx DBTX, table, typedCol, n
//
//nolint:gosec // G201: depTable from WispTableRouting (hardcoded constants)
func RemoveDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, actor string, emitEvent bool) (bool, error) {
return removeDependencyInTx(ctx, tx, issueID, dependsOnID, actor, emitEvent, nil)
return removeDependencyInTx(ctx, tx, issueID, dependsOnID, actor, emitEvent, nil, true)
}
func removeDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, actor string, emitEvent bool, recomputeResult *RecomputeIsBlockedResult) (bool, error) {
// removeDependencyInTx is the body of RemoveDependencyInTx. A deleted edge is a
// change to the source issue's durable state and mints one version row for it,
// whether or not an audit event was requested; an absent edge returns before
// any write and mints nothing. mintVersion is addDependencyInTx's, for the
// same reason.
func removeDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID, actor string, emitEvent bool, recomputeResult *RecomputeIsBlockedResult, mintVersion bool) (bool, error) {
isWisp := IsActiveWispInTx(ctx, tx, issueID)
_, _, eventTable, depTable := WispTableRouting(isWisp)
@ -1041,8 +1118,12 @@ func removeDependencyInTx(ctx context.Context, tx *sql.Tx, issueID, dependsOnID,
mergeRecomputeIsBlockedResult(recomputeResult, recomputed)
// Snapshot only after all derived blocked-state maintenance has completed.
// Never gated on emitEvent — a structural removal is as real to a replaying
// consumer as one from an explicit dep verb.
return eventWritten, RecordDepEventInTx(ctx, tx, EventDepRemove, issueID, depType, dependsOnID, depMetadata, actor)
// consumer as one from an explicit dep verb. The same holds for the
// version row minted beside it.
if err := RecordDepEventInTx(ctx, tx, EventDepRemove, issueID, depType, dependsOnID, depMetadata, actor); err != nil {
return eventWritten, err
}
return eventWritten, mintDependencyVersion(ctx, tx, issueID, actor, mintVersion)
}
func mergeRecomputeIsBlockedResult(target *RecomputeIsBlockedResult, source RecomputeIsBlockedResult) {

View file

@ -259,3 +259,94 @@ func TestReplaceDependencyTargetRekeysCascadedRows(t *testing.T) {
t.Fatalf("unmet sql expectations: %v", err)
}
}
// TestDependencyMetadataEqualComparesValuesNotBytes pins the change-free
// re-add gate's comparison rule. The gate decides between "nothing happened"
// and "a real mutation of the source issue" by comparing metadata the CALLER
// supplied against metadata read back out of a native JSON column, and a
// native JSON column is free to re-canonicalize what it persists — Dolt's
// inserts a space after ':', sorts object keys, and narrows a bare integral
// float to an int. A byte compare therefore reports a change on values that
// never changed. Each same-value row here is a spelling difference a byte
// compare fails and a JCS (RFC 8785) compare survives (#6650).
func TestDependencyMetadataEqualComparesValuesNotBytes(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
a string
b string
want bool
}{
{name: "IdenticalBytes", a: `{"gate":"any-children"}`, b: `{"gate":"any-children"}`, want: true},
{name: "EmptyObjects", a: `{}`, b: `{}`, want: true},
{name: "StorageInsertedSpacing", a: `{"gate":"any-children"}`, b: `{"gate": "any-children"}`, want: true},
{name: "StorageSortedKeys", a: `{"spawner_id":"src-1","gate":"any-children"}`, b: `{"gate":"any-children","spawner_id":"src-1"}`, want: true},
{name: "StorageNarrowedIntegralFloat", a: `{"weight":1.0}`, b: `{"weight":1}`, want: true},
{name: "DifferentValue", a: `{"note":"v1"}`, b: `{"note":"v2"}`, want: false},
{name: "DifferentKey", a: `{"gate":"any-children"}`, b: `{"mode":"any-children"}`, want: false},
{name: "EmptyVersusPopulated", a: `{}`, b: `{"gate":"any-children"}`, want: false},
// Neither side parses, so the rule falls back to the byte compare it
// replaced rather than calling two unparseable strings equal.
{name: "UnparseableFallsBackToBytesEqual", a: `not json`, b: `not json`, want: true},
{name: "UnparseableFallsBackToBytesUnequal", a: `not json`, b: `also not json`, want: false},
{name: "OneSideUnparseableFallsBackToBytes", a: `{"gate":"any-children"}`, b: `{"gate":`, want: false},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := DependencyMetadataEqual(tc.a, tc.b); got != tc.want {
t.Errorf("DependencyMetadataEqual(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
}
// The rule is symmetric: which side came from the column and
// which from the caller must not change the answer.
if got := DependencyMetadataEqual(tc.b, tc.a); got != tc.want {
t.Errorf("DependencyMetadataEqual(%q, %q) = %v, want %v (asymmetric)", tc.b, tc.a, got, tc.want)
}
})
}
}
// TestAddDependencyInTxReadsNullStoredMetadataAsEmptyObject pins the widened
// SELECT's handling of a SQL-NULL metadata column. dependencies.metadata is
// nullable (`JSON DEFAULT (JSON_OBJECT())`, no NOT NULL), so a row written out
// of band — bd sql, an external tool, hand SQL — can hold NULL. Before the
// re-add gate read metadata at all this path scanned only `type` and was
// idempotently happy; scanning NULL into a plain string would hard-fail it
// with "converting NULL to string is unsupported", turning every subsequent
// re-add of that edge into an error. NULL is the absent-metadata state, so it
// reads as `{}` and the change-free re-add of a metadata-free edge stays the
// no-op it was.
func TestAddDependencyInTxReadsNullStoredMetadataAsEmptyObject(t *testing.T) {
t.Parallel()
_, mock, tx := beginMockTx(t)
mock.ExpectQuery(regexp.QuoteMeta("SELECT issue_type FROM issues WHERE id = ?")).
WithArgs("dep-a").
WillReturnRows(sqlmock.NewRows([]string{"issue_type"}).AddRow("task"))
mock.ExpectQuery(regexp.QuoteMeta("SELECT type, metadata FROM dependencies")).
WithArgs("dep-a", "dep-b").
WillReturnRows(sqlmock.NewRows([]string{"type", "metadata"}).AddRow(string(types.DepRelated), nil))
kind := DepTargetIssue
dep := &types.Dependency{IssueID: "dep-a", DependsOnID: "dep-b", Type: types.DepRelated}
created, err := AddDependencyInTx(context.Background(), tx, dep, "writer", AddDependencyOpts{
SourceTable: "issues",
TargetTable: "issues",
WriteTable: "dependencies",
SkipCycleCheck: true,
TargetKind: &kind,
PrecheckedTarget: &DepTargetPrecheck{IssueType: "task"},
})
if err != nil {
t.Fatalf("AddDependencyInTx(existing edge with NULL metadata) = %v, want nil: a change-free re-add is a no-op, not an error", err)
}
if created {
t.Error("AddDependencyInTx reported the edge as created; the edge already existed with the requested type")
}
// No UPDATE and no journal write are expected: scripting only the two
// reads means any write this path attempted would fail the run.
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf("unmet sql expectations: %v", err)
}
}

View file

@ -173,6 +173,11 @@ func addDependencyEdgeInTx(ctx context.Context, tx *sql.Tx, request publicops.Ad
if err != nil {
return nil, err
}
// The edge's referencing (source) issue is versioned by AddDependencyInTx
// itself, at the row write — once, and only for a genuinely inserted row
// (the idempotent re-add mints nothing, the same exemption eventWritten
// draws for the events table below) — so every leg that reaches that
// helper versions identically and this role adds no second mint.
// Stage the source's dependency table always and its events table only
// when a row was recorded — the same selective staging the stores' own
// AddDependencyWithOptions does, so an idempotent re-add cannot sweep
@ -258,6 +263,9 @@ func ExecuteRemoveDependency(ctx context.Context, tx *sql.Tx, request publicops.
if !eventWritten {
return publicops.RemoveDependencyResult{Removed: false}, nil, nil
}
// A removal that actually happened versioned the referencing issue inside
// RemoveDependencyInTx, at the row delete; an absent edge returned above
// without ever reaching that seam.
tables := ChangedTables{}
tables.Add(depTable, eventTable)
return publicops.RemoveDependencyResult{Removed: true}, tables, nil

View file

@ -169,9 +169,14 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
if err := AuthorizeAssigneeTransfer(ctx, tx, before, attempt); err != nil {
return publicops.UpdateResult{}, nil, err
}
// Every constituent below runs its no-mint variant: one guarded update is
// one caller-visible mutation, and its version is minted exactly once at
// the end, after the last patch, so durable_state carries the final row,
// label set and edge set rather than whichever write happened to run
// first.
changedAny := false
if attempt.Claim {
claimed, err := ClaimIssueInTx(ctx, tx, attempt.IssueID, attempt.Actor)
claimed, err := claimIssueInTx(ctx, tx, attempt.IssueID, attempt.Actor, false)
if err != nil {
return publicops.UpdateResult{}, nil, err
}
@ -209,7 +214,7 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
updates[OpForceClosePolicy] = true
}
if len(updates) > 0 {
updated, err := UpdateIssueInTx(ctx, tx, attempt.IssueID, updates, attempt.Actor)
updated, err := updateIssueInTx(ctx, tx, attempt.IssueID, updates, attempt.Actor, true, false)
if err != nil {
return publicops.UpdateResult{}, nil, err
}
@ -222,7 +227,7 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
}
}
}
labelsChanged, err := ApplyLabelPatch(ctx, tx, current, attempt.Patch.Labels, attempt.Actor)
labelsChanged, err := applyLabelPatch(ctx, tx, current, attempt.Patch.Labels, attempt.Actor, false)
if err != nil {
return publicops.UpdateResult{}, nil, err
}
@ -231,7 +236,7 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
_, labelTable, eventTable, _ := WispTableRouting(IsActiveWispInTx(ctx, tx, attempt.IssueID))
tables.Add(labelTable, eventTable)
}
parentResult, err := ApplyParentPatch(ctx, tx, current, attempt.Patch.ParentID, attempt.Actor)
parentResult, err := applyParentPatch(ctx, tx, current, attempt.Patch.ParentID, attempt.Actor, false)
if err != nil {
return publicops.UpdateResult{}, nil, err
}
@ -248,7 +253,7 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
if err != nil {
return publicops.UpdateResult{}, nil, err
}
moved, err := MoveIssuePersistenceInTx(ctx, tx, current, attempt.Patch.Persistence.Value, attempt.Actor)
moved, err := moveIssuePersistenceInTx(ctx, tx, current, attempt.Patch.Persistence.Value, attempt.Actor, false)
if err != nil {
return publicops.UpdateResult{}, nil, err
}
@ -257,6 +262,15 @@ func ExecuteUpdate(ctx context.Context, tx *sql.Tx, request publicops.UpdateRequ
tables.Merge(moved.ChangedTables)
}
}
// The one mint for this guarded update, LAST: after the claim, the row
// write, the label and parent patches and the persistence move. Nothing
// changed means nothing to version (the FR-2 no-op case), and a row that
// moved to the wisp plane is excluded by the seam itself.
if changedAny {
if err := RecordVersionInTx(ctx, tx, attempt.IssueID, attempt.Actor); err != nil {
return publicops.UpdateResult{}, nil, err
}
}
hydrated, err := HydrateIssueOperationResult(ctx, tx, attempt.IssueID, false)
if err != nil {
return publicops.UpdateResult{}, nil, err

View file

@ -136,13 +136,15 @@ var mutationEntryPoints = []string{
// beadDMLExemptions are exported functions the DML detector flags as writing a
// work-bead table but which legitimately do NOT journal, each with a reason.
// They fall into four buckets: (1) derived child-counter maintenance; (2)
// They fall into five buckets: (1) derived child-counter maintenance; (2)
// aux-table writers the templated-%s heuristic can't distinguish from a bead
// table (events, child counters); (3) constituent sub-helpers of a
// create/rename/promote/delete whose top-level entry point journals the whole
// mutation once; (4) compaction maintenance outside the
// create/update/close/delete/dep/label op vocabulary. The staleness check fails
// if any stops being flagged, so an exemption cannot rot.
// create/update/close/delete/dep/label op vocabulary; (5) dual-write
// version-history bookkeeping that runs after the mutation is already
// journaled. The staleness check fails if any stops being flagged, so an
// exemption cannot rot.
var beadDMLExemptions = map[string]string{
// (1) Child counters are derived CLI acceleration state. In contrast,
// is_blocked is part of the exported bead snapshot and its recompute helpers
@ -182,6 +184,20 @@ var beadDMLExemptions = map[string]string{
// omission is invisible to consumers.
"ApplyCompactionInTx": "compaction content rewrite outside the op vocabulary; consumer mirrors of this bead go stale until its next journaled mutation (known contract gap, carried from the reference lineage)",
"RestoreFromSnapshotInTx": "restores a compacted issue outside the op vocabulary; consumer mirrors of this bead go stale until its next journaled mutation (known contract gap, carried from the reference lineage)",
// (5) dual-write version-history bookkeeping. RecordVersionInTx is called
// from inside the same mutationEntryPoints functions (the create, update,
// close, reopen, claim, release, lease-reclaim, defer-wake, label,
// dependency, promote and persistence-move bodies, and their domain/db
// equivalents used by the uow leg — version_completeness_test.go pins the
// set) immediately after those callers already invoke RecordEventInTx, so the
// mutation itself is already journaled by the time RecordVersionInTx runs.
// Its own UPDATE issues SET current_revision = ? only advances a
// denormalized pointer to match the snapshot row it just inserted into
// issue_versions (not a bead table, so it can't anchor the exemption on
// its own) — bookkeeping for an already-journaled mutation, not a second
// mutation that needs its own emit.
"RecordVersionInTx": "advances the denormalized current_revision pointer to match a snapshot just inserted into issue_versions (not a bead table); called from the same entry points that already journal the mutation via RecordEventInTx, so this is bookkeeping for an already-journaled mutation, not a second one",
}
// journalExemptMutations are mutation paths that deliberately do NOT journal

View file

@ -130,8 +130,18 @@ func getLabelsIntoFromTable(ctx context.Context, tx DBTX, labelTable string, ids
// AddLabelInTx adds a label to an issue and records an event within an existing
// transaction. Automatically routes to wisp tables if the ID is an active wisp.
// Uses INSERT IGNORE for idempotency.
// Uses INSERT IGNORE for idempotency. A label is part of the issue's durable
// state, so a label that was actually inserted mints a version row; an
// idempotent re-add (INSERT IGNORE affecting no row) mints nothing.
func AddLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string) error {
return addLabelInTx(ctx, tx, labelTable, eventTable, issueID, label, actor, true)
}
// addLabelInTx is the body of AddLabelInTx. mintVersion controls whether an
// inserted label mints its own version row: the exported entry point always
// does, while a label patch (applyLabelPatch) writes several rows for one
// caller-visible mutation and mints once after the last of them.
func addLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string, mintVersion bool) error {
// Reject an over-length label up front. The INSERT IGNORE below would
// otherwise silently truncate it to the VARCHAR(255) column, storing a label
// the caller never sent; a typed ErrFieldTooLong is the clean rejection.
@ -149,9 +159,14 @@ func AddLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID,
}
}
//nolint:gosec // G201: labelTable is from WispTableRouting ("labels" or "wisp_labels")
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT IGNORE INTO %s (issue_id, label) VALUES (?, ?)`, labelTable), issueID, label); err != nil {
res, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT IGNORE INTO %s (issue_id, label) VALUES (?, ?)`, labelTable), issueID, label)
if err != nil {
return fmt.Errorf("add label: %w", err)
}
inserted, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("add label: rows affected: %w", err)
}
comment := "Added label: " + label
if err := InsertDerivedEvent(ctx, tx, eventTable, AuxEvent{
IssueID: issueID,
@ -163,15 +178,31 @@ func AddLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID,
}
// A label is part of the bead snapshot, so a label write journals as an
// update carrying the complete post-mutation set.
return RecordEventInTx(ctx, tx, EventUpdate, issueID, actor)
if err := RecordEventInTx(ctx, tx, EventUpdate, issueID, actor); err != nil {
return err
}
// Version only when a row landed: INSERT IGNORE on an existing label is
// the no-op case, and a no-op mints nothing (the same gate the dependency
// helpers draw on their inserted/deleted row).
if !mintVersion || inserted == 0 {
return nil
}
return RecordVersionInTx(ctx, tx, issueID, actor)
}
// RemoveLabelInTx removes a label from an issue and records an event within
// an existing transaction. Automatically routes to wisp tables if the ID is
// an active wisp.
// an active wisp. A deleted label row mints a version row; a DELETE that
// matched no row is a no-op and mints nothing.
func RemoveLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string) error {
return removeLabelInTx(ctx, tx, labelTable, eventTable, issueID, label, actor, true)
}
// removeLabelInTx is the body of RemoveLabelInTx; mintVersion is
// addLabelInTx's, for the same reason.
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func RemoveLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string) error {
func removeLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string, mintVersion bool) error {
if labelTable == "" || eventTable == "" {
isWisp := IsActiveWispInTx(ctx, tx, issueID)
_, lt, et, _ := WispTableRouting(isWisp)
@ -182,9 +213,14 @@ func RemoveLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issue
eventTable = et
}
}
if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE issue_id = ? AND label = ?`, labelTable), issueID, label); err != nil {
res, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE issue_id = ? AND label = ?`, labelTable), issueID, label)
if err != nil {
return fmt.Errorf("remove label: %w", err)
}
deleted, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("remove label: rows affected: %w", err)
}
comment := "Removed label: " + label
if err := InsertDerivedEvent(ctx, tx, eventTable, AuxEvent{
IssueID: issueID,
@ -194,5 +230,11 @@ func RemoveLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issue
}); err != nil {
return fmt.Errorf("remove label: record event: %w", err)
}
return RecordEventInTx(ctx, tx, EventUpdate, issueID, actor)
if err := RecordEventInTx(ctx, tx, EventUpdate, issueID, actor); err != nil {
return err
}
if !mintVersion || deleted == 0 {
return nil
}
return RecordVersionInTx(ctx, tx, issueID, actor)
}

View file

@ -780,6 +780,12 @@ func ReclaimExpiredLeasesInTx(ctx context.Context, tx DBTX, cutoff time.Time, fi
if err := RecordEventInTx(ctx, tx, EventUpdate, r.ID, actor); err != nil {
return nil, err
}
// The revert rewrote assignee, status and started_at — durable state —
// so the reclaimed issue gets a version row beside its journal entry,
// past the same two re-checks.
if err := RecordVersionInTx(ctx, tx, r.ID, actor); err != nil {
return nil, err
}
// Logged HERE, past both re-checks, so the audit trail records reverts
// that actually happened: a heartbeat landing after the snapshot makes
// the DELETE match nothing, and a "reverting X" line printed up there

View file

@ -13,8 +13,20 @@ type PersistenceMoveResult struct {
ChangedTables map[string]bool
}
// MoveIssuePersistenceInTx moves a complete issue aggregate to the requested persistence mode.
// MoveIssuePersistenceInTx moves a complete issue aggregate to the requested
// persistence mode. A move that lands (or normalizes) the row on the issues
// plane mints a version row once the target row and its auxiliary copies
// exist; a move whose target is the wisp plane mints nothing (wisps are never
// versioned).
func MoveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue, mode types.PersistenceMode, actor string) (PersistenceMoveResult, error) {
return moveIssuePersistenceInTx(ctx, tx, current, mode, actor, true)
}
// moveIssuePersistenceInTx is the body of MoveIssuePersistenceInTx.
// mintVersion controls whether the move mints its own version row: the
// exported entry point always does, while ExecuteUpdate applies the
// persistence patch last and mints once for the whole guarded update.
func moveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue, mode types.PersistenceMode, actor string, mintVersion bool) (PersistenceMoveResult, error) {
if tx == nil || current == nil || current.ID == "" {
return PersistenceMoveResult{}, fmt.Errorf("move issue persistence: issue and transaction are required")
}
@ -58,6 +70,13 @@ func MoveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue
if err := RecordEventInTx(ctx, tx, EventUpdate, current.ID, actor); err != nil {
return PersistenceMoveResult{}, err
}
// Versioned only on the issues plane; a wisp-plane normalize keeps
// the wisp exclusion.
if mintVersion && !targetWisp {
if err := RecordVersionInTx(ctx, tx, current.ID, actor); err != nil {
return PersistenceMoveResult{}, err
}
}
return result, nil
}
if !sourceWisp && targetWisp {
@ -124,10 +143,17 @@ func MoveIssuePersistenceInTx(ctx context.Context, tx DBTX, current *types.Issue
result.ChangedTables[persistenceIssueTable(targetWisp)] = true
// The bead keeps its ID across a plane move; only where it is stored
// changes. Journal one update carrying the moved snapshot, after derived
// blocked-state maintenance has settled.
// blocked-state maintenance has settled. A move INTO the issues plane
// then mints the row's first version there, after its auxiliary copies
// and retargeted edges exist; a move into the wisp plane mints nothing.
if err := RecordEventInTx(ctx, tx, EventUpdate, current.ID, actor); err != nil {
return PersistenceMoveResult{}, err
}
if mintVersion && !targetWisp {
if err := RecordVersionInTx(ctx, tx, current.ID, actor); err != nil {
return PersistenceMoveResult{}, err
}
}
return result, nil
}

View file

@ -131,9 +131,12 @@ func PromoteFromEphemeralInTx(ctx context.Context, tx DBTX, id string, actor str
// The bead keeps its ID across promotion; only its plane changes. Journal
// one update carrying the now-durable snapshot, after derived blocked-state
// maintenance has settled.
// maintenance has settled — and mint its first version: the promoted row
// is new durable state on the issues plane (a wisp is never versioned, so
// nothing precedes it), minted once after its labels, dependencies and
// comments have been copied across.
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return err
}
return nil
return RecordVersionInTx(ctx, tx, id, actor)
}

View file

@ -117,10 +117,15 @@ func reopenIssueInTx(ctx context.Context, tx DBTX, id, reason, actor string, ret
}
// Snapshot only after all derived blocked-state maintenance has completed.
// A reopen is a status change, so it journals as an update.
// A reopen is a status change, so it journals as an update and mints a
// version; the already-open early returns above write nothing and mint
// nothing.
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return nil, err
}
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return nil, err
}
return &ReopenResult{
IsWisp: isWisp,

View file

@ -139,6 +139,20 @@ var funcNameExemptions = map[string]string{
// Reminting here would be pointless content-wise and would let a stale
// ExpectedVersion CAS reject a row it should still recognize.
"resolveOneConflictRow": "whole-row `theirs` adoption: the adopted row_lock already vouches for the (identical) adopted content",
// RecordVersionInTx (version_history.go) runs immediately after the
// mutation it is snapshotting — create.go/update.go's own writes, or
// domain/db's Insert/Update — and those callers have already minted a
// fresh row_lock in that same INSERT/UPDATE, in the same transaction.
// RecordVersionInTx's own `UPDATE issues SET current_revision = ?` only
// advances a denormalized pointer to the issue_versions row it just
// inserted; it deliberately does not touch row_lock at all (not even to
// carry the existing value forward) because reminting here would bump the
// token a second time within one transaction, invalidating the
// RowVersion/CAS value the primary mutation's own caller already
// captured and could cause a legitimate subsequent CAS check to fail as a
// spurious lost update.
"RecordVersionInTx": "runs after the primary mutation already minted a fresh row_lock in the same transaction; reminting here would double-bump the token and invalidate the RowVersion/CAS value already returned to that mutation's caller",
}
// TestAllIssueRowWritesStampRowLock is the load-bearing completeness guard for

View file

@ -0,0 +1,18 @@
# RFC 8785 (JCS) test vectors
The `input/` and `expected/` pairs are copied verbatim from
[github.com/gowebpki/jcs](https://github.com/gowebpki/jcs) v1.0.1
(`testdata/input` and `testdata/output` upstream — the latter is named
`expected/` here because this repository's `.gitignore` drops any `output`
tree; Apache License 2.0, Copyright 2021
Bret Jordan & Benedikt Thoma, Copyright 2006-2019 WebPKI.org), which carries
the RFC 8785 JSON Canonicalization Scheme test suite from
[cyberphone/json-canonicalization](https://github.com/cyberphone/json-canonicalization).
Each `input/<name>.json` must canonicalize to exactly the bytes of
`expected/<name>.json` (no trailing newline).
`TestCanonicalDurableStateIsJCS` drives `canonicalDurableState` — the helper
`RecordVersionInTx` stores `issue_versions.durable_state` through — over every
pair, so the stored bytes are pinned to the published vectors rather than to
whatever the dependency happens to emit. Do not edit the pairs; local cases
belong in the test's own table.

View file

@ -0,0 +1 @@
[56,{"1":[],"10":null,"d":true}]

View file

@ -0,0 +1 @@
false

View file

@ -0,0 +1 @@
{"peach":"This sorting order","péché":"is wrong according to French","pêche":"but canonicalization MUST","sin":"ignore locale"}

View file

@ -0,0 +1 @@
null

View file

@ -0,0 +1 @@
"this is a test string 1235"

View file

@ -0,0 +1 @@
{"":"empty","1":{"\n":56,"f":{"F":5,"f":"hi"}},"10":{},"111":[{"E":"no","e":"yes"}],"A":{},"a":{}}

View file

@ -0,0 +1 @@
true

View file

@ -0,0 +1 @@
{"Unnormalized Unicode":"Å"}

View file

@ -0,0 +1 @@
{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\u000f\nA'B\"\\\\\"/"}

View file

@ -0,0 +1 @@
{"\n":"Newline","\r":"Carriage Return","1":"One","</script>":"Browser Challenge","€":"Control","ö":"Latin Small Letter O With Diaeresis","€":"Euro Sign","😂":"Smiley","דּ":"Hebrew Letter Dalet With Dagesh"}

View file

@ -0,0 +1,8 @@
[
56,
{
"d": true,
"10": null,
"1": [ ]
}
]

View file

@ -0,0 +1 @@
false

View file

@ -0,0 +1,6 @@
{
"peach": "This sorting order",
"péché": "is wrong according to French",
"pêche": "but canonicalization MUST",
"sin": "ignore locale"
}

View file

@ -0,0 +1 @@
null

View file

@ -0,0 +1 @@
"this is a test string 1235"

View file

@ -0,0 +1,8 @@
{
"1": {"f": {"f": "hi","F": 5} ,"\n": 56.0},
"10": { },
"": "empty",
"a": { },
"111": [ {"e": "yes","E": "no" } ],
"A": { }
}

View file

@ -0,0 +1 @@
true

View file

@ -0,0 +1,3 @@
{
"Unnormalized Unicode":"A\u030a"
}

View file

@ -0,0 +1,5 @@
{
"numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001],
"string": "\u20ac$\u000F\u000aA'\u0042\u0022\u005c\\\"\/",
"literals": [null, true, false]
}

View file

@ -0,0 +1,11 @@
{
"\u20ac": "Euro Sign",
"\r": "Carriage Return",
"\u000a": "Newline",
"1": "One",
"\u0080": "Control\u007f",
"\ud83d\ude02": "Smiley",
"\u00f6": "Latin Small Letter O With Diaeresis",
"\ufb33": "Hebrew Letter Dalet With Dagesh",
"</script>": "Browser Challenge"
}

View file

@ -129,8 +129,12 @@ func finishUnclaimInTx(ctx context.Context, tx DBTX, eventTable string, id strin
}
// A release changes assignee and status, so it journals as an update. Both
// unclaim entry points funnel through here after their CAS succeeded, so
// this covers the conditional release too.
return RecordEventInTx(ctx, tx, EventUpdate, id, actor)
// this covers the conditional release too — and the version row minted
// beside it, for the same durable-state change.
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return err
}
return RecordVersionInTx(ctx, tx, id, actor)
}
// UnclaimIssueIfAssigneeInTx atomically releases a claim only while the issue is

View file

@ -335,17 +335,24 @@ type UpdateResult struct {
//
//nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants)
func UpdateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) {
return updateIssueInTx(ctx, tx, id, updates, actor, true)
return updateIssueInTx(ctx, tx, id, updates, actor, true, true)
}
// UpdateIssueWithoutEventInTx applies normal update semantics without recording
// an intermediate event. Demotion uses this to preserve the historical event
// stream: create/update history is copied, then a single demotion event is added.
func UpdateIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) {
return updateIssueInTx(ctx, tx, id, updates, actor, false)
return updateIssueInTx(ctx, tx, id, updates, actor, false, true)
}
func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string, recordEvent bool) (*UpdateResult, error) {
// updateIssueInTx is the body behind both exported update entry points.
// recordEvent gates the human-facing audit event only. mintVersion controls
// whether an accepted update mints its own version row: both exported entry
// points always do, while ExecuteUpdate — which applies label, parent and
// persistence patches AFTER the row write in the same call — passes false and
// mints once after the last patch, so the version's durable_state carries the
// patched labels and edges rather than the pre-patch row.
func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string, recordEvent bool, mintVersion bool) (*UpdateResult, error) {
updates = cloneUpdateFields(updates)
// Pop the override before anything reads the map as a set of columns. It
// has to come out ahead of the no-op filter too: the filter keeps every key
@ -544,6 +551,11 @@ func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string
if err := RecordEventInTx(ctx, tx, EventUpdate, id, actor); err != nil {
return nil, err
}
if mintVersion {
if err := RecordVersionInTx(ctx, tx, id, actor); err != nil {
return nil, err
}
}
return updateResult, nil
}

View file

@ -0,0 +1,589 @@
package issueops
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"reflect"
"sort"
"testing"
"github.com/steveyegge/beads/internal/storage/journalscan"
)
// This file is the versioned-history twin of journal_completeness_test.go. The
// law it pins (gastownhall/beads#6358, Phase 2 dual-write): every ACCEPTED
// mutation of an issue's durable state — the issues/wisps columns, its labels
// and its outgoing dependencies, i.e. what GetIssueInTx hydrates plus what
// RecordVersionInTx loads — mints exactly one issue_versions row, in the same
// transaction, as the mutation's LAST durable-state write; a no-op mints none;
// a wisp is never versioned (the seam excludes it itself). Comments are not in
// durable_state, is_blocked is derived, and a deleted row has nothing to
// version, so those paths deliberately never reach the seam.
//
// Like the journal guard it detects mutators STRUCTURALLY, by the DML a
// function executes, so a new write path cannot ship without either reaching
// RecordVersionInTx or being justified in the exemption table below.
// versionMintHelpers are the helpers whose call mints a version row. There is
// exactly one seam; a function mints if it calls it directly or through a
// named helper (mintDependencyVersion, addLabelInTx, updateIssueInTx, ...)
// whose mint it did not switch off — see versionMintGate.
var versionMintHelpers = map[string]bool{
"RecordVersionInTx": true,
}
// versionMintGate names the boolean parameter the constituent helpers
// (claimIssueInTx, updateIssueInTx, applyLabelPatch, applyParentPatch,
// moveIssuePersistenceInTx, addLabelInTx, removeLabelInTx, addDependencyInTx,
// removeDependencyInTx) mint under. mintDependencyVersion spells its own
// "mint", but it is only ever handed a caller's mintVersion, never a literal,
// so the one name covers every switch-off in the package.
const versionMintGate = "mintVersion"
// versionMintEdges follows the same call-graph discipline as journalEmitEdges
// — nothing in the derived-readiness family mints, and a mutator must not be
// able to inherit a mint through a recompute — with one refinement the journal
// guard has no need for: a helper that takes a mintVersion bool mints only
// when asked to, so a call passing the literal false for it is NOT a minting
// edge. That is how a composite mutation runs its constituents without minting
// and mints once itself at the end (ExecuteUpdate's claim, row write, label
// and parent patches and persistence move). Without the refinement the
// fixpoint credited the composite with the mint it told its constituents to
// skip, and deleting its own final RecordVersionInTx stayed green (reviewer
// Probe 2 on gastownhall/beads#6358). A call passing true, a variable, or the
// caller's own mintVersion parameter is still a minting edge, so the leaf
// wrappers (ClaimIssueInTx, ApplyLabelPatch, ...) and the forwarding helpers
// keep theirs.
func versionMintEdges(fns map[string]*journalscan.FuncInfo) func(*journalscan.FuncInfo) []string {
return func(f *journalscan.FuncInfo) []string {
var live []string
for _, callee := range journalEmitEdges(f) {
if journalscan.CallsOnlyWithLiteralFalse(fns, f, callee, versionMintGate) {
continue
}
live = append(live, callee)
}
return live
}
}
// versionCompositeMutations are the functions that run constituents with
// versionMintGate switched off and mint once themselves, so each must carry
// its own RecordVersionInTx: nothing it calls with the gate off can carry it
// on its behalf. TestCompositeMutationsCarryTheirOwnMint is what turns
// reviewer Probe 2 (delete ExecuteUpdate's final mint block) into a failure.
var versionCompositeMutations = []string{
"ExecuteUpdate",
"applyLabelPatch",
"applyParentPatch",
}
// versionedEntryPoints are the issueops functions that mutate an issue's
// durable state and must therefore mint — directly or through a helper that
// does. Every write plumbing bottoms out in one of these; the structural
// cross-check (TestEveryBeadMutatorMintsOrIsExempt) keeps the list complete.
var versionedEntryPoints = []string{
// create — the singular path mints in place; the batch path defers the
// mint past PersistDependenciesWithOptionsResult so the first version
// carries the creation-time edge set.
"CreateIssueInTx",
"CreateIssueInTxWithResult",
"CreateIssuesInTx",
"CreateIssuesInTxWithResult",
"CreateIssuesInTxWithContext",
// update, including the metadata verbs that write through it, the label
// and parent patches, and the persistence move
"UpdateIssueInTx",
"UpdateIssueWithoutEventInTx",
"MergeMetadataInTx",
"DeleteMetadataInTx",
"CompareAndSetMetadataKeyInTx",
"ApplyLabelPatch",
"ApplyParentPatch",
"MoveIssuePersistenceInTx",
// close / reopen, including the guarded CAS + savepoint path
"CloseIssueInTx",
"CloseIssueWithoutEventInTx",
"CloseIssueCheckedInTx",
"ReopenIssueInTx",
// the delete role's neighbour rewrite versions the surviving neighbours
// (the deleted rows themselves are the delete family, exempt below)
"RewriteDeletedReferencesInTx",
// claim / release / lease recovery
"ClaimIssueInTx",
"ClaimReadyIssueInTx",
"UnclaimIssueInTx",
"UnclaimIssueIfAssigneeInTx",
"ReleaseIssueInTx",
"ReclaimExpiredLeasesInTx",
// plane moves, graph edges, labels, scheduled status flips
"PromoteFromEphemeralInTx",
"AddDependencyInTx",
"RemoveDependencyInTx",
"AddLabelInTx",
"RemoveLabelInTx",
"WakeExpiredDefersInTx",
// the public lifecycle surface (roles/facade wave). These delegate to the
// leaves above; listing them pins the delegation so a role that grows its
// own DML cannot quietly stop versioning.
"ExecuteCreate",
"ExecuteCreateBatch",
"ExecuteUpdate",
"ExecuteClose",
"ExecuteCloseBatch",
"ExecuteReopen",
"ExecuteClaim",
"ExecuteClaimNext",
"ExecuteAddDependencies",
"ExecuteRemoveDependency",
"ApplyBatchInTx",
}
// versionExemptions are exported functions the DML detector flags as writing a
// work-bead table but which legitimately do NOT mint a version for the row
// they write, each with a reason. The staleness check fails if any stops being
// flagged, so an exemption cannot rot. Note that some of these DO reach the
// seam transitively for a NEIGHBOUR (DeleteInTx rewrites references on the
// surviving issues through UpdateIssueInTx); the exemption is about the row
// the function itself writes, and versionNeverMints below pins the ones that
// must not reach the seam at all.
var versionExemptions = map[string]string{
// comments — a separate table, not part of durable_state (GetIssueInTx
// hydrates labels, not comments), so a comment write versions nothing.
"AddIssueCommentInTx": "comments are not in durable_state",
"ImportIssueCommentInTx": "comments are not in durable_state",
"ExecuteAddComment": "comments are not in durable_state",
"AddCommentEventInTx": "comments are not in durable_state",
"PersistComments": "constituent comment write of a create; comments are not in durable_state",
"InsertDerivedComment": "raw comment insert; comments are not in durable_state",
// is_blocked — derived readiness state, recomputed from the graph, never
// a mutation of the bead in its own right.
"RecomputeIsBlockedInTx": "is_blocked is derived state",
"RecomputeIsBlockedInTxWithResult": "is_blocked is derived state",
"RecomputeIsBlockedForIDsInTx": "is_blocked is derived state",
"RecomputeIsBlockedForWispIDsInTx": "is_blocked is derived state",
"RecomputeIsBlockedAfterMergeInTx": "is_blocked is derived state",
"RecomputeAllIsBlockedInTx": "is_blocked is derived state",
"MarkIsBlockedInTx": "is_blocked is derived state",
// the delete family — no surviving row to version; the deleted-Versioned-
// Bead guarantee is Phase 3 (#6358). DeleteInTx versions its NEIGHBOURS
// through RewriteDeletedReferencesInTx, never the deleted rows.
"DeleteIssueInTx": "delete family: no surviving row (Phase 3)",
"DeleteIssuesInTx": "delete family: no surviving row (Phase 3)",
"DeleteResolvedSetInTx": "delete family: no surviving row (Phase 3)",
"DeleteInTx": "delete family: no surviving row (Phase 3); neighbours version via RewriteDeletedReferencesInTx",
"SweepInTx": "delete family: no surviving row (Phase 3)",
"DeleteIssuesBySourceRepoInTx": "bulk delete: no surviving row (Phase 3)",
"DeleteWispFromDependenciesInTx": "delete-family cleanup of edges whose target is gone",
"DeleteWispsFromDependenciesInTx": "delete-family cleanup of edges whose target is gone",
// rename — history stays keyed to the old id; out of contract by design.
"UpdateIssueIDInTx": "rename: out of contract by design (history stays keyed to the old id)",
"UpdateWispIDInDependenciesInTx": "rename: dep-row rekey, out of contract by design",
"UpdateIssueIDInDependenciesInTx": "rename: dep-row rekey, out of contract by design",
// compaction bookkeeping and restore — outside the op vocabulary; the
// content rewrite that precedes compaction versions through UpdateIssue.
"ApplyCompactionInTx": "compaction bookkeeping columns, out of contract by design",
"RestoreFromSnapshotInTx": "restore: CAS composition is Phase 3 (#6358)",
// constituent sub-helpers whose entry point mints the whole mutation once
"InsertIssueIntoTable": "raw issue insert; the calling create entry point mints",
"InsertIssueIfNew": "raw issue insert; the calling create entry point mints",
"InsertIssueStrictInTx": "raw issue insert; the calling create/persistence-move entry point mints",
"PersistLabels": "constituent label write of a create; the create entry point mints",
"PersistDependencies": "creation-time edges; CreateIssuesInTxWithContext mints once per issue after they land",
"PersistDependenciesWithResult": "creation-time edges; CreateIssuesInTxWithContext mints once per issue after they land",
"PersistDependenciesWithOptionsResult": "creation-time edges; CreateIssuesInTxWithContext mints once per issue after they land",
"RetargetInboundDependenciesToWispInTx": "rewrites INBOUND edges during a plane move; the moved issue's own entry point mints",
"RetargetInboundDependenciesToIssueInTx": "rewrites INBOUND edges during a plane move; the moved issue's own entry point mints",
// aux tables matched via templated %s, not work-bead state
"ReconcileChildCounters": "child_counters are derived CLI acceleration state",
"GetNextChildIDTx": "child_counters allocation, not work-bead state",
"RecordEventInTable": "writes the events audit table (templated %s), not work-bead state",
"RecordFullEventInTable": "writes the events audit table (templated %s), not work-bead state",
"InsertDerivedEvent": "writes the events audit table (templated %s), not work-bead state",
"InsertDerivedEventReturningID": "writes the events audit table (templated %s), not work-bead state",
// the seam itself: its UPDATE issues SET current_revision is the
// bookkeeping half of the mint, not a mutation that needs its own.
"RecordVersionInTx": "the seam itself; advances current_revision to match the row it just inserted",
}
// versionNeverMints pins the deliberate NOT-versioned rulings from the other
// side: each must exist and must not reach RecordVersionInTx, directly or
// transitively, so a well-meaning edit cannot silently start versioning
// comments, derived state, deletes, renames, compaction bookkeeping, lease
// keepalives or bootstrap. (Migrations live in the schema package and are out
// of this scan's reach; they are out of contract by design.)
var versionNeverMints = map[string]string{
"AddIssueCommentInTx": "comments are not in durable_state",
"ImportIssueCommentInTx": "comments are not in durable_state",
"ExecuteAddComment": "comments are not in durable_state",
"RecomputeIsBlockedInTx": "is_blocked is derived state",
"RecomputeIsBlockedInTxWithResult": "is_blocked is derived state",
"RecomputeIsBlockedForIDsInTx": "is_blocked is derived state",
"RecomputeIsBlockedForWispIDsInTx": "is_blocked is derived state",
"RecomputeIsBlockedAfterMergeInTx": "is_blocked is derived state",
"RecomputeAllIsBlockedInTx": "is_blocked is derived state",
"MarkIsBlockedInTx": "is_blocked is derived state",
"DeleteIssueInTx": "delete family (Phase 3)",
"DeleteIssuesInTx": "delete family (Phase 3)",
"DeleteResolvedSetInTx": "delete family (Phase 3)",
"DeleteIssuesBySourceRepoInTx": "bulk delete (Phase 3)",
"UpdateIssueIDInTx": "rename: out of contract by design",
"ApplyCompactionInTx": "compaction bookkeeping: out of contract by design",
"RestoreFromSnapshotInTx": "restore: Phase 3",
"HeartbeatIssueInTx": "lease keepalive: writes only the clone-local leases table, never a durable bead field",
"BootstrapInTx": "bootstrap: config and metadata tables only, no issue-plane row",
}
func versionMints(t *testing.T) (map[string]*journalscan.FuncInfo, map[string]bool) {
t.Helper()
return versionMintsIn(t, ".")
}
// versionMintsIn is versionMints over the package at dir, so the guard's own
// machinery can be proven against a synthetic package.
func versionMintsIn(t *testing.T, dir string) (map[string]*journalscan.FuncInfo, map[string]bool) {
t.Helper()
fns, err := journalscan.ParsePackage(dir)
if err != nil {
t.Fatalf("parse package %s: %v", dir, err)
}
mints := journalscan.Fixpoint(fns,
func(f *journalscan.FuncInfo) bool { return f.CallsAnyOf(versionMintHelpers) },
versionMintEdges(fns))
return fns, mints
}
// compositeMintLeaks returns, for a composite mutation f, every function key
// that one of its live edges — the calls left after the literal-false
// constituents are dropped — resolves to and that reaches the seam: each is a
// mint f would perform besides its own. The called bare name is resolved to
// every key it can denote, the free function and every method of that name,
// exactly as the fixpoint resolves it. mints is keyed "Recv.Name" for a
// method, so a bare-name lookup would quietly stop seeing a constituent the
// moment it became one (TestCompositeCheckSeesMethodConstituents).
func compositeMintLeaks(fns map[string]*journalscan.FuncInfo, mints map[string]bool, f *journalscan.FuncInfo) []string {
seen := map[string]bool{}
var leaks []string
for _, callee := range versionMintEdges(fns)(f) {
for _, key := range journalscan.Resolve(fns, callee) {
if mints[key] && !seen[key] {
seen[key] = true
leaks = append(leaks, key)
}
}
}
sort.Strings(leaks)
return leaks
}
// TestCompositeMutationsCarryTheirOwnMint pins that each composite mutation
// calls RecordVersionInTx itself AND that none of the edges it leaves live
// (after the literal-false constituents are dropped) reaches the seam, each
// called name resolved to every function it can denote (compositeMintLeaks)
// — so the composite's own call is load-bearing, and deleting it fails
// TestEveryVersionedEntryPointMints rather than being papered over by a
// constituent it explicitly told not to mint.
func TestCompositeMutationsCarryTheirOwnMint(t *testing.T) {
fns, mints := versionMints(t)
for _, name := range versionCompositeMutations {
f, defined := fns[name]
if !defined {
t.Errorf("composite mutation %q not found in issueops — was it renamed? update versionCompositeMutations", name)
continue
}
if !f.CallsAnyOf(versionMintHelpers) {
t.Errorf("composite mutation %q does not call RecordVersionInTx itself; it runs its constituents with %s=false, so nothing else mints for it", name, versionMintGate)
}
for _, key := range compositeMintLeaks(fns, mints, f) {
t.Errorf("composite mutation %q would also mint through %q, so its own RecordVersionInTx is no longer the one mint the write-path doc promises — either that constituent is called with %s left on, or it mints unconditionally", name, key, versionMintGate)
}
}
}
// TestCompositeCheckSeesMethodConstituents proves the composite check against
// a synthetic package whose constituent is a METHOD: the mints fixpoint keys
// it "svc.constituent", the composite calls it by the bare name, and the
// check must still see the mint a call with the gate left on lets through.
// This is what keeps TestCompositeMutationsCarryTheirOwnMint from quietly
// ceasing to bite should a constituent in issueops become a method.
func TestCompositeCheckSeesMethodConstituents(t *testing.T) {
dir := t.TempDir()
src := `package probe
func RecordVersionInTx() {}
type svc struct{}
func (s *svc) constituent(mintVersion bool) {
if mintVersion {
RecordVersionInTx()
}
}
// Composite runs its constituent with the gate off and mints once itself.
func Composite(s *svc) { s.constituent(false); RecordVersionInTx() }
// Leaky leaves the gate on, so its constituent mints as well as it does.
func Leaky(s *svc) { s.constituent(true); RecordVersionInTx() }
`
if err := os.WriteFile(filepath.Join(dir, "probe.go"), []byte(src), 0o600); err != nil {
t.Fatal(err)
}
fns, mints := versionMintsIn(t, dir)
if !mints["svc.constituent"] {
t.Fatal("svc.constituent does not mint; the synthetic package no longer exercises a method constituent")
}
if mints["constituent"] {
t.Fatal("mints is keyed by the bare name of a method; the check must resolve to the receiver-qualified key, and this probe no longer shows that it has to")
}
if got := compositeMintLeaks(fns, mints, fns["Composite"]); len(got) != 0 {
t.Errorf("Composite leaks through %q, want nothing: its constituent is switched off", got)
}
if got := compositeMintLeaks(fns, mints, fns["Leaky"]); !reflect.DeepEqual(got, []string{"svc.constituent"}) {
t.Errorf("Leaky leaks through %q, want [svc.constituent]: a method constituent left with the gate on must be seen through its receiver-qualified key", got)
}
}
// TestFalseIsNotShadowedInIssueops pins the reading CallsOnlyWithLiteralFalse
// rests on as EXACT for this package rather than merely conservative. The
// scanner counts a false argument as the predeclared identifier only when
// nothing it can see declares that name; this walk proves nothing in the
// package does, in any declaration position — so every mintVersion=false in
// issueops is the switch-off the guard takes it for, and no true is a false
// in disguise. Test files are walked too: a package-level shadow in one would
// change what every false in the package means under test.
func TestFalseIsNotShadowedInIssueops(t *testing.T) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, ".", nil, parser.SkipObjectResolution)
if err != nil {
t.Fatalf("parse issueops package: %v", err)
}
var positions int
var shadows []string
declared := func(what string, ident *ast.Ident) {
if ident == nil {
return
}
positions++
if ident.Name == "false" || ident.Name == "true" {
shadows = append(shadows, fmt.Sprintf("%s: %s named %s", fset.Position(ident.Pos()), what, ident.Name))
}
}
declaredFields := func(what string, list *ast.FieldList) {
if list == nil {
return
}
for _, field := range list.List {
for _, name := range field.Names {
declared(what, name)
}
}
}
for _, pkg := range pkgs {
for _, file := range pkg.Files {
ast.Inspect(file, func(n ast.Node) bool {
switch node := n.(type) {
case *ast.ImportSpec:
declared("import name", node.Name)
case *ast.ValueSpec:
for _, name := range node.Names {
declared("var/const", name)
}
case *ast.TypeSpec:
declared("type", node.Name)
case *ast.FuncDecl:
declared("function", node.Name)
declaredFields("receiver", node.Recv)
case *ast.FuncType: // the signature of a FuncDecl or a FuncLit
declaredFields("parameter", node.Params)
declaredFields("result", node.Results)
case *ast.AssignStmt:
if node.Tok == token.DEFINE {
for _, lhs := range node.Lhs {
if ident, ok := lhs.(*ast.Ident); ok {
declared("short variable declaration", ident)
}
}
}
case *ast.RangeStmt:
if node.Tok == token.DEFINE {
for _, expr := range []ast.Expr{node.Key, node.Value} {
if ident, ok := expr.(*ast.Ident); ok {
declared("range variable", ident)
}
}
}
case *ast.LabeledStmt:
declared("label", node.Label)
}
return true
})
}
}
if positions == 0 {
t.Fatal("the walk visited no declaration position in issueops — parsing changed; the guard is not actually running")
}
sort.Strings(shadows)
for _, shadow := range shadows {
t.Errorf("%s shadows a predeclared identifier, so a %s=false in this package may not be the switch-off the guard reads it as — rename it", shadow, versionMintGate)
}
}
// TestLiteralFalseCalleesResolveUnambiguously pins the other half of the
// switch-off's exactness. Resolution is name-based: a called bare name
// denotes the free function of that name AND every method of that name, and
// when a caller switches the name off with mintVersion=false the fixpoint
// drops its edge to all of them — including a same-named function that
// declares no mintVersion and mints unconditionally, whose mint the switch-off
// cannot have switched off. So every callee reached by a literal-false
// mintVersion call must resolve to exactly one function, or every function it
// resolves to must declare the gate; otherwise the name is ambiguous and one
// of them must be renamed. (Resolve's semantics are deliberately left alone:
// name-based resolution is what keeps the guard free of type information.)
func TestLiteralFalseCalleesResolveUnambiguously(t *testing.T) {
fns, _ := versionMints(t)
callers := make([]string, 0, len(fns))
for key := range fns {
callers = append(callers, key)
}
sort.Strings(callers)
var switchedOff int
checked := map[string]bool{}
for _, caller := range callers {
f := fns[caller]
for _, callee := range f.AllCallNames() {
if !journalscan.CallsOnlyWithLiteralFalse(fns, f, callee, versionMintGate) {
continue
}
switchedOff++
if checked[callee] {
continue
}
checked[callee] = true
keys := journalscan.Resolve(fns, callee)
if len(keys) == 1 {
continue
}
var ungated []string
for _, key := range keys {
if fns[key].ParamIndex(versionMintGate) < 0 {
ungated = append(ungated, key)
}
}
if len(ungated) > 0 {
t.Errorf("%q is called with %s=false (by %s) and resolves to %q, of which %q declare no %s: the switch-off would drop the fixpoint's edge to a function it cannot have switched off — rename one of them, or give it a %s parameter", callee, versionMintGate, caller, keys, ungated, versionMintGate, versionMintGate)
}
}
}
if switchedOff == 0 {
t.Fatalf("no %s=false call found in issueops — the composite mutations no longer switch their constituents off, or the predicate stopped seeing the literal; the guard is not exercising the switch-off at all", versionMintGate)
}
}
// TestEveryVersionedEntryPointMints parses this package's source, builds the
// intra-package call graph, and asserts every versioned entry point reaches
// RecordVersionInTx directly or through a function that transitively does.
// If a listed mutation stops minting — directly or through its delegates —
// this test fails.
func TestEveryVersionedEntryPointMints(t *testing.T) {
fns, mints := versionMints(t)
for _, entry := range versionedEntryPoints {
if _, defined := fns[entry]; !defined {
t.Errorf("versioned entry point %q not found in issueops — was it renamed? update versionedEntryPoints", entry)
continue
}
if !mints[entry] {
t.Errorf("versioned entry point %q does not mint a version: it neither calls RecordVersionInTx nor a function that transitively does", entry)
}
}
}
// TestEveryBeadMutatorMintsOrIsExempt is the STRUCTURAL completeness
// cross-check. It detects, by DML rather than by name, every EXPORTED function
// that writes a work-bead table (INSERT / UPDATE / DELETE against issues,
// wisps, dependencies, labels, comments, and their wisp variants — literal or
// templated table name), and asserts each one mints (reaches RecordVersionInTx
// directly or transitively) OR is explicitly exempted with a reason. A new
// exported mutator that writes a bead table therefore cannot ship without
// either versioning or being justified in versionExemptions.
func TestEveryBeadMutatorMintsOrIsExempt(t *testing.T) {
fns, mints := versionMints(t)
beadDML := journalscan.Fixpoint(fns,
func(f *journalscan.FuncInfo) bool { return f.OwnBeadDML },
func(f *journalscan.FuncInfo) []string { return f.IdentCalls })
seenExempt := map[string]bool{}
var checked int
for key, f := range fns {
if f.Recv != "" || !f.Exported || !beadDML[key] {
continue
}
if reason, ok := versionExemptions[f.Name]; ok {
if reason == "" {
t.Errorf("%s has an empty exemption reason", f.Name)
}
seenExempt[f.Name] = true
continue
}
checked++
if !mints[key] {
t.Errorf("exported function %q writes a work-bead table but mints no version (no RecordVersionInTx directly or transitively) and is not exempted — make it mint, or add it to versionExemptions with a reason", f.Name)
}
}
if checked == 0 {
t.Fatal("cross-check found no exported bead mutators — DML detection or parsing changed; the guard is not actually running")
}
for m := range versionExemptions {
if !seenExempt[m] {
t.Errorf("exemption %q no longer matches an exported bead-writing function — remove it", m)
}
}
}
// TestVersionNeverMintsPathsStaySilent is the inverse guard. A deliberate
// decision NOT to version is as much a contract as a decision to version, and
// the structural check above cannot defend it. Each entry must still exist (a
// rename invalidates the ruling) and must still be silent (an added mint
// reverses it).
func TestVersionNeverMintsPathsStaySilent(t *testing.T) {
fns, mints := versionMints(t)
for name, reason := range versionNeverMints {
if reason == "" {
t.Errorf("%s has an empty exemption reason", name)
}
if _, defined := fns[name]; !defined {
t.Errorf("never-mints path %q not found in issueops — was it renamed? update versionNeverMints", name)
continue
}
if mints[name] {
t.Errorf("never-mints path %q now reaches RecordVersionInTx, reversing a deliberate ruling: %s\n"+
"If the ruling changed, move it to versionedEntryPoints; otherwise remove the mint.", name, reason)
}
}
}
// TestVersionedEntryPointsAreNotExempt keeps the two tables disjoint: a
// function cannot both be required to mint and be excused from it.
func TestVersionedEntryPointsAreNotExempt(t *testing.T) {
for _, entry := range versionedEntryPoints {
if _, ok := versionExemptions[entry]; ok {
t.Errorf("%q is both a versioned entry point and exempt — pick one", entry)
}
if _, ok := versionNeverMints[entry]; ok {
t.Errorf("%q is both a versioned entry point and a never-mints path — pick one", entry)
}
}
}

View file

@ -0,0 +1,260 @@
package issueops
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/gowebpki/jcs"
)
// Dual-write issue-version history records every accepted issue mutation as a
// row in issue_versions, written in the SAME transaction as the mutation
// itself (see internal/storage/schema/migrations/0067_add_versioned_beads_schema.up.sql).
// Activation mirrors the durable events journal (journal.go): a per-instance
// flag (storage.VersionedHistoryConfigurer) is bound to a concrete
// transaction via ScopeVersionedHistoryTransaction immediately after
// BeginTx, so enabling history on one store instance cannot turn it on for
// any other sharing the process.
//
// RecordVersionInTx is the single seam both direct-SQL legs (dolt,
// embeddeddolt) and the domain/db package (used by uow) call through, from
// inside the same already-short-circuited functions that call
// RecordEventInTx — every accepted mutation of an issue's durable state
// (create, update, close, reopen, claim, release, lease reclaim, defer wake,
// label add/remove, dependency add/remove, promote, persistence move) mints
// exactly one row, as its LAST durable-state write; a no-op mints none. A
// mutation DiscardNoopIssueUpdates has already discarded never reaches either
// seam; the label and dependency helpers, which that filter does not cover,
// gate on their own inserted/deleted row instead (an idempotent re-add or an
// absent remove never reaches this seam either). Composite mutations —
// ExecuteUpdate's claim + row write + label/parent/persistence patches, and a
// batch create's rows + creation-time edges — run their constituents without
// minting and mint once at the end, so the version carries the final state.
// version_completeness_test.go pins the set of issueops functions that must
// reach this seam and the ones deliberately exempt from it.
//
// Ordinals are LOCAL, not wire addresses. issues.current_revision and
// issue_versions.revision are per-store ordinals, minted as MAX(revision)+1
// inside the writing transaction: two disconnected clones can both hold
// revision 8 for the same issue, each describing a different state. The
// only durable address of a version is version_id (migration 0068 steps
// 1-3, not yet landed). The HTTP API's RowVersion/Revision is a
// compare-and-set token, never an address; Phase 3's read surface returns
// version_id, never the ordinal.
//
// SINGLE WRITER ONLY until the version_id primary-key swap lands. With
// PRIMARY KEY (issue_id, revision), two disconnected writers that each mint
// the same ordinal for the same issue collide on merge, and
// TryAutoResolveMergeConflicts (internal/storage/versioncontrolops/mergesettle.go) fails the
// pull for a table it does not know. Enabling versioned history is therefore
// safe only with a SINGLE writer per store until migration 0068 steps 1-3
// (UUID version_id primary key, ordinal demoted to an index) land; those
// steps follow as their own PR.
//
// "Single writer" means one writer AT A TIME per store, not merely one
// clone. SELECT COALESCE(MAX(revision), 0) + 1 against PRIMARY KEY
// (issue_id, revision) is not a safe allocator for two concurrent
// transactions in one store either, and the label and dependency paths are
// not serialized on the issue row the way the claim/close CAS is; the
// RunDualWrite* contract cases exclude concurrent writers, so no test
// speaks to it. Tracked as gastownhall/beads#6379 (item 4).
var versionedHistoryTransactions sync.Map // map[DBTX]bool; entries live for one transaction
// ScopeVersionedHistoryTransaction associates versioned-history activation
// with one concrete transaction and returns a cleanup function. Store
// implementations call it immediately after BeginTx, alongside (not instead
// of) ScopeEventsJournalTransaction. This is instance/project scoped even
// when many stores share a process; there is no process-wide activation
// switch.
func ScopeVersionedHistoryTransaction(tx DBTX, enabled bool) func() {
if tx == nil {
return func() {}
}
versionedHistoryTransactions.Store(tx, enabled)
return func() { versionedHistoryTransactions.Delete(tx) }
}
func versionedHistoryEnabled(tx DBTX) bool {
enabled, _ := versionedHistoryTransactions.Load(tx)
on, _ := enabled.(bool)
return on
}
// issue_versions.attribution_status is a NOT NULL column (migration 0068
// step 6) whose vocabulary aligns to BDP's carried-attribution status
// (gastownhall/bdp#18, merged 2026-09-07): status ∈ {claimed, unknown}. A
// status is an assertion about the actor the mutation arrived with —
// "claimed" when one was supplied, "unknown" when the mutation path had none
// — and is derived from the same actor string every RecordVersionInTx call
// site already passes (no call site carries any other attribution signal).
//
// "imported" is deliberately NOT a status: it is provenance (where a row
// came from), not an assertion about who performed the mutation. It returns
// as a separate provenance marker in the phase that first imports history;
// no writer for it exists yet — Phase 2 is this table's sole writer, and
// every row it mints originated as an accepted mutation.
const (
attributionStatusClaimed = "claimed"
attributionStatusUnknown = "unknown"
)
// attributionStatusForActor derives issue_versions.attribution_status from
// the same actor string every RecordVersionInTx call site already passes: a
// non-empty actor is "claimed", an empty one is "unknown". There is no
// third value — an empty actor means the path had no identity to assert,
// which is exactly what "unknown" says; any stronger reading (a deliberate,
// confirmed absence of attribution) is a claim no call site makes.
func attributionStatusForActor(actor string) string {
if actor == "" {
return attributionStatusUnknown
}
return attributionStatusClaimed
}
// canonicalDurableState renders issue as the bytes RecordVersionInTx stores
// in issue_versions.durable_state: encoding/json's marshal of the issue,
// canonicalized per RFC 8785 (JCS). The canonical form is a function of the
// issue's content alone -- keys sorted, numbers in their one ES6 form
// (1.0 is 1, 1e300 is 1e+300), only the escapes RFC 8785 requires -- so the
// same issue state always yields the same bytes, whatever encoding/json's
// formatting happens to be. Numbers are canonicalized as IEEE-754 doubles
// (RFC 8785 section 3.2.2.3), so an integer past 2^53 is rounded here, once,
// by the writer, before anything hashes it: the stored bytes and the hashed
// bytes are the same bytes. types.Issue carries no such magnitudes (its
// integers are ordinals and priorities), but the rule is stated so nobody
// expects int64 fidelity from the token.
//
// Two properties worth stating because a hand-rolled canonicalizer would get
// them wrong. First, jcs.Transform normalizes away encoding/json's HTML
// escaping of <, > and &, so the token is a function of content, not of
// Go's escaping policy. Second, a snapshot that cannot be canonicalized
// deliberately FAILS the mutation: types.Issue.Metadata is a json.RawMessage
// passed through verbatim, RFC 8785 rejects duplicate keys, and this seam
// returns the error to its caller, which aborts the transaction. An issue
// whose metadata column already holds duplicate keys (reachable through bd
// sql or a hand-written JSONL import) therefore mutates fine with the flag
// off and becomes unmutatable with it on. Fail-closed is the policy for now
// -- bytes that could canonicalize two ways would not be a content token --
// and whether to normalize such metadata first, or to find such rows with
// bd doctor, is gastownhall/beads#6379 (item 3).
func canonicalDurableState(issue any) ([]byte, error) {
marshaled, err := json.Marshal(issue)
if err != nil {
return nil, err
}
canonical, err := jcs.Transform(marshaled)
if err != nil {
return nil, fmt.Errorf("canonicalize (RFC 8785): %w", err)
}
return canonical, nil
}
// RecordVersionInTx mints one issue_versions row for issueID and advances
// issues.current_revision to match, as of tx (read-your-writes within the
// same transaction). A no-op when versioned history is disabled for tx, or
// when issueID resolves to a wisp: wisps carry current_revision for shape
// parity only and are never versioned this phase (design FR-8). IsWisp is
// Ephemeral || NoHistory, so a promoted no-history bead -- a durable
// issues-plane row with NoHistory=true -- is also never versioned; that is
// what no-history means, not an FR-8 wisp rule, and the write-path doc's
// row 13 says so.
//
// The revision it mints is a local ordinal, not an address — see the
// package comment above on ordinals versus version_id, and on the
// single-writer constraint that holds until version_id lands.
//
// actor is the acting identity that performed the mutation, recorded as the
// version row's attribution — "" when the mutation path genuinely has none,
// matching RecordEventInTx's own convention. It also drives
// attribution_status via attributionStatusForActor.
func RecordVersionInTx(ctx context.Context, tx DBTX, issueID, actor string) error {
if !versionedHistoryEnabled(tx) {
return nil
}
issue, err := GetIssueInTx(ctx, tx, issueID)
if err != nil {
return fmt.Errorf("versioned history: snapshot %s: %w", issueID, err)
}
if IsWisp(issue) {
return nil
}
// durable_state is the RFC 8785 (JCS) canonical form of the marshaled
// issue, stored as bytes -- issue_versions.durable_state is a LONGBLOB
// (migration 0068 step 7), not a JSON column. The invariant that buys,
// the one donnabox asked for on #6358 item 4: sha256(stored bytes) is a
// stable content token, because the bytes read back are exactly the
// bytes the writer produced. A Dolt JSON column could not provide that.
// It parses and renormalizes what it stores (measured on dolt 2.2.3:
// 1.0 reads back as 1, 9007199254740993 as 9007199254740992, 1e300 as
// 1e+300, while a LONGBLOB returns the same bytes) -- so the design's
// verbatim-bytes promise (R5.1) and any content-derived token (#5898's
// sha256-jcs) broke between the writer and the disk. JCS pins the bytes
// on the way in (canonicalDurableState); LONGBLOB keeps them as written.
//
// The snapshot itself is the mutated issue (design §15.3, corrected by
// §17.1): the write-path loader GetIssueInTx never hydrates Dependencies
// (types.Issue.Dependencies is omitempty and unrelated to this snapshot's
// own read), so it is populated here, once, for every caller of this
// seam — in GetDependencyRecordsForIssuesInTx's own ordering (issue_id,
// depends_on_id, type, id).
deps, err := GetDependencyRecordsForIssuesInTx(ctx, tx, []string{issueID})
if err != nil {
return fmt.Errorf("versioned history: load dependencies for %s: %w", issueID, err)
}
issue.Dependencies = deps[issueID]
// store_epoch is one shared row (id = 1) that every minting transaction
// reads. Read first and seed only when the row is absent, so the seed
// INSERT happens once per store rather than once per mint: an INSERT IGNORE
// on every mint put that shared row into every write transaction's
// footprint for nothing.
var epoch int
err = tx.QueryRowContext(ctx, "SELECT epoch FROM store_epoch WHERE id = 1").Scan(&epoch)
if errors.Is(err, sql.ErrNoRows) {
if _, seedErr := tx.ExecContext(ctx, "INSERT IGNORE INTO store_epoch (id, epoch) VALUES (1, 1)"); seedErr != nil {
return fmt.Errorf("versioned history: seed store epoch: %w", seedErr)
}
err = tx.QueryRowContext(ctx, "SELECT epoch FROM store_epoch WHERE id = 1").Scan(&epoch)
}
if err != nil {
return fmt.Errorf("versioned history: read store epoch: %w", err)
}
var newRevision int64
if err := tx.QueryRowContext(ctx,
"SELECT COALESCE(MAX(revision), 0) + 1 FROM issue_versions WHERE issue_id = ?", issueID,
).Scan(&newRevision); err != nil {
return fmt.Errorf("versioned history: compute next revision for %s: %w", issueID, err)
}
durableState, err := canonicalDurableState(issue)
if err != nil {
return fmt.Errorf("versioned history: marshal durable state for %s: %w", issueID, err)
}
// durableState is bound as []byte, a LONGBLOB parameter -- never
// string(durableState), which would ask the driver to treat it as text.
if _, err := tx.ExecContext(ctx,
`INSERT INTO issue_versions
(issue_id, revision, epoch, durable_state, change_actor, change_agent, change_message, change_at, attribution_status)
VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?)`,
issueID, newRevision, epoch, durableState, actor, time.Now().UTC(), attributionStatusForActor(actor),
); err != nil {
return fmt.Errorf("versioned history: insert version row for %s: %w", issueID, err)
}
if _, err := tx.ExecContext(ctx,
"UPDATE issues SET current_revision = ? WHERE id = ?", newRevision, issueID,
); err != nil {
return fmt.Errorf("versioned history: advance current_revision for %s: %w", issueID, err)
}
return nil
}

View file

@ -0,0 +1,228 @@
package issueops
import (
"bytes"
"crypto/sha256"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
// TestCanonicalDurableStateIsJCS pins that canonicalDurableState -- the one
// helper RecordVersionInTx stores through -- emits the RFC 8785 (JCS) form,
// not encoding/json's, and that the difference is real: the same value
// marshaled without the JCS step yields different bytes.
//
// Why this matters (donnabox on gastownhall/beads#6358 item 4): the token
// the design derives from durable_state (#5898, sha256-jcs) is only stable if
// the bytes hashed are the bytes stored. Migration 0068 step 7 makes the
// column a LONGBLOB so storage keeps bytes verbatim; this test covers the
// other half, that the writer's bytes are the canonical ones in the first
// place, so the token is a function of content and not of whatever
// encoding/json or a caller-supplied json.Number happened to emit.
//
// The number inputs use json.Number and json.RawMessage deliberately: they
// are the only way to get encoding/json to emit a non-canonical number form
// such as 1.0 or 1E300 verbatim (a float64 1.0 already marshals as 1), which
// is exactly the input a JSON column would have renormalized on its own.
//
// Numbers are one axis. The rest of the pin is table-driven: the RFC 8785
// test vectors that ship with gowebpki/jcs v1.0.1 (testdata/jcs, see its
// README.md), a key-ordering case the vectors leave implicit (RFC 8785
// sorts keys by UTF-16 code units, so an astral-plane key sorts AFTER "é"
// even though its first byte is smaller), and the one place encoding/json
// and RFC 8785 disagree for ordinary issue text: encoding/json escapes <, >
// and & as \u003c-style sequences and JCS does not, so the stored bytes must
// be the JCS form or the token would depend on which marshaler ran first.
// Every case is also checked to be a fixed point of canonicalization, and a
// duplicate-key input is refused rather than silently resolved.
func TestCanonicalDurableStateIsJCS(t *testing.T) {
t.Parallel()
cases := append(jcsTestVectors(t),
jcsCase{
name: "unicode and astral keys sort by UTF-16 code units",
state: json.RawMessage(`{"b":1,"a":2,"é":3,"A":4,"😀":5}`),
want: []byte(`{"A":4,"a":2,"b":1,"é":3,"😀":5}`),
},
jcsCase{
name: "html escapes are normalized away",
state: map[string]any{"s": `<a>&"'</a>`},
want: []byte(`{"s":"<a>&\"'</a>"}`),
},
)
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, err := canonicalDurableState(tc.state)
if err != nil {
t.Fatalf("canonicalDurableState: %v", err)
}
if !bytes.Equal(got, tc.want) {
t.Fatalf("canonicalDurableState =\n %s\nwant\n %s", got, tc.want)
}
// canonical(canonical(x)) == canonical(x): the stored bytes are
// a fixed point, so re-canonicalizing what was read back can
// never change the token.
again, err := canonicalDurableState(json.RawMessage(got))
if err != nil {
t.Fatalf("canonicalDurableState over its own output: %v", err)
}
if !bytes.Equal(again, got) {
t.Fatalf("canonical form is not a fixed point:\n %s\n %s", got, again)
}
})
}
t.Run("plain marshal html-escapes and the canonical form does not", func(t *testing.T) {
t.Parallel()
// The normalization above is doing work: the plain marshal of the
// same value carries encoding/json's HTML-safe escapes, which RFC
// 8785 does not permit (only the escapes it requires survive).
plain, err := json.Marshal(map[string]any{"s": `<a>&"'</a>`})
if err != nil {
t.Fatalf("json.Marshal: %v", err)
}
if !bytes.Contains(plain, []byte(`\u003c`)) || !bytes.Contains(plain, []byte(`\u0026`)) {
t.Fatalf("plain json.Marshal no longer HTML-escapes (%s); the fixture no longer exercises the normalization", plain)
}
got, err := canonicalDurableState(json.RawMessage(plain))
if err != nil {
t.Fatalf("canonicalDurableState: %v", err)
}
if bytes.Contains(got, []byte(`\u00`)) {
t.Fatalf("canonical form still carries a \\u00xx escape: %s", got)
}
})
t.Run("duplicate keys are rejected", func(t *testing.T) {
t.Parallel()
// RFC 8785 has no answer for a duplicate key (section 3.1 forbids
// them), and encoding/json's compaction lets the input through, so
// the JCS step is the only place a snapshot with two "k"s can be
// refused instead of stored with whichever value happened to win.
_, err := canonicalDurableState(json.RawMessage(`{"k":1,"k":2}`))
if err == nil {
t.Fatal("canonicalDurableState(duplicate keys) = nil error, want a refusal")
}
if !strings.Contains(err.Error(), "Duplicate key") {
t.Fatalf("canonicalDurableState(duplicate keys) error = %q, want it to name the duplicate key", err)
}
})
// Issue-shaped: string id, nested object, list, null, and the number
// forms that Dolt's JSON type is known to renormalize.
state := map[string]any{
"id": "bd-1",
"priority": json.Number("1.0"),
"metadata": map[string]any{
"weight": json.Number("1.50"),
"huge": json.Number("1E300"),
"ordinal": json.Number("9007199254740993"), // 2^53 + 1
"tags": []any{json.Number("2.0"), "b", nil},
},
"raw": json.RawMessage(`{ "z" : 10.0e0 , "a" : true }`),
}
got, err := canonicalDurableState(state)
if err != nil {
t.Fatalf("canonicalDurableState: %v", err)
}
// RFC 8785: keys sorted, no whitespace, numbers in ES6 Number::toString
// form (1.0 -> 1, 1.50 -> 1.5, 1E300 -> 1e+300, 2^53+1 -> the double it
// rounds to, 10.0e0 -> 10).
want := []byte(`{"id":"bd-1","metadata":{"huge":1e+300,"ordinal":9007199254740992,"tags":[2,"b",null],"weight":1.5},"priority":1,"raw":{"a":true,"z":10}}`)
if !bytes.Equal(got, want) {
t.Fatalf("canonicalDurableState =\n %s\nwant\n %s", got, want)
}
// The JCS step is doing work: a plain marshal of the same value keeps
// the caller's number forms and spacing, so its bytes differ.
plain, err := json.Marshal(state)
if err != nil {
t.Fatalf("json.Marshal: %v", err)
}
if bytes.Equal(plain, got) {
t.Fatalf("plain json.Marshal already equals the canonical form (%s); this test no longer proves canonicalization matters", plain)
}
for _, nonCanonical := range []string{"1.0", "1.50", "1E300", "9007199254740993", "10.0e0"} {
if !bytes.Contains(plain, []byte(nonCanonical)) {
t.Errorf("plain marshal lost the non-canonical form %q, so the fixture no longer exercises it: %s", nonCanonical, plain)
}
if bytes.Contains(got, []byte(nonCanonical)) {
t.Errorf("canonical form still carries the non-canonical form %q: %s", nonCanonical, got)
}
}
// Determinism: the token is a function of the content. A second pass
// over the same value, and over the already-canonical bytes, hashes
// identically.
again, err := canonicalDurableState(state)
if err != nil {
t.Fatalf("canonicalDurableState (second pass): %v", err)
}
if sha256.Sum256(again) != sha256.Sum256(got) {
t.Fatalf("canonicalDurableState is not deterministic:\n %s\n %s", got, again)
}
idempotent, err := canonicalDurableState(json.RawMessage(got))
if err != nil {
t.Fatalf("canonicalDurableState over its own output: %v", err)
}
if !bytes.Equal(idempotent, got) {
t.Fatalf("canonical form is not a fixed point:\n %s\n %s", got, idempotent)
}
}
// jcsCase is one canonicalization pin: what RecordVersionInTx would hand to
// canonicalDurableState, and the exact bytes RFC 8785 says come out.
type jcsCase struct {
name string
state any
want []byte
}
// jcsTestVectors loads the RFC 8785 input/expected pairs under testdata/jcs
// (provenance in its README.md; the upstream "output" directory is named
// "expected" here because the repository's .gitignore drops any output/
// tree). The count is pinned so an emptied or half-copied directory cannot
// pass as a vacuous table.
func jcsTestVectors(t *testing.T) []jcsCase {
t.Helper()
const shipped = 10 // the vectors in gowebpki/jcs v1.0.1's testdata
dir := filepath.Join("testdata", "jcs")
entries, err := os.ReadDir(filepath.Join(dir, "input"))
if err != nil {
t.Fatalf("list RFC 8785 vectors: %v", err)
}
var cases []jcsCase
for _, entry := range entries {
input, err := os.ReadFile(filepath.Join(dir, "input", entry.Name()))
if err != nil {
t.Fatalf("read RFC 8785 vector input: %v", err)
}
want, err := os.ReadFile(filepath.Join(dir, "expected", entry.Name()))
if err != nil {
t.Fatalf("read RFC 8785 vector output: %v", err)
}
cases = append(cases, jcsCase{name: "rfc8785 vector " + entry.Name(), state: json.RawMessage(input), want: want})
}
if len(cases) != shipped {
t.Fatalf("found %d RFC 8785 vectors under %s, want the %d that ship with gowebpki/jcs v1.0.1", len(cases), dir, shipped)
}
return cases
}
// TestCanonicalDurableStateRejectsUnmarshalableState pins that a value
// encoding/json cannot marshal surfaces as an error rather than as an empty
// or partial snapshot, so RecordVersionInTx fails the transaction instead of
// minting a version row whose durable_state says nothing.
func TestCanonicalDurableStateRejectsUnmarshalableState(t *testing.T) {
t.Parallel()
if _, err := canonicalDurableState(map[string]any{"ch": make(chan int)}); err == nil {
t.Fatal("canonicalDurableState(unmarshalable) = nil error, want an error")
}
}

View file

@ -0,0 +1,61 @@
package issueops
import "testing"
// These tests pin the derivation rule for issue_versions.attribution_status,
// the NOT NULL column migration 0068 step 6 adds. Its vocabulary is BDP's
// carried-attribution status (gastownhall/bdp#18, merged 2026-09-07): exactly
// two values, "claimed" and "unknown". "imported" is provenance, not an
// assertion, and is not a status — it returns as a separate provenance marker
// in the phase that first imports history, for which no writer exists yet.
//
// RecordVersionInTx receives only a plain actor string from every call site
// (none passes any additional attribution context), so the only signal
// available to derive attribution_status from is whether actor is empty: a
// non-empty actor is "claimed", an empty one is "unknown".
func TestAttributionStatusForActor(t *testing.T) {
t.Parallel()
tests := []struct {
name string
actor string
want string
}{
{name: "non-empty actor is claimed", actor: "alice", want: attributionStatusClaimed},
{name: "empty actor is unknown", actor: "", want: attributionStatusUnknown},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := attributionStatusForActor(tc.actor); got != tc.want {
t.Errorf("attributionStatusForActor(%q) = %q, want %q", tc.actor, got, tc.want)
}
})
}
}
// TestAttributionStatusValuesMatchBDP pins the two legal values verbatim
// against bdp#18's vocabulary, so a future edit cannot silently rename one,
// or reintroduce a value BDP does not carry, without failing here — and
// checks that the derivation never yields anything outside that set.
func TestAttributionStatusValuesMatchBDP(t *testing.T) {
t.Parallel()
values := map[string]string{
"claimed": attributionStatusClaimed,
"unknown": attributionStatusUnknown,
}
for want, got := range values {
if got != want {
t.Errorf("attribution status constant = %q, want %q", got, want)
}
}
legal := map[string]bool{"claimed": true, "unknown": true}
for _, actor := range []string{"", "alice", "agent:builder"} {
if got := attributionStatusForActor(actor); !legal[got] {
t.Errorf("attributionStatusForActor(%q) = %q, want one of claimed|unknown", actor, got)
}
}
}

View file

@ -138,6 +138,11 @@ func wakeExpiredDefersInTable(ctx context.Context, tx DBTX, table, eventsTable s
if err := RecordEventInTx(ctx, tx, EventUpdate, id, DeferWakeActor); err != nil {
return woken, err
}
// The status flip is durable state, so the woken bead is versioned
// under the same system actor the event carries.
if err := RecordVersionInTx(ctx, tx, id, DeferWakeActor); err != nil {
return woken, err
}
woken = append(woken, id)
}
return woken, nil

View file

@ -13,6 +13,7 @@ import (
"go/token"
"io/fs"
"regexp"
"sort"
"strings"
)
@ -22,11 +23,28 @@ type FuncInfo struct {
Recv string // receiver type name ("" for free functions)
Name string // bare method/function name
Exported bool // the bare name is exported
Params []string // declared parameter names, in order ("" for an unnamed one)
IdentCalls []string // intra-package bare-identifier calls (free functions)
SelCalls []string // selector calls, by selector name (x.Foo -> "Foo")
Calls []Call // every call, bare or selector, with its arguments
OwnBeadDML bool // body issues INSERT/UPDATE/DELETE against a bead table
}
// Call is one call expression in a function body: the called name (a bare
// identifier, or the selector name of x.Foo) and its arguments, each reduced
// to the bare identifier or literal it passes — "" for any other expression.
// The predeclared false and true read as "false" and "true"; a false or true
// that names a declaration of the package's own instead — a shadow, whether
// the parser resolved it within its file or some file declares the name at
// package level — is "" like any other expression the scanner cannot vouch
// for, so a shadow never reads as the literal. A caller forwarding its own
// parameter reads as that parameter's name, which is what lets a guard tell
// "switched off here" from "left to the caller".
type Call struct {
Name string
Args []string
}
// AllCallNames returns every called name, both bare-identifier and selector.
func (f *FuncInfo) AllCallNames() []string {
return append(append([]string{}, f.IdentCalls...), f.SelCalls...)
@ -42,6 +60,17 @@ func (f *FuncInfo) CallsAnyOf(set map[string]bool) bool {
return false
}
// ParamIndex returns the position of f's parameter named name, or -1 when f
// declares none by that name.
func (f *FuncInfo) ParamIndex(name string) int {
for i, p := range f.Params {
if p == name {
return i
}
}
return -1
}
// ReceiverTypeName returns the bare type name of a method receiver
// (e.g. *fooImpl -> fooImpl).
func ReceiverTypeName(expr ast.Expr) string {
@ -58,12 +87,31 @@ func ReceiverTypeName(expr ast.Expr) string {
// top-level function/method, keyed by "Recv.Name" (or "Name" for free funcs).
func ParsePackage(dir string) (map[string]*FuncInfo, error) {
fset := token.NewFileSet()
// Mode 0 keeps the parser's per-file identifier resolution on. It is what
// lets argNames tell the predeclared false and true from a shadow of the
// same name; under SkipObjectResolution every shadow would read as the
// literal. TestCallsOnlyWithLiteralFalse pins this.
pkgs, err := parser.ParseDir(fset, dir, func(fi fs.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, 0)
if err != nil {
return nil, err
}
// That resolution stops at the file: a use in one file of a false another
// file declares at package level stays unresolved, exactly like the
// predeclared one, though to the compiler it denotes the declaration.
// Fold every file's package-level declarations in so argNames refuses
// those too (TestPackageLevelShadowCrossesFiles).
shadowed := map[string]bool{}
for _, pkg := range pkgs {
for _, file := range pkg.Files {
for name := range predeclaredBools {
if file.Scope != nil && file.Scope.Lookup(name) != nil {
shadowed[name] = true
}
}
}
}
out := map[string]*FuncInfo{}
for _, pkg := range pkgs {
for _, file := range pkg.Files {
@ -72,7 +120,7 @@ func ParsePackage(dir string) (map[string]*FuncInfo, error) {
if !ok {
continue
}
f := &FuncInfo{Name: fn.Name.Name, Exported: fn.Name.IsExported()}
f := &FuncInfo{Name: fn.Name.Name, Exported: fn.Name.IsExported(), Params: paramNames(fn.Type)}
if fn.Recv != nil && len(fn.Recv.List) > 0 {
f.Recv = ReceiverTypeName(fn.Recv.List[0].Type)
}
@ -82,8 +130,10 @@ func ParsePackage(dir string) (map[string]*FuncInfo, error) {
switch fun := node.Fun.(type) {
case *ast.Ident:
f.IdentCalls = append(f.IdentCalls, fun.Name)
f.Calls = append(f.Calls, Call{Name: fun.Name, Args: argNames(node.Args, shadowed)})
case *ast.SelectorExpr:
f.SelCalls = append(f.SelCalls, fun.Sel.Name)
f.Calls = append(f.Calls, Call{Name: fun.Sel.Name, Args: argNames(node.Args, shadowed)})
}
case *ast.BasicLit:
if node.Kind == token.STRING && SQLWritesBeadTable(node.Value) {
@ -103,23 +153,135 @@ func ParsePackage(dir string) (map[string]*FuncInfo, error) {
return out, nil
}
// paramNames flattens a signature's parameter list into one entry per
// parameter, so a position in it lines up with a position in a call's
// argument list: "a, b int" is two entries, and an unnamed parameter is "".
func paramNames(sig *ast.FuncType) []string {
if sig == nil || sig.Params == nil {
return nil
}
var names []string
for _, field := range sig.Params.List {
if len(field.Names) == 0 {
names = append(names, "")
continue
}
for _, name := range field.Names {
names = append(names, name.Name)
}
}
return names
}
// predeclaredBools are the names argNames reads as the boolean literals when
// nothing in the package declares them.
var predeclaredBools = map[string]bool{"false": true, "true": true}
// argNames reduces call arguments to the bare identifier or literal each one
// passes; anything else (a call, a selector, a composite literal) is "". So
// is a false or true that does not denote the predeclared identifier: one the
// parser resolved to a declaration in its own file (a.Obj != nil — a local, a
// parameter, a package-level declaration in the same file) or whose name some
// file declares at package level (shadowed, from ParsePackage).
func argNames(args []ast.Expr, shadowed map[string]bool) []string {
names := make([]string, len(args))
for i, arg := range args {
switch a := arg.(type) {
case *ast.Ident:
if predeclaredBools[a.Name] && (a.Obj != nil || shadowed[a.Name]) {
continue
}
names[i] = a.Name
case *ast.BasicLit:
names[i] = a.Value
}
}
return names
}
// Resolve maps a called bare name to the function keys it can denote: the
// free function of that name, if any, then every method of that name in key
// order (name-based resolution, sufficient for a guard). It is the one
// resolution Fixpoint and CallsOnlyWithLiteralFalse use, exported so a guard
// reasoning about a called name's targets — whether a switch-off is
// unambiguous, whether a live edge reaches the seam through a method — sees
// exactly the keys the fixpoint follows.
func Resolve(fns map[string]*FuncInfo, name string) []string {
var keys []string
if _, ok := fns[name]; ok {
keys = append(keys, name)
}
var methods []string
for key, f := range fns {
if f.Recv != "" && f.Name == name {
methods = append(methods, key)
}
}
sort.Strings(methods)
return append(keys, methods...)
}
// CallsOnlyWithLiteralFalse reports whether f calls callee, and every one of
// those calls passes the predeclared identifier false for callee's boolean
// parameter named gate — the argument callee's own body reads as "skip the
// gated write". A guard that follows call edges to find who reaches a seam
// uses it to drop the edges a caller has explicitly switched off, so a
// composite mutation that runs its constituents with the gate off and
// performs the gated write once itself is not credited with the one it told
// them to skip.
//
// What is checked is the reduced argument (see Call): the bare name false,
// counted as the predeclared identifier only when it resolves to no
// declaration of the package's own. Go lets a local, a parameter or a
// package-level declaration shadow false, and any such shadow reads as an
// unknown expression, never as a switch-off. A consumer can pin that its
// package declares no such shadow at all, so that the name-based reading is
// exact there rather than merely conservative; issueops does, in
// TestFalseIsNotShadowedInIssueops.
//
// The edge stays live (false is returned) whenever the switch-off is not
// certain: callee is unknown or declares no parameter named gate, f never
// calls it, at least one of f's calls passes anything but the literal (true,
// a variable, f's own parameter of that name, a shadowed false, an
// expression), or a call is too short to line up with the signature. callee
// resolves the way Fixpoint resolves edges — Resolve: the free function of
// that name and every method of that name — and every resolution that
// declares the gate must see false. A resolution that declares no gate is
// not consulted, so when a gated function shares its name with an ungated
// one a true result drops the fixpoint's edge to the ungated one too; a
// consumer relying on the switch-off should pin that no literal-false
// callee's name is shared that way (issueops does, in
// TestLiteralFalseCalleesResolveUnambiguously).
func CallsOnlyWithLiteralFalse(fns map[string]*FuncInfo, f *FuncInfo, callee, gate string) bool {
var gateAt []int
for _, key := range Resolve(fns, callee) {
if i := fns[key].ParamIndex(gate); i >= 0 {
gateAt = append(gateAt, i)
}
}
if len(gateAt) == 0 {
return false
}
called := false
for _, call := range f.Calls {
if call.Name != callee {
continue
}
called = true
for _, i := range gateAt {
if i >= len(call.Args) || call.Args[i] != "false" {
return false
}
}
}
return called
}
// Fixpoint returns the set of function keys for which seed is true or which
// (transitively) call a name for which it becomes true, following edges. A
// called bare name resolves to a free function of that name and to any method
// with that name (name-based resolution, sufficient for a guard).
// with that name (Resolve: name-based resolution, sufficient for a guard).
func Fixpoint(fns map[string]*FuncInfo, seed func(*FuncInfo) bool, edges func(*FuncInfo) []string) map[string]bool {
resolve := func(name string) []string {
var keys []string
if _, ok := fns[name]; ok {
keys = append(keys, name)
}
for key, f := range fns {
if f.Recv != "" && f.Name == name {
keys = append(keys, key)
}
}
return keys
}
got := map[string]bool{}
for key, f := range fns {
if seed(f) {
@ -133,7 +295,7 @@ func Fixpoint(fns map[string]*FuncInfo, seed func(*FuncInfo) bool, edges func(*F
continue
}
for _, callee := range edges(f) {
for _, ck := range resolve(callee) {
for _, ck := range Resolve(fns, callee) {
if got[ck] {
got[key] = true
changed = true

View file

@ -1,6 +1,11 @@
package journalscan
import "testing"
import (
"os"
"path/filepath"
"reflect"
"testing"
)
// TestSQLWritesBeadTable pins the DML detector the completeness guards rest on.
// A false negative here silently disarms every guard, so the templated forms —
@ -43,3 +48,199 @@ func TestSQLWritesBeadTable(t *testing.T) {
}
}
}
// TestCallsOnlyWithLiteralFalse pins the gate predicate the versioned-history
// guard rests on: a call that passes the predeclared false for a helper's
// mintVersion-style parameter is switched off, and nothing else is — not a
// declaration of the package's own that borrows the name false, which the
// parser's per-file resolution (ParsePackage's mode 0) tells apart. A false
// positive here would drop a real minting edge (a spurious guard failure); a
// false negative would let a composite mutation keep inheriting the mint it
// told its constituents to skip (gastownhall/beads#6358 reviewer Probe 2),
// which is the hole the predicate exists to close.
func TestCallsOnlyWithLiteralFalse(t *testing.T) {
dir := t.TempDir()
src := `package probe
func seam() {}
func helper(mintVersion bool) {
if mintVersion {
seam()
}
}
// grouped declares the gate inside a grouped parameter list, so its position
// must be counted per name, not per group.
func grouped(a, b int, recordEvent, mintVersion bool) {
if mintVersion {
seam()
}
}
func SwitchedOff() { helper(false) }
func SwitchedOffGrouped() { grouped(1, 2, true, false) }
func SwitchedOn() { helper(true) }
func Variable() { off := false; helper(off) }
func Forwards(mintVersion bool) { helper(mintVersion) }
func Mixed() { helper(false); helper(true) }
func MintsItself() { helper(false); seam() }
func TooShort() { helper() }
func NoGate() { ungated(false) }
func ungated(other bool) { seam() }
func NeverCalls() {}
// The shadows: Go lets a declaration of the package's own take the name
// false, and none of them may read as the switch-off.
func ShadowedLocal() { false := true; helper(false) }
func ShadowedParam(false bool) { helper(false) }
func ShadowedInClosure() { func() { false := true; helper(false) }() }
`
if err := os.WriteFile(filepath.Join(dir, "probe.go"), []byte(src), 0o600); err != nil {
t.Fatal(err)
}
fns, err := ParsePackage(dir)
if err != nil {
t.Fatalf("ParsePackage: %v", err)
}
// The two facts the predicate is built from: declared parameter positions
// and the reduced argument list of every call.
if got := fns["grouped"].Params; !reflect.DeepEqual(got, []string{"a", "b", "recordEvent", "mintVersion"}) {
t.Errorf("grouped.Params = %q, want each name of a grouped parameter list counted separately", got)
}
if got := fns["grouped"].ParamIndex("mintVersion"); got != 3 {
t.Errorf("grouped.ParamIndex(mintVersion) = %d, want 3", got)
}
if got := fns["ungated"].ParamIndex("mintVersion"); got != -1 {
t.Errorf("ungated.ParamIndex(mintVersion) = %d, want -1", got)
}
if got := fns["Mixed"].Calls; !reflect.DeepEqual(got, []Call{{Name: "helper", Args: []string{"false"}}, {Name: "helper", Args: []string{"true"}}}) {
t.Errorf("Mixed.Calls = %+v, want both helper calls with their literal argument", got)
}
for _, name := range []string{"ShadowedLocal", "ShadowedParam", "ShadowedInClosure"} {
if got := fns[name].Calls; !reflect.DeepEqual(got, []Call{{Name: "helper", Args: []string{""}}}) {
t.Errorf("%s.Calls = %+v, want the shadowed false reduced to \"\" rather than read as the literal", name, got)
}
}
for _, tc := range []struct {
caller, callee string
want bool
}{
{"SwitchedOff", "helper", true},
{"SwitchedOffGrouped", "grouped", true},
{"MintsItself", "helper", true}, // the helper edge is off; what MintsItself does on its own is the fixpoint's business
{"SwitchedOn", "helper", false},
{"Variable", "helper", false},
{"Forwards", "helper", false},
{"Mixed", "helper", false},
{"TooShort", "helper", false},
{"NoGate", "ungated", false},
{"NeverCalls", "helper", false},
{"SwitchedOff", "missing", false},
{"ShadowedLocal", "helper", false},
{"ShadowedParam", "helper", false},
{"ShadowedInClosure", "helper", false},
} {
if got := CallsOnlyWithLiteralFalse(fns, fns[tc.caller], tc.callee, "mintVersion"); got != tc.want {
t.Errorf("CallsOnlyWithLiteralFalse(%s -> %s) = %v, want %v", tc.caller, tc.callee, got, tc.want)
}
}
// End to end: following only the edges the predicate leaves live credits
// exactly the callers that can reach the seam, and the predicate is what
// makes the difference — the plain edge set the journal guard follows
// still credits the switched-off callers.
seed := func(f *FuncInfo) bool { return f.CallsAnyOf(map[string]bool{"seam": true}) }
plain := Fixpoint(fns, seed, func(f *FuncInfo) []string { return f.AllCallNames() })
gated := Fixpoint(fns, seed, func(f *FuncInfo) []string {
var live []string
for _, callee := range f.AllCallNames() {
if !CallsOnlyWithLiteralFalse(fns, f, callee, "mintVersion") {
live = append(live, callee)
}
}
return live
})
for name, want := range map[string]bool{
"SwitchedOff": false, "SwitchedOffGrouped": false, "NeverCalls": false, "seam": false,
"SwitchedOn": true, "Variable": true, "Forwards": true, "Mixed": true, "MintsItself": true,
"TooShort": true, "NoGate": true, "helper": true, "grouped": true, "ungated": true,
"ShadowedLocal": true, "ShadowedParam": true, "ShadowedInClosure": true,
} {
if gated[name] != want {
t.Errorf("gated fixpoint reaches seam via %s = %v, want %v", name, gated[name], want)
}
}
for _, name := range []string{"SwitchedOff", "SwitchedOffGrouped"} {
if !plain[name] {
t.Errorf("plain fixpoint does not reach seam via %s; the probe no longer shows the gate doing any work", name)
}
}
}
// TestPackageLevelShadowCrossesFiles pins the half of shadow detection the
// parser cannot do alone. It resolves identifiers per file, so a use in one
// file of a false that another file declares at package level is unresolved,
// exactly like the predeclared one; ParsePackage folds every file's
// package-level declarations in, so such a use is no switch-off either — and,
// the shadow being package-wide, neither is any other false in the package.
func TestPackageLevelShadowCrossesFiles(t *testing.T) {
dir := t.TempDir()
files := map[string]string{
"a.go": `package probe
func seam() {}
func helper(mintVersion bool) {
if mintVersion {
seam()
}
}
func LooksSwitchedOff() { helper(false) }
`,
"b.go": `package probe
var false = true
`,
}
for name, src := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o600); err != nil {
t.Fatal(err)
}
}
fns, err := ParsePackage(dir)
if err != nil {
t.Fatalf("ParsePackage: %v", err)
}
if got := fns["LooksSwitchedOff"].Calls; !reflect.DeepEqual(got, []Call{{Name: "helper", Args: []string{""}}}) {
t.Errorf("LooksSwitchedOff.Calls = %+v, want the false shadowed by another file reduced to \"\"", got)
}
if CallsOnlyWithLiteralFalse(fns, fns["LooksSwitchedOff"], "helper", "mintVersion") {
t.Error("CallsOnlyWithLiteralFalse(LooksSwitchedOff -> helper) = true; a false shadowed at package level in another file read as the switch-off")
}
}
// TestResolve pins the name-based resolution every edge and every switch-off
// goes through: a bare name denotes the free function of that name and every
// method of that name — free function first, then methods in key order, so a
// guard's report of an ambiguity is stable.
func TestResolve(t *testing.T) {
fns := map[string]*FuncInfo{
"helper": {Name: "helper"},
"svc.helper": {Recv: "svc", Name: "helper"},
"db.helper": {Recv: "db", Name: "helper"},
"svc.other": {Recv: "svc", Name: "other"},
}
for name, want := range map[string][]string{
"helper": {"helper", "db.helper", "svc.helper"},
"other": {"svc.other"},
"missing": nil,
} {
if got := Resolve(fns, name); !reflect.DeepEqual(got, want) {
t.Errorf("Resolve(%q) = %q, want %q", name, got, want)
}
}
}

View file

@ -138,6 +138,16 @@ func cliCompatibleMigrationSQL(name, sqlText string) string {
// Replays over a database that never synced the wisp tables must use
// the frozen source text instead -- see cliSubstituteAssumesWispTables.
return cliMigration0067AddVersionedBeadsSchema
case "0068_add_attribution_status.up.sql":
// Direct DDL for the same reason as 0067: the source migration's
// PREPARE guards (INFORMATION_SCHEMA probes) are what make the raw
// .up.sql idempotent when replayed onto an already-migrated store,
// and the 2.2.x CLI no-ops a prepared ADD COLUMN and MODIFY COLUMN
// alike. issue_versions is always present here -- 0067 runs earlier
// in the same fresh-bundle series -- never carries attribution_status
// yet, and still has durable_state as the JSON type 0067 gave it, so
// both of 0068's steps always fire on a fresh bundle.
return cliMigration0068AddAttributionStatus
default:
return sqlText
}
@ -249,6 +259,18 @@ CREATE TABLE IF NOT EXISTS store_epoch (
ALTER TABLE issues ADD COLUMN current_revision BIGINT NOT NULL DEFAULT 1;
ALTER TABLE wisps ADD COLUMN current_revision BIGINT NOT NULL DEFAULT 1;`
// cliMigration0068AddAttributionStatus is 0068 with its two guarded PREPARE
// blocks replaced by the direct ALTERs they would run on a fresh database:
// step 6's ADD COLUMN attribution_status, and step 7's MODIFY COLUMN
// durable_state LONGBLOB (the byte-preserving type the review on
// gastownhall/beads#6358 item 4 asked for -- see the migration's step 7
// header). issue_versions is created earlier in the same series by 0067,
// which still creates durable_state as JSON and whose override is left
// untouched: 0068 is what retypes it. So the column always needs adding and
// the retype always fires here; no wisps twin exists for this table.
const cliMigration0068AddAttributionStatus = `ALTER TABLE issue_versions ADD COLUMN attribution_status VARCHAR(20) NOT NULL;
ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB;`
const cliMigration0041SplitDependenciesTarget = `DELETE FROM dolt_nonlocal_tables;
CALL DOLT_COMMIT('-Am', 'disable nonlocal tables for fk migrations');
SET FOREIGN_KEY_CHECKS = 0;

View file

@ -20,19 +20,6 @@ import (
const migration0067Up = "0067_add_versioned_beads_schema.up.sql"
const migration0067Down = "0067_add_versioned_beads_schema.down.sql"
// TestLatestVersionIncludesMigration0067 pins the real next free slot this
// phase claims. It is deliberately a hardcoded literal, not a comparison
// against another derived value: schema.LatestVersion() drifting to 67 for
// the wrong reason (an unrelated migration landing first) should still be
// caught by this test failing to explain why 67 is versioned-beads-shaped,
// which the CLI test below checks.
func TestLatestVersionIncludesMigration0067(t *testing.T) {
const want = 67
if got := LatestVersion(); got != want {
t.Fatalf("LatestVersion() = %d, want %d (issue_versions/store_epoch/issues.current_revision migration slot claimed by be-hs42e.2)", got, want)
}
}
// TestMigration0067AddsVersionedBeadsSchema is a pure-Go, DB-independent
// check of the frozen migration bytes themselves — it runs even where no
// `dolt` binary is available.
@ -164,7 +151,11 @@ func TestMigration0067AddsVersionedBeadsSchemaThroughDoltCLI(t *testing.T) {
requireDoltColumnShape(t, dir, "issue_versions", "issue_id", "varchar(255)", "NO")
requireDoltDataType(t, dir, "issue_versions", "revision", "bigint", "NO")
requireDoltDataType(t, dir, "issue_versions", "epoch", "int", "NO")
requireDoltDataType(t, dir, "issue_versions", "durable_state", "json", "YES")
// 0067 creates durable_state as JSON, and 0068 step 7 retypes it to
// LONGBLOB (Dolt's JSON type renormalizes numbers, so it cannot hold the
// verbatim bytes a content token hashes -- see 0068's step 7 header). This
// test runs the whole bundle, so the shape it sees is the LONGBLOB one.
requireDoltDataType(t, dir, "issue_versions", "durable_state", "longblob", "YES")
requireDoltColumnShape(t, dir, "issue_versions", "change_actor", "varchar(255)", "YES")
requireDoltColumnShape(t, dir, "issue_versions", "change_agent", "varchar(255)", "YES")
requireDoltColumnShape(t, dir, "issue_versions", "change_message", "text", "YES")
@ -194,8 +185,12 @@ func TestMigration0067AddsVersionedBeadsSchemaThroughDoltCLI(t *testing.T) {
requireDoltDataType(t, dir, "wisps", "current_revision", "bigint", "NO")
// Composite PK (issue_id, revision) is enforced: same pair twice fails.
runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:00')`)
if err := runDoltSQLExpectingError(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:01')`); err == nil {
// attribution_status is 0068's NOT NULL column (not yet Phase 1's
// concern, but present on any schema this test's fresh bundle produces),
// so both inserts must supply it or Dolt rejects them before the PK
// check below ever runs.
runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:00', 'unknown')`)
if err := runDoltSQLExpectingError(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:01', 'unknown')`); err == nil {
t.Error("duplicate (issue_id, revision) insert into issue_versions succeeded, want primary key violation")
}

View file

@ -0,0 +1,170 @@
package schema
import (
"os"
"strings"
"testing"
"github.com/steveyegge/beads/internal/testutil"
)
// Phase 2 of the versioned-beads epic (be-hs42e / gastownhall/beads#6132,
// this slice: be-hs42e.3 / #6135) adds one column: issue_versions gains a
// NOT NULL attribution_status (design §16.4, R14), written by
// RecordVersionInTx / attributionStatusForActor
// (internal/storage/issueops/version_history.go) from the same build that
// ships this migration, so the NOT NULL constraint never rejects a
// pre-existing row. Steps 1-5 of design §16.3 (the version_id PK swap and
// participation_generation) are a different bead's scope and are not in this
// migration file.
//
// Step 7 (added at review, donnabox on #6358 item 4) retypes
// issue_versions.durable_state from JSON to LONGBLOB: Dolt's JSON type
// renormalizes numbers, so it cannot keep the verbatim bytes (R5.1) that a
// content-derived token hashes. The writer now stores the RFC 8785 (JCS)
// canonical bytes; the table is empty in this era, so no data converts.
const migration0068Up = "0068_add_attribution_status.up.sql"
const migration0068Down = "0068_add_attribution_status.down.sql"
// TestLatestVersionIncludesMigration0068 pins the real next free slot this
// phase claims, superseding 0067's own version of this test (LatestVersion()
// moved from 67 to 68 the moment this migration file was added). Deliberately
// a hardcoded literal for the same reason 0067's was: LatestVersion()
// drifting to 68 for the wrong reason (an unrelated migration landing first)
// should still be caught by this test failing to explain why 68 is
// attribution-status-shaped, which the CLI test below checks.
func TestLatestVersionIncludesMigration0068(t *testing.T) {
const want = 68
if got := LatestVersion(); got != want {
t.Fatalf("LatestVersion() = %d, want %d (issue_versions.attribution_status migration slot claimed by be-hs42e.3)", got, want)
}
}
// TestMigration0068AddsAttributionStatus is a pure-Go, DB-independent check
// of the frozen migration bytes themselves — it runs even where no `dolt`
// binary is available.
//
// It pins the same guarded-PREPARE shape 0067 uses and for the same reason:
// the guard is what makes a raw replay of this file onto an already-migrated
// store a no-op (internal/storage/dolt's pr4107 replay harness requires this
// of every migration >= 0046), and Dolt accepts no unprepared conditional
// ADD COLUMN. The cost is the same pre-2.3 CLI hazard 0060/0065/0066/0067
// carry, so this migration needs the same direct-DDL override in
// cliCompatibleMigrationSQL, policed by the same two guard tests
// (TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified and
// TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities).
func TestMigration0068AddsAttributionStatus(t *testing.T) {
upSQL, err := MigrationSQL(migration0068Up)
if err != nil {
t.Fatalf("MigrationSQL(%s) error = %v, want the migration file to exist", migration0068Up, err)
}
for _, want := range []string{
"ALTER TABLE issue_versions ADD COLUMN attribution_status VARCHAR(20) NOT NULL",
"COLUMN_NAME = 'attribution_status'",
"@issue_versions_as_needs_add",
// Step 7: the durable_state retype, guarded on DATA_TYPE (0057's
// shape) so a replay onto a store already at LONGBLOB no-ops.
"ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB",
"COLUMN_NAME = 'durable_state'",
"@issue_versions_ds_needs_retype",
"DATA_TYPE <> 'longblob'",
} {
if !strings.Contains(upSQL, want) {
t.Errorf("0068 up migration missing %q\nfull SQL:\n%s", want, upSQL)
}
}
if !strings.Contains(strings.ToUpper(upSQL), "PREPARE STMT FROM @SQL") {
t.Error("0068 up migration must keep its guarded PREPARE block — it is what makes a raw .up.sql replay onto an already-migrated store a no-op, and Dolt accepts no unprepared conditional ADD COLUMN. Unwrapping it also invalidates cliMigration0068AddAttributionStatus.")
}
// The bundle override is what keeps the PREPARE above off the pre-2.3
// CLI path. Assert it directly rather than trusting the two schema_test
// assertions to stay pointed at this migration.
for _, want := range []string{
"ALTER TABLE issue_versions ADD COLUMN attribution_status VARCHAR(20) NOT NULL;",
// Step 7's retype has to reach the bundle as direct DDL too, or a
// fresh CLI-built database keeps 0067's JSON column while the
// runtime has LONGBLOB.
"ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB;",
} {
if !strings.Contains(cliCompatibleMigrationSQL(migration0068Up, upSQL), want) {
t.Errorf("0068's CLI bundle substitute missing direct DDL %q", want)
}
}
if cliSubstituteAssumesWispTables(migration0068Up) {
t.Error("0068's CLI substitute touches only issue_versions, which has no wisps-side counterpart table — it must not be listed in cliSubstituteAssumesWispTables")
}
// down.sql files are not part of the embedded FS (only migrations/*.up.sql
// is //go:embed'd — see mainSource.files), so unlike the up side above,
// this reads straight from disk by package-relative path, matching
// TestMigration0067AddsVersionedBeadsSchema's precedent.
downBytes, err := os.ReadFile("migrations/" + migration0068Down)
if err != nil {
t.Fatalf("read %s: %v, want the migration file to exist", migration0068Down, err)
}
downSQL := string(downBytes)
for _, want := range []string{
"ALTER TABLE issue_versions DROP COLUMN attribution_status",
"COLUMN_NAME = 'attribution_status'",
// Step 7's reverse: back to the JSON type 0067 created, guarded on
// DATA_TYPE so an already-rolled-back store no-ops.
"ALTER TABLE issue_versions MODIFY COLUMN durable_state JSON",
"COLUMN_NAME = 'durable_state'",
"@issue_versions_ds_is_longblob",
} {
if !strings.Contains(downSQL, want) {
t.Errorf("0068 down migration missing %q\nfull SQL:\n%s", want, downSQL)
}
}
// Only migrations/*.up.sql is embedded into the CLI fresh bundle
// (mainSource.files), so the pre-2.3 prepared-DDL hazard never reaches a
// down migration and the guard is free — 0060's/0067's downs are the
// precedent.
if !strings.Contains(strings.ToUpper(downSQL), "PREPARE STMT FROM @SQL") {
t.Error("0068 down migration must guard its DROP COLUMN the way the up migration guards its ADD COLUMN, so a partially-applied or already-rolled-back workspace rolls back safely")
}
}
// TestMigration0068AddsAttributionStatusThroughDoltCLI applies the full
// migration bundle through a real `dolt` binary (skipped without one — see
// testutil.RequireDoltBinary) and checks the shape acceptance criteria a
// pure-Go SQL-text check cannot: actual column type/nullability as Dolt
// reports it, and that the NOT NULL constraint is real (an insert that omits
// attribution_status must fail, matching the fixture fix this migration
// forced onto TestMigration0067AddsVersionedBeadsSchemaThroughDoltCLI).
func TestMigration0068AddsAttributionStatusThroughDoltCLI(t *testing.T) {
testutil.RequireDoltBinary(t)
dir := t.TempDir()
runDoltCommand(t, dir, "init", "--name", "test", "--email", "test@example.com")
runDoltSQL(t, dir, AllMigrationsSQL())
requireDoltColumnShape(t, dir, "issue_versions", "attribution_status", "varchar(20)", "NO")
// Step 7: 0067 created durable_state as JSON; after 0068 it is the
// byte-preserving LONGBLOB the writer's JCS canonical form needs.
requireDoltDataType(t, dir, "issue_versions", "durable_state", "longblob", "YES")
requireDoltNoRows(t, dir, "SELECT issue_id FROM issue_versions", "issue_versions")
if err := runDoltSQLExpectingError(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:00')`); err == nil {
t.Error("insert into issue_versions omitting attribution_status succeeded, want a NOT NULL violation")
}
runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status) VALUES ('iv-1', 1, 1, '2026-09-01 00:00:00', 'claimed')`)
rows := queryDoltCSV(t, dir, `SELECT attribution_status FROM issue_versions WHERE issue_id = 'iv-1'`)
if len(rows) != 1 || rows[0]["attribution_status"] != "claimed" {
t.Fatalf("attribution_status round-trip failed post-migration: %v", rows)
}
// Step 7's actual property, measured rather than inferred from the
// type name: bytes written to durable_state come back byte for byte.
// These three number forms are the ones Dolt's JSON type renormalizes
// (on 2.2.3 the same INSERT into a JSON column reads back as
// {"a":1,"big":9007199254740992,"e":1e+300}), so a regression to JSON
// fails here even if the DATA_TYPE assertion above were loosened.
const verbatim = `{"a":1.0,"big":9007199254740993,"e":1e300}`
runDoltSQL(t, dir, `INSERT INTO issue_versions (issue_id, revision, epoch, change_at, attribution_status, durable_state) VALUES ('iv-2', 1, 1, '2026-09-01 00:00:00', 'claimed', '`+verbatim+`')`)
rows = queryDoltCSV(t, dir, `SELECT durable_state FROM issue_versions WHERE issue_id = 'iv-2'`)
if len(rows) != 1 || rows[0]["durable_state"] != verbatim {
t.Fatalf("durable_state round-trip changed the bytes post-migration: got %v, want %q", rows, verbatim)
}
}

View file

@ -0,0 +1,44 @@
-- Reverse of 0068 steps 6 and 7 only (attribution_status, and the
-- durable_state LONGBLOB retype), undone in reverse order. Steps 1-5 of
-- section 16.3 do not exist in this migration (see 0068's up file), so
-- there is nothing else to reverse here.
--
-- issue_versions is guaranteed empty in any real rollback scenario for the
-- same reason the up migration's NOT NULL-no-default is safe (Phase 2 is
-- this table's first writer, shipping in the same build as this column), so
-- dropping the column loses no data that could exist independent of this
-- migration.
--
-- Guarded on INFORMATION_SCHEMA the same way 0067's down is, so a
-- partially-applied or already-rolled-back workspace rolls back safely.
-- Only migrations/*.up.sql is embedded into the CLI fresh bundle, so the
-- PREPARE hazard (cli_prepared_ddl.go) never reaches this file.
--
-- Step 7 reverse: put durable_state back to the JSON type 0067 created it
-- with. Guarded on DATA_TYPE so a store that never took the retype, or was
-- already rolled back, no-ops. issue_versions is empty in any real rollback
-- scenario (see above), so there are no LONGBLOB bytes for the JSON type to
-- reject or renormalize on the way back.
SET @issue_versions_ds_is_longblob = (
SELECT IF(DATA_TYPE = 'longblob', 1, 0)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'issue_versions'
AND COLUMN_NAME = 'durable_state'
);
SET @sql = IF(@issue_versions_ds_is_longblob = 1,
'ALTER TABLE issue_versions MODIFY COLUMN durable_state JSON',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- Step 6 reverse: drop attribution_status.
SET @issue_versions_as_has = (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'issue_versions'
AND COLUMN_NAME = 'attribution_status'
);
SET @sql = IF(@issue_versions_as_has > 0,
'ALTER TABLE issue_versions DROP COLUMN attribution_status',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

View file

@ -0,0 +1,106 @@
-- Migration 0068: Phase 2 dual-write schema for versioned beads (be-hs42e.3
-- / gastownhall/beads#6135), step 6 of design section 16.3 (be-dt74u
-- amendment, be-hs42e.3's design field), plus step 7 -- the durable_state
-- LONGBLOB retype added at review, which has its own header further down.
--
-- Steps 1-5 of section 16.3 (version_id CHAR(36) UUID PK swap;
-- participation_generation BIGINT NULL on issues and its wisps shape-parity
-- mirror) are deliberately NOT in this file: be-v33pa's own scope is BASE
-- re-seating + attribution_status (section 16.4) only, per its exit
-- contract. A later bead may append the remaining steps to this same file --
-- scripts/check-migration-hygiene.sh Check C only protects a migration
-- already shipped on the base branch, and this one is still unmerged.
--
-- attribution_status (section 16.4, vocabulary aligned to BDP's
-- carried-attribution status, gastownhall/bdp#18, merged 2026-09-07): exactly
-- two legal values, 'claimed' (the mutation arrived with an actor) and
-- 'unknown' (the mutation path had none). 'imported' is provenance, not an
-- assertion, and is NOT a status -- it returns as a separate provenance
-- marker in the phase that first imports history, for which no writer
-- exists yet. A NOT NULL column with no default is safe here because
-- issue_versions (created by 0067, a prior migration in this same set) is
-- guaranteed empty at this point in any replay -- Phase 2 is this table's
-- first and only writer, and its dual-write code lands in the same build as
-- this column, so there is no pre-existing row for the NOT NULL constraint
-- to reject. See RecordVersionInTx / attributionStatusForActor in
-- internal/storage/issueops/version_history.go for what populates it.
--
-- Ordinals are local, not wire addresses: issues.current_revision and
-- issue_versions.revision are per-store ordinals (two disconnected clones can
-- both hold revision 8 for the same issue). The only durable address of a
-- version is version_id (steps 1-3 above, not yet landed). The HTTP API's
-- RowVersion/Revision is a compare-and-set token, never an address, and Phase
-- 3's read surface returns version_id, never the ordinal.
--
-- SINGLE WRITER ONLY until steps 1-3 land: with PRIMARY KEY (issue_id,
-- revision), two disconnected writers that each mint the same ordinal
-- collide on merge and TryAutoResolveMergeConflicts fails the pull for a
-- table it does not know, so enabling versioned history is safe only with a
-- single writer per store until the UUID version_id primary key lands and
-- the ordinal is demoted to an index. Those steps follow as their own PR.
-- "Single writer" means one writer at a time per store, not merely one
-- clone: MAX(revision)+1 is not a safe allocator for two concurrent
-- transactions in one store either (gastownhall/beads#6379, item 4).
--
-- Guarded the same way 0067's ADD COLUMNs are (see that file's header for
-- the full explanation of why: no MariaDB-only IF NOT EXISTS on Dolt 2.2.3's
-- ADD COLUMN, so an INFORMATION_SCHEMA probe + PREPARE is the only
-- replay-safe shape) -- makes a raw-SQL replay of this file a clean no-op on
-- an already-migrated store. Needs a CLI-bundle direct-DDL override
-- (cliMigration0068AddAttributionStatus in cli_migrations.go), the same
-- dolthub/dolt#11345 escape hatch 0067 uses, guarded by
-- TestBundleMigrationsWithPreparedALTERAreOverriddenOrJustified.
--
-- No wisps twin needed: issue_versions has no wisps-side counterpart table
-- at all (design section 16.3), so cliSubstituteAssumesWispTables does not
-- apply to this migration either.
SET @issue_versions_as_needs_add = (
SELECT IF(COUNT(*) = 0, 1, 0)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'issue_versions'
AND COLUMN_NAME = 'attribution_status'
);
SET @sql = IF(@issue_versions_as_needs_add = 1,
'ALTER TABLE issue_versions ADD COLUMN attribution_status VARCHAR(20) NOT NULL',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- 0068 step 7, added at review (donnabox on gastownhall/beads#6358 item
-- 4): retype issue_versions.durable_state from JSON to LONGBLOB.
--
-- 0067 created durable_state as a Dolt JSON column. Dolt's JSON type does
-- not keep the bytes it is handed -- it parses and renormalizes them, and
-- numbers do not survive the round trip (measured on dolt 2.2.3): 1.0 reads
-- back as 1, 9007199254740993 (past 2^53) reads back as 9007199254740992,
-- 1e300 reads back as 1e+300. A LONGBLOB returns the same bytes it was
-- given, byte for byte (same measurement). That breaks the design's
-- verbatim-bytes promise (R5.1) and makes any content-derived token
-- impossible, because sha256 over the bytes read back would not equal
-- sha256 over the bytes written. The column has to preserve bytes, so it
-- becomes a LONGBLOB. The writer (RecordVersionInTx in
-- internal/storage/issueops/version_history.go) stores the RFC 8785 (JCS)
-- canonical form of the marshalled issue and readers parse those bytes, so
-- the stored bytes are exactly the bytes a content token hashes.
--
-- No data conversion is needed: issue_versions is empty in the Phase 2 era
-- (this migration and the table's first writer ship in the same build --
-- see the attribution_status note above), so the MODIFY changes only the
-- column type. Guarded on DATA_TYPE the same way 0057 guards its LONGTEXT
-- widenings: the retype fires when the column exists and is not yet
-- LONGBLOB, and a raw-SQL replay onto an already-migrated store is a clean
-- no-op (a missing column makes the probe yield NULL, and the IF takes the
-- SELECT 1 branch, the same way 0067's table-exists guards no-op). The
-- CLI-bundle override (cliMigration0068AddAttributionStatus) carries the
-- direct MODIFY for the same pre-2.3 CLI reason as step 6.
SET @issue_versions_ds_needs_retype = (
SELECT IF(DATA_TYPE <> 'longblob', 1, 0)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'issue_versions'
AND COLUMN_NAME = 'durable_state'
);
SET @sql = IF(@issue_versions_ds_needs_retype = 1,
'ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB',
'SELECT 1');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

View file

@ -1962,6 +1962,11 @@ func TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities(t *testing.T)
// 0067: two-plane prepared ADD COLUMN, same shape as 0060.
"ALTER TABLE issues ADD COLUMN current_revision BIGINT NOT NULL DEFAULT 1;",
"ALTER TABLE wisps ADD COLUMN current_revision BIGINT NOT NULL DEFAULT 1;",
// 0068: single-plane prepared ADD COLUMN, same shape as 0066 (no
// wisps twin — issue_versions has none), plus step 7's prepared
// MODIFY COLUMN (durable_state JSON -> LONGBLOB), same shape as 0065.
"ALTER TABLE issue_versions ADD COLUMN attribution_status VARCHAR(20) NOT NULL;",
"ALTER TABLE issue_versions MODIFY COLUMN durable_state LONGBLOB;",
} {
if !strings.Contains(got, want) {
t.Fatalf("AllMigrationsSQL missing direct CLI DDL %q", want)
@ -1988,6 +1993,10 @@ func TestAllMigrationsSQLUsesDirectDDLForKnownCLIIncompatibilities(t *testing.T)
// also appear in the ignored twin, which is not bundled.
"@issues_cr_needs_add",
"@wisps_cr_needs_add",
// 0068 guards both of its ALTERs the same way; only its source text
// carries these probes.
"@issue_versions_as_needs_add",
"@issue_versions_ds_needs_retype",
} {
if strings.Contains(got, forbidden) {
t.Fatalf("AllMigrationsSQL contains source prepared-DDL guard %q", forbidden)

View file

@ -839,6 +839,30 @@ type EventsJournalConfigurer interface {
SetEventsJournalEnabled(enabled bool)
}
// VersionedHistoryConfigurer controls dual-write issue-version history
// activation on ONE storage instance. Implementations must never use
// process-global state, for the same reason as EventsJournalConfigurer:
// a process can hold several stores at once, and enabling history on one must
// not turn it on for any other. Callers type-assert; a store that does not
// implement it simply cannot record version history.
//
// SINGLE WRITER ONLY until the version_id primary-key swap lands.
// issue_versions is keyed PRIMARY KEY (issue_id, revision), and revision is
// a local ordinal (MAX(revision)+1 inside the writing transaction), so two
// disconnected writers that each mint the same ordinal for the same issue
// collide on merge — and TryAutoResolveMergeConflicts
// (versioncontrolops/mergesettle.go) fails the pull for a table it does not
// know. Enabling versioned history is therefore safe only with a SINGLE
// writer per store until migration 0068 steps 1-3 (UUID version_id primary
// key, ordinal demoted to an index) land; those steps follow as their own
// PR. "Single writer" means one writer at a time per store, not merely one
// clone: MAX(revision)+1 is not a safe allocator for two concurrent
// transactions in one store either (gastownhall/beads#6379, item 4). See
// issueops/version_history.go for why the ordinal is never an address.
type VersionedHistoryConfigurer interface {
SetVersionedHistoryEnabled(enabled bool)
}
// LifecycleManager provides lifecycle inspection beyond Close().
type LifecycleManager interface {
IsClosed() bool

View file

@ -0,0 +1,41 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestCrossRecordInvariantContract wires this leg into the R16.1
// cross-record invariant contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestCrossRecordInvariantContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.CrossRecordInvariantFixture{IssuePrefix: "xrec"}
t.Run("SurvivesTwoPassingPerRecordGuards", func(t *testing.T) {
conformance.RunCrossRecordInvariantSurvivesTwoPassingPerRecordGuards(t, ctx, fixture)
})
t.Run("StoreInvariantTransactionScopesExactlyTheSpanningRecords", func(t *testing.T) {
conformance.RunStoreInvariantTransactionScopesExactlyTheSpanningRecords(t, ctx, fixture)
})
t.Run("InvariantRefusalNamesTheViolatedInvariant", func(t *testing.T) {
conformance.RunInvariantRefusalNamesTheViolatedInvariant(t, ctx, fixture)
})
t.Run("MemoryKeyAliasUniquenessIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMemoryKeyAliasUniquenessIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("MaximumEndpointMultiplicityIsAStoreInvariantNotACAS", func(t *testing.T) {
conformance.RunMaximumEndpointMultiplicityIsAStoreInvariantNotACAS(t, ctx, fixture)
})
t.Run("AdvisoryLeaseAloneDoesNotPreventTheInvariantViolation", func(t *testing.T) {
conformance.RunAdvisoryLeaseAloneDoesNotPreventTheInvariantViolation(t, ctx, fixture)
})
t.Run("LeaseAcquisitionRecordsNoHistoryEntry", func(t *testing.T) {
conformance.RunLeaseAcquisitionRecordsNoHistoryEntry(t, ctx, fixture)
})
}

View file

@ -5,6 +5,7 @@ import (
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
)
// TestUOWDependencyEditorContract runs the shared DependencyEditor contract
@ -29,6 +30,8 @@ func TestUOWDependencyEditorContract(t *testing.T) {
{name: "RefusesCrossPlaneCycle", run: conformance.RunDependencyEditorRefusesCrossPlaneCycle},
{name: "AddedEchoesTheRequestOrder", run: conformance.RunDependencyEditorAddedEchoesTheRequestOrder},
{name: "SameTypeReAddIsIdempotent", run: conformance.RunDependencyEditorSameTypeReAddIsIdempotent},
{name: "SameTypeReAddWithChangedMetadataMintsOneVersion", run: conformance.RunDependencyEditorSameTypeReAddWithChangedMetadataMintsOneVersion},
{name: "SameTypeReAddWithIdenticalMetadataIsANoOp", run: conformance.RunDependencyEditorSameTypeReAddWithIdenticalMetadataIsANoOp},
{name: "RepeatsWithinOneRequestCollapse", run: conformance.RunDependencyEditorRepeatsWithinOneRequestCollapse},
{name: "AttributesItsEventsToTheActor", run: conformance.RunDependencyEditorAttributesItsEventsToTheActor},
{name: "RetypeRefusalLeavesTheOriginalEdge", run: conformance.RunDependencyEditorRetypeRefusalLeavesTheOriginalEdge},
@ -79,14 +82,24 @@ func newUOWDependencyEditorFixture(t *testing.T, ctx context.Context) conformanc
if err != nil {
t.Fatalf("NewDependencyEditor: %v", err)
}
configurer, ok := provider.(storage.EventsJournalConfigurer)
if !ok {
t.Fatalf("provider %T does not implement storage.EventsJournalConfigurer", provider)
}
versionConfigurer, ok := provider.(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("provider %T does not implement storage.VersionedHistoryConfigurer", provider)
}
kit := newUOWRoleFixtureKit(provider, "bd")
return conformance.DependencyEditorFixture{
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
IssuePrefix: kit.IssuePrefix,
Editor: editor,
CreateIssue: kit.CreateIssue,
CreateWisp: kit.CreateWisp,
AddDependency: kit.AddDependency,
QueryScalar: kit.QueryScalar,
CountHistory: kit.CountHistory,
SetJournalEnabled: configurer.SetEventsJournalEnabled,
SetVersionedHistoryEnabled: versionConfigurer.SetVersionedHistoryEnabled,
}
}

View file

@ -57,6 +57,9 @@ type doltSQLProvider struct {
// eventsJournalEnabled activates the durable events journal for THIS
// provider instance only. See SetEventsJournalEnabled.
eventsJournalEnabled atomic.Bool
// versionedHistoryEnabled activates dual-write issue-version history for
// THIS provider instance only. See SetVersionedHistoryEnabled.
versionedHistoryEnabled atomic.Bool
}
// SetEventsJournalEnabled activates the durable events journal for every unit
@ -73,6 +76,13 @@ func (p *doltSQLProvider) SetEventsJournalEnabled(enabled bool) {
p.eventsJournalEnabled.Store(enabled)
}
// SetVersionedHistoryEnabled activates dual-write issue-version history for
// every unit of work this provider begins from now on. Per instance, never
// process-global — see SetEventsJournalEnabled.
func (p *doltSQLProvider) SetVersionedHistoryEnabled(enabled bool) {
p.versionedHistoryEnabled.Store(enabled)
}
type bootstrapPreparationError struct {
err error
retryable bool
@ -147,9 +157,10 @@ func applyProviderOptions(opts []ProviderOption) providerOptions {
}
var (
_ UnitOfWorkProvider = (*doltSQLProvider)(nil)
_ TxProvider = (*doltSQLProvider)(nil)
_ storage.EventsJournalConfigurer = (*doltSQLProvider)(nil)
_ UnitOfWorkProvider = (*doltSQLProvider)(nil)
_ TxProvider = (*doltSQLProvider)(nil)
_ storage.EventsJournalConfigurer = (*doltSQLProvider)(nil)
_ storage.VersionedHistoryConfigurer = (*doltSQLProvider)(nil)
)
func (p *doltSQLProvider) NewUOW(ctx context.Context) (UnitOfWork, error) {
@ -177,14 +188,16 @@ func (p *doltSQLProvider) BeginTx(ctx context.Context) (Tx, error) {
return nil, fmt.Errorf("uow: failed to start transaction: %w", err)
}
// Bind journal activation to the connection this unit of work is pinned to,
// AFTER START TRANSACTION so the seq allocation's UPDATE and the SELECT that
// must observe it are inside one transaction on one session. The scope is
// released when the connection is (doltServerTx.releaseConn / poisonConn),
// so an entry cannot outlive its transaction.
// Bind journal and versioned-history activation to the connection this unit
// of work is pinned to, AFTER START TRANSACTION so the seq allocation's
// UPDATE and the SELECT that must observe it are inside one transaction on
// one session. Both scopes are released when the connection is
// (doltServerTx.releaseConn / poisonConn), so an entry cannot outlive its
// transaction.
return &doltServerTx{
conn: conn,
clearJournalScope: issueops.ScopeEventsJournalTransaction(conn, p.eventsJournalEnabled.Load()),
clearVersionScope: issueops.ScopeVersionedHistoryTransaction(conn, p.versionedHistoryEnabled.Load()),
}, nil
}

View file

@ -18,6 +18,10 @@ type doltServerTx struct {
// releaseConn and poisonConn — so the activation entry cannot outlive the
// transaction it describes, whichever way the transaction ends.
clearJournalScope func()
// clearVersionScope is clearJournalScope's counterpart for dual-write
// issue-version history: same binding at BeginTx, same release at
// releaseConn/poisonConn.
clearVersionScope func()
}
var _ Tx = (*doltServerTx)(nil)
@ -155,6 +159,7 @@ func (t *doltServerTx) rollbackConn(ctx context.Context) error {
func (t *doltServerTx) releaseConn() {
t.releaseJournalScope()
t.releaseVersionScope()
if t.conn != nil {
_ = t.conn.Close()
t.conn = nil
@ -171,6 +176,15 @@ func (t *doltServerTx) releaseJournalScope() {
}
}
// releaseVersionScope is releaseJournalScope's counterpart for dual-write
// issue-version history. Idempotent for the same reason.
func (t *doltServerTx) releaseVersionScope() {
if t.clearVersionScope != nil {
t.clearVersionScope()
t.clearVersionScope = nil
}
}
// poisonConn discards the pinned session instead of returning it to the pool.
// A session whose transaction may still be open must never be reused: because
// go-sql-driver's ResetSession only performs a liveness check (no
@ -179,6 +193,7 @@ func (t *doltServerTx) releaseJournalScope() {
// database/sql close the connection and drop it from the pool.
func (t *doltServerTx) poisonConn() {
t.releaseJournalScope()
t.releaseVersionScope()
if t.conn == nil {
return
}

View file

@ -0,0 +1,229 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/domain"
"github.com/steveyegge/beads/internal/types"
)
// TestDualWriteContract runs the dual-write history contract against the
// unit-of-work provider. All three legs share RecordVersionInTx's one body,
// so this is an engine check rather than a second vote — and here it checks
// the composition, the part that genuinely differs on this leg: dual-write
// history has to land inside the SAME unit of work as the mutation it
// accompanies, and this is the only leg where that mutation's own commit is
// assembled by composition rather than opened directly against a *sql.DB.
func TestDualWriteContract(t *testing.T) {
ctx := context.Background()
fixture := newUOWDualWriteFixture(t, ctx, "dwc", true)
t.Run("MintsOneVersionRowPerAcceptedMutation", func(t *testing.T) {
conformance.RunDualWriteMintsOneVersionRowPerAcceptedMutation(t, ctx, fixture)
})
t.Run("NoOpMutationMintsNoRow", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationMintsNoRow(t, ctx, fixture)
})
t.Run("AttributionIsRecordedWithTheMutation", func(t *testing.T) {
conformance.RunDualWriteAttributionIsRecordedWithTheMutation(t, ctx, fixture)
})
t.Run("CurrentRevisionMatchesTheNewVersionRow", func(t *testing.T) {
conformance.RunDualWriteCurrentRevisionMatchesTheNewVersionRow(t, ctx, fixture)
})
t.Run("NoOpMutationLeavesThePriorVersionRowUnperturbed", func(t *testing.T) {
conformance.RunDualWriteNoOpMutationLeavesThePriorVersionRowUnperturbed(t, ctx, fixture)
})
}
// TestDualWriteContractFlagOff runs FR-7 against a provider constructed with
// the flag OFF from the start — its own provider, not a shared one, so "flag
// off" means what FR-7 promises rather than "not yet turned on this session".
func TestDualWriteContractFlagOff(t *testing.T) {
ctx := context.Background()
fixture := newUOWDualWriteFixture(t, ctx, "dwcoff", false)
t.Run("FlagOffProducesNoVersionRows", func(t *testing.T) {
conformance.RunDualWriteFlagOffProducesNoVersionRows(t, ctx, fixture)
})
}
// TestDualWriteFixtureKitIsWired is this leg's half of the explicit
// per-leg guardrail design §8.5 calls for in place of AST auto-discovery —
// see the dolt leg's TestDualWriteFixtureKitIsWired for why the guardrail is
// needed even though TestEveryLegWiresEveryRoleContract's scan already
// enumerates and confirms wiring for all six RunDualWriteXxx entrypoints.
func TestDualWriteFixtureKitIsWired(t *testing.T) {
ctx := context.Background()
fixture := newUOWDualWriteFixture(t, ctx, "dwk", true)
if fixture.Mutate == nil {
t.Error("DualWriteFixture.Mutate is nil")
}
if fixture.MutateAsNoOp == nil {
t.Error("DualWriteFixture.MutateAsNoOp is nil")
}
if fixture.CurrentRevision == nil {
t.Error("DualWriteFixture.CurrentRevision is nil")
}
if fixture.VersionRowCount == nil {
t.Error("DualWriteFixture.VersionRowCount is nil")
}
if fixture.LatestVersionAttribution == nil {
t.Error("DualWriteFixture.LatestVersionAttribution is nil")
}
}
// TestUOWCreateWithLabelAndEdgeMintsPerRepositoryWrite_KnownDivergence makes
// the uow leg's 1+N+M divergence machine-visible (reviewer MINOR-3 on
// gastownhall/beads#6358). TestDualWriteContract's Mutate creates an issue
// with no labels and no dependencies, so its "exactly one version row per
// accepted mutation" case cannot see what a fuller create does on this leg:
// domain.IssueUseCase.CreateIssue inserts the row and then persists each
// label and each edge through its own repository (domain/db label.go and
// dependency.go), and every one of those repository writes reaches
// issueops.RecordVersionInTx on its own — 1 + N + M rows for ONE
// caller-visible create. The direct legs (dolt, embeddeddolt) mint exactly
// one row for the same shape: issueops.CreateIssuesInTxWithContext runs its
// constituents without minting and mints once per issue after the
// creation-time edges land.
//
// This test pins the CURRENT, measured behavior — three rows for one label
// and one edge — so the divergence is a red test away from being fixed
// rather than a comment. KNOWN DIVERGENCE gastownhall/beads#6379:
// it is EXPECTED TO FLIP when that follow-up lands and the uow create mints
// once; update the want to 1 then and fold the shape into the contract.
func TestUOWCreateWithLabelAndEdgeMintsPerRepositoryWrite_KnownDivergence(t *testing.T) {
ctx := context.Background()
const prefix = "dwle"
provider := newUOWVersionedHistoryProvider(t, ctx, prefix, true)
kit := newUOWRoleFixtureKit(provider, prefix)
// The edge needs a target that exists; seeded through the kit, with no
// labels and no edges, it doubles as the control for the bare shape.
target := prefix + "-target"
if err := kit.CreateIssue(ctx, &types.Issue{
ID: target, Title: "t-" + target, IssueType: types.TypeTask, Status: types.StatusOpen,
}, "actor"); err != nil {
t.Fatalf("seeding %s: %v", target, err)
}
id := prefix + "-label-and-edge"
if err := RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) {
_, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{
Issue: &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
},
ExplicitID: id,
Labels: []string{"one"},
Dependencies: []domain.DependencySpec{{Type: types.DepBlocks, TargetID: target}},
CreateOnly: true,
}, "actor")
return "create " + id, err
}); err != nil {
t.Fatalf("creating %s with one label and one edge: %v", id, err)
}
count := func(what, query string, args ...any) int {
t.Helper()
var n int
if err := kit.QueryScalar(ctx, query, args, &n); err != nil {
t.Fatalf("counting %s: %v", what, err)
}
return n
}
// The rows counted below belong to a create that really carried both
// writes, not to one that dropped a label or an edge on the way in.
if labels := count("labels", "SELECT COUNT(*) FROM labels WHERE issue_id = ?", id); labels != 1 {
t.Fatalf("labels on %s = %d, want 1", id, labels)
}
if edges := count("edges", "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND "+
"COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?", id, target); edges != 1 {
t.Fatalf("edges %s -> %s = %d, want 1", id, target, edges)
}
// 1 issue row + 1 label + 1 edge, each minted by its own repository write.
// The direct legs mint exactly 1 for this shape.
const mintedToday = 3
got := count("version rows for "+id, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", id)
if got != mintedToday {
t.Errorf("version rows for %s after one create with 1 label + 1 edge = %d, want the %d this leg mints today "+
"(1 issue + 1 label + 1 edge); 1 would mean gastownhall/beads#6379 landed — flip this test into the contract",
id, got, mintedToday)
}
// The bare shape on the same leg mints one row, so the two extra rows
// above are the label and the edge, not something else about this leg.
if bare := count("version rows for "+target, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", target); bare != 1 {
t.Errorf("version rows for %s (no labels, no edges) = %d, want 1", target, bare)
}
t.Logf("KNOWN DIVERGENCE gastownhall/beads#6379: uow create with 1 label + 1 edge minted %d version rows "+
"(1 issue + 1 label + 1 edge, one per repository write); the direct legs mint exactly 1 for the same shape. "+
"This test is expected to FLIP when the follow-up lands.", got)
}
// newUOWVersionedHistoryProvider boots one provider for a versioned-history
// suite and sets the flag as asked — through the capability accessor's
// operator half, the same way newUOWJournalFixture reaches
// storage.EventsJournalConfigurer: a provider that stopped offering the role
// is the regression this assertion exists to catch.
func newUOWVersionedHistoryProvider(t *testing.T, ctx context.Context, prefix string, enabled bool) UnitOfWorkProvider {
t.Helper()
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
configurer, ok := provider.(storage.VersionedHistoryConfigurer)
if !ok {
t.Fatalf("provider %T does not implement storage.VersionedHistoryConfigurer", provider)
}
configurer.SetVersionedHistoryEnabled(enabled)
return provider
}
func newUOWDualWriteFixture(t *testing.T, ctx context.Context, prefix string, enabled bool) conformance.DualWriteFixture {
t.Helper()
provider := newUOWVersionedHistoryProvider(t, ctx, prefix, enabled)
kit := newUOWRoleFixtureKit(provider, prefix)
return conformance.DualWriteFixture{
IssuePrefix: prefix,
Mutate: func(ctx context.Context, id string) error {
return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) {
_, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{
Issue: &types.Issue{
ID: id, Title: "t-" + id, IssueType: types.TypeTask, Status: types.StatusOpen,
},
ExplicitID: id,
CreateOnly: true,
}, "actor")
return "create " + id, err
})
},
MutateAsNoOp: func(ctx context.Context, id string) error {
// Re-sets title to the exact value Mutate already gave it, so
// issueops.DiscardNoopIssueUpdates discards it before it ever
// reaches RecordVersionInTx.
return RunTx(ctx, provider, func(ctx context.Context, uw UnitOfWork) (string, error) {
return "update " + id, uw.IssueUseCase().UpdateIssue(ctx, id,
map[string]any{"title": "t-" + id}, "actor")
})
},
CurrentRevision: func(ctx context.Context, id string) (int64, error) {
var revision int64
err := kit.QueryScalar(ctx, "SELECT current_revision FROM issues WHERE id = ?", []any{id}, &revision)
return revision, err
},
VersionRowCount: func(ctx context.Context, id string) (int, error) {
var count int
err := kit.QueryScalar(ctx, "SELECT COUNT(*) FROM issue_versions WHERE issue_id = ?", []any{id}, &count)
return count, err
},
LatestVersionAttribution: func(ctx context.Context, id string) (actor, agent, message string, err error) {
err = kit.QueryScalar(ctx, `
SELECT COALESCE(change_actor, ''), COALESCE(change_agent, ''), COALESCE(change_message, '')
FROM issue_versions
WHERE issue_id = ?
ORDER BY revision DESC
LIMIT 1`, []any{id}, &actor, &agent, &message)
return actor, agent, message, err
},
}
}

View file

@ -0,0 +1,50 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestExpectedRevisionContract wires this leg into the R16/R17
// expected-revision contract. Phase 0 leaves every hook nil in every
// backend's fixture kit (architecture §12), so each case below skips by
// name; this file exists so TestEveryLegWiresEveryRoleContract counts this
// leg, and so the cases start running for real the moment this leg's fixture
// kit grows a non-nil hook.
func TestExpectedRevisionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.ExpectedRevisionFixture{IssuePrefix: "erev"}
t.Run("AcceptsAWriteNamingTheCurrentVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingTheCurrentVersion(t, ctx, fixture)
})
t.Run("AcceptsAWriteNamingNoVersion", func(t *testing.T) {
conformance.RunExpectedRevisionAcceptsAWriteNamingNoVersion(t, ctx, fixture)
})
t.Run("CoversFieldsOutsideAnyWatchedSubset", func(t *testing.T) {
conformance.RunExpectedRevisionCoversFieldsOutsideAnyWatchedSubset(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionAddress", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionAddress(t, ctx, fixture)
})
t.Run("RefusalReportsTheRefusingVersionsChangeAttribution", func(t *testing.T) {
conformance.RunRefusalReportsTheRefusingVersionsChangeAttribution(t, ctx, fixture)
})
t.Run("RefusalIsATypedOutcomeNotAGenericError", func(t *testing.T) {
conformance.RunRefusalIsATypedOutcomeNotAGenericError(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromAnAcceptedWrite", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromAnAcceptedWrite(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromNotFound", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromNotFound(t, ctx, fixture)
})
t.Run("RefusalIsDistinguishableFromValidationFailure", func(t *testing.T) {
conformance.RunRefusalIsDistinguishableFromValidationFailure(t, ctx, fixture)
})
t.Run("RefusalNeverSilentlyPicksAWinner", func(t *testing.T) {
conformance.RunRefusalNeverSilentlyPicksAWinner(t, ctx, fixture)
})
}

View file

@ -352,6 +352,16 @@ func (p *notifyingProvider) SetEventsJournalEnabled(enabled bool) {
}
}
// SetVersionedHistoryEnabled forwards dual-write issue-version history
// activation to the provider that actually binds it to a transaction
// (doltSQLProvider.BeginTx), for the same reason and in the same shape as
// SetEventsJournalEnabled above.
func (p *notifyingProvider) SetVersionedHistoryEnabled(enabled bool) {
if configurer, ok := p.inner.(storage.VersionedHistoryConfigurer); ok {
configurer.SetVersionedHistoryEnabled(enabled)
}
}
// eventsMaintenanceRunner is issueops.EventsMaintenanceRunner under this file's
// import alias, named once so the forwarder below reads as an ordinary
// capability check.

View file

@ -294,11 +294,13 @@ func TestNotifyingProviderBuildsRolesOnItself(t *testing.T) {
"RunNonTx": true,
"SetPoolLimits": true,
"Unwrap": true,
// Events-journal capability plumbing: activation binds on the inner
// provider's transactions, and a retention pass writes no bead. Neither
// builds a role, so neither can build one "on itself".
"SetEventsJournalEnabled": true,
"RunEventsMaintenanceTx": true,
// Events-journal and versioned-history capability plumbing: activation
// for both binds on the inner provider's transactions, and a retention
// pass writes no bead. None of these build a role, so none of them can
// build one "on itself".
"SetEventsJournalEnabled": true,
"RunEventsMaintenanceTx": true,
"SetVersionedHistoryEnabled": true,
}
var checked int

View file

@ -0,0 +1,72 @@
package uow
import (
"context"
"testing"
"github.com/steveyegge/beads/backend/conformance"
)
// TestRetentionContract wires this leg into the R20 retention contract.
// Phase 0 leaves every hook nil in every backend's fixture kit (architecture
// §12), so each case below skips by name; this file exists so
// TestEveryLegWiresEveryRoleContract counts this leg, and so the cases start
// running for real the moment this leg's fixture kit grows a non-nil hook.
func TestRetentionContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.RetentionFixture{IssuePrefix: "rete"}
t.Run("RemovalLeavesTheAddressAbleToAnswer", func(t *testing.T) {
conformance.RunRemovalLeavesTheAddressAbleToAnswer(t, ctx, fixture)
})
t.Run("RemovalReasonIsRetentionErasureOrReorganizationDistinctly", func(t *testing.T) {
conformance.RunRemovalReasonIsRetentionErasureOrReorganizationDistinctly(t, ctx, fixture)
})
t.Run("RemovalReportsTheSurvivingRetainedWindow", func(t *testing.T) {
conformance.RunRemovalReportsTheSurvivingRetainedWindow(t, ctx, fixture)
})
t.Run("RemovalNeverReassignsASurvivingAddress", func(t *testing.T) {
conformance.RunRemovalNeverReassignsASurvivingAddress(t, ctx, fixture)
})
t.Run("GoneIsDistinguishableFromUnknown", func(t *testing.T) {
conformance.RunGoneIsDistinguishableFromUnknown(t, ctx, fixture)
})
t.Run("AnAddressNeverResolvesToADifferentState", func(t *testing.T) {
conformance.RunAnAddressNeverResolvesToADifferentState(t, ctx, fixture)
})
t.Run("ADestructiveOperationEnumeratesAffectedAddressesFirst", func(t *testing.T) {
conformance.RunADestructiveOperationEnumeratesAffectedAddressesFirst(t, ctx, fixture)
})
t.Run("AHoldPreventsRemovalAndReportsInRetainedBounds", func(t *testing.T) {
conformance.RunAHoldPreventsRemovalAndReportsInRetainedBounds(t, ctx, fixture)
})
t.Run("ForcingAHeldRemovalRecordsWhoWhenWhy", func(t *testing.T) {
conformance.RunForcingAHeldRemovalRecordsWhoWhenWhy(t, ctx, fixture)
})
t.Run("EveryRetentionAnswerNamesItsProducingStore", func(t *testing.T) {
conformance.RunEveryRetentionAnswerNamesItsProducingStore(t, ctx, fixture)
})
t.Run("AStoreWithNoLineageKnowledgeAnswersUnknownNotGone", func(t *testing.T) {
conformance.RunAStoreWithNoLineageKnowledgeAnswersUnknownNotGone(t, ctx, fixture)
})
t.Run("AStoreThatRemovesStateStillAnswersGoneDurably", func(t *testing.T) {
conformance.RunAStoreThatRemovesStateStillAnswersGoneDurably(t, ctx, fixture)
})
t.Run("ErasureMintsACorrectedVersionRatherThanEditingInPlace", func(t *testing.T) {
conformance.RunErasureMintsACorrectedVersionRatherThanEditingInPlace(t, ctx, fixture)
})
}
// TestEpochContract wires this leg into the R20 epoch contract. Same Phase 0
// all-nil state as TestRetentionContract above.
func TestEpochContract(t *testing.T) {
ctx := context.Background()
fixture := conformance.EpochFixture{IssuePrefix: "epch"}
t.Run("AnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange", func(t *testing.T) {
conformance.RunAnEpochBumpIsTriggeredOnlyByRestoreReinitOrSchemeChange(t, ctx, fixture)
})
t.Run("EpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed", func(t *testing.T) {
conformance.RunEpochBumpVoidsOnlyAddressesOfVersionsNoLongerServed(t, ctx, fixture)
})
}