Skip to content

Committed storage discipline — commit-durable single-version components (closes ~6× Versioned write gap) #392

Closed

Description

@nockawa

Summary

Add a Committed durability discipline for SingleVersion-layout components: writes are staged per transaction, made atomic and zero-loss durable at Transaction.Commit via a logical-redo WAL record (the unified SlotRecord with a Committed flag), then published in place to the cluster slot — with read-committed isolation and O(1) rollback, and no revision chain.

It is not a new StorageMode value: it shares the SingleVersion cluster layout (byte-identical) and is selected by a runtime knob (TickFence default ⇄ Commit escalation) on the existing per-UoW durability axis (ADR-005). This closes the ~6× Versioned write gap for the large class of components that need atomicity + zero-loss durability but not snapshot isolation / temporal queries.

Authoritative design doc: claude/design/Ecs/committed-storage-mode.md (rev 3)
WAL-program integration record (decision D7): claude/design/Durability/MinimalWal/05-committed-mode.md
Study (rationale + file:line evidence): claude/scratch/single-version-commit-mode-study.md

Why (3 code-verified facts)

  1. The 6× is the write path, not reads. Versioned bulk HEAD reads are already 2.6 ns = SV (HEAD-in-cluster, ADR-045 telemetry-lock #3). The gap is COW content-chunk alloc + chain append + GC.
  2. The WAL slot record already is "logical redo of component bytes → cluster slot." After WAL v2 (Minimal WAL — Durability Redesign (P0 + P1) #399), the unified SlotRecord / RecordCodec is replayed by RecoveryApplier's slot upsert in LSN order. The Committed write reuses the same wire format + replay; only the trigger (commit vs tick) and a Committed RecordFlag differ. Zero new WAL plumbing.
  3. The runtime DAG already forbids concurrent same-entity write×write and undeclared read×write at Build() (AC-01/AC-02, rules/runtime-scheduling.md). So read-committed is sufficient for engine-scheduled systems — MVCC snapshot isolation was doing work the scheduler guarantees statically.

Decision (four behaviours, three StorageMode layout values)

StorageMode (layout) Discipline (runtime) For
Transient — scratch; lost on crash
SingleVersion TickFence (default) position/velocity/health — ≤1-tick-loss OK, batched WAL, max throughput (kept)
SingleVersion Commit (escalation) same layout when a write must be zero-loss + atomic (teleport, pickup), via side-tx
Versioned (always commit-scoped) economy/progression + temporal + multi-master conflict handlers

Mandated write path — Variant A (deferred-apply / staging arena). Writes are buffered per-transaction (reusing the Versioned SingleCache read-your-own-writes mechanism); at commit the WAL SlotRecord is appended, then values are published in place to the cluster slot. Variant B (in-place + undo) is rejected: pre-commit in-place writes dirty the page, and the fuzzy checkpoint — gated only by ActiveChunkWriters, released before commit — could persist uncommitted bytes into the data file with no compensating WAL record → unrecoverable phantom data (violates CM-01 / CK-02).

Index timing — aligned with Versioned. The exact secondary B+Tree Move + view notifications happen at commit; spatial R-tree, zone maps and cluster broad-phase AABBs stay fence-batched for all modes (no Committed-specific spatial behaviour — the durability knob must not perturb when a structure reflects a write).

Out of scope (stays Versioned): snapshot isolation, temporal/"AS OF", TAIL indexes, multi-master conflict-rebase.

Acceptance Criteria

  • AC-1 — Shared layout, runtime discipline. A SingleVersion component can be written under TickFence (default) or Commit discipline chosen at runtime per tx / side-tx — no layout change, no new StorageMode enum value.
  • AC-2 — Commit durability. A Commit-discipline write is recoverable to the exact committed value after a crash (Immediate ⇒ durable at Commit; Deferred/GroupCommit ⇒ durable at uow.Flush()). Crash/recovery test (SimulateHardCrash after WAL flush, before checkpoint).
  • AC-3 — Atomicity + rollback. All Commit writes become visible together at commit; tx.Rollback() discards the staged values (HEAD was never touched). No partial visibility to a concurrent/subsequent transaction.
  • AC-4 — Read path unchanged on the hot path. Other transactions read the cluster HEAD slot directly (read-committed), no chain walk. The only added branch is one per-transaction-constant _tx.Discipline check on the writing tx's own read-your-own-writes path (SingleCache). Bulk iteration stays ≤2.7 ns/entity.
  • AC-5 — Write path ~SV-class. A Commit write (Variant A staging) is ≤25 ns; commit publish ≤60 ns/component; ≥8× faster than a Versioned write (Zen 4). The TickFence in-place path (~3 ns) is unregressed. (Measured: write 23.25 ns ✓, 22.6× vs Versioned ✓, TickFence unregressed ✓; publish 65 ns vs ≤60 ns is inconclusive — BDN iteration too short — follow-up to re-measure. See the benchmark comment below.)
  • AC-6 — No chain allocated. A Commit write allocates zero CompRevTable / content chunks / deferred-cleanup entries.
  • AC-7 — Recovery reuse. Recovery replays Commit records as ordinary SlotRecords (Committed flag set) through RecoveryApplier's slot upsert in LSN order, composing with tick-fence records for the same slot (last-writer-wins by LSN). Zero Committed-specific recovery code.
  • AC-8 — Scheduler safety. A system declaring ReadsSnapshot on a SingleVersion-layout component is rejected at Build() (rule CM-04 / runtime-scheduling.md AC-05).
  • AC-9 — Versioned & TickFence untouched. No behavioural change to Versioned or to SingleVersion under the default TickFence discipline.
  • AC-10 — Tests + proof. Unit + recovery + scheduler-rejection tests; CM-01 mid-tx page-memory probe; CM-04 Build()-rejection; span-over-staged Debug-assert; MixedDiscipline crash-sweep workload; TLA+ Spec S3 green; write/commit benchmarks recorded. All green in the full suite (zero new reds).
  • AC-11 — Exact-index consistency at commit. After a Commit tx commits, an exact secondary B+Tree query reflects the committed value with no false-negative (Move done at commit, matching Versioned). Spatial/zone-maps/cluster-AABBs stay fence-batched for all modes. Query-after-commit test.

Key open questions — resolved in design

  1. ReadsSnapshot policy → reject at Build() (CM-04). ✅
  2. Distinct chunk type vs flag → reuse the unified SlotRecord with a Committed RecordFlag (WAL v2); no distinct chunk type. ✅
  3. WAL volume for multi-write-per-tick → staging coalesces to the last value per slot at commit; one record per slot per commit. ✅
  4. Detect-only conflict counter → deferred; last-writer-wins only. ✅

Body reconciled 2026-06-25 to match the authoritative rev-3 design doc (Variant A supersedes the original Variant-B mandate per decision D7). Original Variant-B framing preserved in git history of the design doc.

Shipped 2026-06-26 via #401 (engine) + typhon-claude#52 (docs). AC boxes reflect the merged result; AC-5 publish-pass benchmark is inconclusive (re-measure follow-up).

🤖 Generated with Claude Code

Activity

  1. moved this to Ready in Typhon devon Jun 9, 2026
  2. nockawa commented on Jun 25, 2026

    @nockawa
    CollaboratorAuthor

    📌 Post-implementation doc TODO — update claude/design/Ecs/06-storage-modes.md

    Once the Committed discipline is implemented, 06-storage-modes.md must be updated to introduce the durability-discipline axis on the SingleVersion layout. As written it describes only the TickFence behaviour, so several statements become false under the Commit discipline. Hold the edit until implementation so the doc set doesn't describe an unbuilt feature as present.

    Add: a "Durability discipline (TickFence ⇄ Commit)" section + a sub-matrix (or a Commit column). The new column reads: "SV read path + Versioned commit/durability/index/view semantics, minus the revision chain and snapshot isolation."

    Statements in 06 that are TickFence-only and flip under Commit:

    Location Doc says (TickFence) Under Commit
    L339–343, L468 SV write "immediately visible to all readers" Staged; invisible to others until commit-publish
    Matrix L33 "WAL on commit: None" Per-commit SlotRecords
    Matrix L34 "WAL tick fence: Yes" No — durable at commit, dirty bit cleared (CM-03)
    Matrix L36 "Crash recovery: ≤1 tick loss" Zero-loss at commit
    Matrix L38–39 Indexes/Views "Updated at tick boundary (deferred)" At commit (B+Tree + spatial-escape + views)
    Matrix L41, L468 "Data updates: Direct write (no UoW needed)" Requires a transaction (only reachable via tx/side-tx)
    L417–427 Rollback: SV "NOT reverted … by design" Reverted — the V-vs-SV rollback asymmetry disappears under Commit

    Also fix one pre-existing imprecision: L38 "Versioned Indexes: Updated at commit" really means "B+Tree at commit, spatial at fence" — relevant because Commit is intentionally stricter than Versioned on spatial (reconciles fat-AABB escapes at commit; see design doc §Derived-structure maintenance / CM-05).

    Authoritative spec for the feature: claude/design/Ecs/committed-storage-mode.md (rev 3).

  3. nockawa commented on Jun 25, 2026

    @nockawa
    CollaboratorAuthor

    ✏️ Correction to the previous comment — spatial stays at the fence (aligned with Versioned)

    The prior comment said Commit reconciles spatial-escapes at commit and is "stricter than Versioned on spatial." That was wrong and has been reverted in the design doc (rev 3). Corrected rule:

    Commit aligns with Versioned exactly — it's the transactional sibling, and the durability knob must not perturb which derived structures are fresh when (decision #31):

    • B+Tree (exact index) + view notifications → at commit (both Commit and Versioned).
    • Spatial R-tree, zone maps, cluster AABBs → at the tick fence (all modes, incl. Versioned). Spatial is a tick-granular, conservative, derived broad-phase; a not-yet-reconciled fat-AABB escape is an in-memory lag identical across modes — not a per-mode discrepancy, and rebuilt from HEAD on recovery (RB-01).

    So the 06-storage-modes.md post-impl matrix row should read: Indexes (B+Tree) + Views → at commit; spatial → at fence under Commit — not "spatial-escape at commit." And there is no "stricter than Versioned" caveat; the earlier note about that is withdrawn. (The L38 "Versioned indexes at commit" imprecision still stands: it means B+Tree-at-commit, spatial-at-fence — which is now exactly what Commit does too.)

    Making spatial commit-synchronous would be a separate spatial-subsystem decision affecting all modes (perf cost: per-commit reinserts, losing the batched/parallel AabbRefresh) — out of scope for #392; file its own issue if ever wanted.

  4. moved this from Ready to In Progress in Typhon devon Jun 25, 2026
  5. nockawa commented on Jun 25, 2026

    @nockawa
    CollaboratorAuthor

    Implementation plan — approved 2026-06-25 (core feature + tests)

    Scope this pass: core feature + unit/recovery/scheduler tests + CM-01 probe (AC-1..9, AC-11). Deferred to a follow-up: TLA+ Spec S3, the MixedDiscipline crash-sweep workload, and the BDN ≤25/≤60 ns perf gate (the write/commit path is built perf-shaped; only the formal benchmark is deferred). ECS-12 (DirtyBitmap orphaned-array race) is treated as orthogonal — Variant-A staging never Sets the dirty bit on the write, and the publish-time clear is last-writer-wins-benign per CM-03; ECS-12 stays a separate H-track bug.

    Authority: claude/design/Ecs/committed-storage-mode.md (rev 3). Branch: feature/committed-storage-mode.

    Codebase readiness (verified)

    • RecordFlags.Committed is defined (RecordFormat.cs:46) and stamped from batch.CommittedDiscipline (RecordCodec.cs:90-94); RecoveryApplier applies Committed records as ordinary LSN-ordered slot upserts → AC-7 free, zero new recovery code.
    • CreateSideTransaction exists (TickContext.cs:73, Func<DurabilityMode,Transaction>); per-tx arena _commitBatchArena exists (Transaction.cs:1630, commit-time-lazy → hoist to first staged write).
    • Versioned B+Tree-at-commit template: PrepareClusterVersionedSlot (Transaction.cs:1322-1472) + PublishClusterVersionedSlot (1479-1506).

    Steps (each mapped to ACs)

    1. DurabilityDiscipline enum + [Component(DefaultDiscipline=)] + ComponentTable.Discipline (AC-1)
    2. Thread discipline through CreateQuickTransaction/CreateUnitOfWork/CreateTransaction/CreateSideTransaction → Transaction.Discipline, CM-02 freeze-on-first-write (AC-1)
    3. Variant-A staging into the arena + CompRevInfo.StagedOffset + read-your-own-writes branch on _tx.Discipline (AC-4, AC-6)
    4. Commit publish: BUILD via new AddSlotStaged (zero-copy) → APPEND → WAIT → PUBLISH memcpy→HEAD; O(1) rollback; CM-01 probe (AC-2, AC-3, AC-6)
    5. Exact B+Tree Move + view-notify at commit, mirroring PrepareClusterVersionedSlot; spatial stays at fence (AC-11)
    6. Scheduler Build() rejection of ReadsSnapshot on non-Versioned + new rule AC-05 (AC-8)
    7. Tests per AC + full suite; doc fixes

    Deviations flagged at approval

    • D-a CM-04 rejects ReadsSnapshot on any non-Versioned (incl. Transient), not only SingleVersion (neither has MVCC history).
    • D-b DefaultDiscipline=Commit resolution = escalate-on-first-write + freeze + log (open-Q1 "keep + log"); throw a clear CM-02 error if a TickFence write already happened.
    • D-c zero-copy staging via CommitBatchBuilder.AddSlotStaged(offset,len); staged ref invalidated by the next Write in the same tx (documented + Debug-guarded).

    🤖 Generated with Claude Code

  6. nockawa commented on Jun 25, 2026

    @nockawa
    CollaboratorAuthor

    Core implemented + tested — 2026-06-25 (branch feature/committed-storage-mode)

    Variant-A (deferred-apply / staging) Committed discipline on the cluster path, regression-free against the full suite (baseline-diffed — every full-suite red is pre-existing or parallel-flakiness; my changes add zero new reds).

    Acceptance criteria

    AC Status Evidence
    AC-1 discipline API + DefaultDiscipline escalation (CM-02) ✅ CommitDiscipline_*, DefaultDiscipline_Commit_EscalatesTransaction
    AC-2 commit durability (crash recovery) ✅ CommitDiscipline_Write_SurvivesHardCrash — required building the cluster RecoveryApplier increment (the deferred "cluster path")
    AC-3 atomicity + O(1) rollback ✅ CommitDiscipline_MultiWrite_Atomic, CommitDiscipline_Rollback_DiscardsStaged
    AC-4 read path + read-your-own-writes; HEAD untouched pre-commit (CM-01) ✅ CommitDiscipline_ReadYourOwnWrites, CommitDiscipline_StagedWrite_NotVisibleBeforeCommit
    AC-6 no chain ✅ staged writes never allocate CompRevTable/content chunks (Variant-A staging buffer)
    AC-7 recovery reuse (LSN-ordered slot upsert, Committed flag = telemetry) ✅ recovery test + RecordCodec/RecoveryDriver unchanged
    AC-8 scheduler CM-04 rejection + rule AC-05 ✅ ReadsSnapshot_OnSingleVersionComponent_ThrowsAtBuild; runtime-scheduling.md AC-05
    AC-9 Versioned/TickFence unregressed ✅ full suite, no new reds (baseline-diffed)
    AC-11 / CM-05 exact B+Tree index fresh at commit (no fence) ✅ CommitDiscipline_IndexedWrite_FreshAtCommit_NoFence
    AC-5 ≤25/≤60 ns BDN gate ⏳ deferred path built perf-shaped; formal benchmark not run
    AC-10 TLA+ Spec S3 + MixedDiscipline crash sweep ⏳ deferred CM-01/CM-04 covered by unit tests; formal proof gates deferred

    Notable engineering decisions / deviations

    • Cluster recovery increment built. AC-2 was not free as the design assumed — RecoveryApplier was flat-path only. Added a cluster reconstruction path (claim slot → SoA value write → ClusterEntityRecord), mirroring live FinalizeSpawns. This is the previously-deferred "P2-gated cluster recovery."
    • Scope: Commit discipline currently requires a cluster-eligible archetype; a non-cluster SingleVersion write under Commit throws loudly (non-cluster support = follow-up).
    • Staging: dedicated per-tx native buffer (stable pointers, isolated from SingleCache to avoid colliding with Versioned revision consumers), copied into the WAL batch via AddSlot at commit. The "stage directly into the batch arena (zero re-copy)" micro-opt is deferred for pointer-safety.
    • Index reconcile extracted into a shared ReconcileClusterIndexAndViews reused by both the Versioned cluster commit and the Committed publish (rationalize = subtract).
    • Two bugs found + fixed mid-implementation: SingleCache staging collision (NRE in revision manager) → dedicated CommitStaged dict; CM-04 Build() NRE on access-less engine systems → null-Access guard; CM-02 escalation hole on the cluster in-place path → NoteSvInPlaceWrite.

    Docs updated: committed-storage-mode.md (status + impl notes), MinimalWal/05-committed-mode.md §1 (index-timing correction), rules/runtime-scheduling.md (AC-05).

    Ready for review + commit (engine + tests in the main repo; docs in the nested claude/ repo).

    🤖 Generated with Claude Code

  7. nockawa commented on Jun 26, 2026

    @nockawa
    CollaboratorAuthor

    AC-5 / AC-10 benchmark record (Zen 4 — Ryzen 9 7950X, .NET 10, Release)

    CommittedDisciplineBenchmarks, OperationsPerInvoke = N = 1000, [SimpleJob(warmup:3, iter:7)], MemoryDiagnoser.

    Method Mean Cost (Δ over Resolve_Only 73.76 ns) Allocated
    Resolve_Only (baseline) 73.76 ns — 1 B
    Write_Sv_TickFence 80.77 ns +7.0 ns 1 B
    Write_Sv_Commit 97.01 ns +23.25 ns 104 B
    Write_Versioned 600.14 ns +526.4 ns 288 B
    Commit_Sv_Commit 214.28 ns (full commit) 170 B
    Publish_Only 65.48 ns (publish pass) 0 B

    Verdict vs AC-5 targets

    Target Result
    Commit write ≤ 25 ns 23.25 ns ✅ met
    ≥ 8× faster than Versioned write 526 / 23.25 = 22.6× ✅ exceeds
    TickFence in-place ~3 ns, unregressed +7.0 ns (baseline ±5 ns noise; path unchanged) ✅ no regression
    Commit publish ≤ 60 ns/component 65.48 ns ⚠️ ~9% over — but inconclusive: BDN warned the Publish_Only iteration (57 µs) is too short to measure reliably (Error ±18.7 ns, band ≈ 47–84 ns)

    Notes

    • Write_Sv_Commit allocates 104 B/op — the managed Dictionary<long,StagedSlot> staging directory (the native staging buffer is off-heap, not counted). Still 3× under Versioned's 288 B, and AC-6 (no revision chain) holds; not allocation-free.
    • The publish-pass result is the one soft spot. To turn it from inconclusive into a clean pass/fail, Publish_Only needs a longer iteration (e.g. larger N or InvocationCount); recommend a small follow-up to re-measure it in isolation.

    PRs: engine #401, docs nockawa/typhon-claude#52.

  8. moved this from In Progress to Done in Typhon devon Jun 26, 2026
  9. added a commit that references this issue on Jun 26, 2026
    cbef4b6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions