Skip to content

A plain open-and-close of a healthy database leaves 36 pages claimed-by-segment but free in the bitmap (SEG-02) #771

Closed

Description

@nockawa

Summary

Build a database, close it cleanly, scan → Sound. Reopen it, do nothing, close it cleanly, scan → Divergent.

▲ Divergence CHK-SEG-02   36 pages are claimed by a segment but the allocation bitmap says they are free.
                          Pages 69, 70, 71, 72, 73, 74, 75, 76, … (+28 more)

No damage is applied anywhere. The only thing between the two scans is an open and a close.

Scope narrowed. This originally also reported CHK-WAL-04 Fatal on the same cycle. That half was a check bug and is fixed on feature/750-integrity-gap — see the comment below. What remains is SEG-02, where I still cannot say whether the engine or the check is wrong.

Why it matters

It blocks G3 (#755), which repairs derived structures by opening the database and letting the engine's rebuild net run. That is only sound if opening is not itself a change the scanner objects to. Right now every such repair heals its target and hands back a database carrying a finding it did not have before.

SEG-02 describes this direction as the dangerous one: the allocator believes those 36 pages are available and could hand one to a second owner, at which point two structures write over each other.

Narrowed

Identical with and without ForceCheckpoint() before the close, so it is the open/close cycle itself:

Cycle Result
build → scan Sound, 0 findings
reopen + InitializeArchetypes + ForceCheckpoint → close → scan SEG-02
reopen + InitializeArchetypes → close → scan SEG-02 — identical

Reproducer: RegenerationSideEffectTests on feature/750-integrity-gap. AnOpenAndCloseCycleLeavesAHealthyDatabaseSound is the plain statement; WhichHalfOfTheCycleIntroducesFindings(bool checkpoint) is the narrowing.

Two candidate causes, still undiscriminated

(a) The engine's reopen path is wrong — it allocates pages for rebuilt structures, publishes the segment directory that claims them, and does not publish the matching occupancy bits. That would be a durability-ordering defect with a live-page-reuse consequence.

(b) The check is wrong about a legitimate post-reopen state — e.g. pages reserved for a segment but not yet considered allocated until first written, which the bitmap catches up with later.

The WAL half of this issue turned out to be (b), which is weak evidence for (b) here too — but only weak. The SEG-02 direction is genuinely dangerous if it is (a), and unlike the WAL check, SEG-02 does have test coverage that passes on freshly-built databases.

Suggested first step

Identify what owns pages 69+ after the reopen. If they belong to a segment the rebuild created, the question is whether the occupancy write is ordered after the directory write, or lost. If they belong to a segment that existed before the reopen, the question is different and the check is more likely the culprit.

Not the flake band

Deterministic, every run, both configurations. Distinct from #720.

Activity

  1. added theissue type on Aug 10, 2026
  2. updated Area Durability, Estimate M, Product Engine and Priority P1-High on Aug 10, 2026
  3. changed the title [-]A plain open-and-close of a healthy database leaves it Unopenable by the scanner (WAL-04 Fatal + SEG-02)[/-] [+]A plain open-and-close of a healthy database leaves 36 pages claimed-by-segment but free in the bitmap (SEG-02)[/+] on Aug 10, 2026
  4. nockawa commented on Aug 10, 2026

    @nockawa
    CollaboratorAuthor

    The WAL-04 half was a check bug — fixed on feature/750-integrity-gap

    Two things were wrong with CHK-WAL-04, and it shipped with no test at all, which is how neither was noticed.

    1. It checked segment ids for contiguity, and ids are not dense

    if (previousId != long.MinValue && h.SegmentId > previousId + 1)   // WalChecks.cs

    Measured on a healthy database:

    after build    id=1 firstLsn=1        + one unused spare
    after reopen   id=1 firstLsn=1, id=3 firstLsn=129   + a new spare
    

    There was never an id 2. The pre-allocated spare is promoted with a fresh id and the counter has moved on, so the sequence jumps by design. The check read that as a hole and reported Fatal on any database 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 starting 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).

    2. A second bug this exposed, in WAL-02

    A segment's last LSN is not in its header, so the fix has to walk the frames — and doing that revealed that the frame walk was advancing by FrameLength. Frames are not densely packed:

    file 0000000000000001.wal
       data [4096..4216)  len=120
       data [8192..8312)  len=120
       data [12288..12408) len=120        … eight frames, all at 4 KiB boundaries
    

    IWalFileIO.WriteAligned requires 4096-aligned offsets and lengths (the O_DIRECT constraint), so each drain occupies a whole block and the next frame starts at the next boundary. 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.

    Coverage

    WalWindowContiguityTests, three cases, because either direction alone is satisfiable by a wrong check:

    • a segment retired below the checkpoint is not a hole — the repro from this issue
    • a segment whose first LSN skips past the previous one's coverage is Fatal
    • the no-checkpoint boundary, where the whole log is the window

    The positive case synthesises its gap rather than deleting a file, and the reason is worth recording: 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.

    What this leaves

    The open-and-close cycle now produces Divergent rather than Unopenable — the Fatal is gone, SEG-02 remains. The issue is retitled to match.

    It is also weak evidence for cause (b) on the SEG-02 half, since the WAL half turned out to be a check that was confidently wrong about a layout it had never been tested against. Weak, though: SEG-02 does have coverage that passes on freshly-built databases, so it is not untested in the same way.

  5. added 2 commits that reference this issue on Aug 11, 2026
  6. nockawa commented on Aug 11, 2026

    @nockawa
    CollaboratorAuthor

    Root-caused. It is (a) — an engine defect. SEG-02 is correct.

    Raised to P0: this is silent data corruption on any open that does not register the full schema, and it invalidates G3's design rather than merely blocking it.

    The census settles the direction

    The issue's suggested first step was "identify what owns pages 69+". The answer is that nothing added pages — the reopen cleared bits over pages that were already claimed:

                      BEFORE     AFTER     DELTA
    PageCount            105       105         0     file did not grow
    PagesScanned         105       105         0     no new pages
    SegmentsWalked        16        16         0     no segment created
    CheckpointLsn        128       128               the ForceCheckpoint was a no-op
    PagesAllocated       105        69       -36     ← 36 bits CLEARED
    

    69 + 36 = 105, so the bitmap now marks pages 0–68 allocated and 69–104 free — a contiguous truncation, not a scatter.

    The re-derive ran, on a cleanly-closed database

    WalFilesPresentAtOpen                  True    ← after a CLEAN shutdown
    LastOpenOccupancyRederiveWordsChanged  1
    

    One 64-bit word covers pages 64–127, so "36 bits cleared" and "1 word changed" are one event. RederiveOccupancyOnCrash — whose doc comment says "Crash-path only", and whose call site claims "a clean reopen (recycled WAL) skips it entirely" — ran anyway, because WalFilesPresentAtOpen is true whenever WAL files exist, which a clean shutdown does not preclude.

    The clinching experiment

    Same database, same reopen, one variable — whether the caller registers CompA before InitializeArchetypes:

    reopen registers schema PagesAllocated rederive words changed verdict
    no 105 → 69 (−36) 1 CHK-SEG-02
    yes 105 → 105 (0) 0 Sound

    Mechanism

    The file holds 16 segments. A reopen with no component types registers 12, all ending at page 68. BuildOwnedPageBitmap derives owned from MMF.RegisteredSegments, so the other 4 segments' 36 pages are attributed to nobody — and CK-09 adopts the result wholesale (BitmapL3.OverwriteFromDerived, "a full replacement, NOT a read-then-diff"), so those live pages are marked free.

    Why only 12 register:

    foreach (var meta in ArchetypeRegistry.GetAllArchetypes())      // the CODE registry
        var hasPersisted = TryGetPersistedArchetype(meta, out var persisted);

    The reopen loop iterates registered CLR archetypes and looks the persisted record up by them. A persisted archetype with no registered type is never visited, so its segments are never loaded.

    The rule and the code disagree

    CK-09 states owned "depends only on persisted segment directories" and that the operation is "idempotent". Neither holds: it depends on what the caller registered. The persisted directory is intact and correct the whole time — nothing reads it. This is not a decision that metadata stops being authoritative under suspicion; it is the re-derive reading the derived source instead of the authoritative one.

    The consequence is CK-09's own on_violation, verbatim: "a clear bit over a live page double-allocates it (data corruption)."

    Two defects

    1. The gate does not mean "crash." WalFilesPresentAtOpen is true after a clean shutdown, so a crash-path-only routine runs on every clean reopen. Cheap to fix, and it is what makes the bug reachable here.
    2. owned is schema-dependent. This is the dangerous one: it fires on a genuine crash too, wherever the opening process does not register every persisted archetype.

    Impact on #755 (G3)

    This does not merely block G3, it invalidates its design. DerivedStructureRegeneration.Run deliberately registers no component type, so that repair works on a forensic machine that never ran the application — which is precisely the configuration that maximises the damage. "Repair by opening" would corrupt every database it touched.

    Fix shape

    Derive owned from the persisted segment directories, not from the in-memory registry. #750's offline SegmentWalker already enumerates all 16 segments from the file with no schema assembly whatsoever, which is the existence proof that the file is sufficient. _persistedArchetypes is already populated one loop earlier in the same method.

    Reproducer: RegenerationSideEffectTests (converted from a fixture-level [Ignore], which NUnit applies unconditionally — no --filter could reach it, so the bug's own reproducer could not be run) plus Seg02Probe, on feature/771-seg02-reopen.

  7. moved this to In Progress in Typhonon Aug 11, 2026
  8. added a commit that references this issue on Aug 11, 2026
  9. moved this from In Progress to Done in Typhonon Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    P0-Critical

    Estimate

    M

    Area

    Durability

    Start date

    None yet

    Target date

    None yet

    Bug status

    None yet

    Product

    Engine

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions