From 1adf83ca4e0a288e2370de1eca3cbcda0ba901e8 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 17:06:55 +0530 Subject: [PATCH] test(grammar): bounded-exhaustive parser vs grammar.pest verifier (#643) src/query/datalog/parser/verifier.rs (test-only, not wasm32) checks every 1-3 character string through parse_edn and every balanced filler of up to MINIGRAF_GRAMMAR_BOUND (default 3) of 32 tokens in 15 command templates through parse_datalog_command against grammar.pest: pest rejects => parser rejects; pest accepts => parser accepts or raises a SEMANTIC code (each with a witness). Today's drift is KNOWN_DRIFT, one entry per cause, each failure put down to its first cause in text order (#649, #650, #651). grammar.pest: exact fact and retract_fact, edn_value_only, reserved list heads are never rule names, literal keywords end at a word boundary. The two arity corpus files move to invalid/syntax/. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019kY61Y11gcRD91Y6b7jbGT --- CHANGELOG.md | 2 + CLAUDE.md | 3 +- README.md | 2 +- docs/TEST_COVERAGE.md | 3 +- src/query/datalog/parser.rs | 3 + src/query/datalog/parser/verifier.rs | 800 ++++++++++++++++++ tests/grammar/grammar.pest | 65 +- .../fact_too_few_elements.edn | 0 .../retract_wrong_arity.edn | 0 9 files changed, 856 insertions(+), 22 deletions(-) create mode 100644 src/query/datalog/parser/verifier.rs rename tests/grammar/invalid/{semantic => syntax}/fact_too_few_elements.edn (100%) rename tests/grammar/invalid/{semantic => syntax}/retract_wrong_arity.edn (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37511a804..ea90d3b09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -103,6 +103,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `tests/snapshot_atomicity_test.rs` races a writer against a reader: a query must see each transaction whole, whether written with `execute` or a `WriteTransaction` (#554), and must read one state for all its patterns (#555), in memory and on file. It also runs the v2.x checkpoint race from #558, which never failed on v3: copy-on-write checkpoints do not overwrite pages a published reader uses. - **The `datalog_eval` fuzz guard counts partial bindings** (#597). The guard skipped inputs whose patterns join to more than 50,000 rows, counting only the rows after the last pattern. A `not-join` body still runs on the executor pattern by pattern in text order, so a 120-pattern body built hundreds of thousands of partial bindings before its last pattern matched nothing, and ran past the 60-second timeout. The guard now counts the bindings after every pattern. On the `v3` corpus (4,783 inputs) coverage drops by 7 of 9,719 edges. The input is added as a seed, as is the `btree_page` input of the cursor fix above. +- **Parser vs grammar verifier (#643).** `src/query/datalog/parser/verifier.rs` checks, for every generated input, that the parser rejects what `tests/grammar/grammar.pest` rejects, and accepts what it accepts unless the error code is semantic (a listed code with a witness pest accepts). It runs every string of 1 to 3 characters over 102 characters (ASCII, `\t \n \r`, four non-ASCII stand-ins) through `parse_edn`, and every bracket-balanced sequence of up to `MINIGRAF_GRAMMAR_BOUND` (default 3) of 32 tokens in 15 command templates through `parse_datalog_command`, also with no separators up to 3 tokens. Deterministic; about 20 s by default and 3.5 min at bound 4 on a 16-thread machine. The drift it found is listed in `KNOWN_DRIFT` by cause (comments and non-ASCII letters #650; empty sections, ignored keywords, rule and call heads, a lone `:` or `-`, unterminated strings #651; a fact of more than four elements losing elements, #649); each fix removes its entry. `grammar.pest` now says what the parser means: a fact is exactly `[e a v]` plus an optional valid-time map and a retracted fact exactly `[e a v]`; `not`, `not-join`, `or`, `or-join` (and `and` inside an `or`) are never rule names; literal keywords end at a word boundary (`:find?x` is one keyword). + ### Documentation - **Durability, recovery and operations guide** (#398). `docs/DURABILITY.md`, also published on the docs site, covers what survives a process crash and a power loss under `SyncMode::Full` and `SyncMode::Normal`, what opening after a crash does and what it costs, which filesystems and container setups are supported, how to back up a live database (offline copy, volume snapshot, or `fact_log` into `LogWriter` from the running process) and restore it, how to check and repair a file with `verify()` and `rebuild_indexes()`, how to upgrade from v2.x and roll back, which storage errors mean retry, reopen or restore, and the known limitations. Writing it found #535: a `.wal` from a later checkpoint is replayed onto an older `.graph` without an error, so the restore steps remove any `.wal` first. A log-writer test runs the documented online backup while another thread writes past the automatic checkpoint threshold. diff --git a/CLAUDE.md b/CLAUDE.md index 2bbaa5fea..bfd3c55a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,6 +129,7 @@ cargo run < demos/demo_negation.txt 3. **`src/query/datalog/`** — Datalog engine - `parser.rs`: EDN/Datalog parser — `transact`, `retract`, `query`, `rule`, `:as-of`, `:valid-at`, `not`, `not-join`; `resolve_pseudo_sources` names each per-fact pseudo-attribute's source (nearest earlier same-entity pattern, lexical scope) and its hidden metadata variable `?#.`, else PRS-081 (#594) + - `parser/verifier.rs`: test-only (not wasm32) bounded-exhaustive check of the parser against `tests/grammar/grammar.pest` (#643): every 1–3 character string (`parse_edn`) and every balanced token filler up to `MINIGRAF_GRAMMAR_BOUND` (default 3) in 15 command templates (`parse_datalog_command`); pest rejects ⇒ parser rejects, pest accepts ⇒ parser accepts or raises a `SEMANTIC` code; today's drift is `KNOWN_DRIFT`, one entry per cause, removed by its fix (#649–#651) - `executor.rs`: Query executor — temporal filter (tx-time → net-assert → valid-time), not/not-join post-filter - `matcher.rs`: Pattern matching with variable unification; `edn_to_value`, `edn_to_entity_id` - `aggregate.rs`: `Agg` (one aggregate of one group) and `Running` (a window's running value), shared by the executor and the engine; exact sums (`i128` integers saturated once, fixed-point floats rounded once), `value_order` (one total order of values for window sorts, peers, `rank` and `min`/`max`), `named_vars` (a window's tie-break variables) (#547) @@ -205,7 +206,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1646 tests** (1636 passing, 10 ignored; unit + integration + doc). +**1650 tests** (1640 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 dce536d39..354ebabff 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 1646 tests +cargo test # run 1650 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index afb9194c0..5fbdf8c1c 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-20 with `cargo test --quiet` -**Result**: 1,636 passing tests and 10 ignored tests (1,646 total) +**Result**: 1,640 passing tests and 10 ignored tests (1,650 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). Rule-body tests in `tests/recursive_rules_test.rs` check that a `:db/valid-at` pattern in a rule definition, in its `not` and `not-join` bodies and in its `or` branches binds the query's valid time, on the semi-naive, stratified and magic-sets paths (#617). Tests in `tests/not_join_test.rs` check that a rule calling a rule with `not-join`, `not` or `or` returns that rule's rows, with a free and a literal argument and through a forwarding rule, and that a rule with its own `not-join` calling one gets the same rows whether or not the query asks for the callee first; stratification unit tests check that such a caller, a rule forwarding to it and a caller of a recursive one sit above the callee, and that recursion through a rule with a `not` still stratifies (#628). Tests in `tests/not_join_test.rs` check that recursion through a rule with `not`, `not-join` or `or`, directly or through another rule, returns every row along a chain, and that the `not` still removes the rows it should; evaluator unit tests check that such recursion stops at its fixpoint that `max_iterations` and `max_results` end one that does not with INT-020, and that `max_results` counts the facts every pass derives, not only the mixed rule's (#633). @@ -24,6 +24,7 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value - **Disjunction equality** (`tests/or_equality_test.rs`, 5 tests; #546): an `or` / `or-join` branch meets the outer row by join equality on every executor path (a keyword in the outer row meets a ref in a branch; `0.0` and `-0.0`; floats `1e-20` apart do not), branches naming different outer variables each meet the outer row on their own, and an `or-join` branch that does not bind its join variable keeps every outer row when it has a row; through `execute` and a cursor, in memory and after a checkpoint. Engine unit tests run every disjunction shape with each branch form forced and reordering on and off against the executor, and cover routing (rule invocations, nested `or`, registry predicates, branch-local metadata stay on the executor), the branch form the planner picks, `Distinct` (equal rows collapse; a keyword and a ref, `-0.0` and `0.0`), and that a hashed branch is read once and a correlated one runs only for rows earlier branches did not match. - **Aggregates and windows** (`tests/aggregate_window_rules_test.rs`, 8 tests; #547): exact float `sum` and window `avg`, integer `sum` saturating once, exact window `sum` of integers above 2^53, `min`/`max` of `-0.0` and `0.0`, `rank` by keywords (peers 1 1 3 3), a running `sum` giving peers the value at the last peer, `row-number` breaking ties by the other `:find` variables, and `INT-041` from a failing group. `src/query/datalog/aggregate.rs` (15 unit tests) checks every accumulator over every order of small inputs and that `value_order` is a total order; `tests/window_functions_test.rs` checks `PRS-082` and a window over the groups of an aggregate query, and `tests/plan_independence_test.rs` runs aggregate, window and mixed queries with reordering on and off. `Aggregate` on the engine (#547 PR 2, `src/query/engine/tests.rs`, 3 tests): every built-in aggregate grouped by keywords, refs, booleans, floats and long strings, over `nil` values, keywords and refs, with `:with` and `or`, at six temporal settings in memory, after a checkpoint and after reopen, against the executor; an ungrouped aggregate reads every row and returns one batch of one row; the zero row and empty answers; groups in value order over several batches; `INT-041` from a later group; a group dropped by `min` of no value. `tests/aggregation_test.rs` checks that a group of `0.0` and `-0.0` returns `-0.0` in either insertion order. - **Parser error codes** (`tests/error_codes_prs_test.rs`, 26 new tests; #643): each of `PRS-083` to `PRS-107` (the parse errors that were `INT-019`, and the retract arity that was `INT-000`) from its `docs/ERROR_REFERENCE.md` example, in the Parser category, with its argument in the message and without the old `datalog parser: ` prefix; three of them through `prepare`. +- **Parser vs grammar** (`src/query/datalog/parser/verifier.rs`, 4 tests; #643): about 1.07M lexical strings and 555K structural inputs at the default bound (7.6M at `MINIGRAF_GRAMMAR_BOUND=4`) checked against `tests/grammar/grammar.pest`; known drift by cause in `KNOWN_DRIFT` (#649–#651), semantic codes with witnesses in `SEMANTIC`. - **Plan independence** (`tests/plan_independence_test.rs`, 15 tests, `test-oracle` feature only; #596): a matrix of queries (joins in both text orders, cross products, keyword and ref, floats, long strings, filter and binding expressions, recursive rules and rules with `not`, `or`/`or-join` including the #250 short-circuit shapes, placed and deferred `not`/`not-join`, aggregates, `:as-of`, `:valid-at`, `:any-valid-time`), in memory and on file after a checkpoint and a reopen, through `execute` and a cursor, gives the same bag of rows with clause reordering on and off (`minigraf::__reorder`) and with the engine's negation bodies and `or` branches chosen, forced hashed and forced correlated (`minigraf::__subplans`, #546; the matrix gains #546's negation and disjunction shapes); #596's example and the unification cases (an expression whose output is its input, two expressions on one variable, integer vs float, `-0.0` vs `0.0`); and `or` / `or-join` branches whose expressions read or bind from a variable only the outer row binds, nested and in rule bodies (#620); and expressions, chains of them and a `not` after them, reading a variable only an `or` binds, in queries, with rules and in rule bodies (#625; `tests/disjunction_test.rs` repeats them without `test-oracle`). Under `test-oracle` the model-based and property tests also rerun every generated query with reordering off (the property test also with negation bodies and `or` branches forced hashed; it generates `or` / `or-join` over bound variables, #546). Unit tests cover `branch_outer_reads` (#620), the planner deferring an expression only an `or` can bind for, after the expressions placed before it and ahead of the deferred `not`s (#625), `apply_expr` (equal, different, integer vs float, NaN, `-0.0`/`0.0` with and without replacing, keyword vs ref both ways, a failing expression), `Binders::expression`, the switch (source order kept, per thread, restored on drop), and the engine planner's `Bind` modes and build side with the switch off; the engine's join matrix gains six unification shapes. - **Public diagnostics**: structured parser, query, storage, WAL, API, and internal error codes; the error-code registry is checked against [`ERROR_REFERENCE.md`](ERROR_REFERENCE.md). - **Compatibility and quality**: golden-file corpus of released file formats, cross-platform format compatibility, property-based tests, long-haul smoke coverage, a weekly soak at 10M facts with a 5-hour churn (#392), XTDB/Datomic semantic compatibility, grammar conformance, and rustdoc examples. diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index 1faedbea0..ae3efa56f 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -2125,6 +2125,9 @@ fn parse_rule(elements: &[EdnValue]) -> Result { })) } +#[cfg(all(test, not(target_arch = "wasm32")))] +mod verifier; + #[cfg(test)] mod tests { use super::*; diff --git a/src/query/datalog/parser/verifier.rs b/src/query/datalog/parser/verifier.rs new file mode 100644 index 000000000..5854901f5 --- /dev/null +++ b/src/query/datalog/parser/verifier.rs @@ -0,0 +1,800 @@ +//! Bounded-exhaustive check of the parser against `tests/grammar/grammar.pest` (#643). +//! +//! For every generated input `s` (design: +//! `docs/superpowers/specs/2026-10-20-grammar-drift-verifier-design.md`): +//! +//! 1. pest rejects `s` ⇒ the parser rejects `s`; +//! 2. pest accepts `s` ⇒ the parser accepts `s`, or rejects it with a code in [`SEMANTIC`]. +//! +//! Two levels generate the inputs, both deterministically: +//! +//! - lexical: every string of 1 to 3 characters over [`alphabet`], pest's +//! `edn_value_only` against [`parse_edn`]; +//! - structural: every balanced sequence of up to `k` [`TOKENS`] in the hole of each of +//! [`TEMPLATES`], pest's `command` against [`parse_datalog_command`]. `k` is +//! `MINIGRAF_GRAMMAR_BOUND` (default [`DEFAULT_BOUND`]). +//! +//! Drift that exists today is listed in [`KNOWN_DRIFT`]. Each failing input is put down +//! to its first cause in text order ([`lexical_cause`], [`structural_cause`]), so it +//! matches at most one entry. A failure with no known cause fails the test, and so does +//! an entry that no failure matches once `k` reaches its `min_k`: a fix removes its entry. + +use super::{parse_datalog_command, parse_edn}; +use crate::error::MinigrafError; +use crate::query::datalog::types::EdnValue; +use pest::Parser as _; +use std::fmt::Write as _; + +#[derive(pest_derive::Parser)] +#[grammar = "tests/grammar/grammar.pest"] +struct G; + +const DEFAULT_BOUND: usize = 3; + +/// Fillers of up to this many tokens are also joined with no separators, including at +/// both template boundaries (`parse_edn` and pest each read `:find?e` as one keyword, +/// so the lexical level cannot see how glued tokens split). +const GLUE_BOUND: usize = 3; + +const LEXICAL_MAX_LEN: usize = 3; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Outcome { + Accept, + Reject(&'static str), +} + +fn outcome(r: anyhow::Result) -> Outcome { + match r { + Ok(_) => Outcome::Accept, + Err(e) => Outcome::Reject(MinigrafError::from(e).code()), + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Level { + Lexical, + Structural, +} + +// ── Inputs ──────────────────────────────────────────────────────────────── + +/// Printable ASCII, then `\t \n \r`, then non-ASCII stand-ins: a letter, a CJK +/// character, an Arabic-Indic digit and a no-break space. +fn alphabet() -> Vec { + let mut a: Vec = (0x20u8..=0x7E).map(char::from).collect(); + a.extend(['\t', '\n', '\r', 'é', '名', '٣', '\u{00A0}']); + a +} + +const TOKENS: [&str; 32] = [ + "(", + ")", + "[", + "]", + "{", + "}", + "query", + "transact", + "rule", + "not", + "not-join", + "or", + "and", + ":find", + ":where", + ":with", + ":as-of", + ":valid-at", + ":any-valid-time", + ":over", + ":order-by", + ":valid-from", + ":foo", + "?x", + "?y", + "foo", + "1", + "1.5", + "\"2024-01-01T00:00:00Z\"", + "<", + "$s", + "#uuid \"550e8400-e29b-41d4-a716-446655440000\"", +]; + +/// Bracket token → `(kind, opens)`. +fn bracket(t: u8) -> Option<(u8, bool)> { + (t < 6).then_some((t / 2, t.is_multiple_of(2))) +} + +/// `(prefix, suffix)`: the hole sits between them. Each puts the hole where a short +/// filler can complete a clause. +const TEMPLATES: [(&str, &str); 15] = [ + ("(query [", "])"), + ("(query [:find", ":where [?x :a ?y]])"), + ("(query [:find ?x :where [?x :a ?y]", "])"), + ("(query [:find ?x :where [?x :a ?y] (not", ")])"), + ("(query [:find ?x :where [?x :a ?y] (not-join [?x]", ")])"), + ("(query [:find ?x :where [?x :a ?y] (or", ")])"), + ("(query [:find ?x :where [?x :a ?y] (or-join [?x]", ")])"), + ("(query [:find ?x :where [?x :a ?y] (or (and", "))])"), + ("(query [:find ?x (sum ?y :over (", ")) :where [?x :a ?y]])"), + ("(transact [", "])"), + ("(transact [[:a :b 1", "]])"), + ("(transact {", "} [[:a :b 1]])"), + ("(retract [", "])"), + ("(rule [(", ") [?x :a 1]])"), + ("(rule [(foo ?x)", "])"), +]; + +/// Calls `f` on every balanced filler of exactly `len` tokens, in token-index order. +fn each_filler(len: usize, f: &mut impl FnMut(&[u8])) { + fn go(buf: &mut Vec, stack: &mut Vec, len: usize, f: &mut impl FnMut(&[u8])) { + let left = len - buf.len(); + if left == 0 { + if stack.is_empty() { + f(buf); + } + return; + } + for t in 0..TOKENS.len() as u8 { + match bracket(t) { + // Every open bracket needs a closer in the tokens left after this one. + Some((kind, true)) if stack.len() < left - 1 => { + stack.push(kind); + buf.push(t); + go(buf, stack, len, f); + buf.pop(); + stack.pop(); + } + Some((kind, false)) if stack.last() == Some(&kind) => { + stack.pop(); + buf.push(t); + go(buf, stack, len, f); + buf.pop(); + stack.push(kind); + } + None if stack.len() < left => { + buf.push(t); + go(buf, stack, len, f); + buf.pop(); + } + _ => {} + } + } + } + go(&mut Vec::new(), &mut Vec::new(), len, f); +} + +fn bound() -> usize { + std::env::var("MINIGRAF_GRAMMAR_BOUND") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_BOUND) +} + +// ── Semantic codes ──────────────────────────────────────────────────────── + +/// A code that an input `grammar.pest` accepts can raise, with such an input. Every +/// site that raises a listed code must be semantic; the comment above each entry +/// gives the sites (`parser.rs`) and why. +struct Semantic { + code: &'static str, + witness: &'static str, +} + +const SEMANTIC: &[Semantic] = &[ + // parse_query: `:with` without an aggregate in `:find` (the reference's Semantic + // Constraints). + Semantic { + code: "PRS-021", + witness: "(query [:find ?x :with ?y :where [?x :a ?y]])", + }, + // parse_query: a `:with` variable no `:where` clause binds. + Semantic { + code: "PRS-022", + witness: "(query [:find (count ?x) :with ?z :where [?x :a ?y]])", + }, + // parse_query, two sites: a `:find` variable, or a window's variable, that no + // `:where` clause binds (#406). + Semantic { + code: "PRS-080", + witness: "(query [:find ?z :where [?x :a ?y]])", + }, + // parse_window: a window's `:over` without `:order-by` (`over_option*` allows none). + Semantic { + code: "PRS-084", + witness: "(query [:find ?x (sum ?y :over ()) :where [?x :a ?y]])", + }, + // parse_rule: a rule body with no pattern or rule call (`rule_vector` allows + // `where_clause*`). + Semantic { + code: "PRS-107", + witness: "(rule [(foo ?x)])", + }, +]; + +fn is_semantic(code: &str) -> bool { + SEMANTIC.iter().any(|s| s.code == code) +} + +// ── Known drift ─────────────────────────────────────────────────────────── + +/// The cause a failing input is put down to. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Cause { + // Lexical. + /// `;` starts a line comment in the parser; the grammar has no comments. + Comment, + /// A string with no closing quote reads to the end of the input. + UnterminatedString, + /// A non-ASCII letter or digit in a symbol or keyword (the grammar is ASCII). + UnicodeLetter, + /// `:` with no keyword character after it is the keyword `:`. + BareColon, + /// `-` with no word character after it is the symbol `-`. + LoneMinus, + // Structural. + /// `(query [])`. + EmptyQuery, + /// `:find` with no find spec before the next keyword or the end. + EmptyFind, + /// `:where` with no clause before the next keyword or the end. + EmptyWhere, + /// `:with` with no variable before the next keyword or the end. + EmptyWith, + /// A keyword the query vector does not know, with no value after it, is ignored. + UnknownKeyword, + /// A value after `:as-of`, `:valid-at`, `:any-valid-time` or `:max-*` and its + /// argument continues the section before that keyword. + ResumedSection, + /// A clause list whose head is a variable or an operator is read as a rule call. + CallHead, + /// A `:find` list whose head is a variable is read as an aggregate. + AggregateHead, + /// A rule head whose name is not a plain symbol or whose argument is not a + /// variable. + RuleHead, + /// A fact `[e a v {…} x …]`: the parser drops everything after the map. + FactArity, +} + +impl Cause { + fn level(self) -> Level { + match self { + Cause::Comment + | Cause::UnterminatedString + | Cause::UnicodeLetter + | Cause::BareColon + | Cause::LoneMinus => Level::Lexical, + _ => Level::Structural, + } + } +} + +struct Drift { + cause: Cause, + issue: u32, + /// The smallest structural bound whose inputs show it (unused at the lexical level). + min_k: usize, +} + +const KNOWN_DRIFT: &[Drift] = &[ + Drift { + cause: Cause::Comment, + issue: 650, + min_k: 0, + }, + Drift { + cause: Cause::UnterminatedString, + issue: 651, + min_k: 0, + }, + Drift { + cause: Cause::UnicodeLetter, + issue: 650, + min_k: 0, + }, + Drift { + cause: Cause::BareColon, + issue: 651, + min_k: 0, + }, + Drift { + cause: Cause::LoneMinus, + issue: 651, + min_k: 0, + }, + Drift { + cause: Cause::EmptyQuery, + issue: 651, + min_k: 0, + }, + Drift { + cause: Cause::EmptyFind, + issue: 651, + min_k: 0, + }, + Drift { + cause: Cause::EmptyWhere, + issue: 651, + min_k: 1, + }, + Drift { + cause: Cause::EmptyWith, + issue: 651, + min_k: 1, + }, + Drift { + cause: Cause::UnknownKeyword, + issue: 651, + min_k: 1, + }, + Drift { + cause: Cause::ResumedSection, + issue: 651, + min_k: 3, + }, + Drift { + cause: Cause::CallHead, + issue: 651, + min_k: 3, + }, + Drift { + cause: Cause::AggregateHead, + issue: 651, + min_k: 4, + }, + Drift { + cause: Cause::RuleHead, + issue: 651, + min_k: 1, + }, + Drift { + cause: Cause::FactArity, + issue: 649, + min_k: 3, + }, +]; + +/// Characters the parser reads as part of a symbol after its first. +fn symbol_char(c: char) -> bool { + c.is_alphanumeric() || matches!(c, '?' | '_' | '-' | '/') +} + +/// The first cause, in text order, of a lexical failure. +fn lexical_cause(text: &str) -> Option { + let c: Vec = text.chars().collect(); + let mut i = 0; + while i < c.len() { + let next = c.get(i + 1).copied(); + match c[i] { + '"' => { + i += 1; + loop { + match c.get(i) { + None => return Some(Cause::UnterminatedString), + Some('\\') => i += 2, + Some('"') => break, + Some(_) => i += 1, + } + } + } + ';' => return Some(Cause::Comment), + ':' if !next.is_some_and(symbol_char) => return Some(Cause::BareColon), + '-' if !next.is_some_and(symbol_char) + && !(i > 0 && (symbol_char(c[i - 1]) || matches!(c[i - 1], ':' | '#' | '$'))) => + { + return Some(Cause::LoneMinus); + } + ch if !ch.is_ascii() && ch.is_alphanumeric() => return Some(Cause::UnicodeLetter), + _ => {} + } + i += 1; + } + None +} + +/// The first cause, in text order, of a structural failure, read from the parser's +/// EDN tree of the input (glued tokens split as the parser splits them). +fn structural_cause(text: &str) -> Option { + let EdnValue::List(cmd) = parse_edn(text).ok()? else { + return None; + }; + let arg = cmd.get(1); + match cmd.first()? { + EdnValue::Symbol(s) if s == "query" => query_cause(arg?.as_vector()?), + EdnValue::Symbol(s) if s == "rule" => rule_cause(arg?.as_vector()?), + EdnValue::Symbol(s) if s == "transact" => cmd.last()?.as_vector()?.iter().find_map(|f| { + let f = f.as_vector()?; + (f.len() > 4 && f[3].is_map()).then_some(Cause::FactArity) + }), + _ => None, + } +} + +/// Walks the query vector's sections as `parse_query` does. +fn query_cause(items: &[EdnValue]) -> Option { + if items.is_empty() { + return Some(Cause::EmptyQuery); + } + let value_at = |j: usize| items.get(j).is_some_and(|v| v.as_keyword().is_none()); + // The section that values go to: `:find`, `:where`, or an unknown keyword. + let mut section: Option<&str> = None; + let mut i = 0; + while i < items.len() { + let Some(k) = items[i].as_keyword() else { + let cause = match section { + Some(":where") => clause_cause(&items[i]), + Some(":find") => find_cause(&items[i]), + _ => None, + }; + if cause.is_some() { + return cause; + } + i += 1; + continue; + }; + match k { + ":as-of" | ":valid-at" | ":max-derived-facts" | ":max-results" | ":any-valid-time" => { + i += if k == ":any-valid-time" { 1 } else { 2 }; + if section.is_some() && value_at(i) { + return Some(Cause::ResumedSection); + } + } + ":with" => { + if !value_at(i + 1) { + return Some(Cause::EmptyWith); + } + i += 1; + while value_at(i) { + i += 1; + } + } + _ if !value_at(i + 1) => { + return Some(match k { + ":find" => Cause::EmptyFind, + ":where" => Cause::EmptyWhere, + _ => Cause::UnknownKeyword, + }); + } + _ => { + section = Some(k); + i += 1; + } + } + } + None +} + +/// Whether pest's `plain_sym` reads all of `s`. +fn is_plain_symbol(s: &str) -> bool { + let word = |c: char| c.is_ascii_alphanumeric() || matches!(c, '?' | '_' | '-' | '/'); + let mut chars = s.chars(); + match chars.next() { + Some(c) if c.is_ascii_alphabetic() || c == '_' => chars.all(word), + Some('-') => !chars.as_str().is_empty() && chars.all(word), + _ => false, + } +} + +/// Whether pest's `op_sym` reads all of `s`. +fn is_op_symbol(s: &str) -> bool { + matches!(s, "<=" | ">=" | "!=" | "<" | ">" | "=" | "+" | "*" | "/") +} + +/// The cause in a `:find` spec: an aggregate or window list must start with a name. +fn find_cause(spec: &EdnValue) -> Option { + match spec.as_list()?.first()? { + EdnValue::Symbol(f) if !is_plain_symbol(f) && !is_op_symbol(f) => { + Some(Cause::AggregateHead) + } + _ => None, + } +} + +/// The first cause in a `:where` clause, a negation or disjunction body, or a rule body. +fn clause_cause(clause: &EdnValue) -> Option { + let list = clause.as_list()?; + let EdnValue::Symbol(head) = list.first()? else { + return None; + }; + let rest = &list[1..]; + match head.as_str() { + "not" => rest.iter().find_map(clause_cause), + "not-join" => rest.get(1..)?.iter().find_map(clause_cause), + "or" => rest.iter().find_map(branch_cause), + "or-join" => rest.get(1..)?.iter().find_map(branch_cause), + h if !is_plain_symbol(h) => Some(Cause::CallHead), + _ => None, + } +} + +fn branch_cause(branch: &EdnValue) -> Option { + match branch.as_list().map(Vec::as_slice) { + Some([EdnValue::Symbol(and), body @ ..]) if and == "and" => { + body.iter().find_map(clause_cause) + } + _ => clause_cause(branch), + } +} + +fn rule_cause(rule: &[EdnValue]) -> Option { + let head = rule.first()?.as_list()?; + let name_ok = matches!(head.first(), Some(EdnValue::Symbol(s)) if is_plain_symbol(s)); + let args_ok = head + .iter() + .skip(1) + .all(|a| matches!(a, EdnValue::Symbol(s) if s.starts_with('?'))); + if !(name_ok && args_ok) { + return Some(Cause::RuleHead); + } + rule[1..].iter().find_map(clause_cause) +} + +// ── The check ───────────────────────────────────────────────────────────── + +/// Which clause of the property an input breaks, if any. +fn failure(pest_ok: bool, parser: Outcome) -> Option { + match (pest_ok, parser) { + (false, Outcome::Accept) => Some("pest rejects, parser accepts".to_string()), + (true, Outcome::Reject(code)) if !is_semantic(code) => Some(format!( + "pest accepts, parser rejects with syntax code {code}" + )), + _ => None, + } +} + +/// How many failures an entry matched, and the first. +#[derive(Default, Clone)] +struct Hits { + count: u64, + first: Option, +} + +impl Hits { + fn add(&mut self, shown: &str) { + self.count += 1; + if self.first.is_none() { + self.first = Some(shown.to_string()); + } + } + + fn merge(&mut self, other: Hits) { + self.count += other.count; + if self.first.is_none() { + self.first = other.first; + } + } +} + +const SHOWN: usize = 20; + +#[derive(Default)] +struct Report { + inputs: u64, + /// One per [`KNOWN_DRIFT`] entry. + known: Vec, + /// Failures with no known cause, by reason. + unknown: Vec<(String, Hits)>, + /// The first [`SHOWN`] failures with no known cause. + unknown_shown: Vec, +} + +impl Report { + fn new() -> Self { + Report { + known: vec![Hits::default(); KNOWN_DRIFT.len()], + ..Report::default() + } + } + + fn check(&mut self, level: Level, text: &str, pest_ok: bool, parser: Outcome) { + self.inputs += 1; + let Some(why) = failure(pest_ok, parser) else { + return; + }; + let cause = match level { + Level::Lexical => lexical_cause(text), + Level::Structural => structural_cause(text), + }; + let shown = format!("{text:?} ({why})"); + match KNOWN_DRIFT.iter().position(|d| Some(d.cause) == cause) { + Some(i) => self.known[i].add(&shown), + None => { + if self.unknown_shown.len() < SHOWN { + self.unknown_shown.push(shown.clone()); + } + match self.unknown.iter_mut().find(|(w, _)| *w == why) { + Some((_, hits)) => hits.add(&shown), + None => { + let mut hits = Hits::default(); + hits.add(&shown); + self.unknown.push((why, hits)); + } + } + } + } + } + + /// Adds `other`, whose inputs come after this report's. + fn merge(&mut self, other: Report) { + self.inputs += other.inputs; + for (h, o) in self.known.iter_mut().zip(other.known) { + h.merge(o); + } + for (why, o) in other.unknown { + match self.unknown.iter_mut().find(|(w, _)| *w == why) { + Some((_, hits)) => hits.merge(o), + None => self.unknown.push((why, o)), + } + } + let room = SHOWN - self.unknown_shown.len(); + self.unknown_shown + .extend(other.unknown_shown.into_iter().take(room)); + } + + /// Prints the entries' matches and fails on any failure with no known cause, or + /// on an entry of `level` that matched nothing although `k` reaches it. + fn finish(self, level: Level, k: usize) { + let mut out = String::new(); + let mut stale = false; + for (d, h) in KNOWN_DRIFT.iter().zip(&self.known) { + if d.cause.level() != level { + continue; + } + match &h.first { + Some(first) => { + let _ = writeln!( + out, + " known {:?} (#{}): {} inputs, first {first}", + d.cause, d.issue, h.count + ); + } + None if level == Level::Lexical || k >= d.min_k => { + stale = true; + let _ = writeln!( + out, + " STALE {:?} (#{}): matched no failing input; remove the entry", + d.cause, d.issue + ); + } + None => {} + } + } + let summary = format!("{level:?} level, k = {k}, {} inputs:\n{out}", self.inputs); + if self.unknown.is_empty() && !stale { + eprintln!("{summary}"); + return; + } + let mut msg = summary; + if !self.unknown.is_empty() { + msg.push_str("failures with no known cause, by reason:\n"); + for (why, h) in &self.unknown { + let first = h.first.as_deref().unwrap_or(""); + let _ = writeln!(msg, " {} x {why}; first {first}", h.count); + } + msg.push_str("the first of them:\n"); + for u in &self.unknown_shown { + let _ = writeln!(msg, " {u}"); + } + } + panic!("grammar drift:\n{msg}"); + } +} + +/// Checks every string of `len` characters whose first character is in `first`. +fn check_lexical(chars: &[char], len: usize, first: std::ops::Range) -> Report { + let mut report = Report::new(); + let mut digits = vec![0usize; len]; + digits[0] = first.start; + let mut text = String::new(); + loop { + text.clear(); + text.extend(digits.iter().map(|&d| chars[d])); + let pest_ok = G::parse(Rule::edn_value_only, &text).is_ok(); + report.check(Level::Lexical, &text, pest_ok, outcome(parse_edn(&text))); + // Odometer step: the last digit turns fastest. + let mut i = len - 1; + loop { + digits[i] += 1; + if digits[i] < if i == 0 { first.end } else { chars.len() } { + break; + } + if i == 0 { + return report; + } + digits[i] = 0; + i -= 1; + } + } +} + +fn check_template(template: usize, k: usize) -> Report { + let (prefix, suffix) = TEMPLATES[template]; + let mut report = Report::new(); + let mut text = String::new(); + for len in 0..=k { + each_filler(len, &mut |filler| { + for sep in [" ", ""] { + if sep.is_empty() && len > GLUE_BOUND { + continue; + } + text.clear(); + text.push_str(prefix); + for &t in filler { + text.push_str(sep); + text.push_str(TOKENS[usize::from(t)]); + } + text.push_str(sep); + text.push_str(suffix); + let pest_ok = G::parse(Rule::command, &text).is_ok(); + let parser = outcome(parse_datalog_command(&text)); + report.check(Level::Structural, &text, pest_ok, parser); + } + }); + } + report +} + +/// Runs `jobs` on scoped threads and merges their reports in job order. +fn run(jobs: Vec, f: impl Fn(J) -> Report + Sync) -> Report { + let f = &f; + std::thread::scope(|s| { + let handles: Vec<_> = jobs.into_iter().map(|j| s.spawn(move || f(j))).collect(); + let mut total = Report::new(); + for h in handles { + total.merge(h.join().expect("verifier worker panicked")); + } + total + }) +} + +#[test] +fn lexical_level() { + let chars = alphabet(); + assert_eq!(chars.len(), 102, "alphabet size"); + let n = chars.len(); + let parts = std::thread::available_parallelism().map_or(4, |p| p.get().min(n)); + // One job per (length, range of first characters), in input order. + let jobs: Vec<_> = (1..=LEXICAL_MAX_LEN) + .flat_map(|len| (0..parts).map(move |p| (len, p * n / parts..(p + 1) * n / parts))) + .collect(); + run(jobs, |(len, first)| check_lexical(&chars, len, first)).finish(Level::Lexical, 0); +} + +#[test] +fn structural_level() { + let k = bound(); + run((0..TEMPLATES.len()).collect(), |t| check_template(t, k)).finish(Level::Structural, k); +} + +#[test] +fn filler_counts_match_the_spec() { + let count = |k: usize| { + let mut n = 0u64; + for len in 0..=k { + each_filler(len, &mut |_| n += 1); + } + n + }; + assert_eq!(count(3), 18_516); + assert_eq!(count(4), 487_678); +} + +#[test] +fn semantic_witnesses_raise_their_code() { + for s in SEMANTIC { + assert!( + G::parse(Rule::command, s.witness).is_ok(), + "pest rejects the witness of {}", + s.code + ); + assert_eq!( + outcome(parse_datalog_command(s.witness)), + Outcome::Reject(s.code), + "witness of {}", + s.code + ); + } +} diff --git a/tests/grammar/grammar.pest b/tests/grammar/grammar.pest index f70f825fe..5fae33350 100644 --- a/tests/grammar/grammar.pest +++ b/tests/grammar/grammar.pest @@ -5,6 +5,28 @@ WHITESPACE = _{ " " | "\t" | "\n" | "\r" | "," } // Used in negative lookaheads to enforce keyword boundaries. word_cont = _{ ASCII_ALPHANUMERIC | "?" | "_" | "-" | "/" } +// Literal keywords: atomic, so that no whitespace is skipped before the +// boundary check (":find?x" is one keyword, as the parser reads it). +kw_find = @{ ":find" ~ !word_cont } +kw_where = @{ ":where" ~ !word_cont } +kw_with = @{ ":with" ~ !word_cont } +kw_as_of = @{ ":as-of" ~ !word_cont } +kw_valid_at = @{ ":valid-at" ~ !word_cont } +kw_any_valid_time = @{ ":any-valid-time" ~ !word_cont } +kw_max_derived_facts = @{ ":max-derived-facts" ~ !word_cont } +kw_max_results = @{ ":max-results" ~ !word_cont } +kw_over = @{ ":over" ~ !word_cont } +kw_partition_by = @{ ":partition-by" ~ !word_cont } +kw_order_by = @{ ":order-by" ~ !word_cont } +kw_desc = @{ ":desc" ~ !word_cont } +kw_asc = @{ ":asc" ~ !word_cont } +kw_valid_from = @{ ":valid-from" ~ !word_cont } +kw_valid_to = @{ ":valid-to" ~ !word_cont } + +// Reserved list heads: the parser reads these lists as clauses, never as rule calls. +reserved_head = @{ ("not-join" | "not" | "or-join" | "or") ~ !word_cont } +and_head = @{ "and" ~ !word_cont } + // ── EDN PRIMITIVES ──────────────────────────────────────────────────────── // boolean: "true" or "false" — only when NOT followed by a word character @@ -59,6 +81,9 @@ edn_list = { "(" ~ edn_value* ~ ")" } edn_vector = { "[" ~ edn_value* ~ "]" } edn_map = { "{" ~ (edn_value ~ edn_value)* ~ "}" } +// One EDN value and nothing else: the lexical oracle of the parser verifier (#643). +edn_value_only = { SOI ~ edn_value ~ EOI } + // ── TOP-LEVEL COMMAND ───────────────────────────────────────────────────── command = { SOI ~ (transact_cmd | retract_cmd | query_cmd | rule_cmd) ~ EOI } @@ -69,18 +94,20 @@ transact_cmd = { } // ── RETRACT ─────────────────────────────────────────────────────────────── -retract_cmd = { "(" ~ "retract" ~ fact_vector ~ ")" } +retract_cmd = { "(" ~ "retract" ~ "[" ~ retract_fact* ~ "]" ~ ")" } // Fact vector: a vector of individual fact vectors fact_vector = { "[" ~ fact* ~ "]" } -// A single fact: permissive (edn_value+) so arity violations are semantic, not syntax. -// The real parser enforces [E A V] or [E A V {map}]; pest only requires ≥1 element. -fact = { "[" ~ edn_value+ ~ "]" } +// A single fact: exactly [E A V] or [E A V {valid-time map}]. +fact = { "[" ~ edn_value ~ edn_value ~ edn_value ~ valid_time_map? ~ "]" } + +// A retracted fact: exactly [E A V]. +retract_fact = { "[" ~ edn_value ~ edn_value ~ edn_value ~ "]" } // Transaction-level valid-time options map valid_time_map = { "{" ~ valid_time_pair* ~ "}" } -valid_time_pair = { (":valid-from" | ":valid-to") ~ string_lit } +valid_time_pair = { (kw_valid_from | kw_valid_to) ~ string_lit } // ── QUERY ───────────────────────────────────────────────────────────────── query_cmd = { "(" ~ "query" ~ query_vector ~ ")" } @@ -95,7 +122,7 @@ query_section = { // ── FIND SECTION ────────────────────────────────────────────────────────── // :find accepts variables, aggregates, and window functions -find_section = { ":find" ~ find_spec+ } +find_section = { kw_find ~ find_spec+ } find_spec = { window_expr | aggregate_expr | variable } // Aggregate: (func-name ?var) — e.g. (count ?e), (sum ?salary) @@ -103,17 +130,17 @@ aggregate_expr = { "(" ~ (op_sym | plain_sym) ~ variable ~ ")" } // Window function: (func ?var :over (...)) or (func :over (...)) for rank/row-number window_expr = { - "(" ~ (op_sym | plain_sym) ~ (variable ~ ":over" | ":over") ~ over_clause ~ ")" + "(" ~ (op_sym | plain_sym) ~ (variable ~ kw_over | kw_over) ~ over_clause ~ ")" } over_clause = { "(" ~ over_option* ~ ")" } over_option = { - ":partition-by" ~ variable | - ":order-by" ~ variable | - ":desc" | ":asc" + kw_partition_by ~ variable | + kw_order_by ~ variable | + kw_desc | kw_asc } // ── WHERE SECTION ───────────────────────────────────────────────────────── -where_section = { ":where" ~ where_clause+ } +where_section = { kw_where ~ where_clause+ } // where_clause covers all clause forms where_clause = { @@ -136,11 +163,11 @@ not_join_clause = { "(" ~ "not-join" ~ join_vars ~ where_clause+ ~ ")" } or_clause = { "(" ~ "or" ~ or_branch+ ~ ")" } or_join_clause = { "(" ~ "or-join" ~ join_vars ~ or_branch+ ~ ")" } join_vars = { "[" ~ variable* ~ "]" } -or_branch = { and_branch | where_clause } +or_branch = { and_branch | !("(" ~ and_head) ~ where_clause } and_branch = { "(" ~ "and" ~ where_clause+ ~ ")" } // Rule invocation: (predicate-name args...) -rule_invocation = { "(" ~ plain_sym ~ edn_value* ~ ")" } +rule_invocation = { "(" ~ !reserved_head ~ plain_sym ~ edn_value* ~ ")" } // ── EXPRESSIONS ─────────────────────────────────────────────────────────── expr = { "(" ~ expr_body ~ ")" } @@ -158,12 +185,12 @@ expr_arg = { } // ── TEMPORAL / WITH SECTIONS ─────────────────────────────────────────────── -as_of_section = { ":as-of" ~ (integer_lit | string_lit | bind_slot) } -valid_at_section = { ":valid-at" ~ (string_lit | ":any-valid-time" | bind_slot) } -any_valid_time_section = { ":any-valid-time" } -with_section = { ":with" ~ variable+ } -max_derived_facts_section = { ":max-derived-facts" ~ integer_lit } -max_results_section = { ":max-results" ~ integer_lit } +as_of_section = { kw_as_of ~ (integer_lit | string_lit | bind_slot) } +valid_at_section = { kw_valid_at ~ (string_lit | kw_any_valid_time | bind_slot) } +any_valid_time_section = { kw_any_valid_time } +with_section = { kw_with ~ variable+ } +max_derived_facts_section = { kw_max_derived_facts ~ integer_lit } +max_results_section = { kw_max_results ~ integer_lit } // ── RULE ────────────────────────────────────────────────────────────────── // (rule [(head ?args) body-clause ...]) diff --git a/tests/grammar/invalid/semantic/fact_too_few_elements.edn b/tests/grammar/invalid/syntax/fact_too_few_elements.edn similarity index 100% rename from tests/grammar/invalid/semantic/fact_too_few_elements.edn rename to tests/grammar/invalid/syntax/fact_too_few_elements.edn diff --git a/tests/grammar/invalid/semantic/retract_wrong_arity.edn b/tests/grammar/invalid/syntax/retract_wrong_arity.edn similarity index 100% rename from tests/grammar/invalid/semantic/retract_wrong_arity.edn rename to tests/grammar/invalid/syntax/retract_wrong_arity.edn