#3051·LiteDB

Split #3025 + #3027 into reviewable compatibility, recovery, and durability PRs

Author: JKamskerCreated Sep 29, 2026Updated Sep 29, 2026

Goal

Replace the overlapping work in #3025 and #3027 with 10 focused implementation/test PRs, plus one separately reviewable slot-reuse optimization if it can be extracted cleanly. Preserve the final fixes, historical compatibility, regression evidence and review history—not the chronological sequence of superseded implementations.

This is an extraction/integration plan, not a new engine redesign or a merge-safety sign-off. The proposed boundaries must be validated on the actual extracted trees. Do not force the numbered split by introducing an unsafe intermediate protocol.

Rechecked source snapshots — 2026-09-29

Source Pinned head Reported scope
#3025 — legacy validation, recovery, released-file corpus, rebuild ownership ad48da8a25181e3555366b4e1b2ba2538cfb63fb, JKamsker/LiteDB:codex/fix-3022-release-compatibility 21 commits; 48 changed files; +2,137 / −64
#3027 — IO regressions, WAL/recovery, durability/failure policy, proofs 3d136a46f2e7f19bb32a93cf4b90a44e79360d2b, claude/compassionate-knuth-m52zj6 198 commits; 246 changed files; +24,548 / −947
Current upstream dev checked for this plan 5dd942a7367c361fadd600be4ce10aace2768b27 Includes #3045 safety-evidence infrastructure

The source metadata, changed-file inventories, relevant patches and review discussions were re-read for this plan. No extracted branches were built or tested as part of writing this issue.

Do not carry the previous four #3027 findings forward as still-unfixed blockers. The latest response describes their fixes and reports 15/15 regression proofs passing. Preserve and rerun that evidence after extraction; the original run does not certify a different tree.

Key fixes to retain:

  • Encrypted partial-header recovery: 659784920, with its encrypted-sector and stale-generation discriminators.
  • Possibly-written confirmation outcomes: ad3382f6a and 0ce00ee55; a successful truncation in the current file view alone does not establish NotCommitted.
  • Outstanding header journal / promotion ordering: ae3f68bee4, db394db6f4, and the corresponding permanent tests/proof.
  • Fifteen known-bad/candidate registrations in the pinned proof manifest.

1. Proposed PRs and actual base-branch targets

S01–S11 are planning IDs, not GitHub issue/PR numbers. Replace the implementation-link column when PRs exist. Branch names below are proposed names.

ID Branch / scope Initial PR base Implementation
S01 split/01-release-corpus — released-database corpus/tooling dev TBD
S02 split/02-unix-mutex-names — Unix shared mutex name length dev TBD
S03 split/03-rebuild-ownership — rebuild admission/ownership split/02-unix-mutex-names TBD
S04 split/04-legacy-salvage — legacy validation + safe opening recovery/salvage split/03-rebuild-ownership TBD
S05 split/05-vector-compatibility — legacy vector/index metadata dev TBD
S06 split/06-legacy-wal — legacy WAL validation and drain-or-refuse dev TBD
S07 split/07-caller-streams — stream-constructor/lifetime/open semantics dev TBD
S08 split/08-wal-write-atomicity — WAL and transaction failure containment dev TBD
S09 split/09-durability-protocol — coherent WAL durability/recovery protocol split/08-wal-write-atomicity TBD
S10 split/10-readonly-continuation — post-failure continuation and acknowledged-only view split/09-durability-protocol TBD
S11 split/11-witness-slot-reuse — optional removal of redundant slot-reuse sync split/09-durability-protocol TBD
current dev
├── S01 released corpus/tooling
├── S02 Unix mutex names
│   └── S03 rebuild ownership
│       └── S04 legacy validation + salvage
├── S05 vector/index compatibility
├── S06 legacy WAL conversion
├── S07 caller-stream semantics
└── S08 WAL/transaction failure containment
    └── S09 durability + recovery protocol
        ├── S10 read-only continuation + acknowledged-only view
        └── S11 witness-based slot-reuse optimization [optional extraction]

The tree shows primary review bases, not every integration prerequisite. S01 supplies shared compatibility tooling. Before final validation/merge of S09, integrate the earlier opening/migration/stream work—particularly S04, S06 and S07—and the other landed roots. Rebase S08/S09 onto that updated dev; do not quietly copy sibling changes into S09's diff. S10 must also be tested with the S03/S04 ownership/opening behavior.

After a parent merges, retarget/rebase its child onto current dev and rerun the affected evidence. A PR has one base; secondary dependencies must be explicitly integrated, not represented as fictitious multiple GitHub bases.

Staging the branches and expensive experiments in JKamsker/LiteDB is reasonable. Keep its dev synchronized with upstream and use the same branch names within the chosen review repository. Do not specify an upstream base branch that only exists in the fork. Upstream roots ultimately target litedb-org/LiteDB:dev.

2. Per-PR scope, ownership and acceptance criteria

S01 — Released database corpus and compatibility tooling

Source: #3025. Contract: historical fixtures and their expected contents have independently reproducible provenance.

Own tools/ReleaseCompatibility/Corpus.cs, Writer/*, artifacts-revision.txt, corpus generation/download/validation infrastructure, and the corresponding CI scaffolding/documentation. Preserve the immutable released corpus revision: 56 plain/encrypted fixtures from the 22 stable v5 and six stable v4 writers described in #3025.

Keep producer package/assembly/database hashes, historical runtime/globalization information, generator recipes and exact expected documents. Preserve originals and test mutation on copies. Retain the bounded build timeout and meaningful timeout diagnostics.

Extraction caveat: Current/Program.cs and Current/DamagedFile.cs are not merely infrastructure: they assert opening, upgrade and salvage behavior. Move their fix-dependent assertions/CI activation with S04 or the appropriate consumer. Do not make this supposedly test-only PR green by weakening expected payloads, tolerating arbitrary rejection, or silently skipping broken fixtures. If the whole corpus cannot pass before an engine fix, land the independently useful scaffold first and account explicitly for the later activation.

Acceptance: fixture inventory/hashes validate; historical writers independently reopen their outputs; each activated case actually executes. The completed stack runs Linux/ICU, macOS/ICU, Windows/ICU and Windows/NLS coverage with the original exact-data/index/write/rollback/reopen checks.

S02 — Unix shared mutex name-length compatibility

Source: #3027, beginning with 01831c79f. Contract: valid long/non-ASCII paths do not overflow the runtime's mutex-name limit.

Own SharedMutexNameFactory.cs, SharedMutexNameLength_Tests, the Unix test attribute where first needed, and Issue_3027_SharedMutexNameLength with its proof/configuration entries.

Acceptance: exercise a real shared open on Unix, verify the boundary at which hashing applies, deterministic names, and unchanged names on paths/platforms not affected by the fix. Test relevant cultures. This is not a general path-alias/locking-identity redesign.

S03 — Exclusive rebuild ownership and admission

Source: #3025 / #3035, including bd95a2ae, ce6d67f98, 7bbb32fc8, 9a6c1be63, ad48da8a.

Contract: ownership spans source acquisition, replacement construction, install/rollback and reopened-engine handoff. An opener must not pass a marker check and later resume against replaced files with stale metadata.

Own RebuildAdmission.cs, RebuildSource.cs, ownership-related hunks of RebuildService.cs, Engine/Rebuild.cs, LiteEngine.cs, EngineSettings.cs, and relevant factory/disposal changes. Include RebuildOwnership*, RebuildAdmissionPlatform_Tests, install/rollback tests and the independent-process harness.

Acceptance: force competing opens before the marker, during installation and through handoff; assert exact original/candidate/backup data and WAL, acknowledged concurrent writes and successful later writes. Cover repeated owner death, bounded admission, unsupported locking, cleanup failure, plain/encrypted files and Direct/Shared/Coordinated interactions on Windows/Unix.

Keep ordinary Direct opens available when named mutexes are genuinely unsupported, while rebuild/upgrade/recovery remain protected. Do not swallow permission or actual I/O failures as platform limitations. Preserve the durable incomplete-installation marker. Retain documented path/older-binary limitations rather than promising universal alias coordination.

Do not add the proposed live/online rebuild redesign here. Transfer the #3035 completion link to this PR when it exists.

S04 — Legacy validation, safe opening recovery and partial-document salvage

Source: #3025 / #3022 plus #3027's damaged-document work.

Contract: classify a legacy opening failure correctly, preserve rejected inputs, and recover the readable data through one bounded, ownership-protected recovery path.

Own CollationValidation, LegacyFileException, LegacyIndexComparison, relevant index-migration diagnostics, EnginePragmas' early LIMIT_SIZE/collation-stamp interpretation, Engine/Recovery.cs, recovery/error types, and salvage hunks of FileReaderV7/V8, IFileReader, RebuildService, LiteEngine and EngineState.

Keep corruption versus incompatible ordering distinct, preserve useful collection/page/address details, and retain real read-only inspection semantics. Combine #3025's safe close/reopen protocol with #3027's complete-documents-first salvage, unique/duplicate handling, rejected-part _id handling, _rebuild_errors identification of retained partial documents and preservation of the original rebuild cause.

Important semantic conflict—not a mechanical merge: #3025 closes a source rejected by opening validation without checkpointing/marking it, whereas #3027 uses _markedForRebuild for its constructor retry and retains Default_open_reports_the_damage_and_only_marks_the_file_for_rebuild in its proof guard list. See the pinned #3025 opening path and #3027 opening path.

Proposed resolution: validation-only refusal preserves both source files; eligible writable AutoRebuild starts recovery explicitly, without needing to mark-and-retry first. Keep runtime corruption marking distinct. Record this choice and its coverage-ledger disposition; adapt the conflicting marking assertion into an equally strong source-preservation assertion instead of deleting it without replacement. Do not accidentally preserve two independent AutoRebuild retry mechanisms.

Acceptance: cover both an already-invalid header and newly detected migration/validation damage; exactly bounded recovery; no automatic replacement from explicit read-only opens, internally read-only continuations or caller streams; stop replacement on cleanup error; failed candidate reopen does not poison the fresh file or trigger a rebuild loop. Preserve WAL-only inserts/updates/deletes and all intact documents before salvaging partial ones. Verify exact diagnostic identities, duplicate/unique behavior, subsequent writes and cold reopen.

Include Issue3022*, affected Issue2417/Issue2812Recovery/Issue2812CollationStamp cases, LegacyDamagedDocument_Tests, damaged fixtures/generators and Issue_3027_LegacyDamagedDocument. Transfer #3022 completion here.

S05 — Legacy vector/index metadata compatibility

Source: #3027, final behavior of cf92a407d, 0c0df7b85, a6af38881 and associated tests.

Contract: stale bytes left by a released v5 DropIndex are not treated as live vector metadata; supported prerelease vector representations still receive their declared read/migrate/reject behavior.

Own CollectionPage.cs and related metadata decoding/validation hunks, LegacyDroppedIndex_Tests, PrereleaseVectorFile_Tests, DropIndex_5_0_21.zip, the prerelease fixture/generator/provenance and Issue_3027_LegacyDroppedIndex.

Acceptance: real v5 drop layouts remain writable with exact records and indexes after migration, crash/reopen and subsequent writes. Cover malformed or mismatched vector metadata, real prerelease input and preserved ordinary indexes. Run the salvage interaction on the integrated S04+S05 tree; put any shared diagnostic helper in a declared prerequisite rather than duplicating it.

Do not resurrect the earlier superseded marker/header-byte designs by cherry-picking the initial implementation alone.

S06 — Legacy WAL validation and complete conversion drain

Source: #3027's legacy WAL fixes.

Contract: a legacy WAL is validated and completely drained before destructive conversion, or the operation refuses without modifying the source.

Own structural validation/drain hunks in DiskService.FileVersion, initialization/validation/trailing-page handling, WalChecksum and the legacy restore/checkpoint path. Include LegacyWalSharedMigration, LegacyWalTornTail, LegacyWalPageBound, ConvertedWalBesideLegacyHeader tests; relevant plain/encrypted crash/foreign/concurrent-WAL fixtures and generators; and both legacy-WAL proofs.

Acceptance: blocked/unreadable reader registries leave data and WAL byte-identical and can recover after unblocking; validate committed page type, page-ID bounds, committed-header bounds and available database-identity evidence; reject converted/foreign WALs safely; handle torn tails and concurrent legacy allocation layouts without rejecting valid histories. Verify exact WAL-only transaction effects and cold reopen.

Boundary: structural conversion safety goes here; the new policy for unavailable syncs, overwrite barriers, header-frame generation and durable cleanup goes into S09. Keep the existing conservative refusal until that protocol is available. Do not claim the ambiguous legacy ownership cases in #3043 are solved.

S07 — Caller-stream constructor, lifetime and opening semantics

Source: #3027.

Contract: caller-owned streams keep their documented lifetime and opening semantics; inspection does not mutate them or persist unrelated settings.

Own LiteDatabase(Stream) disposal/checkpoint behavior, CheckpointEachCommit/ReadOnlyStorage settings and associated open-time fallback hunks. Include StreamDatabaseDispose, LegacyReadOnlyStream, ReadOnlyStorageEngine tests and the two stream proofs.

Acceptance: double dispose; disposal with an open transaction; rollback/release; no persisted CHECKPOINT=1; caller ownership retained; no log/header marking/repair from a non-writable inspection path; explicit no-op transactions remain supported where promised. Preserve caller settings when taking an internal read-only copy. Cover current/legacy streams and migration crash images.

Not here: buffered-stream flush/failure handoff is S08; continuation after a live engine's write failure is S10; broader custom-stream durability promises remain #3044.

S08 — WAL write and transaction failure containment

Source: #3027.

Contract: after a potentially torn WAL write or failed safepoint, no later acknowledged transaction is appended/published behind an unsafe state; a reader-triggered buffered write failure reaches the writer.

Own torn append/slot-rewrite handling, failure publication before releasing the writer, pending-buffer ownership/handoff in ConcurrentStream/HeldWrites, rollback-only transaction state, and pinned $dump/$page_list slot handling. Include the final batch-flush and post-recorded-failure guards (063c832898, 4662fe49f4), not just the superseded per-page flush workaround.

Own TornWalAppend, TornSlotRewrite, SharedBufferedLogStream, CallerStreamFlushCost, FailedSafepointWrite, DumpPinnedWalSlot and the relevant checkpoint/promotion failure-window assertions. Allocate the three matching proofs below.

Acceptance: deterministic waiting writer and reader interleavings; all relevant exception types; original failure retained when cleanup also fails; no read/write access to a rollback-only transaction; subsequent commit cannot publish a partial safepoint; exact previously acknowledged state after cold reopen; pinned versions remain readable.

Terminal engine stop is an acceptable explicitly documented intermediate failure behavior here. It must not continue writing. Preserve the later read-only-continuation assertions under S10, with a tracked split of assertions—not a deleted/skipped regression. If a black-box repro bundles both contracts, separate the assertions or move the minimal required dependency forward before calling the layer independently proven.

S09 — Coherent WAL durability and recovery protocol

Source: #3027. Base: S08, rebased with the earlier opening/migration work integrated.

Contract: durable acknowledgments have a recoverable generation; in-place writes and destructive WAL cleanup are ordered behind the required durable evidence.

Keep these together:

  • DiskService.DataWrites accounting and checks before log shrink, slot clearing, journal/legacy-backup removal; include the final salt/header publication barrier.
  • Header frame in every non-volatile WAL generation; old no-header-frame compatibility; header-journal precedence; generation/salt checks; engine and rebuild-reader support; refusal to initialize over a live/unreadable WAL.
  • Plain and encrypted partial-header reconstruction, including the ciphertext-blank-sector fix and wrong-password/stale-generation rejection.
  • Overwrite barriers for checkpoints, legacy conversion and compact/index promotion in both commit modes; retain journals and WAL when durability is unavailable.
  • Header write-back before retiring the journal after a failed sync (e4b9553fd), distinct from the wider #3048 residual.
  • Failure publication/recheck under the writer lock: a promotion that waited on a failed checkpoint must perform no further write or sync.

Tighten the earlier suggested boundary: fail-loud durable-commit admission, actual commit-sync error handling, required failure recording/stop state, bounded WAL retention (wal limit, default 1 GiB), and the diagnostics needed to explain refusal belong in this PR wherever the protocol relies on them. They are not merely UI features to defer to S10. Keep unsupported-sync and actual I/O failures distinct; state any existing unverified-sync exception explicitly.

Likewise, wherever LiteDB.CommitOutcome is introduced, ship the final written-confirmation logic with it: only a provable abort is NotCommitted; a possibly published confirmation is Unknown unless its removal is durably established. Include WrittenConfirmation_Tests, including failed/unreportable cleanup syncs and non-I/O exceptions. Do not publish the earlier incorrect classification as an intermediate API.

Own the corresponding DiskService.*, `