From ab0d7fe1adab5d52b3d437f45025d44254569a5c Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 22:36:59 +0530 Subject: [PATCH 1/2] fix(rules): QRY-013 head entity, nil metadata for derived facts, UDFs in rule or branches (#548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR 1 of 3 for #548 (streaming engine 6/9), spec §4, so both engines give one answer for rule queries: - A rule head whose entity is not a ref or keyword fails with the new QRY-013 on every path (was INT-022 on positive rules; the not/or path dropped the row). The mixed pass propagates INT-022 for an unbound head variable too. - Derived facts are loaded with tx-count 0 (no stored fact has it), and a per-fact pseudo-attribute reading one binds nil. FactStorage::transact is now test-only. - or/or-join branches in rule bodies get the database's function registry. Adds the implementation plan docs/superpowers/plans/2026-10-20-548-recursive.md. Tests: 1687 total (1677 passing). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019kY61Y11gcRD91Y6b7jbGT --- CHANGELOG.md | 3 + CLAUDE.md | 2 +- README.md | 2 +- docs/ERROR_REFERENCE.md | 18 +++ docs/TEST_COVERAGE.md | 2 +- .../plans/2026-10-20-548-recursive.md | 111 +++++++++++++ src/error.rs | 10 ++ src/graph/storage.rs | 4 + src/query/datalog/aggregate.rs | 2 +- src/query/datalog/evaluator.rs | 99 ++++++++---- src/query/datalog/matcher.rs | 6 +- tests/recursive_rules_test.rs | 146 ++++++++++++++++++ 12 files changed, 367 insertions(+), 38 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-20-548-recursive.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 16d6f01b13..ee4b95fc70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 A lone `-` stays the subtraction operator; the grammar now lists it with the other operators. The verifier's #651 entries are removed. - **One rule limit, `max_derived_facts`, on the total facts a rule query derives** (#553). `OpenOptions::max_derived_facts` and `:max-derived-facts` now limit every fact the rules of one query derive, across iterations and strata (the database's own facts do not count); they used to limit the new facts of one iteration. `OpenOptions::max_results` and `:max-results`, which already limited the total (#528), are deprecated aliases of it (`#[deprecated]` on the Rust field and builder method); the lower of the two applies, and a per-query value still replaces the database's. `OpenOptions::max_results` now defaults to no limit of its own, so it can lower the limit but not raise it: a caller who raised `max_results` above 1,000,000 must raise `max_derived_facts` instead. Neither ever limited the rows a query returns, whatever the name said; `:limit` (#306) will. A caller who lowered `max_derived_facts` to cap each iteration now caps the total, so a long recursion whose iterations each stayed under the limit can now fail with `INT-020`. The `INT-020` text now reads `evaluator: iteration or derived-fact limit exceeded: Max derived facts (N) exceeded. …`. The 1,000-iteration limit and the 1,000,000 default are unchanged. +- **A rule head whose entity is not an entity fails with `QRY-013`** (#548). A rule head's first argument is the entity of the fact it derives and must be a ref or a keyword; a string, number, boolean or `nil` there now fails the query with the new code `QRY-013` (`rule head entity is not an entity: rule 'named' gives a String where a ref or a keyword is needed`). A positive rule used to fail with `INT-022`, and a rule with `not`, `not-join`, `or` or `or-join` silently dropped the row. A head variable the body does not bind now fails with `INT-022` on the `not`/`or` path too, which also dropped the row. +- **A fact a rule derives has no metadata** (#548). `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read from a derived fact (`(reach ?x ?y) [?x :reach ?y] [?x :db/tx-count ?c]`) now bind `nil`, and a constant (`[?x :db/tx-count 1]`) never matches one; a stored fact with the same attribute keeps its own. They used to bind the rule evaluator's working values: the time the query ran, forever, and a counter of its own. `:db/valid-at` still binds the query's valid time. ### Added @@ -53,6 +55,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **An `or` branch in a rule body knows the registered predicates** (#548). A rule with `or`/`or-join` evaluated its branches with the built-in functions only, so a predicate registered with `register_predicate` in a branch (`(or [(big? ?v)] [?x :special true])`) was unknown there. Branches now get the database's functions, as the rest of the rule body does. - **A pseudo-attribute in a rule body reads the stored fact** (#661). In a rule without `not`, `not-join`, `or` or `or-join`, `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read the rule evaluator's working copy of the fact: valid-from was the time the query ran, valid-to forever, and the tx-count and tx-id those of the copy. With `[:a :edge :b]` valid from 2020-01-01 to 2021-01-01, `(rule [(vf ?x ?t) [?x :edge ?y] [?x :db/valid-from ?t]])` returned the query's time for `:a`; it now returns 2020-01-01, as the same pattern in a query body does. Stored data was never affected. Present since v0.15.0; fixed on v2.x too. - **Rule queries with a literal argument return every row** (#608). Magic-sets rewriting restricts a rule to the facts its callers demand, but it took each rule's bound arguments from the first call it saw and assumed every other call matched. A call that did not — the same rule called with free arguments elsewhere in the query, a call inside `or` or `not`, a call from a rule the query calls with free arguments, or a rule-body call whose argument nothing bound yet — either failed with `INT-022` (`(chain ?x :c)` with `(chain ?x ?y) :- (link ?x ?m) (chain ?m ?y)`) or silently returned too few rows (`(link ?x :c) (link ?p ?q)` returned only the `:c` edges for `?p ?q`). A query with both arguments literal next to another rule call also lost its rows. The demand on each rule is now the one every call site supplies, and a rule some call site reads in full is evaluated in full. Present since v1.2.0. - **A `:db/valid-at` pattern in a `not-join` body binds the query's valid time on every path** (#615). When the body also held an expression, sat in an `or` branch, or ran in a query that invokes a rule, the body bound `nil`, so `(not-join [?e] [?e :db/valid-at ?t] [(> ?t 0)])` never matched and excluded nothing; without the expression the same body excluded every entity. It now binds the query's `:valid-at` value (or the current time) as the other paths do. Present since v0.13.1; v2.x is affected too. diff --git a/CLAUDE.md b/CLAUDE.md index 62fe6fd85b..707608515d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -206,7 +206,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1681 tests** (1671 passing, 10 ignored; unit + integration + doc). +**1687 tests** (1677 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 555cf73ba0..0bd58d83f9 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 1681 tests +cargo test # run 1687 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index c88ee07005..f9bc8bc610 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -146,6 +146,7 @@ with no `CodedError` anywhere in its chain. | QRY-009 | Rules lock poisoned | Query Execution | | QRY-010 | Unknown aggregate function | Query Execution | | QRY-011 | Unknown window function | Query Execution | +| QRY-013 | Rule head entity is not an entity | Query Execution | | STG-001 | Invalid header: too short | Storage | | STG-002 | Invalid magic number: not a .graph file | Storage | | STG-003 | Invalid v4/v5/v6 header too short (deprecated) | Storage | @@ -2305,6 +2306,23 @@ predicate evaluation, or fact transacting. ``` *`frob` is not a window built-in; register it first* +### QRY-013 Rule head entity is not an entity + +**Error text**: `rule head entity is not an entity: rule '{}' gives a {} where a ref or a keyword is needed` + +**Cause**: A rule produced a head whose first argument, the entity of the fact it derives, is not an entity: a string, a number, a boolean or `nil`. Only a ref, or a keyword (which names the entity `uuidv5(keyword)`), is an entity. The head's second argument, the value, may be any value. The query that invoked the rule fails, whether the rule has `not`/`not-join`/`or`/`or-join` clauses or not. Before v3.0.0 a positive rule failed with INT-022 and a rule with `not`/`or` clauses silently dropped the row. (QRY-012 is reserved.) + +**Resolution**: +- Put an entity variable first in the head: `(owner ?item ?person)`, not `(owner ?name ?item)` where `?name` binds a string. +- To derive a fact about a value, keep the entity first and the value second. + +**Example**: +```datalog +(rule [(named ?n ?e) [?e :name ?n]]) +(query [:find ?e :where (named ?n ?e)]) +``` +*`?n` binds a string, so rule `named` gives a String as its entity* + --- ## STG — Storage Errors diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 4be6745dc9..188a5ad0a2 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,671 passing tests and 10 ignored tests (1,681 total) +**Result**: 1,677 passing tests and 10 ignored tests (1,687 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). diff --git a/docs/superpowers/plans/2026-10-20-548-recursive.md b/docs/superpowers/plans/2026-10-20-548-recursive.md new file mode 100644 index 0000000000..a7e7dda869 --- /dev/null +++ b/docs/superpowers/plans/2026-10-20-548-recursive.md @@ -0,0 +1,111 @@ +# Recursive rules on the streaming engine (#548) — Plan + +Spec: `docs/superpowers/specs/2026-10-20-recursive-engine-design.md`. PRs target `v3`. None +uses a closing keyword for #473; #548 closes by hand after PR 3. Prerequisites merged: +#553 (#663, one total `max_derived_facts`) and #661 (#665, pseudo-attributes in rule bodies +read the stored fact). + +| PR | Steps | Branch | +|---|---|---| +| 1 | 1–7: executor rule fixes (spec §4) | `fix/548-executor-rules` | +| 2 | 8–15: `Recursive` and rule queries on the engine (spec §5) | `feat/548-recursive` | +| 3 | 16–19: acceptance and measurement (spec §7) | `feat/548-acceptance` | + +Each PR leaves `v3` with no unused code, updates the test counts and `CHANGELOG.md` for what +it ships, and has a docs-site PR (`../minigraf-docs`) when it changes documented behaviour +(PR 1 does; PR 2 changes no answer; PR 3 adds measurements only). + +## Design decisions not fixed by the spec + +1. **How a derived fact is marked.** `Fact::new(…, 0)` already gives tx-count 0, tx-id 0, + valid-from 0 and valid-to forever. `RecursiveEvaluator` loads its delta with + `FactStorage::load_facts` and `StratifiedEvaluator`'s mixed pass with `load_fact`, + instead of `FactStorage::transact`, so the mark survives; the positive pass already + copied facts with `load_fact`. `FactStorage::transact` has no other non-test caller and + becomes `#[cfg(test)]` (writes go through `transact_batch`). +2. **Where `nil` is decided.** `PatternMatcher::metadata` returns `Value::Null` for a + tx-count-0 fact, for every per-fact pseudo-attribute. No stored fact has tx-count 0: + the counter starts at 1, the v1 migration on v2.x numbered from 1, and `LogWriter` + rejects 0 (`API-015`). Magic seeds also have tx-count 0 and are query-local; they bind + `nil` too, which matches spec §3.3 (they are not stored facts of the snapshot). + `:db/valid-at` is not per fact and is unchanged. +3. **`QRY-013`'s text** names the predicate and the kind of the value: + `rule head entity is not an entity: rule '{}' gives a {} where a ref or a keyword is + needed`, the kind from `aggregate::type_name` (made `pub(crate)`), `symbol` for a bare + symbol in the head. `QRY-012` stays reserved for #549 (a comment in `ErrorCode`). +4. **The mixed pass propagates `instantiate_head`'s error** (`?`), so an unbound head + variable is `INT-022` there too (spec §3.4), with the same text as the positive path. +5. **The function registry in rule-body `or` branches** is a read guard on + `StratifiedEvaluator::functions`, taken where `FunctionRegistry::with_builtins()` was. + +## PR 1 — executor rule fixes + +1. `ErrorCode::Qry013` in `src/error.rs` (enum, `REGISTRY`, the exhaustive match, `ALL`), + row and section in `docs/ERROR_REFERENCE.md`. +2. `RecursiveEvaluator::instantiate_head`: entity conversion failure is `QRY-013`. +3. `StratifiedEvaluator` mixed pass: `instantiate_head_public(…)?` replaces + `if let Ok(fact)`. +4. Derived facts tx-count 0 (decision 1); `FactStorage::transact` test-only. +5. `PatternMatcher::metadata`: `nil` for tx-count 0 (decision 2). +6. Mixed-pass `or` branches get the database's registry (decision 5). +7. Tests (`tests/recursive_rules_test.rs`): `QRY-013` on the positive, magic-set, `not`, + `not-join`, `or` and nested-`not-join` paths; keyword and ref heads still derive; + `INT-022` for an unbound head variable on both paths; `nil` metadata for facts derived + by positive and `not` rules, a stored fact of the same attribute keeping its own, a + constant matching only the stored fact; a registered predicate in a rule-body `or` + branch. Unit test `test_head_entity_must_be_an_entity` (string, integer, bare symbol; + a keyword head gives tx-count 0). `CHANGELOG.md` (two breaking entries, one fixed), + counts. Docs-site PR (`v3/548-executor-rules`): the rule-head error and the metadata + rule, `@since v3.0.0`. UniFFI binding PRs follow the new `ErrorCode` once merged. + +## PR 2 — `Recursive` and rule queries on the engine + +8. **Relation store** (`src/query/engine/relation.rs`): per evaluated predicate an + append-only `Vec` of `[Cell; 2]` rows, an identity `HashSet` (spec §3.2: floats by + bits with `-0.0` ≠ `0.0` and one NaN; a keyword `Iid` distinct from the `Eid` it names; + long strings by content), an entity-key index to row positions, and round boundaries + (`start_k`, `end_k`). Seeding: each stratum predicate's identity set from one scan of + its stored facts; magic seeds appended as rows before round 1. Unit tests for identity + and ranges. +9. **Derived scan source** (`plan.rs` `ScanSpec`, `scan.rs`): `derived: Option` + with the predicates read (one for `:p`, every evaluated one for a variable or `_` + attribute, the attribute cell the ident of `:p`) and a `Range` (`Full`, `Old`, + `Delta`). `Full`/`Old` read committed, pending, then derived rows; `Delta` derived + rows only. Derived rows fill metadata columns with `nil`; entity probes use the + relation's index. Constants and bound values filter as on the other sources. +10. **Rule bodies as plans**: a `Builder` entry that plans a rule body (invocations as + `rule_invocation_to_pattern` patterns) and ends in a head projection of two cells + (entity checked as spec §5.3: `Eid`, or `Iid` via `IdSpace::keyword_eid`, else + `QRY-013`; one-argument heads project `true`). `None` (executor) when a body cannot + be planned. +11. **`Recursive`** (`src/query/engine/recursive.rs`): strata from `stratify()` over the + evaluated predicates (`all_preds` as `StratifiedEvaluator::evaluate`); round 1 every + rule `Full`; round `k > 1` one variant per same-stratum top-level invocation + (`Delta` / `Old` before / `Full` after); naive rules (spec §5.3's list, found on the + parsed body) every round, all `Full`; heads checked against the identity set, + appended at the round's end, each counted against `max_derived_facts`; `INT-020` + after `max_iterations` rounds (the empty round counts). +12. **Query body**: planned as any engine query after `Recursive`, every scan with the + derived source `Full`. +13. **Routing** (`DatalogExecutor::open_query`): a rule query goes to the engine when its + body and every evaluated rule body plan, it has no `:as-of` timestamp and no slot left, + and it is not in a write transaction (`facts_override`); else the executor. The oracle + compares both (bags, or both errors). +14. **Tests**: `tests/recursive_engine_test.rs` (spec §7's list), every query also through + the oracle; existing rule suites (`recursive_rules_test`, `negation_test`, + `disjunction_test`, `magic_sets_test`, model and property tests) now reach the engine. +15. **Binary size** against the 1,230 KiB gate (v3 ~1,211 KiB); if over, the PR says by + how much and why before the gate moves. `CHANGELOG.md` Internal entry, counts, envelope + smoke at 100K. + +## PR 3 — acceptance and measurement + +16. Acceptance test: a layered graph (63 layers of 50 nodes, complete bipartite edges + between neighbours, ≈ 5M `reach` facts in 63 rounds) completes with peak RSS + proportional to the derived relation; `max_derived_facts` stops a runaway rule with + `INT-020`. Ignored by default (run in the soak/bench job), as other large tests. +17. Envelope `recursive` shape (transitive closure at 100K, 1M, 10M base facts) in + `examples/perf_envelope.rs`. +18. Bench machine A/B (engine against `origin/v3`, `numactl` one node, idle machine): + wall time and peak RSS; #379 point queries must not regress. +19. Results in `CHANGELOG.md`; close #548 by hand. diff --git a/src/error.rs b/src/error.rs index 339f58aed9..ac2d9f3e56 100644 --- a/src/error.rs +++ b/src/error.rs @@ -172,6 +172,8 @@ pub(crate) enum ErrorCode { Qry009, Qry010, Qry011, + // QRY-012 is reserved for the query memory limit (#549). + Qry013, Int000, Stg001, Stg002, @@ -1069,6 +1071,12 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ "unknown window function '{}' — register it with register_aggregate() before querying", ErrorCategory::Query, ), + ( + ErrorCode::Qry013, + "QRY-013", + "rule head entity is not an entity: rule '{}' gives a {} where a ref or a keyword is needed", + ErrorCategory::Query, + ), ( ErrorCode::Int000, "INT-000", @@ -2267,6 +2275,7 @@ mod tests { | ErrorCode::Qry009 | ErrorCode::Qry010 | ErrorCode::Qry011 + | ErrorCode::Qry013 | ErrorCode::Stg001 | ErrorCode::Stg002 | ErrorCode::Stg003 @@ -2527,6 +2536,7 @@ mod tests { ErrorCode::Qry009, ErrorCode::Qry010, ErrorCode::Qry011, + ErrorCode::Qry013, ErrorCode::Stg001, ErrorCode::Stg002, ErrorCode::Stg003, diff --git a/src/graph/storage.rs b/src/graph/storage.rs index 776e8aba77..192c84afcc 100644 --- a/src/graph/storage.rs +++ b/src/graph/storage.rs @@ -428,6 +428,10 @@ impl FactStorage { /// /// # Returns /// The TxId (timestamp) assigned to these facts + /// + /// Test-only since rules stopped transacting derived facts (#548); + /// writes go through `transact_batch`. + #[cfg(test)] pub(crate) fn transact( &self, fact_tuples: Vec<(EntityId, Attribute, Value)>, diff --git a/src/query/datalog/aggregate.rs b/src/query/datalog/aggregate.rs index 7ada445f5c..ef923760c9 100644 --- a/src/query/datalog/aggregate.rs +++ b/src/query/datalog/aggregate.rs @@ -314,7 +314,7 @@ fn canonical(v: &Value) -> Value { } /// The type name used in error messages. -fn type_name(v: &Value) -> &'static str { +pub(crate) fn type_name(v: &Value) -> &'static str { match v { Value::String(_) => "String", Value::Integer(_) => "Integer", diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index 57401add59..d05b8f26ba 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -187,13 +187,8 @@ impl RecursiveEvaluator { break; } - // Add delta facts to derived storage - for fact in delta { - derived.transact( - vec![(fact.entity, fact.attribute.clone(), fact.value.clone())], - None, - )?; - } + // Add delta facts to derived storage, as derived (tx-count 0) + derived.load_facts(delta)?; } Ok(derived) @@ -368,8 +363,14 @@ impl RecursiveEvaluator { .get(1) .ok_or_else(|| err_coded!(ErrorCode::Int022, "Rule head missing entity argument"))?; let entity_edn = self.substitute_variable(head_1, binding)?; - let entity = edn_to_entity_id(&entity_edn) - .map_err(|e| err_coded!(ErrorCode::Int022, format!("Failed to convert entity: {e}")))?; + // Only a ref or a keyword names an entity; anything else fails the + // query, on every path (#548). + let entity = edn_to_entity_id(&entity_edn).map_err(|_| { + let kind = edn_to_value(&entity_edn) + .map(|v| crate::query::datalog::aggregate::type_name(&v)) + .unwrap_or("symbol"); + err_coded!(ErrorCode::Qry013, predicate, kind) + })?; let value = if head.len() >= 3 { // 2-arg head: (reachable ?from ?to) — value is head[2] @@ -389,7 +390,8 @@ impl RecursiveEvaluator { // Use ":predicate-name" as the attribute for derived facts let attribute = format!(":{}", predicate); - // Create the fact (no tx_id yet, will be added when transacted) + // A derived fact has no metadata: tx-count 0, which no stored fact + // has, makes a per-fact pseudo-attribute read `nil` from it (#548). Ok(Fact::new(entity, attribute, value, 0)) } @@ -889,15 +891,16 @@ impl StratifiedEvaluator { // Apply Or/OrJoin clauses (unchanged, applied after the plan loop). let candidates = { use crate::query::datalog::executor::apply_or_clauses; - use crate::query::datalog::functions::FunctionRegistry; let registry_guard = self .rules .read() .map_err(|_| err_coded!(ErrorCode::Qry009))?; - // Rule bodies in the semi-naive evaluator don't have access to a - // FunctionRegistry (UDF registration happens at the db layer). Use the - // built-in-only registry so or-branches can still use built-in predicates. - let fn_registry = FunctionRegistry::with_builtins(); + // The database's functions: a registered predicate in + // an or branch is known there too (#548). + let fn_registry = self + .functions + .read() + .map_err(|_| err_coded!(ErrorCode::Qry008))?; // An or branch binds `:db/valid-at` from a `ValidAt`, the // inverse of the executor's mapping to `self.valid_at`. let branch_valid_at = match &self.valid_at { @@ -982,25 +985,24 @@ impl StratifiedEvaluator { } // All Not / NotJoin conditions held -> derive head fact - if let Ok(fact) = temp_eval.instantiate_head_public(&rule.head, &binding) { - let key = ( - fact.entity, - fact.attribute.clone(), - encode_value(&fact.value), - ); - if !known.insert(key) { - continue; - } - new_in_pass = true; - derived_total += 1; - if derived_total > self.max_derived_facts { - return Err(derived_facts_exceeded(self.max_derived_facts)); - } - // Use transact (not load_fact) so derived facts get a proper - // tx_id and incremented tx_count, matching spec step (d). - let _ = accumulated - .transact(vec![(fact.entity, fact.attribute, fact.value)], None); + // A head that is not an entity, or names an unbound + // variable, fails the query as on the positive path (#548). + let fact = temp_eval.instantiate_head_public(&rule.head, &binding)?; + let key = ( + fact.entity, + fact.attribute.clone(), + encode_value(&fact.value), + ); + if !known.insert(key) { + continue; + } + new_in_pass = true; + derived_total += 1; + if derived_total > self.max_derived_facts { + return Err(derived_facts_exceeded(self.max_derived_facts)); } + // Loaded as derived (tx-count 0): no metadata (#548). + accumulated.load_fact(fact)?; } } @@ -1269,6 +1271,37 @@ mod tests { ); } + #[test] + fn test_head_entity_must_be_an_entity() { + // A value or a bare symbol as the head entity is QRY-013 (#548). + let evaluator = RecursiveEvaluator::new( + FactStorage::new(), + Arc::new(RwLock::new(RuleRegistry::new())), + Arc::new(RwLock::new(FunctionRegistry::with_builtins())), + 1000, + DEFAULT_MAX_DERIVED_FACTS, + ); + let binding = std::collections::HashMap::new(); + for entity in [ + EdnValue::String("x".to_string()), + EdnValue::Integer(1), + EdnValue::Symbol("foo".to_string()), + ] { + let head = vec![EdnValue::Symbol("p".to_string()), entity]; + let err: crate::error::MinigrafError = evaluator + .instantiate_head(&head, &binding) + .unwrap_err() + .into(); + assert_eq!(err.code(), "QRY-013", "not an entity"); + } + let head = vec![ + EdnValue::Symbol("p".to_string()), + EdnValue::Keyword(":a".to_string()), + ]; + let fact = evaluator.instantiate_head(&head, &binding).unwrap(); + assert_eq!(fact.tx_count, 0, "a derived fact has tx-count 0"); + } + #[test] fn test_evaluate_rule_empty_body_returns_empty_derived() { // Line 225 TRUE: patterns.is_empty() && expr_clauses.is_empty() → return Ok(derived) diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index bbc319ca97..a5d4c7bf62 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -132,8 +132,12 @@ impl PatternMatcher { } /// The metadata `attr` of `fact`. `:db/valid-at` is not per fact; it - /// never names a hidden variable. + /// never names a hidden variable. A fact a rule derived (tx-count 0, + /// which no stored fact has) has no metadata: `nil` (#548). fn metadata(fact: &Fact, attr: &PseudoAttr) -> Value { + if fact.tx_count == 0 { + return Value::Null; + } Value::Integer(match attr { PseudoAttr::ValidFrom | PseudoAttr::ValidAt => fact.valid_from, PseudoAttr::ValidTo => fact.valid_to, diff --git a/tests/recursive_rules_test.rs b/tests/recursive_rules_test.rs index 8c1cbba6b2..e2509b8187 100644 --- a/tests/recursive_rules_test.rs +++ b/tests/recursive_rules_test.rs @@ -681,3 +681,149 @@ fn test_pseudo_attributes_in_rule_bodies_read_the_stored_fact() { } } } + +/// The error code of a command that must fail. +fn err_code(db: &Minigraf, input: &str) -> String { + match db.execute(input) { + Ok(_) => panic!("expected an error for {input}"), + Err(e) => e.code().to_string(), + } +} + +/// #548: a rule head whose entity is not a ref or a keyword fails the query +/// with QRY-013 on every path: a positive rule (was INT-022), the magic-sets +/// rewrite, and rules with `not` or `or` (which dropped the row). +#[test] +fn test_rule_head_entity_not_an_entity_is_qry013() { + let db = Minigraf::in_memory().unwrap(); + exec(&db, r#"(transact [[:a :name "alice"] [:b :alias 7]])"#); + exec(&db, "(rule [(named ?n ?e) [?e :name ?n]])"); + exec( + &db, + "(rule [(visible ?n ?e) [?e :name ?n] (not [?e :hidden true])])", + ); + exec( + &db, + "(rule [(called ?n ?e) (or [?e :name ?n] [?e :alias ?n])])", + ); + exec( + &db, + "(rule [(unnamed ?n ?e) [?e :name ?n] (not-join [?e] [?e :hidden true])])", + ); + for query in [ + "(query [:find ?e :where (named ?n ?e)])", + r#"(query [:find ?e :where (named "alice" ?e)])"#, + "(query [:find ?e :where (visible ?n ?e)])", + "(query [:find ?e :where (called ?n ?e)])", + "(query [:find ?e :where (unnamed ?n ?e)])", + "(query [:find ?e :where [?e :name _] (not-join [?e] (visible ?n ?e))])", + ] { + assert_eq!(err_code(&db, query), "QRY-013", "head entity is a value"); + } +} + +/// #548: a keyword or ref head entity names an entity on every path. +#[test] +fn test_rule_head_keyword_and_ref_entities_derive() { + let db = Minigraf::in_memory().unwrap(); + exec( + &db, + "(transact [[:a :likes :b] [:a :likes :c] [:c :hidden true]])", + ); + exec(&db, "(rule [(liked ?y ?x) [?x :likes ?y]])"); + exec( + &db, + "(rule [(shown ?y ?x) [?x :likes ?y] (not [?y :hidden true])])", + ); + let rows = result_rows(exec(&db, "(query [:find ?y :where (liked ?y ?x)])")); + assert_eq!(rows.len(), 2, "two liked entities"); + let rows = result_rows(exec(&db, "(query [:find ?y :where (shown ?y ?x)])")); + assert_eq!(rows.len(), 1, "one shown entity"); +} + +/// #548: a head variable the body does not bind fails with INT-022 on the +/// `not`/`or` path too, which dropped the row. +#[test] +fn test_rule_head_unbound_variable_is_int022_on_every_path() { + let db = Minigraf::in_memory().unwrap(); + exec(&db, r#"(transact [[:a :name "alice"]])"#); + exec(&db, "(rule [(loose ?x ?y) [?x :name _]])"); + exec( + &db, + "(rule [(looser ?x ?y) [?x :name _] (not [?x :hidden true])])", + ); + for query in [ + "(query [:find ?x :where (loose ?x ?y)])", + "(query [:find ?x :where (looser ?x ?y)])", + ] { + assert_eq!(err_code(&db, query), "INT-022", "unbound head variable"); + } +} + +/// #548: a derived fact has no metadata. A per-fact pseudo-attribute whose +/// source matched one binds nil (the row is kept), and a constant never +/// matches it; a stored fact of the same attribute keeps its own. Facts +/// derived by positive rules and by rules with `not` alike. +#[test] +fn test_derived_facts_have_nil_metadata() { + let db = Minigraf::in_memory().unwrap(); + exec(&db, "(transact [[:a :edge :b] [:b :edge :c]])"); + exec(&db, "(transact [[:z :reach :w]])"); + exec(&db, "(rule [(reach ?x ?y) [?x :edge ?y]])"); + exec(&db, "(rule [(reach ?x ?y) [?x :edge ?z] (reach ?z ?y)])"); + exec(&db, "(rule [(leaf ?x) [?y :edge ?x] (not [?x :edge _])])"); + + for attr in [ + ":db/valid-from", + ":db/valid-to", + ":db/tx-count", + ":db/tx-id", + ] { + let rows = result_rows(exec( + &db, + &format!( + "(query [:find ?x ?y ?m :valid-at :any-valid-time :where (reach ?x ?y) [?x :reach ?y] [?x {attr} ?m]])" + ), + )); + assert_eq!(rows.len(), 4, "three derived facts and a stored one"); + let nils = rows.iter().filter(|r| r[2] == Value::Null).count(); + assert_eq!(nils, 3, "derived facts bind nil"); + + let rows = result_rows(exec( + &db, + &format!( + "(query [:find ?x ?m :valid-at :any-valid-time :where (leaf ?x) [?x :leaf ?v] [?x {attr} ?m]])" + ), + )); + assert_eq!( + rows, + vec![vec![rows[0][0].clone(), Value::Null]], + "one leaf, nil" + ); + } + + let rows = result_rows(exec( + &db, + "(query [:find ?x :valid-at :any-valid-time :where (reach ?x ?y) [?x :reach ?y] [?x :db/tx-count 2]])", + )); + assert_eq!(rows.len(), 1, "a constant matches the stored fact only"); +} + +/// #548: an `or` branch in a rule body knows the database's registered +/// predicates, not the built-ins only. +#[test] +fn test_rule_or_branch_uses_registered_predicates() { + let db = Minigraf::in_memory().unwrap(); + db.register_predicate("big?", |v| matches!(v, Value::Integer(n) if *n > 100)) + .unwrap(); + exec( + &db, + "(transact [[:a :n 500] [:b :n 5] [:c :n 6] [:c :special true]])", + ); + exec( + &db, + "(rule [(notable ?x) [?x :n ?v] (or [(big? ?v)] [?x :special true])])", + ); + let rows = result_rows(exec(&db, "(query [:find ?x :where (notable ?x)])")); + assert_eq!(rows.len(), 2, "a by the predicate, c by the branch pattern"); +} From e373d1e77122b9369a55126f5fc0852aad688da1 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 22:37:38 +0530 Subject: [PATCH 2/2] test(rules): check the leaf row count before reading it (#548) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019kY61Y11gcRD91Y6b7jbGT --- tests/recursive_rules_test.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/tests/recursive_rules_test.rs b/tests/recursive_rules_test.rs index e2509b8187..3890ad5369 100644 --- a/tests/recursive_rules_test.rs +++ b/tests/recursive_rules_test.rs @@ -795,11 +795,8 @@ fn test_derived_facts_have_nil_metadata() { "(query [:find ?x ?m :valid-at :any-valid-time :where (leaf ?x) [?x :leaf ?v] [?x {attr} ?m]])" ), )); - assert_eq!( - rows, - vec![vec![rows[0][0].clone(), Value::Null]], - "one leaf, nil" - ); + assert_eq!(rows.len(), 1, "one leaf"); + assert_eq!(rows[0][1], Value::Null, "a derived leaf binds nil"); } let rows = result_rows(exec(