diff --git a/CHANGELOG.md b/CHANGELOG.md index d95694f32..c0852c270 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - A string with no closing quote fails with the new `PRS-109` (it ran to the end of the input), and a `:` with no name after it, such as `:+`, with the new `PRS-110` (it was the keyword `:`). 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. ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 423d09773..a8b408ae3 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 -**1672 tests** (1662 passing, 10 ignored; unit + integration + doc). +**1680 tests** (1670 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 a1a95dd3f..c10ebbdc6 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 1672 tests +cargo test # run 1680 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/ERROR_REFERENCE.md b/docs/ERROR_REFERENCE.md index f80d2fed6..c88ee0700 100644 --- a/docs/ERROR_REFERENCE.md +++ b/docs/ERROR_REFERENCE.md @@ -240,7 +240,7 @@ with no `CodedError` anywhere in its chain. | INT-017 | Pseudo-attribute not valid in this position | Internal | | INT-018 | Variable not bound by any outer/earlier clause | Internal | | INT-019 | Datalog parser internal error | Internal | -| INT-020 | Evaluator iteration/result limit exceeded | Internal | +| INT-020 | Evaluator iteration/derived-fact limit exceeded | Internal | | INT-021 | Evaluator: unsupported where-clause in evaluate_rule | Internal | | INT-022 | Datalog evaluator internal error | Internal | | INT-023 | Packed page: fact exceeds slot capacity | Internal | @@ -3591,20 +3591,27 @@ matches on `INT-019` for those errors must match the new codes. **Resolution**: - Report the input that raised it as a bug. -### INT-020 Evaluator iteration/result limit exceeded +### INT-020 Evaluator iteration/derived-fact limit exceeded -**Error text**: `evaluator: iteration or result limit exceeded: {}` +**Error text**: `evaluator: iteration or derived-fact limit exceeded: {}` -**Cause**: The recursive rule evaluator (semi-naive evaluation) exceeded its -maximum iteration count, maximum derived facts per iteration, or maximum -number of facts derived in total (`max_results`; the database's own facts do -not count) — guards against infinite recursion/cycles or -runaway-generating rules. +**Cause**: The recursive rule evaluator exceeded its maximum iteration count +(1,000), or its rules derived more facts in total than `max_derived_facts` +allows (`OpenOptions::max_derived_facts` or `:max-derived-facts`, default +1,000,000; the database's own facts do not count) — guards against infinite +recursion/cycles or runaway-generating rules. `max_results` / `:max-results` +are deprecated aliases of that limit; when both are given, the lower applies. +Neither limits the rows a query returns. + +Before v3.0.0, `max_derived_facts` limited the facts derived in one iteration, +`max_results` limited the total, and the text read `iteration or result limit +exceeded`. From v3.0.0 there is one limit, on the total (#553). **Resolution**: - Check the rule for an unintended cycle (e.g. `(ancestor ?x ?y) [?x - :parent ?y]` combined with a cyclic `:parent` graph). Raise the relevant - limit via query options if the workload is legitimately large. + :parent ?y]` combined with a cyclic `:parent` graph). Raise + `max_derived_facts` (or `:max-derived-facts` on the query) if the workload + is legitimately large. ### INT-021 Evaluator: unsupported where-clause in evaluate_rule diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index 2e2d32d22..08c39e3c0 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,652 passing tests and 10 ignored tests (1,662 total) +**Result**: 1,670 passing tests and 10 ignored tests (1,680 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/src/cursor.rs b/src/cursor.rs index 0ebd8a186..e8bf1f316 100644 --- a/src/cursor.rs +++ b/src/cursor.rs @@ -8,7 +8,7 @@ //! Queries the streaming engine runs (#473) produce rows as they are pulled, //! one internal batch at a time: closing or dropping the cursor stops the //! work. Other queries compute the whole answer when the cursor opens, so -//! `max_results` and `max_derived_facts` apply exactly as they do to +//! `max_derived_facts` applies exactly as it does to //! [`crate::Minigraf::execute`]. Either way a cursor is owned (it borrows //! nothing from the database handle), and [`Cursor::next_batch`] can fail. diff --git a/src/db.rs b/src/db.rs index 88eb10f99..82d327315 100644 --- a/src/db.rs +++ b/src/db.rs @@ -21,7 +21,6 @@ use crate::graph::FactStorage; use crate::graph::storage::Snapshot; use crate::graph::types::Value; use crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS; -use crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS; use crate::query::datalog::executor::DatalogExecutor; use crate::query::datalog::executor::QueryResult; use crate::query::datalog::functions::{ @@ -137,11 +136,18 @@ pub struct OpenOptions { /// [`read_only`](Self::read_only) handle. A tool that reads the whole file /// can keep it resident with `file_size / 4096` pages. pub page_cache_size: usize, - /// Maximum facts that can be derived per recursive rule iteration. - /// Defaults to 1_000_000. Use to prevent runaway recursive rules. + /// Maximum facts the rules of one query may derive in total; the + /// database's own facts do not count. Defaults to 1_000_000. Stops a + /// runaway recursive rule with `INT-020`; it never limits returned rows. pub max_derived_facts: usize, - /// Maximum facts a rule query may derive. Defaults to 1_000_000. - /// The database's own facts do not count against it. + /// Deprecated alias of [`max_derived_facts`](Self::max_derived_facts): + /// the lower of the two applies (#553). Defaults to `usize::MAX`, no + /// limit of its own, so it can lower the limit but not raise it; raise + /// `max_derived_facts` instead. It never limited returned rows. + #[deprecated( + since = "3.0.0", + note = "use `max_derived_facts`; the lower of the two applies" + )] pub max_results: usize, /// Open even when the filesystem cannot lock files at all. /// @@ -181,13 +187,14 @@ pub struct OpenOptions { pub read_only: bool, } +#[allow(deprecated)] // `max_results`, kept as an alias until it is removed impl Default for OpenOptions { fn default() -> Self { OpenOptions { wal_checkpoint_threshold: 1000, page_cache_size: 256, max_derived_facts: DEFAULT_MAX_DERIVED_FACTS, - max_results: DEFAULT_MAX_RESULTS, + max_results: usize::MAX, allow_unlocked: false, synchronous: SyncMode::Full, read_only: false, @@ -220,25 +227,38 @@ impl OpenOptions { self } - /// Set the maximum facts that can be derived per recursive rule iteration. + /// Set the maximum facts the rules of one query may derive in total. /// - /// Defaults to 1_000_000. Use lower values to prevent runaway recursive rules - /// from consuming excessive memory. Can be overridden per-query using - /// `:max-derived-facts N` in the query vector. + /// Defaults to 1_000_000. The database's own facts do not count against it, + /// and queries without rules are not limited by it. A query that derives + /// more fails with `INT-020`, which stops a runaway recursive rule. Can be + /// overridden per query with `:max-derived-facts N` in the query vector. pub fn max_derived_facts(mut self, n: usize) -> Self { self.max_derived_facts = n; self } - /// Set the maximum number of facts a rule query may derive. - /// - /// Defaults to 1_000_000. The database's own facts do not count against it, - /// and queries without rules are not limited by it. + /// Deprecated alias of [`max_derived_facts`](Self::max_derived_facts): + /// the lower of the two applies (#553), so it can lower the limit but not + /// raise it above `max_derived_facts`. It never limited the rows a query + /// returns. + #[deprecated( + since = "3.0.0", + note = "use `max_derived_facts`; the lower of the two applies" + )] + #[allow(deprecated)] pub fn max_results(mut self, n: usize) -> Self { self.max_results = n; self } + /// The limit rule queries run with: the lower of `max_derived_facts` and + /// its deprecated alias `max_results` (#553). + #[allow(deprecated)] + fn derived_fact_limit(&self) -> usize { + self.max_derived_facts.min(self.max_results) + } + /// Open even when the filesystem cannot lock files. See /// [`OpenOptions::allow_unlocked`] for when this is appropriate. #[must_use] @@ -786,10 +806,7 @@ impl Minigraf { self.inner.rules.clone(), self.inner.functions.clone(), ); - executor.set_limits( - self.inner.options.max_derived_facts, - self.inner.options.max_results, - ); + executor.set_limits(self.inner.options.derived_fact_limit()); executor.set_snapshot(snapshot); executor } @@ -800,8 +817,8 @@ impl Minigraf { /// while it is open do not change it. The cursor owns what it needs, so it /// can outlive this handle and move to another thread. Queries the /// streaming engine runs produce rows as they are pulled; others compute - /// the whole answer here, and `max_results` and `max_derived_facts` apply - /// exactly as they do to [`Minigraf::execute`]. + /// the whole answer here, and `max_derived_facts` applies exactly as it + /// does to [`Minigraf::execute`]. /// /// # Errors /// @@ -1491,10 +1508,7 @@ impl<'a> WriteTransaction<'a> { self.inner.rules.clone(), self.inner.functions.clone(), ); - executor.set_limits( - self.inner.options.max_derived_facts, - self.inner.options.max_results, - ); + executor.set_limits(self.inner.options.derived_fact_limit()); return executor.execute(cmd); } @@ -1505,10 +1519,7 @@ impl<'a> WriteTransaction<'a> { self.inner.rules.clone(), self.inner.functions.clone(), ); - executor.set_limits( - self.inner.options.max_derived_facts, - self.inner.options.max_results, - ); + executor.set_limits(self.inner.options.derived_fact_limit()); executor.execute(cmd) } @@ -1521,10 +1532,7 @@ impl<'a> WriteTransaction<'a> { self.inner.rules.clone(), self.inner.functions.clone(), ); - executor.set_limits( - self.inner.options.max_derived_facts, - self.inner.options.max_results, - ); + executor.set_limits(self.inner.options.derived_fact_limit()); executor.execute(DatalogCommand::Rule(rule)) } @@ -2277,6 +2285,7 @@ mod tests { // ── file-backed: open_with_options custom threshold ─────────────────────── #[test] + #[allow(deprecated)] // every field, `max_results` too fn test_open_with_options_custom_threshold() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("test.graph"); @@ -2755,9 +2764,7 @@ mod tests { fn test_max_derived_facts_limit_enforced() { // Recursive rule will derive many facts // Low limit should trigger error - let low_opts = OpenOptions::default() - .max_derived_facts(5) - .max_results(1_000_000); + let low_opts = OpenOptions::default().max_derived_facts(5); let db_low = Minigraf::in_memory_with_options(low_opts).unwrap(); // Add base edges in a chain @@ -2784,9 +2791,7 @@ mod tests { ); // Same query with higher limit should succeed - let high_opts = OpenOptions::default() - .max_derived_facts(100_000) - .max_results(1_000_000); + let high_opts = OpenOptions::default().max_derived_facts(100_000); let db_high = Minigraf::in_memory_with_options(high_opts).unwrap(); db_high.execute("(transact [[:a :edge :b] [:b :edge :c] [:c :edge :d] [:d :edge :e] [:e :edge :f]])").unwrap(); @@ -2847,6 +2852,112 @@ mod tests { ); } + /// A chain a → b → c → d → e → f and transitive `reachable`: 15 pairs + /// derived, never more than 5 new in one iteration. + fn chain_db(opts: OpenOptions) -> Minigraf { + let db = Minigraf::in_memory_with_options(opts).unwrap(); + db.execute( + "(transact [[:a :edge :b] [:b :edge :c] [:c :edge :d] [:d :edge :e] [:e :edge :f]])", + ) + .unwrap(); + db.execute("(rule [(reachable ?x ?y) [?x :edge ?y]])") + .unwrap(); + db.execute("(rule [(reachable ?x ?y) [?x :edge ?z] (reachable ?z ?y)])") + .unwrap(); + db + } + + const CHAIN_QUERY: &str = "(query [:find ?x ?y :where (reachable ?x ?y)])"; + + fn chain_code(db: &Minigraf, query: &str) -> Option { + db.execute(query).err().map(|e| e.code().to_string()) + } + + #[test] + fn max_derived_facts_limits_the_total_not_one_iteration() { + // #553: the limit counts every fact derived, across iterations. + let db = chain_db(OpenOptions::default().max_derived_facts(15)); + assert_eq!(chain_code(&db, CHAIN_QUERY), None, "15 derived facts fit"); + let db = chain_db(OpenOptions::default().max_derived_facts(14)); + let err = db.execute(CHAIN_QUERY).unwrap_err(); + assert_eq!(err.code(), "INT-020"); + assert!( + err.to_string().contains("Max derived facts (14) exceeded"), + "INT-020 names derived facts" + ); + } + + #[test] + #[allow(deprecated)] + fn max_results_is_an_alias_and_the_lower_limit_applies() { + let int020 = Some("INT-020".to_string()); + let db = chain_db(OpenOptions::default().max_results(14)); + assert_eq!(chain_code(&db, CHAIN_QUERY), int020, "alias alone"); + let db = chain_db(OpenOptions::default().max_results(15)); + assert_eq!(chain_code(&db, CHAIN_QUERY), None, "alias alone, enough"); + let db = chain_db( + OpenOptions::default() + .max_derived_facts(14) + .max_results(1_000), + ); + assert_eq!( + chain_code(&db, CHAIN_QUERY), + int020, + "max_derived_facts lower" + ); + let db = chain_db( + OpenOptions::default() + .max_derived_facts(1_000) + .max_results(14), + ); + assert_eq!(chain_code(&db, CHAIN_QUERY), int020, "max_results lower"); + } + + #[test] + #[allow(deprecated)] + fn max_derived_facts_alone_raises_the_limit_above_the_default() { + // The alias has no limit of its own unless set (#553). + let opts = OpenOptions::default().max_derived_facts(2_000_000); + assert_eq!(opts.derived_fact_limit(), 2_000_000); + assert_eq!(OpenOptions::default().derived_fact_limit(), 1_000_000); + assert_eq!( + OpenOptions::default() + .max_results(2_000_000) + .derived_fact_limit(), + 1_000_000, + "the alias does not raise the limit" + ); + } + + #[test] + fn per_query_limits_replace_the_database_limit_and_the_lower_applies() { + let int020 = Some("INT-020".to_string()); + let q = |opts: &str| format!("(query [:find ?x ?y :where (reachable ?x ?y) {opts}])"); + let db = chain_db(OpenOptions::default().max_derived_facts(14)); + assert_eq!( + chain_code(&db, &q(":max-derived-facts 15")), + None, + "replaces" + ); + assert_eq!( + chain_code(&db, &q(":max-results 15")), + None, + "alias replaces" + ); + let db = chain_db(OpenOptions::default()); + assert_eq!(chain_code(&db, &q(":max-results 14")), int020, "alias"); + assert_eq!( + chain_code(&db, &q(":max-derived-facts 15 :max-results 14")), + int020, + ":max-results lower" + ); + assert_eq!( + chain_code(&db, &q(":max-derived-facts 14 :max-results 15")), + int020, + ":max-derived-facts lower" + ); + } + // ── read-only handle drop must not modify the file ──────────────────────── #[test] diff --git a/src/error.rs b/src/error.rs index 2c4172fd2..339f58aed 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1636,7 +1636,7 @@ pub(crate) const REGISTRY: &[(ErrorCode, &str, &str, ErrorCategory)] = &[ ( ErrorCode::Int020, "INT-020", - "evaluator: iteration or result limit exceeded: {}", + "evaluator: iteration or derived-fact limit exceeded: {}", ErrorCategory::Internal, ), ( diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index bd7354187..a6f8dfd24 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -39,10 +39,19 @@ use std::sync::{Arc, RwLock}; /// Default maximum iterations for recursive evaluation (kept for reference). #[allow(dead_code)] pub const DEFAULT_MAX_ITERATIONS: usize = 1000; -/// Default maximum facts that can be derived per iteration +/// Default maximum facts the rules of one query may derive in total; base +/// facts do not count (#553). pub const DEFAULT_MAX_DERIVED_FACTS: usize = 1_000_000; -/// Default maximum total query results -pub const DEFAULT_MAX_RESULTS: usize = 1_000_000; + +/// `INT-020` for a rule query that derived more than `limit` facts (#553). +fn derived_facts_exceeded(limit: usize) -> anyhow::Error { + err_coded!( + ErrorCode::Int020, + format!( + "Max derived facts ({limit}) exceeded. The rules derived more facts than the limit; base facts do not count." + ) + ) +} /// Recursive evaluator for Datalog rules using semi-naive evaluation. /// @@ -66,10 +75,8 @@ pub struct RecursiveEvaluator { functions: Arc>, /// Maximum iterations before giving up (prevents infinite loops) max_iterations: usize, - /// Maximum facts that can be derived per iteration - max_derived_facts: usize, /// Maximum facts the rules may derive in one evaluation; base facts do not count - max_results: usize, + max_derived_facts: usize, /// The value a `:db/valid-at` pattern in a rule body binds (#617) valid_at: Value, } @@ -82,15 +89,13 @@ impl RecursiveEvaluator { /// * `rules` - Rule registry /// * `functions` - Function registry for UDF predicates/aggregates /// * `max_iterations` - Safety limit (e.g., 1000) - /// * `max_derived_facts` - Maximum facts per iteration - /// * `max_results` - Maximum facts the rules may derive (base facts do not count) + /// * `max_derived_facts` - Maximum facts the rules may derive (base facts do not count) pub fn new( storage: FactStorage, rules: Arc>, functions: Arc>, max_iterations: usize, max_derived_facts: usize, - max_results: usize, ) -> Self { RecursiveEvaluator { storage, @@ -98,7 +103,6 @@ impl RecursiveEvaluator { functions, max_iterations, max_derived_facts, - max_results, valid_at: Value::Null, } } @@ -143,7 +147,8 @@ impl RecursiveEvaluator { (f.entity, f.attribute.clone(), encoded) }) .collect(); - // `max_results` limits the facts the rules derive, not the database (#528). + // `max_derived_facts` limits the facts the rules derive, not the + // database (#528, #553). let base_count = seen_facts.len(); let mut iteration = 0; @@ -165,17 +170,6 @@ impl RecursiveEvaluator { // Evaluate rules once, get new facts let new_facts = self.evaluate_iteration(predicates, &derived)?; - // Check per-iteration fact limit - if new_facts.len() > self.max_derived_facts { - return Err(err_coded!( - ErrorCode::Int020, - format!( - "Max derived facts per iteration ({}) exceeded. Rule may be generating too many facts.", - self.max_derived_facts - ) - )); - } - // Compute delta: facts not yet seen let mut delta = Vec::new(); for fact in new_facts { @@ -183,11 +177,8 @@ impl RecursiveEvaluator { let key = (fact.entity, fact.attribute.clone(), encoded); if !seen_facts.contains(&key) { // Check total derived-fact limit - if seen_facts.len() - base_count >= self.max_results { - return Err(err_coded!( - ErrorCode::Int020, - format!("Max query results ({}) exceeded.", self.max_results) - )); + if seen_facts.len() - base_count >= self.max_derived_facts { + return Err(derived_facts_exceeded(self.max_derived_facts)); } seen_facts.insert(key); delta.push(fact); @@ -582,8 +573,9 @@ pub struct StratifiedEvaluator { rules: Arc>, functions: Arc>, max_iterations: usize, + /// Maximum facts the rules may derive in one evaluation, across strata + /// and repeated passes; base facts do not count (#553) max_derived_facts: usize, - max_results: usize, /// The value a `:db/valid-at` pattern in a rule body binds (#617) valid_at: Value, } @@ -595,7 +587,6 @@ impl StratifiedEvaluator { functions: Arc>, max_iterations: usize, max_derived_facts: usize, - max_results: usize, ) -> Self { StratifiedEvaluator { storage, @@ -603,7 +594,6 @@ impl StratifiedEvaluator { functions, max_iterations, max_derived_facts, - max_results, valid_at: Value::Null, } } @@ -661,7 +651,7 @@ impl StratifiedEvaluator { drop(registry); // release read lock before recursive calls let accumulated = self.storage.clone(); - // Facts the rules derive, for `max_results` across strata and repeated + // Facts the rules derive, for `max_derived_facts` across strata and repeated // passes (each pass's `RecursiveEvaluator` sees earlier ones as base). let mut derived_total = 0usize; @@ -734,7 +724,6 @@ impl StratifiedEvaluator { self.functions.clone(), self.max_iterations, self.max_derived_facts, - self.max_results, ) .with_valid_at(self.valid_at.clone()); let derived = sub_eval.evaluate_recursive_rules(&stratum_preds)?; @@ -755,11 +744,8 @@ impl StratifiedEvaluator { ); if !existing.contains(&key) { derived_total += 1; - if derived_total > self.max_results { - return Err(err_coded!( - ErrorCode::Int020, - format!("Max query results ({}) exceeded.", self.max_results) - )); + if derived_total > self.max_derived_facts { + return Err(derived_facts_exceeded(self.max_derived_facts)); } let _ = accumulated.load_fact(fact); } @@ -780,7 +766,7 @@ impl StratifiedEvaluator { }) .collect(); } - let mut new_in_pass = 0usize; + let mut new_in_pass = false; for (_pred, rule) in &mixed_rules { // Collect Pattern and Expr clauses for the planner. // RuleInvocations are converted to Pattern; Not/NotJoin/Or/OrJoin extracted separately. @@ -950,7 +936,6 @@ impl StratifiedEvaluator { Arc::clone(&self.functions), 1, self.max_derived_facts, - self.max_results, ); 'binding: for binding in candidates { @@ -1009,22 +994,10 @@ impl StratifiedEvaluator { if !known.insert(key) { continue; } - new_in_pass += 1; - if new_in_pass > self.max_derived_facts { - return Err(err_coded!( - ErrorCode::Int020, - format!( - "Max derived facts per iteration ({}) exceeded. Rule may be generating too many facts.", - self.max_derived_facts - ) - )); - } + new_in_pass = true; derived_total += 1; - if derived_total > self.max_results { - return Err(err_coded!( - ErrorCode::Int020, - format!("Max query results ({}) exceeded.", self.max_results) - )); + 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). @@ -1034,7 +1007,7 @@ impl StratifiedEvaluator { } } - if !repeat || new_in_pass == 0 { + if !repeat || !new_in_pass { break; } } @@ -1096,14 +1069,8 @@ mod tests { let rules = Arc::new(RwLock::new(RuleRegistry::new())); let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); - let _evaluator = RecursiveEvaluator::new( - storage, - rules, - functions, - 1000, - DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, - ); + let _evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, DEFAULT_MAX_DERIVED_FACTS); // Note: RecursiveEvaluator uses evaluate_recursive_rules, not evaluate // let derived = _evaluator.evaluate(&["p".to_string()]).unwrap(); } @@ -1146,7 +1113,6 @@ mod tests { functions.clone(), 0, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); let code = expect_err_code(result); @@ -1159,7 +1125,7 @@ mod tests { #[test] fn test_max_derived_facts_exceeded_returns_int020() { // Same rationale as test_max_iterations_exceeded_returns_error above: - // "Max derived facts per iteration exceeded" shares INT-020. + // "Max derived facts exceeded" shares INT-020. let storage = create_test_storage(); let rules = Arc::new(RwLock::new(RuleRegistry::new())); register_test_rule(&rules, r#"(rule [(reachable ?x ?y) [?x :connected ?y]])"#); @@ -1168,10 +1134,8 @@ mod tests { r#"(rule [(reachable ?x ?y) [?x :connected ?z] (reachable ?z ?y)])"#, ); let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); - // max_derived_facts=0 means the very first iteration's derived facts - // (there are 2 base :connected facts) exceed the limit. - let evaluator = - RecursiveEvaluator::new(storage, rules, functions, 1000, 0, DEFAULT_MAX_RESULTS); + // max_derived_facts=0 means the first derived fact exceeds the limit. + let evaluator = RecursiveEvaluator::new(storage, rules, functions, 1000, 0); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); let code = expect_err_code(result); assert_eq!(code, "INT-020"); @@ -1203,7 +1167,6 @@ mod tests { functions, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate_recursive_rules(&["reachable".to_string()]); let code = expect_err_code(result); @@ -1239,7 +1202,6 @@ mod tests { functions, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate_recursive_rules(&["over_ten".to_string()]); let code = expect_err_code(result); @@ -1272,7 +1234,6 @@ mod tests { functions, DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate(&["reachable".to_string()]); let code = expect_err_code(result); @@ -1285,14 +1246,8 @@ mod tests { let storage = FactStorage::new(); let rules = Arc::new(RwLock::new(RuleRegistry::new())); let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); - let evaluator = RecursiveEvaluator::new( - storage, - rules, - functions, - 1000, - DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, - ); + let evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, DEFAULT_MAX_DERIVED_FACTS); let result = evaluator.rule_invocation_to_pattern(&[]); assert!( result.is_err(), @@ -1306,14 +1261,8 @@ mod tests { let storage = FactStorage::new(); let rules = Arc::new(RwLock::new(RuleRegistry::new())); let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); - let evaluator = RecursiveEvaluator::new( - storage, - rules, - functions, - 1000, - DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, - ); + let evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, DEFAULT_MAX_DERIVED_FACTS); let head = vec![EdnValue::Symbol("predicate".to_string())]; // only 1 element let binding = std::collections::HashMap::new(); let result = evaluator.instantiate_head(&head, &binding); @@ -1342,14 +1291,8 @@ mod tests { }; registry.register_rule_unchecked("empty-body-pred".to_string(), rule); let rules = Arc::new(RwLock::new(registry)); - let evaluator = RecursiveEvaluator::new( - storage, - rules, - functions, - 1000, - DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, - ); + let evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, DEFAULT_MAX_DERIVED_FACTS); let result = evaluator.evaluate_recursive_rules(&["empty-body-pred".to_string()]); // Should succeed (returns base facts only, derives nothing) assert!(result.is_ok(), "empty body rule should not fail"); @@ -1388,14 +1331,8 @@ mod tests { }; registry.register_rule_unchecked("expr-only-pred".to_string(), rule); let rules = Arc::new(RwLock::new(registry)); - let evaluator = RecursiveEvaluator::new( - storage, - rules, - functions, - 1000, - DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, - ); + let evaluator = + RecursiveEvaluator::new(storage, rules, functions, 1000, DEFAULT_MAX_DERIVED_FACTS); // This exercises the expr-only path. The expr evaluates to false → no facts derived. let result = evaluator.evaluate_recursive_rules(&["expr-only-pred".to_string()]); assert!(result.is_ok(), "expr-only rule body should not fail"); @@ -1483,7 +1420,6 @@ mod tests { functions, 1000, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); // Ask for both "a" and "nonexistent" — nonexistent has no rules → stratum_preds may be empty let result = evaluator.evaluate(&["a".to_string(), "nonexistent".to_string()]); @@ -1555,7 +1491,6 @@ mod tests { functions, 1000, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let result = evaluator.evaluate(&["big".to_string()]); assert!( @@ -1573,30 +1508,6 @@ mod tests { ); } - #[test] - fn test_stratified_max_results_limit() { - let storage = create_test_storage(); - let functions = Arc::new(RwLock::new(FunctionRegistry::with_builtins())); - let rules = Arc::new(RwLock::new(RuleRegistry::new())); - - register_test_rule(&rules, "(rule [(all ?x) [?x :connected _]])"); - - let evaluator = StratifiedEvaluator::new( - storage, - rules, - functions, - 100, - DEFAULT_MAX_DERIVED_FACTS, - 1, // very low max_results - ); - - let result = evaluator.evaluate(&["all".to_string()]); - assert!( - result.is_err(), - "stratified should error when max_results exceeded" - ); - } - #[test] fn test_stratified_max_derived_facts_limit() { let storage = create_test_storage(); @@ -1606,12 +1517,7 @@ mod tests { register_test_rule(&rules, "(rule [(all ?x) [?x :connected _]])"); let evaluator = StratifiedEvaluator::new( - storage, - rules, - functions, - 100, - 1, // very low max_derived_facts - DEFAULT_MAX_RESULTS, + storage, rules, functions, 100, 1, // very low max_derived_facts ); let result = evaluator.evaluate(&["all".to_string()]); @@ -1657,7 +1563,6 @@ mod tests { Arc::clone(&functions), DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_DERIVED_FACTS, - DEFAULT_MAX_RESULTS, ); let derived = evaluator.evaluate(&["eligible".to_string()]).unwrap(); @@ -1673,7 +1578,7 @@ mod tests { fn counter_evaluator( guard: &str, max_iterations: usize, - max_results: usize, + max_derived_facts: usize, ) -> StratifiedEvaluator { let storage = FactStorage::new(); storage @@ -1689,21 +1594,18 @@ mod tests { &rules, &format!("(rule [(n ?x ?w) (n ?x ?v) {guard} [(+ ?v 1) ?w] (not [?x :stop true])])"), ); - StratifiedEvaluator::new( - storage, - rules, - functions, - max_iterations, - DEFAULT_MAX_DERIVED_FACTS, - max_results, - ) + StratifiedEvaluator::new(storage, rules, functions, max_iterations, max_derived_facts) } #[test] fn test_recursion_through_mixed_rule_reaches_fixpoint() { - let derived = counter_evaluator("[(< ?v 3)]", DEFAULT_MAX_ITERATIONS, DEFAULT_MAX_RESULTS) - .evaluate(&["n".to_string()]) - .unwrap(); + let derived = counter_evaluator( + "[(< ?v 3)]", + DEFAULT_MAX_ITERATIONS, + DEFAULT_MAX_DERIVED_FACTS, + ) + .evaluate(&["n".to_string()]) + .unwrap(); let n = derived .get_asserted_facts() .unwrap() @@ -1715,18 +1617,19 @@ mod tests { #[test] fn test_recursion_through_mixed_rule_max_iterations() { - let result = counter_evaluator("", 5, DEFAULT_MAX_RESULTS).evaluate(&["n".to_string()]); + let result = + counter_evaluator("", 5, DEFAULT_MAX_DERIVED_FACTS).evaluate(&["n".to_string()]); assert_eq!(expect_err_code(result), "INT-020"); } #[test] - fn test_recursion_through_mixed_rule_max_results() { + fn test_recursion_through_mixed_rule_max_derived_facts() { let result = counter_evaluator("", DEFAULT_MAX_ITERATIONS, 3).evaluate(&["n".to_string()]); assert_eq!(expect_err_code(result), "INT-020"); } #[test] - fn test_recursion_through_mixed_rule_max_results_counts_every_pass() { + fn test_recursion_through_mixed_rule_max_derived_facts_counts_every_pass() { // n0 → m0 → n1 → m1 → n2 → m2 → n3: seven facts, three from the mixed // rule and one from each positive pass. let rules = Arc::new(RwLock::new(RuleRegistry::new())); @@ -1736,7 +1639,7 @@ mod tests { &rules, "(rule [(m ?x ?v) (n ?x ?v) [(< ?v 3)] (not [?x :stop true])])", ); - let evaluator = |max_results| { + let evaluator = |max_derived_facts| { // The evaluator adds what it derives to this storage. let storage = FactStorage::new(); storage @@ -1750,8 +1653,7 @@ mod tests { Arc::clone(&rules), Arc::new(RwLock::new(FunctionRegistry::with_builtins())), DEFAULT_MAX_ITERATIONS, - DEFAULT_MAX_DERIVED_FACTS, - max_results, + max_derived_facts, ) }; evaluator(7).evaluate(&["n".to_string()]).unwrap(); diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 6dab13390..c0ca92e77 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -152,8 +152,8 @@ pub struct DatalogExecutor { rules: Arc>, // RwLock pre-wired for 7.7b register_aggregate API. functions: Arc>, + /// The most facts a rule query may derive, base facts not counted (#553). max_derived_facts: usize, - max_results: usize, } impl DatalogExecutor { @@ -167,7 +167,6 @@ impl DatalogExecutor { rules: Arc::new(RwLock::new(RuleRegistry::new())), functions: Arc::new(RwLock::new(FunctionRegistry::with_builtins())), max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS, - max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS, } } @@ -187,7 +186,6 @@ impl DatalogExecutor { rules, functions, max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS, - max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS, } } @@ -206,7 +204,6 @@ impl DatalogExecutor { rules, functions, max_derived_facts: crate::query::datalog::evaluator::DEFAULT_MAX_DERIVED_FACTS, - max_results: crate::query::datalog::evaluator::DEFAULT_MAX_RESULTS, } } @@ -231,7 +228,6 @@ impl DatalogExecutor { rules: Arc>, functions: Arc>, max_derived_facts: usize, - max_results: usize, ) -> Self { DatalogExecutor { storage, @@ -241,14 +237,13 @@ impl DatalogExecutor { rules, functions, max_derived_facts, - max_results, } } - /// Set complexity limits on an existing executor. - pub fn set_limits(&mut self, max_derived_facts: usize, max_results: usize) { + /// Set the most facts a rule query may derive, base facts not counted + /// (`OpenOptions::max_derived_facts`, #553). + pub fn set_limits(&mut self, max_derived_facts: usize) { self.max_derived_facts = max_derived_facts; - self.max_results = max_results; } /// Read every fact from `snapshot`, so the queries of this executor see @@ -612,7 +607,6 @@ impl DatalogExecutor { rules: self.rules.clone(), functions: self.functions.clone(), max_derived_facts: self.max_derived_facts, - max_results: self.max_results, } } @@ -809,9 +803,13 @@ impl DatalogExecutor { filtered_storage.load_fact(fact)?; } - // Compute effective limits: per-query override takes precedence over executor default. - let effective_max_derived = query.max_derived_facts.unwrap_or(self.max_derived_facts); - let effective_max_results = query.max_results.unwrap_or(self.max_results); + // A per-query limit replaces the executor's; `:max-results` is a + // deprecated alias of `:max-derived-facts`, and the lower of the two + // applies (#553). + let effective_max_derived = match (query.max_derived_facts, query.max_results) { + (None, None) => self.max_derived_facts, + (a, b) => a.unwrap_or(usize::MAX).min(b.unwrap_or(usize::MAX)), + }; // Apply magic sets rewriting for demand-driven recursive evaluation. // Returns None for all-free queries — zero overhead path. @@ -840,7 +838,6 @@ impl DatalogExecutor { self.functions.clone(), 1000, // max iterations effective_max_derived, - effective_max_results, ) .with_valid_at(valid_at_value.clone()); @@ -4178,7 +4175,7 @@ mod tests { rules.clone(), functions.clone(), ); - executor.set_limits(1_000_000, 1_000_000); + executor.set_limits(1_000_000); executor .execute(parse_datalog_command(r#"(rule [(reachable ?x ?y) [?x :edge ?y]])"#).unwrap()) diff --git a/src/query/datalog/types.rs b/src/query/datalog/types.rs index 717cf47d0..1893b8782 100644 --- a/src/query/datalog/types.rs +++ b/src/query/datalog/types.rs @@ -558,11 +558,12 @@ pub struct DatalogQuery { pub valid_at: Option, /// Grouping variables that participate in grouping but are excluded from output rows. pub with_vars: Vec, - /// Per-query override for maximum derived facts per recursive rule iteration. - /// `None` falls back to the executor's configured limit (from `OpenOptions`). + /// Per-query `:max-derived-facts`: the most facts the query's rules may + /// derive in total, base facts not counted (#553). With neither this nor + /// `max_results`, the executor's limit (from `OpenOptions`) applies. pub max_derived_facts: Option, - /// Per-query override for maximum total query results. - /// `None` falls back to the executor's configured limit (from `OpenOptions`). + /// Per-query `:max-results`, a deprecated alias of `:max-derived-facts`; + /// with both, the lower applies (#553). It never limited returned rows. pub max_results: Option, } diff --git a/tests/cursor_test.rs b/tests/cursor_test.rs index 32228f521..de322e43c 100644 --- a/tests/cursor_test.rs +++ b/tests/cursor_test.rs @@ -225,7 +225,10 @@ fn query_on_a_write_transaction_thread_is_int_001() { #[test] fn rule_limits_apply_while_the_engine_materialises() { - let db = OpenOptions::new().max_results(3).open_memory().unwrap(); + let db = OpenOptions::new() + .max_derived_facts(3) + .open_memory() + .unwrap(); db.execute("(transact [[:a :next :b] [:b :next :c] [:c :next :d] [:d :next :e]])") .unwrap(); db.execute("(rule [(reach ?x ?y) [?x :next ?y]])").unwrap(); diff --git a/tests/error_codes_qry_test.rs b/tests/error_codes_qry_test.rs index cdcce23d4..de98e4576 100644 --- a/tests/error_codes_qry_test.rs +++ b/tests/error_codes_qry_test.rs @@ -66,7 +66,7 @@ fn query_with_rules_unknown_predicate_returns_qry_007() { /// A recursive rule with an artificially tiny per-query `max_derived_facts` /// hits `RecursiveEvaluator::evaluate_recursive_rules`'s "Max derived facts -/// per iteration exceeded" branch (src/query/datalog/evaluator.rs). No +/// exceeded" branch (src/query/datalog/evaluator.rs). No /// QRY-0xx code is documented for this in ERROR_REFERENCE.md — see the /// module doc comment above for why. #277 step 6 assigned this shared /// "limit exceeded" family the INT-020 code. diff --git a/tests/recursive_rules_test.rs b/tests/recursive_rules_test.rs index 2be4dc4ff..03737cbb6 100644 --- a/tests/recursive_rules_test.rs +++ b/tests/recursive_rules_test.rs @@ -469,12 +469,13 @@ fn test_convergence_simple_graph() { } } -/// #528: `max_results` limits what the rules derive, not the size of the database. -/// A rule query must answer on a database with more live facts than `max_results`. +/// #528, #553: `max_derived_facts` limits what the rules derive, not the size +/// of the database. A rule query must answer on a database with more live +/// facts than the limit. #[test] -fn test_max_results_counts_derived_facts_not_base_facts() { +fn test_max_derived_facts_counts_derived_facts_not_base_facts() { let db = minigraf::OpenOptions::new() - .max_results(10) + .max_derived_facts(10) .open_memory() .unwrap(); // A chain a -> b -> c -> d, plus 50 unrelated facts: 53 live facts in all. @@ -499,7 +500,7 @@ fn test_max_results_counts_derived_facts_not_base_facts() { } // The limit still stops a rule that derives more than it allows. let err = db - .execute("(query [:find ?x ?y :where (boss ?x ?y) :max-results 5])") + .execute("(query [:find ?x ?y :where (boss ?x ?y) :max-derived-facts 5])") .unwrap_err(); assert_eq!(err.code(), "INT-020"); }