diff --git a/.github/workflows/coverage-gates.yml b/.github/workflows/coverage-gates.yml index c615fac78a..ae7e23e90f 100644 --- a/.github/workflows/coverage-gates.yml +++ b/.github/workflows/coverage-gates.yml @@ -17,41 +17,32 @@ jobs: steps: - uses: actions/checkout@v4 - - name: Install Rust stable - uses: dtolnay/rust-toolchain@stable + # Branch coverage needs nightly. Pinned so a toolchain update cannot move + # the numbers under an unrelated PR; bump it on purpose and re-measure. + - name: Install Rust nightly + uses: dtolnay/rust-toolchain@master with: + toolchain: nightly-2026-10-01 components: llvm-tools-preview - name: Install cargo-llvm-cov uses: taiki-e/install-action@cargo-llvm-cov - - name: Generate coverage (text) - run: cargo llvm-cov --text 2>&1 > cov_text.txt || true + - name: Build the pid_ns_helper example used by lock tests + # cargo-llvm-cov puts test binaries where the lock tests' lookup of + # examples/ next to the test binary fails; same workaround as + # llvm-cov.yml. + run: cargo build --examples --target-dir /tmp/minigraf-lock-test-examples + # A failing test fails the job: a partial report must never be gated. + - name: Run the tests with branch coverage + env: + MINIGRAF_PID_NS_HELPER: /tmp/minigraf-lock-test-examples/debug/examples/pid_ns_helper + run: cargo llvm-cov --branch --no-report + + - name: Summarize coverage + run: cargo llvm-cov report --branch --json --summary-only --output-path coverage.json + + # Thresholds come from coverage-thresholds.toml (#396). - name: Check per-module thresholds - run: | - FAIL=0 - check_module() { - local file=$1 threshold=$2 - local pct - pct=$(grep "$file" cov_text.txt | grep -oP '\d+\.\d+(?=%)' | tail -1) - if [ -z "$pct" ]; then - echo "WARNING: $file not found in coverage report" - return 0 - fi - if python3 -c "import sys; sys.exit(0 if float('$pct') >= $threshold else 1)"; then - echo "OK: $file: ${pct}% >= ${threshold}%" - else - echo "FAIL: $file: ${pct}% < ${threshold}%" - return 1 - fi - } - # Thresholds from coverage-thresholds.toml - check_module "wal.rs" 75 || FAIL=1 - check_module "db.rs" 70 || FAIL=1 - check_module "persistent_facts" 70 || FAIL=1 - check_module "btree_v6" 65 || FAIL=1 - check_module "executor.rs" 75 || FAIL=1 - check_module "evaluator.rs" 75 || FAIL=1 - check_module "stratification" 75 || FAIL=1 - exit $FAIL + run: python3 scripts/coverage_gates.py coverage-thresholds.toml coverage.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c8db5a603..08cfe94c59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Fuzzing reaches the v8 decoders, and the corpus is kept between runs (#387, #375).** On `v3`, the `btree_page` and `fact_page` targets still wrote the pre-release single-header layout and stopped at `STG-032` on every input, and `file_header` rarely got past the meta CRC. The page targets now start from a real v8 file built through the public API (rewritten with `LogWriter` at fixed tx times so its bytes are the same in every process). They overwrite one page with the input and recompute that page's checksum. `btree_page` fuzzes any leaf or internal node of the five trees, `file_header` fuzzes either meta slot (with or without a matching CRC, with or without the other slot), and `fact_page` fuzzes the fact page of a v7 golden file through migration and the read-only load. Each run executes one input-chosen probe query or `verify()`. The nightly fuzz workflow now runs every target in its own parallel job, on `main` and `v3` on alternating crons, and keeps each target's corpus in the Actions cache. A new weekly workflow (`fuzz-corpus.yml`) minimizes the cached corpus with `cargo fuzz cmin`, keeps every committed `seed_*` file, and proposes the result as a pull request. - **Two fuzz targets check results, not just crashes (#387).** `ops_sequence` decodes the input into up to 32 storage operations (transact, retract, a write transaction that commits or rolls back, checkpoint, reopen, and a crash that opens a copy of the file and WAL) and, after each one, compares the full rows now and at an input-chosen `:as-of`, plus one input-chosen query shape, with the reference model of the model-based test. It uses that test's driver and checks, now in `tests/reference_model`, so the proptest test and the fuzzer share one oracle. `corrupt_file` damages a file written over three checkpoints with up to 16 byte flips and an optional truncation, without fixing any checksum, and requires every query to fail or to return exactly the answers of the last checkpoint or the one before it, all from the same one. Its first run found that a file cut to under one page opens as a new, empty database (#506); the target skips those lengths until that is fixed. - **Weekly soak test at scale (#392).** `tests/soak_test.rs` grows a file-backed database to 10M live facts in batches of 1–2,000 facts (multi-valued tags and shard values in one transaction, strings over 64 bytes, refs), then churns it for the rest of a 5-hour budget at 50 transactions a second: retracts and re-asserts of random facts, and long retract/assert histories on 32 hot entities. It checkpoints every 20–200 transactions and reopens every 2–10 minutes, half from a checkpointed file and half replaying the WAL. Every 10 minutes, after every reopen, and between churn writes it checks samples against a reference that derives each entity's facts from its number and keeps only what was retracted: EAVT per entity, entity and attribute on the tags, AVET by unique name, AEVT over a sparse attribute, `:as-of` on hot entities, and the transaction counter; a full scan runs in a child process at 2M facts (so its memory does not hide a leak), and `verify()` at the end. It fails if RSS after a reopen grows past 1.25× the baseline plus 256 MiB. Metrics (file size, open and checkpoint time, RSS and peak RSS, p50/p99 per query path) go to a JSON-lines file that `.github/workflows/soak.yml` uploads weekly, alternating `main` and `v3`. `soak_short` runs the same driver at 20K facts in the per-PR suite. Found #518: attribute-and-value patterns scan the whole attribute. +- **Coverage gates that gate (#396).** The per-module gate in `coverage-gates.yml` had never checked anything: the instrumented test run failed (the lock tests could not find `pid_ns_helper`), the report it grepped was empty, and every module was skipped with a warning, so the job passed. It also read `cargo llvm-cov --text`, which has no per-file percentages, and named `btree_v6`, which v3 no longer has. The job now runs the whole suite with branch coverage on a pinned nightly, fails if any test fails, and checks each file's line and branch percentage against `coverage-thresholds.toml` with `scripts/coverage_gates.py`; a file missing from the report, or without branch data, fails. The thresholds file covers the WAL, `db.rs`, the fact log and log writer, every storage file, and the evaluator, executor and stratification, with floors at the measured values less one point. It also lists the paths left uncovered on purpose (invariant checks, browser-only and Windows-only paths). New tests cover the WAL's fact-size and fact-count limits (the old fact-size test changed bytes inside the fact and never reached the limit), a WAL opened in a missing directory, a failed cut of a torn WAL tail, short v7 pages and slots past the count, backup meta pages of another generation or length, a torn first meta with data in page 1, `save` with nothing pending, `into_backend` with pending facts, `rebuild_indexes` with nothing checkpointed, unsorted or repeated B+tree input, a stored key inserted with another value, a tree pointer to a page of another type, the read-only `MutexStorageBackend`, and two threads missing the same page in the page cache (before, only a lucky race reached that path). Branch coverage of `wal.rs` went from 83% to 95%, `packed_pages.rs` from 86% to 100%, `persistent_facts.rs` from 82% to 88%, and `btree.rs` from 85% to 85.5%. ### Known issues diff --git a/CLAUDE.md b/CLAUDE.md index 5c39448fad..8b9c1c27e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -198,7 +198,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1409 tests** (1399 passing, 10 ignored; unit + integration + doc). +**1423 tests** (1413 passing, 10 ignored; unit + integration + doc). See `docs/TEST_COVERAGE.md` for the full per-file breakdown. **Testing conventions** — see the Testing Conventions section below before writing any tests. diff --git a/README.md b/README.md index 266588374e..baccc90789 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ let r2 = pq.execute(&[("tx", BindValue::TxCount(2)), ("entity", BindValue::Entit ```bash cargo run # interactive Datalog REPL -cargo test # run 1409 tests +cargo test # run 1423 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/ROADMAP.md b/ROADMAP.md index 984dbf801a..5741d6d49d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -95,7 +95,7 @@ Scope — release-gate testing and documentation: - Fault injection across save/WAL/recovery (#390) - Long-running soak test at scale (#392; done on `v3`: `tests/soak_test.rs`, 10M facts and a 5-hour churn weekly, alternating `main` and `v3`) - Benchmarks at 100K–10M facts and a published performance envelope (#394) -- Higher storage/WAL coverage gates and branch-coverage gates (#396) +- Higher storage/WAL coverage gates and branch-coverage gates (#396; on `v3`: line and branch floors per file in `coverage-thresholds.toml`, checked on every PR) - Durability, recovery and operations guide (#398) --- diff --git a/coverage-thresholds.toml b/coverage-thresholds.toml new file mode 100644 index 0000000000..997ca56ea9 --- /dev/null +++ b/coverage-thresholds.toml @@ -0,0 +1,124 @@ +# Per-file coverage floors, checked on every push and PR by +# .github/workflows/coverage-gates.yml (scripts/coverage_gates.py). The single +# source of truth for the gates (#396). +# +# Percentages of lines and branches covered by `cargo llvm-cov --branch` with +# the nightly pinned in that workflow, test modules included. Each floor is +# the measured value rounded down, minus one point of slack (none at 100%). +# A floor only goes up: raise it in the PR that adds the tests, and lower one +# only with the reason in the PR. Target for the storage and WAL files: 90% +# branches. +# +# Known uncovered paths, left on purpose: +# - INT-049 bails in btree.rs and persistent_facts.rs (a leaf or node that +# cannot fit, an empty level, a tree deeper than MAX_TREE_DEPTH, a rebuilt +# index failing its own check): invariant checks that no input reaches +# without a bug elsewhere. +# - persistent_facts.rs `check_fits` / `check_written` with +# `holds_every_page() == false`: only the browser buffer, covered by the +# wasm tests in wasm.yml, which this job does not measure. +# - wal.rs `delete_file` retry sleep: Windows only (one attempt elsewhere). +# - wal.rs `scan_entries` read error other than EOF: needs a failing read on a +# regular file, which the fault plan (storage/fault.rs) does not inject. + +# WAL and the public API + +[files."src/wal.rs"] +lines = 97 +branches = 94 + +[files."src/db.rs"] +lines = 95 +branches = 87 + +[files."src/fact_log.rs"] +lines = 91 +branches = 97 + +[files."src/log_writer.rs"] +lines = 97 +branches = 100 + +[files."src/graph/storage.rs"] +lines = 97 +branches = 91 + +# Storage engine + +[files."src/storage/backend/file.rs"] +lines = 88 +branches = 74 + +[files."src/storage/btree.rs"] +lines = 94 +branches = 84 + +[files."src/storage/cache.rs"] +lines = 86 # the test-only BarrierBackend's unused trait methods count +branches = 75 + +[files."src/storage/dict.rs"] +lines = 94 +branches = 89 + +[files."src/storage/freelist.rs"] +lines = 95 +branches = 59 + +[files."src/storage/index.rs"] +lines = 100 +branches = 74 + +[files."src/storage/keys.rs"] +lines = 94 +branches = 80 + +[files."src/storage/meta.rs"] +lines = 96 +branches = 74 + +[files."src/storage/mod.rs"] +lines = 84 +branches = 92 + +[files."src/storage/node.rs"] +lines = 90 +branches = 79 + +[files."src/storage/packed_pages.rs"] +lines = 97 +branches = 100 + +[files."src/storage/page.rs"] +lines = 90 +branches = 83 + +[files."src/storage/persistent_facts.rs"] +lines = 95 +branches = 86 + +[files."src/storage/reader.rs"] +lines = 97 +branches = 94 + +[files."src/storage/value_pages.rs"] +lines = 85 +branches = 80 + +[files."src/storage/verify.rs"] +lines = 79 +branches = 70 + +# Query engine + +[files."src/query/datalog/evaluator.rs"] +lines = 88 +branches = 84 + +[files."src/query/datalog/executor.rs"] +lines = 93 +branches = 76 + +[files."src/query/datalog/stratification.rs"] +lines = 100 +branches = 100 diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 5528f48fdb..2f08a50cfa 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,9 +4,9 @@ **Verified**: 2026-10-10 with `cargo test --quiet` -**Result**: 1,399 passing tests and 10 ignored tests (1,409 total) +**Result**: 1,413 passing tests and 10 ignored tests (1,423 total) -This covers the unreleased file-format-v8 work (#287, #371): the index-key value-collision fix, the v7→v8 migration, and the drop of formats v1–v6. It otherwise still covers the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Merged from the v2.x line: `tests/point_query_history_test.rs` and new storage unit tests check that attribute-narrowed bound-entity lookups return exactly what a full scan returns, and that `net_asserted_facts` matches its previous implementation on randomized histories (#323). Attribute-scan tests check that the AEVT range covers exactly the queried attribute, including non-ASCII names such as `:丿` and prefix siblings such as `:ab` for `:a` (#381). Incremental B+tree rebuild tests check that checkpoints which copy untouched index leaves produce exactly the entries and file checksum a full rebuild would, including over repeated checkpoints, that single-fact checkpoints do not fragment the index, and that a damaged slot directory is rejected rather than copied (#315). B+tree cursor tests check that every scan walks the tree, not the leaf `next_leaf` chain: full scans and start positions match the input, `seek` from the current position lands where a fresh descent from the root would (randomized, plus within a leaf, to a sibling, across subtrees, past the end, into the gap after a leaf, and backwards as a no-op), a seek to the sibling leaf reads exactly one page, reads are unchanged with every `next_leaf` zeroed, a child pointer into a non-B+tree page is STG-013, and a cycle in child pointers is an error, not a hang (v8 storage format PR 1, #374). Directory-sync unit tests check that creating the `.graph` file or the WAL, and deleting the WAL, fsync the parent directory after the file operation, and that reopening an existing file does not (#389). Disjunction tests check that `or-join` returns an empty result, not INT-031, when no rows reach it: on an empty database, after a pattern that matches nothing, after a `not` that removes every row, and in a rule body (#405). A stratification unit test builds the same two-rule negative cycle 64 times and checks that the INT-054 message names the same predicate pair every time (#410). Magic-sets tests check that a recursive rule with a literal start that recurses through another rule returns the same results as without the literal (#297). API tests check that `execute()` and `WriteTransaction::execute()` reject `$slot` bind tokens in every position with API-010 (#407). The REPL `run()` test now runs in a child process with null stdin, so it no longer hangs when the test runner's stdin is an open non-TTY stream (#415). v8 page-format tests (PR 2, #374, #388) check the 24-byte page header (a flipped bit, a wrong page id and a future generation each give their own STG code, legacy page types fail before the CRC, and a failed page is never cached), meta-page encoding, the free-list chain, WAL v2's base generation, and every row of the meta-selection table: both slots valid, a torn newest slot with the WAL's base generation (opens at the older one), a WAL newer than the valid meta, pages of the next generation on the free list or past `page_count` with no WAL (all STG-033, with the file unmodified), an unknown feature bit (STG-034), and a pre-release v8 single header (STG-032). Fault-injection tests crash `save()` at every page write (cleanly and with torn pages, including the meta write) and every sync, and crash a v7 migration at every write; each reopen finds exactly the old or the new checkpoint, and every reachable page plus the free list covers the file exactly. Twenty-five consecutive saves never write a page the previous meta references. Covering-key tests (PR 3, #433) check that byte order equals logical order for every key component and value type on random tuples (negative, zero and large integers, NaN and ±0.0, strings with 0x00, 64- and 65-byte strings, FOREVER, newest-transaction-first) and that every component round-trips; that prefix-compressed leaves and shortest-separator internal nodes round-trip, agree with a linear scan, keep `max(left) < s ≤ min(right)`, and reject an overflow; that the byte-key B+tree's builds, incremental rebuilds, cursor and `seek` match their expected sets; that dictionary ids are assigned once, never reused, shared between a keyword attribute and value, and deterministic; that a re-asserted or retracted long value writes no new value page and a forced hash collision still finds the right value; that one transaction with two timestamps is STG-037 and a missing dictionary entry STG-036; that committed reads by entity, entity and attribute, attribute, and in full equal an in-memory model across eight checkpoints and a reopen; that short-valued reads touch no value page; that a v7 file with every value type, long strings, refs and retractions migrates to exactly the same facts; that a pre-covering-key v8 file is STG-032; and that string values over 4,068 bytes and attributes or keywords over 1,024 bytes are WAL-003. A WAL test checks that reopening next to a fully checkpointed WAL does not reuse transaction numbers (#447). Copy-on-write checkpoint tests (PR 4, #434) check that lazy free-list pops and pushes conserve every page across page boundaries, partial head pages and chain exhaustion, never hand out a page freed in the same generation, and share unread chain pages unchanged; that a copy-on-write insert equals a sorted merge for random batches (including keys below the first and above the last, many into one leaf, root growth to depth 3, and 1 KB separators that split internal nodes), leaves the old tree readable and unchanged, frees exactly the replaced nodes, writes only new pages, writes exactly one leaf and two internal nodes for one entry in a depth-3 tree, and does not fragment leaves under single inserts; that a checkpoint after 1 or 100 right-edge facts writes at most the tree-depth difference more pages at 100,000 facts than at 10,000, and at most one path per new entry per tree for random keys; and that four reader threads querying throughout 40 checkpoints never fail and never see the fact count go backwards. Hardening tests (PR 5) damage an index leaf, an internal node, a dictionary leaf, a value page and a free-list page in turn. Every committed read or checkpoint that reaches the damaged page fails with STG-029, never with wrong or fewer rows. A query through `Minigraf` on a file with damaged leaves fails with STG-029, and the file still opens at its last checkpoint. A size test measures at most 200 bytes per fact (142 measured) on 144k facts in #433's shape; its 1.15M-fact variant is ignored locally and runs in the nightly smoke workflow. A shared dictionary-cache test checks that cached ident and timestamp lookups return the same facts and that the cache stays bounded. Merged from the v2.x line: storage and `edge_cases_test.rs` tests check that more than 65,535 uncheckpointed facts each resolve to their own fact through entity lookups and attribute scans, in memory and file-backed (#445). Merged from the v2.x line: `tests/golden_corpus_test.rs` opens a copy of each committed golden file in `tests/golden/` (v7 files written by minigraf 2.0.3: one checkpoint, several checkpoints, indexes rebuilt on open, a crash-left WAL, an already-checkpointed WAL, same-transaction multi-values) and checks its manifest's CRC32, `tx_count` and query results after open, after a checkpoint and reopen, and after one more write; a second test checks that every golden file has a manifest (#391). On `v3` the same test checks that each v7 file has a v8 meta page after its first open and gives the same results after reopening the migrated file, and adds seven v8 golden files (one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values at the size limits); the #371 queries, skipped on v2.x, run and pass. `tests/model_based_test.rs` runs random sequences of transacts, retracts, write transactions, checkpoints, reopens and simulated crashes against a file and, after every step, compares the transaction counter, `verify`, full rows with windows and tx counts, and six query shapes under `:as-of N` and `:valid-at T` with a reference model (#385). `tests/property_test.rs` writes random histories (batched transacts, retracts, write transactions, checkpoints) in memory and to a file, and compares random queries (one to three joined patterns, `not` or `not-join`, a comparison predicate, `:as-of`, `:valid-at` or `:any-valid-time`) with a reference evaluator, on the open file and after a reopen; a query error fails the test (#386). `tests/crash_kill_test.rs` kills a child process running a seeded workload (multi-valued batches, batched retracts, five checkpoint modes) at a random point and checks that the reopened file holds exactly the transactions the child logged as committed, or those plus the one in flight, through full-scan, AEVT, AVET, EAVT and `:as-of` queries and `verify`, again after a second reopen and after a checkpoint plus reopen (#384). Integrity tests (#373) check that intact files verify with no problems and an exact fact and page count, and that `verify` reports each kind of damage with its code: an EAVT, AEVT, AVET or VAET leaf missing an entry (STG-038), keys out of order and a page reached from two trees (STG-039), a rotted index leaf (STG-029), a free page still in use and a leaked page (STG-035), a missing transaction entry (STG-036), and an entity id whose UUID maps to another id (STG-040). After each index or free-list damage, `rebuild_indexes` leaves a file that verifies clean, reads back every fact and accounts for every page. The source is an index that agrees with another one, or the only intact one; three intact indexes that all disagree, or a damaged dictionary, give STG-041 with the file unchanged. A rebuild commits pending facts, including new ids and long values. A crash at every write (clean and torn) and every sync of a rebuild reopens either at the old generation with only its old damage or at the new one with none, never losing a fact. Through `Minigraf` (`tests/integrity_test.rs`), a rebuild commits WAL entries and deletes the WAL, and flipping a byte in each leaf of a file in turn is always reported, then either repaired (index leaves) or refused with STG-041 and the file unchanged (dictionary leaves). Page-count tests (#497) check that a CRC-valid meta whose `page_count` is past the end of the file (one page past, 2^50, `u64::MAX`; with the other slot valid or damaged; with or without a WAL) and a file cut short by one page, three pages or down to three pages are `STG-044` at open, with the file unchanged and not grown, while a `page_count` exactly at the end opens; that a checkpoint whose pages did not all reach the backend fails with `INT-049` before writing its meta, and the file reopens at the previous generation; and that `verify` at a meta counting pages past the end reports `STG-044` without scanning to that count. Through `Minigraf` (`tests/integrity_test.rs`), a file truncated by one or three pages and a file whose meta was rewritten with `page_count` 2^50 and a valid CRC are `STG-044` read-write and read-only, with no WAL created and the file length unchanged. The `file_header` fuzz input from #497 is a corpus seed. A sub-page test (#506, `tests/integrity_test.rs`) checks that a file of 1 to 4,095 bytes is `STG-045` read-write and read-only, unchanged and with no WAL, when it is a database cut below one page or foreign bytes, and opens as a new database that takes writes when it is a prefix of the first meta page or all zeros; a file-backend unit test checks that `partial_page` returns the bytes past the last whole page. The `corrupt_file` fuzzer no longer skips files under one page: they must fail to open or open empty, and the #506 input is a corpus seed. Damaged v7 fact page tests (#496) check that a page in the counted fact range whose type byte is anything but the fact-page type (zero, `0x01`, the v2.x B+tree types, `0xFF`, a zeroed page; first and last page) is `STG-014` rather than skipped, while a range derived from the first index root skips only v2.x B+tree pages; that opening such a v7 file read-write or read-only fails with `STG-014` and writes nothing; and, in `tests/migration_matrix_test.rs`, that the golden `v7_basic.graph` with page 1's type byte changed or page 1 overwritten with noise fails both opens with the file unchanged and no WAL created. Both inputs are `fact_page` corpus seeds. Merged from the v2.x line: `tests/edge_cases_test.rs` checks the same refusal and acceptance through `Minigraf::open` on a database checkpointed twice (#506). Torn-WAL-tail tests (#513) check that opening a WAL writer cuts off a partial last entry (cut in the checksum, the header or the payload) or an entry with a bad checksum and everything after it, then appends where replay reaches, and leaves an intact WAL byte for byte; that an append that fails part-way makes every later append `WAL-007` while a rejected oversize fact (`WAL-003`, nothing written) does not; through `Minigraf`, that the failed transaction is not applied, later `transact` and `commit` are `WAL-007`, and a `checkpoint()` makes writes work again; and, in `tests/wal_test.rs`, that a commit made after reopening a crash-left WAL with each kind of torn tail survives a second crash. The fault matrix (#390, `src/fault_matrix.rs`) drives a test-only fault plan through the real file backend, WAL and directory fsync: an EIO, a short or torn write (1, 40 and 4,095 bytes), a full disk that keeps failing every later write, a failed fsync, and a failed fsync that also loses the writes since the last good one ("fsyncgate"), each at every write or sync call of a transact, a transact that creates the WAL, an automatic checkpoint, `checkpoint()`, the close-time checkpoint and `rebuild_indexes()`, on a database committed over two checkpoints with multi-valued, retracted and long values and entries pending in the WAL. After each fault, the handle holds the old facts or those plus the whole transaction, never part of one; after a failed checkpoint another is `STG-046`; a later write succeeds or is `WAL-007`/`STG-046`; a kill and reopen gives exactly the handle's facts, plus the failed transaction whole or not at all, and `verify` finds nothing; and a commit after recovery survives another kill. Two more tests fill the disk halfway through a checkpoint (`STG-046`, reads unchanged, reopen intact), and fail the fsync after a checkpoint's meta write and then retry the checkpoint, crashing at each of its writes: the retry is refused and every reopen is intact (without the refusal, a reopen hits `STG-029`). Unit tests check the fault plan's counting, and that a `rebuild_indexes` refused with `STG-041` leaves the handle usable. Live-read tests (#379) check that `triple_len` ends exactly where `tx↓` begins for every value type and index; that on random histories (several valid-time windows, retractions, re-assertions, several values per attribute, long values, 12 transactions per checkpoint) the committed live read for every scan kind and `:as-of` point is exactly the net-asserted set, that it stays equivalent with pending facts on top, and after reopen; and that a point read on a triple asserted and retracted 2,000 times reads under a third of the pages a history read does, with or without `:as-of`. `tests/live_reads_test.rs` runs the same history in a checkpointed file database and in memory and checks that point, attribute, full-scan, join, valid-time, `:as-of` and rule queries return the same rows, before and after reopen. One-window tests (#435) check that `net_asserted_facts` keeps each triple's newest transaction only (a later window replaces an earlier one, closing an open window, a retraction in the newest transaction hides it, records with two windows in one transaction keep both, once each) against a per-triple model on random histories; that the on-disk key walk agrees at every `:as-of` before and after reopen; and that `API-011` rejects two windows of one fact in one transaction without taking a `tx_count`. `tests/valid_time_window_test.rs` checks replacing, closing, extending, reopening and retract-then-reassert through entity-bound and attribute queries in memory, on a checkpointed file and after reopen, `API-011` from `transact` and from `WriteTransaction::execute`, and a later statement's window committed when two statements of a `WriteTransaction` give one fact different windows. Window-validation tests (#436) check that `check_valid_windows` rejects an empty window, an inverted one, and a `:valid-to` at or before the transaction time when `:valid-from` is left out, but not retractions; that `execute` rejects each such `transact` (both bounds, equal bounds, `:valid-to` only, a per-fact bound inverting the transaction's window) with `API-019` without writing or taking a `tx_count`, in memory, checkpointed and after reopen; that `tx.execute()` rejects them and the transaction still commits its other statements; that `commit()` rejects a default `valid_from` that has passed the `:valid-to` by commit time; and that `FactStorage::transact_batch` takes no `tx_count` on rejection. Statement-order tests (#477, `tests/statement_order_test.rs`) run every mix of two statements on one fact inside a `WriteTransaction` (retract then assert, assert then retract, two retracts, two windows, after a committed assertion and on an empty database) and check that reads inside the transaction and the committed rows agree, in memory, checkpointed and after reopen; that other facts of an overridden statement survive; that the commit is one transaction without the overridden records; and that two windows in one statement are `API-011` from `tx.execute()` while the rest commits. A unit test checks the commit collapse keeps each fact's newest statement in order. A log-writer test checks that an inverted window is `API-019`, a second window of a fact in one transaction `API-011`, and an assertion and a retraction of one fact in one transaction `API-020` in either order, each leaving the writer usable and the output exact, while duplicate retractions, identical repeats and the same fact in the next transaction are accepted. Cursor tests (#432, `tests/cursor_test.rs`) check that `query()` batches partition the `execute()` answer for several batch sizes (never empty, never over `max_rows`, `max_rows == 0` still progresses, `None` stays `None`), that the iterator and aggregates, rules, `:as-of` and `:any-valid-time` match `execute()`, that a cursor opened before a `transact`, a `WriteTransaction` commit, a retract or a checkpoint returns the pre-write answer to the end (in memory and file-backed), that `transact`/`retract`/`rule` are `API-012` and bind slots `API-010`, that a `WriteTransaction` thread gets `INT-001`, that rule limits give `INT-020` as from `execute()`, that `PreparedQuery::query` matches `PreparedQuery::execute`, and that a cursor is `Send` and outlives its database handle. Fact-log tests (#430, `tests/fact_log_test.rs`) check that `fact_log()` returns exactly the records written (assertions and retractions, with `tx_count` and `tx_id`) in memory, with everything pending, half checkpointed, fully checkpointed and after reopen, in both orders, with windows of 1 to 1,000 records and batch sizes of 1 to 1,000, in non-decreasing `tx_count` in Tx order; that every layout gives identical records, including valid-time windows and long string values; that a transaction larger than the window is split with no loss or duplicate; that attribute, attribute-prefix, entity and tx-range filters and their combinations match a model, and unknown names match nothing; that writes after open are not in the log; that `checkpoint()` and `rebuild_indexes()` are `API-013` while a log is open (a checkpoint with nothing to write is allowed), that automatic checkpoints from `execute()` and `WriteTransaction::commit` wait for the log, and that closing, dropping or finishing the log releases the database; that a `WriteTransaction` thread gets `INT-001`; and that a log is `Send`, outlives its database handle, and the deferred writes replay on the next open. Read-only open tests (#429, `tests/read_only_open_test.rs`) check that a read-only handle on a file with checkpointed facts and a pending WAL returns the same query results, `tx_count` and fact log as a read-write open; that queries, a cursor, a fact log, `verify`, `prepare`, rules and a UDF leave the `.graph` and WAL bytes and the `.graph` mtime unchanged, and no WAL is created; that `transact`, `retract`, `begin_write`, `checkpoint` and `rebuild_indexes` are `API-014` without taking a `tx_count`, also on a read-only in-memory database and through the builder path; that a missing file is `STG-042` and nothing is created; that an empty file is an empty database and stays 0 bytes; that read-only handles share a file while a read-write one is refused with `STG-025`, both ways; that a file without write permission opens read-only; and that small and whole-file page caches work. File-backend unit tests check that a shared-mode backend refuses page writes and syncs with `INT-056`, that the in-process registry counts readers and admits readers or one writer (also without kernel locks), and that a reader in another process shares the file with a reader here and refuses a writer here with `STG-026`. Storage unit tests check that a read-only open of a v7 file at every point of an interrupted migration (clean and torn writes) sees every fact and writes nothing, and that an empty backend stays empty. `tests/golden_corpus_test.rs` opens a copy of every golden file read-only first and checks its `tx_count` and queries, and that neither the file nor its WAL changes. Log-writer tests (#431, `tests/log_writer_test.rs`) copy a source's fact log (assertions, retractions, an explicit valid-time window, long strings, refs, keywords, checkpointed and pending facts) through `LogWriter` and check that the new file has no `.partial` or WAL, verifies clean, and gives the source's `tx_count`, fact log and query results (current, `:valid-at`, `:any-valid-time`, every `:as-of`, and entity-, attribute- and value-bound lookups) read-write, read-only and after reopen (#370); that it takes new writes at the source's next `tx_count`; that 90,000 facts over two batch commits verify clean and count correctly at `:as-of`; that a purged middle transaction is a hole whose `:as-of` equals the one before, and trailing holes keep the counter through `advance_tx_count`; that an empty log is an empty database with the counter; that `tx_count` 0, a lower or closed transaction and a backwards advance are `API-015`, a second `tx_id` `API-016`, a second window `API-011`, a retraction of an asserted fact in one transaction `API-020`, an empty window `API-019` and oversize values or idents `WAL-003`, each leaving the writer usable and the output exact, with repeats written once; that an existing target or WAL is `STG-043`, a second writer `STG-025` and `read_only` `API-014`; that a stale `.partial` is reused; that dropping an unfinished writer leaves nothing; that `finish` refuses a target created during the build and leaves it untouched; and that `LogWriter` is `Send`. Unit tests check that a batch commits only when a transaction opens past the batch size, never splitting one, and that `FileBackend::truncate` empties a file. A unit test in `error.rs` checks that `MinigrafError::invalid_argument` and `MinigrafError::closed`, the constructors for language bindings, give API-017 and API-018 with their text. Query-validation tests (#406, #414) check that a plain `:find` variable or a window function's argument, `:partition-by` or `:order-by` variable that no `:where` clause binds (including `?_` wildcards) is `PRS-080` from both `execute()` and `prepare()`, naming the variable, while variables bound by a pattern, an attribute position, a rule call, an expression binding, an `or-join`, every branch of an `or`, a pseudo-attribute or a window spec are accepted, and bind slots are not mistaken for `:find` variables; and that an unknown aggregate is `QRY-010` and an unknown window function `QRY-011` on an empty database, when no row matches, when rows match, through a rule query and through a prepared query, while a registered UDF in either position returns an empty result on an empty database. Three `BrowserDb` tests (wasm32, run with `wasm-bindgen-test` in a browser, not counted above) check that `query()` batches of 1, 7 and 1,000 give the rows of `execute()`, that a cursor keeps the answer from when it opened and returns the end after `close()`, and that a `transact` is API-012. The wasm32 targets run in CI (`.github/workflows/wasm.yml`). In a browser (`wasm-pack test --headless`, Firefox and Chrome): 32 `wasm_bindgen_test` tests: nineteen for `BrowserDb` (including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read, from #470), eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before), and two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. Five of the `BrowserDb` tests (#411, #440) check that opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open; that after each of 60 transacts memory, and at the end IndexedDB, hold exactly the pages not on the free list while the file grows by under one page per transact; that a commit applied in memory but never flushed reopens at the previous one and keeps working; that an export after churn is as long as the meta says and imports back with its free pages dropped; and that `importGraph()` deletes the replaced database's IndexedDB keys. Two buffer tests check that releasing a page drops its bytes and any unflushed write, and that export writes a released page as zeros. A native storage test checks that a file whose free pages are all zeros (as the browser exports them), both just migrated from v7 and after 20 saves, opens, verifies clean and keeps committing, and the free-list test checks that a checkpoint reports exactly the ids it newly lists. On `wasm32-wasip1` under Wasmtime: the unit and integration tests that do not use a file run, 935 passing; nine that spawn threads or a child process are ignored on WASI. These are not counted above. +This covers the unreleased file-format-v8 work (#287, #371): the index-key value-collision fix, the v7→v8 migration, and the drop of formats v1–v6. It otherwise still covers the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Merged from the v2.x line: `tests/point_query_history_test.rs` and new storage unit tests check that attribute-narrowed bound-entity lookups return exactly what a full scan returns, and that `net_asserted_facts` matches its previous implementation on randomized histories (#323). Attribute-scan tests check that the AEVT range covers exactly the queried attribute, including non-ASCII names such as `:丿` and prefix siblings such as `:ab` for `:a` (#381). Incremental B+tree rebuild tests check that checkpoints which copy untouched index leaves produce exactly the entries and file checksum a full rebuild would, including over repeated checkpoints, that single-fact checkpoints do not fragment the index, and that a damaged slot directory is rejected rather than copied (#315). B+tree cursor tests check that every scan walks the tree, not the leaf `next_leaf` chain: full scans and start positions match the input, `seek` from the current position lands where a fresh descent from the root would (randomized, plus within a leaf, to a sibling, across subtrees, past the end, into the gap after a leaf, and backwards as a no-op), a seek to the sibling leaf reads exactly one page, reads are unchanged with every `next_leaf` zeroed, a child pointer into a non-B+tree page is STG-013, and a cycle in child pointers is an error, not a hang (v8 storage format PR 1, #374). Directory-sync unit tests check that creating the `.graph` file or the WAL, and deleting the WAL, fsync the parent directory after the file operation, and that reopening an existing file does not (#389). Disjunction tests check that `or-join` returns an empty result, not INT-031, when no rows reach it: on an empty database, after a pattern that matches nothing, after a `not` that removes every row, and in a rule body (#405). A stratification unit test builds the same two-rule negative cycle 64 times and checks that the INT-054 message names the same predicate pair every time (#410). Magic-sets tests check that a recursive rule with a literal start that recurses through another rule returns the same results as without the literal (#297). API tests check that `execute()` and `WriteTransaction::execute()` reject `$slot` bind tokens in every position with API-010 (#407). The REPL `run()` test now runs in a child process with null stdin, so it no longer hangs when the test runner's stdin is an open non-TTY stream (#415). v8 page-format tests (PR 2, #374, #388) check the 24-byte page header (a flipped bit, a wrong page id and a future generation each give their own STG code, legacy page types fail before the CRC, and a failed page is never cached), meta-page encoding, the free-list chain, WAL v2's base generation, and every row of the meta-selection table: both slots valid, a torn newest slot with the WAL's base generation (opens at the older one), a WAL newer than the valid meta, pages of the next generation on the free list or past `page_count` with no WAL (all STG-033, with the file unmodified), an unknown feature bit (STG-034), and a pre-release v8 single header (STG-032). Fault-injection tests crash `save()` at every page write (cleanly and with torn pages, including the meta write) and every sync, and crash a v7 migration at every write; each reopen finds exactly the old or the new checkpoint, and every reachable page plus the free list covers the file exactly. Twenty-five consecutive saves never write a page the previous meta references. Covering-key tests (PR 3, #433) check that byte order equals logical order for every key component and value type on random tuples (negative, zero and large integers, NaN and ±0.0, strings with 0x00, 64- and 65-byte strings, FOREVER, newest-transaction-first) and that every component round-trips; that prefix-compressed leaves and shortest-separator internal nodes round-trip, agree with a linear scan, keep `max(left) < s ≤ min(right)`, and reject an overflow; that the byte-key B+tree's builds, incremental rebuilds, cursor and `seek` match their expected sets; that dictionary ids are assigned once, never reused, shared between a keyword attribute and value, and deterministic; that a re-asserted or retracted long value writes no new value page and a forced hash collision still finds the right value; that one transaction with two timestamps is STG-037 and a missing dictionary entry STG-036; that committed reads by entity, entity and attribute, attribute, and in full equal an in-memory model across eight checkpoints and a reopen; that short-valued reads touch no value page; that a v7 file with every value type, long strings, refs and retractions migrates to exactly the same facts; that a pre-covering-key v8 file is STG-032; and that string values over 4,068 bytes and attributes or keywords over 1,024 bytes are WAL-003. A WAL test checks that reopening next to a fully checkpointed WAL does not reuse transaction numbers (#447). Copy-on-write checkpoint tests (PR 4, #434) check that lazy free-list pops and pushes conserve every page across page boundaries, partial head pages and chain exhaustion, never hand out a page freed in the same generation, and share unread chain pages unchanged; that a copy-on-write insert equals a sorted merge for random batches (including keys below the first and above the last, many into one leaf, root growth to depth 3, and 1 KB separators that split internal nodes), leaves the old tree readable and unchanged, frees exactly the replaced nodes, writes only new pages, writes exactly one leaf and two internal nodes for one entry in a depth-3 tree, and does not fragment leaves under single inserts; that a checkpoint after 1 or 100 right-edge facts writes at most the tree-depth difference more pages at 100,000 facts than at 10,000, and at most one path per new entry per tree for random keys; and that four reader threads querying throughout 40 checkpoints never fail and never see the fact count go backwards. Hardening tests (PR 5) damage an index leaf, an internal node, a dictionary leaf, a value page and a free-list page in turn. Every committed read or checkpoint that reaches the damaged page fails with STG-029, never with wrong or fewer rows. A query through `Minigraf` on a file with damaged leaves fails with STG-029, and the file still opens at its last checkpoint. A size test measures at most 200 bytes per fact (142 measured) on 144k facts in #433's shape; its 1.15M-fact variant is ignored locally and runs in the nightly smoke workflow. A shared dictionary-cache test checks that cached ident and timestamp lookups return the same facts and that the cache stays bounded. Merged from the v2.x line: storage and `edge_cases_test.rs` tests check that more than 65,535 uncheckpointed facts each resolve to their own fact through entity lookups and attribute scans, in memory and file-backed (#445). Merged from the v2.x line: `tests/golden_corpus_test.rs` opens a copy of each committed golden file in `tests/golden/` (v7 files written by minigraf 2.0.3: one checkpoint, several checkpoints, indexes rebuilt on open, a crash-left WAL, an already-checkpointed WAL, same-transaction multi-values) and checks its manifest's CRC32, `tx_count` and query results after open, after a checkpoint and reopen, and after one more write; a second test checks that every golden file has a manifest (#391). On `v3` the same test checks that each v7 file has a v8 meta page after its first open and gives the same results after reopening the migrated file, and adds seven v8 golden files (one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values at the size limits); the #371 queries, skipped on v2.x, run and pass. `tests/model_based_test.rs` runs random sequences of transacts, retracts, write transactions, checkpoints, reopens and simulated crashes against a file and, after every step, compares the transaction counter, `verify`, full rows with windows and tx counts, and six query shapes under `:as-of N` and `:valid-at T` with a reference model (#385). `tests/property_test.rs` writes random histories (batched transacts, retracts, write transactions, checkpoints) in memory and to a file, and compares random queries (one to three joined patterns, `not` or `not-join`, a comparison predicate, `:as-of`, `:valid-at` or `:any-valid-time`) with a reference evaluator, on the open file and after a reopen; a query error fails the test (#386). `tests/crash_kill_test.rs` kills a child process running a seeded workload (multi-valued batches, batched retracts, five checkpoint modes) at a random point and checks that the reopened file holds exactly the transactions the child logged as committed, or those plus the one in flight, through full-scan, AEVT, AVET, EAVT and `:as-of` queries and `verify`, again after a second reopen and after a checkpoint plus reopen (#384). Integrity tests (#373) check that intact files verify with no problems and an exact fact and page count, and that `verify` reports each kind of damage with its code: an EAVT, AEVT, AVET or VAET leaf missing an entry (STG-038), keys out of order and a page reached from two trees (STG-039), a rotted index leaf (STG-029), a free page still in use and a leaked page (STG-035), a missing transaction entry (STG-036), and an entity id whose UUID maps to another id (STG-040). After each index or free-list damage, `rebuild_indexes` leaves a file that verifies clean, reads back every fact and accounts for every page. The source is an index that agrees with another one, or the only intact one; three intact indexes that all disagree, or a damaged dictionary, give STG-041 with the file unchanged. A rebuild commits pending facts, including new ids and long values. A crash at every write (clean and torn) and every sync of a rebuild reopens either at the old generation with only its old damage or at the new one with none, never losing a fact. Through `Minigraf` (`tests/integrity_test.rs`), a rebuild commits WAL entries and deletes the WAL, and flipping a byte in each leaf of a file in turn is always reported, then either repaired (index leaves) or refused with STG-041 and the file unchanged (dictionary leaves). Page-count tests (#497) check that a CRC-valid meta whose `page_count` is past the end of the file (one page past, 2^50, `u64::MAX`; with the other slot valid or damaged; with or without a WAL) and a file cut short by one page, three pages or down to three pages are `STG-044` at open, with the file unchanged and not grown, while a `page_count` exactly at the end opens; that a checkpoint whose pages did not all reach the backend fails with `INT-049` before writing its meta, and the file reopens at the previous generation; and that `verify` at a meta counting pages past the end reports `STG-044` without scanning to that count. Through `Minigraf` (`tests/integrity_test.rs`), a file truncated by one or three pages and a file whose meta was rewritten with `page_count` 2^50 and a valid CRC are `STG-044` read-write and read-only, with no WAL created and the file length unchanged. The `file_header` fuzz input from #497 is a corpus seed. A sub-page test (#506, `tests/integrity_test.rs`) checks that a file of 1 to 4,095 bytes is `STG-045` read-write and read-only, unchanged and with no WAL, when it is a database cut below one page or foreign bytes, and opens as a new database that takes writes when it is a prefix of the first meta page or all zeros; a file-backend unit test checks that `partial_page` returns the bytes past the last whole page. The `corrupt_file` fuzzer no longer skips files under one page: they must fail to open or open empty, and the #506 input is a corpus seed. Damaged v7 fact page tests (#496) check that a page in the counted fact range whose type byte is anything but the fact-page type (zero, `0x01`, the v2.x B+tree types, `0xFF`, a zeroed page; first and last page) is `STG-014` rather than skipped, while a range derived from the first index root skips only v2.x B+tree pages; that opening such a v7 file read-write or read-only fails with `STG-014` and writes nothing; and, in `tests/migration_matrix_test.rs`, that the golden `v7_basic.graph` with page 1's type byte changed or page 1 overwritten with noise fails both opens with the file unchanged and no WAL created. Both inputs are `fact_page` corpus seeds. Merged from the v2.x line: `tests/edge_cases_test.rs` checks the same refusal and acceptance through `Minigraf::open` on a database checkpointed twice (#506). Torn-WAL-tail tests (#513) check that opening a WAL writer cuts off a partial last entry (cut in the checksum, the header or the payload) or an entry with a bad checksum and everything after it, then appends where replay reaches, and leaves an intact WAL byte for byte; that an append that fails part-way makes every later append `WAL-007` while a rejected oversize fact (`WAL-003`, nothing written) does not; through `Minigraf`, that the failed transaction is not applied, later `transact` and `commit` are `WAL-007`, and a `checkpoint()` makes writes work again; and, in `tests/wal_test.rs`, that a commit made after reopening a crash-left WAL with each kind of torn tail survives a second crash. The fault matrix (#390, `src/fault_matrix.rs`) drives a test-only fault plan through the real file backend, WAL and directory fsync: an EIO, a short or torn write (1, 40 and 4,095 bytes), a full disk that keeps failing every later write, a failed fsync, and a failed fsync that also loses the writes since the last good one ("fsyncgate"), each at every write or sync call of a transact, a transact that creates the WAL, an automatic checkpoint, `checkpoint()`, the close-time checkpoint and `rebuild_indexes()`, on a database committed over two checkpoints with multi-valued, retracted and long values and entries pending in the WAL. After each fault, the handle holds the old facts or those plus the whole transaction, never part of one; after a failed checkpoint another is `STG-046`; a later write succeeds or is `WAL-007`/`STG-046`; a kill and reopen gives exactly the handle's facts, plus the failed transaction whole or not at all, and `verify` finds nothing; and a commit after recovery survives another kill. Two more tests fill the disk halfway through a checkpoint (`STG-046`, reads unchanged, reopen intact), and fail the fsync after a checkpoint's meta write and then retry the checkpoint, crashing at each of its writes: the retry is refused and every reopen is intact (without the refusal, a reopen hits `STG-029`). Unit tests check the fault plan's counting, and that a `rebuild_indexes` refused with `STG-041` leaves the handle usable. Live-read tests (#379) check that `triple_len` ends exactly where `tx↓` begins for every value type and index; that on random histories (several valid-time windows, retractions, re-assertions, several values per attribute, long values, 12 transactions per checkpoint) the committed live read for every scan kind and `:as-of` point is exactly the net-asserted set, that it stays equivalent with pending facts on top, and after reopen; and that a point read on a triple asserted and retracted 2,000 times reads under a third of the pages a history read does, with or without `:as-of`. `tests/live_reads_test.rs` runs the same history in a checkpointed file database and in memory and checks that point, attribute, full-scan, join, valid-time, `:as-of` and rule queries return the same rows, before and after reopen. One-window tests (#435) check that `net_asserted_facts` keeps each triple's newest transaction only (a later window replaces an earlier one, closing an open window, a retraction in the newest transaction hides it, records with two windows in one transaction keep both, once each) against a per-triple model on random histories; that the on-disk key walk agrees at every `:as-of` before and after reopen; and that `API-011` rejects two windows of one fact in one transaction without taking a `tx_count`. `tests/valid_time_window_test.rs` checks replacing, closing, extending, reopening and retract-then-reassert through entity-bound and attribute queries in memory, on a checkpointed file and after reopen, `API-011` from `transact` and from `WriteTransaction::execute`, and a later statement's window committed when two statements of a `WriteTransaction` give one fact different windows. Window-validation tests (#436) check that `check_valid_windows` rejects an empty window, an inverted one, and a `:valid-to` at or before the transaction time when `:valid-from` is left out, but not retractions; that `execute` rejects each such `transact` (both bounds, equal bounds, `:valid-to` only, a per-fact bound inverting the transaction's window) with `API-019` without writing or taking a `tx_count`, in memory, checkpointed and after reopen; that `tx.execute()` rejects them and the transaction still commits its other statements; that `commit()` rejects a default `valid_from` that has passed the `:valid-to` by commit time; and that `FactStorage::transact_batch` takes no `tx_count` on rejection. Statement-order tests (#477, `tests/statement_order_test.rs`) run every mix of two statements on one fact inside a `WriteTransaction` (retract then assert, assert then retract, two retracts, two windows, after a committed assertion and on an empty database) and check that reads inside the transaction and the committed rows agree, in memory, checkpointed and after reopen; that other facts of an overridden statement survive; that the commit is one transaction without the overridden records; and that two windows in one statement are `API-011` from `tx.execute()` while the rest commits. A unit test checks the commit collapse keeps each fact's newest statement in order. A log-writer test checks that an inverted window is `API-019`, a second window of a fact in one transaction `API-011`, and an assertion and a retraction of one fact in one transaction `API-020` in either order, each leaving the writer usable and the output exact, while duplicate retractions, identical repeats and the same fact in the next transaction are accepted. Cursor tests (#432, `tests/cursor_test.rs`) check that `query()` batches partition the `execute()` answer for several batch sizes (never empty, never over `max_rows`, `max_rows == 0` still progresses, `None` stays `None`), that the iterator and aggregates, rules, `:as-of` and `:any-valid-time` match `execute()`, that a cursor opened before a `transact`, a `WriteTransaction` commit, a retract or a checkpoint returns the pre-write answer to the end (in memory and file-backed), that `transact`/`retract`/`rule` are `API-012` and bind slots `API-010`, that a `WriteTransaction` thread gets `INT-001`, that rule limits give `INT-020` as from `execute()`, that `PreparedQuery::query` matches `PreparedQuery::execute`, and that a cursor is `Send` and outlives its database handle. Fact-log tests (#430, `tests/fact_log_test.rs`) check that `fact_log()` returns exactly the records written (assertions and retractions, with `tx_count` and `tx_id`) in memory, with everything pending, half checkpointed, fully checkpointed and after reopen, in both orders, with windows of 1 to 1,000 records and batch sizes of 1 to 1,000, in non-decreasing `tx_count` in Tx order; that every layout gives identical records, including valid-time windows and long string values; that a transaction larger than the window is split with no loss or duplicate; that attribute, attribute-prefix, entity and tx-range filters and their combinations match a model, and unknown names match nothing; that writes after open are not in the log; that `checkpoint()` and `rebuild_indexes()` are `API-013` while a log is open (a checkpoint with nothing to write is allowed), that automatic checkpoints from `execute()` and `WriteTransaction::commit` wait for the log, and that closing, dropping or finishing the log releases the database; that a `WriteTransaction` thread gets `INT-001`; and that a log is `Send`, outlives its database handle, and the deferred writes replay on the next open. Read-only open tests (#429, `tests/read_only_open_test.rs`) check that a read-only handle on a file with checkpointed facts and a pending WAL returns the same query results, `tx_count` and fact log as a read-write open; that queries, a cursor, a fact log, `verify`, `prepare`, rules and a UDF leave the `.graph` and WAL bytes and the `.graph` mtime unchanged, and no WAL is created; that `transact`, `retract`, `begin_write`, `checkpoint` and `rebuild_indexes` are `API-014` without taking a `tx_count`, also on a read-only in-memory database and through the builder path; that a missing file is `STG-042` and nothing is created; that an empty file is an empty database and stays 0 bytes; that read-only handles share a file while a read-write one is refused with `STG-025`, both ways; that a file without write permission opens read-only; and that small and whole-file page caches work. File-backend unit tests check that a shared-mode backend refuses page writes and syncs with `INT-056`, that the in-process registry counts readers and admits readers or one writer (also without kernel locks), and that a reader in another process shares the file with a reader here and refuses a writer here with `STG-026`. Storage unit tests check that a read-only open of a v7 file at every point of an interrupted migration (clean and torn writes) sees every fact and writes nothing, and that an empty backend stays empty. `tests/golden_corpus_test.rs` opens a copy of every golden file read-only first and checks its `tx_count` and queries, and that neither the file nor its WAL changes. Log-writer tests (#431, `tests/log_writer_test.rs`) copy a source's fact log (assertions, retractions, an explicit valid-time window, long strings, refs, keywords, checkpointed and pending facts) through `LogWriter` and check that the new file has no `.partial` or WAL, verifies clean, and gives the source's `tx_count`, fact log and query results (current, `:valid-at`, `:any-valid-time`, every `:as-of`, and entity-, attribute- and value-bound lookups) read-write, read-only and after reopen (#370); that it takes new writes at the source's next `tx_count`; that 90,000 facts over two batch commits verify clean and count correctly at `:as-of`; that a purged middle transaction is a hole whose `:as-of` equals the one before, and trailing holes keep the counter through `advance_tx_count`; that an empty log is an empty database with the counter; that `tx_count` 0, a lower or closed transaction and a backwards advance are `API-015`, a second `tx_id` `API-016`, a second window `API-011`, a retraction of an asserted fact in one transaction `API-020`, an empty window `API-019` and oversize values or idents `WAL-003`, each leaving the writer usable and the output exact, with repeats written once; that an existing target or WAL is `STG-043`, a second writer `STG-025` and `read_only` `API-014`; that a stale `.partial` is reused; that dropping an unfinished writer leaves nothing; that `finish` refuses a target created during the build and leaves it untouched; and that `LogWriter` is `Send`. Unit tests check that a batch commits only when a transaction opens past the batch size, never splitting one, and that `FileBackend::truncate` empties a file. A unit test in `error.rs` checks that `MinigrafError::invalid_argument` and `MinigrafError::closed`, the constructors for language bindings, give API-017 and API-018 with their text. Query-validation tests (#406, #414) check that a plain `:find` variable or a window function's argument, `:partition-by` or `:order-by` variable that no `:where` clause binds (including `?_` wildcards) is `PRS-080` from both `execute()` and `prepare()`, naming the variable, while variables bound by a pattern, an attribute position, a rule call, an expression binding, an `or-join`, every branch of an `or`, a pseudo-attribute or a window spec are accepted, and bind slots are not mistaken for `:find` variables; and that an unknown aggregate is `QRY-010` and an unknown window function `QRY-011` on an empty database, when no row matches, when rows match, through a rule query and through a prepared query, while a registered UDF in either position returns an empty result on an empty database. Coverage-gate tests (#396) check that replay stops at a WAL entry whose first fact is longer than 10 MB or that claims more than 1M facts, that a WAL writer cannot be opened in a missing directory, and that a failed cut of a torn WAL tail fails the open and leaves the file as it was; that a short v7 page and a slot past the record count are `INT-024`; that a migration backup meta of another generation or file length is not used (`STG-032`, file unchanged), and a torn first meta with data in page 1 is `STG-032`, not a new file; that `save` with nothing pending writes nothing, `into_backend` saves pending facts, and `rebuild_indexes` with nothing checkpointed commits the pending facts; and that unsorted or repeated B+tree input and a stored key inserted with another value are `INT-049`, a tree pointer to a free-list page is `STG-013` from `get`, a leaf walk and a copy-on-write insert, and the read-only `MutexStorageBackend` refuses writes, syncs and close. A page-cache test holds two threads in the backend read so both miss the same page, and checks that both get the one cached copy; before it, that path ran only when the scheduler happened to race the threads, and the gate flapped. Three `BrowserDb` tests (wasm32, run with `wasm-bindgen-test` in a browser, not counted above) check that `query()` batches of 1, 7 and 1,000 give the rows of `execute()`, that a cursor keeps the answer from when it opened and returns the end after `close()`, and that a `transact` is API-012. The wasm32 targets run in CI (`.github/workflows/wasm.yml`). In a browser (`wasm-pack test --headless`, Firefox and Chrome): 32 `wasm_bindgen_test` tests: nineteen for `BrowserDb` (including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read, from #470), eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before), and two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. Five of the `BrowserDb` tests (#411, #440) check that opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open; that after each of 60 transacts memory, and at the end IndexedDB, hold exactly the pages not on the free list while the file grows by under one page per transact; that a commit applied in memory but never flushed reopens at the previous one and keeps working; that an export after churn is as long as the meta says and imports back with its free pages dropped; and that `importGraph()` deletes the replaced database's IndexedDB keys. Two buffer tests check that releasing a page drops its bytes and any unflushed write, and that export writes a released page as zeros. A native storage test checks that a file whose free pages are all zeros (as the browser exports them), both just migrated from v7 and after 20 saves, opens, verifies clean and keeps committing, and the free-list test checks that a checkpoint reports exactly the ids it newly lists. On `wasm32-wasip1` under Wasmtime: the unit and integration tests that do not use a file run, 956 passing; ten that spawn threads or a child process are ignored on WASI. These are not counted above. ### Covered Areas @@ -36,8 +36,13 @@ cargo test --quiet # Include the scheduled/ignored tests when the host supports them cargo test -- --include-ignored -# Generate a local branch-coverage report (requires cargo-llvm-cov) -cargo llvm-cov --branch --html +# Generate a local branch-coverage report (requires cargo-llvm-cov and a nightly toolchain) +cargo +nightly llvm-cov --branch --html + +# Check the per-file gates the way CI does +cargo +nightly llvm-cov --branch --no-report +cargo +nightly llvm-cov report --branch --json --summary-only --output-path coverage.json +python3 scripts/coverage_gates.py coverage-thresholds.toml coverage.json ``` -Coverage percentages are intentionally not fixed in this document: they depend on the current toolchain and instrumentation. The CI coverage gates and the command above are the source of truth for the current measurement. +Coverage percentages are intentionally not fixed in this document: they depend on the toolchain and instrumentation. `coverage-thresholds.toml` holds the per-file line and branch floors, measured with the nightly pinned in `.github/workflows/coverage-gates.yml`, and lists the paths left uncovered on purpose (#396). Delete `target/llvm-cov-target` after changing the toolchain or cargo-llvm-cov version: stale binaries from an older build are merged into the report and skew it. diff --git a/scripts/coverage_gates.py b/scripts/coverage_gates.py new file mode 100644 index 0000000000..a39eeb0f51 --- /dev/null +++ b/scripts/coverage_gates.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Check per-file coverage floors from coverage-thresholds.toml (#396). + +Usage: coverage_gates.py + +The JSON is `cargo llvm-cov report --branch --json --summary-only`. Every file +named in the thresholds must be in the report, with branch data when it has a +branch floor; a missing file or missing branch data fails the gate instead of +being skipped, so an empty or partial report can never pass. +""" + +import json +import sys +import tomllib + + +def main() -> int: + thresholds_path, report_path = sys.argv[1], sys.argv[2] + with open(thresholds_path, "rb") as f: + floors = tomllib.load(f)["files"] + with open(report_path) as f: + report = json.load(f) + + by_path = {} + for entry in report["data"][0]["files"]: + name = entry["filename"].replace("\\", "/") + for path in floors: + if name.endswith("/" + path): + by_path[path] = entry["summary"] + + failures = 0 + print(f"{'file':<40} {'metric':<9} {'covered':>8} {'floor':>6}") + for path, floor in floors.items(): + summary = by_path.get(path) + if summary is None: + print(f"{path:<40} FAIL: not in the coverage report") + failures += 1 + continue + for metric in ("lines", "branches"): + if metric not in floor: + continue + counts = summary.get(metric, {}) + if not counts.get("count"): + print(f"{path:<40} {metric:<9} FAIL: no {metric} data") + failures += 1 + continue + pct = counts["percent"] + ok = pct >= floor[metric] + failures += not ok + mark = "" if ok else " FAIL" + print(f"{path:<40} {metric:<9} {pct:>7.2f}% {floor[metric]:>5}%{mark}") + + if failures: + print(f"\n{failures} coverage gate(s) failed. Add tests, or list a path " + "left uncovered, with its reason, in the thresholds file; lower a " + "floor only with the reason in the PR.") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/storage/btree.rs b/src/storage/btree.rs index b55a67017c..453948e72b 100644 --- a/src/storage/btree.rs +++ b/src/storage/btree.rs @@ -1486,4 +1486,102 @@ mod tests { assert_eq!(alloc.next_append() - next, 3, "leaf + 2 internal nodes"); assert_eq!(freed.len(), 3); } + + fn code(e: anyhow::Error) -> &'static str { + crate::error::MinigrafError::from(e).code() + } + + #[test] + fn unsorted_or_repeated_input_is_int_049() { + let cache = PageCache::new(16); + for bad in [ + vec![entry(2, 1), entry(1, 1)], + vec![entry(1, 1), entry(1, 1)], + ] { + let mut backend = MemoryBackend::new(); + let mut alloc = PageAllocator::new(Vec::new(), 2, 1); + let err = build_btree(bad.clone(), &mut backend, &cache, &mut alloc).unwrap_err(); + assert_eq!(code(err), "INT-049"); + let (root, next) = build_at(vec![entry(5, 1)], &mut backend, &cache, 2); + let mut alloc = PageAllocator::new(Vec::new(), next, 2); + let mut freed = Vec::new(); + let err = + cow_insert(root, bad, &mut backend, &cache, &mut alloc, &mut freed).unwrap_err(); + assert_eq!(code(err), "INT-049"); + } + } + + #[test] + fn insert_of_a_stored_key_with_another_value_is_int_049() { + let cache = PageCache::new(16); + let mut backend = MemoryBackend::new(); + let (root, next) = build_at(vec![entry(1, 1)], &mut backend, &cache, 2); + let mut alloc = PageAllocator::new(Vec::new(), next, 2); + let mut freed = Vec::new(); + let same = cow_insert( + root, + vec![entry(1, 1)], + &mut backend, + &cache, + &mut alloc, + &mut freed, + ) + .unwrap(); + assert_eq!(stream_all_entries(same, &backend, &cache).unwrap().len(), 1); + let other = vec![(key(1, 1), vec![1u8])]; + let err = + cow_insert(root, other, &mut backend, &cache, &mut alloc, &mut freed).unwrap_err(); + assert_eq!(code(err), "INT-049"); + } + + /// A tree pointer to a page of another type (here a free-list page) is + /// STG-013 on every path that follows it. + #[test] + fn node_of_another_page_type_is_stg_013() { + let cache = PageCache::new(16); + let mut backend = MemoryBackend::new(); + let id = 2; + let mut page = crate::storage::page::new_page(crate::storage::page::PAGE_TYPE_FREELIST, 0); + crate::storage::page::seal(&mut page, id, 1).unwrap(); + backend.write_page(id, &page).unwrap(); + + assert_eq!( + code(get(id, &key(1, 1), &backend, &cache).unwrap_err()), + "STG-013" + ); + assert_eq!( + code(collect_leaf_pages(id, &backend, &cache, None).unwrap_err()), + "STG-013" + ); + let mut alloc = PageAllocator::new(Vec::new(), 3, 2); + let mut freed = Vec::new(); + let err = cow_insert( + id, + vec![entry(1, 1)], + &mut backend, + &cache, + &mut alloc, + &mut freed, + ) + .unwrap_err(); + assert_eq!(code(err), "STG-013"); + } + + #[test] + fn mutex_backend_reads_and_refuses_writes() { + let mut inner = MemoryBackend::new(); + inner.write_page(0, &[7u8; PAGE_SIZE]).unwrap(); + let mut b = MutexStorageBackend(Arc::new(Mutex::new(inner))); + assert_eq!(b.read_page(0).unwrap()[0], 7); + assert_eq!(b.page_count().unwrap(), 1); + assert!(b.holds_every_page()); + assert!(b.partial_page().unwrap().is_none()); + assert_eq!(b.backend_name(), "mutex-adapter"); + assert_eq!( + code(b.write_page(0, &[0u8; PAGE_SIZE]).unwrap_err()), + "INT-049" + ); + assert_eq!(code(b.sync().unwrap_err()), "INT-049"); + assert_eq!(code(b.close().unwrap_err()), "INT-049"); + } } diff --git a/src/storage/cache.rs b/src/storage/cache.rs index 63a36f8c0e..427d2592af 100644 --- a/src/storage/cache.rs +++ b/src/storage/cache.rs @@ -240,6 +240,58 @@ mod tests { p } + /// Holds every `read_page` until two are in flight, so two threads miss + /// the same page before either caches it. + struct BarrierBackend { + inner: MemoryBackend, + barrier: std::sync::Barrier, + } + + impl StorageBackend for BarrierBackend { + fn write_page(&mut self, page_id: u64, data: &[u8]) -> Result<()> { + self.inner.write_page(page_id, data) + } + fn read_page(&self, page_id: u64) -> Result> { + self.barrier.wait(); + self.inner.read_page(page_id) + } + fn sync(&mut self) -> Result<()> { + Ok(()) + } + fn page_count(&self) -> Result { + self.inner.page_count() + } + fn close(&mut self) -> Result<()> { + Ok(()) + } + fn backend_name(&self) -> &'static str { + "barrier" + } + } + + /// Two threads that miss the same page both load it; the second to take + /// the write lock returns the first one's cached copy. + #[test] + #[cfg_attr(target_os = "wasi", ignore = "spawns threads; WASI has no threads")] + fn test_concurrent_misses_share_one_cached_copy() { + let mut inner = MemoryBackend::new(); + inner.write_page(1, &make_page(1, 0x5A)).unwrap(); + let backend = BarrierBackend { + inner, + barrier: std::sync::Barrier::new(2), + }; + let cache = PageCache::new(4); + let (a, b) = std::thread::scope(|s| { + let a = s.spawn(|| cache.get_or_load(1, &backend).unwrap()); + let b = s.spawn(|| cache.get_or_load(1, &backend).unwrap()); + (a.join().unwrap(), b.join().unwrap()) + }); + assert!(Arc::ptr_eq(&a, &b), "one copy cached and returned to both"); + assert_eq!(a[MARK], 0x5A); + let cached = cache.get_or_load(1, &backend.inner).unwrap(); + assert!(Arc::ptr_eq(&a, &cached)); + } + #[test] fn test_cache_miss_loads_from_backend() { let mut backend = MemoryBackend::new(); diff --git a/src/storage/packed_pages.rs b/src/storage/packed_pages.rs index 4069c213c4..e82113af9d 100644 --- a/src/storage/packed_pages.rs +++ b/src/storage/packed_pages.rs @@ -175,6 +175,15 @@ mod tests { assert_eq!(crate::error::MinigrafError::from(err).code(), "STG-015"); } + #[test] + fn short_page_and_slot_past_the_count_are_int_024() { + let pages = pack_facts_v7(&[make_fact(1)]); + let err = read_slot_v7(&pages[0][..PAGE_SIZE - 1], 0).unwrap_err(); + assert_eq!(crate::error::MinigrafError::from(err).code(), "INT-024"); + let err = read_slot_v7(&pages[0], 1).unwrap_err(); + assert_eq!(crate::error::MinigrafError::from(err).code(), "INT-024"); + } + fn backend_with(pages: &[Vec]) -> MemoryBackend { let mut backend = MemoryBackend::new(); for (i, p) in pages.iter().enumerate() { diff --git a/src/storage/persistent_facts.rs b/src/storage/persistent_facts.rs index b36c422472..fb1a1ff07a 100644 --- a/src/storage/persistent_facts.rs +++ b/src/storage/persistent_facts.rs @@ -1439,6 +1439,80 @@ mod tests { assert_eq!(code(open_mem(&mem, None).err().unwrap()), "STG-032"); } + /// The backup meta in the last page restores page 0 only if it is the + /// generation-1 meta of a file this long (spec §9 step 5). + #[test] + fn backup_meta_of_another_generation_or_length_is_not_used() { + let base = three_generations(); + let last = base.page_count().unwrap() - 1; + let m3 = match MetaPage::decode(&base.read_page(slot_page(3)).unwrap()) { + SlotState::Valid(m) => m, + _ => panic!("gen 3 valid"), + }; + let gen_2 = MetaPage { + generation: 2, + ..m3 + }; + let short = MetaPage::empty(1); + for backup in [gen_2, short] { + let mut mem = deep_copy(&base); + damage(&mut mem, 0); + damage(&mut mem, 1); + mem.write_page(last, &backup.encode()).unwrap(); + let before = snapshot(&mem); + assert_eq!(code(open_mem(&mem, None).err().unwrap()), "STG-032"); + assert!(snapshot(&mem) == before, "file unchanged"); + } + } + + /// A torn first meta write is a new file only while page 1 is blank. + #[test] + fn torn_initial_meta_with_data_in_page_1_is_stg_032() { + let mut mem = MemoryBackend::new(); + let mut page0 = MetaPage::empty(1).encode(); + let written = page0.iter().rposition(|&b| b != 0).unwrap(); + page0[written..].fill(0); + mem.write_page(0, &page0).unwrap(); + let mut page1 = vec![0u8; PAGE_SIZE]; + page1[7] = 1; + mem.write_page(1, &page1).unwrap(); + let before = snapshot(&mem); + assert_eq!(code(open_mem(&mem, None).err().unwrap()), "STG-032"); + assert!(snapshot(&mem) == before, "file unchanged"); + } + + #[test] + fn save_with_nothing_pending_writes_nothing() { + let mem = three_generations(); + let mut pfs = open_mem(&mem, None).unwrap(); + let before = snapshot(&mem); + pfs.save().unwrap(); + assert_eq!(pfs.generation(), 3); + assert!(snapshot(&mem) == before, "file unchanged"); + } + + #[test] + fn into_backend_saves_pending_changes() { + let mut pfs = PersistentFactStorage::new(MemoryBackend::new(), 16).unwrap(); + put_batch(&mut pfs, 0..5); + let mem = pfs.into_backend().unwrap(); + let pfs = open_mem(&mem, None).unwrap(); + assert_eq!(pfs.generation(), 2); + assert_eq!(count_n(&pfs), 5); + } + + #[test] + fn rebuild_with_nothing_checkpointed_commits_the_pending_facts() { + let mem = MemoryBackend::new(); + let mut pfs = PersistentFactStorage::new(mem.clone(), 16).unwrap(); + put_batch(&mut pfs, 0..5); + pfs.rebuild_indexes().unwrap(); + drop(pfs); + let pfs = open_mem(&mem, None).unwrap(); + assert_eq!(pfs.generation(), 2); + assert_eq!(count_n(&pfs), 5); + } + /// A file from a v3.0.0 development build before covering keys has valid /// meta pages but trees without a dictionary: refused, never misread. #[test] diff --git a/src/wal.rs b/src/wal.rs index eab0df8da5..98a37961ec 100644 --- a/src/wal.rs +++ b/src/wal.rs @@ -934,22 +934,59 @@ mod tests { writer.append_entry(1, &[fact]).unwrap(); writer.file.sync_all().unwrap(); - // Manually corrupt the WAL to have a fact larger than MAX_FACT_SIZE + // Overwrite the first fact's length, after the entry's checksum, + // tx_count and num_facts, with one just over MAX_FACT_SIZE. let mut file = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); - file.seek(std::io::SeekFrom::End(-20)).unwrap(); - // Overwrite the fact length to be huge - let huge_len: u32 = (10 * 1024 * 1024 + 1) as u32; // Just over MAX_FACT_SIZE + file.seek(std::io::SeekFrom::Start(WAL_HEADER_SIZE as u64 + 20)) + .unwrap(); + let huge_len: u32 = (10 * 1024 * 1024 + 1) as u32; file.write_all(&huge_len.to_le_bytes()).unwrap(); drop(file); - // Try to read - should fail gracefully + // Replay stops at the entry instead of allocating 10 MB. let mut reader = WalReader::open(&path).unwrap(); - let result = reader.read_entries(); - assert!( - result.is_err() || result.unwrap().is_empty(), - "Should fail or return empty on corrupted large fact" - ); + assert!(reader.read_entries().unwrap().is_empty()); + } + + #[test] + fn test_wal_entry_with_too_many_facts_ends_replay() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + wal_with_entries(&path, 2); + let one_len = { + let p = dir.path().join("one.wal"); + wal_with_entries(&p, 1).len() + }; + // Entry 2's num_facts, after its checksum and tx_count. + let mut file = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + file.seek(std::io::SeekFrom::Start(one_len as u64 + 12)) + .unwrap(); + file.write_all(&1_000_001u64.to_le_bytes()).unwrap(); + drop(file); + assert_eq!(tx_counts(&path), [1]); + } + + #[test] + fn test_wal_writer_open_fails_in_a_missing_directory() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("missing").join("test.wal"); + assert!(WalWriter::open_or_create(&path, SyncMode::Full).is_err()); + } + + #[test] + fn test_wal_writer_failed_tail_cut_leaves_the_wal_as_it_was() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let two = wal_with_entries(&path, 2); + let torn = &two[..two.len() - 1]; + std::fs::write(&path, torn).unwrap(); + + fault::arm(fault::Fault::Eio, 0); + assert!(WalWriter::open_or_create(&path, SyncMode::Full).is_err()); + assert_eq!(fault::disarm(), Some(Site::WalTruncate)); + assert!(std::fs::read(&path).unwrap() == torn, "nothing was cut"); + assert_eq!(tx_counts(&path), [1]); } // ── #360: WAL-0xx error code regression tests ──────────────────────────