Transactions: Block-MVCC + Graph-SSI + Semantic Merge
2,642 words6 subsections1 listingA design document: it describes the 1.0 target, not what runs today.
On this page6
7.1 Isolation model
- Default: SERIALIZABLE via SSI over canonical logical read/write dependencies, conservatively represented by the witness types in §7.3. SSI establishes an acyclic serialization-graph order; it does not assert that commit-marker order is the serialization order. Strict serializability additionally requires that a transaction snapshot include every commit whose acknowledgement completed before the transaction began and that publication/acknowledgement obey the real-time commit state machine in §5.2. In the Local posture those premises hold by construction: a single sequencer orders every semantic command; snapshot acquisition reads and revalidates the current published slot (§5.3), so every commit acknowledged before acquisition is included; and acknowledgement follows gap-free visible publication (§5.2). They are necessary, not sufficient: exact acyclicity admits serializable-but-not-strict histories through long-lived read-write pivots, so the Local certifier additionally enforces the registered strictness law — real-time precedence edges (every transaction whose visible publication precedes the candidate's snapshot acquisition precedes it in the checked serialization graph) or, equivalently by the registered earliest-committer argument that any cycle in the union of the dependency graph and the real-time order must route through a long-lived concurrent pivot carrying an rw-in and an rw-out edge whose rw-out target commits first, a registered Cahill-style dangerous-structure rule. With the law, the Local default contract is STRICT SERIALIZABLE, registered under §1.11 as a
proof-class theorem whose premises are exactly the three construction facts plus the strictness law; without the law, strictness is not claimable.READ_ONLY_HISTORICAL,SNAPSHOT,SNAPSHOT_FOLLOWER(max_lag),BRANCH_CAUSAL, and explicit historical selectors (AS OF) remain the named carve-outs. The added conservatism raises abort rates for long-lived writers — most under Required-audit visible-prefix lag, where writers validate against applied state while readers see the visible prefix and backward rw edges become more common — and that cost is a registeredbenchmarkdistribution, never assumed free. W12 remains plain SERIALIZABLE unless the Meta certifier adopts the same real-time-edge rule; the oracle strengthening is registered in Appendix F's FG-INV-05 row. - Ordinary serializable read-only transactions may receive a serialization failure.
READ_ONLY DEFERRABLEmay wait for a safe snapshot and, once acquired, is immune to SSI abort.READ_ONLY_HISTORICAL,SNAPSHOT,SNAPSHOT_FOLLOWER(max_lag), andBRANCH_CAUSALremain named typed contracts; the server rejects rather than silently weakens a requested minimum. - SSI transaction records, rw-edge summaries, and SIREAD witnesses survive commit until every transaction that overlapped their lifetime has ended. Reclamation is tied to an explicit overlap horizon, not the reader's commit. Coarsening under memory pressure is an atomic monotone replacement: the coarse superset becomes visible before fine entries are removed. Pressure may increase false aborts but never erase a possible dependency; admission returns
ResourceExhaustedrather than dropping correctness metadata. - SIREAD witnesses never block. Mutations remain proposal-private until finalization computes the complete block/constraint/quota lock set. The coordinator acquires that set in canonical
(lock_class, graph, partition, object)order; an implementation may instead use a proved no-wait abort protocol. It never waits while holding an unordered subset, and discovery of a missing lower-order lock releases without publication and restarts validation. Lock exclusivity is FG-INV-02; wait-for acyclicity and cancellation cleanup have separate model/oracle coverage. - Writers conflict on final logical effects after the merge ladder, constraints, FCW, and SSI are reevaluated. The monotone state machine is
Active -> Validating -> FinalPrepared -> PayloadDurable -> OrderSubmitted -> CommandCommitted -> Applied(MarkerRef) -> Acknowledged, withAbortedlegal only before the irreversible ordering boundary and externally reportedUnknownrepresenting an unresolved observer outcome, not an internal rollback state. Single-node mode collapses consensus substates but not their ordering; cancellation and retries follow §5.2. - Core local invariants include idempotent transaction-token outcomes, fenced unique block/constraint-lock ownership, and finite correctly ordered version chains, but those alone do not prove SI or SSI. Publication, branch visibility, deletes, own writes, witness soundness, and metadata lifetime are separate registry obligations (§15.5, Appendix F).
7.2 Granularity choices (and why)
Blocks (~256 edges) are the graph analogue of frankensqlite's pages: fine enough that writers to different neighborhoods never touch (fan-out of real workloads means most concurrent writes hit distinct vertices, let alone blocks), coarse enough that lock/siread tables stay small and cache-resident. Vertex-level would false-conflict on hubs; edge-level would drown in metadata. Hub blocks that do contend escalate to delta-chains (§6.2.3), which converts conflict into commutative appends — contention is handled by changing the data structure, not by tuning locks.
7.3 Phantom protection for pattern queries
SSI needs to protect both observed elements and observed absence. Every physical access path declares an abstract logical-read domain plus a conservative witness encoding:
BlockRange { descriptor, stable_low_key, stable_high_key, generation,
visible_version, routing_translation_epoch }
AdjacencyRange { descriptor, low_key, high_key, gaps, descriptor_epoch }
LabelPartition { label_expr, partition, predicate, gaps, scan_epoch }
IndexRange { index_generation, low_key, high_key, gaps, early_stop_boundary }
NegativePattern { canonical_predicate, quantified_domain }
PathCut { path_semantics, automaton_state, mode_state_class,
settled_domain, unexpanded_edge_domain, cost_boundary,
feasible_time_domain, topology_epoch }
Each witness implementation supplies three executable contracts: concretization(w), the set of logical positive and negative observations represented; may_affect(final_write, w); and refine(coarse, trace). A BlockRange is logical-keyed: split, seal, and compaction publish a mutation-routing translation from old generation/range to its covering descendants, retained until the SSI overlap horizon passes; an implementation unable to retain that translation emits AdjacencyRange directly. A bare physical block address is never a witness. FG-INV-06 requires both concretization(refined) ⊆ concretization(coarse) and preservation of every logically relevant positive read, gap, absence observation, early-stop boundary, and path cut. Refining a predicate to only elements returned or encountered is forbidden unless the binder proved it was a point predicate.
WitnessTrace is execution evidence, not automatically the predicate domain. ORDER BY/LIMIT, anti/semi joins, optional matches, negative patterns, uniqueness probes, and early-terminated scans register the gaps or remaining domains whose absence affected the result. Path witnesses use the same mode-aware product state and proved dominance relations as §8.2; (NFA state, partition, cost) alone is not accepted for TRAIL, SIMPLE/ACYCLIC, temporal, capture-sensitive, or negative-cost semantics.
An apparent overlap may be refined under a bounded resource reservation. If exact overlap survives, or the budget expires, validation conservatively aborts and reports whether refinement was truncated. That conservative abort is the disposition of the validating candidate whose witness overlap could not be refined away, not an edge-level law: dependency edges among committed transactions are legal and retained — they are the SSI serialization graph — the accept/reject law for a candidate is §7.1's certification law (the cycle/dangerous-structure/real-time-edge test), and refinement only shrinks the conservative edge set that enters that test. Canonical predicate normalization improves witness reuse but is not itself a proof of semantic equivalence; every rewrite used for witness identity carries a law certificate. The refine-vs-abort policy is a performance decision card and cannot change the conservative-abort fallback.
The default SERIALIZABLE claim is gated on: formal soundness of every witness constructor and refinement; preservation through every optimizer rewrite; exhaustive small-graph differential histories against an independent reference dependency checker; and model-based tests inserting precisely the missing edges/vertices/index keys that could invalidate negative and path results. Until a witness family passes those gates, queries using it are rejected in SERIALIZABLE mode rather than silently downgraded.
7.4 The semantic merge ladder (and why graphs love it)
On base-drift at commit (block changed since snapshot), before aborting:
- Semantic re-evaluation: evaluate the original intents against the current branch heads under a capability-stripped
Cx. Eligibility depends on operation semantics, active constraints, captured reads, property merge algebra, and branch policy. An edge addition is not coordination-free when uniqueness or cardinality makes it non-monotone. Re-evaluation is incremental by law: rung 1 re-evaluates exactly the transitive closure of the intents whose captured observations drifted together with every intent that depends, through procedure-output observations, workspace-generation reads, or escaped-allocation bindings, on a re-evaluated intent, evaluated in intent-ordinal order to a fixpoint against the rebased upstream state; a reused per-intent result carries an unchanged-observation certificate naming the exactCapturedIntentObservationset it was validated against, and intents whose registeredConsistencyClassproves CALM-monotone eligibility in the composed context skip re-evaluation entirely. - Structured physical reuse: a disjoint physical patch may be retained only as an optional accelerator after the semantic result is fixed and only when its apply-basis digest still matches.
- Final-effect regeneration: produce a new
CommittedEffectSet, permanent IDs/keys, constraint reads, canonical logical deltas, write summary, and witnesses. Rerun FCW, SSI, and all affected constraints. Then build and persist a new capsule as required by §5.2; no successful rung may publish the pre-rebase capsule or its stale availability receipts. - Abort/retry with a capability-redacted machine-readable conflict report when no safe resolution exists.
frankensqlite built this ladder to rescue B-tree page conflicts. Selected graph intents have promising algebraic merge opportunities, but actual eligibility is constraint- and read-context-dependent; hit rate and skew benefit are benchmark questions, not architectural facts. The same evaluator serves transaction rebase, branch merge (§5.6), and multi-writer preparation (§14.4) through distinct typed policies. Rung-1 replay determinism is enforced by construction: the rebase evaluator runs under a capability-stripped Cx—no clock, entropy, network, or filesystem—and accepts every needed snapshot/constraint input explicitly, so ambient nondeterminism is inexpressible and missing inputs fail closed. The incremental-rebase law of rung 1 is registered as a subordinate clause of FG-INV-17, whose "every semantic drift regenerates effects" language is glossed as extensional equality: the composed result of reused and re-evaluated intents must equal full re-evaluation extensionally, enforced by that row's existing final-effect/workspace/allocation/result digest oracle, with a differential oracle running both paths on sampled conflicts. Observation granularity is a decision-card question — coarse constraint or adjacency observations drift often and defeat reuse — and rung 3's revalidation is not a substitute for the law: it reruns FCW, SSI, and constraints over final effects but never re-derives effects from intents. The one law binds all three evaluator consumers — transaction rebase, §5.6 branch merge, and §14.4 multi-writer preparation.
Three formal strengthenings of the ladder:
- Rung eligibility is proved for a complete context.
ConsistencyClassis derived from the intent algebra only after composing schema constraints and read dependencies. CALM-style monotonicity is sufficient only within the declared lattice and authority domain; a context-free table is a cache of proved classifications, never the source of truth. - Multi-branch semantics are explicit. Only registered associative, commutative, idempotent joins are order-independent. Other resolvable intents use the pinned total order
(source_head_seq, source_branch_id, source_intent_ordinal, element_id)recorded in the merge policy; unresolved cases return conflicts. Merge records carry the target visibility parent plus source heads as non-parent provenance, all bases/imported ranges, policy, and final digest (§5.6), so retries are idempotent and order is auditable without inventing multiple target ancestries. No general cocycle claim is made without a formal merge algebra and higher-order coherence proof. - An invariant-preserving rung between commutative-replay and abort. Escrow merge modes preserve numeric invariants (x ≥ 0, quota ceilings, degree caps) without per-operation cross-branch/replica coordination by pre-distributing rights per branch/replica with an idempotent transfer ledger, under exactly §4.7's purpose claim — abort/rebase-rate reduction and merge-order independence within the single commit order, coordination amortized into rights transfers rather than eliminated, depletion escalating that intent to the ordered path. The model-checked transfer protocol lives in the sim lab's standing scenarios. This is the missing middle for exactly the counter-shaped properties (inventories, budgets, rate limits) that LWW mangles and aborts throttle.
7.5 Bulk & DDL paths
DDL and logical bulk effects never bypass ordinary transactions. Catalog graph/branch aliases and branchable label/type/property/constraint/index definitions are SchemaOp entries in GraphIntentBatch and CommittedEffectSet; there is no CatalogMutationSpec, SchemaMutationSpec, IndexDefinitionSpec, or IndexActivationSpec control-command shortcut. Physical staging/build progress is control state, but it cannot change query-visible schema or graph contents.
BulkLoadRequestKey binds posture, tenant/principal, authority ceiling, destination coordinate, mode, scoped idempotency key, source-format contract, canonical import options, schema/constraint contract, and security binding. BulkSourceChunkManifest is bounded {load_id,chunk_ordinal,source_byte_range,source_digest,parser_profile_oid,canonical_logical_batch_ref:StrongRef<CanonicalBulkLogicalBatch>,row_count,logical_effect_digest,optional_staged_run_refs[],resource_charge_ref,body_digest}; ordinals and source ranges are gap-free and each row has its original source-row digest. CanonicalBulkLoadManifest owns a nonempty ordered chunk set plus total source/row/effect commitments and the deterministic Merkle root; physical runs are optional accelerators and can never define an effect. BulkLoadRegistry<Role> maps the request key/load ID to exactly one state-shaped record: Reserved{capability/request replay,source pin,resource reservation} -> Ingesting{next_chunk_ordinal,chunk_root} -> Sealed{manifest_ref} -> CommitPrepared{ordinary registration/workspace/prepare owner,manifest_ref} -> Committed{marker_identity,final_effect_digest} or Aborted{reason,staging_disposition}. BulkLoadTransitionSpec<Role> has exactly Reserve, AppendChunk, Seal, PrepareCommit, and Abort; its u8 arm tags follow that source order and each is an explicitly registered Local/Meta staging control. Committed is reached only by the transaction-carried BulkLoad intent of the finalizing ordinary transaction, never by a staging-control arm; matching chunk retry returns its original record and any ordinal/digest/body drift fails. No record points to a future state or command, and no client timeout releases staging.
Online load pins one registered snapshot, ingests bounded chunks, builds optional sealed runs, and continuously catches up the exact self-contained delta stream from the pin through a declared watermark. Finalization publishes the manifest as one or more bounded BulkLoad intents inside an ordinary transaction, reauthorizes the union of effects, revalidates SSI/constraints/valid-time/escrow/resources/branch-head CAS against the current head, and commits one exact net effect/delta sequence. Staged runs are selected only when their effect-equivalence proof and apply basis match; otherwise ordinary Strata construction regenerates them. Offline fenced load is legal only with OfflineBulkEpochFence {coordinate,expected_empty_graph_and_branch_root,expected_schema_root,exclusive_graph_epoch,zero_active_snapshot_txn_subscription_or_derived_consumer_proof,writer_fence_and_configuration,resource_and_audit_owner} durably installed before parsing. It still finalizes through an ordinary transaction/marker and all constraints; the fence merely permits direct construction of initial sealed runs. Any nonempty/current-head drift rejects publication. OfflineBulkEpochFenceInstallSpec durably installs the fence and OfflineBulkEpochFenceReleaseSpec is the sole ordered release path on abort; the ordered completion consumes the installed fence, and ordered abort proves no commit and releases it through that spec. Recovery resumes the exact request or drives explicit abort, never infers success from run bytes.
In W12, Meta owns the request/manifest/ordinary transaction and exact participant set; shards may stage only certified routed chunk projections and return idempotent closure/effect certificates. Global finalization proves a bijection among manifest chunks, routed rows, shard prepares, union effects, constraints, and optional run-equivalence evidence before the single Meta decision. Backup/restore, checkpoints, GC, key scans, role transition, and resource floors retain every nonterminal source pin/chunk/run/participant owner. Crash matrices cover reserve, every chunk boundary, seal, tail catch-up, prepare, audit visibility, decision, abort, duplicate/conflicting chunks, empty-fence races, ENOSPC, and physical-run rejection.
Index build has a separate, exact shadow lifecycle. A committed SchemaOp::DeclareIndex creates a versioned IndexDefinition in DeclaredBuilding; it does not make any generation usable. DerivedBuildRegistry<Role> maps (definition_oid,generation_id) through Reserved -> SnapshotBuilding{pin,watermark} -> CatchingUp{contiguous_delta_frontier} -> Validating{candidate_component_root} -> ReadyForSchemaActivation{validation_certificate_ref} -> Active, or from any preactivation state to Aborted{typed_reason,disposition}. DerivedBuildTransitionSpec<Role> has exactly Reserve, PublishSnapshotProgress, PublishCatchupProgress, BeginValidation, PublishReady, and Abort; every progress update is monotone/idempotent, owns its bounded closure, and advertises its exact watermark. DerivedGenerationValidationCertificate binds definition/identity/security/authority, pinned snapshot, complete delta interval, exact component root/content commitment, scalar/collation/approximation profiles, constraint and deletion semantics, validation oracle results, resource bounds, and signer/configuration evidence. It names no future activation.
Only a later ordinary SchemaOp::ActivateDerivedGeneration transaction, strongly naming an already-built Ready certificate and rechecking the current definition/head/security state, atomically changes the definition/generation registry to Active. Rebuild creates a distinct generation; old Active remains usable until that transaction switches it and retention floors protect old snapshots. Exact indexes prove answer equivalence or fall back; approximate generations carry their own semantic generation and ApproximationProfile, so a changed ANN topology cannot masquerade as the same definition. Contract enablement and typed-column/schema migrations use the same shadow/catch-up/validate/transactional-activate pattern. Cancellation/abort never changes schema, and GC cannot reclaim pins/components/certificates until abort/activation, audit visibility, and a covering cut. Differential, metamorphic, crash, stale-tail, definition-drift, policy/revocation, branch-fork/merge, delete, approximation-generation, and rebuild-switch tests gate every index kind.
7.6 The write path as asupersync choreography
WriteCoordinator is a supervised actor. Commit requests arrive on a two-phase MPSC whose reserve/commit protocol prevents a cancelled producer from publishing a partial queue entry. Its response is a oneshot obligation whose unresolved terminal state is detected by the obligation/leak oracle; detection is not confused with impossibility. Group-commit batching uses bounded queues and the three-lane scheduler with an explicitly tested fairness/deadline policy, rather than claiming that an EDF hint alone proves starvation freedom. These are typed runtime contracts plus lab-tested database state-machine obligations, not guarantees inherited without integration evidence.