Skip to content

#729 Database integrity: check, report and repair - #736

Merged
nockawa merged 7 commits into
mainfrom
feature/db-repair
Aug 10, 2026
Merged

nockawa merged 7 commits into
mainfrom
feature/db-repair

Conversation

@nockawa

@nockawa nockawa commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Implements the full Integrity design series — all six phases in the planned order. Closes #730, #731, #732, #733, #734, #735.

The problem

Typhon already repairs damaged databases. Module RB is a real, rule-governed, tested recovery net. What it cannot do is say anything: it runs only at open, only on the crash path, cannot be invoked, and reports into log lines. Its outcome is binary — the database opens, or it throws.

So the engine can silently repair a database and the operator learns nothing, or refuse to open one and the operator learns nothing useful either. This adds the missing half.

$ typhon check game.typhon --depth deep

  game.typhon · format v6 · 4,318 pages (33.7 MiB) · checkpoint LSN 31,613
  clean shutdown: yes

  VERDICT: SOUND                     no findings

  LIMITS OF THIS SCAN
    This scan verifies that the database is INTERNALLY CONSISTENT. It cannot verify that the
    database matches what was committed…

  4,318 pages scanned · 82 segments · 4,221 pages with per-sector verification · 69 ms

It found a real bug on its first run

Against a healthy database.

SavePages — the structural ChangeSet flush — guards its checksum stamping on FilePageIndex > 0. The write was not guarded. A flush carrying logical page 0 overwrote meta slot 0 with an image whose stored checksum no longer matched its content.

The meta pair exists so a torn write can never destroy the only copy of the root metadata. Half of it was being destroyed on ordinary shutdowns. Nothing complained — the surviving slot still opened the database, and every structure was individually well-formed. It would have surfaced only later, as a permanently unopenable database after a second, unrelated tear. That is exactly what CK-05 exists to prevent.

CollectDirtyMemPageIndices had the IsExternallyPersisted exclusion all along; SavePages is fed by a ChangeSet rather than that scan, so it never applied. Fixed by extending the partition that already existed there for CK-05 directory pages. Regression: MetaPairStructuralFlushTests.

This is the argument for the feature, made by the feature: a [silent] violation no amount of internal consistency checking could notice.

What's in it

Offline scanner — reads a .typhon bundle as bytes. No engine, no lock, no replay. Not a preference: booting the engine destroys the evidence (the rebuild net re-derives the structures you wanted to inspect before you get a handle), cannot reach the case that most justifies a checker, and mutates. Every pointer is range-checked before it is followed; there is a test that overwrites the entire data file with random bytes and requires a verdict rather than an exception.

Segment discovery is physical, not bootstrap-driven — a root page says so in its own header, so the sweep finds every segment without trusting a dictionary that may itself be damaged. The trap is that an A/B twin is a byte copy of its primary, root flag included; the discriminator is self-reference, since a segment's directory names its own root as entry 0 and a twin's copy still names the primary.

20 checks across BOO / PHY / SEG / WAL, each naming the rules/ invariant it enforces.

Report — findings carry a locus in every applicable addressing scheme, a severity, a confidence (a live scan sees a consistent page but never a consistent database, so its cross-structure conclusions are Suspected and repair never acts on them), and a loss estimate that never reports 0 when the answer is unknown. Text + JSON; the verdict is the exit code so it drops into cron or CI unparsed.

Every report carries a limits block, including a fully green one. That is the point of it: a recovery gap that discarded a committed update leaves a database that passes every check, because it is self-consistent — merely stale.

Repair — plan → consent → act. The plan is a file, not a flag: it records a fingerprint of the exact state it was built for, and applying re-scans and refuses on drift. The lossless repairs are implemented (restore a degraded pair slot from its verified sibling; re-derive the allocation bitmap). Findings whose data is genuinely gone are reported under Unaddressed with the escalation stated, never silently dropped — excising rows from a damaged page needs the archetype layout, and guessing is what the design forbids.

Format revision 6 — one checksum over 8192 bytes becomes sixteen over 512-byte sectors, each with a currency stamp. Zero added bytes (the space was already reserved and already CRC-covered) and the checksum path gets faster:

granularity ns/page
8192 B, 1 chain (before) 602.5
16 × 512 B (shipped) 459.9

−23.7 %, because a single 8 KiB chain is latency-bound on crc32's 3-cycle latency while 16 independent chains are not.

The generation stamp is what a checksum alone cannot do: a torn write leaves a valid image of the previous generation, so its CRC passes and only currency distinguishes it. The rule takes the maximum across the header and every sector — comparing each sector against the header inverts when sector 0 is the part that failed to persist, condemning the one sector that landed and accepting every stale one. There is a test for exactly that.

Verify on open — Spine tier, on by default. The clean-shutdown flag records that the last process closed properly, not that the bytes survived. A fatal finding refuses the open with the report attached; lesser findings open and log.

Surfaces — typhon check, typhon repair; POST /api/integrity/{scan,plan,apply}, path-based rather than session-based because a scan must work on a database that will not open and a repair needs exclusive access.

Deviations from the design

Recorded in 08 §4 rather than silently absorbed.

  1. The Workbench decode layer was not moved into the engine. The design's premise was wrong about it: StorageMapService walks in-memory engine structures on a live healthy database, not disk bytes. Moving it would have produced a walker that crashes on the databases the scanner exists to diagnose. Written fresh instead; the Workbench is untouched and becomes a consumer.
  2. Cross-structure checks (CHN/CLU/IDX/MAP/ALO) deferred — they need offline schema decode. Named in the report's ChecksSkipped.
  3. Class B excision planned but not executed — same schema dependency; acting on a guess is forbidden.

Testing

36 new tests. Full suite 5,106 passed / 5 failed — the same 5 that fail on unmodified main, baselined 3× before and after (known ~1-in-3 flake band, #720). Release build clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_017CWY311fU31yKmmkEkPWaM

@nockawa

nockawa commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

🔴 Not merge-ready — one open CI failure

Typhon.Workbench.Tests…Stress_Config_Completes_Without_Backpressure_Timeout fails on aws-gate-selfhosted:

System.InvalidOperationException: B+Tree insert made no progress in 10000 pessimistic retries.
The descent keeps reaching a leaf it can neither validate nor modify … (see #695)

What's established

Gate green on main the same day runs 31287494290 (01:03), 31285348301 (00:03)
Fails on this branch deterministically 3 consecutive gate runs, identical message
Passes locally in Release 5 consecutive runs, 2–3 s each
Not the known flake band (#720) a flake does not repeat 3/3 on one named test

So it is a regression from this branch until proven otherwise, and it is environment-sensitive.

One real bug of exactly the right shape was found — and it wasn't enough

The per-sector footer and the chunk-occupancy bitmap share a page's metadata region. The first implementation had the base logical segment stamp a default of 16 sectors at page init and the chunk-based subclass narrow it right after. That window is not empty: CreateOrGrow unlatches each new page while it is still dirty — the surrounding code already documents and defends that race — so a checkpoint landing in it persists the page while it still claims 16 sectors, writing CRC values through the bitmap of any segment whose stride needs more than 24 bytes of it.

It fails silently: bits flipped under the chunk allocator, chunks handed out twice. The downstream symptom is precisely a B+Tree descent reaching a leaf it can neither validate nor modify.

Fixed in ae5f621d (MetadataReservedBytes virtual, consulted at page init so the geometry is never wrong even transiently) with a decisive regression test — neutering the override makes strides 8/16/24/32 fail with the offsets spelled out. The gate still failed afterwards, so the fix is necessary and not sufficient.

Bisect: prepared, never ran

A probe forcing every page back onto the whole-page checksum — isolating the format change from everything else — was pushed as 1e01d87f. The self-hosted runner went to queued and stayed there for 45 minutes, so it produced no signal. Reverted in 4e682cb6 to leave the branch in its intended state.

To resume: re-add if (…) return 0; at the top of PageSectorFooter.ChooseSectorCount and re-run the gate.

  • green ⟹ the per-sector format change is implicated
  • red ⟹ the cause is one of: SavePages's externally-persisted exclusion, verify-on-open, or the FilePageIndex stamp — and the next split is between those three

Full write-up in 08 §7a.

Everything else is green: engine suite 5,113 passed / 5 pre-existing failures, Workbench suite 606 passed, Release build clean, both doc gates pass.

Typhon repairs damaged databases already — module RB is a real, rule-governed, tested recovery net. What it cannot do is say anything. It runs only at open, only on the crash path, cannot be invoked, and reports into log lines; its outcome is binary, the database opens or it throws. So the engine can silently repair a database and the operator learns nothing, or refuse to open one and the operator learns nothing useful either. This adds the missing half: an instrument that says what is wrong, what a repair would cost, and what it could not have seen.

The scanner reads a .typhon bundle as bytes with no engine, no lock, no replay. That is not a preference. Booting the engine to inspect a database destroys the evidence (the rebuild net clears and re-derives the very structures you wanted to look at before you get a handle), cannot reach the case that most justifies a checker (an open that fails loudly leaves nothing to ask questions through), and mutates. Every pointer is range-checked before it is followed and every walk is bounded, because a checker that crashes on the databases it exists to diagnose is worse than useless — there is a test that overwrites the whole data file with random bytes and requires a verdict rather than an exception.

Segment discovery is physical rather than bootstrap-driven: a root page says so in its own header, so a full sweep finds every segment without trusting a dictionary that may itself be damaged. The bootstrap's pointers become a claim to verify instead of the source of truth. The one trap is A/B protection — a directory twin is a byte copy of its primary, root flag included — and the discriminator is self-reference, since a segment's directory names its own root as entry 0 and a twin's copy still names the primary.

Twenty checks across four families, each naming the rules/ invariant it enforces. Findings carry a locus in every addressing scheme that applies, a severity, a confidence (a live scan sees a consistent page but never a consistent database, so its cross-structure conclusions are Suspected and repair never acts on them), and a loss estimate that never reports zero when the answer is unknown. Every report carries a limits block stating what the scan could not have detected, including on a fully green one — that is the point of it, since a recovery gap that discarded a committed update leaves a database that passes every check because it is self-consistent, merely stale.

Repair is plan, consent, act. The plan is a file, not a flag: it records a fingerprint of the exact state it was built for, and applying re-scans and refuses on drift, because repairing against a stale diagnosis is how a repair tool damages a healthy database. The lossless repairs are implemented — restoring the unusable half of a protected page pair from its verified sibling, and re-deriving the allocation bitmap from the reachability walk, which matters most in the phantom direction where a free bit over a live page would eventually let the allocator hand it to a second owner. Findings whose data is genuinely gone are reported under Unaddressed with the escalation stated, never silently dropped: excising rows from a damaged page needs the archetype layout, and guessing at it is exactly what the design forbids.

Format revision 6 replaces one checksum over 8192 bytes with sixteen over 512-byte sectors, each paired with a currency stamp. It costs zero added bytes — the space is already inside the page and already CRC-covered — and the checksum path gets faster, 602.5ns to 459.9ns per page measured on Zen 4, because a single 8KiB CRC chain is latency-bound on the crc32 instruction's three-cycle latency while sixteen independent chains are not. The generation stamp is what the checksum alone cannot do: a torn write leaves a valid image of the previous generation whose CRC passes, so only currency distinguishes it. The rule takes the maximum across the header and every sector, because comparing each sector against the header inverts when sector 0 is the part that failed to persist — it would condemn the one sector that landed and accept every stale one.

Open-time verification runs the spine tier by default. The clean-shutdown flag records that the last process closed properly, not that the bytes survived, so damage that happened while a database was closed was previously served in silence. The tier is bounded by segment count rather than database size and catches the structurally-broken class, which is where opening anyway does the most harm. A fatal finding refuses the open with the report attached; lesser findings open and log, because a database with a divergent index is still a working database.

typhon check and typhon repair carry the verdict in their exit code so they drop into cron or a CI gate unparsed. The Workbench gets scan, plan and apply endpoints, deliberately path-based rather than session-based since a scan must work on a database that will not open and a repair needs exclusive access.

The scanner found a real bug on its first run against a healthy database. SavePages, the structural ChangeSet flush, guards its checksum stamping on FilePageIndex greater than zero but did not guard the write, so a flush carrying logical page 0 overwrote meta slot 0 with a stale checksum. The pair silently degraded to a single copy on ordinary shutdowns — the exact precondition CK-05 exists to make impossible — and would have surfaced only as a permanently unopenable database after a second, unrelated tear. CollectDirtyMemPageIndices had the exclusion all along; SavePages is fed by a ChangeSet rather than that scan, so it never applied. Fixed by extending the partition that already existed there for directory pages.

Thirty-six new tests. Full suite: 5106 passed, 5 failed, the same five that fail on unmodified main, baselined three times before and after.
The per-sector footer and the chunk-occupancy bitmap share a page's metadata region, the bitmap growing up from its start and the footer down from its end. Which of the two gets how much depends on the segment's stride, and only the chunk-based subclass knows that — so the first version had the base logical segment stamp a default of 16 sectors at page init and the subclass narrow it immediately afterwards.

That window is not empty. CreateOrGrow unlatches each new page while it is still dirty, which is exactly the race the surrounding code already documents and defends against with EnsureDirtyAtLeast; a checkpoint landing in it persists the page while it still claims 16 sectors, putting the footer at [96,192) and writing CRC values straight through the bitmap of any segment whose stride needs more than 24 bytes of it. Stride 16 loses 32 bytes of bitmap, stride 8 loses everything.

Nothing about that fails loudly. It silently flips bits under the chunk allocator, which then hands out chunks it has already given away or loses them entirely, and the damage surfaces much later and somewhere else — in this case as a B+Tree descent reaching a leaf it can neither validate nor modify, on the CI runner, reproducibly, in a test that passes on every machine with fewer cores.

The fix moves the decision to where it can be made once and correctly: MetadataReservedBytes is a virtual on LogicalSegment that ChunkBasedSegment overrides, and InitHeader consults it. A page therefore never declares a geometry its bitmap cannot accommodate, not even transiently. The subclass's post-hoc re-declaration is removed rather than kept as belt-and-braces — leaving it in would have masked exactly the signal the new test looks for.

SectorGeometryDeclarationTests asserts the invariant on real pages across six strides after both Create and Grow, and separately that stamping a page leaves its bitmap byte-identical. Neutering the override makes the first four cases fail with the offsets spelled out.
Temporary. Neutralises the per-sector write-path change while leaving the scanner, the repair pipeline, the surfaces and verify-on-open in place, so the gate answers whether the aws-gate B+Tree liveness failure comes from the format change or from something else in this branch. To be reverted either way.
The self-hosted runner never picked the job up, so the probe produced no signal. Removing it leaves the branch in its intended state; the report records how to re-arm it.
merge-gate.yml was the only workflow in the repo with no timeout-minutes anywhere, and it is the one that runs on the persistent c6id. With no cap it inherited GitHub's 360-minute default, so a gate that hung held a billed box for six hours; today one ran 55 minutes and was only stopped because someone happened to be looking at it. Every other workflow was already capped, which is what made this one stand out.

The suite is 2-3 minutes healthy and 5 is already abnormal, so the self-hosted gate step gets 10 minutes and the job 15. The step budget is deliberately below the job budget: the step dies first, which leaves the if: always() report and artifact steps free to run, so the .trx says where it hung. A job-level cap alone kills everything and leaves no evidence of why.

The ephemeral paths had the same exposure by a different route — sky launch holds the VM for exactly as long as the step runs — so aws-gate, coverage and benchmark are capped too, the last generously since a z1d.metal profile run is legitimately long.

A second hole came out of the same look: sky launch --down only tears the cluster down on a normal exit. A step timeout or a cancelled run kills sky mid-flight and strands the instance, billing with nothing watching it, so capping the job alone would have converted a hung job into an orphaned VM. All three ephemeral jobs now run sky down under if: always(), which no-ops when the cluster is already gone.
…t costs

Spine verification is on by default at every database open, and it was documented — and asserted in the PR — as bounded by segment count rather than database size. It was not. Scan called DiscoverStructure at every depth, whose first pass reads every page in the file, so each open performed a full-file read. On the 105-page databases the engine tests build this is invisible; on the gate's 4,318-page fixtures, across thousands of opens, it is the difference between a three-minute suite and one that had not finished in fifty-five.

That is precisely the tax the design refused when it rejected a full sweep at open, so this is the feature contradicting its own stated contract rather than merely being slow. Spine now reaches segments through the bootstrap's own pointers and walks only those directories. It gives up what the physical sweep buys — a segment the bootstrap has forgotten is invisible to it — and that trade is the point of the tier: Spine answers whether the database can be traversed at all, which is worth asking on every open, while whether every page is accounted for is worth asking when someone asks it.

The test that existed to prevent exactly this passed throughout. It asserted Totals.PagesScanned == 0, but that counter is only incremented by the later checksum sweep, so it measured something unrelated to the claim and made a serious performance defect look guarded. The replacement counts pages actually read, at the IPageSource boundary where the cost is incurred, and a second test pins the scaling property directly by comparing a small database against one eight times its size. Restoring the old behaviour makes them fail with 224 reads growing to 1,696 as the file grows from 105 to 841 pages, so they are demonstrably decisive rather than merely present.

The lesson is narrow and worth keeping: when the claim is about cost, assert at the boundary where the cost is paid.
The API shipped complete and exercised but had no way in from the UI. This adds one, and deviates from 06-surfaces §3 on where it lives.

That doc names Storage Health the primary host. It cannot be. DockHost mounts only when a session exists and every storage panel keys on sessionId, so a view hosted there is reachable only while the database is open — which excludes the Unopenable verdict, a database another process holds, and the moment after the session is closed to give repair its exclusive access. Those are the three cases the feature exists for. So Integrity is its own path-scoped view with two homes: a dockview panel when a session exists, full-bleed over the Welcome screen when one does not, same component either way. Storage Health keeps the doc's intent as a Spine-tier verdict strip that links into it, and the File Map gets the integrity lens as designed. The entry point sits in the File menu rather than View because it acts on a file, not on the current session; filing the recovery tool under View puts it behind the thing that is broken.

The design's two non-negotiables are enforced structurally rather than by convention. LimitsBlock has no collapse control, no defaultOpen and no prop that hides it, and renders immediately above the action bar at every stage so it is the last thing read before deciding to act. LossManifest renders every entry, virtualized rather than capped, because a cap would turn "here is everything you are about to lose" into "here is some of it" silently; the row count is printed so a reader can verify nothing was dropped between the server and the screen. The repair flow is a panel, not a modal — a dialog that scrolls internally trains the eye to reach past its content for the button underneath.

Exclusive access is enforced the buildable way. The design routes it through the cooperative lock handoff, which is still Status: Designed and unbuilt, so the UI detects that the session holds the target path, blocks Repair and offers to close the session. The server independently returns 409 on a held lock, so the UI enforces a rule it does not have to be trusted with.

Scan is a mutation rather than a query despite being read-only and idempotent. As a query the library decides when it runs — on mount, on focus, on reconnect — and a refetch behind the operator's back would silently invalidate a plan they were mid-way through reading. The store drops the plan and any consent whenever a new scan or a retarget lands, so plan staleness is caught before the operator invests attention in it and again by the server's fingerprint check.

One shared-code fix: FetchError read only RFC 7807 title/detail, but five controllers across 19 call sites return a bare {error}, so every one of those messages collapsed to "HTTP 409" at the client boundary — the caller saw a status code where the server had written a sentence explaining what to do about it.

Tests: 19 vitest over the model's normalisation and the store's invalidation rules, the panel enrolled in the AC2.11 conformance suite, and 5 Playwright cases driven over deliberately damaged databases via a new DEBUG-only fixture endpoint. Without that endpoint the canary could only assert the green path, which is the one outcome whose regression matters least. The dry-run case hashes the data file either side and asserts byte-equality; without that, "dry run" is a label on a button.

Deferred: per-finding-code consent, which 05 §3 specifies but DatabaseRepair.Apply cannot express — it takes a single bool, and per-code checkboxes over a boolean API would be theatre.
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 P1 — offline bundle scanner (page walk, classification, CRC sweep)

1 participant