diff --git a/CHANGELOG.md b/CHANGELOG.md index e4538e76e2..7bd187de5b 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 - A retract that removes several values of one attribute in one call now hides all of them (#371). - 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 WAL from a later checkpoint is refused at open with `STG-047`** (#535). Opening an older `.graph` next to a `.wal` created after a later checkpoint, as happens when a backup is restored and the current WAL is left in place, replayed the WAL on top of the older file and reported success: the later transactions were applied and the ones between the two checkpoints were silently missing, and the next checkpoint made the gap permanent. The WAL's header records the generation it was created at; open now refuses, read-write and read-only, when that is newer than every meta page in the file, and leaves both files unmodified. A WAL with an older base (a crash between a checkpoint's commit and its WAL delete) replays as before. v2.x WALs record no generation, so v2.x cannot detect this. - **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 failed checkpoint is never retried on the same handle** (#390). A checkpoint that failed after it may have written (a failed write, a full disk, a failed `fsync`) could be retried by the next checkpoint. After a failed `fsync` the operating system may have dropped the written pages, and the checkpoint's meta page may have reached the disk although the call failed; a retry could then overwrite pages that meta references, and a crash during the retry left a file that failed to read with `STG-029`. Now every later write, checkpoint and index rebuild through that handle fails with the new `STG-046`, queries keep working, and the close-time checkpoint is skipped. Reopening the database recovers everything committed: it is all in the WAL. A `rebuild_indexes()` refused with `STG-041` writes nothing and does not count as failed. A fault-injection matrix now covers EIO, torn and short writes, a full disk and failed fsyncs at every write and sync of transacts, checkpoints, the close-time checkpoint and index rebuilds. - **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. diff --git a/CLAUDE.md b/CLAUDE.md index bc63cf4343..9d83947a8e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -201,7 +201,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1428 tests** (1418 passing, 10 ignored; unit + integration + doc). +**1432 tests** (1422 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 89cf2de4b2..2368a3ce09 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 1428 tests +cargo test # run 1432 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/DURABILITY.md b/docs/DURABILITY.md index 16f39f15c4..704d969f10 100644 --- a/docs/DURABILITY.md +++ b/docs/DURABILITY.md @@ -54,7 +54,7 @@ Batching is the other lever: `begin_write()`, several `execute()` calls and one Opening a file-backed database: 1. Takes the file lock (see [Where a database can live](#where-a-database-can-live)). A lock held by a crashed process is released by the kernel when it dies, so there is never a stale lock to clean up. -2. Reads both meta pages and opens at the valid one with the higher generation. If only one is valid, the WAL's recorded base generation and the pages in the file are checked to make sure the damaged one did not hold a newer completed checkpoint; if it did, the open fails with `STG-033` instead of silently going back. +2. Reads both meta pages and opens at the valid one with the higher generation. If only one is valid, the WAL's recorded base generation and the pages in the file are checked to make sure the damaged one did not hold a newer completed checkpoint; if it did, the open fails with `STG-033` instead of silently going back. If the WAL was created at a later generation than the newest meta page, it belongs to a later state of the file and the open fails with `STG-047` (#535). 3. Checks the meta page against the file: unknown feature bits are `STG-034`, a file shorter than the meta page says is `STG-044`. 4. Replays the WAL into memory, skipping entries at or below the file's checkpointed transaction count, and stopping at the first truncated or damaged entry. 5. For a read-write open, cuts the WAL back to the end of its last valid entry and syncs it, so the next commit lands where replay will find it (#513). @@ -134,7 +134,7 @@ A process that does not have the database open can do the same through a read-on 1. Stop every process that uses the database. 2. Move the current `app.graph` and `app.graph.wal` aside rather than deleting them. -3. **Make sure no `app.graph.wal` is left in the directory**, then copy in the backup's `app.graph`, and its `app.graph.wal` if the backup has one. A WAL from a later state of the database, next to an older `app.graph`, is replayed on top of it today and leaves a gap in the history without an error (#535). +3. **Make sure no `app.graph.wal` is left in the directory**, then copy in the backup's `app.graph`, and its `app.graph.wal` if the backup has one. A WAL from a later state of the database, next to an older `app.graph`, would leave a gap in the history; open refuses it with `STG-047` (#535). v2.x cannot detect it and replays it. 4. Open the database and run `verify()` (below). ## Checking and repairing a file @@ -191,13 +191,12 @@ Every error has a code (`MinigrafError::code()`); the [error reference](https:// | **Use another library version.** The file is not modified | `STG-006` (format newer than this library), `STG-034` (feature bits from a newer v3.x), `STG-028` (format older than v7: open with v2.x first), `WAL-002` (WAL from another version: open with that version and `checkpoint()`) | | **Repair.** Found by `verify()` | `STG-035`, `STG-038`, `STG-039` → `rebuild_indexes()`. `STG-036`, `STG-040` → restore | | **Restore from backup.** The file is damaged or is not this database; a failed open leaves it unmodified | `STG-029`, `STG-030`, `STG-031` (a damaged page; inside an index, try `rebuild_indexes()` first), `STG-032`, `STG-033`, `STG-041`, `STG-044`, `STG-045`, `STG-002` (not a Minigraf file: check the path) | -| **Restore, or accept losing the WAL** | `WAL-001` (the `.wal` file is not a WAL). Copy both files first. Deleting the `.wal` opens the database without the transactions since the last checkpoint | +| **Restore, or accept losing the WAL** | `WAL-001` (the `.wal` file is not a WAL), `STG-047` (the `.wal` is from a later state than `app.graph`, usually a restore that left the current WAL in place: move the WAL aside, or restore the `app.graph` it belongs to). Copy both files first. Deleting the `.wal` opens the database without the transactions since the last checkpoint | A write that returns an I/O error may still have committed (see [Failures while running](#failures-while-running)); check before writing it again. ## Known limitations -- **A WAL from a later checkpoint is replayed onto an older `.graph`** (#535, open). Restoring an old `app.graph` next to a newer `app.graph.wal` leaves a silent gap in the history. Workaround: remove every `.wal` before restoring, as in [Restoring](#restoring). - **A damaged WAL entry ends replay.** Replay stops at the first entry whose CRC fails, and a read-write open then cuts the WAL there, so a bit flip in the middle of the WAL loses that entry and every later one without an error. With `SyncMode::Full` this needs damage after the sync; a torn entry from a crash is always the last one. - **One writing process at a time.** A database is single-writer; a second process gets `STG-026`. Share one handle inside a process, or put one process in front of the database. - **No online backup from another process.** A read-only open needs every read-write handle closed. Copy from inside the writing process (see [Backups](#backups)), or use a volume snapshot. diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index efec5b24fc..976e331360 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -158,6 +158,7 @@ with no `CodedError` anywhere in its chain. | STG-044 | File shorter than its meta page count | Storage | | STG-045 | File shorter than one page and not a new database | Storage | | STG-046 | Earlier checkpoint failed on this handle | Storage | +| STG-047 | WAL is from a later checkpoint | Storage | | WAL-001 | Invalid WAL magic number | WAL | | WAL-002 | Unsupported WAL version | WAL | | WAL-003 | Value size exceeds maximum | WAL | @@ -2324,6 +2325,20 @@ Nothing committed is lost. Every committed transaction is still in the WAL, and --- +### STG-047 WAL is from a later checkpoint + +**Error text**: `WAL is from a later checkpoint: it was created at generation {} but the file is at generation {}. Replaying it would leave a gap in the history (was an older .graph restored next to a newer .wal?)` + +**Cause**: The `.wal` file's header records the generation of the checkpoint that was current when the WAL was created. A WAL is deleted after the next checkpoint commits, so it is never newer than the `.graph` file it belongs to. This WAL is newer than every meta page in the file: the `.graph` is an older copy of the database, such as a restored backup, and the WAL beside it came from the live database. Its entries start after a checkpoint this file does not have, so replaying them would apply the later transactions and silently skip the ones in between. Earlier versions did that. Neither file is modified, read-write or read-only. v2.x WALs record no generation, so v2.x cannot detect this. + +**Resolution**: +- If you are restoring a backup: move the `.wal` aside and open again. The database opens at the backup. +- If the `.graph` was replaced by mistake: put back the `.graph` that the WAL belongs to. + +**Scenario**: An operator copies last night's `app.graph` over the current one and leaves the current `app.graph.wal` in the directory. + +--- + ## WAL — Write-Ahead Log Errors WAL errors relate to the sidecar `.wal` file written alongside the `.graph` file. diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 2d1e920558..73160518c6 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-11 with `cargo test --quiet` -**Result**: 1,418 passing tests and 10 ignored tests (1,428 total) +**Result**: 1,422 passing tests and 10 ignored tests (1,432 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. 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. A WAL test checks that a checkpoint with no facts to flush still removes a WAL whose entries are all already in the file, and the golden-corpus test now requires the WAL to be gone after a checkpoint for the `stale_wal` fixtures too (#457). A WAL test checks that closing a handle opened with `wal_checkpoint_threshold(usize::MAX)`, in both sync modes, leaves the `.graph` file byte for byte as it was and keeps the WAL, whose entries replay on the next open, and a unit test closes an in-memory handle under the same setting (#476). A recursive-rule test checks that a rule query on a database with more live facts than `max_results` returns its answer, with a bound and with a free first argument, and that a query deriving more facts than its `:max-results` is still `INT-020` (#528). A log-writer test runs the online backup from `docs/DURABILITY.md`: it copies a read-write handle with an uncheckpointed transaction through `fact_log` and `LogWriter` while another thread writes past the automatic checkpoint threshold, and checks that the copy verifies clean, holds exactly the records the log returned and the counter read after the log opened, and that every concurrent write reaches the source's file once the log is dropped (#398). diff --git a/src/error.rs b/src/error.rs index 964bbacb2d..09062d28a2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -190,6 +190,7 @@ pub(crate) enum ErrorCode { Stg044, Stg045, Stg046, + Stg047, Wal001, Wal002, Wal003, @@ -1108,6 +1109,12 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "an earlier checkpoint failed on this handle and is not retried; reopen the database", ErrorCategory::Storage, ), + ( + ErrorCode::Stg047, + "STG-047", + "WAL is from a later checkpoint: it was created at generation {} but the file is at generation {}. Replaying it would leave a gap in the history (was an older .graph restored next to a newer .wal?)", + ErrorCategory::Storage, + ), ( ErrorCode::Wal001, "WAL-001", @@ -2030,6 +2037,7 @@ mod tests { | ErrorCode::Stg044 | ErrorCode::Stg045 | ErrorCode::Stg046 + | ErrorCode::Stg047 | ErrorCode::Wal001 | ErrorCode::Wal002 | ErrorCode::Wal003 @@ -2255,6 +2263,7 @@ mod tests { ErrorCode::Stg044, ErrorCode::Stg045, ErrorCode::Stg046, + ErrorCode::Stg047, ErrorCode::Wal001, ErrorCode::Wal002, ErrorCode::Wal003, diff --git a/src/storage/persistent_facts.rs b/src/storage/persistent_facts.rs index e9fccc73d0..a995a74d6f 100644 --- a/src/storage/persistent_facts.rs +++ b/src/storage/persistent_facts.rs @@ -199,6 +199,7 @@ impl PersistentFactStorage { { bail_coded!(ErrorCode::Stg045, tail.len()); } + check_wal_not_later(1, wal_base)?; return Ok(Opened::Fresh); } let page0 = backend.read_page(0)?; @@ -211,9 +212,19 @@ impl PersistentFactStorage { match (slot_a, slot_b) { (SlotState::Valid(a), SlotState::Valid(b)) => { let m = if a.generation >= b.generation { a } else { b }; + check_wal_not_later(m.generation, wal_base)?; check_fits(&*backend, &m)?; Ok(Opened::Meta(m)) } + (SlotState::Valid(m), SlotState::Empty) | (SlotState::Empty, SlotState::Valid(m)) => { + // The other slot was never written, so no later generation + // was committed to this file. + check_wal_not_later(m.generation, wal_base)?; + m.check_features()?; + check_fits(&*backend, &m)?; + check_single_valid(&*backend, m, wal_base)?; + Ok(Opened::Meta(m)) + } (SlotState::Valid(m), _) | (_, SlotState::Valid(m)) => { // Refuse an unreadable file before probing its pages. m.check_features()?; @@ -223,6 +234,8 @@ impl PersistentFactStorage { } _ => { if let Some(h) = LegacyHeaderV7::detect(&page0)? { + // Migration opens at generation 1; a v2.x WAL reads as 1. + check_wal_not_later(1, wal_base)?; return Ok(Opened::LegacyV7(h)); } // A torn page-0 write while committing a migration: the backup @@ -232,6 +245,7 @@ impl PersistentFactStorage { && m.generation == 1 && m.page_count == page_count { + check_wal_not_later(1, wal_base)?; m.check_features()?; if !read_only { backend.write_page(0, &m.encode())?; @@ -240,6 +254,7 @@ impl PersistentFactStorage { return Ok(Opened::Meta(m)); } if page_count <= 2 && is_torn_initial_meta(&*backend, &page0)? { + check_wal_not_later(1, wal_base)?; return Ok(Opened::Fresh); } if page0.get(0..4) != Some(&crate::storage::MAGIC_NUMBER[..]) { @@ -801,6 +816,19 @@ fn check_written(backend: &dyn StorageBackend, m: &MetaPage) -> Result<()> { Ok(()) } +/// Fail with STG-047 if the WAL was created at a generation later than `g`, +/// the newest this file holds (#535). A WAL is created at the generation +/// active at the time and deleted after the next checkpoint commits, so its +/// base is never newer than the file it belongs to: the file is an older copy, +/// such as a restored backup. A base at or below `g` is fine (a crash between +/// a checkpoint's commit and its WAL delete leaves an older base, #457). +fn check_wal_not_later(g: u64, wal_base: Option) -> Result<()> { + match wal_base { + Some(b) if b > g => bail_coded!(ErrorCode::Stg047, b, g), + _ => Ok(()), + } +} + /// Exactly one meta slot is valid, at generation `g`. Fail with STG-033 if a /// later commit `g + 1` completed and its meta was lost (spec §4.1.1 table). fn check_single_valid( @@ -1353,6 +1381,49 @@ mod tests { assert_eq!(open_mem(&mem, Some(1)).unwrap().generation(), 2); } + #[test] + fn wal_from_a_later_generation_is_stg_047() { + // Both slots valid (gens 2 and 3): a WAL created at gen 4 belongs to + // a later state of the file, such as the one this copy was taken from. + let mem = three_generations(); + let before = snapshot(&mem); + assert_eq!(code(open_mem(&mem, Some(4)).err().unwrap()), "STG-047"); + let ro = PersistentFactStorage::open_read_only(mem.clone(), 16, Some(4)); + assert_eq!(code(ro.err().unwrap()), "STG-047"); + assert!( + snapshot(&mem) == before, + "a failed open must not modify the file" + ); + // A WAL at or below the chosen generation replays as before (#457). + for b in 1..=3 { + assert_eq!(open_mem(&mem, Some(b)).unwrap().generation(), 3); + } + } + + #[test] + fn wal_later_than_a_single_generation_file_is_stg_047() { + // Gen 1 only: page 1 was never written as a meta page. + let mem = MemoryBackend::new(); + assert_eq!(open_mem(&mem, None).unwrap().generation(), 1); + assert_eq!(open_mem(&mem, Some(1)).unwrap().generation(), 1); + assert_eq!(code(open_mem(&mem, Some(2)).err().unwrap()), "STG-047"); + } + + #[test] + fn wal_later_than_a_new_or_v7_file_is_stg_047() { + // An empty file next to a WAL from generation 2. + let mem = MemoryBackend::new(); + assert_eq!(code(open_mem(&mem, Some(2)).err().unwrap()), "STG-047"); + assert_eq!(mem.page_count().unwrap(), 0, "nothing initialised"); + assert_eq!(open_mem(&mem, Some(1)).unwrap().generation(), 1); + // A v7 file migrates to generation 1; a v2.x WAL reads as base 1. + let v7 = v7_file(&sample_facts(3), 3); + let before = snapshot(&v7); + assert_eq!(code(open_mem(&v7, Some(2)).err().unwrap()), "STG-047"); + assert!(snapshot(&v7) == before, "not migrated"); + assert_eq!(open_mem(&v7, Some(1)).unwrap().generation(), 1); + } + #[test] fn wal_newer_than_the_valid_meta_is_stg_033() { let mut mem = three_generations(); diff --git a/tests/integrity_test.rs b/tests/integrity_test.rs index 4ce4b5fa9a..1a453d92d4 100644 --- a/tests/integrity_test.rs +++ b/tests/integrity_test.rs @@ -249,3 +249,55 @@ fn meta_page_count_past_end_is_refused_and_file_never_grows() { "no WAL created" ); } + +/// Restoring an older `.graph` next to the current `.wal` (#535): the WAL was +/// created at a later checkpoint, so replaying it would leave a hole where the +/// transactions between the two checkpoints were. Open refuses with STG-047, +/// read-write and read-only, and leaves both files as they were. +#[test] +fn wal_from_a_later_checkpoint_is_refused() { + use minigraf::OpenOptions; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("a.graph"); + let wal = dir.path().join("a.graph.wal"); + let backup = dir.path().join("backup.graph"); + let opts = || OpenOptions::new().wal_checkpoint_threshold(usize::MAX); + { + let db = Minigraf::open_with_options(&path, opts()).unwrap(); + db.execute("(transact [[:a :n 1]])").unwrap(); + db.checkpoint().unwrap(); + } + // Offline backup: copy with no handle open (Windows refuses the read). + std::fs::copy(&path, &backup).unwrap(); + { + let db = Minigraf::open_with_options(&path, opts()).unwrap(); + for n in 2..=3 { + db.execute(&format!("(transact [[:a :n {n}]])")).unwrap(); + db.checkpoint().unwrap(); + } + db.execute("(transact [[:a :n 4]])").unwrap(); + // A usize::MAX threshold skips the close checkpoint: 4 stays in the WAL. + drop(db); + } + assert!(wal.exists(), "transaction 4 is in the WAL"); + std::fs::copy(&backup, &path).unwrap(); + let graph_before = std::fs::read(&path).unwrap(); + let wal_before = std::fs::read(&wal).unwrap(); + + let err = Minigraf::open_with_options(&path, opts()).err().unwrap(); + assert_eq!(err.code(), "STG-047"); + let err = Minigraf::open_with_options(&path, opts().read_only(true)) + .err() + .unwrap(); + assert_eq!(err.code(), "STG-047"); + assert!( + std::fs::read(&path).unwrap() == graph_before, + "file untouched" + ); + assert!(std::fs::read(&wal).unwrap() == wal_before, "WAL untouched"); + + // Removing the WAL, as the durability guide says, opens the backup. + std::fs::remove_file(&wal).unwrap(); + let db = Minigraf::open_with_options(&path, opts()).unwrap(); + assert_eq!(count(&db, "(query [:find ?v :where [?e :n ?v]])"), 1); +}