Make PR safety review and integrated regression audits explicit
Goal
Make LiteDB's existing safety guidance executable and repeatable: a locally correct PR must not silently invalidate previously supported storage, recovery, concurrency, compatibility, query, or API behavior.
The central question remains:
Which previously valid states, transitions, callers, and files can this change invalidate—and what evidence would detect that?
The strategy is not simply a longer checklist or more fuzzing. It is:
short PR declaration → affected contracts → discriminating tests → current integrated-tree evidence → bounded merge/release decision.
This issue establishes that process and its first working examples. It does not require completing every possible audit or replacing the current test infrastructure before it can close.
docs/rules/* remain the normative engineering guidance; #2988 remains the storage planning epic and #2623 the authoritative release-readiness tracker. Linking a roadmap or experiment here does not automatically make all of it a v6 blocker. Concrete newly confirmed release defects receive their own issues and release dispositions.
Existing building blocks: extend, do not duplicate
Baseline inspected for this refinement: dev at d2a1d9d0dd726c5f3342fb19e0b641d3b6137be3 (2026-09-28). This is an inventory, not a claim that all listed coverage currently passes or is sufficient.
- Data safety, validation, and compatibility already require risk-scaled evidence, independent oracles, forced interleavings, and repeated recovery testing.
- LiteDB.Fuzz already provides model-based targets, raw-file integrity checks, oracle self-tests, recorded input/replay, regression corpora, and bounded campaigns. REVIEW-AUDIT.md already maps review findings to executable evidence.
- Reusable CI already runs real-version compatibility scripts and separates production builds used by tools from hook-enabled test assemblies. Full CI already has a scheduled full matrix and failure reporting.
The missing connection is a maintained answer to: which contract is covered, under which assumptions, by which scenario, on which actual revision? Reuse these runners, manifests, reports and workflows before introducing another framework.
1. Keep the mandatory PR section small
Use five short prompts; link to deeper requirements rather than copying this whole issue into each PR:
## Safety / regression evidence
- Contracts and risk: what stays supported, what intentionally changes, and why?
- Prior states and interactions: which existing files, callers, modes, and neighboring mechanisms are affected?
- Failure outcomes: which transitions change, and what must happen on failure, retry, disposal, or reopen?
- Evidence: tests/oracles, proof the risky path ran, failing-before evidence where applicable, and tested revision/run.
- Coverage delta and residual concerns: tests removed/weakened/replaced, remaining gaps, and the strongest plausible counterexample.A documentation-only PR can give a brief justified non-applicability statement. A test-only PR changing a durability oracle, test selection, timeouts, skips, or corpus expectations is not automatically low risk.
Evidence scales with affected behavior, including indirect callers—not just the changed directory or lines of code. Use the existing levels in docs/rules/validation.md:
| Affected surface | Additional review focus |
|---|---|
| Local behavior | Boundary/error cases and affected callers |
| Shared query/mapper/serializer/index behavior | Independent expected semantics, cross-path comparisons, historical representations and public API behavior |
| Stateful/concurrent/ownership behavior | Forced interleavings, snapshots, progress, cleanup, repeated execution and process boundaries |
| Files/WAL/streams/sidecars | Failed and partial I/O, byte preservation, ownership, restart, exact committed contents and diagnostics |
| Upgrade/checkpoint/replacement/recovery protocols | Explicit state model, durable ordering, interruption of recovery itself, compatibility and allowed terminal states |
Path-based classification may suggest obligations, but must not silently downgrade a transitive storage/concurrency change. A changed risk classification must refresh the applicable evidence.
Account for old tests, not merely old test names
When removing, replacing, skipping, narrowing, repinning, or weakening coverage, identify the previous invariant and where it remains covered. Include CI filters/partitions, fixture generators, expected-error allowlists, timeouts and corpus hashes in this review.
A replacement may be stronger; old code need not remain forever. But a new test proving one property does not justify losing a separate property such as sustained-contention progress. Preserve both where necessary. Intentional behavior changes need an explicit compatibility decision, not an updated golden file alone.
2. Connect contracts to executable evidence
Maintain a small index of important invariants, using stable IDs or stable documentation anchors. Do not create a second competing specification or a hand-maintained list of every test.
Start with a few high-value families:
| Contract family | Typical executable evidence |
|---|---|
| Acknowledged durable transactions survive within the stated fault model | Independent operation/acknowledgment history, crash/persistence faults, exact cold-reopen state |
| Recovery never combines incompatible data/WAL generations | Install/rollback transition matrix, namespace/persistence faults, old/new/refused outcome checks |
| Readers retain their admitted snapshot across writes and reclamation | Multiple observed live generations, forced overlapping writes/checkpoints/reuse, full snapshot contents |
| Supported historical inputs preserve their documented behavior | Actual producer binaries/files, explicit read/migrate/reject outcomes, indexes and mutation lifecycle |
| Query and mapping paths preserve meaning | Independent model plus applicable indexed/unindexed, cached/uncached, generated/reflection or API/SQL comparisons |
For each identified risk in a PR, link a compact evidence row containing:
- contract/assumptions and relevant state transition;
- test/scenario and independent expected outcome;
- observed marker, counter, plan or fault boundary proving execution;
- command/run, actual source tree, test/harness revision, runtime/architecture and relevant storage configuration;
- result and any explicit gap or limitation.
Generate repetitive metadata from CI. Authors should link evidence, not manually paste pages of logs.
Record whether a test fails on the relevant broken revision. Where the current baseline no longer reproduces, name the versions and conditions attempted; do not manufacture a failing-before claim. A deliberately broken implementation variant can validate a guard, but is not proof that a reported historical regression occurred.
A broad green suite, a test count, or line coverage alone is not this evidence. Coverage must include the required semantic events: e.g. a real handoff, two live snapshots, an actual retired-slot reuse, an indexed plan, or the selected crash boundary.
3. Make the safety contract precise before adding tests
Model the lifecycle and simplify the protocol
For significant stateful changes, write down:
preconditions → admitted state → visible state → durable publication
→ failure/rollback → recovery/retry → cleanupDescribe the allowed outcomes at the affected boundaries. Include states created by a prior version and combinations produced by other recently merged features.
Review design alternatives before accumulating compensation branches: can a state be removed, publication delayed, recovery metadata retained longer, or a known-correct path kept while an optimization is isolated? A smaller protocol that can be checked convincingly is preferable to a larger protocol justified by increasingly elaborate local tests.
Small executable state-machine models are useful for difficult protocols, but introducing a formal-methods tool or rewriting the engine is not a prerequisite for this issue.
Distinguish failure models
Do not use the word “crash-safe” without identifying what was tested:
| Model | What the evidence must distinguish |
|---|---|
| Exception / failed API or I/O operation | Whether cleanup/unwinding ran; transient failure versus continued failure during rollback/recovery |
| Abrupt process or owner death | No graceful engine disposal; surviving processes/OS cache/locks and cold process re-entry |
| Modeled OS/power loss | Volatile versus durable state, lost/reordered/torn writes, file creation/rename/delete and directory-entry persistence where relevant |
| OS/VM reset or physical-device campaign | Actual tested platform/storage guarantees and limitations; not inferred from a process-kill test |
| Corrupt or unsupported input | Detection/diagnostics, no silent empty/stale result, source preservation and controlled recovery/salvage contract |
A matrix covering every registered hook can still omit a real persistent transition. Independently review the actual I/O/ownership/publication sequence against the fault model. New hooks must enter the matrix, but missing hooks must also be discoverable.
Concrete example: #2978 is a strong install/rollback state-machine test pattern; #3011 separately tracks rebuild marker/rename directory-durability concerns. The former is not automatically evidence for the latter. Do not infer any platform's power-loss guarantee merely from “the filesystem is journaled.”
Define transaction outcomes, not just “data must remain”
The oracle must account for full operations and transaction boundaries, including updates, deletes, uniqueness and FileStorage changes—not just retained insert IDs.
- Durably acknowledged: the recovered history must preserve the transaction's committed effect, subject to legitimate later transactions and the documented durability assumptions.
- Known aborted before commit: no partial transaction effects may leak.
- Outcome unknown at interruption: the transaction may have committed before its response was observed. Allow only complete outcomes permitted by the protocol; do not assume “no observed acknowledgment” means “must be absent.”
- Explicitly degraded durability: test the actual documented guarantee and diagnostics. Do not silently grant power-loss durability or treat a genuine I/O error as “sync unsupported.”
Keep the expected operation/acknowledgment history outside the engine under test and outside the failure domain being destroyed. A separate parent is sufficient only for a child-process failure model, not automatically for a whole-machine reset. Verify that the acknowledgment recorder itself cannot lose or misclassify completed operations.
For concurrent histories, model allowed ordering and snapshot semantics; do not impose one arbitrary schedule that the public contract never promised.
“Fails closed” is conditional, not a universal pass
For each input/fault scenario, say which outcomes are permitted. Rejecting every valid database is not a safety fix. A valid supported file must still open, migrate or request an explicitly required writable upgrade according to its contract.
A recovery-incomplete refusal is acceptable only where that protocol permits it, with preserved evidence and actionable recovery instructions. Where automatic recovery is promised, permanent refusal after a recoverable interruption is a failure. Silent stale data is never an acceptable substitute.
Keep ordinary open/inspection, recovery and potentially lossy salvage distinct. Do not let an automatic repair hide the first failing state in a test.
4. Test composition, not only individual features
Build a small reusable set of database lifecycle scenarios on top of the existing targets. Reuse operation generation, fault hooks, models and artifact retention; avoid another giant bespoke harness.
Example scenario, instantiated only for supported combinations:
actual historical file
→ supported upgrade and legacy/new representations
→ indexed updates / transactional FileStorage changes
→ multiple live reader generations
→ another writer commits; checkpoint/reclamation is actually exercised
→ interruption at a selected boundary
→ a second interruption during recovery
→ cold open in a fresh process
→ verify complete logical state, index results and applicable structural integrity
→ further write, checkpoint and cold reopenDifferent variants cover rebuild/replacement, Shared mapped-read admission/fallback, and query/mapper/cache interactions. Direct/Shared or mixed-version combinations that are unsupported must exercise their rejection contract, not be silently treated as supported workloads.
Select interactions by shared state, not a blind Cartesian product. Start with known dangerous pairs; add explicit multi-feature sequences where a protocol spans more than two mechanisms. Pairwise configuration coverage alone is not evidence for an ordered recovery protocol.
Exercise more than the first successful cycle: repeated recovery, cache invalidation, version resets, slot reuse, close/reopen and owner turnover. Assert that these transitions actually happened; running a loop repeatedly is not proof of them.
Independent and complementary oracles
Use the existing logical-model, raw-integrity and differential machinery together where applicable:
- exact typed payloads, multiplicity, index keys/results, uniqueness, transaction effects and FileStorage bytes/metadata;
- raw structure/ownership/link validation, without silently rebuilding first;
- warm observations and fresh-process cold reads, followed by subsequent valid operations;
- indexed/unindexed or optimized/reference-path comparisons with proof each path ran.
Two paths sharing the same buggy decoder/comparer/translator are not independent. Historical versions are useful compatibility references but not universal truth for semantics intentionally changed or previously buggy. Explicitly classify expected differences.
Retain and extend oracle-selftest. For high-risk changes, also check that an unsafe implementation variant is detected by the end-to-end scenario, not only that a standalone assertion rejects a fabricated bad result. Examples: omit a durability barrier in the model, lose one acknowledged update, permit stale cleanup, bypass a generation check, or silently disable the required optimized path.
Keep instrumented deterministic tests, but also retain/extend applicable black-box production-assembly tests with TestingEnabled=false. Observers/barriers must not be the only reason the shipped code behaves correctly. Preserve existing production compatibility-tool coverage rather than claiming it does not exist.
Include resource and progress contracts
Concurrency and lifetime changes must distinguish correctness, liveness and performance. Cover per-worker completed progress, bounded waits under stated scheduling assumptions, stale-handle/buffer reuse, shutdown/disposal, lease cleanup, disk/temp-space and handle/thread growth where affected.
Use timeouts as deadlock guards, not as the sole proof of the interleaving. Keep throughput/tail-latency measurements separate from deterministic correctness assertions; do not fix a liveness test by removing the competing workload.
5. Make historical compatibility a versioned contract
Extend the existing fixture corpus and real-version scripts rather than proposing a new corpus from zero.
Define expected behavior for each selected producer/consumer/configuration boundary:
| Outcome | Required assertion |
|---|---|
| Read directly | Exact logical/index results; promised read-only byte preservation |
| Migrate automatically | Complete safe migration, retries/interruption behavior, subsequent writes/reopen |
| Require explicit/writable upgrade | Specific actionable rejection and preserved source bytes before upgrade |
| Unsupported or older-reader rejection | No accidental fallback to legacy decoding, no truncation or other unintended mutation |
Compatibility is not “all versions can always write each other's files.” Separate released versions from intentionally supported prerelease/internal format boundaries. Include mixed-process engine versions and coordination-sidecar ABI compatibility only where support is claimed; otherwise test safe refusal/fallback.
Because prerelease packages may themselves have been publicly distributed, treat published prereleases as an explicit policy decision rather than accidental internal-only states. Define which published prerelease window/boundaries are covered. For those in scope, the current engine must have a declared outcome—read, migrate, explicit upgrade, or reject without mutation. Do not infer indefinite support for every historical prerelease merely because a package was once published.
Each fixture manifest should capture:
producer package/version or exact commit + binary hash
generator source/recipe and fixture hashes
OS/runtime/architecture/culture/collation when representation depends on them
configuration and complete data/WAL/required-sidecar bundle
independent expected logical model and index/query expectations
expected consumer read/migrate/reject behavior
provenance and reason this boundary is retainedPreserve originals; run mutating tests on copies. Verify both the data and relevant companions on byte-preservation/rejection paths. A changed golden fixture or logical expectation requires an explicit reviewed explanation; never regenerate it automatically from the current engine to make CI green.
Include ordinary clean/dirty WAL, plain/encrypted, indexed/unindexed, partial migration, and important mixed representations. Where relevant cover FileStorage, multikey/computed indexes, custom collation, cross-runtime ordering, finite LIMIT_SIZE, custom streams and capacity failure.
Start with high-value supported boundaries and expand on findings. Do not require every historical build or every configuration combination. Keep reproducible small fixtures/corpora in the repository where practical; retain larger evidence in the existing artifact repository with immutable references and sufficient retention.
A source-code revert is not necessarily a database downgrade. Record the one-way-format/recovery/backup consequences of reverting a storage change or rolling back a release.
6. Test the candidate that will actually be integrated
A PR's old green result does not validate its combination with later merges. Existing PR merge-ref checks are useful; the requirement is fresh evidence for the actual candidate tree, not a claim that current CI only tests isolated heads.
For affected safety-critical paths:
- Validate against current
devand any preceding stack/queue changes; record the actual checkout SHA/tree and relevant dependency/tool inputs. - Invalidate affected evidence after a relevant head/base/stack change. An unchanged source tree may justify reusing evidence
Source: litedb-org/LiteDB