From 06ee84bef98adf85391fadcc304f04432238a172 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 16:07:39 +0530 Subject: [PATCH] feat(errors): PRS-083..PRS-107 replace user-facing INT-019 parse errors (#643) The parser's long-tail syntax and structure errors shared INT-019 with a "datalog parser: " prefix. Each user-reachable site now has its own Parser-category code with today's text, and parse_retract checks the fact arity itself (PRS-090, was INT-000 via Pattern::from_edn). The four unreachable invariant sites keep INT-019. ERROR_REFERENCE.md gets a row and section per code; the INT-019 section lists what replaced it. Plan steps 1-5 of docs/superpowers/plans/2026-10-20-643-grammar-verifier.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019kY61Y11gcRD91Y6b7jbGT --- CHANGELOG.md | 1 + CLAUDE.md | 2 +- README.md | 2 +- docs/ERROR_REFERENCE.md | 414 +++++++++++++++++++++++++++++++++- docs/TEST_COVERAGE.md | 3 +- src/error.rs | 225 ++++++++++++++++++ src/query/datalog/parser.rs | 122 +++------- tests/error_codes_prs_test.rs | 244 ++++++++++++++++++++ 8 files changed, 911 insertions(+), 102 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cdfcb3dd..37511a804 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **A pseudo-attribute pattern never gives a variable its value** (#606). A variable bound by several patterns returns the value of the first real pattern in the `:where` text that binds it (#545); a `:db/valid-at` pattern that the planner ran first used to bind its entity variable itself, as a ref, so `[:find ?b ?t :where [?b :db/valid-at ?t] [?a :friend ?b] [?b :name "Bob"]]` returned the ref of `:bob` with source order and the keyword `:bob` stored by `:friend` natively. It returns the keyword now, whatever runs first. Only the keyword-or-ref kind changes; rows and counts are the same. - **Every build reorders query clauses; the `wasm` feature does nothing** (#594, #596). The `wasm` Cargo feature kept patterns, `not` clauses and `or` branches in source order and turned off the `or` short-circuits (#250), for small browser datasets and a predictable order. With every answer independent of the plan (#594, #596, #606) it only made queries slower, and no first-party build enabled it (the browser package uses `browser`). The feature is kept, so builds that name it still resolve, but is deprecated and has no effect. - **Aggregate and window answers no longer depend on the order of their input** (#547). Before, aggregates and window functions read their rows in the order the plan produced them, and several answers followed that order. Six cases changed. (1) `sum` over floats is exact: the values are added without rounding and the total is rounded once, so `1e16 + 1.0 + -1e16 + 1.0 + 0.5` gives `2.5` in every order (before, `1.5` or `2.5`). Window `sum` and `avg` likewise. (2) `sum` over integers saturates once, at the end: `i64::MAX + 1 + -1` gives `i64::MAX` (before, `i64::MAX - 1` or `i64::MAX` by order). (3) Window `sum` over integers adds them exactly; before they were added as floats, so a running total above 2^53 lost its low digits. (4) `min` / `max` of floats follow one order: `-0.0` before `0.0`, NaN after every other number (before, the first of two such values seen won). Window `min` / `max` use the same order over any values, so the minimum of keywords is the first in text order. (5) Window functions sort each partition by `:order-by` under one total order of values (numbers by numeric value, an integer before an equal float, then strings, booleans, refs, keywords, `nil`), so keywords, refs and booleans now sort (before, any two of them compared equal and kept their input order). Rows with equal `:order-by` values are peers: `rank` gives them the same rank, and `sum`, `count`, `min`, `max`, `avg` and registered window functions give every peer the value at the last peer, as SQL does; `row-number` numbers peers in the order of the other variables `:find` names. For example, with `?s` of 1.5, 5, 10, 10, `(sum ?s :over (:order-by ?s))` gave 1.5, 6.5, 16.5, 26.5, the 16.5 going to either tied row, and now gives 1.5, 6.5, 26.5, 26.5; ranking `:x :x :y :y` by `:order-by` gave ranks depending on the order the scan met them (1 2 3 4 when interleaved) and now gives 1 1 3 3. (6) In a query with aggregates, a window's argument, `:partition-by` and `:order-by` must be plain `:find` variables, or the query fails at parse time with the new `PRS-082`; before, any other variable read `nil` on every group row. The error a failing aggregate query reports is the first error, in `:find` order, of the first failing group in output order. A registered aggregate still receives its values in input order, which can depend on the plan; one whose result depends on that order may answer equivalent queries differently. (7) A group whose grouping variable holds floats that are equal as groups compare them (`-0.0` and `0.0`, or NaNs) returns the least of them in that order, so `-0.0` when the group holds it; before, it returned the first one the plan met. +- **Parse errors that were `INT-019` now carry their own `PRS` codes** (#643). The parser's long-tail syntax and structure errors (a bind slot with no name, a window without `:order-by`, a non-vector query, malformed `:with`, `:find`, valid-time map, retract fact, `not`/`not-join`/`or` body, pattern and rule) used one internal code, `INT-019`, with a `datalog parser: ` prefix. Each now has its own Parser-category code, `PRS-083` to `PRS-107`, documented in `docs/ERROR_REFERENCE.md`; the message is the old text without the prefix. A retract fact without exactly three elements was `INT-000` and is now `PRS-090`. Code that matches on `INT-019` (or `INT-000` for retract arity), or on the `Internal` category, for these errors must match the new codes. `INT-019` stays registered for parser invariants no input is known to reach. ### Added diff --git a/CLAUDE.md b/CLAUDE.md index c6e63cba8..2bbaa5fea 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -205,7 +205,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1620 tests** (1610 passing, 10 ignored; unit + integration + doc). +**1646 tests** (1636 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 5aa760d3c..dce536d39 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 1620 tests +cargo test # run 1646 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index bef8069a3..585e12f33 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -103,6 +103,31 @@ with no `CodedError` anywhere in its chain. | PRS-080 | :find variable not bound in :where | Parser | | PRS-081 | Pseudo-attribute has no source pattern | Parser | | PRS-082 | Window reads a non-grouping variable | Parser | +| PRS-083 | Bind slot without a name | Parser | +| PRS-084 | Window without :order-by | Parser | +| PRS-085 | Query argument is not a vector | Parser | +| PRS-086 | :with holds a non-variable | Parser | +| PRS-087 | :find element is not a variable or aggregate | Parser | +| PRS-088 | Unknown key in valid-time map | Parser | +| PRS-089 | Retract fact is not a vector | Parser | +| PRS-090 | Retract fact must have 3 elements | Parser | +| PRS-091 | Invalid regex pattern | Parser | +| PRS-092 | Item inside (not) is not a clause | Parser | +| PRS-093 | not-join inside not or not-join | Parser | +| PRS-094 | not-join without a join-variable vector | Parser | +| PRS-095 | not-join join variable is not a variable | Parser | +| PRS-096 | Item inside (not-join) is not a clause | Parser | +| PRS-097 | Rule invocation without a predicate name | Parser | +| PRS-098 | Pattern must have 3 elements | Parser | +| PRS-099 | Item inside or branch is not a clause | Parser | +| PRS-100 | Rule without a body | Parser | +| PRS-101 | Rule body is not a vector | Parser | +| PRS-102 | Rule body is empty | Parser | +| PRS-103 | Rule head is not a list | Parser | +| PRS-104 | Rule head is empty | Parser | +| PRS-105 | Rule head without a predicate name | Parser | +| PRS-106 | Rule body clause is not a vector or list | Parser | +| PRS-107 | Rule body has no clause | Parser | | QRY-001 | Invalid entity | Query Execution | | QRY-002 | Attribute must be a keyword | Query Execution | | QRY-003 | Cannot transact a pseudo-attribute | Query Execution | @@ -1613,6 +1638,381 @@ $<4097-char-slot-name> ``` *`?salary` is aggregated, not a group: order by `?dept`, or drop `(sum ?salary)`* +### PRS-083 Bind slot without a name + +**Error text**: `Bind slot '$' must be followed by an identifier (e.g. $entity)` + +**Cause**: A `$` in a query is not followed by an identifier. Bind slots name the value supplied at execution time, as `$entity` or `$min-age`. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Name the slot: `$name`, then pass a value for `name` when executing the prepared query. + +**Example**: +```datalog +(query [:find ?e :where [?e :name $]]) +``` +*Write `$name` and bind `name`* + +### PRS-084 Window without :order-by + +**Error text**: `':order-by' is required in the ':over' clause` + +**Cause**: A window function's `:over` clause has no `:order-by`. Every window orders its rows; `:partition-by` is optional, `:order-by` is not. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Add `(:order-by ?var)` to the `:over` clause. + +**Example**: +```datalog +(query [:find ?e (rank :over (:partition-by ?d)) :where [?e :dept ?d]]) +``` +*Add `:order-by`, e.g. `(:partition-by ?d :order-by ?e)`* + +### PRS-085 Query argument is not a vector + +**Error text**: `Query argument must be a vector` + +**Cause**: The argument of `(query ...)` is not a vector. A query is one vector holding `:find`, optional `:with`, `:where` and the temporal keywords. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Wrap the query in square brackets: `(query [:find ... :where ...])`. + +**Example**: +```datalog +(query (:find ?e :where [?e :a ?v])) +``` +*Use `[` `]`, not `(` `)`* + +### PRS-086 :with holds a non-variable + +**Error text**: `':with' clause accepts only variables, got {}` + +**Cause**: An element of `:with` is not a logic variable. `:with` lists variables that keep otherwise identical rows apart before aggregation. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- List only `?variables` after `:with`. + +**Example**: +```datalog +(query [:find (count ?e) :with 7 :where [?e :a ?v]]) +``` +*`7` is not a variable; write `:with ?v`* + +### PRS-087 :find element is not a variable or aggregate + +**Error text**: `Expected variable or aggregate expression in :find clause, got {}` + +**Cause**: An element of `:find` is neither a logic variable nor an aggregate or window expression such as `(count ?e)`. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Return variables bound in `:where`, or aggregate them. + +**Example**: +```datalog +(query [:find 7 :where [?e :a ?v]]) +``` +*`7` is a constant; return a variable* + +### PRS-088 Unknown key in valid-time map + +**Error text**: `Unknown key in valid-time map: {}; expected :valid-from or :valid-to` + +**Cause**: The map before a `transact`'s facts, or the fourth element of a fact, holds a key other than `:valid-from` or `:valid-to`. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Use only `:valid-from` and `:valid-to`; both are optional. + +**Example**: +```datalog +(transact {:valid-at "2024-01-01"} [[:alice :name "Alice"]]) +``` +*Write `:valid-from`* + +### PRS-089 Retract fact is not a vector + +**Error text**: `Each fact must be a vector [e a v]` + +**Cause**: An element of the `(retract [...])` vector is not a fact vector. Each fact to retract is a vector `[entity attribute value]`. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Wrap each fact in its own vector: `(retract [[:alice :name "Alice"]])`. + +**Example**: +```datalog +(retract [:alice]) +``` +*Write `[[:alice :name "Alice"]]`* + +### PRS-090 Retract fact must have 3 elements + +**Error text**: `Retract fact must have exactly 3 elements (E A V), got {}` + +**Cause**: A fact in `(retract [...])` does not have exactly three elements. A retraction names one fact by entity, attribute and value; it takes no valid-time map. Before v3.0.0 this was `INT-000`. + +**Resolution**: +- Give entity, attribute and value: `[:alice :name "Alice"]`. + +**Example**: +```datalog +(retract [[:alice :name]]) +``` +*The value is missing* + +### PRS-091 Invalid regex pattern + +**Error text**: `invalid regex pattern {}: {}` + +**Cause**: The pattern given to `matches?` is not a valid regular expression. The error shows the pattern and the regex error. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Fix the pattern; escape regex metacharacters such as `(`, `[` and `.` with `\\` inside the string. + +**Example**: +```datalog +(query [:find ?e :where [?e :name ?n] [(matches? ?n "(")]]) +``` +*`(` opens a group that never closes; write `"\\("`* + +### PRS-092 Item inside (not) is not a clause + +**Error text**: `expected pattern or rule invocation inside (not), got {}` + +**Cause**: An item inside `(not ...)` is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Put patterns `[?e :attr ?v]` or rule calls `(rule-name ?x)` inside `not`. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (not 7)]) +``` +*`7` is not a clause* + +### PRS-093 not-join inside not or not-join + +**Error text**: `(not-join ...) cannot appear inside another (not ...) or (not-join ...)` + +**Cause**: A `(not-join ...)` appears inside another `(not ...)` or `(not-join ...)`. Negations do not nest. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Move the inner negation out, or express it as a rule and call the rule inside the outer `not`. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (not (not-join [?e] [?e :b 1]))]) +``` +*Write the inner `not-join` as a rule, or move it to the top level* + +### PRS-094 not-join without a join-variable vector + +**Error text**: `(not-join) first argument must be a vector of join variables` + +**Cause**: The first argument of `(not-join ...)` is not a vector. `not-join` takes the variables it shares with the outer query as a vector, then its clauses. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Write the join variables in square brackets: `(not-join [?e] ...)`. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (not-join ?e [?e :b 1])]) +``` +*Write `[?e]`* + +### PRS-095 not-join join variable is not a variable + +**Error text**: `(not-join) join variables must be logic variables, got {}` + +**Cause**: An element of `not-join`'s join-variable vector is not a logic variable. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- List only `?variables` in the vector. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (not-join [7] [?e :b 1])]) +``` +*`7` is not a variable* + +### PRS-096 Item inside (not-join) is not a clause + +**Error text**: `expected pattern or rule invocation inside (not-join), got {}` + +**Cause**: An item after `not-join`'s join variables is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Put patterns `[?e :attr ?v]` or rule calls `(rule-name ?x)` after the join variables. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (not-join [?e] 7)]) +``` +*`7` is not a clause* + +### PRS-097 Rule invocation without a predicate name + +**Error text**: `Rule invocation must start with predicate name (symbol), got {}` + +**Cause**: A list in `:where` or a rule body does not start with a symbol, so it is not a rule invocation (nor `not`, `or` or another clause form). Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Start the list with the rule's name: `(reachable ?a ?b)`. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (7 ?e)]) +``` +*`7` is not a rule name* + +### PRS-098 Pattern must have 3 elements + +**Error text**: `Pattern must have exactly 3 elements (E A V), got {}` + +**Cause**: A pattern vector in `:where`, a rule body, or a `not`/`or` body does not have exactly three elements: entity, attribute and value. Use `_` for a position you do not care about. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Give all three positions: `[?e :attr ?v]` or `[?e :attr _]`. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] [?e :b]]) +``` +*Write `[?e :b _]`* + +### PRS-099 Item inside or branch is not a clause + +**Error text**: `expected clause inside or branch, got {}` + +**Cause**: An item inside `(or ...)`, `(or-join ...)` or `(and ...)` is neither a vector (a pattern or an expression clause) nor a list (a rule invocation or another clause form). Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Make each branch a pattern, a rule call, or an `(and ...)` of clauses. + +**Example**: +```datalog +(query [:find ?e :where [?e :a ?v] (or 7)]) +``` +*`7` is not a clause* + +### PRS-100 Rule without a body + +**Error text**: `Rule must have a body` + +**Cause**: `(rule)` has no argument. A rule is one vector: a head list, then one or more body clauses. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Write `(rule [(name ?args) clause ...])`. + +**Example**: +```datalog +(rule) +``` +*Add the rule vector* + +### PRS-101 Rule body is not a vector + +**Error text**: `Rule body must be a vector` + +**Cause**: The argument of `(rule ...)` is not a vector. The head and body go inside one vector. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Wrap head and body in square brackets: `(rule [(reachable ?a ?b) [?a :edge ?b]])`. + +**Example**: +```datalog +(rule (reachable ?a ?b)) +``` +*Put the head and its clauses in `[` `]`* + +### PRS-102 Rule body is empty + +**Error text**: `Rule body cannot be empty` + +**Cause**: The rule vector is empty: it has no head and no clauses. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Write the head list, then at least one clause. + +**Example**: +```datalog +(rule []) +``` +*Add `(name ?args)` and a clause* + +### PRS-103 Rule head is not a list + +**Error text**: `Rule head must be a list: (predicate ?args)` + +**Cause**: The first element of the rule vector is not a list. The head names the rule and its arguments: `(predicate ?args)`. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Write the head as a list: `(reachable ?a ?b)`. + +**Example**: +```datalog +(rule [reachable [?a :edge ?b]]) +``` +*Write `(reachable ?a ?b)`* + +### PRS-104 Rule head is empty + +**Error text**: `Rule head cannot be empty` + +**Cause**: The rule head is `()`: it has no predicate name. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Name the rule and its arguments: `(reachable ?a ?b)`. + +**Example**: +```datalog +(rule [() [?a :edge ?b]]) +``` +*Write `(reachable ?a ?b)`* + +### PRS-105 Rule head without a predicate name + +**Error text**: `Rule head must start with a symbol (predicate name)` + +**Cause**: The rule head does not start with a symbol, so the rule has no name. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Start the head with the rule's name: `(reachable ?a ?b)`. + +**Example**: +```datalog +(rule [(7 ?a) [?a :edge ?b]]) +``` +*`7` is not a name* + +### PRS-106 Rule body clause is not a vector or list + +**Error text**: `Rule body clause must be a vector (pattern) or list (rule invocation / not), got {}` + +**Cause**: An element after the rule head is neither a vector (a pattern or an expression clause) nor a list (a rule invocation, `not`, `or` or another clause form). Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Write each body clause as `[?e :attr ?v]` or `(name ?args)`. + +**Example**: +```datalog +(rule [(reachable ?a) 7]) +``` +*`7` is not a clause* + +### PRS-107 Rule body has no clause + +**Error text**: `Rule must have at least one pattern or rule invocation in body` + +**Cause**: The rule vector holds a head and nothing else. A rule derives its head from at least one body clause. Before v3.0.0 this was `INT-019`. + +**Resolution**: +- Add a pattern or rule invocation after the head. + +**Example**: +```datalog +(rule [(reachable ?a)]) +``` +*Add a clause, e.g. `[?a :edge ?b]`* + --- ## QRY — Query Execution Errors @@ -3060,14 +3460,16 @@ earlier clause in the query. **Error text**: `datalog parser: {}` -**Cause**: A shared catch-all for the parser's remaining long-tail syntax -and structural errors (malformed `:with`/`:find` clauses, malformed -fact/rule/pattern vectors, invalid regex literals in `matches?`, and -similar). The `{}` carries the specific underlying message. +**Cause**: An invariant inside the parser does not hold. No input is known +to reach it; if you see it, please report it with the input. + +Before v3.0.0 this code was also the parser's catch-all for long-tail syntax +and structural errors. From v3.0.0 those carry their own codes: `PRS-083` to +`PRS-107` (`PRS-090` replaced `INT-000` for the retract arity). Code that +matches on `INT-019` for those errors must match the new codes. **Resolution**: -- Read the wrapped message text for the specific syntax problem and correct - the input accordingly. +- Report the input that raised it as a bug. ### INT-020 Evaluator iteration/result limit exceeded diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index a17ab9ec9..afb9194c0 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,610 passing tests and 10 ignored tests (1,620 total) +**Result**: 1,636 passing tests and 10 ignored tests (1,646 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). @@ -23,6 +23,7 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value - **Negation equality** (`tests/negation_equality_test.rs`, 5 tests; #546): a value a `not` / `not-join` body takes from the outer row compares by join equality on every path (exclusion set, per-row body with an expression, a query that invokes a rule, a rule body): `1e-20` and `2e-20` differ, `0.0` equals `-0.0`, a keyword imported into an entity position equals the ref, and a float literal in the body still matches within `f64::EPSILON`; through `execute` and a cursor, in memory and after a checkpoint. Engine unit tests (`src/query/engine/tests.rs`, 6 more) run every negation shape (hashed and correlated bodies, keys on entity, value and attribute positions, floats, keywords and refs, long strings, bodies reading an imported variable, variable-free bodies, per-fact pseudo-attributes and `:db/valid-at` in bodies, deferred and repeated negations) at six temporal settings with each body form forced and reordering on and off, in memory and on file before and after checkpoints, against the executor; and check the form the planner picks, routing, multiplicity, failing expressions and unknown predicates in bodies, and that a hashed body is read once while a correlated one probes once per outer row. Optimizer unit tests cover `plan_seeded` and the `SUBPLANS` switch. - **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`. - **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/error.rs b/src/error.rs index aa532820d..9d4334d2d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -129,6 +129,31 @@ pub(crate) enum ErrorCode { Prs080, Prs081, Prs082, + Prs083, + Prs084, + Prs085, + Prs086, + Prs087, + Prs088, + Prs089, + Prs090, + Prs091, + Prs092, + Prs093, + Prs094, + Prs095, + Prs096, + Prs097, + Prs098, + Prs099, + Prs100, + Prs101, + Prs102, + Prs103, + Prs104, + Prs105, + Prs106, + Prs107, Qry001, Qry002, Qry003, @@ -779,6 +804,156 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "{} in {} must be a plain :find variable when the query has aggregates", ErrorCategory::Parser, ), + ( + ErrorCode::Prs083, + "PRS-083", + "Bind slot '$' must be followed by an identifier (e.g. $entity)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs084, + "PRS-084", + "':order-by' is required in the ':over' clause", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs085, + "PRS-085", + "Query argument must be a vector", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs086, + "PRS-086", + "':with' clause accepts only variables, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs087, + "PRS-087", + "Expected variable or aggregate expression in :find clause, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs088, + "PRS-088", + "Unknown key in valid-time map: {}; expected :valid-from or :valid-to", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs089, + "PRS-089", + "Each fact must be a vector [e a v]", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs090, + "PRS-090", + "Retract fact must have exactly 3 elements (E A V), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs091, + "PRS-091", + "invalid regex pattern {}: {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs092, + "PRS-092", + "expected pattern or rule invocation inside (not), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs093, + "PRS-093", + "(not-join ...) cannot appear inside another (not ...) or (not-join ...)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs094, + "PRS-094", + "(not-join) first argument must be a vector of join variables", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs095, + "PRS-095", + "(not-join) join variables must be logic variables, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs096, + "PRS-096", + "expected pattern or rule invocation inside (not-join), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs097, + "PRS-097", + "Rule invocation must start with predicate name (symbol), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs098, + "PRS-098", + "Pattern must have exactly 3 elements (E A V), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs099, + "PRS-099", + "expected clause inside or branch, got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs100, + "PRS-100", + "Rule must have a body", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs101, + "PRS-101", + "Rule body must be a vector", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs102, + "PRS-102", + "Rule body cannot be empty", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs103, + "PRS-103", + "Rule head must be a list: (predicate ?args)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs104, + "PRS-104", + "Rule head cannot be empty", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs105, + "PRS-105", + "Rule head must start with a symbol (predicate name)", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs106, + "PRS-106", + "Rule body clause must be a vector (pattern) or list (rule invocation / not), got {}", + ErrorCategory::Parser, + ), + ( + ErrorCode::Prs107, + "PRS-107", + "Rule must have at least one pattern or rule invocation in body", + ErrorCategory::Parser, + ), ( ErrorCode::Qry001, "QRY-001", @@ -2000,6 +2175,31 @@ mod tests { | ErrorCode::Prs080 | ErrorCode::Prs081 | ErrorCode::Prs082 + | ErrorCode::Prs083 + | ErrorCode::Prs084 + | ErrorCode::Prs085 + | ErrorCode::Prs086 + | ErrorCode::Prs087 + | ErrorCode::Prs088 + | ErrorCode::Prs089 + | ErrorCode::Prs090 + | ErrorCode::Prs091 + | ErrorCode::Prs092 + | ErrorCode::Prs093 + | ErrorCode::Prs094 + | ErrorCode::Prs095 + | ErrorCode::Prs096 + | ErrorCode::Prs097 + | ErrorCode::Prs098 + | ErrorCode::Prs099 + | ErrorCode::Prs100 + | ErrorCode::Prs101 + | ErrorCode::Prs102 + | ErrorCode::Prs103 + | ErrorCode::Prs104 + | ErrorCode::Prs105 + | ErrorCode::Prs106 + | ErrorCode::Prs107 | ErrorCode::Qry001 | ErrorCode::Qry002 | ErrorCode::Qry003 @@ -2228,6 +2428,31 @@ mod tests { ErrorCode::Prs080, ErrorCode::Prs081, ErrorCode::Prs082, + ErrorCode::Prs083, + ErrorCode::Prs084, + ErrorCode::Prs085, + ErrorCode::Prs086, + ErrorCode::Prs087, + ErrorCode::Prs088, + ErrorCode::Prs089, + ErrorCode::Prs090, + ErrorCode::Prs091, + ErrorCode::Prs092, + ErrorCode::Prs093, + ErrorCode::Prs094, + ErrorCode::Prs095, + ErrorCode::Prs096, + ErrorCode::Prs097, + ErrorCode::Prs098, + ErrorCode::Prs099, + ErrorCode::Prs100, + ErrorCode::Prs101, + ErrorCode::Prs102, + ErrorCode::Prs103, + ErrorCode::Prs104, + ErrorCode::Prs105, + ErrorCode::Prs106, + ErrorCode::Prs107, ErrorCode::Qry001, ErrorCode::Qry002, ErrorCode::Qry003, diff --git a/src/query/datalog/parser.rs b/src/query/datalog/parser.rs index bc49c1874..1faedbea0 100644 --- a/src/query/datalog/parser.rs +++ b/src/query/datalog/parser.rs @@ -251,10 +251,7 @@ fn tokenize(input: &str) -> Result> { } } if name.is_empty() { - bail_coded!( - ErrorCode::Int019, - "Bind slot '$' must be followed by an identifier (e.g. $entity)" - ); + bail_coded!(ErrorCode::Prs083); } tokens.push(Token::BindSlot(name)); } @@ -679,12 +676,7 @@ fn parse_window_expr(elems: &[EdnValue]) -> Result { j += 1; } - let order_by = order_by.ok_or_else(|| { - err_coded!( - ErrorCode::Int019, - "':order-by' is required in the ':over' clause" - ) - })?; + let order_by = order_by.ok_or_else(|| err_coded!(ErrorCode::Prs084))?; Ok(FindSpec::Window(WindowSpec { func, @@ -709,7 +701,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let query_vector = elements[0] .as_vector() - .ok_or_else(|| err_coded!(ErrorCode::Int019, "Query argument must be a vector"))?; + .ok_or_else(|| err_coded!(ErrorCode::Prs085))?; let mut find_specs: Vec = Vec::new(); let mut with_vars: Vec = Vec::new(); @@ -849,10 +841,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { } EdnValue::Keyword(_) => break, other => { - bail_coded!( - ErrorCode::Int019, - format!("':with' clause accepts only variables, got {other:?}") - ); + bail_coded!(ErrorCode::Prs086, format!("{other:?}")); } } } @@ -875,12 +864,7 @@ fn parse_query(elements: &[EdnValue]) -> Result { find_specs.push(parse_aggregate(elems)?); } other => { - bail_coded!( - ErrorCode::Int019, - format!( - "Expected variable or aggregate expression in :find clause, got {other:?}" - ) - ); + bail_coded!(ErrorCode::Prs087, format!("{other:?}")); } }, Some(":where") => { @@ -1119,12 +1103,7 @@ fn parse_valid_time_map(pairs: &[(EdnValue, EdnValue)]) -> Result<(Option, valid_to = Some(parse_timestamp(s)?); } _ => { - bail_coded!( - ErrorCode::Int019, - format!( - "Unknown key in valid-time map: {key:?}; expected :valid-from or :valid-to" - ) - ); + bail_coded!(ErrorCode::Prs088, format!("{key:?}")); } } } @@ -1152,7 +1131,10 @@ fn parse_retract(elements: &[EdnValue]) -> Result { for fact in facts_vector { let fact_vec = fact .as_vector() - .ok_or_else(|| err_coded!(ErrorCode::Int019, "Each fact must be a vector [e a v]"))?; + .ok_or_else(|| err_coded!(ErrorCode::Prs089))?; + if fact_vec.len() != 3 { + bail_coded!(ErrorCode::Prs090, fact_vec.len()); + } patterns.push(Pattern::from_edn(fact_vec).map_err(anyhow::Error::msg)?); } @@ -1232,10 +1214,7 @@ fn parse_expr(list: &[EdnValue]) -> Result { match &rhs { Expr::Lit(Value::String(pattern)) => { let compiled = regex_lite::Regex::new(pattern).map_err(|e| { - err_coded!( - ErrorCode::Int019, - format!("invalid regex pattern {pattern:?}: {e}") - ) + err_coded!(ErrorCode::Prs091, format!("{pattern:?}"), e) })?; let rhs_lit = Expr::Lit(Value::String(pattern.clone())); return Ok(Expr::BinOp( @@ -1373,20 +1352,14 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result { if !allow_not { - bail_coded!( - ErrorCode::Int019, - "(not-join ...) cannot appear inside another (not ...) or (not-join ...)" - ); + bail_coded!(ErrorCode::Prs093); } // Syntax: (not-join [?v1 ?v2 ...] clause1 clause2 ...) if list.len() < 3 { @@ -1395,20 +1368,14 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result v, _ => { - bail_coded!( - ErrorCode::Int019, - "(not-join) first argument must be a vector of join variables" - ); + bail_coded!(ErrorCode::Prs094); } }; let join_vars: Vec = join_var_vec .iter() .map(|v| match v { EdnValue::Symbol(s) if s.starts_with('?') => Ok(s.clone()), - _ => Err(err_coded!( - ErrorCode::Int019, - format!("(not-join) join variables must be logic variables, got {v:?}") - )), + _ => Err(err_coded!(ErrorCode::Prs095, format!("{v:?}"))), }) .collect::>()?; let mut inner = Vec::new(); @@ -1434,12 +1401,7 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result bail_coded!( - ErrorCode::Int019, - format!("Rule invocation must start with predicate name (symbol), got {head:?}") - ), + _ => bail_coded!(ErrorCode::Prs097, format!("{head:?}")), } } @@ -1518,13 +1477,7 @@ fn parse_list_as_where_clause(list: &[EdnValue], allow_not: bool) -> Result Result { if vec.len() != 3 { - bail_coded!( - ErrorCode::Int019, - format!( - "Pattern must have exactly 3 elements (E A V), got {}", - vec.len() - ) - ); + bail_coded!(ErrorCode::Prs098, vec.len()); } // SAFETY: len == 3 check above guarantees indices 0, 1, 2 exist @@ -1599,10 +1552,7 @@ fn parse_or_branch_item(item: &EdnValue) -> Result { // allow_not=true: or branches can contain not/not-join/or/or-join parse_list_as_where_clause(inner_list, true) } - _ => bail_coded!( - ErrorCode::Int019, - format!("expected clause inside or branch, got {item:?}") - ), + _ => bail_coded!(ErrorCode::Prs099, format!("{item:?}")), } } @@ -2083,7 +2033,7 @@ fn parse_rule(elements: &[EdnValue]) -> Result { // elements[0] = Vector with head (list) + body (patterns/rule calls) if elements.is_empty() { - bail_coded!(ErrorCode::Int019, "Rule must have a body"); + bail_coded!(ErrorCode::Prs100); } if elements.len() > 1 { @@ -2095,24 +2045,21 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] let body_vec = elements[0] .as_vector() - .ok_or_else(|| err_coded!(ErrorCode::Int019, "Rule body must be a vector"))?; + .ok_or_else(|| err_coded!(ErrorCode::Prs101))?; if body_vec.is_empty() { - bail_coded!(ErrorCode::Int019, "Rule body cannot be empty"); + bail_coded!(ErrorCode::Prs102); } // First element is the head (must be a list) // SAFETY: is_empty() check above guarantees index 0 exists #[allow(clippy::indexing_slicing)] - let head_list = body_vec[0].as_list().ok_or_else(|| { - err_coded!( - ErrorCode::Int019, - "Rule head must be a list: (predicate ?args)" - ) - })?; + let head_list = body_vec[0] + .as_list() + .ok_or_else(|| err_coded!(ErrorCode::Prs103))?; if head_list.is_empty() { - bail_coded!(ErrorCode::Int019, "Rule head cannot be empty"); + bail_coded!(ErrorCode::Prs104); } // Verify head starts with a symbol (predicate name) @@ -2120,10 +2067,7 @@ fn parse_rule(elements: &[EdnValue]) -> Result { #[allow(clippy::indexing_slicing)] match &head_list[0] { EdnValue::Symbol(_) => {} - _ => bail_coded!( - ErrorCode::Int019, - "Rule head must start with a symbol (predicate name)" - ), + _ => bail_coded!(ErrorCode::Prs105), } // Rest of body_vec are patterns, rule invocations, or (not ...) clauses @@ -2144,20 +2088,12 @@ fn parse_rule(elements: &[EdnValue]) -> Result { let clause = parse_list_as_where_clause(list, true)?; body_clauses.push(clause); } else { - bail_coded!( - ErrorCode::Int019, - format!( - "Rule body clause must be a vector (pattern) or list (rule invocation / not), got {item:?}" - ) - ); + bail_coded!(ErrorCode::Prs106, format!("{item:?}")); } } if body_clauses.is_empty() { - bail_coded!( - ErrorCode::Int019, - "Rule must have at least one pattern or rule invocation in body" - ); + bail_coded!(ErrorCode::Prs107); } resolve_pseudo_sources(&mut body_clauses)?; diff --git a/tests/error_codes_prs_test.rs b/tests/error_codes_prs_test.rs index 184774f02..1cc145e70 100644 --- a/tests/error_codes_prs_test.rs +++ b/tests/error_codes_prs_test.rs @@ -476,3 +476,247 @@ fn prepare_rejects_transact_command_not_prs() { // Transact command, it's just the wrong command kind for prepare(). assert_ne!(err.category(), ErrorCategory::Parser); } + +// ── PRS-083..PRS-107: parse errors that were INT-019 (#643) ───────────────── + +/// Execute `input`, assert the Parser-category `expected_code`, and that the +/// message carries `needle` (the error's argument, or its fixed text). +fn assert_code_and_message(input: &str, expected_code: &str, needle: &str) { + assert_execute_code(input, expected_code); + let err = db().execute(input).expect_err("input must be rejected"); + let text = err.to_string(); + assert!( + text.contains(needle), + "message for {} lacks {}: {}", + expected_code, + needle, + text + ); + assert!( + !text.contains("datalog parser:"), + "{} message keeps the INT-019 prefix", + expected_code + ); +} + +#[test] +fn prs_083_bind_slot_without_name() { + assert_code_and_message( + "(query [:find ?e :where [?e :name $]])", + "PRS-083", + "Bind slot '$'", + ); +} + +#[test] +fn prs_084_over_without_order_by() { + assert_code_and_message( + "(query [:find ?e (rank :over (:partition-by ?d)) :where [?e :dept ?d]])", + "PRS-084", + "':order-by' is required", + ); +} + +#[test] +fn prs_085_query_argument_not_a_vector() { + assert_code_and_message( + "(query (:find ?e :where [?e :a ?v]))", + "PRS-085", + "Query argument must be a vector", + ); +} + +#[test] +fn prs_086_with_takes_only_variables() { + assert_code_and_message( + "(query [:find (count ?e) :with 7 :where [?e :a ?v]])", + "PRS-086", + "7", + ); +} + +#[test] +fn prs_087_find_element_not_variable_or_aggregate() { + assert_code_and_message("(query [:find 7 :where [?e :a ?v]])", "PRS-087", "7"); +} + +#[test] +fn prs_088_unknown_valid_time_key() { + assert_code_and_message( + r#"(transact {:valid-at "2024-01-01"} [[:alice :name "Alice"]])"#, + "PRS-088", + ":valid-at", + ); +} + +#[test] +fn prs_089_retract_fact_not_a_vector() { + assert_code_and_message( + "(retract [:alice])", + "PRS-089", + "Each fact must be a vector", + ); +} + +#[test] +fn prs_090_retract_fact_wrong_arity() { + assert_code_and_message("(retract [[:alice :name]])", "PRS-090", "got 2"); + assert_code_and_message( + r#"(retract [[:alice :name "Alice" 1]])"#, + "PRS-090", + "got 4", + ); +} + +#[test] +fn prs_091_invalid_regex() { + assert_code_and_message( + r#"(query [:find ?e :where [?e :name ?n] [(matches? ?n "(")]])"#, + "PRS-091", + "\"(\"", + ); +} + +#[test] +fn prs_092_not_body_item_not_a_clause() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (not 7)])", + "PRS-092", + "7", + ); +} + +#[test] +fn prs_093_not_join_nested_in_not() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (not (not-join [?e] [?e :b 1]))])", + "PRS-093", + "cannot appear inside another", + ); +} + +#[test] +fn prs_094_not_join_first_argument_not_a_vector() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (not-join ?e [?e :b 1])])", + "PRS-094", + "first argument must be a vector", + ); +} + +#[test] +fn prs_095_not_join_variable_not_logic_variable() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (not-join [7] [?e :b 1])])", + "PRS-095", + "7", + ); +} + +#[test] +fn prs_096_not_join_body_item_not_a_clause() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (not-join [?e] 7)])", + "PRS-096", + "7", + ); +} + +#[test] +fn prs_097_rule_invocation_head_not_a_symbol() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (7 ?e)])", + "PRS-097", + "7", + ); +} + +#[test] +fn prs_098_pattern_wrong_arity() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] [?e :b]])", + "PRS-098", + "got 2", + ); +} + +#[test] +fn prs_099_or_branch_item_not_a_clause() { + assert_code_and_message( + "(query [:find ?e :where [?e :a ?v] (or 7)])", + "PRS-099", + "7", + ); +} + +#[test] +fn prs_100_rule_without_body() { + assert_code_and_message("(rule)", "PRS-100", "Rule must have a body"); +} + +#[test] +fn prs_101_rule_body_not_a_vector() { + assert_code_and_message( + "(rule (reachable ?a ?b))", + "PRS-101", + "Rule body must be a vector", + ); +} + +#[test] +fn prs_102_rule_body_empty() { + assert_code_and_message("(rule [])", "PRS-102", "Rule body cannot be empty"); +} + +#[test] +fn prs_103_rule_head_not_a_list() { + assert_code_and_message( + "(rule [reachable [?a :edge ?b]])", + "PRS-103", + "Rule head must be a list", + ); +} + +#[test] +fn prs_104_rule_head_empty() { + assert_code_and_message( + "(rule [() [?a :edge ?b]])", + "PRS-104", + "Rule head cannot be empty", + ); +} + +#[test] +fn prs_105_rule_head_not_a_symbol() { + assert_code_and_message( + "(rule [(7 ?a) [?a :edge ?b]])", + "PRS-105", + "Rule head must start with a symbol", + ); +} + +#[test] +fn prs_106_rule_body_clause_not_vector_or_list() { + assert_code_and_message("(rule [(reachable ?a) 7])", "PRS-106", "7"); +} + +#[test] +fn prs_107_rule_body_has_no_clause() { + assert_code_and_message( + "(rule [(reachable ?a)])", + "PRS-107", + "at least one pattern or rule invocation", + ); +} + +#[test] +fn prs_083_to_107_reach_through_prepare() { + let cases: &[(&str, &str)] = &[ + ("(query [:find ?e :where [?e :name $]])", "PRS-083"), + ("(query [:find 7 :where [?e :a ?v]])", "PRS-087"), + ("(query [:find ?e :where [?e :a ?v] [?e :b]])", "PRS-098"), + ]; + for (input, code) in cases { + assert_prepare_code(input, code); + } +}