From 25582a6de609f8e525d2ff613145db9fb899d2a9 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Sat, 10 Oct 2026 14:57:45 +0530 Subject: [PATCH] fix(wal): never append after a torn WAL entry (#513) WAL replay stops at the first partial or damaged entry, but the writer appended at the end of the file. After a crash during an append, the next session's commits went in after the partial entry, so a second crash before any checkpoint lost them although each was fsynced and reported committed. A failed append in a running process did the same to the next commit through that handle. - WalWriter::open_or_create_at cuts an existing WAL back to the end of its last valid entry and syncs it before appending (scan_entries, shared with WalReader::read_entries). - After a failed write or sync, the writer refuses every later append with the new WAL-007. A checkpoint (which deletes the WAL) or a reopen starts a clean writer. A rejected oversize fact (WAL-003) writes nothing and does not poison the writer. Tests: WAL unit tests for each torn-tail shape, a bad-checksum entry, an intact WAL left byte for byte, WAL-007 after a torn append (test-only hook), and WAL-003 not poisoning; a Minigraf test for WAL-007 from transact and commit and recovery by checkpoint; and a wal_test.rs integration test that crashes a child after a torn tail and checks the commit survives. Refs #513 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012wXxZguv7PgKQjMMH4yJ5h --- CHANGELOG.md | 1 + CLAUDE.md | 2 +- README.md | 2 +- docs/ERROR_REFERENCE.md | 18 +++ docs/TEST_COVERAGE.md | 4 +- src/db.rs | 50 +++++- src/error.rs | 9 ++ src/wal.rs | 336 +++++++++++++++++++++++++++++++--------- tests/wal_test.rs | 48 ++++++ 9 files changed, 388 insertions(+), 82 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c137168c..958b54159 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Queries no longer lose or duplicate facts when more than 65,535 facts are waiting for a checkpoint (#445; also fixed in v2.0.3). - **A file shorter than its meta page count is refused at open with `STG-044`** (#497). Open never compared the meta page's `page_count` with the file's length. A truncated file (an interrupted copy, a partial download) opened, and its queries and checkpoints then failed with `INT-049` after the WAL had accepted writes. A meta with a `page_count` far past the end opened too: its next checkpoint wrote at that page id, leaving a sparse file of up to 4 EiB, and `verify()` scanned to that count and never finished. Open now refuses both, read-write and read-only, without modifying the file. It does not fall back to the other meta page, because a valid newer meta means that checkpoint happened. A checkpoint now fails with `INT-049` instead of writing a meta that counts pages the backend does not hold, and `verify()` reports a `page_count` past the end as `STG-044` and stops its page scan at the end of the file. `BrowserDb` is not checked: it keeps only live pages (#440), so its store has no length to compare. New code `STG-044`. - **A file shorter than one page is refused at open with `STG-045` unless it is a torn first write** (#506). Open treated any file under 4 KiB as a new database, because it holds no whole page, and a read-write open wrote a new empty database over it. A database cut below one page by an interrupted copy, or an unrelated file at the path, was silently replaced. Now such a file opens as a new database only when its bytes are zeros or a prefix of the first meta page a new database writes (what a crash during creation can leave, the rule a torn full page 0 already followed); anything else is `STG-045`, read-write and read-only, and the file is not modified. A zero-length file is still a new database. New code `STG-045`. +- **A commit made after a torn WAL entry is no longer lost on recovery** (#513). Recovery replays the WAL up to its first partial or damaged entry, but the writer appended after the end of the file. After a crash during an append, the next session's commits went in after the partial entry, so a second crash before any checkpoint lost them, although each had been fsynced and reported as committed. A failed append (short write, full disk, I/O error) did the same to the next commit through that handle. Opening a database for writing now cuts the WAL back to the end of its last valid entry, and syncs it, before anything is appended. After a failed append, every later write through that handle fails with the new `WAL-007` until the database is reopened or a `checkpoint()` succeeds. The transaction whose append failed is not applied; after a reopen it is either there in full (its entry reached the disk) or not at all. Affected every release since v0.5.0. - **A v7 fact page with a damaged type byte fails the upgrade with `STG-014`** (#496). Opening a v7 file skipped, without an error, any page in its fact-page range whose type byte was not the fact-page type. The read-write open then upgraded the file to v8 and freed the old v7 pages, so that page's facts were lost for good; the read-only open returned the same answer with them missing. A v2.x writer fills that range with fact pages only, so any other type there is damage: open now fails with `STG-014`, read-write and read-only, and leaves the v7 file as it was. v7 fact pages have no checksum of their own, so damage elsewhere in a page can still decode to wrong facts or fail with another code; keep a copy of a v7 file until it has opened under v3.0.0. - Reopening next to a WAL whose entries were all already checkpointed no longer rewinds the transaction counter, so later transactions no longer reuse `tx_count` values and `:as-of` history stays correct (#447; also fixed in v2.0.3). diff --git a/CLAUDE.md b/CLAUDE.md index 3a75b4a9a..7a58e8368 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -197,7 +197,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1386 tests** (1377 passing, 9 ignored; unit + integration + doc). +**1393 tests** (1384 passing, 9 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 14bde82ed..879da8352 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 1386 tests +cargo test # run 1393 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index 693ca35b1..720f03886 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -163,6 +163,7 @@ with no `CodedError` anywhere in its chain. | WAL-004 | Fact serialised size exceeds u32 range | WAL | | WAL-005 | WAL num_facts exceeds platform usize | WAL | | WAL-006 | Failed to delete WAL file | WAL | +| WAL-007 | Earlier WAL write failed on this handle | WAL | | API-001 | Write lock poisoned | Database API | | API-002 | Unexpected command variant in write path | Database API | | API-003 | Attribute must be a keyword | Database API | @@ -2392,6 +2393,23 @@ The WAL is replayed on open and deleted on checkpoint. --- +### WAL-007 Earlier WAL write failed on this handle + +**Error text**: `an earlier write to the WAL failed on this handle; reopen the database or call checkpoint() before writing again` + +**Cause**: A write or fsync of the `.wal` file failed earlier on this handle (for example a full disk or an I/O error), and that write returned its own error. The WAL may now end in a partial entry. Recovery stops at the first partial entry, so anything appended after it would be lost after a crash. Every later write through this WAL fails with WAL-007 instead. + +The transaction whose write failed was not applied in memory. Whether it is durable is unknown: if its entry reached the disk whole, it is replayed when the database is next opened; otherwise it is lost. It is never applied in part. + +**Resolution**: +- Fix the cause (free disk space, check the device), then reopen the database. Opening cuts off a partial entry at the end of the WAL. +- Or call `checkpoint()`. A successful checkpoint writes the committed facts to the `.graph` file and deletes the WAL; the next write starts a new one. The failed transaction is then gone for good. +- If the failed transaction matters, check after reopening whether it is there, and write it again if it is not. + +**Scenario**: The disk fills during `db.execute("(transact ...)")`, which fails with an I/O error. The next `transact` fails with WAL-007 until the database is reopened or `checkpoint()` succeeds. + +--- + ## API — Database API Errors API errors indicate a violated contract in how the public `Minigraf` or diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index cd7122833..fb9b7b97f 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,377 passing tests and 9 ignored tests (1,386 total) +**Result**: 1,384 passing tests and 9 ignored tests (1,393 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). 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. 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. ### Covered Areas diff --git a/src/db.rs b/src/db.rs index 4e0ccdaf1..ded7be338 100644 --- a/src/db.rs +++ b/src/db.rs @@ -621,8 +621,11 @@ impl Minigraf { /// replay the facts on next open. /// /// If the WAL write fails, an error is returned and the in-memory store is - /// left unchanged. The database remains consistent for subsequent in-process - /// operations. + /// left unchanged. The WAL may then end in a partial entry, so later writes + /// through this handle fail with WAL-007 until the database is reopened or + /// a [`checkpoint`](Self::checkpoint) succeeds; reads keep working. Whether + /// the failed transaction is durable is unknown: after a reopen it is there + /// in full or not at all. /// /// Returns `Err` if called from the same thread that holds an active /// `WriteTransaction` (use `tx.execute()` instead). @@ -2401,6 +2404,49 @@ mod tests { ); } + // ── #513: a failed WAL append ───────────────────────────────────────────── + + /// A WAL append that fails part-way leaves its transaction unapplied and + /// refuses later writes with WAL-007, so nothing lands after the partial + /// entry. A checkpoint deletes the WAL and writes work again. + #[test] + fn test_failed_wal_append_refuses_writes_until_checkpoint() { + fn names(db: &Minigraf) -> usize { + match db + .execute("(query [:find ?n :where [?e :name ?n]])") + .unwrap() + { + QueryResult::QueryResults { results, .. } => results.len(), + _ => 0, + } + } + let dir = tempfile::tempdir().unwrap(); + let db_path = dir.path().join("test.graph"); + let db = Minigraf::open(&db_path).unwrap(); + db.execute("(transact [[:a :name \"A\"]])").unwrap(); + + crate::wal::tear_next_append(9); + db.execute("(transact [[:b :name \"B\"]])") + .expect_err("the torn append fails"); + assert_eq!(names(&db), 1, "the failed transaction is not applied"); + + let err = db + .execute("(transact [[:c :name \"C\"]])") + .expect_err("later writes are refused"); + assert_eq!(err.code(), "WAL-007"); + let mut tx = db.begin_write().unwrap(); + tx.execute("(transact [[:c :name \"C\"]])").unwrap(); + assert_eq!(tx.commit().unwrap_err().code(), "WAL-007"); + assert_eq!(names(&db), 1); + + db.checkpoint().unwrap(); + db.execute("(transact [[:d :name \"D\"]])").unwrap(); + assert_eq!(names(&db), 2); + drop(db); + let db = Minigraf::open(&db_path).unwrap(); + assert_eq!(names(&db), 2, "A and D survive reopen"); + } + // ── file-backed: checkpoint deletes WAL and updates main file ───────────── #[test] diff --git a/src/error.rs b/src/error.rs index 26c4467f4..7a83276dd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -195,6 +195,7 @@ pub(crate) enum ErrorCode { Wal004, Wal005, Wal006, + Wal007, Api001, Api002, Api003, @@ -1136,6 +1137,12 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "failed to delete WAL file {}: {}", ErrorCategory::Wal, ), + ( + ErrorCode::Wal007, + "WAL-007", + "an earlier write to the WAL failed on this handle; reopen the database or call checkpoint() before writing again", + ErrorCategory::Wal, + ), ( ErrorCode::Api001, "API-001", @@ -2021,6 +2028,7 @@ mod tests { | ErrorCode::Wal004 | ErrorCode::Wal005 | ErrorCode::Wal006 + | ErrorCode::Wal007 | ErrorCode::Api001 | ErrorCode::Api002 | ErrorCode::Api003 @@ -2244,6 +2252,7 @@ mod tests { ErrorCode::Wal004, ErrorCode::Wal005, ErrorCode::Wal006, + ErrorCode::Wal007, ErrorCode::Api001, ErrorCode::Api002, ErrorCode::Api003, diff --git a/src/wal.rs b/src/wal.rs index 57f97ae96..15d6324e5 100644 --- a/src/wal.rs +++ b/src/wal.rs @@ -163,6 +163,9 @@ pub struct WalEntry { pub struct WalWriter { file: File, sync_mode: SyncMode, + /// An append failed, so the file may end in a partial entry. Later + /// appends would land after it, where replay never reaches (#513). + failed: bool, } impl WalWriter { @@ -195,7 +198,11 @@ impl WalWriter { // durable too, or a power loss can lose the whole file (#389). sync_parent_dir(path)?; file.seek(SeekFrom::End(0))?; - return Ok(WalWriter { file, sync_mode }); + return Ok(WalWriter { + file, + sync_mode, + failed: false, + }); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} Err(e) => return Err(e.into()), @@ -206,6 +213,14 @@ impl WalWriter { match check_wal_header_length(&mut file)? { WalHeaderState::Present => { validate_wal_header(&mut file)?; + // A crash during an append can leave a partial entry at the + // end. Replay stops there, so an entry appended after it + // would be lost: cut it off before appending (#513). + let (_, valid_end) = scan_entries(&mut file)?; + if file.metadata()?.len() > valid_end { + file.set_len(valid_end)?; + file.sync_all()?; + } } // A previous crash landed between this file's creation and its // header write completing; no entry could have been appended @@ -218,7 +233,11 @@ impl WalWriter { } } file.seek(SeekFrom::End(0))?; - Ok(WalWriter { file, sync_mode }) + Ok(WalWriter { + file, + sync_mode, + failed: false, + }) } /// The `SyncMode` this writer was opened with. Used only in tests, to @@ -233,9 +252,32 @@ impl WalWriter { /// The entry is written atomically from the caller's perspective: /// a partial write produces a bad CRC32, which the reader discards. /// Then flushes to disk, unless `sync_mode` is `SyncMode::Normal` — see [`SyncMode`]. + /// + /// After a failed write or sync, every later append fails with WAL-007: + /// the file may end in a partial entry, and replay stops there (#513). A + /// new writer (after a checkpoint deletes the WAL, or on reopen) starts + /// clean. Whether the failed entry itself is durable is unknown: it is + /// replayed on reopen if it reached the disk whole, and lost otherwise. pub fn append_entry(&mut self, tx_count: u64, facts: &[Fact]) -> Result<()> { + if self.failed { + bail_coded!(ErrorCode::Wal007); + } let entry_bytes = serialize_entry(tx_count, facts)?; - self.file.write_all(&entry_bytes)?; + let written = self.write_entry(&entry_bytes); + if written.is_err() { + self.failed = true; + } + written + } + + fn write_entry(&mut self, entry_bytes: &[u8]) -> Result<()> { + #[cfg(test)] + if let Some(n) = TEAR_NEXT_APPEND.take() { + self.file + .write_all(&entry_bytes[..n.min(entry_bytes.len())])?; + return Err(io::Error::other("test: torn WAL append").into()); + } + self.file.write_all(entry_bytes)?; match self.sync_mode { SyncMode::Full => self.file.sync_data()?, SyncMode::Normal => {} @@ -278,6 +320,20 @@ impl WalWriter { } } +// Test-only: the next append on this thread writes only the first `n` bytes +// of its entry, then fails, as a short write or a full disk would. +#[cfg(test)] +thread_local! { + static TEAR_NEXT_APPEND: std::cell::Cell> = + const { std::cell::Cell::new(None) }; +} + +/// Make the next WAL append on this thread write `n` bytes and fail. +#[cfg(test)] +pub(crate) fn tear_next_append(n: usize) { + TEAR_NEXT_APPEND.set(Some(n)); +} + // ─── WalReader ────────────────────────────────────────────────────────────── /// Reads and validates WAL entries for crash recovery. @@ -319,95 +375,104 @@ impl WalReader { /// with an invalid CRC32 (partial write) or at EOF. Earlier entries are /// unaffected by a bad entry. pub fn read_entries(&mut self) -> Result> { - self.file.seek(SeekFrom::Start(WAL_HEADER_SIZE as u64))?; - let mut entries = Vec::new(); - - loop { - // Read checksum (4 bytes); EOF here means no more entries - let mut csum_buf = [0u8; 4]; - match self.file.read_exact(&mut csum_buf) { - Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break, - Err(e) => return Err(e.into()), - Ok(()) => {} - } - let expected_csum = u32::from_le_bytes(csum_buf); + Ok(scan_entries(&mut self.file)?.0) + } +} - // Read tx_count (8 bytes) - let mut tx_count_buf = [0u8; 8]; - if self.file.read_exact(&mut tx_count_buf).is_err() { - break; // truncated - } - let tx_count = u64::from_le_bytes(tx_count_buf); +/// Read every valid entry after the header, stopping at the first truncated +/// or corrupt one or at EOF. Also returns the offset where the valid entries +/// end: the end of the header if there are none. +fn scan_entries(file: &mut File) -> Result<(Vec, u64)> { + file.seek(SeekFrom::Start(WAL_HEADER_SIZE as u64))?; + let mut entries = Vec::new(); + let mut valid_end = WAL_HEADER_SIZE as u64; + + loop { + // Read checksum (4 bytes); EOF here means no more entries + let mut csum_buf = [0u8; 4]; + match file.read_exact(&mut csum_buf) { + Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break, + Err(e) => return Err(e.into()), + Ok(()) => {} + } + let expected_csum = u32::from_le_bytes(csum_buf); - // Read num_facts (8 bytes) - let mut num_facts_buf = [0u8; 8]; - if self.file.read_exact(&mut num_facts_buf).is_err() { - break; // truncated - } - let num_facts = usize::try_from(u64::from_le_bytes(num_facts_buf)) - .map_err(|_| err_coded!(ErrorCode::Wal005))?; + // Read tx_count (8 bytes) + let mut tx_count_buf = [0u8; 8]; + if file.read_exact(&mut tx_count_buf).is_err() { + break; // truncated + } + let tx_count = u64::from_le_bytes(tx_count_buf); - // Sanity cap: no legitimate entry has more than 1M facts - const MAX_FACTS_PER_ENTRY: usize = 1_000_000; - if num_facts > MAX_FACTS_PER_ENTRY { - break; // treat as corrupt entry - } + // Read num_facts (8 bytes) + let mut num_facts_buf = [0u8; 8]; + if file.read_exact(&mut num_facts_buf).is_err() { + break; // truncated + } + let num_facts = usize::try_from(u64::from_le_bytes(num_facts_buf)) + .map_err(|_| err_coded!(ErrorCode::Wal005))?; - // Maximum fact size to prevent memory exhaustion from large facts - const MAX_FACT_SIZE: usize = 10 * 1024 * 1024; // 10MB + // Sanity cap: no legitimate entry has more than 1M facts + const MAX_FACTS_PER_ENTRY: usize = 1_000_000; + if num_facts > MAX_FACTS_PER_ENTRY { + break; // treat as corrupt entry + } - // Build payload for CRC32 verification - let mut payload = Vec::new(); - payload.extend_from_slice(&tx_count_buf); - payload.extend_from_slice(&num_facts_buf); + // Maximum fact size to prevent memory exhaustion from large facts + const MAX_FACT_SIZE: usize = 10 * 1024 * 1024; // 10MB + + // Build payload for CRC32 verification + let mut payload = Vec::new(); + payload.extend_from_slice(&tx_count_buf); + payload.extend_from_slice(&num_facts_buf); + + // Read each fact + let mut facts = Vec::new(); // grow dynamically instead of pre-allocating + let mut truncated = false; + for _ in 0..num_facts { + let mut len_buf = [0u8; 4]; + if file.read_exact(&mut len_buf).is_err() { + truncated = true; + break; + } + let fact_len = u32::from_le_bytes(len_buf) as usize; + if fact_len > MAX_FACT_SIZE { + truncated = true; + break; + } + payload.extend_from_slice(&len_buf); - // Read each fact - let mut facts = Vec::new(); // grow dynamically instead of pre-allocating - let mut truncated = false; - for _ in 0..num_facts { - let mut len_buf = [0u8; 4]; - if self.file.read_exact(&mut len_buf).is_err() { - truncated = true; - break; - } - let fact_len = u32::from_le_bytes(len_buf) as usize; - if fact_len > MAX_FACT_SIZE { - truncated = true; - break; - } - payload.extend_from_slice(&len_buf); + let mut fact_bytes = vec![0u8; fact_len]; + if file.read_exact(&mut fact_bytes).is_err() { + truncated = true; + break; + } + payload.extend_from_slice(&fact_bytes); - let mut fact_bytes = vec![0u8; fact_len]; - if self.file.read_exact(&mut fact_bytes).is_err() { + match postcard::from_bytes::(&fact_bytes) { + Ok(f) => facts.push(f), + Err(_) => { truncated = true; break; } - payload.extend_from_slice(&fact_bytes); - - match postcard::from_bytes::(&fact_bytes) { - Ok(f) => facts.push(f), - Err(_) => { - truncated = true; - break; - } - } - } - - if truncated { - break; } + } - // Verify CRC32 over the full payload - let actual_csum = crc32fast::hash(&payload); - if expected_csum != actual_csum { - break; // corrupted entry — stop here - } + if truncated { + break; + } - entries.push(WalEntry { tx_count, facts }); + // Verify CRC32 over the full payload + let actual_csum = crc32fast::hash(&payload); + if expected_csum != actual_csum { + break; // corrupted entry — stop here } - Ok(entries) + entries.push(WalEntry { tx_count, facts }); + valid_end = file.stream_position()?; } + + Ok((entries, valid_end)) } // ─── Unit tests ───────────────────────────────────────────────────────────── @@ -679,6 +744,125 @@ mod tests { assert_eq!(entries[0].tx_count, 1); } + // ── #513: torn tail and failed appends ───────────────────────────────── + + /// The bytes of a WAL holding entries `1..=n`. + fn wal_with_entries(path: &Path, n: u64) -> Vec { + let mut writer = WalWriter::open_or_create(path, SyncMode::Full).unwrap(); + for tx in 1..=n { + let fact = make_fact(Uuid::new_v4(), ":name", Value::Integer(tx as i64), tx); + writer.append_entry(tx, &[fact]).unwrap(); + } + drop(writer); + std::fs::read(path).unwrap() + } + + fn tx_counts(path: &Path) -> Vec { + let mut reader = WalReader::open(path).unwrap(); + let entries = reader.read_entries().unwrap(); + entries.iter().map(|e| e.tx_count).collect() + } + + #[test] + fn test_wal_writer_cuts_off_torn_tail_before_appending() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let two = wal_with_entries(&path, 2); + let one_len = { + let p = dir.path().join("one.wal"); + wal_with_entries(&p, 1).len() + }; + let second = two.len() - one_len; + for cut in [1, 4, 12, 20, second - 1] { + std::fs::write(&path, &two[..one_len + cut]).unwrap(); + let mut writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().len(), + one_len as u64, + "the partial entry is cut off on open" + ); + let fact = make_fact(Uuid::new_v4(), ":name", Value::Integer(7), 7); + writer.append_entry(7, &[fact]).unwrap(); + drop(writer); + assert_eq!(tx_counts(&path), [1, 7], "the new entry is reachable"); + } + } + + #[test] + fn test_wal_writer_cuts_off_entry_with_bad_checksum() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let mut bytes = wal_with_entries(&path, 3); + let one_len = { + let p = dir.path().join("one.wal"); + wal_with_entries(&p, 1).len() + }; + // Damage entry 2; entry 3 after it is unreachable and goes too. + bytes[one_len] ^= 0xFF; + std::fs::write(&path, &bytes).unwrap(); + let writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + drop(writer); + assert_eq!(std::fs::metadata(&path).unwrap().len(), one_len as u64); + assert_eq!(tx_counts(&path), [1]); + } + + #[test] + fn test_wal_writer_keeps_an_intact_wal() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let bytes = wal_with_entries(&path, 3); + let writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + drop(writer); + assert!(std::fs::read(&path).unwrap() == bytes, "nothing to cut"); + } + + #[test] + fn test_wal_failed_append_refuses_later_appends_with_wal_007() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let mut writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + let fact = |tx: u64| make_fact(Uuid::new_v4(), ":name", Value::Integer(1), tx); + writer.append_entry(1, &[fact(1)]).unwrap(); + + tear_next_append(10); + writer + .append_entry(2, &[fact(2)]) + .expect_err("the torn append fails"); + let err: crate::error::MinigrafError = writer + .append_entry(3, &[fact(3)]) + .expect_err("later appends are refused") + .into(); + assert_eq!(err.code(), "WAL-007"); + drop(writer); + assert_eq!(tx_counts(&path), [1], "nothing after the torn entry"); + + // A new writer cuts off the partial entry and appends normally. + let mut writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + writer.append_entry(4, &[fact(4)]).unwrap(); + drop(writer); + assert_eq!(tx_counts(&path), [1, 4]); + } + + #[test] + fn test_wal_rejected_entry_does_not_poison_the_writer() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("test.wal"); + let mut writer = WalWriter::open_or_create(&path, SyncMode::Full).unwrap(); + let huge = make_fact( + Uuid::new_v4(), + ":name", + Value::String("x".repeat(MAX_VALUE_BYTES + 1)), + 1, + ); + writer + .append_entry(1, &[huge]) + .expect_err("WAL-003, before anything is written"); + let fact = make_fact(Uuid::new_v4(), ":name", Value::Integer(1), 2); + writer.append_entry(2, &[fact]).unwrap(); + drop(writer); + assert_eq!(tx_counts(&path), [2]); + } + #[test] fn test_wal_delete_file() { let dir = tempfile::tempdir().unwrap(); diff --git a/tests/wal_test.rs b/tests/wal_test.rs index 79e3f6191..c801f342b 100644 --- a/tests/wal_test.rs +++ b/tests/wal_test.rs @@ -741,6 +741,54 @@ fn wal_corrupt_tail_never_applied() { assert_eq!(names.len(), 1, "fake entry must not create phantom facts"); } +/// A crash during an append leaves a torn entry at the end of the WAL. The +/// next session's commits must not be appended after it, or recovery stops +/// at the torn entry and loses them after a second crash (#513). +#[test] +fn wal_commit_after_torn_tail_survives_second_crash() { + // A second entry to tear: the WAL of a session that wrote two facts. + let (_template_dir, template_path, one_entry) = setup_db_with_one_fact(); + run_crashing_child( + &template_path, + 1000, + &[r#"(transact [[:e9 :name "Torn"]])"#], + CrashTx::Implicit, + ); + let two_entries = read_wal_bytes(&template_path); + let second_entry = &two_entries[one_entry.len()..]; + assert!(second_entry.len() > 12, "second entry too short to tear"); + let mut bad_crc = second_entry.to_vec(); + bad_crc[0] ^= 0xFF; + + let tails: [(&str, Vec); 4] = [ + ("partial checksum", second_entry[..2].to_vec()), + ("partial header", second_entry[..10].to_vec()), + ( + "partial payload", + second_entry[..second_entry.len() - 3].to_vec(), + ), + ("bad checksum", bad_crc), + ]; + for (name, tail) in tails { + let (_dir, db_path, mut torn) = setup_db_with_one_fact(); + torn.extend_from_slice(&tail); + write_wal_bytes(&db_path, &torn); + run_crashing_child( + &db_path, + 1000, + &[r#"(transact [[:e2 :name "Bob"]])"#], + CrashTx::Implicit, + ); + let mut names = query_names(&db_path); + names.sort(); + assert_eq!( + names, + ["Alice", "Bob"], + "a commit after a torn tail must survive ({name})" + ); + } +} + // ══ #214 lock-leak tests ══════════════════════════════════════════════════ #[test]