Repository navigation
Description
Page-cache durability — structural writes lost on clean shutdown at scale
Severity: P0 — Foundational. This is a class of bug that silently corrupts the persisted database. The user CANNOT trust the engine for production until this is fixed. Symptoms surface as orphan pages in the Workbench File Map, "Schema migration required" banners on reopen at scale, and chain↔directory inconsistencies caught by the new integrity check at
LogicalSegment.Load.
TL;DR
Clean shutdown of a non-trivial database (≥ 455 K entities, Default × 100 fixture) non-deterministically loses some writes that were correctly performed in memory during LogicalSegment.CreateOrGrow. The in-memory state is cartesian-proven correct at PRE-CLOSE; the on-disk state after dispose varies wildly between runs of the same fixture (same seed). The bug is NOT in CreateOrGrow, NOT in WAL recovery's FPI repair, NOT in disk-read truncation, NOT in the shutdown checkpoint guard. It is somewhere in the page-cache write path / checkpoint interaction, exposed under x100 scale write pressure.
Context
What we were doing
The previous initiative (#TBD-fill-in: BulkLoad write path + stability investigation) was wrapping up. While debugging an unrelated Workbench File Map "Unknown pages" complaint, the integrity-check primitive added during the wrap-up (chain↔directory cross-check at LogicalSegment.Load) started deterministically catching on-disk inconsistencies that had been silently propagating before.
Standing constraints:
- No WAL replay is involved. This is a clean-shutdown scenario: fixture builds →
engine.ForceCheckpoint()→ engine dispose → reopen. There is no crash, no torn-write, no recovery path. - The fixture is fully deterministic (single-threaded transactions, fixed seed
123_456_789). Typhon.Workbench.Tests.UnknownPagesDiagnosticTestis the deterministic-ish reproducer ([Explicit]). Run with--filter "FullyQualifiedName~UnknownPagesDiagnosticTest".- All foundational fixes from this session landed and are needed; without them the bug also has additional contributing causes (see "Fixes Already In" below).
The integrity check (the detector)
The session added DatabaseEngine.RunStorageIntegrityCheck() plus an inline chain ↔ directory cross-check at the end of LogicalSegment.Load:
- Directory = root page's raw-data section (500 entries) + extension map pages (2000 entries each), walked via
LogicalSegmentNextMapPBID. - Chain = forward walk via each data page's
LogicalSegmentNextRawDataPBIDheader field, page by page.
These are two independent persistent witnesses of the same truth (the segment's data-page list). When they disagree, one of the two writes lost durability. The check throws on Load with a precise diff:
LogicalSegment integrity check failed at Load:
root=113 kind=Revision directory=256 chain=528 (diff=+272)
// chain reaches 272 MORE pages than the directory enumerates
+N (chain ahead): the directory was truncated on disk; data-page chain pointers survived.
-N (directory ahead): the chain pointers were truncated on disk; root-page directory survived.
Both directions appear in failing runs. Sometimes in the same run for different segments. The data-page forward chain and the root-page directory section are persisted by separate write code paths inside CreateOrGrow, so partial-loss-in-one-but-not-the-other is the signature.
Symptoms
Reproducer
dotnet test test/Typhon.Workbench.Tests/Typhon.Workbench.Tests.csproj -c Debug --no-build \
--filter "FullyQualifiedName~UnknownPagesDiagnosticTest" \
-- NUnit.RunOnlyExplicitTests=trueThe test exercises std/bulk × scale {1, 10, 100} of the Default fixture (FixtureConfig.Default, ~4 550 entities × scale).
Stability matrix (current)
| Scale | std path | bulk path |
|---|---|---|
| x1 (4 550 entities) | stable PASS | stable PASS |
| x10 (45 500 entities) | stable PASS | stable PASS |
| x100 (455 000 entities) | flaky — ~40% PASS / ~60% FAIL | flaky — similar |
Failure example messages (varying run to run):
root=113 kind=Revision directory=256 chain=528 (diff=+272)
root=193 kind=Component directory=512 chain=128 (diff=-384)
root=325 kind=EntityMap directory=640 chain=1280 (diff=+640)
root=145 kind=Revision directory=128 chain=256 (diff=+128)
root=101 kind=Component directory=128 chain=32 (diff=-96)
The failing segment, kind, and diff change between runs. Power-of-2 alignments dominate — they correspond to ChunkBasedSegment.Grow doubling steps (4 → 8 → 16 → ... → 1024 cap).
Direct disk evidence (cartesian)
A raw File.OpenRead probe of the .bin file after engine dispose, before reopen, showed dramatic non-determinism for the SAME segment between consecutive runs of the same fixture:
Run 1: page 97 → directory[500] + NextMapPBID=801, ext page 801 has 1548 entries
Run 5: page 97 → directory[256], NextMapPBID=0 (NO extension link)
Same fixture config. Same seed. Different on-disk state. The writes themselves are non-deterministic.
Cartesian-proven facts
Each fact below is established by a code-path inspection or a fact-finding assertion that fired or did NOT fire across many runs.
| # | Fact | How proven |
|---|---|---|
| 1 | In-memory chain post-CreateOrGrow is correct. _pages.Length == WalkForwardChainPageCount(epoch) immediately after each CreateOrGrow return. |
Inline assertion at end of CreateOrGrow — never fires. |
| 2 | In-memory directory post-CreateOrGrow is correct. _pages.Length == WalkDirectoryPageCount(epoch) (root + extensions walked the same way Load does). |
Inline assertion — never fires. |
| 3 | PRE-CLOSE in-memory state is HEALTHY for every run. Full engine integrity check (orphan/phantom popcount + chain/directory for every registered segment) runs from inside the fixture before ForceCheckpoint() + dispose. Always reports IsHealthy=true. |
RunStorageIntegrityCheck() from FixtureDatabase before close. |
| 4 | Disk state after dispose is NON-DETERMINISTIC. Same fixture (same seed, same config) produces different on-disk segment sizes between runs. | Raw File.OpenRead probe of .bin after dispose. |
| 5 | No FPI repair fires during reopen. The disk content's stored CRC matches the computed CRC. The integrity bug is NOT FPI overwriting valid data with stale FPI. | Logger ("Repaired torn page") never fires. |
| 6 | No short disk reads. RandomAccess.ReadAsync always returns PageSize. |
Debug.Assert(bytesRead == PageSize) never fires. |
| 7 | _fileSize is consistent — the file on disk is the expected ~100 MB (12 224 pages), MMF.FileSize reads as the same. |
Side-by-side probe + MMF.FileSize accessor. |
| 8 | The shutdown checkpoint cycle's if (_shutdown) return; early-return at CheckpointManager.cs:344 skipped fsync + DC-decrement after writing pages. This was a real bug; removing it is part of this session's fixes (see "Fixes Already In"). |
[FACT] SHUTDOWN cycle exit: dirty=1445 unchanged from entry (before the fix). |
| 9 | The shutdown's "final cycle if LSN advanced" guard at CheckpointManager.cs:275 was a real bug for structural writes (CreateOrGrow doesn't advance LSN). Removed. |
Code reading + the fact that fixing it made smaller scales stable. |
| 10 | BitmapL3.SetL1 used Interlocked.Or for the bulk-of-64 path — non-undoable; on failure it left orphan bits in the bitmap. Replaced with Interlocked.CompareExchange. |
Code reading + matching power-of-2 orphan ranges in [ClassifyAllPages] before the fix. |
| 11 | LogicalSegmentNextRawDataPBID was vestigial dead code — written but never read, and Grow never patched the OLD tail's pointer. Now actively used as the integrity invariant. |
Grep + code reading. |
| 12 | Many engine callers pass null ChangeSet to MMF.AllocateChunkBasedSegment / AllocateSegment (DatabaseEngine.cs:4242, 4263, 4312, 4344). Without ChangeSet, changeSet?.AddByMemPageIndex(...) is a no-op, and CreateOrGrow's writes had no EnsureDirtyAtLeast call — so writes happened to memory but DC stayed at 0, and the page cache could evict the modification as "clean". |
Code reading + bug surfaced at x10 scale before the fix. |
| 13 | UnlatchPageExclusive does NOT mark the page dirty — only changeSet?.AddByMemPageIndex OR an explicit EnsureDirtyAtLeast does. |
Code reading at PagedMMF.cs:1294-1320. |
Hypotheses ELIMINATED (don't waste time on these)
| Hypothesis | Why ruled out |
|---|---|
| ❌ "Checkpoint atomicity / multi-page transactional boundary" | No WAL replay involved in clean shutdown. Once writes reach disk + fsync, they're durable. There's no atomic-batch concept to violate. |
| ❌ "CreateOrGrow's logic has wrong content" | In-memory chain and directory post-condition asserts (running at end of every CreateOrGrow) NEVER fire. The writes happen with correct content. |
| ❌ "FPI repair overwrites good data with stale FPI" | The "Repaired torn page" log never fires. CRCs match on disk. |
| ❌ "Short disk read leaves stale bytes in cache" | Debug.Assert(bytesRead == PageSize) never fires. |
| ❌ "File-size mismatch causes pages-beyond-EOF to read as zero" | File is 100 MB / 12 224 pages on disk, matches MMF.FileSize. |
| ❌ "Shutdown checkpoint LSN guard skipped final cycle" | Fixed (removed) and the bug still surfaces in some runs. Necessary fix but not sufficient. |
❌ "_shutdown early-return in cycle skipped fsync+DC-decrement" |
Same — fixed and necessary but not sufficient. |
| ❌ "SetL1 bulk-of-64 OR leaks bits" | Fixed (CAS). Was a real bug for orphan-page bitmap leak but separate from the chain↔directory durability flake. |
What's left — narrowed targets for next session
Given everything above, the bug must be in one of these page-cache write-path mechanics:
Hypothesis A — DirtyCounter accounting hole
A write path that mutates a page without bumping DC. Search for direct memory writes to pages that don't go through ChangeSet.AddByMemPageIndex or EnsureDirtyAtLeast. Note that UnlatchPageExclusive does not mark dirty (proven Fact #13) — every page-write code path must mark dirty explicitly. Audit ALL writes via Grep for page.RawData< / page.StructAt<...> = / Interlocked.Or(ref data[.
Hypothesis B — page eviction race
Page cache is bounded (default ~8192 pages); x100 fixture has 12 224 pages — eviction pressure is real. A page evicted with DC=0 (clean) is reloaded from disk on next request. If a subsequent grow modifies that just-reloaded page but EnsureDirtyAtLeast is missed (Hypothesis A), the modification dies in cache without being written. Need per-page DC history under load.
Hypothesis C — CopyPageWithSeqlock skip on contended pages
CopyPageWithSeqlock SKIPS pages where the writer holds the latch >100 ms (PagedMMF.cs:1720). The page stays dirty, supposedly caught by the next cycle. But if the page is repeatedly contended across cycles, AND the shutdown cycle also hits the same condition, the skip might escape to disk. Should log skip count per cycle.
Hypothesis D — Page-state confusion (Allocating / Idle / Free transitions)
FetchPageToMemoryOnMiss (PagedMMF.cs:832) and RequestPageEpoch (line 628) manage PageState transitions. If a fresh-alloc page transitions through states wrongly, a subsequent modification might be lost. The Allocating → Idle transition at line 654 happens AFTER the epoch tag — this is a careful sequence; needs re-validation under eviction.
Hypothesis E — ChangeSet.ReleaseExcessDirtyMarks double-decrement
After my EnsureDirtyAtLeast(2), a UoW commit calls ReleaseExcessDirtyMarks which caps DC at 1. Another UoW touching the same page → IncrementDirty (+1), ReleaseExcessDirtyMarks caps at 1 again. Two decrements vs one increment per UoW — DC drift downward over time. If DC drifts to 0, a subsequent grow writes without explicit EnsureDirtyAtLeast (Hypothesis A) is silently lost. Add an invariant assertion at end of each UoW: DC ≥ 1 for every page modified.
What I'd suggest first
- Per-page DC history dump under x100. Instrument
IncrementDirtyandDecrementDirtyto log to a ring buffer permemPageIndex. After the test fails, dump the buffer for the specific failing segment's root page. The trail shows the EXACT sequence — and the failure mode (decrement-without-increment / write-without-mark). - Audit all direct page writes for missing
EnsureDirtyAtLeast. There may be more than just theCreateOrGrowpaths I patched. - Audit
RequestPageEpochrace window between epoch tag and IO completion — specifically the page-state-transition gap aroundAllocating → Idle.
Fixes Already In (from this session — needed regardless of this bug)
These are independent, correct, foundational fixes that should land as part of closing this issue. They eliminate other contributing causes; without them, x1 / x10 scales were ALSO flaky.
| File | Change | Reason |
|---|---|---|
src/Typhon.Engine/Storage/internals/ManagedPagedMMF.BitmapL3.cs |
SetL1: Interlocked.Or → Interlocked.CompareExchange |
Bulk-of-64 allocator OR set 64 bits before realizing the L1 word was partially occupied; couldn't undo. CAS leaves bitmap untouched on collision. |
src/Typhon.Engine/Storage/internals/LogicalSegment.cs |
(1) Grow patches the OLD tail's LogicalSegmentNextRawDataPBID to the first new page(2) EnsureDirtyAtLeast(2) on every CreateOrGrow page-write (data-page-init, map-page-write, terminator-on-next-map, old-tail patch)(3) In-memory chain + directory post-condition asserts at end of CreateOrGrow (4) WalkForwardChainPageCount + WalkDirectoryPageCount helpers(5) Chain ↔ Directory cross-check at end of Load (throws on mismatch with precise diff) |
(1) Made the data-page chain a maintained invariant. (2) Closed the lost-write window when callers pass null ChangeSet.(3) Catches Grow logic bugs at the source. (4)+(5) The loud integrity guard. |
src/Typhon.Engine/Durability/internals/CheckpointManager.cs |
(1) Shutdown final cycle is unconditional (no LSN guard) — _walManager.DurableLsn not always advancing for structural writes.(2) Removed the if (_shutdown) return; early-return at line 344 that skipped fsync + DC-decrement. |
Two real shutdown-path bugs that silently dropped writes from the final cycle. |
src/Typhon.Engine/Storage/internals/PagedMMF.cs |
Debug.Assert(bytesRead == PageSize) after async disk read |
Defensive: a short read would silently leave stale/zero bytes in cache. |
src/Typhon.Engine/Storage/public/StorageMapTypes.cs + Ecs/public/DatabaseEngine.StorageIntrospection.cs + Storage/internals/ManagedPagedMMF.cs |
New StorageIntegrityReport API + DatabaseEngine.RunStorageIntegrityCheck() (popcount canary, in-memory chain/dir, ChunkBasedSegment cap check) |
Foundational defensive layer — never-lost-silently-again. |
test/Typhon.Workbench.Tests/UnknownPagesDiagnosticTest.cs |
[Explicit] test exercising std/bulk × scale {1,10,100} with full integrity assertion + raw-disk probing |
The deterministic-ish reproducer for THIS bug. Use this to drive the fix. |
Stability trajectory
- Before any fixes: every scale flaky; x1 sometimes failed; up to 1804 orphan pages in single runs.
- With this session's fixes: x1 / x10 are stably clean across many runs; x100 still flakes ~60 % but every failure is loud and named by the integrity check (segment root, kind, diff direction, diff magnitude).
Acceptance criteria for closing this issue
- Root cause identified with a cartesian-proven mechanism (which DC accounting hole / which write path / which race window)
- Fix applied + commented with the cartesian proof
-
UnknownPagesDiagnosticTestpasses stably across 10 consecutive runs at all scales (x1, x10, x100) - No regression in the existing engine suite (
dotnet test test/Typhon.Engine.Tests/...) - Workbench File Map "Unknown pages" no longer shows non-trivial counts on a fixture-built DB
-
RunStorageIntegrityCheck()is wired into a periodic CI check or pre-merge gate - Document the durability invariant in
claude/rules/durability.md: every page-write code path MUST be preceded or followed byEnsureDirtyAtLeast(≥1)—UnlatchPageExclusivedoes NOT mark dirty.
Related (not duplicates)
- The 8.5 M
BulkLoadreopen failure (CompC=schema_error) is the same family of bug — a different victim metadata page lost on persist. Fixing this likely fixes that. BulkLoadReopenIntegrationTest([Explicit]) and theRawValueHashMapScaleRepro([Explicit]) are two additional probes for the same underlying durability defect. All three converge on the same target.
Lessons / discipline reminder
Per the user's directive mid-session: stop guessing; gather facts. The right path was:
- Add the in-memory post-condition assert at end of
CreateOrGrow→ proved CreateOrGrow logic is correct. - Add the PRE-CLOSE integrity check from inside the fixture → proved in-memory is correct at close time.
- Add raw
.bindisk probe → proved disk content is wrong AND varies between runs. - Add short-read assertion + FPI-repair logging → ruled out two more hypotheses.
- Audit shutdown checkpoint code → found two real bugs to fix.
Hours of hypothesizing earlier in the session produced nothing. ~30 min of cartesian fact-finding produced the present scoped issue.
🤖 Generated with Claude Code
Activity
nockawa commentedon Jun 29, 2026
Closing as superseded by #385. The root-cause DC-cap race that produced this clean-shutdown structural-write loss is fixed there (commit 8151dfe). Minor follow-ups (CI integrity gate, doc invariant) are tracked separately.