Skip to content

#750 Close the integrity gap: 27 of 27 cross-structure checks, each with a fixture that produces exactly it - #772

Merged
nockawa merged 25 commits into
mainfrom
feature/750-integrity-gap
Aug 11, 2026
Merged

nockawa merged 25 commits into
mainfrom
feature/750-integrity-gap

Conversation

@nockawa

@nockawa nockawa commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

Closes #752 · #753 · #754 · #762 · Part of #750 · Advances #755 (blocked, see below)

Docs: Typhon-Claude PR #80 — merge that first, per the docs-first order.

What this is

The shipped scanner (#729) implemented 20 of 47 catalogued checks and did lossless repair only. The cross-structure families — the ones that catch a database where every individual structure is well-formed — were all deferred, on the grounds that they needed schema information the file does not carry.

That premise was wrong, and correcting it is what this branch is. All 27 Tier 0–2 checks now run, offline, with no schema assembly:

Family Running
CHN 01 02 03 04 05 06
CLU 01 02 03 04 05
ALO 01 02 03 04
MAP 01 02 03 04
IDX 01 02 03 04 05 06 07
WAL 02 (and 04 corrected)

Every one has a negative case over a healthy database at Deep, declares itself skipped when its precondition fails, and — with two stated exceptions — a damage fixture that produces exactly it and nothing else.

The correction the whole plan rested on

09 §1 concluded "the schema is not in the file", generalised from one call site (DBD = new DatabaseDefinitions()). That is a true statement about how the engine boots and a false one about what the file records.

ComponentR1, ArchetypeR1, FieldR1 and AssemblyR1 are all persisted. Between them they carry component sizes, field offsets and types, per-field index roots, per-archetype component membership, storage modes and the entity-key watermark — everything the deferred checks were said to need.

Two increments are closed as unnecessary by this:

  • G5 (typhon check --schema <dll>) — FieldR1 carries OffsetInComponentStorage, SizeInComponentStorage, Type and IndexSPI. The four Tier-2 checks it existed to unlock need no assembly and no new CLI surface.
  • G1's second half — component count is in ArchetypeR1. Only the stride was genuinely missing, and that half shipped as format revision 7.

The habit that would have prevented the error, and its repeat: before concluding a quantity is absent from the file, grep for its R1.

What is new, structurally

Reader Unlocks
ChunkGeometry offline chunk arithmetic; proved against the engine across 25 strides and >10,000 chunk ids
SchemaCatalogReader the manifest, including collection fields through the VSBS
VsbsReader ComponentR1.Fields, ArchetypeR1.ComponentNames, and ALO-04's handle accounting
ClusterLayoutReader ClusterSize and per-component data offsets, re-derived and pinned against the engine
IndexDirectoryReader + IndexNodeLayout B+Tree directory and all four node layouts

Plus DamageKit: 16 damage primitives, each declaring the byte ranges it writes, the exact finding codes a correct scan must produce, the verdict, and whether repair is lossless. Three disciplines enforced mechanically — baseline proven Sound first, byte-exact diff against a pre-damage snapshot, and detection asserted exactly in both directions.

Defects found, and how

Nine decode defects were caught, every one by running against healthy data and treating the finding as a bug in the reader. None was findable against damaged data, because a wrong decoder produces plausible values either way.

The two worth reading:

  • The EntityMap walk's chunk cursor aliased one page buffer. The walk nests three deep, so reading a bucket rewrote the directory the outer loop was still iterating: 27 of 256 buckets visited, 4 keys of 64 returned. Misread as a bucket-layout problem for two rounds; the layout was right all along. No existing assertion could see it — MAP-01 passes trivially on a subset, MAP-03 passes because fewer entries cannot collide, MAP-04 passes because no pointer was bad. Counting against a known population, from outside the walk, is what catches it.
  • WAL-02 was inspecting one frame out of eight. Frames are written one per 4 KiB drain block (the O_DIRECT alignment IWalFileIO requires), not densely packed. A walk advancing by FrameLength reads the padding after frame 0 as unwritten space and stops. Surfaced only because fixing WAL-04 forced the same bytes to be read for a different purpose.

Also: a cluster does not always hold 64 slots (CLU-01 read String64 bytes as entity keys on a healthy database); a B+Tree node holds N keys and N+1 children with the leftmost in its own field; IDX-05 counted internal-node separator keys as duplicates; CLU-03's first run joined two different EntityId encodings, matched nothing, and reported success over an empty comparison.

That last one produced the rule now applied throughout: comparing nothing and agreeing are indistinguishable in a report unless one of them says so. Checks that can compare zero items declare themselves skipped.

Engine-facing fixes

  • WAL-04 asserted contiguity over segment ids, and ids are not dense. The pre-allocated spare is promoted with a fresh id, so a healthy log goes 1 → 3. Any database opened twice drew a Fatal. Now compares LSN coverage, bounded to the replayable window. It shipped with no test; it has three now.
  • typhon repair --apply threw on any plan containing a RegenerateDerivedStructures step, because nothing ever supplied the callback Apply asks for. Worse than the step being absent: the plan is rendered for an operator as a list of what will happen, and they consented to a step the tool could not perform.
  • CHK-BOO-02 promised a format-revision guard that did not exist (Integrity G10 — repair --apply must refuse a format revision it does not know (OQ-7) #762). Rule IR-01 now backs it, Apply refuses on any mismatch before the pre-repair copy, and a CLI ratchet fails if a --force is ever added.

Honest gaps

Verification

Suite      5205 passed · 20 skipped · 3 failures
Integrity  123 tests green
Gates      check-rule-scopes · audit-rule-coverage (0 blocking) · check-doc-links — PASS

The three failures are pre-existing on main, deterministic, and tracked: DirtyCounter_IsConservedAtQuiesce and ParallelOperations_AreLinearizable → #400 (both raise the ChangeSet concurrent mutation guard, which names #400 in its own text); PayloadAxes_SurviveACrash → #389. Evidence added to both issues, including a CsCheck counterexample shrunk to two operations on two threads with a reproducing seed.

Review notes

Read 09 §5.4 (docs PR #80) first — it is the status table and the list of corrections, and it is the shortest path to what this branch actually establishes. The commits are ordered so each is independently reviewable; the two worth the most attention are e524111b (the aliasing fix) and ef9a9882 (the WAL corrections), because both changed what an already-green test was proving.

nockawa added 25 commits August 10, 2026 16:08
Every repair claim in this area rests on the corruption it starts from. A fixture that damages a page by approximate means and then reports a successful repair has established only that some code ran — not that it did the right thing, and not that it did nothing else. The failure mode is silent, because the assertion at the end is green either way.

So the kit states, for each primitive, exactly which byte ranges it will write, exactly which finding codes a correct scanner must produce, and whether repair of that damage must be lossless. Three checks enforce it mechanically. Baseline asserts the database is Sound before anything is touched, so a finding afterwards cannot have predated the damage. AssertOnlyDeclaredBytesChanged diffs the whole file and fails on any byte that moved outside a declared range. AssertDetectedExactly requires the declared codes and no others, because "it reported something" is the failure this feature exists to replace. Four tests damage the kit's own assertions to prove they fire.

Two things the fixture was getting wrong surfaced immediately, both of which would have quietly weakened every test built on it. The WAL was being written beside the bundle rather than inside it, which is not the shape the engine produces; any damage that also disturbed the checkpoint watermark then drew a second finding about a missing log, and that finding was about the fixture. And the two halves of the meta pair are not interchangeable: clobbering the half the database reads from leaves it on the previous metadata write, one generation back, with the clean-shutdown flag clear. The kit now asks which slot is current rather than assuming, and callers choose Stale to isolate the pair check or Current to exercise the compound case.

FlipByteInPage takes the expected verdict as a parameter rather than declaring one. The same one-byte corruption is DataLoss on a page holding live primary data and Divergence on a derived one; only the caller knows which page it picked, so a default would have made the kit assert its own assumption.

The round-trip tests end on the property rather than the report. Repairing the meta pair must leave both halves valid — that is what CK-05 buys, and it is not the same claim as "the scan is clean now", since a database running on one good slot also scans clean until that slot tears. The proof is to knock out the other half afterwards and require the database to survive it.

Suite: 5134 passed, 3 failed — the same three that fail on unmodified main, baselined three times there and at the pre-#737 branch point.
…self (format revision 7)

An offline reader could already find a segment, read its directory and classify every page — LogicalSegmentHeader.Kind was added so introspection would not have to re-derive ownership from context. What it could not do was locate chunk n inside any of those pages, because the stride reaches ChunkBasedSegment as a constructor argument derived from a CLR component type and was nowhere in the file. One missing integer, and the entire cross-structure check family is unreachable: every CHN check reads engine-defined chunk headers rather than schema-shaped payload, and still cannot get to them.

Stride is the same class of fact as Kind, about the same page, so it goes in the same place. Two bytes at [54,56) of the base-header zone, beside the sector-geometry declaration F-2 introduced, leaving [56,64) free. A ushort because a chunk cannot exceed one page's raw data area, so a wider field would buy nothing and cost a third of what is left. No page-layout growth and no effect on chunk capacity — the metadata region where the occupancy bitmap and sector footers live is untouched.

Written at page init through the same virtual as MetadataReservedBytes, and for the same reason that hook exists: a page is unlatched and dirty between CreateOrGrow initialising it and its owner finishing with it, so a post-hoc stamp races a checkpoint that catches it in that window. Stamped on every page rather than only the root, because a repair tool meets torn roots — that is its job — and four bytes of already-free header space is not worth trading for losing the ability to interpret a segment whose root is gone.

Clean break: revision 7 does not read revision 6, and the existing gate already refuses with the revision found and the one expected. That matters more than usual here. The geometry bytes read as zero on a v6 page and zero means "this segment has no chunks", so a reader that tolerated the older revision would conclude exactly the wrong thing about a segment full of them, and every check downstream would agree with it. The test forges a v6 bundle properly — patching the revision in both meta slots and re-stamping each page with the engine's own StampPageForWrite — so the file reaching the open path is checksum-valid in every respect except the one under test. Patching the byte alone would have produced a CRC failure and the test would have passed while proving something else.

Cluster size and component count are not yet recorded. ChunkBasedSegment does not know them: segments are created generically with a stride and the cluster layout is known one layer up, in ArchetypeClusterState. [56,64) is reserved for them. They gate the CLU family only; stride alone unlocks CHN, MAP, ALO and the structural IDX checks.

Suite: 5139 passed, the same three failures that fail on unmodified main. The round-trip test doubles as the collision detector for the byte range: it reads the stride back after checkpoints and a reopen, so anything else writing there shows up as a mismatch rather than as silence.
…s not speak (IR-01)

`repair --apply` had no format-revision check at all, and the scanner's own report was already telling operators otherwise: CHK-BOO-02's detail text read "Repair is refused outright on a newer format". Documented behaviour that is only documented is worse than absent behaviour, because it gets relied on. This adds the guard the sentence promised, and widens it to the case OQ-7 decided on.

The comparison is equality, not "at least". The instinct that an older revision must be safe to write is the dangerous one, and #753 is the standing counter-example: revision 7 claimed bytes [54,56) for the chunk stride, and those bytes are zero on a revision-6 page — zero being this build's sentinel for "this segment holds no chunks". An older page therefore does not fail to decode, it decodes to a confident wrong answer, and every cross-structure check downstream agrees with it. Before this change a v6 bundle drew no finding at all and `--apply` would have run to completion: pre-repair copy taken, pair slot rewritten, then the derived-structure step failing deep inside the engine's version gate, leaving a half-applied repair on a database this build should never have touched.

Split by verb, per OQ-7. `IntegrityScanner` still scans a foreign revision and names both revisions in the finding — an operator reaching for a scanner has already lost the happy path, so refusing to diagnose defeats the tool. `DatabaseRepair.Apply` refuses, gating on `DescribeRevisionRefusal` before the fingerprint drift check and before the pre-repair copy, and reading the revision from the file rather than from the plan (a plan can arrive from another build or a text editor). `Plan` emits zero steps and sets `BlockedReason` — blocked is kept distinct from empty, because "nothing to repair" over a database full of findings is the most misleading thing this tool could print. The CLI and the Workbench panel render the refusal instead of offering an apply they know will fail.

There is no override, and that is now enforceable rather than aspirational: `RepairCommandSurfaceTests` fails if a `--force`, `--ignore-version` or similarly-named option is ever added to the repair command, and says to change the rule first.

`rules/durability.md` gains module IR and rule IR-01. #729 shipped roughly three thousand lines of scanner and repair with no rules at all; this is the first, and it gives G12's check-to-rule matrix somewhere to point.

Proof is one revision-6 forgery driving both halves: the revision patched in both meta slots and each re-stamped with the engine's own StampPageForWrite, so the file is checksum-valid in every respect except the one under test. The refusal assertion requires the message to name both revisions, which is what separates it from the drift check — forging the revision also moves the fingerprint, so a weaker assertion would pass against a build with no gate. `Mutant_ApplyWithoutTheRevisionGate` shows the assertion can fail.

The forgery moved into DamageKit, and doing so exposed a defect in #753's own copy of it: it re-stamped each meta page with the slot number as its page index, but an A/B twin records the primary's index — that is how a reader tells the two apart — so the forgery was making a structural change as well as a re-label. The test was green, because it asserted an exception the version gate throws long before anything reads a page index. AssertOnlyDeclaredBytesChanged found it in one line.

Full suite 5146 passed, 3 pre-existing failures unchanged. check-rule-scopes, audit-rule-coverage and check-doc-links all pass; coverage baseline moves to 193 rules, 27 verified, 5 with mutants.
… every stride

The cross-structure checks read engine-defined chunk headers out of raw bytes, and they find them by re-deriving the engine's layout arithmetic from the one fact a page now records — the stride (#753). Everything else that arithmetic needs turns out to be a pure function of it: the cache-line alignment padding, chunks per page, where chunk 0 starts, how many words the occupancy bitmap occupies. That is what made "persist geometry" a four-byte change instead of a schema project, and it is also the thing most worth being wrong about, because a re-derivation that drifts does not fail. It reads plausible-looking chunk headers out of the wrong offsets and reports confident findings about them.

So `ChunkGeometry` is not argued for, it is compared. The engine allocates a real segment at each of twenty-five strides and is asked where its chunks are; the offline locator is asked the same with nothing but the stride. Every derived quantity matches, and `GetChunkLocation` matches across the whole addressable range — over ten thousand chunk ids, asserted, because a locator that resolved nothing would satisfy the rest. The strides are picked for the arithmetic's discontinuities rather than for tidiness: 8 is the minimum a chunk-based segment allows, 64 is the alignment ceiling where padding collapses to zero, and the awkward ones between are where padding is non-zero and the raw-data area divides unevenly.

The occupancy half is proved separately, against a real database. The first attempt did it on a bare ManagedPagedMMF and read zeros out of a five-page file — correctly, as it turns out: a bare page file has no checkpoint machinery, so nothing it allocates ever reaches disk. Worth keeping as a finding rather than working around, because the offline claim means nothing about bytes that are not there. The occupancy comparison now runs where the checks will: a database built through the engine, checkpointed and closed, with the engine's own segment descriptors captured while it was alive as ground truth.

No checks yet — this is the floor they stand on.
…HN-02 against a guess

03-checks.md lists CHN-02 as "post-recovery chains satisfy ItemCount == 1, NextChunkId == 0, UowId cleared", citing RB-03. But RB-03 is the postcondition of the chain SCRUB, and the scrub runs on the crash path — so a cleanly-closed database that has simply accumulated MVCC history has every right to hold multi-element chains, and an offline reader looking at a file at rest cannot tell "never scrubbed because it never crashed" from "crashed and the scrub did not run". Written unconditionally, the check would have reported a divergence on every healthy database with history in it.

So it was measured rather than argued. 32 entities, four update rounds, 128 revisions written, one checkpoint, clean close: every chain is already collapsed to a single element and not one still points at a continuation chunk. The shape RB-03 describes as the scrub's postcondition is also what an ordinary consolidating checkpoint leaves behind, which is what lets CHN-02 assert it without knowing whether recovery ever ran.

The boundary the measurement does not establish is the one the check will have to respect, and it is now written down in both the test and 09 §5.3: a file left by a crash, or closed without a checkpoint, has had no such consolidation, so CHN-02 gates on the bootstrap's clean-shutdown flag rather than firing unconditionally.

The probe is kept as a guard rather than deleted. It asserts the measured shape with the full histogram in the failure message, so the day a checkpoint stops consolidating, the test that says so is the one CHN-02 was designed on. It also pins sizeof(CompRevStorageHeader) at 28 — a comment in CompRevStorageElementTests still implies 20 — because every CHN element read is sliced by that number and nothing else in the suite would notice it moving.

Full suite 5150 passed, the same 3 pre-existing failures.
… a scan needs

05 §9.6 asked whether a crash-path open can put re-derived state on disk before RB-04 refuses, and said the answer decides whether offline-first is a preference or a hard requirement. The reasoning on the code suggested it could not: RebuildEntityMapOnCrash only dirties page-cache pages, and ResolveSuspectPrimaryPages throws before SealRecovery. Nobody had traced eviction, so this measures instead of arguing.

It is a hard requirement. Against a database with one torn live cluster page, a crash-path open rewrites about twenty-five pages — seventeen of them EntityMap, plus Occupancy, Component, Revision and a Cluster page — at the default cache size and again with the cache at its floor, where eviction is forced rather than hoped for. Those are exactly the structures a cross-structure check reads as independent corroboration, so one open replaces them with values re-derived from the damaged database and the scan afterwards can only confirm that the rebuild agrees with itself.

Two consequences, both recorded in the design. The checks that G2 adds have to state their confidence honestly rather than reporting Confirmed for anything found offline, because a database opened since the damage is no longer offering independent structures. And no surface may advise opening before checking; that flow destroys what the check needs.

A second result fell out of the same probe and it is a boundary rather than a defect: the open succeeded. The engine served a database the offline scan calls DataLoss, because RB-04's detection is read-triggered — a page joins the suspect set when a load CRCs it, and recovery loads only what it needs, so a torn page nothing touches is never checked. That is what RB-04 documents, demonstrated end to end for the first time, and it is the plainest case for an exhaustive offline sweep: the engine finds damage where it steps, a scanner finds it everywhere. Pinned so that a change to RB-04's reach shows up here rather than silently outdating the rationale.

Suite: 5137 passed, the same three failures that fail on unmodified main. Three full runs; a fourth victim appeared once, which is the documented random-victim flake band and not a change in rate.
The note recording that CK-05 was violated and fixed never reached this repository. rules/ moved here from the docs repo in #747, and it moved from that repo's main — which did not carry the note, because the design branch holding it was still unmerged. The code fix landed; the rule text describing what it fixed did not. So rules/durability.md has been documenting CK-05 without recording that a real violation of it was found, or naming the regression test that now guards the property.

The note is back, with the detail that matters: the exclusion existed all along in CollectDirtyMemPageIndices, but SavePages is fed by a ChangeSet rather than by that scan, so it never applied there — and while the checksum-stamping step was guarded by FilePageIndex > 0, the write was not. Ordinary shutdowns were reducing the pair to a single copy, silently, because the surviving slot still opened the database and every structure was individually well-formed.

The verified: field now also names MetaPairStructuralFlushTests and says why it was needed: every earlier CK-05 test checks the pair's read selection or its write protocol in isolation, and the bug was a second writer bypassing the protocol entirely. Sole-writer was the property nothing covered.

Beyond the port, CK-05 gains a genuineness proof. It is [fatal] and had no [VerifiesRule] test; it now has one, plus the [RuleMutant] companion the audit asks for — a database with one clobbered slot driven through the verifier's own assertion path, required to fail. That distinction is not academic for this rule: the violation survived for months precisely because "at least one slot is valid" keeps the database opening, so a verifier that could not fail would have looked identical to one that worked. rules_with_mutant goes from four to five across the whole codebase, and the ratchet baseline is updated to hold it.

A second note records what the damage work established: the two halves of the pair are not interchangeable to a reader, since clobbering the current one leaves the database a generation back with CleanShutdown clear.

check-rule-scopes and audit-rule-coverage both pass, 0 blocking. Suite: 5119 passed, the same three pre-existing failures.
…an was built on

09 §1 concluded "the schema is not in the file" and drew three consequences from it: the tiering that says four checks need a schema assembly, G1's scope, and G5's existence. Two of its three rows are wrong.

The inference came from `DBD = new DatabaseDefinitions()`, which is a true statement about how the engine BOOTS and not about what the file RECORDS. Alongside the rebuilt runtime definitions the engine persists a self-describing manifest, and it was sitting in the bootstrap keys that same document lists: ComponentR1 carries CompSize, CompOverhead, FieldCount and the FieldR1 descriptors; ArchetypeR1 carries ComponentCount, ComponentNames in slot order, NextEntityKey, and the EntityMap, cluster and index segment roots. ComponentCount and NextEntityKey are the two values recorded as being nowhere.

Measured rather than inferred a second time. On a closed bundle, with no engine and no schema assembly: the bootstrap names the catalog segment, its stride is exactly sizeof(ComponentR1) — one row per chunk — and six rows decode whose ComponentSPI and VersionSPI all resolve to segments a physical sweep found by a completely independent route. The catalog contains its own definition, and that row's ComponentSPI is the segment it was read from. A decoder reading the wrong offsets would still produce integers; it would not produce that fixed point.

What it changes: G1's unfinished half is unnecessary, since ArchetypeR1 already carries component count and cluster identity, so [56,64) need not be claimed. MAP-01/02/03, CLU-01/02/05 and ALO-02 are not blocked on it. And Tier 2 may not exist as a tier — ComponentR1.Fields is field layout, which is the only thing IDX-03/04 and CLU-03/04 were said to need an assembly for, so G5 wants re-examining before it is built.

G1's stride half is untouched and turns out to be the keystone rather than one of two halves: the catalogs are themselves chunk-based segments, so none of the above is readable without the stride being on the page.

What is genuinely still un-decoded is narrower and mechanical: String64 and ComponentCollection<T> are handles into the string table and VSBS, so reading names and field descriptors needs those indirections walked. The row structure is proven; the variable-size payloads are the remaining work.

The test is kept as a guard rather than deleted. If a later change stops persisting the manifest, this is what says so — before seven cross-structure checks quietly start reporting nothing.
…ct two claims I made about how

Follows the §1 correction through to the values the checks actually need. The chain is bootstrap → the ComponentR1 catalog → the row named Typhon.Schema.Archetype → that row's segment → ArchetypeR1 rows, and out of them come ComponentCount, NextEntityKey, and the cluster, EntityMap and index segment roots. Every one of those SPIs is asserted to resolve against a segment list built by an independent physical sweep, so the decode is cross-checked rather than merely plausible.

Two things I said last commit were wrong.

String64 is not a handle into the string table. It is a `fixed byte[64]` of UTF-8 stored inline, and it decodes with no indirection at all — I had called ToString() where the accessor is AsString, got the type name back, and concluded there was a level of indirection to walk. There is not. Names now decode, and the archetype catalog is reached BY NAME rather than by a revision number that happened to be unique in this fixture.

And a real trap, found by the assertion rather than by reading: ArchetypeR1's persisted row is 108 bytes while the CLR struct is 112. The engine stores the component's own size; the CLR rounds the type up to the alignment of its widest field, and `long NextEntityKey` forces that to a multiple of 8. So MemoryMarshal.Read<ArchetypeR1> over a 108-byte chunk reads four bytes it does not own — the next row's, or past the page's raw-data area on the last chunk of a page, where it throws instead. ComponentR1 hides this completely: its 160 bytes already land on an 8-boundary, so stride and struct size agree, and a reader built and tested only against the component catalog works right up until it meets the archetype one. ReadRow<T> copies into a zero-filled buffer of the struct's size, which is the only form correct in both directions.

Also worth recording: Marshal.SizeOf is the wrong ruler here. MemoryMarshal.Read uses the managed layout, so Unsafe.SizeOf is what a reader must compare against.

What remains genuinely un-decoded is now only ComponentCollection<T> — the VSBS indirection behind ComponentR1.Fields and ArchetypeR1.ComponentNames. Neither is needed for ComponentCount or NextEntityKey, both of which are plain fields.
…ive that proves it survives a bad pointer

Moves the manifest decode out of a test and into Integrity/internals, where the checks can use it. SchemaCatalogReader walks bootstrap → the ComponentR1 catalog → the row named Typhon.Schema.Archetype → ArchetypeR1 rows, and hands back ComponentView (size, overhead, field count, component and revision segment roots) and ArchetypeView (component count, entity-key watermark, cluster, EntityMap and index segment roots).

The archetype catalog is found BY NAME in the component catalog rather than by a bootstrap key, because it does not have one — it is an ordinary component like any other, which is the same reason its rows are readable at all.

Every pointer is validated against the physical sweep before it is followed, and a row that fails keeps its other fields with the bad pointer zeroed. That is MAP-04's discipline applied one level above the entity maps: the catalogue calls it "a hard requirement on the traversal code, not merely a finding", and a manifest is nothing but pointers. A reader that gave up on the first bad row would leave every downstream check with nothing, which is the failure mode this feature exists to replace.

The damage primitive is the interesting half. RedirectCatalogSegmentPointer points one row's data-segment pointer at page 3 — inside the file, not a segment root, not the meta pair. An out-of-range pointer is easy to reject; an in-range pointer to the wrong page is what turns a scan into a crash or, worse, into confident nonsense about somebody else's segment. It re-stamps the page afterwards, so what the reader meets is a wrong pointer rather than a torn page; without that the scan would stop at a checksum failure and the test would pass while proving something else, exactly as the format-revision forgery had to avoid.

Three tests: a healthy database yields every component and archetype with no diagnostics; a redirected pointer is named in the diagnostics, dropped rather than followed, and costs neither the rest of the manifest nor the archetype catalog; a destroyed meta pair degrades to "nothing recovered, and here is why" instead of throwing.

Suite: 5157 passed. The three known pre-existing failures, plus Calibration_Reasonable, which passes alone in 197 ms and is a timing flake under full-suite load — the integrity module is offline-only and calibration never calls it. Gates all green.
The chain family reads inside chunks rather than around them, which is what nothing before this could do. Every field it touches — NextChunkId, ItemCount, EntityPK — is engine-defined; what it was missing was never the schema but the arithmetic to find the next chunk, and format revision 7 supplied it. The manifest reader supplies the other half: which segments hold revision chains at all.

CHN-02 gates on the clean-shutdown flag, per the measurement two commits back. RB-03 describes the collapsed shape as the SCRUB's postcondition and the scrub runs on the crash path, but an ordinary consolidating checkpoint leaves the same shape — so on a cleanly-closed file the check is sound, and on a crash-path file it would report a divergence on a perfectly healthy database. It declares itself skipped there rather than staying quiet.

CHN-03 separates "points at a freed chunk" from "points past the segment" from "the page could not be read", because they are different faults and only the first is a live hazard: a freed chunk can be handed to another chain at any moment, so the history beyond it is either gone or about to be overwritten by an unrelated entity's revisions.

CHN-04 bounds every walk by the segment's own capacity, so a cyclic chain produces a finding rather than a hung scanner on precisely the database somebody was trying to diagnose. The test asserts the scan COMPLETES, which is the part that would otherwise be discovered by a CI timeout.

Four tests, and the negative one is not a formality: a chain walker with an off-by-one in its chunk arithmetic reports plausible findings about every database it meets, and only a clean run over healthy data at Deep depth catches that. It also asserts the family was not skipped, since "no findings" and "never ran" render identically otherwise.

Two defects the kit caught in its own primitives, both of which would have made green tests that proved nothing.

The re-stamp helper forced the whole-page CRC form on every page. That is right for A/B protected pages, whose twin is what protects them from a torn write, and wrong for ordinary data pages, which carry per-sector footers since revision 6 — so the scan reported CHK-PHY-01 on top of the intended finding. AssertDetectedExactly caught it because it requires the code set to match in BOTH directions.

Then, with the form corrected, the byte-exactness assertion caught the next layer: a per-sector stamp writes footers growing down from the end of the metadata region, not a checksum at offset 8, so the declared range was wrong. RestampPage now diffs the page and reports what it actually changed, which is exact by construction and stays correct when the footer layout moves.

Suite 5162 passed, the same three pre-existing failures. Gates green.
…2, CLU-05

The cluster family is what the §1 correction bought. A cluster's entity keys live at 8 + 8·componentCount from the chunk base, and componentCount is the value 09 §1 recorded as being nowhere in the file — it is in ArchetypeR1. With it, CLU-01, CLU-02 and CLU-05 read a cluster's engine-defined prefix without a schema assembly and without walking the ComponentNames collection.

CLU-02 and CLU-05 are the pair that would have caught #697, and RB-06 says why they matter more than they look: an allocator restored below its own population hands out an identifier a live entity already holds, and the collision is silent because both sides are individually well-formed.

Two things I had wrong, both caught by running the checks rather than by reading.

The cluster slot array holds packed EntityIds — routing id in the low 16 bits, entity key above — while NextEntityKey counts only the key. Comparing the raw value against the watermark reported every entity in a healthy database as over the limit. And both watermarks are inclusive: NextFreeTSN and NextEntityKey record the LAST value issued, not the next one free, so the comparison is strictly-greater and a live entity holding exactly the watermark is the ordinary resting state.

Then the G0 crash fixtures caught the larger one. Every watermark comparison is only meaningful after a clean close. RB-05 is explicit that BK_NextFreeTSN is refreshed ONLY on clean shutdown and that recovery recomputes the resumption floor from three terms — so on a crash-path file the persisted value is stale by design and lags every revision the WAL window still holds. Unguarded, ALO-01, ALO-02, CHN-05 and CLU-05 reported a fatal allocator fault on a database behaving exactly as documented. All four now gate on the clean-shutdown flag and declare themselves skipped rather than staying quiet, the same shape CHN-02 already had. That gate has its own test.

ALO-01 is RB-05's third term as a check. The failure it prevents is silent, permanent, and leaves a database that passes everything else: a consolidating checkpoint can advance committed TSNs into the data file without leaving them in the WAL window, so a floor computed from the checkpoint and the replayed window alone lands below the newest consolidated revision, and every reader afterwards snapshots beneath it while MVCC hides the latest value.

Ten of the twenty-three checks now run. Suite 5167 passed, the same three pre-existing failures.
…d pointer, and reports it

Twelve of twenty-three checks now run. The entity-map walk decodes the meta record — which lives in chunk 0, the slot every other chunk-based segment reserves as its null sentinel — then the inline directory array, the overflow dir-index chain, and every bucket chain, bounding each walk and validating each chunk id before dereferencing it.

MAP-04's boundary is drawn where the evidence supports it and no further. An id the segment cannot contain, or a page that will not read, is damage and is reported. An id that is in range but whose chunk the bitmap marks free is a CAVEAT, because linear hashing splits incrementally and a published directory slot can legitimately name a chunk whose allocation has not caught up — observed on a healthy fixture, not theorised. What is not softened either way is following it: an unallocated chunk is never dereferenced, which is MAP-04's actual requirement and the reason RB-01 calls a torn hash directory a hard process crash rather than a wrong answer.

MAP-01 and MAP-02 are declared unrun rather than shipped. The idea that unblocked them is real — comparing the map's identities against the cluster's live entity keys answers both questions without needing the per-entry record size, which is not on disk — and MAP-01 comes out clean on healthy fixtures once the key encoding is right: the map keys on the bare entity key, not the packed EntityId, because the routing bits are constant within an archetype and are not stored. But MAP-02 does not: the bucket walk recovers a strict subset of a healthy map's entries, so the comparison would report live entities as unreachable. Bounding the scan by the live BucketCount from PackedMeta made it worse and removing the bound did not fix it, which points at the bucket entry layout rather than the directory walk.

MAP-01 is withheld alongside it deliberately. Forward-only checking passes trivially on a map that is missing half its entries — that is the classic mistake 03 §7 names — so shipping it alone would be the reassuring half of a pair whose other half is broken.

The damage fixture points a directory slot far past the segment's capacity rather than merely at a free chunk, so the case under test is unambiguous. The load-bearing assertion is that the scan completes, and that the finding says the pointer was not followed.

Suite 5170 passed, the same three pre-existing failures. Gates green.
… watermark

Two checks that need only what the manifest and the bootstrap already hand over, and both are about a claimed identity rather than about content.

IDX-01 is IX-02's failure shape stated at the segment level. A per-archetype index stores ClusterLocations — pointers into one archetype's cluster SoA — so two archetypes naming one tree means entries written by one decode against the other's cluster. RB-04's note is explicit that this is an access violation on first decode rather than a wrong row, which is why shared ownership is worth a check of its own rather than being left to whatever notices first. It also reports an index segment an archetype names but that does not exist; both are lossless, since an index is derived from cluster data.

ALO-03 compares NextLsn against the checkpoint LSN. Only that half: the stronger form — above every LSN present in the log — needs the WAL's records walked, which is WAL-02's territory and is not decoded here. The half that is checked is the one whose violation is unrecoverable, because a watermark below the checkpoint means the next record appended takes a sequence number the data file has already consolidated past, and recovery cannot order the two.

Both are asserted clean against healthy databases and neither has a positive damage fixture yet — forging an ArchetypeR1 row's index pointer is a different primitive from the ones the kit has, and I would rather say that than imply coverage the tests do not have.

The remaining IDX checks declare themselves unrun: key order, high-key bounds, sibling links, height and entry-to-field agreement all need the B+Tree node layout decoded, which is separate work and is not guessed at here.

Fourteen of twenty-three checks now run. Suite 5168 passed with the three known pre-existing failures plus two that pass in isolation — Transient_SpawnDestroy_Throughput and OutputPhase_ContinuousSpawn — both timing-sensitive and in the repository's known full-suite flake band; the integrity module is offline-only and neither test invokes it.
…bug that broke the EntityMap walk

The collection fields of the manifest were never followed, and they turn out to hold most of what the remaining checks were waiting for. ComponentR1.Fields is a ComponentCollection<FieldR1> and ArchetypeR1.ComponentNames a ComponentCollection<String64>, so field offsets, field types, per-field index roots, per-archetype component membership and each component's storage mode are all one buffer-id hop away. VsbsReader follows that hop offline: chunk chain through NextChunkId, elements after the wider root header in the first chunk and after the 8-byte header in the rest, sizes taken from the engine's own structs rather than written as literals. Collection segments are pooled by stride, so a buffer id alone names nothing — the element type picks the stride and the stride picks the segment, and a stride claimed by two segments is reported rather than resolved to whichever came first.

That closes G5. The four Tier 2 checks it existed to unlock — IDX-03, IDX-04, CLU-03, CLU-04 — need no schema assembly and no new CLI surface, because FieldR1 carries OffsetInComponentStorage, SizeInComponentStorage, Type and IndexSPI. It is the same correction as 09 §1.1 one level deeper, and the habit that would have prevented both is to grep for a quantity's R1 before concluding it is absent.

SchemaCatalogAgreementTests is the discipline rather than the feature: it compares the decoded field descriptors against the runtime definitions they were written from, value by value, not by count. A decoder that finds the right number of fields at the wrong offsets satisfies a count assertion and then reads every component's bytes from the wrong place. It passed first run, which is the argument for asking the engine instead of inferring from struct declarations.

With the manifest deeper, the EntityMap's value size becomes derivable: RecordSize = 19 + 4 x versionedSlotCount, and the Versioned count comes from the archetype's component list crossed with each component's storage mode. That gives bucket capacity, and with it where a bucket's key array ends and its value records begin.

But the walk was broken by something else entirely, and it was not the bucket layout it was blamed on for two rounds. ChunkCursor returned a span over one reused page buffer, and the walk nests three deep: reading a bucket on another page rewrote the directory the outer loop was still iterating. 27 of 256 buckets were visited and four keys of sixty-four came back, which reads exactly like a layout problem. The cursor now copies into caller-owned buffers, one per nesting level, and the walk recovers all 64.

Nothing else had the defect — ChainChecks and ClusterChecks are flat walks that never hold a chunk across another read — but the aliasing was invisible to every existing assertion, so EveryLiveEntityIsFoundInTheMap counts against a known population from outside the walk. MAP-01 passes trivially on a subset, MAP-03 passes because fewer entries cannot collide, MAP-04 passes because no pointer was bad.

MAP-01 now checks what the catalogue states rather than a weaker set comparison: an entry can name a real entity and still point at another entity's slot, and only comparing the location sees it. ClusterChecks publishes where each live entity sits so it can.

The three D5 cluster fixtures now declare MAP codes alongside their CLU ones. That is not drift: every one of those mutations changes which identities the cluster holds without editing the map, so the two structures genuinely disagree afterwards and the checks say so.
…ure walked

Both catch a database where every individual structure is well-formed, which is the class of damage this feature exists for and the class a per-structure walk cannot reach by construction.

CHN-06 asks whether anything still references each revision chain. The entity record's tail is one compRevFirstChunkId per Versioned slot, in the archetype's component order, so the EntityMap is the authority on which chains are still owned. A root carrying a live owning entity key that no record points at is storage nothing reads and nothing frees: recovery cannot reclaim a chain it cannot reach, so the space is held for the lifetime of the database. Reported as reclaimable rather than as loss, because the entity's data is intact and it is the reference that is gone.

CLU-04 corroborates the archetype's ComponentCount against its component-name list. Those are two independently persisted records of the same fact, and the fact is not a description of the cluster layout but the layout itself: the count fixes the width of the per-component enabled-bit words and therefore the offset of the entity-key array and of everything behind it. Reading a cluster through the wrong one returns another component's bytes as this one's without failing, which is why it reports Fatal rather than as a divergence.

Both live in their own pass rather than in the families they draw on, because of an ordering constraint that would otherwise fail silently. CHN-06 compares two sets that the chain pass and the map pass each fill half of, so running it inside either reports the unfilled half as damage.

OrphanRevisionChain is the fixture, and the shape it produces is the argument for the check: four bytes cleared in the value half of a bucket leave the chain still well-formed and still owning its entity, the entity still live and still in the map, and only the reference between them gone. TheStrandedChainIsInvisibleToTheChainAndMapFamilies asserts that explicitly rather than leaving it implied, so a future change that made CHN-03 or MAP-02 notice would show up instead of quietly making CHN-06 redundant.

The primitive could not have been written before the manifest read the VSBS: its offset arithmetic needs the bucket's key/value split, which needs the entity-record size, which needs the archetype's Versioned component count.
A ComponentCollection field is a four-byte buffer id and nothing else, so the correctness of collection storage rests entirely on those handles resolving and on every allocated buffer still being named by one. The alpha plan called this the one cheap, high-value fix for #389.

The two directions are not two views of one thing and the check treats them differently. A handle that does not resolve is data loss: a collection is primary data with no derived copy to rebuild from, so it reports NotRepairable with a Collection loss estimate. A buffer nothing references loses nothing at all and is never reclaimed, which is #389's actual shape, and reports as a lossless divergence.

The reverse half stands down whenever a user component declares a collection or variable-length string field, because those handles live in per-entity component data this build does not decode. Reporting under that condition would call every legitimate user buffer a leak, and a report that cries wolf on healthy databases trains its reader to ignore it. The system catalogs are excluded from that test by name rather than by heuristic — their handles are exactly the ones the forward half follows, so counting them would stand the check down on every database.

Resolving a handle means walking its chunk chain, not reading its root header. A buffer id that addresses a freed chunk, or whose chain does not terminate, fails at the walk; taking the root on trust would accept both. TryWalkChunkIds does that without decoding elements, which matters because accounting for buffers cannot depend on knowing an element type the scan may never learn.

BreakCollectionHandle supplies both fixtures from the same four bytes. The dangling case turned out to produce two findings rather than one, and both are correct: redirecting a handle names storage that does not exist AND abandons the buffer that used to be named. The test asserts both, because asserting only the first would let a check that missed the second look right.
…e-component fixture was hiding

An index segment's chunk 0 is a tree directory — a BTreeDirectoryHeader then one BTreeDirectoryEntry per registered tree — which is what makes an index enumerable offline at all. Without it there is no way to tell a root node from any other allocated chunk.

IDX-06 checks what the node prefix can answer without knowing the key width. All four node layouts share the same 20 bytes (Control, OlcVersion, PrevChunk, NextChunk, LeftValue) and diverge immediately after, because the high key is 2, 4, 8 or 64 bytes wide and shifts the value and key arrays with it. Which variant a tree uses follows from the indexed field's type, and reading a node through the wrong one yields keys that decode perfectly and mean nothing. So the checks are: every sibling link resolves to an allocated chunk, no chain revisits a node, no node claims more entries than any layout of its stride could hold, and the directory does not claim more trees than its chunk can carry. IDX-02/03/04/05/07 declare themselves unrun with that reason stated rather than guessing at a width.

The directory also answers #657 directly. A tree's identity in a shared segment is the pair (StableId, Slot), and StableId alone is not unique because field ids restart at 0 for every component — two components in one archetype that each index their field #0 both register as 0. When that pair repeats, lookup returns the first match for both and one component's index silently resolves the other's entities.

The capacity bound is deliberately the loosest one that is still sound. A tighter, variant-specific bound would report healthy nodes of a wider-keyed tree as over-full, and a false positive on a correct database is worse than letting a subtly-wrong count through.

The fixture had to change to prove any of it. The default schema declares no indexed field, so an index segment never exists in it and every IDX check quietly skipped — which reads in a report exactly like a check that passed. BuildIndexedDatabase uses the #661 schema, which indexes both a String64 and an int and therefore carries two roots with different node strides.

Running against it immediately produced three CHK-CLU-01 findings on a healthy database, with entity keys like 12592 — ASCII "01", read out of a String64 field. A cluster does not always hold 64 slots: ArchetypeClusterInfo picks a ClusterSize to fit the stride, and the entity-id array is exactly that many longs, so slot 63 of a 48-slot cluster is the middle of the first component's data rather than an empty slot. The CompA fixture is single-component and never exposed it.

The occupancy word bounds the scan soundly without needing ClusterSize itself: FullMask keeps bits at or above ClusterSize clear, so if slot k is occupied then slots 0..k all exist. Occupied slots are always safe to read; free ones only below the highest occupied slot. Slots above it are skipped because this scan cannot yet tell whether they exist, which is a different statement from them being uninteresting.
… entries actually say

Which of the four node layouts a tree uses is decided at construction from field.Type, so the same mapping recovers it offline — and the field a tree indexes is identified by its directory entry's StableId, which is the field id, resolved through the archetype's component list at the entry's Slot. Every link in that chain is persisted. IndexNodeLayout takes its offsets from Marshal.OffsetOf against the engine's own IndexNNChunk types rather than recomputing them, so a field moving inside one of those moves this reader with it.

Two things about key comparison that a hand-rolled version would get wrong. Keys are stored raw, in the key type's own order — OrderedKeyEncoding exists for the K-way merge and is not what lands on disk — so comparing two stored keys routes through the engine's encoder, which is a strictly monotonic map onto long and is all an order check needs. Unsigned biasing and the float sign-flip come from there rather than being reimplemented; getting either wrong makes a correct index look unsorted around zero, which is an entirely convincing false report.

And entries are not stored from position 0. A node keeps Start and Count and wraps, so reading the array in physical order returns a rotated sequence that looks exactly like a key-order violation on a perfectly ordered node.

IDX-05 fired on every key of a healthy database on its first run. Internal-node keys are separators copied up from the leaves below them, so counting them finds every key twice — uniqueness is a leaf property and is now only asserted there.

IDX-02 checks IX-02's shape at entry granularity: an entry whose packed ClusterLocation names a slot the occupancy word marks free. RB-04 records that decoding one of those is an access violation rather than a wrong row, so this is not a stale result, it is a read of memory belonging to nothing. Restricted to per-archetype cluster index segments, since only their values are ClusterLocations, and skipped for multi-value fields whose entries hold a VSBS buffer id instead — that is IDX-07's territory.

The damage fixture failed open before it worked, and the way it failed is worth recording. It scanned the segment for any leaf, but an archetype index segment hosts the primary-key tree alongside the field ones, and a PK node read through an int layout is written at an offset belonging to nothing. The scan came back Sound with the tree under test untouched. It now descends the chosen tree's own leftmost path, which is still a different traversal from the level-by-level walk the check uses — a fixture sharing its subject's traversal cannot catch a defect in it.

Both modes leave the tree structurally perfect, so IDX-06 sees nothing. That separation is deliberate: structure and contents fail independently, and an index whose shape is flawless can still answer every query wrongly.
…dex against the data it indexes

09 §1.1 listed "cluster size and component count" as recovered by ArchetypeR1. Only the second is true — the row carries ComponentCount and no ClusterSize. That generalisation is the same shape as the error it was correcting: one fact checked, a neighbouring one assumed.

It does not need to be persisted, because it is a pure function of things that are. SelectClusterSize takes a fixed header size and a per-entity size, and both come out of the manifest: the header from ComponentCount, the per-entity size from ComponentR1's component sizes plus four bytes per AllowMultiple indexed field in FieldR1. ClusterLayoutReader calls the engine's own selector with reconstructed arguments rather than reimplementing its scoring loop — the arguments are what has to be recovered; the algorithm is already in the assembly.

Two agreement tests, because the derivation has two halves that fail differently. The sweep proves the arithmetic across 6 component counts x 18 sizes x 3 multi-field counts, with sizes varied WITHIN each archetype so a derivation that summed wrongly but symmetrically cannot pass. The bundle test proves the inputs are recovered correctly from disk, which is the half a manifest-decode bug would break while the arithmetic stayed perfect. The check also refuses to proceed when the derived stride disagrees with the persisted one — a re-derivation that drifts is worse than none.

That unblocks IDX-03 and IDX-04, and closes what remained of G5's justification. Both directions are required and shipping only the forward one is the classic mistake: forward-only checking passes completely on an index missing half its entries, which is exactly what a rebuild over pre-apply state produces. IDX-04 is what catches it.

The walk had a decode bug that only a healthy database could reveal. A B+Tree node holds N keys and N+1 children — Values[i] is the subtree to the RIGHT of key i, and the leftmost child lives in its own LeftValue field. Reading only the value array misses the leftmost subtree at every level, which is not a partial walk but one that omits an exponentially growing share of the tree. It surfaced as IDX-04 reporting live entities as missing from a perfectly good index, and it would have been invisible against damaged data.

Both damage fixtures now declare a second code, and both are true rather than incidental. Rewriting a key breaks the node's order and makes that entry disagree with the value the entity holds. Repointing a value makes the entry name a free slot and leaves the entity it used to name with no entry at all — the reverse-direction finding, arriving from a mutation that never touched the reverse direction.
…chain head

A Versioned component is stored twice on purpose — the revision chain holds the authoritative history, the cluster holds a copy of the current value so a read costs one cache line instead of a chain walk. RB-03 lists "cluster HEAD equals chain HEAD" as a postcondition and nothing at runtime re-checks it, which is exactly the situation an offline scanner exists for.

Reading the chain head needed one more layout fact: a component chunk's overhead sits at the FRONT, so the value starts at CompOverhead, and both that and CompSize are on the ComponentR1 row. The head element is the chain root's element at FirstItemIndex, which CHN-02 already established is the only element after a consolidating checkpoint. Gated on a clean shutdown for the same reason CHN-02 is: on a crash-path file the head has not been consolidated yet, and any disagreement would be recovery's remaining work rather than damage.

The finding names the chain as authoritative rather than reporting a symmetric disagreement. That is what makes it actionable: the repair rewrites the cluster from the chain, losslessly, and an operator handed two plausible values with no stated direction has a puzzle rather than a fix.

It first ran and compared nothing. The cluster stores a packed EntityId while a chain header's EntityPK may be either form, so the join matched no entity, every slot fell into the caveat path, and the check reported success over an empty comparison — a scan that looked like it ran and had verified nothing. It now tries both encodings, and declares itself skipped when a component's join produces zero comparisons, because comparing nothing and agreeing are indistinguishable in a report unless one of them says so.

ChunkSource copies rather than aliasing a shared page: two are live at once, a chain chunk and the value chunk it points at, and they can land on the same page. That is the same defect that broke the EntityMap walk, avoided by construction this time rather than after two rounds of debugging.

D5(DuplicateKey) now declares CLU-03 alongside its other codes, and it is the sharpest of the three: the second slot claims the first entity's identity while still holding its own component data, so its copy is measured against a chain that was never its own.
…ting what blocked them

IDX-07 was declared unrun because a multi-value entry's buffer element type "is not recorded per index". That was wrong twice over. The element type is always int, a packed ClusterLocation, and the buffer lives in the index segment itself rather than a pooled component-collection segment — L64MultipleNodeStorage builds it as VariableSizedBufferSegment<int> over the tree's own segment. A dangling buffer id is the more dangerous half of the check: every entity filed under that key becomes unreachable at once, not one row but the whole bucket, and the node stays structurally perfect so nothing else sees it.

WAL-02 closes G7, and finding it took the same mistake this branch has now made four times. The first attempt walked the WalChunkHeader format from the start of the data region, found nothing on any database, and reported success — the identical shape to CLU-03's empty join. The two framings are nested: a segment is a run of WalFrameHeader frames, and each frame contains CRC-bearing chunks. Measured on a real segment, a frame of length 120 at byte 4096 holds one 104-byte chunk at 4112, and 16 + 104 is the frame length. So the catalogue's "CRC chain per drain block" is real, one level in from where it was looked for.

Two further false positives on healthy databases shaped the final form, and both are about the same distinction. A frame running past the end of the FILE is a truncation by construction — there is nothing after it that could tell corruption from a partial append — so it is always a tail. And bytes left over that are too few to encode a chunk are alignment padding, not a break: the CompA fixture happens to tile exactly and the indexed one does not, which is how treating it as damage came to fire on a healthy database.

The torn-tail negative is the test that matters most here. An unverifiable chunk at the end of an append-only log is what a crash mid-append leaves, and recovery already handles it by stopping at the last chunk that verifies. A check that reported it would put a finding on every crash-recovered database in existence — this feature's own failure mode reached from the opposite direction.

The positive fixture has to extend the log before breaking it. The writer coalesces a whole drain into one frame holding one chunk, and a checkpoint drops everything before it, so a fixture-sized database produces a log with exactly one frame and one chunk however the writes are batched — a log that cannot express "a break before the tail" at all. Copying the final frame gives the walk something real to reach past the break, and a byte-for-byte duplicate parses and verifies exactly as the original does.
…pening actually does

DatabaseRepair.Apply has always taken a regenerateDerived callback and nothing ever supplied one, so any plan containing a RegenerateDerivedStructures step threw when applied. That is worse than the step being unimplemented: the plan is rendered for an operator as a list of what will happen, and they consented to a step the tool could not perform. RepairCommand now passes DerivedStructureRegeneration.Run, which opens the bundle, lets the engine's rebuild net run, checkpoints and closes cleanly.

The callback registers no component type, deliberately. If regeneration needed the schema assembly it would fail on exactly the forensic case the feature exists for — a database recovered on a machine that never ran the application.

Then the round-trip test asked whether repair-by-opening is sound, and the answer is not yet. A plain open-and-close of a HEALTHY database, with no damage anywhere, leaves it Unopenable: CHK-WAL-04 Fatal (a segment missing from the middle of the log) plus CHK-SEG-02 (36 pages claimed by a segment while the bitmap calls them free). Identical with and without ForceCheckpoint, so it is the cycle itself rather than checkpoint behaviour. Filed as #771 with the narrowing, because I cannot tell yet whether the reopen path is wrong or whether two shipped checks are wrong about a legitimate post-reopen state, and which it is changes the fix completely.

That blocks G3's acceptance criterion rather than merely delaying it: a repair that heals its target and hands back a Fatal finding the database did not have before has not repaired anything, it has traded one report for another.

Separately, CLU-03 is not healed by an open-and-close at all. G3's design says to wire RebuildClusterFromChains to a per-page damage trigger, and a plain open arms no such trigger — so that half of the increment is untouched engine work rather than something the callback reaches.

The tests stay written and Ignored against #771 rather than deleted. They are the reproducer, and the question they ask is G3's precondition: does opening a database change it. Deleting them would leave that question unasked the next time someone reaches for this approach.

Also fixes a TypeScript regression from G10: adding blockedReason to RepairPlanDto made a Record-to-DTO cast in integrityModel.test.ts non-overlapping, which broke the Workbench build and with it the Shell's.
Two bugs, and the check shipped with no test at all, which is how neither was noticed.

The first: contiguity was asserted over consecutive segment ids across every file present. Measured on a healthy database, after one open the log holds id 1 covering LSNs 1-128 plus a pre-allocated spare; after a second open it holds id 1, id 3 starting at LSN 129, and a new spare. There was never an id 2 — the spare is promoted with a fresh id and the counter has moved on. So the sequence jumps by design, and the check reported Fatal on any database that had been opened twice.

What recovery actually needs is that the LSNs form an unbroken run: it replays forward and stops at the first sequence number it cannot find. Segment 1 ending at 128 and segment 3 beginning at 129 is contiguous in the sense that matters, whatever the file names say. WAL-04 now compares LSN coverage, bounded to the replayable window — records below the checkpoint are already in the data file, so segments entirely under it may legally be absent, and with no checkpoint recorded the whole log is the window.

The second bug fell out of the first. A segment's last LSN is not in its header, so the fix has to walk the frames, and doing that revealed the frame walk was advancing by FrameLength. Frames are not densely packed: a real segment holds eight 120-byte frames at exactly 4096, 8192, 12288 and so on, because IWalFileIO.WriteAligned requires 4096-aligned offsets and lengths for O_DIRECT and each drain takes a whole block. Advancing by FrameLength reads the padding after frame 0 as an unwritten block and stops, so WAL-02 was inspecting one frame out of eight and passing. Both walks now advance by drain block, which is the fifth time this session a decoder aimed at the wrong offset produced a check that looked like it passed.

Three test cases, because either direction alone is satisfiable by a wrong check: a segment retired below the checkpoint is not a hole, a segment whose first LSN skips past the previous one's coverage is Fatal, and the no-checkpoint boundary where every segment is replayable.

The positive case synthesises its gap rather than deleting a file. The engine reclaims segments as soon as their records are checkpointed, so a fixture-sized database keeps exactly one written segment however many times it is reopened — there is never an interior one to remove, and filling three segments without checkpointing is millions of records. The fixture copies the real segment with its id and first LSN advanced past the original's coverage, recomputing the header CRC the way the reader verifies it, so what the scan meets is a well-formed segment that simply begins too late.

An open-and-close cycle now leaves a healthy database Divergent rather than Unopenable. #771 is retitled and narrowed to the SEG-02 half, which is still undiscriminated between an engine defect and a check that is wrong about a legitimate post-reopen state.
The only conflict was coverage/rule-coverage.md, which is generated by scripts/audit-rule-coverage.py and carries a "do not hand-edit" banner, so it was resolved by re-running the generator over the merged tree rather than by merging its text. The totals are the union of both sides: 198 rules against a common base of 192, main contributing five from the OLC work and this branch contributing IR-01.

Main's B+Tree changes are behavioural and touch no field of the Index*Chunk structs, so the offline node readers this branch adds decode the same layout as before. Integrity suite is 123 passed, 0 failed, 7 skipped against #771 — unchanged by the merge.
@nockawa
nockawa merged commit 12eaa44 into main Aug 11, 2026
11 checks passed
@nockawa
nockawa deleted the feature/750-integrity-gap branch August 11, 2026 00:29
nockawa added a commit that referenced this pull request Aug 11, 2026
…est engine test sat unrun (#775)

The gate filters the Workbench suite on tools/Typhon.Workbench/** only, so the heaviest page-cache/B+Tree stress case — which lives there — never ran on an engine merge. #765 and #769 executed it zero times; #772 ran it only by touching an SPA file. A green gate was reporting on a test it had skipped.

Moved into Typhon.Engine.Tests and quarantined against #774: reliably red on the gate box, 2 of 2, green locally. shard.py's retry net now covers the Workbench suite too, without softening any verdict.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Integrity G0 — settle OQ-6a: can a crash-poisoned EntityMap reach disk before RB-04's loud-fail?

1 participant