From 854807d8b513fedb1bdc09ee64a42437f8a00937 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Thu, 8 Oct 2026 12:22:23 +0530 Subject: [PATCH 1/2] test: SIGKILL crash test checks the committed data (#384) The child runs a seeded workload (multi-valued batches, batched retracts, re-assertions) under five checkpoint modes and logs each transaction after execute returns. After the kill, the reopened file must equal the model after the last logged transaction or the one in flight, through full-scan, AEVT, AVET, EAVT and :as-of queries, with verify clean; again after a second reopen and after a checkpoint plus reopen. Refs #384 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012wXxZguv7PgKQjMMH4yJ5h --- .github/workflows/crash-kill.yml | 7 +- CHANGELOG.md | 1 + ROADMAP.md | 2 +- docs/TEST_COVERAGE.md | 2 +- .../plans/2026-10-08-crash-kill-data-check.md | 24 + ...2026-10-08-crash-kill-data-check-design.md | 97 ++++ tests/crash_kill_test.rs | 474 +++++++++++++++--- 7 files changed, 542 insertions(+), 65 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-08-crash-kill-data-check.md create mode 100644 docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md diff --git a/.github/workflows/crash-kill.yml b/.github/workflows/crash-kill.yml index 3a78dfc1b1..fe66f61021 100644 --- a/.github/workflows/crash-kill.yml +++ b/.github/workflows/crash-kill.yml @@ -8,7 +8,10 @@ name: SIGKILL crash-safety fuzz (nightly) # matrix rather than Linux only. tests/crash_kill_test.rs runs a small # smoke count in the per-PR suite (rust.yml, already cross-platform); this # workflow runs a much larger round count nightly for statistical -# confidence on each OS. +# confidence on each OS. Since #384 each round also checks that the reopened +# file holds exactly the transactions the child confirmed (EAVT, AEVT, AVET, +# full scan, :as-of, verify). The test prints its base seed; replay a +# failure with MINIGRAF_CRASH_KILL_SEED. on: schedule: @@ -58,7 +61,7 @@ jobs: echo "- Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" echo "- Commit: $GITHUB_SHA" echo "- Reproduce: cargo test --test crash_kill_test -- --nocapture" - echo " (set MINIGRAF_CRASH_KILL_ROUNDS to raise the round count)" + echo " (set MINIGRAF_CRASH_KILL_ROUNDS to raise the round count; MINIGRAF_CRASH_KILL_SEED to the printed base seed to replay)" echo echo "## Test output" echo diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fcb1af784..5e4c868e7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Golden-file compatibility corpus (#391).** `tests/golden/` holds v7 files written by minigraf 2.0.3, each with a JSON manifest of its CRC32, `tx_count` and expected query results. They cover one checkpoint, several checkpoints, indexes rebuilt on open, a WAL left by a crash, a WAL whose entries were already checkpointed, and same-transaction multi-values (#371). `tests/golden_corpus_test.rs` opens a copy of each file and checks its manifest after open, after a checkpoint and reopen, and after one more write. Golden files are never regenerated, only added; a new `golden-corpus` job in `policy.yml` fails a pull request that changes one. The generator is a standalone crate pinned to `minigraf = "=2.0.3"` (`tests/golden/gen/v7/`). On `v3`, each v7 file must also carry a v8 meta page after its first open, and seven v8 files are frozen alongside them, written by the `v3` branch at `23aa57c` (`tests/golden/gen/v8/`): 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 (a 4,068-byte string stored twice, the 64/65-byte inline boundary, a 1,000-byte attribute and keyword). All #371 queries now pass. - **Model-based storage test (#385).** `tests/model_based_test.rs` runs random sequences of `transact` (multi-valued batches, transaction- and fact-level valid-time windows, a triple repeated with another window), `retract`, write transactions (committed or rolled back, retracting their own assertions), checkpoints, reopens (default, a 4-page cache, auto-checkpoint every 2 writes) and simulated crashes (a copy of the `.graph` file and WAL taken while the handle is open, so the WAL is replayed) against a file in a temp dir. After every step, `current_tx_count`, `verify`, full rows with windows and tx counts, and entity-, entity+attribute-, attribute-, attribute+value-, value-bound and full-scan queries, under `:as-of N` and `:valid-at T`, must match a plain reference model (one valid-time window per triple, #435; API-011 for two windows of one triple in one statement and API-019 for an empty or inverted window, from `execute` and `tx.execute`, #436; the last statement that writes a triple decides it at commit, #477). Reads inside a write transaction are checked against what its commit will hold. Normal CI runs 24 cases; the nightly property-test workflow runs 30,000. +- **SIGKILL crash test checks committed data (#384).** `tests/crash_kill_test.rs` used to check only that the file reopened and one attribute query ran, so it missed #370 and could not reach #371. The child now runs a seeded workload (multi-valued batches, batched retracts, re-assertions) and logs each transaction after `execute` returns; it checkpoints after every transaction, every third, never (WAL replay), automatically every 2 writes, or every third with `SyncMode::Normal`. After a `SIGKILL` at a random point, the reopened file must hold exactly the model after the last logged transaction or the one in flight, through a full scan, attribute (AEVT), attribute+value (AVET) and entity-bound (EAVT) queries and `:as-of`, with `verify` clean. The checks run again after a second reopen and after a checkpoint plus reopen. Per-PR CI runs 5 rounds (one per mode); the nightly crash-kill workflow runs 100 per OS. `MINIGRAF_CRASH_KILL_SEED` replays a failure. ## v2.0.3 — 2026-10-06 diff --git a/ROADMAP.md b/ROADMAP.md index 3b1e9871a9..394cd59340 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -77,7 +77,7 @@ Scope — query API: Scope — release-gate testing and documentation: - Golden-file compatibility corpus for every format version (#391; done on `v3`: six v7 files from 2.0.3 checked after migration, seven v8 files frozen at `23aa57c`) -- SIGKILL crash test that checks committed data through EAVT, AEVT and full scan (#384) +- SIGKILL crash test that checks committed data through EAVT, AEVT and full scan (#384; done on `v3`: `tests/crash_kill_test.rs`, 100 rounds per OS nightly) - Model-based test of transact/retract/checkpoint/reopen (#385; done on `v3`: `tests/model_based_test.rs`, 30,000 cases nightly) - Wider property tests: file-backed, batched, retracts, temporal, joins (#386) - Persistent fuzz corpus and an operation-sequence target (#387) diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index a0e0e2e64e..867c579d83 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -6,7 +6,7 @@ **Result**: 1,363 passing tests and 9 ignored tests (1,372 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). 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). 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/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). 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/docs/superpowers/plans/2026-10-08-crash-kill-data-check.md b/docs/superpowers/plans/2026-10-08-crash-kill-data-check.md new file mode 100644 index 0000000000..fa1550423a --- /dev/null +++ b/docs/superpowers/plans/2026-10-08-crash-kill-data-check.md @@ -0,0 +1,24 @@ +# SIGKILL crash test data check — Plan + +Spec: `docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md` (#384). + +1. **Generator and model** in `tests/crash_kill_test.rs`: a xorshift RNG seeded + per round; `Model { live: BTreeSet<(e, a, v)>, history: Vec> }`; + `next_tx(&mut rng, &model) -> (edn, new_live)`. The child and the parent + both drive it, so they produce the same statements. +2. **Child entrypoint** reads the env (db path, log path, seed, variant), opens + with the variant's options, loops: execute, append `k\n` to the log, + checkpoint per variant. +3. **Parent round**: spawn, poll the log until a random target count, jitter, + kill, reap, parse `N`. +4. **Checks**: tx count is `N` or `N + 1`; full scan, AEVT, EAVT, AVET equal + `M(T)`; `:as-of` samples; `verify()`. Run on reopen, second reopen, and + checkpoint + reopen. +5. **Self-check before relying on it**: break the model on purpose (drop the + last transaction from `M`) and confirm the test fails; then restore. +6. Run per-PR rounds and `MINIGRAF_CRASH_KILL_ROUNDS=200` locally; clippy, fmt. +7. Docs: test count in CLAUDE.md, README.md, docs/TEST_COVERAGE.md (the + replaced test keeps the count unless a test is added); comment in + `crash-kill.yml`. No CHANGELOG entry beyond the v3.0.0 test-suite line, if + one exists. +8. PR to `v3`, "Refs #384", monitor CI. diff --git a/docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md b/docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md new file mode 100644 index 0000000000..a1e6545c4e --- /dev/null +++ b/docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md @@ -0,0 +1,97 @@ +# SIGKILL crash test checks committed data — Design + +**Issue:** #384, tracker #383 +**Milestone:** v3.0.0, branch `v3` (test only; no library change) + +## 1. Goal + +`tests/crash_kill_test.rs` kills a child process mid-write and then only checks +that the file opens and that one AEVT query runs. It missed #370 (EAVT broken, +AEVT intact) and could not reach #371 (one fact per transaction). After this +change, every round checks that the data on disk is exactly the data the child +committed. + +## 2. Shape + +The test keeps its name and its parent/child structure, so `crash-kill.yml` +(nightly, 100 rounds on Linux, macOS and Windows) and the per-PR suite pick it +up unchanged. `sigkill_during_checkpoint_never_permanently_corrupts_file` is +replaced by `sigkill_keeps_exactly_the_committed_transactions`. + +Each round: + +1. Pick a seed and a workload variant (§4). Spawn the child with the database + path, a confirmation-log path, the seed and the variant. +2. The child runs transaction `k = 1, 2, …` from a deterministic generator + (§3). After `execute` returns, it appends `k\n` to the confirmation log with + one `write_all`. +3. The parent waits until the log holds a random target of 1–60 confirmed + transactions (poll every 1 ms, 30 s timeout), sleeps 0–20 ms more, then + kills the child (`SIGKILL` on Unix, `TerminateProcess` on Windows). +4. The parent reads the log. `N` is the last complete line (a line with no + newline is ignored). +5. Checks (§5) on: the first reopen; a second reopen; and a reopen after an + explicit `checkpoint()`. + +The confirmation log is not fsynced. A process kill does not drop the OS page +cache, so a written line survives the kill the same way the WAL entry does. +fsync would only slow the child down. + +## 3. Workload + +A transaction is one `execute`. The generator is a function of the seed and the +model state, so the parent rebuilds the same model by replaying it. + +- Pools: 4 keyword entities `:e0`–`:e3`, 3 attributes (`:a0`, `:a1`, + `:tag/丿`), values: integers 0–7 and two strings longer than the 64-byte + inline limit. +- **Multi-valued batch** (`transact`, 1–6 facts, ~60%): several values of one + entity and attribute in the same transaction (#371), plus random other facts. + Never the same triple twice in one transaction. +- **Batched retract** (`retract`, ~30%): 1–4 currently live triples. When + nothing is live, a batch is generated instead. +- **Re-assert** (~10%): a batch that asserts a triple retracted earlier. + +All facts use the default valid time. Valid-time behaviour is the model-based +test's job (#385). + +## 4. Variants + +The round number picks one, so every per-PR run covers them all: + +| Variant | Child loop | Kill lands in | +|---|---|---| +| `CheckpointEach` | transact, then `checkpoint()` | mostly `save()` | +| `CheckpointEvery(3)` | `checkpoint()` after every 3rd transaction | WAL append and `save()` | +| `WalOnly` | never checkpoints (`wal_checkpoint_threshold(usize::MAX)`) | WAL append; replay on reopen | +| `AutoCheckpoint` | `wal_checkpoint_threshold(2)` | auto-checkpoint inside `execute` | +| `NormalSync` | as `CheckpointEvery(3)` with `SyncMode::Normal` | same; no WAL fsync | + +## 5. Checks + +The model gives the live triples after `k` transactions, `M(k)`. On each +reopened handle: + +- `current_tx_count()` is `N` or `N + 1`. Call it `T`. `N + 1` means the + in-flight transaction reached the WAL or file before the kill but not the + log. Nothing beyond it can exist. +- Full scan `[?e ?a ?v]`, AEVT `[?e ?v]` per attribute, EAVT `[ ?a ?v]` + per entity, and AVET `[?e ]` per attribute and value: each, rendered + without UUIDs, equals the matching part of `M(T)`. The union over entities + and attributes must equal the full scan. +- `:as-of k` full scans for a few `k ≤ T` (1, `T/2`, `T - 1`) equal `M(k)`. +- `verify()` reports no problems. + +Failure messages name the round, seed, variant, `N` and `T`. Setting +`MINIGRAF_CRASH_KILL_SEED` replays one seed. Assert messages print no `Uuid` +bearing types (CLAUDE.md). + +## 6. Cost + +Per-PR: 5 rounds (one per variant), each well under a second. The nightly +workflow keeps its 100 rounds per OS. + +## 7. Out of scope + +Kills inside `begin_write`/`commit` (covered by the in-process crash tests in +`tests/common`), valid-time windows, and fault injection (#390). diff --git a/tests/crash_kill_test.rs b/tests/crash_kill_test.rs index b330990f97..2bcc0abdbf 100644 --- a/tests/crash_kill_test.rs +++ b/tests/crash_kill_test.rs @@ -1,39 +1,42 @@ -//! #308 regression: a `SIGKILL` during an active `transact`/`checkpoint` -//! must never permanently corrupt the database (header checksum mismatch, -//! no recovery path). +//! A `SIGKILL` at any point while a child process writes must leave the +//! database holding exactly the transactions the child had committed (#384). //! -//! Two fixes landed together, both closing the same class of bug -- a -//! multi-step on-disk state transition that a kill could land in the -//! middle of: -//! - `src/storage/backend/file.rs`: `FileBackend::write_page` now -//! recomputes `header_checksum` every time it persists a `page_count` -//! bump, so the on-disk header is self-consistent at every single-page -//! write, not just at the deliberate commits in -//! `PersistentFactStorage::save`. -//! - `src/wal.rs`: a WAL sidecar file shorter than its own header (a crash -//! between `create_new` and `write_wal_header` completing) is now -//! treated as an empty WAL instead of a hard read error, since no entry -//! could ever have been appended at that point. +//! The child runs a deterministic workload from a seed: multi-valued batches +//! (#371), batched retracts and re-assertions, with checkpoints at a rate set +//! by the round's variant. After each `execute` returns, it appends the +//! transaction's number to a confirmation log. The parent kills it at a random +//! point, replays the same workload into a reference model, and checks the +//! reopened file through the entity-bound (EAVT), attribute (AEVT), value +//! (AVET) and full-scan paths, `:as-of`, and `verify()`. The checks run again +//! after a second reopen and after a checkpoint plus reopen, to catch damage a +//! checkpoint copies forward. //! -//! This test reproduces the original report directly: spawn a child that -//! loops `transact` + `checkpoint()` on a fresh `.graph` file, kill it with -//! a real `SIGKILL` at a random point mid-loop, and confirm a fresh process -//! can still open the file afterward. +//! A transaction can reach the WAL or file before the kill and still miss the +//! log, so the reopened state is the model after `N` or `N + 1` transactions, +//! where `N` is the last confirmed one. Nothing else is allowed. //! -//! Round count is controlled by `MINIGRAF_CRASH_KILL_ROUNDS` (default: a -//! small smoke count so this runs unconditionally, cheaply, in the per-PR -//! suite). `.github/workflows/crash-kill.yml` runs a much larger nightly -//! count for statistical confidence, matching the ~26% per-round corruption -//! rate observed in the original report before the fix. +//! The log is not fsynced: a process kill keeps the OS page cache, so a +//! written line survives exactly as the WAL entry does. +//! +//! This also covers the original #308 report (a kill mid-checkpoint left a +//! header checksum mismatch): every round must reopen. +//! +//! Round count: `MINIGRAF_CRASH_KILL_ROUNDS` (default 5, one per variant; +//! `.github/workflows/crash-kill.yml` runs 100 nightly on each OS). Replay a +//! failure with the base seed it prints: `MINIGRAF_CRASH_KILL_SEED`. +//! +//! Design: docs/superpowers/specs/2026-10-08-crash-kill-data-check-design.md #![cfg(not(target_arch = "wasm32"))] -use minigraf::db::Minigraf; +use minigraf::db::{Minigraf, OpenOptions, SyncMode}; +use minigraf::{QueryResult, Value}; +use std::collections::{BTreeSet, HashMap}; +use std::io::Write; +use std::path::Path; use std::process::Command; use std::time::{Duration, Instant}; +use uuid::Uuid; -/// Per-PR default: cheap enough to run on every CI build, but with a ~1 - -/// 0.74^5 ≈ 78% chance of catching a reintroduced bug at the original 26% -/// per-round corruption rate. const DEFAULT_ROUNDS: usize = 5; fn rounds() -> usize { @@ -43,36 +46,357 @@ fn rounds() -> usize { .unwrap_or(DEFAULT_ROUNDS) } -/// Cheap, dependency-free jitter for the kill delay. No cryptographic -/// requirement here -- just enough spread across the checkpoint loop's -/// write window to land the kill at varying points mid-`save()`. -fn jitter_millis(seed: u64, max: u64) -> u64 { - let mut x = seed ^ 0x9E37_79B9_7F4A_7C15; - x ^= x << 13; - x ^= x >> 7; - x ^= x << 17; - x % max.max(1) +// ── Workload ────────────────────────────────────────────────────────────────── + +const ENTITIES: u8 = 4; +const ATTRS: [&str; 3] = [":a0", ":a1", ":tag/丿"]; +/// Values 0..8 are integers; 8 and 9 are strings over the 64-byte inline limit +/// that share a 40-byte prefix. +const VALUES: u8 = 10; + +fn long_string(i: u8) -> String { + format!( + "{}{}", + "p".repeat(40), + if i == 8 { "A" } else { "B" }.repeat(40) + ) +} + +fn value_edn(v: u8) -> String { + if v < 8 { + v.to_string() + } else { + format!("\"{}\"", long_string(v)) + } +} + +fn value_render(v: u8) -> String { + if v < 8 { + format!("i{v}") + } else { + format!("s{v}") + } +} + +/// An `(entity, attribute, value)` triple, as pool indices. +type Triple = (u8, u8, u8); + +fn triple_edn((e, a, v): Triple) -> String { + format!("[:e{e} {} {}]", ATTRS[a as usize], value_edn(v)) +} + +/// xorshift64: deterministic, dependency-free. +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Self { + Rng(seed ^ 0x9E37_79B9_7F4A_7C15 | 1) + } + + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n.max(1) + } + + fn below_u8(&mut self, n: u8) -> u8 { + self.below(u64::from(n)) as u8 + } +} + +/// The next transaction of the workload, and the live triples after it. +fn next_tx(rng: &mut Rng, live: &BTreeSet) -> (String, BTreeSet) { + let mut next = live.clone(); + if !live.is_empty() && rng.below(10) < 3 { + // Batched retract of 1-4 live triples. + let pool: Vec = live.iter().copied().collect(); + let mut picked = BTreeSet::new(); + for _ in 0..1 + rng.below(4) { + picked.insert(pool[rng.below(pool.len() as u64) as usize]); + } + let body: Vec = picked.iter().map(|t| triple_edn(*t)).collect(); + for t in &picked { + next.remove(t); + } + return (format!("(retract [{}])", body.join(" ")), next); + } + // Multi-valued batch: 1-3 values of one entity and attribute (#371), plus + // 0-3 other triples. Triples retracted earlier come back this way. A + // triple is never repeated within one transaction. + let e = rng.below_u8(ENTITIES); + let a = rng.below_u8(ATTRS.len() as u8); + let mut picked = BTreeSet::new(); + for _ in 0..1 + rng.below(3) { + picked.insert((e, a, rng.below_u8(VALUES))); + } + for _ in 0..rng.below(4) { + picked.insert(( + rng.below_u8(ENTITIES), + rng.below_u8(ATTRS.len() as u8), + rng.below_u8(VALUES), + )); + } + let body: Vec = picked.iter().map(|t| triple_edn(*t)).collect(); + next.extend(picked); + (format!("(transact [{}])", body.join(" ")), next) } +/// Live triples after each transaction: `history[k]` is the state after `k`. +fn model(seed: u64, txs: u64) -> Vec> { + let mut rng = Rng::new(seed); + let mut history = vec![BTreeSet::new()]; + for _ in 0..txs { + let (_, next) = next_tx(&mut rng, history.last().unwrap()); + history.push(next); + } + history +} + +// ── Variants ────────────────────────────────────────────────────────────────── + +#[derive(Clone, Copy, Debug)] +enum Variant { + /// `checkpoint()` after every transaction: the kill mostly lands in a save. + CheckpointEach, + /// `checkpoint()` after every third transaction. + CheckpointEvery3, + /// Never checkpoints: reopen replays the WAL. + WalOnly, + /// `wal_checkpoint_threshold(2)`: checkpoints inside `execute`. + AutoCheckpoint, + /// As `CheckpointEvery3`, with `SyncMode::Normal` (no WAL fsync). + NormalSync, +} + +const VARIANTS: [Variant; 5] = [ + Variant::CheckpointEach, + Variant::CheckpointEvery3, + Variant::WalOnly, + Variant::AutoCheckpoint, + Variant::NormalSync, +]; + +impl Variant { + fn options(self) -> OpenOptions { + let opts = OpenOptions::new(); + match self { + Variant::WalOnly => opts.wal_checkpoint_threshold(usize::MAX), + Variant::AutoCheckpoint => opts.wal_checkpoint_threshold(2), + Variant::NormalSync => opts.synchronous(SyncMode::Normal), + Variant::CheckpointEach | Variant::CheckpointEvery3 => opts, + } + } + + fn checkpoint_after(self, k: u64) -> bool { + match self { + Variant::CheckpointEach => true, + Variant::CheckpointEvery3 | Variant::NormalSync => k % 3 == 0, + Variant::WalOnly | Variant::AutoCheckpoint => false, + } + } +} + +// ── Checks ──────────────────────────────────────────────────────────────────── + +fn entity_uuid(e: u8) -> Uuid { + Uuid::new_v5(&Uuid::NAMESPACE_OID, format!(":e{e}").as_bytes()) +} + +struct Checker { + uuids: HashMap, + /// Names the round in every failure message. + ctx: String, +} + +impl Checker { + fn render(&self, v: &Value) -> String { + match v { + Value::Integer(n) => format!("i{n}"), + Value::String(s) => match (8..VALUES).find(|i| long_string(*i) == *s) { + Some(i) => format!("s{i}"), + None => format!("s?{}", s.len()), + }, + Value::Keyword(k) => k.clone(), + Value::Ref(u) => match self.uuids.get(u) { + Some(e) => format!("r{e}"), + None => "r?".to_string(), + }, + _ => "?".to_string(), + } + } + + fn rows(&self, db: &Minigraf, query: &str) -> Vec { + let result = db + .execute(query) + .unwrap_or_else(|e| panic!("{}: query failed ({}): {query}", self.ctx, e.code())); + let QueryResult::QueryResults { results, .. } = result else { + panic!("{}: not a query result: {query}", self.ctx); + }; + let mut rows: Vec = results + .iter() + .map(|row| { + row.iter() + .map(|v| self.render(v)) + .collect::>() + .join(" ") + }) + .collect(); + rows.sort(); + rows + } + + fn expect(&self, db: &Minigraf, query: &str, want: impl Iterator) { + let mut want: Vec = want.collect(); + want.sort(); + assert_eq!(self.rows(db, query), want, "{}: {query}", self.ctx); + } + + /// The reopened state must be the model after `confirmed` or + /// `confirmed + 1` transactions, through every index path. + fn check(&self, db: &Minigraf, history: &[BTreeSet], confirmed: u64) { + let t = db.current_tx_count(); + assert!( + t == confirmed || t == confirmed + 1, + "{}: tx count {t} after {confirmed} confirmed transactions", + self.ctx + ); + let live = &history[t as usize]; + let full = |s: &BTreeSet| -> Vec { + s.iter() + .map(|&(e, a, v)| format!("r{e} {} {}", ATTRS[a as usize], value_render(v))) + .collect() + }; + + // Full scan. + self.expect( + db, + "(query [:find ?e ?a ?v :where [?e ?a ?v]])", + full(live).into_iter(), + ); + // AEVT: attribute scans; AVET: attribute and value bound. + for (ai, attr) in ATTRS.iter().enumerate() { + let ai = ai as u8; + self.expect( + db, + &format!("(query [:find ?e ?v :where [?e {attr} ?v]])"), + live.iter() + .filter(|t| t.1 == ai) + .map(|&(e, _, v)| format!("r{e} {}", value_render(v))), + ); + for v in 0..VALUES { + self.expect( + db, + &format!("(query [:find ?e :where [?e {attr} {}]])", value_edn(v)), + live.iter() + .filter(|t| t.1 == ai && t.2 == v) + .map(|&(e, _, _)| format!("r{e}")), + ); + } + } + // EAVT: entity-bound lookups (the path #370 broke). + for e in 0..ENTITIES { + self.expect( + db, + &format!("(query [:find ?a ?v :where [:e{e} ?a ?v]])"), + live.iter() + .filter(|t| t.0 == e) + .map(|&(_, a, v)| format!("{} {}", ATTRS[a as usize], value_render(v))), + ); + } + // Earlier states, through :as-of. + let samples: BTreeSet = [1, t / 2, t.saturating_sub(1)] + .into_iter() + .filter(|k| (1..t).contains(k)) + .collect(); + for k in samples { + self.expect( + db, + &format!("(query [:find ?e ?a ?v :as-of {k} :where [?e ?a ?v]])"), + full(&history[k as usize]).into_iter(), + ); + } + let report = db + .verify() + .unwrap_or_else(|e| panic!("{}: verify failed ({})", self.ctx, e.code())); + assert!(report.is_ok(), "{}: verify found problems", self.ctx); + } +} + +fn open(path: &Path, ctx: &str) -> Minigraf { + Minigraf::open(path).unwrap_or_else(|e| panic!("{ctx}: reopen failed ({})", e.code())) +} + +/// Complete lines in the confirmation log; the last is the newest confirmed +/// transaction. A partial last line is ignored. +fn confirmed(log: &Path) -> u64 { + let text = std::fs::read_to_string(log).unwrap_or_default(); + let complete = &text[..text.rfind('\n').map_or(0, |i| i + 1)]; + let mut n = 0; + for (i, line) in complete.lines().enumerate() { + let k: u64 = line.parse().expect("log line is a number"); + assert_eq!(k, i as u64 + 1, "log lines are 1, 2, 3, ..."); + n = k; + } + n +} + +// ── Test ────────────────────────────────────────────────────────────────────── + #[test] -fn sigkill_during_checkpoint_never_permanently_corrupts_file() { +fn sigkill_keeps_exactly_the_committed_transactions() { let exe = std::env::current_exe().expect("test binary path"); + let base_seed: u64 = std::env::var("MINIGRAF_CRASH_KILL_SEED") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or_else(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() as u64 + }); + println!("crash-kill base seed {base_seed} (replay: MINIGRAF_CRASH_KILL_SEED={base_seed})"); + let uuids: HashMap = (0..ENTITIES).map(|e| (entity_uuid(e), e)).collect(); for round in 0..rounds() { + let seed = base_seed ^ (round as u64 + 1).wrapping_mul(0x2545_F491_4F6C_DD1D); + let variant_idx = round % VARIANTS.len(); + let variant = VARIANTS[variant_idx]; let dir = tempfile::tempdir().unwrap(); let db_path = dir.path().join("kill.graph"); + let log_path = dir.path().join("confirmed.log"); let mut child = Command::new(&exe) .args(["crash_kill_child_entrypoint", "--exact", "--nocapture"]) .env("MINIGRAF_KILL_DB", &db_path) + .env("MINIGRAF_KILL_LOG", &log_path) + .env("MINIGRAF_KILL_SEED", seed.to_string()) + .env("MINIGRAF_KILL_VARIANT", variant_idx.to_string()) .spawn() .expect("spawn crash-kill child"); - let seed = Instant::now().elapsed().as_nanos() as u64 - ^ (round as u64).wrapping_mul(0x2545_F491_4F6C_DD1D); - let delay = Duration::from_millis(5 + jitter_millis(seed, 150)); - std::thread::sleep(delay); - + // Kill after a random number of confirmed transactions, plus jitter so + // the kill lands anywhere inside the next execute or checkpoint. + let mut rng = Rng::new(seed.rotate_left(17)); + let target = 1 + rng.below(60); + let deadline = Instant::now() + Duration::from_secs(30); + while confirmed(&log_path) < target { + if let Some(status) = child.try_wait().expect("poll child") { + panic!("round {round} seed {seed}: child exited early ({status})"); + } + assert!( + Instant::now() < deadline, + "round {round} seed {seed}: child too slow" + ); + std::thread::sleep(Duration::from_millis(1)); + } + std::thread::sleep(Duration::from_micros(rng.below(20_000))); child.kill().expect("SIGKILL crash-kill child"); let status = child.wait().expect("reap crash-kill child"); assert!( @@ -80,32 +404,60 @@ fn sigkill_during_checkpoint_never_permanently_corrupts_file() { "round {round}: child must not exit cleanly before being killed" ); - // A fresh handle in a fresh process must always be able to open the - // file after the kill -- this is the exact guarantee #308 broke. - let db = match Minigraf::open(&db_path) { - Ok(db) => db, - Err(e) => panic!("round {round}: reopen after SIGKILL must not fail: {e}"), + let n = confirmed(&log_path); + let history = model(seed, n + 1); + let ctx = |stage: &str| { + format!("round {round} seed {seed} variant {variant:?} confirmed {n}: {stage}") + }; + let checker = |stage: &str| Checker { + uuids: uuids.clone(), + ctx: ctx(stage), }; - db.execute("(query [:find ?e :where [?e :k ?v]])") - .unwrap_or_else(|e| panic!("round {round}: query after reopen must not fail: {e}")); + + let db = open(&db_path, &ctx("first reopen")); + checker("first reopen").check(&db, &history, n); + drop(db); + + let db = open(&db_path, &ctx("second reopen")); + checker("second reopen").check(&db, &history, n); + db.checkpoint() + .unwrap_or_else(|e| panic!("{}: checkpoint failed ({})", ctx("checkpoint"), e.code())); + drop(db); + + let db = open(&db_path, &ctx("reopen after checkpoint")); + checker("reopen after checkpoint").check(&db, &history, n); } } -/// Child half of the SIGKILL fuzz loop above: opens `MINIGRAF_KILL_DB` and -/// loops transact + checkpoint until killed. A no-op when the marker -/// environment variable is absent -- same convention as -/// `tests/common::crash_child_entrypoint`. +/// Child half of the test above: runs the seeded workload until killed. A no-op +/// when `MINIGRAF_KILL_DB` is absent, as in `tests/common::crash_child_entrypoint`. #[test] fn crash_kill_child_entrypoint() { let Ok(db_path) = std::env::var("MINIGRAF_KILL_DB") else { return; }; - let db = Minigraf::open(&db_path).expect("child opens db"); - let mut i: u64 = 0; - loop { - db.execute(&format!("(transact [[:e{i} :k {i}]])")) - .expect("child transact"); - db.checkpoint().expect("child checkpoint"); - i += 1; + let env = |k: &str| std::env::var(k).unwrap_or_else(|_| panic!("child needs {k}")); + let seed: u64 = env("MINIGRAF_KILL_SEED").parse().expect("seed"); + let variant = VARIANTS[env("MINIGRAF_KILL_VARIANT") + .parse::() + .expect("variant")]; + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(env("MINIGRAF_KILL_LOG")) + .expect("child opens log"); + + let db = Minigraf::open_with_options(&db_path, variant.options()).expect("child opens db"); + let mut rng = Rng::new(seed); + let mut live = BTreeSet::new(); + for k in 1.. { + let (stmt, next) = next_tx(&mut rng, &live); + db.execute(&stmt).expect("child transaction"); + log.write_all(format!("{k}\n").as_bytes()) + .expect("child logs transaction"); + live = next; + if variant.checkpoint_after(k) { + db.checkpoint().expect("child checkpoint"); + } } } From a3362ecfa4b77444fa244b02c47a88bdb577d331 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Thu, 8 Oct 2026 12:55:23 +0530 Subject: [PATCH 2/2] ci(crash-kill): alternate the nightly run between main and v3 (#384) Scheduled runs use this file from the default branch, so the branch under test comes from the cron string, as in bench.yml: main at 03:17 UTC, v3 at 15:17 UTC. Failure issues name the branch and the commit that was tested. Refs #384 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012wXxZguv7PgKQjMMH4yJ5h --- .github/workflows/crash-kill.yml | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/.github/workflows/crash-kill.yml b/.github/workflows/crash-kill.yml index fe66f61021..fa72f14c7a 100644 --- a/.github/workflows/crash-kill.yml +++ b/.github/workflows/crash-kill.yml @@ -1,5 +1,13 @@ name: SIGKILL crash-safety fuzz (nightly) +# Two branches alternate every 12 hours: main at 03:17 UTC, v3 at 15:17 UTC. +# Scheduled runs always use this file from the default branch, so the branch +# under test is chosen from the cron string that fired (as in bench.yml). +# Keep the cron strings here and in CRASH_REF/run-name identical. +run-name: >- + SIGKILL crash-safety fuzz (${{ github.event_name == 'workflow_dispatch' && inputs.ref + || (github.event.schedule == '17 15 * * *' && 'v3' || 'main') }}) + # #308: an abrupt kill landing mid-checkpoint had a ~26% chance of leaving # the header on disk with a bumped page_count but a stale checksum -- # permanent corruption with no recovery path. The bug was in the ordering @@ -10,18 +18,27 @@ name: SIGKILL crash-safety fuzz (nightly) # workflow runs a much larger round count nightly for statistical # confidence on each OS. Since #384 each round also checks that the reopened # file holds exactly the transactions the child confirmed (EAVT, AEVT, AVET, -# full scan, :as-of, verify). The test prints its base seed; replay a +# full scan, :as-of; verify on v3). The test prints its base seed; replay a # failure with MINIGRAF_CRASH_KILL_SEED. on: schedule: - - cron: "17 3 * * *" + - cron: "17 3 * * *" # main + - cron: "17 15 * * *" # v3 workflow_dispatch: + inputs: + ref: + description: Branch to test + required: true + default: main permissions: contents: read issues: write +env: + CRASH_REF: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || (github.event.schedule == '17 15 * * *' && 'v3' || 'main') }} + jobs: crash-kill: name: SIGKILL fuzz suite @@ -34,6 +51,8 @@ jobs: steps: - uses: actions/checkout@v4 + with: + ref: ${{ env.CRASH_REF }} - name: Install Rust stable uses: dtolnay/rust-toolchain@stable @@ -52,14 +71,14 @@ jobs: shell: bash env: GH_TOKEN: ${{ github.token }} - ISSUE_TITLE: "Nightly SIGKILL crash-safety failure (${{ matrix.os }})" + ISSUE_TITLE: "Nightly SIGKILL crash-safety failure (${{ env.CRASH_REF }}, ${{ matrix.os }})" run: | report_file="crash-kill-failure.md" { - echo "The nightly SIGKILL crash-safety fuzz suite failed on ${{ matrix.os }}." + echo "The nightly SIGKILL crash-safety fuzz suite failed on ${{ env.CRASH_REF }} (${{ matrix.os }})." echo echo "- Run: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - echo "- Commit: $GITHUB_SHA" + echo "- Commit: $(git rev-parse HEAD)" echo "- Reproduce: cargo test --test crash_kill_test -- --nocapture" echo " (set MINIGRAF_CRASH_KILL_ROUNDS to raise the round count; MINIGRAF_CRASH_KILL_SEED to the printed base seed to replay)" echo