diff --git a/CHANGELOG.md b/CHANGELOG.md index f7d16a9bca..be95cb471b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Join answers no longer depend on the query plan** (#545). Two cases changed. A join on a float value now pairs `0.0` with `-0.0`, as a shared variable compared after the join key already did; before, `Value`'s hash told them apart, so the join key never paired them. NaN still equals nothing. Float constants in a pattern still match within `f64::EPSILON`. And a variable bound to a keyword by one pattern and to the ref of the entity the keyword names by another, which already joined, now returns the kind from the first of those patterns in the `:where` text. Before, it returned the kind from the pattern the planner ran first, so the answer could change with the selectivity of the other patterns, and differed under the `wasm` feature, which does not reorder. For example, with `[:alice :friend :bob]` stored as a keyword, `[:find ?b :where [?a :friend ?b] [?b :name "Bob"]]` returned the ref of `:bob`, because the planner runs the pattern with two constants first, and now returns the keyword `:bob`. Expression bindings follow the next entry (#596). The rule covers the top-level `:where` of queries with and without rules; inside `or`, `not` and rule bodies the kinds are unchanged. - **An expression binding a variable that another clause binds keeps only the rows where the two agree** (#596). `[(f …) ?x]` used to overwrite `?x` wherever the planner ran it, so when a pattern also bound `?x` the answer depended on whether that pattern ran first, and differed under the `wasm` feature, which does not reorder. Now the expression unifies: the row is kept when its result equals `?x`'s value, with the join equality of #545 (floats by IEEE `==`, a keyword equal to a ref to the entity it names, an integer never equal to a float, NaN equal to nothing). For example, with `[:a :age 30] [:b :age 40] [:p1 :score 41]`, `[:find ?a ?x :where [?e :age ?a] [:p1 :score ?x] [(+ ?a 1) ?x]]` returned `[30 31] [40 41]` natively and now returns `[40 41]`, as it did under `wasm`. `[(+ ?v 1) ?v]` never matches, and two expressions binding one variable must agree. When the two values differ only as keyword and ref, the variable returns the value of the first clause in the `:where` text that binds it, expressions included. This applies to `or` branches, `not` bodies and rule bodies too, on the executor and on the streaming engine. - **A value a `not` / `not-join` body takes from the outer row compares as a join compares it** (#546). The executor had two paths for a negation body: the exclusion-set path compared the outer row's values as joins do (floats by IEEE `==`, a keyword equal to a ref to the entity it names), while the per-row path, taken when the body held an expression or a pseudo-attribute, in a query that invokes a rule, in an `or` branch and in a rule body, substituted each outer value into the body as a literal, so a float matched within `f64::EPSILON`. The answer therefore changed with the shape of the body: with `[:e1 :x 1e-20] [:g :y 2e-20]`, `[:find ?e :where [?e :x ?f] (not-join [?f] [?g :y ?f])]` returned `:e1` and `[:find ?e :where [?e :x ?f] (not-join [?f] [?g :y ?f] [(> ?f 0.0)])]` returned nothing. Every path now matches the body from the outer values, compared by join equality, so both return `:e1`; `0.0` and `-0.0` are equal and NaN equals nothing. A literal constant in the body still matches floats within `f64::EPSILON`. +- **An `or` / `or-join` gives the same answer on every executor path** (#546). The executor evaluated `or` branches on two paths, and their answers differed. The joined path, taken unless a branch held a `not`, a pseudo-attribute reading an outer pattern's metadata or an expression reading an outer variable, ran each branch alone and joined its rows to the outer rows. The per-row path started each branch from the outer row. Three cases changed, all to the per-row answer. (1) The joined path compared values exactly, so a keyword never met a ref to the entity it names: with `[:alice :friend :bob] [:bob :name "B"]`, `[:find ?e ?n :where [?e :friend ?f] (or [?f :name ?n] [?f :alias ?n])]` returned nothing and now returns `:alice "B"`; floats compare by IEEE `==`. (2) It joined every branch's rows on the outer variables any branch names, so `(or [?e :a ?x] [?f :b ?x])` matched nothing; each branch now meets the outer row on the variables it names. (3) It dropped the rows of an `or-join` branch that does not bind every join variable; such a branch constrains nothing about that variable, so `(or-join [?e] [?x :a 1] [?e :b 2])` keeps every outer row when some entity has `:a 1`. Rows an `or` returns are still distinct. Also, with no `:valid-at`, `:db/valid-at` in a branch read the wall clock instead of the query's "now"; it now reads the query's. - **A per-fact pseudo-attribute reads the nearest pattern before it with the same entity** (#594). `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read the metadata of one fact: the one matched by their *source*, chosen when the query, rule or prepared query is parsed, as the nearest pattern before them in the `:where` text with the same entity term and a stored attribute (a keyword, or a variable as in `[?e ?a _]`). The search starts in the pseudo-attribute's own clause list and moves outwards, before each enclosing `not` / `or`; it crosses a `not-join` / `or-join` only for an entity variable in its join variables, and stops at a rule body, which never reads its caller's patterns. Terms are the same when they are one variable, one `$slot`, or constants naming one entity (`:alice` and its UUID). Before, they read the last pattern *the planner ran* that matched the entity, so the answer depended on the plan and differed under the `wasm` feature: in `[?e :person/name ?n] [?e :person/age ?a] [?e :db/tx-count ?t]`, `?t` could be the tx-count of either fact, and is now the `:person/age` fact's. Three further changes follow: (1) with no source, the query fails at parse time with the new `PRS-081` instead of matching every visible fact of the entity (`[?e :db/tx-count ?t]` before `[?e :person/name ?n]`, a `_` entity, a pseudo-attribute in a rule body whose only candidate is in the caller); to read every fact of an entity, write `[?e ?a _]` before it; (2) inside `not`, `not-join`, `or` and `or-join`, a pseudo-attribute reads the outer fact, so `[?e :person/name ?n] (not [?e :db/tx-count 1])` excludes the entities whose *name* fact is from tx 1, where before the body matched any fact of the entity; (3) rows that differ only in a source fact's metadata are no longer merged by `or`. `:db/valid-at` is unchanged. The pseudo-attribute pattern now binds or checks a value; it never scans facts, so the planner places it after its source rather than by selectivity. - **A pseudo-attribute pattern never gives a variable its value** (#606). A variable bound by several patterns returns the value of the first real pattern in the `:where` text that binds it (#545); a `:db/valid-at` pattern that the planner ran first used to bind its entity variable itself, as a ref, so `[:find ?b ?t :where [?b :db/valid-at ?t] [?a :friend ?b] [?b :name "Bob"]]` returned the ref of `:bob` with source order and the keyword `:bob` stored by `:friend` natively. It returns the keyword now, whatever runs first. Only the keyword-or-ref kind changes; rows and counts are the same. - **Every build reorders query clauses; the `wasm` feature does nothing** (#594, #596). The `wasm` Cargo feature kept patterns, `not` clauses and `or` branches in source order and turned off the `or` short-circuits (#250), for small browser datasets and a predictable order. With every answer independent of the plan (#594, #596, #606) it only made queries slower, and no first-party build enabled it (the browser package uses `browser`). The feature is kept, so builds that name it still resolve, but is deprecated and has no effect. @@ -73,7 +74,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Cursors stream the queries the engine runs** (#473, part 2: #544, third PR). `Minigraf::query`, `PreparedQuery::query` and `BrowserDb.query` no longer compute the whole answer at open for these queries: the cursor pulls one batch of up to 1,024 rows from the engine's operators when it runs out of rows, and `close` or dropping it stops the work. An attribute scan drained with `next_batch(1000)` holds 7 MiB at 1M and 10M facts (was 58 and 458 MiB) and runs 3–17 % faster (#394 envelope). The answer is still the database as it was when the cursor opened, whatever is written or checkpointed while it is open. A read error that happens after some rows of a `next_batch` call were gathered is returned by the next call, after those rows. No API change. - **Joins run on the streaming engine** (#473, part 3: #545, second PR). Queries of several patterns with stored attributes, with or without expression clauses, now run on the engine. Patterns run in the planner's order: the first is a scan, and each later one is an `IndexNestedLoopJoin` when its entity is a variable already bound (one entity range per row, committed and pending), or a `HashJoin` otherwise (value and attribute positions, cross products), built on the side with the smaller estimate. Joins follow the executor's rules (#545, first PR): floats are equal by IEEE `==`, a keyword equals a ref to the entity it names, and a variable keeps the value of its first pattern in the `:where` text. Measured at 1M facts (#394 envelope, p50 and peak RSS): `[:p :follows ?f] [?f :name ?n]` 796 ms → 50 µs and 322 → 4 MiB; `[:p :manager ?b] [?s :manager ?b] [?s :name ?n]` 1.67 s → 148 ms and 392–462 → 14 MiB; `[?e :follows ?f] [?f :group 7] [?f :name ?n]` 2.6 s → 1.1 s and 468–480 → 42 MiB. `or`, `not`, rules and aggregates still run on the executor. Results are unchanged (`test-oracle`). - **Pseudo-attributes across joins and `:db/valid-at` run on the streaming engine** (#473, part 3: #545, third PR). A per-fact pseudo-attribute pattern (`:db/valid-from`, `:db/valid-to`, `:db/tx-count`, `:db/tx-id`) reads the metadata of its source (#594, above): the source's scan or join fills a metadata column from the fact's key, and the pattern binds or checks against it. A `:db/valid-at` pattern joins with every visible fact of its entity, as `[e _ _]` would, with the query's valid time as a column. Measured at 10M facts (#394 envelope, p50 and peak RSS): `[:p :follows ?f] [?f :name ?n] [?f :db/tx-count ?t]` 34 s → 56 µs and 6.0–7.5 GiB → 4 MiB (3.2 s → 56 µs at 1M). Results are unchanged (`test-oracle`). -- **`not` and `not-join` run on the streaming engine** (#473, part 4: #546, first PR). An `AntiJoin` keeps the outer rows for which the body has no row; it never deduplicates. A body that has the same rows for every outer row (its expressions and pseudo-attributes read only variables its own patterns bind) runs once, and its rows' values of the variables it shares with the outer row form a hash set. Any other body, and one whose first pattern's entity comes from the outer row, runs once per outer row from a one-row seed of the values it imports, stopping at its first row: an entity-bound body costs one index probe per row and holds nothing. Bodies are ordered with the imported variables counted as bound. Queries whose negation holds a rule invocation, and queries with `or` / `or-join`, stay on the executor. Measured (#394 envelope, p50 and peak RSS): an entity-bound `not` (`[?e :group 7] (not [?e :age 7])`, run per row) 760 ms → 27 ms and 222 → 6 MiB at 1M facts, 8.7 s → 0.29 s and 1.2 GiB → 6 MiB at 10M; a `not-join` keyed on a value whose body has an expression (`(not-join [?a] [?f :group 17] [?f :age ?a] [(< ?a 50)])`, hashed) 1.29 s → 5.8 ms at 100K, over 60 s → 53 ms and 171 → 7 MiB at 1M, over 60 s → 0.57 s and 1.5 GiB → 9 MiB at 10M. Other workloads unchanged. Results are unchanged (`test-oracle`). +- **`not` and `not-join` run on the streaming engine** (#473, part 4: #546, first PR). An `AntiJoin` keeps the outer rows for which the body has no row; it never deduplicates. A body that has the same rows for every outer row (its expressions and pseudo-attributes read only variables its own patterns bind) runs once, and its rows' values of the variables it shares with the outer row form a hash set. Any other body, and one whose first pattern's entity comes from the outer row, runs once per outer row from a one-row seed of the values it imports, stopping at its first row: an entity-bound body costs one index probe per row and holds nothing. Bodies are ordered with the imported variables counted as bound. Queries whose negation holds a rule invocation stay on the executor. Measured (#394 envelope, p50 and peak RSS): an entity-bound `not` (`[?e :group 7] (not [?e :age 7])`, run per row) 760 ms → 27 ms and 222 → 6 MiB at 1M facts, 8.7 s → 0.29 s and 1.2 GiB → 6 MiB at 10M; a `not-join` keyed on a value whose body has an expression (`(not-join [?a] [?f :group 17] [?f :age ?a] [(< ?a 50)])`, hashed) 1.29 s → 5.8 ms at 100K, over 60 s → 53 ms and 171 → 7 MiB at 1M, over 60 s → 0.57 s and 1.5 GiB → 9 MiB at 10M. Other workloads unchanged. Results are unchanged (`test-oracle`). +- **`or` and `or-join` run on the streaming engine** (#473, part 4: #546, second PR). A `Union` extends each outer row by every row of every branch; a `Distinct` then keeps one of each set of equal rows, comparing values as the executor does (`0.0` equals `-0.0`, a keyword never equals a ref, a row holding NaN is never a duplicate). Each branch is planned as a `not` body is: a branch with the same rows for every outer row runs once, into a table of its rows by their values of the variables it shares with the outer row; any other branch, and one whose first pattern's entity comes from the outer row, runs per outer row from a one-row seed. When the branches bind no new variable (every `or-join`, and an `or` that only filters), an outer row is returned once, from the first branch that has a row. A query whose first clause to run is an `or` starts from the empty row. These stay on the executor: a branch with a rule invocation, a nested `or`, or a predicate the function registry may not have; an `or` whose branches bind their own patterns' metadata; and a branch whose `not` reads a variable only the branch's expression binds. Measured (#394 envelope, p50 and peak RSS): an `or-join` of two branches keyed on a value (`[?e :group 7] [?e :age ?a] (or-join [?a] (and [?f :group 17] [?f :age ?a] [(< ?a 30)]) (and [?g :group 27] [?g :age ?a] [(> ?a 60)]))`, both hashed) 111 ms → 8.3 ms at 100K facts, 1.44 s → 80 ms and 306 → 7 MiB at 1M, 17.1 s → 0.86 s and 1.9 GiB → 12 MiB at 10M. Other workloads unchanged. Results are unchanged (`test-oracle`). - **Committed reads hide superseded history on index keys** (#379). A query's committed facts are now reduced to the ones that survive net-assert (each fact's assertion from its newest transaction, unless that transaction retracted it; #435) while walking the index keys, before any fact is built. Only surviving entries are decoded and translated through the dictionary. A transaction that retracted a triple hides everything older in it, and a long run of hidden entries is skipped with one `seek`. `:as-of N` point and attribute queries now take the same index path instead of reading every fact in the file. On a checkpointed file with 2,000 superseded values, a point query takes 1.03 ms instead of 4.61 ms, an attribute scan 1.24 ms instead of 5.87 ms, and an `:as-of` point query 23 µs instead of 5.6 ms (at depth 1). Results are unchanged: the executor still applies net-assert to committed and pending facts together, and a pending fact is always newer than a committed one. - **B+tree reads no longer follow leaf sibling links** (v8 storage format, PR 1 of 5; #374). Every index scan uses a cursor that walks down from the root and keeps the path, with a forward `seek` that climbs only as far as needed. This prepares for copy-on-write index pages, which cannot keep sibling links. The file format and query results are unchanged. Concurrent 100k-fact scans take 25–37 % less time and checkpointing after one fact at 10k facts 9 % less; single point lookups and attribute scans are 2–6 % slower (about 0.4 µs per lookup). A corrupted child pointer now fails with STG-013 (wrong page type) or INT-049 (cycle) instead of following a bad link. @@ -90,6 +92,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Pseudo-attribute sources (#594).** `tests/pseudo_source_test.rs` covers the source rule (nearest earlier pattern in the text, two pseudo-attributes sharing one, every fact through `[?e ?a _]`, constants by entity id, `$slot`s by name), `PRS-081` for each shape with no source, reading the outer fact from `not`, `not-join` (listed and unlisted variable), `or` (never a sibling branch) and `or-join`, closed rule bodies, and `:db/valid-at`. Parser, optimizer and matcher unit tests cover the hidden variables, their placement and the join variables a crossed `not-join` gains. The plan-independence matrix gains the pseudo-attribute shapes. - **Answers that depend on the plan fail the tests (#596).** A test-only switch (`minigraf::__reorder`, `test-oracle` feature) turns off every place the native build reorders: the pattern selectivity sort, the `not`/`not-join` and `or`/`or-join` cost sorts and the `or` short-circuits (#250), and the engine's `HashJoin` build side. `tests/plan_independence_test.rs` runs a matrix of queries (joins, expressions, rules, `or`/`or-join`, `not`/`not-join`, keyword and ref, floats, long strings, aggregates, time travel), in memory and on file, through `execute` and a cursor, with the switch on and off, and requires the same rows. Under `test-oracle` the model-based (#385) and property (#386) tests also run every generated query with the switch off. - **Negation bodies in both forms (#546).** A second test-only switch (`minigraf::__subplans`, `test-oracle` feature) forces the engine's `not` / `not-join` bodies to run hashed or correlated. `tests/plan_independence_test.rs` runs every query with the body forms chosen, forced hashed and forced correlated, each with reordering on and off; its matrix gains negations over floats near zero, `0.0` and `-0.0`, keywords and refs of one entity, long strings, bodies reading an imported variable they do not bind, variable-free bodies and `:db/valid-at`. `tests/negation_equality_test.rs` checks the changed answers on every executor path, in memory and after a checkpoint. The property test's rerun also forces hashed bodies. Engine unit tests cover the form the planner picks, routing, multiplicity, failing expressions in bodies, and that a hashed body is read once and a correlated one probes once per row. +- **Disjunctions (#546).** `tests/or_equality_test.rs` checks the changed `or` / `or-join` answers through `execute` and a cursor, in memory and after a checkpoint. `tests/plan_independence_test.rs` gains disjunctions (keywords meeting refs, floats near zero, long strings as keys, branches naming different outer variables or no join variable, a branch with `not`, an `or` with nothing before it, a cross product, `:db/valid-at` in a branch), run with branches chosen, forced hashed and forced correlated. The property test generates `or` and `or-join` over bound variables, with a reference evaluator that deduplicates the rows they keep. Engine unit tests run every disjunction shape with each branch form forced against the executor, and cover routing, the form the planner picks, `Distinct`, and that a hashed branch is read once. - `tests/snapshot_atomicity_test.rs` races a writer against a reader: a query must see each transaction whole, whether written with `execute` or a `WriteTransaction` (#554), and must read one state for all its patterns (#555), in memory and on file. It also runs the v2.x checkpoint race from #558, which never failed on v3: copy-on-write checkpoints do not overwrite pages a published reader uses. - **The `datalog_eval` fuzz guard counts partial bindings** (#597). The guard skipped inputs whose patterns join to more than 50,000 rows, counting only the rows after the last pattern. A `not-join` body still runs on the executor pattern by pattern in text order, so a 120-pattern body built hundreds of thousands of partial bindings before its last pattern matched nothing, and ran past the 60-second timeout. The guard now counts the bindings after every pattern. On the `v3` corpus (4,783 inputs) coverage drops by 7 of 9,719 edges. The input is added as a seed, as is the `btree_page` input of the cursor fix above. diff --git a/CLAUDE.md b/CLAUDE.md index a70ab298cd..ad430dcaf7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,11 +135,11 @@ cargo run < demos/demo_negation.txt - `stratification.rs`: `DependencyGraph`, `stratify()` — negative edges + cycle detection - `rules.rs`: `RuleRegistry` — thread-safe rule management - `types.rs`: `EdnValue`, `Pattern`, `DatalogQuery`, `AsOf`, `ValidAt`, `WhereClause` (incl. `Not`, `NotJoin`); `PseudoAttr` enum, `AttributeSpec` wrapper - - `optimizer.rs`: Selectivity-based join reordering on every build (the `wasm` feature is a deprecated no-op). `reorder()` gates every reordering site; tests turn it off per thread (`set_reorder`, `minigraf::__reorder` under `test-oracle`, #596); `plan_seeded` orders a body with its imported variables counted as bound, and `subplans()` lets tests force the engine's negation bodies hashed or correlated (`set_subplans`, `minigraf::__subplans`, #546) + - `optimizer.rs`: Selectivity-based join reordering on every build (the `wasm` feature is a deprecated no-op). `reorder()` gates every reordering site; tests turn it off per thread (`set_reorder`, `minigraf::__reorder` under `test-oracle`, #596); `plan_seeded` orders a body with its imported variables counted as bound, and `subplans()` lets tests force the engine's negation bodies and `or` branches hashed or correlated (`set_subplans`, `minigraf::__subplans`, #546) - `prepared.rs`: `BindValue`, `PreparedQuery` — parse-once/execute-many with named `$slot` bind slots; `prepare_query`, `substitute` - `magic_sets.rs`: Magic-sets rewriting for demand-driven recursive rule evaluation (not applied to rules with `not`/`not-join`) -3a. **`src/query/engine/`** — Streaming query engine (#473), beside the executor until #551: `plan.rs` (which queries it runs: patterns, expression clauses and `not`/`not-join` without rule invocations, in `optimizer::plan` order (deferred `not`s last); a per-fact pseudo-attribute pattern reads the metadata column its source's scan fills (the hidden variable the parser named, #594), and `:db/valid-at` joins as `[e _ _]`; plain `:find` variables, today), `scan.rs` (one pattern over committed key ranges via `CommittedReader::key_source`/`live_keys`, AVET ranges for cross-kind constants, then the pending range by whole runs; one entity per probe for a join), `join.rs` (`IndexNestedLoopJoin` when the pattern's entity is bound, `HashJoin` otherwise; `JoinKey`: floats by IEEE `==`, a keyword equals a ref to the entity it names), `filter.rs` (`Filter`/`Bind` and pseudo-attribute steps over batches; a `Bind` on a bound slot keeps the rows where the result is join-equal, #596), `anti.rs` (`AntiJoin`, #546: a body with the same rows for every outer row runs once into a hash set of its imported-variable keys; any other body, or one whose first pattern's entity is imported, runs per outer row from `seed.rs`'s one-row `Seed`, via `Operator::rewind`; never deduplicates), `cell.rs`/`batch.rs` (id cells in columnar batches of 1,024), `ids.rs` (DICT and provisional ids, `keyword_eid`), `project.rs` (ids → values for returned rows only), `oracle.rs` (with `cfg(test)` or the `test-oracle` feature, every engine query also runs on the executor and must agree). `mod.rs`: `Operator` (`next_batch`/`rewind`/`close`/`counters`), `Stream` (the operator tree over an owned `Snapshot`, pulled one batch at a time). `DatalogExecutor::open` / `execute_query` try it first: a cursor gets the `Stream` (`Answer::Stream`), `execute` drains it. +3a. **`src/query/engine/`** — Streaming query engine (#473), beside the executor until #551: `plan.rs` (which queries it runs: patterns, expression clauses, `not`/`not-join` and `or`/`or-join` without rule invocations, in `optimizer::plan` order, then the `or`s in text order, then the deferred `not`s; a per-fact pseudo-attribute pattern reads the metadata column its source's scan fills (the hidden variable the parser named, #594), and `:db/valid-at` joins as `[e _ _]`; plain `:find` variables, today), `scan.rs` (one pattern over committed key ranges via `CommittedReader::key_source`/`live_keys`, AVET ranges for cross-kind constants, then the pending range by whole runs; one entity per probe for a join), `join.rs` (`IndexNestedLoopJoin` when the pattern's entity is bound, `HashJoin` otherwise; `JoinKey`: floats by IEEE `==`, a keyword equals a ref to the entity it names), `filter.rs` (`Filter`/`Bind` and pseudo-attribute steps over batches; a `Bind` on a bound slot keeps the rows where the result is join-equal, #596), `anti.rs` (`AntiJoin`, #546: a body with the same rows for every outer row runs once into a hash set of its imported-variable keys; any other body, or one whose first pattern's entity is imported, runs per outer row from `seed.rs`'s one-row `Seed`, via `Operator::rewind`; never deduplicates), `union.rs`/`distinct.rs` (`Union` and `Distinct`, #546: each `or` branch planned as a `not` body is, hashed into a table or run per outer row; then one row per distinct binding, as the executor's `Value`s compare), `cell.rs`/`batch.rs` (id cells in columnar batches of 1,024), `ids.rs` (DICT and provisional ids, `keyword_eid`), `project.rs` (ids → values for returned rows only), `oracle.rs` (with `cfg(test)` or the `test-oracle` feature, every engine query also runs on the executor and must agree). `mod.rs`: `Operator` (`next_batch`/`rewind`/`close`/`counters`), `Stream` (the operator tree over an owned `Snapshot`, pulled one batch at a time). `DatalogExecutor::open` / `execute_query` try it first: a cursor gets the `Stream` (`Answer::Stream`), `execute` drains it. 4. **`src/temporal.rs`** — UTC-only timestamp parsing (avoids chrono CVE GHSA-wcg3-cvx6-7396) @@ -204,7 +204,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1578 tests** (1568 passing, 10 ignored; unit + integration + doc). +**1588 tests** (1578 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 dbbab0d037..3318439d3b 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 1578 tests +cargo test # run 1588 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index e2eb4ee769..810330d096 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-19 with `cargo test --quiet` -**Result**: 1,568 passing tests and 10 ignored tests (1,578 total) +**Result**: 1,578 passing tests and 10 ignored tests (1,588 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). @@ -21,7 +21,8 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value - **Join rules** (`tests/join_rules_test.rs`, 10 tests; #545): a join on a float value pairs `0.0` with `-0.0`, through the hash key and as a shared variable, and a float constant still matches within epsilon; a variable bound to a keyword by one pattern and to the ref of the same entity by another returns the kind from the first pattern in `:where` text order, when the planner runs the patterns in another order, through the attribute position, before and after a rule call, and with a repeated pattern; an expression binding unifies with a pattern binding the same variable, and the first binder in the text, pattern or expression, gives the value (#596); a pseudo-attribute pattern never gives a variable its value, even when it runs first (#606; the plan-independence matrix checks it with reordering off). Under the `test-oracle` feature the joins among them also run on the streaming engine. A unit test checks that `-0.0` and `0.0` hash alike. - **Pseudo-attribute sources** (`tests/pseudo_source_test.rs`, 12 tests; #594): a per-fact pseudo-attribute reads the nearest earlier pattern in the text with the same entity term (#594's example in both text orders), two pseudo-attributes share a source, `[:alice ?a _]` gives one row per fact, constant and bound value terms check, `:alice` and its UUID are one term while `?e` and `:alice` are not, PRS-081 for a pattern after it, alone, `_`/`?_x` entities, another entity's pattern and a rule call; a `not` body reads the outer fact (and a source inside the body), `not-join` crosses for a listed variable only, `or` branches read the outer fact and never a sibling, `or-join`, closed rule bodies, `$slot`s by name at prepare time, and `:db/valid-at` once per fact. Parser unit tests check the hidden variables (`?#.`), the join variable a crossed `not-join` gains, and the PRS-081 text; an optimizer test places a pseudo-attribute pattern after its source and the pattern binding its value; matcher tests read the hidden variable, a substituted integer, and nothing without a source; the engine tests run the sourced shapes and check PRS-081 for the old fallback shapes. The plan-independence matrix gains eleven pseudo-attribute shapes. - **Negation equality** (`tests/negation_equality_test.rs`, 5 tests; #546): a value a `not` / `not-join` body takes from the outer row compares by join equality on every path (exclusion set, per-row body with an expression, a query that invokes a rule, a rule body): `1e-20` and `2e-20` differ, `0.0` equals `-0.0`, a keyword imported into an entity position equals the ref, and a float literal in the body still matches within `f64::EPSILON`; through `execute` and a cursor, in memory and after a checkpoint. Engine unit tests (`src/query/engine/tests.rs`, 6 more) run every negation shape (hashed and correlated bodies, keys on entity, value and attribute positions, floats, keywords and refs, long strings, bodies reading an imported variable, variable-free bodies, per-fact pseudo-attributes and `:db/valid-at` in bodies, deferred and repeated negations) at six temporal settings with each body form forced and reordering on and off, in memory and on file before and after checkpoints, against the executor; and check the form the planner picks, routing, multiplicity, failing expressions and unknown predicates in bodies, and that a hashed body is read once while a correlated one probes once per outer row. Optimizer unit tests cover `plan_seeded` and the `SUBPLANS` switch. -- **Plan independence** (`tests/plan_independence_test.rs`, 12 tests, `test-oracle` feature only; #596): a matrix of queries (joins in both text orders, cross products, keyword and ref, floats, long strings, filter and binding expressions, recursive rules and rules with `not`, `or`/`or-join` including the #250 short-circuit shapes, placed and deferred `not`/`not-join`, aggregates, `:as-of`, `:valid-at`, `:any-valid-time`), in memory and on file after a checkpoint and a reopen, through `execute` and a cursor, gives the same bag of rows with clause reordering on and off (`minigraf::__reorder`) and with the engine's negation bodies chosen, forced hashed and forced correlated (`minigraf::__subplans`, #546; the matrix gains #546's negation shapes); #596's example and the unification cases (an expression whose output is its input, two expressions on one variable, integer vs float, `-0.0` vs `0.0`); and `or` / `or-join` branches whose expressions read or bind from a variable only the outer row binds, nested and in rule bodies (#620). Under `test-oracle` the model-based and property tests also rerun every generated query with reordering off (the property test also with negation bodies forced hashed). Unit tests cover `branch_outer_reads` (#620), `apply_expr` (equal, different, integer vs float, NaN, `-0.0`/`0.0` with and without replacing, keyword vs ref both ways, a failing expression), `Binders::expression`, the switch (source order kept, per thread, restored on drop), and the engine planner's `Bind` modes and build side with the switch off; the engine's join matrix gains six unification shapes. +- **Disjunction equality** (`tests/or_equality_test.rs`, 5 tests; #546): an `or` / `or-join` branch meets the outer row by join equality on every executor path (a keyword in the outer row meets a ref in a branch; `0.0` and `-0.0`; floats `1e-20` apart do not), branches naming different outer variables each meet the outer row on their own, and an `or-join` branch that does not bind its join variable keeps every outer row when it has a row; through `execute` and a cursor, in memory and after a checkpoint. Engine unit tests run every disjunction shape with each branch form forced and reordering on and off against the executor, and cover routing (rule invocations, nested `or`, registry predicates, branch-local metadata stay on the executor), the branch form the planner picks, `Distinct` (equal rows collapse; a keyword and a ref, `-0.0` and `0.0`), and that a hashed branch is read once and a correlated one runs only for rows earlier branches did not match. +- **Plan independence** (`tests/plan_independence_test.rs`, 12 tests, `test-oracle` feature only; #596): a matrix of queries (joins in both text orders, cross products, keyword and ref, floats, long strings, filter and binding expressions, recursive rules and rules with `not`, `or`/`or-join` including the #250 short-circuit shapes, placed and deferred `not`/`not-join`, aggregates, `:as-of`, `:valid-at`, `:any-valid-time`), in memory and on file after a checkpoint and a reopen, through `execute` and a cursor, gives the same bag of rows with clause reordering on and off (`minigraf::__reorder`) and with the engine's negation bodies and `or` branches chosen, forced hashed and forced correlated (`minigraf::__subplans`, #546; the matrix gains #546's negation and disjunction shapes); #596's example and the unification cases (an expression whose output is its input, two expressions on one variable, integer vs float, `-0.0` vs `0.0`); and `or` / `or-join` branches whose expressions read or bind from a variable only the outer row binds, nested and in rule bodies (#620). Under `test-oracle` the model-based and property tests also rerun every generated query with reordering off (the property test also with negation bodies and `or` branches forced hashed; it generates `or` / `or-join` over bound variables, #546). Unit tests cover `branch_outer_reads` (#620), `apply_expr` (equal, different, integer vs float, NaN, `-0.0`/`0.0` with and without replacing, keyword vs ref both ways, a failing expression), `Binders::expression`, the switch (source order kept, per thread, restored on drop), and the engine planner's `Bind` modes and build side with the switch off; the engine's join matrix gains six unification shapes. - **Public diagnostics**: structured parser, query, storage, WAL, API, and internal error codes; the error-code registry is checked against [`ERROR_REFERENCE.md`](ERROR_REFERENCE.md). - **Compatibility and quality**: golden-file corpus of released file formats, cross-platform format compatibility, property-based tests, long-haul smoke coverage, a weekly soak at 10M facts with a 5-hour churn (#392), XTDB/Datomic semantic compatibility, grammar conformance, and rustdoc examples. diff --git a/docs/superpowers/plans/2026-10-18-546-negation-disjunction.md b/docs/superpowers/plans/2026-10-18-546-negation-disjunction.md index b539d087a0..29c2c22686 100644 --- a/docs/superpowers/plans/2026-10-18-546-negation-disjunction.md +++ b/docs/superpowers/plans/2026-10-18-546-negation-disjunction.md @@ -110,6 +110,27 @@ The exclusion-set paths (`apply_not_clause`, `apply_not_join_clause`) already co replacing a cell could not change an answer; this matches the executor, whose body paths pass `replace = false`. +11. **Which `or`s the engine runs (PR 2).** A branch is planned by the same code as a + `not` body (`Builder::sub`), with its `not`s, placed or deferred, as in a query. The + executor keeps: + - a branch holding a rule invocation or a nested `or` / `or-join` (the executor + evaluates a nested one unseeded inside the branch, where a join variable bound only + outside it is an `INT-031`); + - a branch with a predicate the function registry may lack: the executor reports + `QRY-007` only when a row reaches it; + - an `or` whose branches bind different hidden metadata variables (each branch's own + sources): the executor's rows keep them; + - a branch whose `not` reads a variable only the branch's expression binds: the + executor applies a branch's `not`s before its expressions. + + Three more executor answers depended on the path; the per-row path, taken when a + branch reads the outer row, gave the spec's answer. (a) and (b) came up while + comparing the two paths for this plan, (c) from the oracle. PR 2 fixes them in the + executor: (a) a branch naming different outer variables than another met no outer + row on the joined path; (b) an `or-join` branch that does not bind every join + variable lost its rows on the joined path; (c) `:db/valid-at` in a branch read the + wall clock, not the query's "now". + ## Steps ### 1. Executor: seeded bodies (PR 1) diff --git a/examples/perf_envelope.rs b/examples/perf_envelope.rs index 9622c413c9..2377458707 100644 --- a/examples/perf_envelope.rs +++ b/examples/perf_envelope.rs @@ -518,6 +518,24 @@ fn shapes(e: usize, tx_half: u64, hot_tx_half: u64) -> Vec { .count() }, }, + // #546: an `or-join` of two closed branches over different + // groups, each read once and keyed on a value. + Shape { + name: "or_2", + query: "[:find ?e :where [?e :group 7] [?e :age ?a] \ + (or-join [?a] (and [?f :group 17] [?f :age ?a] [(< ?a 30)]) \ + (and [?g :group 27] [?g :age ?a] [(> ?a 60)]))]" + .into(), + rows: { + let ages: std::collections::HashSet = (0..e) + .filter(|i| (i % 100 == 17 && i % 90 < 30) || (i % 100 == 27 && i % 90 > 60)) + .map(|i| i % 90) + .collect(); + (0..e) + .filter(|i| i % 100 == 7 && ages.contains(&(i % 90))) + .count() + }, + }, Shape { name: "recursive_ancestors", query: format!("[:find ?b :where (boss :p{leaf} ?b)]"), diff --git a/src/lib.rs b/src/lib.rs index bf8ab9e015..035e0182cd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,7 +135,7 @@ pub fn __reorder(on: bool) -> ReorderGuard { query::datalog::optimizer::set_reorder(on) } -// Plan-independence tests (#546): force how negation bodies run. +// Plan-independence tests (#546): force how negation bodies and `or` branches run. #[cfg(feature = "test-oracle")] #[doc(hidden)] pub use query::datalog::optimizer::{Subplans, SubplansGuard}; diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 28133fb3bc..350d000ec8 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -722,7 +722,7 @@ impl DatalogExecutor { filtered_facts.clone(), &rules_guard, query.as_of.clone(), - query.valid_at.clone(), + Some(branch_valid_at(&valid_at_value)), ®istry, )?; drop(rules_guard); @@ -973,7 +973,7 @@ impl DatalogExecutor { derived_facts.clone(), &rules_guard, query.as_of.clone(), - query.valid_at.clone(), + Some(branch_valid_at(&valid_at_value)), ®istry, )?; drop(rules_guard); @@ -1330,12 +1330,9 @@ pub(crate) fn reads_metadata(clauses: &[WhereClause]) -> bool { }) } -/// The variables an `or` / `or-join` branch's expressions read that the branch -/// itself never binds — by a pattern, a rule invocation or an expression output, -/// its own or an enclosing nested branch's. Only the outer row can bind them, so -/// a branch with any must be seeded with that row, not evaluated from an empty -/// binding and joined afterwards (#620). -pub(crate) fn branch_outer_reads(branch: &[WhereClause]) -> std::collections::HashSet { +/// The variables an `or` / `or-join` branch binds itself: by a pattern, a +/// rule invocation or an expression output. +fn branch_binds(branch: &[WhereClause]) -> std::collections::HashSet { let mut bound = std::collections::HashSet::new(); for c in branch { match c { @@ -1357,6 +1354,16 @@ pub(crate) fn branch_outer_reads(branch: &[WhereClause]) -> std::collections::Ha _ => {} } } + bound +} + +/// The variables an `or` / `or-join` branch's expressions read that the branch +/// itself never binds — by a pattern, a rule invocation or an expression output, +/// its own or an enclosing nested branch's. Only the outer row can bind them, so +/// a branch with any must be seeded with that row, not evaluated from an empty +/// binding and joined afterwards (#620). +pub(crate) fn branch_outer_reads(branch: &[WhereClause]) -> std::collections::HashSet { + let bound = branch_binds(branch); let mut reads = std::collections::HashSet::new(); for c in branch { match c { @@ -1889,6 +1896,15 @@ fn project_find_specs(bindings: &[Binding], find_specs: &[FindSpec]) -> Vec ValidAt { + match valid_at_value { + Value::Integer(t) => ValidAt::Timestamp(*t), + _ => ValidAt::AnyValidTime, + } +} + /// Evaluate a single branch of an `or`/`or-join` against incoming bindings. /// /// Processing order (note: top-level execute_query now uses an interleaved plan loop @@ -2026,6 +2042,13 @@ pub(crate) fn evaluate_branch( /// Non-Or/OrJoin clauses are ignored (handled elsewhere). /// For `Or`: union results from all branches (deduplicated by full binding map). /// For `OrJoin`: union results, then project out branch-private variables. +/// A branch row meets an outer row by join equality (#546, spec §5.3): a +/// keyword equals a ref to the entity it names; floats compare by IEEE `==` +/// (`Value`'s own equality). Dedup keys stay exact `Value`s. +fn join_value(v: &Value) -> Value { + PatternMatcher::normalize_join_value(v) +} + pub(crate) fn apply_or_clauses( clauses: &[WhereClause], mut bindings: Vec, @@ -2162,7 +2185,8 @@ pub(crate) fn apply_or_clauses( let mut k: Vec<(String, Value)> = branch_var_names .iter() .filter_map(|v| { - b.get(*v).map(|val| (v.to_string(), val.clone())) + b.get(*v) + .map(|val| (v.to_string(), join_value(val))) }) .collect(); k.sort_unstable_by(|a, b| a.0.cmp(&b.0)); @@ -2173,7 +2197,7 @@ pub(crate) fn apply_or_clauses( let mut k: Vec<(String, Value)> = branch_var_names .iter() .filter_map(|v| { - incoming.get(*v).map(|val| (v.to_string(), val.clone())) + incoming.get(*v).map(|val| (v.to_string(), join_value(val))) }) .collect(); k.sort_unstable_by(|a, b| a.0.cmp(&b.0)); @@ -2186,34 +2210,41 @@ pub(crate) fn apply_or_clauses( } } - // Determine shared variable names: variables present in both - // incoming bindings and branch results. - // Exclude internal metadata keys (prefixed with `__`) — those are - // fact-specific and differ between patterns for the same entity. - let branch_var_names: std::collections::HashSet<&str> = union_bindings + // Each branch row meets an incoming row on the variables both + // bind: the row's own, since branches may name different + // outer variables (#546). Exclude internal metadata keys + // (prefixed with `__`) — those are fact-specific and differ + // between patterns for the same entity. + let outer_vars: std::collections::HashSet<&str> = bindings .iter() .flat_map(|b| b.keys().map(|k| k.as_str())) .filter(|k| !k.starts_with("__")) .collect(); - let shared_vars: Vec = bindings - .iter() - .flat_map(|b| b.keys().cloned()) - .collect::>() - .into_iter() - .filter(|v| !v.starts_with("__") && branch_var_names.contains(v.as_str())) - .collect(); // With no shared variable every key is empty, so each incoming // row joins every branch row: a cross product (#610). - // Build HashMap: shared-key tuple → Vec - let mut branch_map: HashMap, Vec> = HashMap::new(); + // Group the branch rows by their shared variables, then key + // each group's rows on them. + type Groups = Vec<(Vec, HashMap, Vec>)>; + let mut groups: Groups = Vec::new(); for b in union_bindings { - let key: Vec<(String, Value)> = shared_vars + let mut shared: Vec = b + .keys() + .filter(|k| outer_vars.contains(k.as_str())) + .cloned() + .collect(); + shared.sort_unstable(); + let key: Vec<(String, Value)> = shared .iter() - .filter_map(|v| b.get(v).map(|val| (v.clone(), val.clone()))) + .filter_map(|v| b.get(v).map(|val| (v.clone(), join_value(val)))) .collect(); - branch_map.entry(key).or_default().push(b); + if !groups.iter().any(|(vars, _)| *vars == shared) { + groups.push((shared.clone(), HashMap::new())); + } + if let Some((_, map)) = groups.iter_mut().find(|(vars, _)| *vars == shared) { + map.entry(key).or_default().push(b); + } } // For each incoming binding, look up matching branch results and merge. @@ -2221,11 +2252,14 @@ pub(crate) fn apply_or_clauses( let mut seen_result: std::collections::HashSet> = std::collections::HashSet::new(); for incoming in &bindings { - let key: Vec<(String, Value)> = shared_vars - .iter() - .filter_map(|v| incoming.get(v).map(|val| (v.clone(), val.clone()))) - .collect(); - if let Some(matches) = branch_map.get(&key) { + for (shared, branch_map) in &groups { + let key: Vec<(String, Value)> = shared + .iter() + .filter_map(|v| incoming.get(v).map(|val| (v.clone(), join_value(val)))) + .collect(); + let Some(matches) = branch_map.get(&key) else { + continue; + }; for branch_binding in matches { // Merge: start with incoming, extend with branch-introduced vars. let mut merged = incoming.clone(); @@ -2281,11 +2315,13 @@ pub(crate) fn apply_or_clauses( // others are fresh inside), and keep the distinct rows some // branch matches, as the joined path below does. So does a // branch whose expression reads a join variable it does not - // bind itself (#620). - if sorted_oj_branches - .iter() - .any(|b| reads_metadata(b) || !branch_outer_reads(b).is_empty()) - { + // bind itself (#620), and one that does not bind every join + // variable: the joined path would drop its rows (#546). + if sorted_oj_branches.iter().any(|b| { + reads_metadata(b) + || !branch_outer_reads(b).is_empty() + || !join_vars.iter().all(|v| branch_binds(b).contains(v)) + }) { let mut seen: std::collections::HashSet> = std::collections::HashSet::new(); let mut result: Vec = Vec::new(); @@ -2344,7 +2380,9 @@ pub(crate) fn apply_or_clauses( .map(|incoming| { join_vars .iter() - .filter_map(|v| incoming.get(v).map(|val| (v.clone(), val.clone()))) + .filter_map(|v| { + incoming.get(v).map(|val| (v.clone(), join_value(val))) + }) .collect::>() }) .collect() @@ -2374,7 +2412,7 @@ pub(crate) fn apply_or_clauses( if seen_proj.insert(key) { let bkey: Vec<(String, Value)> = join_vars .iter() - .filter_map(|v| b.get(v).map(|val| (v.clone(), val.clone()))) + .filter_map(|v| b.get(v).map(|val| (v.clone(), join_value(val)))) .collect(); branch_map.entry(bkey).or_default().push(b); } @@ -2391,7 +2429,7 @@ pub(crate) fn apply_or_clauses( for incoming in &bindings { let key: Vec<(String, Value)> = join_vars .iter() - .filter_map(|v| incoming.get(v).map(|val| (v.clone(), val.clone()))) + .filter_map(|v| incoming.get(v).map(|val| (v.clone(), join_value(val)))) .collect(); if let Some(matches) = branch_map.get(&key) { for branch_binding in matches { diff --git a/src/query/datalog/optimizer.rs b/src/query/datalog/optimizer.rs index b7a75fb7d7..4091e3585c 100644 --- a/src/query/datalog/optimizer.rs +++ b/src/query/datalog/optimizer.rs @@ -69,7 +69,7 @@ thread_local! { static SUBPLANS: std::cell::Cell = const { std::cell::Cell::new(Subplans::Choose) }; } -/// How the engine runs a negation body: [`Subplans::Choose`], except in +/// How the engine runs a negation body or an `or` branch: [`Subplans::Choose`], except in /// tests while this thread forces a form ([`set_subplans`]). Both forms give /// the same rows. #[inline] diff --git a/src/query/engine/distinct.rs b/src/query/engine/distinct.rs new file mode 100644 index 0000000000..c32e8c7e13 --- /dev/null +++ b/src/query/engine/distinct.rs @@ -0,0 +1,77 @@ +//! `Distinct` (#546 spec §5.2): after an `or`'s `Union`, keeps the first of +//! the rows equal in every variable, as the executor's `Value`s compare: +//! floats by IEEE `==` (`-0.0` equals `0.0`, a NaN equals nothing, so a row +//! holding one is always kept), and a keyword never equal to a ref. + +use super::batch::Batch; +use super::cell::{Cell, JoinKey}; +use super::{Counters, Ctx, Operator}; +use anyhow::Result; +use std::collections::HashSet; + +pub(crate) struct Distinct { + child: Box, + slots: Vec, + /// The rows returned since the last rewind. + seen: HashSet>, + counters: Counters, +} + +impl Distinct { + pub(crate) fn new(child: Box, slots: Vec) -> Self { + Distinct { + child, + slots, + seen: HashSet::new(), + counters: Counters::new("Distinct"), + } + } + + /// Whether row `i` of `batch` is the first of its kind. + fn first(&mut self, batch: &Batch, i: usize, ctx: &mut Ctx<'_>) -> Result { + let mut key = Vec::with_capacity(self.slots.len()); + for &slot in &self.slots { + let Some(c) = batch.cols.get(slot).and_then(|c| c.get(i)) else { + return Ok(true); + }; + let Some(k) = JoinKey::of(c, false, ctx)? else { + return Ok(true); + }; + key.push(k); + } + Ok(self.seen.insert(key)) + } +} + +impl Operator for Distinct { + fn next_batch(&mut self, ctx: &mut Ctx<'_>) -> Result> { + while let Some(mut batch) = self.child.next_batch(ctx)? { + self.counters.rows_in += batch.len as u64; + let mut keep = Vec::with_capacity(batch.len); + for i in 0..batch.len { + keep.push(self.first(&batch, i, ctx)?); + } + batch.retain(&keep); + if batch.len > 0 { + self.counters.out(&batch); + return Ok(Some(batch)); + } + } + Ok(None) + } + + fn rewind(&mut self, seed: &[Cell]) { + self.seen.clear(); + self.child.rewind(seed); + } + + fn close(&mut self) { + self.seen = HashSet::new(); + self.child.close(); + } + + fn counters(&self, out: &mut Vec) { + out.push(self.counters); + self.child.counters(out); + } +} diff --git a/src/query/engine/filter.rs b/src/query/engine/filter.rs index 8adce32a3d..b405ac3e69 100644 --- a/src/query/engine/filter.rs +++ b/src/query/engine/filter.rs @@ -29,6 +29,8 @@ impl Apply { Step::Bind(..) => "Bind", Step::Join(_) => "Join", Step::Anti(_) => "AntiJoin", + Step::Union(_) => "Union", + Step::Distinct(_) => "Distinct", }; Apply { child, @@ -125,8 +127,9 @@ fn apply(step: &Step, mut batch: Batch, ctx: &mut Ctx<'_>) -> Result { batch.retain(&keep); batch.set_col(*slot, out); } - // Joins are operators of their own (`join::Join`, `anti::AntiJoin`). - Step::Join(_) | Step::Anti(_) => {} + // Joins are operators of their own (`join::Join`, `anti::AntiJoin`, + // `union::Union`, `distinct::Distinct`). + Step::Join(_) | Step::Anti(_) | Step::Union(_) | Step::Distinct(_) => {} } Ok(batch) } diff --git a/src/query/engine/mod.rs b/src/query/engine/mod.rs index 6af0a4dd2f..ce572ecdd7 100644 --- a/src/query/engine/mod.rs +++ b/src/query/engine/mod.rs @@ -9,6 +9,7 @@ mod anti; mod batch; mod cell; +mod distinct; mod filter; mod ids; mod join; @@ -20,6 +21,7 @@ mod scan; mod seed; #[cfg(all(test, not(target_arch = "wasm32")))] mod tests; +mod union; use crate::error::{ErrorCode, err_coded}; use crate::graph::storage::Snapshot; @@ -159,6 +161,8 @@ pub(crate) fn build(source: plan::Source, steps: Vec) -> Box Box::new(join::Join::new(root, spec)), plan::Step::Anti(body) => Box::new(anti::AntiJoin::new(root, body)), + plan::Step::Union(branches) => Box::new(union::Union::new(root, branches)), + plan::Step::Distinct(slots) => Box::new(distinct::Distinct::new(root, slots)), step => Box::new(filter::Apply::new(root, step)), }; } diff --git a/src/query/engine/plan.rs b/src/query/engine/plan.rs index 62eb367daa..69618ed638 100644 --- a/src/query/engine/plan.rs +++ b/src/query/engine/plan.rs @@ -26,8 +26,8 @@ use crate::query::datalog::executor::Binders; use crate::query::datalog::matcher::edn_to_entity_id; use crate::query::datalog::optimizer; use crate::query::datalog::types::{ - AsOf, AttributeSpec, DatalogQuery, EdnValue, Expr, FindSpec, Pattern, PseudoAttr, ValidAt, - WhereClause, + AsOf, AttributeSpec, DatalogQuery, EdnValue, Expr, FindSpec, Pattern, PseudoAttr, UnaryOp, + ValidAt, WhereClause, }; use std::collections::{HashMap, HashSet}; @@ -130,6 +130,12 @@ pub(crate) enum Step { /// `not` / `not-join`: keeps the rows for which the body has no row /// (#546). Anti(Body), + /// `or` / `or-join`: each row once per row of each branch, extended by + /// the branch's cells of the new variables (#546 spec §5.1). + Union(Vec), + /// Keeps the first of the rows whose cells at these slots are equal as + /// the executor's values are (#546 spec §5.2). + Distinct(Vec), } /// A `not` / `not-join` body (#546 spec §4). @@ -146,12 +152,22 @@ pub(crate) enum Body { Hashed { plan: Box, keys: Vec }, } +/// One branch of an `or` / `or-join` (#546 spec §5.1). +#[derive(Debug, Clone)] +pub(crate) struct Branch { + pub(crate) body: Body, + /// The body slots whose cells extend the outer row, in the order of the + /// slots they fill; empty for an `or-join`. + pub(crate) new: Vec, +} + /// Where a plan's rows start. #[derive(Debug, Clone)] pub(crate) enum Source { /// The first pattern. Scan(ScanSpec), - /// One row: the cells a correlated body imports, in its first slots. + /// One row: the cells a correlated body imports, in its first slots; + /// for a query whose first clause to run is an `or`, the empty row. Seed, } @@ -269,6 +285,8 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { | WhereClause::Expr { .. } | WhereClause::Not(_) | WhereClause::NotJoin { .. } + | WhereClause::Or(_) + | WhereClause::OrJoin { .. } ) }) { return None; @@ -278,16 +296,20 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { as_of, valid, ); - let (planned, mut deferred) = optimizer::plan(query.where_clauses.clone()); + let (planned, deferred) = optimizer::plan(query.where_clauses.clone()); for (c, _) in planned { b.clause(c)?; } - // A `not` whose variables only an expression binds runs last, as on the - // executor. - if optimizer::reorder() { - deferred.sort_by_key(optimizer::clause_cost); + // `or` / `or-join` after the clauses the plan places, in text order, as + // on the executor (spec §5.1). + for c in &query.where_clauses { + if matches!(c, WhereClause::Or(_) | WhereClause::OrJoin { .. }) { + b.clause(c.clone())?; + } } - for c in deferred { + // A `not` whose variables only an `or` binds runs last, as on the + // executor. + for c in sorted(deferred) { b.clause(c)?; } @@ -482,6 +504,11 @@ impl Builder { let step = self.anti(&clauses, join_vars)?; self.push_anti(step); } + WhereClause::Or(branches) => self.union(&branches, None)?, + WhereClause::OrJoin { + join_vars, + branches, + } => self.union(&branches, Some(join_vars))?, _ => return None, } Some(()) @@ -496,7 +523,7 @@ impl Builder { } /// The `AntiJoin` of `body`, whose variables `vars` the outer row gives - /// where it binds them (spec §2), hashed or correlated (spec §4.4). + /// where it binds them (spec §2). fn anti(&self, body: &[WhereClause], vars: Vec) -> Option { if !body .iter() @@ -504,13 +531,91 @@ impl Builder { { return None; } + Some(Step::Anti(self.sub(body, vars)?.0)) + } + + /// The `Union` and `Distinct` of an `or` (`join` is `None`) or an + /// `or-join` (spec §5). + fn union(&mut self, branches: &[Vec], join: Option>) -> Option<()> { + if self.source.is_none() { + // Nothing before the `or` binds a variable: its outer side is + // the empty row. + self.source = Some(Source::Seed); + self.steps.append(&mut self.front); + } + let mut subs = Vec::with_capacity(branches.len()); + for branch in branches { + let vars: Vec = match &join { + // The parser requires every join variable bound before + // (INT-031 on the executor otherwise). + Some(j) if j.iter().all(|v| self.slots.by_var.contains_key(v)) => j.clone(), + Some(_) => return None, + None => optimizer::clause_ref_vars(branch).into_iter().collect(), + }; + let imports: HashSet = vars + .iter() + .filter(|v| self.slots.by_var.contains_key(*v)) + .cloned() + .collect(); + if !runs_branch(branch, &imports) { + return None; + } + subs.push(self.sub(branch, vars)?); + } + // The variables a branch binds that the rows do not. Every branch of + // an `or` binds the same (PRS-057), but their sources' hidden + // variables differ; the executor keeps those, so such an `or` stays + // there. An `or-join` keeps none. + let mut names: Vec = Vec::new(); + if join.is_none() { + for (k, (_, slots)) in subs.iter().enumerate() { + let mut own: Vec = slots + .by_var + .keys() + .filter(|v| !self.slots.by_var.contains_key(*v)) + .cloned() + .collect(); + own.sort(); + if k == 0 { + names = own; + } else if own != names { + return None; + } + } + } + let mut arms = Vec::with_capacity(subs.len()); + let mut kinds = vec![0u8; names.len()]; + for (body, slots) in subs { + let mut new = Vec::with_capacity(names.len()); + for (n, kind) in names.iter().zip(kinds.iter_mut()) { + let inner = *slots.by_var.get(n)?; + *kind |= slots.kind(inner); + new.push(inner); + } + arms.push(Branch { body, new }); + } + for (n, kind) in names.into_iter().zip(kinds) { + let s = self.slots.add(kind); + self.slots.by_var.insert(n, s); + } + self.steps.push(Step::Union(arms)); + let mut slots: Vec = self.slots.by_var.values().copied().collect(); + slots.sort_unstable(); + self.steps.push(Step::Distinct(slots)); + Some(()) + } + + /// The plan of a `not` body or an `or` branch whose variables `vars` + /// the outer row gives where it binds them (spec §2), hashed or + /// correlated (spec §4.4), and its slots. + fn sub(&self, body: &[WhereClause], vars: Vec) -> Option<(Body, Slots)> { let mut imports: Vec<(String, usize)> = vars .into_iter() .filter_map(|v| self.slots.by_var.get(&v).map(|&s| (v, s))) .collect(); imports.sort_by_key(|&(_, s)| s); let seeded: HashSet = imports.iter().map(|(v, _)| v.clone()).collect(); - let (seeded_order, _) = optimizer::plan_seeded(body.to_vec(), &seeded); + let (seeded_order, seeded_deferred) = optimizer::plan_seeded(body.to_vec(), &seeded); // A probe per outer row holds nothing: correlated when the first // pattern's entity is imported. let probe = seeded_order @@ -521,7 +626,7 @@ impl Builder { }) .and_then(|p| p.entity.as_variable()) .is_some_and(|e| seeded.contains(e)); - let hashable = closed(body); + let hashable = closed(body, &seeded); let hash = match optimizer::subplans() { optimizer::Subplans::Choose => hashable && !probe, optimizer::Subplans::Hash => hashable, @@ -530,7 +635,11 @@ impl Builder { let (as_of, valid) = (self.as_of, self.valid); if hash { let mut b = Builder::new(None, as_of, valid); - for (c, _) in optimizer::plan(body.to_vec()).0 { + let (planned, deferred) = optimizer::plan(body.to_vec()); + for (c, _) in planned { + b.clause(c)?; + } + for c in sorted(deferred) { b.clause(c)?; } let keys = imports @@ -546,10 +655,9 @@ impl Builder { }) }) .collect(); - return Some(Step::Anti(Body::Hashed { - plan: Box::new(b.finish()?), - keys, - })); + let slots = std::mem::take(&mut b.slots); + let plan = Box::new(b.finish()?); + return Some((Body::Hashed { plan, keys }, slots)); } let mut b = Builder::new(None, as_of, valid); for (v, outer) in &imports { @@ -560,23 +668,74 @@ impl Builder { for (c, _) in seeded_order { b.clause(c)?; } - Some(Step::Anti(Body::Correlated { - plan: Box::new(b.finish()?), - imports: imports.into_iter().map(|(_, s)| s).collect(), - })) + for c in sorted(seeded_deferred) { + b.clause(c)?; + } + let slots = std::mem::take(&mut b.slots); + let plan = Box::new(b.finish()?); + Some(( + Body::Correlated { + plan, + imports: imports.into_iter().map(|(_, s)| s).collect(), + }, + slots, + )) } } +/// Deferred `not`s, cheapest first when reordering, as on the executor. +fn sorted(mut deferred: Vec) -> Vec { + if optimizer::reorder() { + deferred.sort_by_key(optimizer::clause_cost); + } + deferred +} + +/// Whether the engine runs `branch` of an `or` whose rows give `imports` +/// (decision 11 of the #546 plan). It holds patterns, expressions and +/// `not`s only (a rule invocation or a nested `or` stays on the executor), +/// and no predicate the registry may lack: the executor reports that only +/// when a row reaches it. The executor applies a branch's `not`s before its +/// expressions, so a `not` must not read a variable only an expression of +/// the branch binds. +fn runs_branch(branch: &[WhereClause], imports: &HashSet) -> bool { + let mut by_pattern: HashSet = imports.clone(); + let mut by_expr: HashSet<&str> = HashSet::new(); + for c in branch { + match c { + WhereClause::Pattern(p) => by_pattern.extend(optimizer::pattern_bound_vars(p)), + WhereClause::Expr { + expr: Expr::UnaryOp(UnaryOp::Udf(_), _), + .. + } => return false, + WhereClause::Expr { binding, .. } => by_expr.extend(binding.as_deref()), + WhereClause::Not(_) | WhereClause::NotJoin { .. } => {} + _ => return false, + } + } + branch.iter().all(|c| { + let reads: Vec = match c { + WhereClause::Not(body) => optimizer::clause_ref_vars(body).into_iter().collect(), + WhereClause::NotJoin { join_vars, .. } => join_vars.clone(), + _ => return true, + }; + reads + .iter() + .all(|v| by_pattern.contains(v) || !by_expr.contains(v.as_str())) + }) +} + /// Whether `p` is a per-fact pseudo-attribute pattern (it scans nothing). fn per_fact(p: &Pattern) -> bool { matches!(&p.attribute, AttributeSpec::Pseudo(a) if a.is_per_fact()) } /// Whether `body` has the same rows for every outer row (spec §2): it has a -/// pattern to scan, and every variable its expressions and per-fact -/// pseudo-attributes read is bound by one of its other patterns (decision 6 -/// of the #546 plan). -fn closed(body: &[WhereClause]) -> bool { +/// pattern to scan, every variable its expressions and per-fact +/// pseudo-attributes read is bound by one of its other patterns, and every +/// variable of `imports` a nested `not` reads is too (decision 6 of the #546 +/// plan). +fn closed(body: &[WhereClause], imports: &HashSet) -> bool { let bound: HashSet = body .iter() .filter_map(|c| match c { @@ -596,6 +755,12 @@ fn closed(body: &[WhereClause]) -> bool { .as_ref() .and_then(EdnValue::as_variable) .is_some_and(|v| bound.contains(v)), + WhereClause::Not(inner) => optimizer::clause_ref_vars(inner) + .iter() + .all(|v| !imports.contains(v) || bound.contains(v)), + WhereClause::NotJoin { join_vars, .. } => join_vars + .iter() + .all(|v| !imports.contains(v) || bound.contains(v)), _ => true, }) } diff --git a/src/query/engine/seed.rs b/src/query/engine/seed.rs index c3530db28e..5479ba11f9 100644 --- a/src/query/engine/seed.rs +++ b/src/query/engine/seed.rs @@ -1,5 +1,6 @@ //! `Seed` (#546): the one row a correlated body starts from, the cells it -//! imports from the outer row. +//! imports from the outer row; or the empty row an `or` extends when nothing +//! runs before it. use super::batch::Batch; use super::cell::Cell; @@ -14,11 +15,12 @@ pub(crate) struct Seed { } impl Seed { - /// A seed with no row until the first rewind. + /// A seed of the empty row, until a rewind gives it another (#546: a + /// query whose first clause to run is an `or` starts from it). pub(crate) fn new() -> Self { Seed { row: Vec::new(), - done: true, + done: false, counters: Counters::new("Seed"), } } diff --git a/src/query/engine/tests.rs b/src/query/engine/tests.rs index c007afd441..937dc4ea53 100644 --- a/src/query/engine/tests.rs +++ b/src/query/engine/tests.rs @@ -993,9 +993,8 @@ fn planner_chooses_the_body_form() { assert_eq!(forms(constant), ["correlated"]); } -/// Which negations the engine runs (#546 PR 1): every `not` / `not-join` -/// without a rule invocation; a query with `or` stays on the executor -/// until PR 2. +/// Which negations the engine runs (#546): every `not` / `not-join` +/// without a rule invocation. #[test] fn negation_routing() { let db = Minigraf::in_memory().unwrap(); @@ -1009,10 +1008,7 @@ fn negation_routing() { ] { rows(&db, q); } - for q in [ - "(query [:find ?e :where [?e :person/name ?n] (not (okay ?e))])", - "(query [:find ?e :where [?e :person/name ?n] (or [?e :person/ok true] [?e :person/age 21])])", - ] { + for q in ["(query [:find ?e :where [?e :person/name ?n] (not (okay ?e))])"] { let before = runs(); db.execute(q).unwrap(); assert_eq!(runs(), before, "query stayed on the executor"); @@ -1088,3 +1084,325 @@ fn negation_bodies_run_per_row_or_once() { let read: u64 = c.iter().filter(|c| c.op == "Scan").map(|c| c.rows_in).sum(); assert!(read <= 150, "the body is read once"); } + +/// `or` / `or-join` shapes (#546 PR 2), as `(find, clauses)`: branches +/// probed and keyed, new variables, keywords meeting refs, attributes, floats +/// and long strings as keys, branches reading outer variables, metadata and +/// the valid time, a branch with `not`, branches naming different outer +/// variables or no join variable, an `or` with nothing before it, a cross +/// product, deferred `not`s and expressions after an `or`. +fn disjunctions() -> Vec<(&'static str, &'static str)> { + vec![ + // Correlated: the branch's entity is imported. + ( + "?e ?n", + "[?e :person/name ?n] (or [?e :person/ok true] [?e :person/age 21])", + ), + ( + "?e ?x", + "[?e :person/name ?n] (or [?e :person/age ?x] [?e :person/score ?x])", + ), + ( + "?e", + "[?e :person/friend ?f] (or [?f :person/ok true] [?f :person/status :s1])", + ), + // Hashed: keyed on a value, a ref, an attribute, a float, a long + // string. + ( + "?e ?f", + "[?e :person/age ?a] (or [?f :person/age ?a] [?f :person/score ?a])", + ), + ( + "?e", + "[?e :person/age ?a] (or-join [?a] (and [?f :person/age ?a] [?f :person/ok true]) [?f :person/score ?a])", + ), + ( + "?e ?b", + "[?e :person/boss ?b] (or-join [?b] [?x :person/friend ?b] [?x :person/self ?b])", + ), + ( + "?e", + "[?e :person/alias ?b] (or-join [?b] [?x :person/boss ?b] [?x :person/friend ?b])", + ), + ( + "?e ?x", + "[?e :person/attr ?x] (or-join [?x] [:p1 ?x 21] [:p2 ?x 22])", + ), + ( + "?e ?s", + "[?e :person/score ?s] (or-join [?s] [?f :person/score ?s] [?f :person/age ?s])", + ), + ( + "?e", + "[?e :person/bio ?b] (or-join [?b] (and [?f :person/bio ?b] [?f :person/ok true]) [?f :person/name ?b])", + ), + // A branch reading an outer variable it does not bind. + ( + "?e", + "[?e :person/age ?a] (or [(> ?a 21)] [?e :person/ok true])", + ), + ( + "?e", + "[?e :person/age ?a] (or-join [?a] (and [?f :person/age ?b] [(< ?b ?a)]) [?f :person/score ?a])", + ), + // A branch with `not`. + ( + "?e ?a", + "[?e :person/name ?n] (or (and [?e :person/age ?a] (not [?e :person/ok true])) [?e :person/score ?a])", + ), + ( + "?e", + "[?e :person/age ?a] (or-join [?a] (and [?f :person/age ?a] (not-join [?f] [?f :person/ok true])) [?f :person/score ?a])", + ), + // Branches naming different outer variables; a branch binding no + // join variable. + ( + "?e ?f", + "[?e :person/friend ?f] (or [?e :person/ok true] [?f :person/ok false])", + ), + ( + "?e", + "[?e :person/name ?n] (or-join [?e] [?x :person/age 23] [?e :person/ok true])", + ), + // Nothing before the `or`; a cross product. + ("?e", "(or [?e :person/ok true] [?e :person/age 21])"), + ( + "?e ?f", + "[?e :person/ok true] (or [?f :person/age 21] [?f :person/age 22])", + ), + // Metadata of an outer source, and the valid time. + ( + "?e", + "[?e :person/name ?n] (or-join [?e] (and [?e :db/tx-count ?t] [(> ?t 3)]) [?e :person/ok true])", + ), + ( + "?e ?t", + "[?e :person/name ?n] (or [?e :db/valid-at ?t] [?e :person/age ?t])", + ), + // A `not` and an expression on what the `or` binds; two `or`s. + ( + "?e ?a", + "[?e :person/name ?n] (or [?e :person/age ?a] [?e :person/score ?a]) (not-join [?a] [?f :person/age ?a] [?f :person/ok true])", + ), + ( + "?e ?a", + "[?e :person/name ?n] (or [?e :person/age ?a] [?e :person/score ?a]) [(> ?a 0)]", + ), + ( + "?e", + "[?e :person/name ?n] (or [?e :person/ok true] [?e :person/age 21]) (or-join [?e] [?e :person/status :s0] [?e :person/status :s2])", + ), + // Duplicate outer rows collapse. + ( + "?e", + "[?e :person/friend ?f] [?g :person/friend ?f] (or [?e :person/ok true] [?e :person/ok false])", + ), + ] +} + +fn disjunction_queries(tx: u64) -> Vec { + let mut out = Vec::new(); + for (find, clauses) in disjunctions() { + for temporal in temporals(tx) { + // Per-fact metadata needs `:any-valid-time` (INT-026). + if clauses.contains(":db/tx-count") && !temporal.contains(":any-valid-time") { + continue; + } + out.push(format!( + "(query [:find {find} {temporal} :where {clauses}])" + )); + } + } + out +} + +/// Every disjunction shape with each branch form forced and reordering on +/// and off; the oracle compares each run with the executor. +fn check_disjunctions(db: &Minigraf) -> usize { + use crate::query::datalog::optimizer::{Subplans, set_reorder, set_subplans}; + let tx = db.current_tx_count(); + let mut total = 0; + for mode in [Subplans::Choose, Subplans::Hash, Subplans::Correlated] { + for on in [true, false] { + let _m = set_subplans(mode); + let _r = set_reorder(on); + total += disjunction_queries(tx) + .iter() + .map(|q| rows(db, q)) + .sum::(); + } + } + total +} + +#[test] +fn disjunction_matches_executor() { + let dir = tempfile::tempdir().unwrap(); + let mem = Minigraf::in_memory().unwrap(); + let file = Minigraf::open(dir.path().join("or.graph")).unwrap(); + for round in 0..3 { + write_round(&mem, round); + assert!(check_disjunctions(&mem) > 0, "disjunctions return rows"); + write_round(&file, round); + check_disjunctions(&file); + file.checkpoint().unwrap(); + check_disjunctions(&file); + } +} + +/// Which disjunctions the engine runs (#546 PR 2): `or` / `or-join` whose +/// branches hold patterns, expressions and `not`s; a rule invocation, a +/// nested `or`, a predicate the registry may lack, an `or` whose branches +/// bind their own sources' metadata, and a branch `not` reading what only +/// the branch's expression binds stay on the executor (decision 11). +#[test] +fn disjunction_routing() { + let db = Minigraf::in_memory().unwrap(); + write_round(&db, 0); + db.execute("(rule [(okay ?e) [?e :person/ok true]])") + .unwrap(); + for q in [ + "(query [:find ?e :where [?e :person/name ?n] (or [?e :person/ok true] [?e :person/age 21])])", + "(query [:find ?e :where (or [?e :person/ok true] [?e :person/age 21])])", + "(query [:find ?e :where [?e :person/name ?n] (or (and [?e :person/ok true] (not [?e :person/age 21])) [?e :person/age 22])])", + "(query [:find ?e :any-valid-time :where [?e :person/name ?n] (or-join [?e] (and [?f :person/age ?a] [?f :db/tx-count ?t]) [?e :person/ok true])])", + ] { + rows(&db, q); + } + for q in [ + "(query [:find ?e :where [?e :person/name ?n] (or (okay ?e) [?e :person/age 21])])", + "(query [:find ?e :where [?e :person/name ?n] (or (or [?e :person/ok true] [?e :person/age 22]) [?e :person/age 21])])", + "(query [:find ?e :where [?e :person/age ?a] (or (and [?e :person/ok true] [(no-such-pred? ?a)]) [?e :person/age 21])])", + "(query [:find ?e :any-valid-time :where [?e :person/name ?n] (or (and [?e :person/age ?a] [?e :db/tx-count ?t]) (and [?e :person/score ?a] [?e :db/tx-id ?t]))])", + "(query [:find ?e :where [?e :person/age ?a] (or (and [(+ ?a 1) ?b] (not [?f :person/age ?b])) (and [(+ ?a 2) ?b] [?e :person/ok true]))])", + ] { + let before = runs(); + let _ = db.execute(q); + assert_eq!(runs(), before, "query stayed on the executor"); + } +} + +/// The branch forms the planner chooses: as a `not` body's (spec §4.4, +/// §5.1), with a branch's `not` reading an imported variable the branch's +/// patterns do not bind keeping it correlated. +#[test] +fn planner_chooses_the_branch_form() { + use super::plan::{Body, Step, plan}; + use crate::query::datalog::parser::parse_datalog_command; + use crate::query::datalog::types::DatalogCommand; + let forms = |q: &str| -> Vec<&'static str> { + let Ok(DatalogCommand::Query(query)) = parse_datalog_command(q) else { + panic!("expected a query"); + }; + let plan = plan(&query).expect("an engine plan"); + plan.steps + .iter() + .flat_map(|s| match s { + Step::Union(branches) => branches + .iter() + .map(|b| match b.body { + Body::Hashed { .. } => "hashed", + Body::Correlated { .. } => "correlated", + }) + .collect(), + _ => Vec::new(), + }) + .collect() + }; + assert_eq!( + forms("(query [:find ?e :where [?e :a ?x] (or-join [?e ?x] [?e :b 1] [?f :c ?x])])"), + ["correlated", "hashed"] + ); + assert_eq!( + forms( + "(query [:find ?e :where [?e :a ?x] (or-join [?x] [?f :b ?x] (and [?f :c ?y] [(< ?y ?x)]))])" + ), + ["hashed", "correlated"] + ); + assert_eq!( + forms( + "(query [:find ?e :where [?e :a ?x] (or-join [?x] (and [?f :b ?x] (not [?f :c 1])) (and [?f :b ?y] (not [?f :c ?x])))])" + ), + ["hashed", "correlated"] + ); + assert_eq!( + forms("(query [:find ?e :where (or [?e :b 1] [?e :c 2])])"), + ["hashed", "hashed"] + ); +} + +/// `Distinct` after `Union` collapses equal rows, as the executor's `or` +/// does, and keeps rows that differ only in a variable `:find` leaves out; +/// `-0.0` equals `0.0`, a keyword never equals a ref. +#[test] +fn disjunction_rows_are_distinct() { + let db = Minigraf::in_memory().unwrap(); + db.execute( + "(transact [[:a :n 1] [:a :m 1] [:a :k :b] [:a :k #uuid \"8bd6a0fe-0f33-5b3c-a8c4-0b5ba4ea0d42\"] \ + [:z :f 0.0] [:z :f -0.0] [:y :f 0.0]])", + ) + .unwrap(); + // Both branches give `:a`: one row. + assert_eq!( + rows( + &db, + "(query [:find ?e :where [?e :n _] (or [?e :n 1] [?e :m 1])])" + ), + 1 + ); + // Rows differing in `?k` (a keyword and a ref) are two rows. + assert_eq!( + rows( + &db, + "(query [:find ?e :where [?e :k ?k] (or [?e :n 1] [?e :m 1])])" + ), + 2 + ); + // `-0.0` and `0.0`: `:z` has two facts but one row per `?f` value. + assert_eq!( + rows( + &db, + "(query [:find ?e ?f :where [?e :f ?f] (or [?e :f 0.0] [?e :f 1.0])])" + ), + 2 + ); +} + +/// A correlated branch runs per outer row from its seed; a hashed one is +/// read once (#546 spec §5.1); with no new variable an outer row is +/// returned once, from the first branch that has a row. +#[test] +fn disjunction_branches_run_per_row_or_once() { + let db = Minigraf::in_memory().unwrap(); + let facts: String = (0..50) + .map(|i| format!("[:e{i} :n {i}] [:e{i} :tag :t{}]", i % 5)) + .collect(); + db.execute(&format!("(transact [{facts}])")).unwrap(); + let ops = |q: &str| { + // One pull reads every outer row: there are fewer than a batch. + let mut cursor = db.query(q).unwrap(); + cursor.next_batch(1).unwrap().expect("a row"); + cursor.counters() + }; + let c = ops("(query [:find ?e :where [?e :n ?v] (or [?e :tag :t0] [?e :tag :t1])])"); + let union = c.iter().find(|c| c.op == "Union").expect("a Union"); + assert_eq!(union.rows_in, 50); + assert_eq!(union.rows_out, 20); + assert_eq!( + c.iter() + .filter(|c| c.op == "Seed") + .map(|c| c.rows_out) + .sum::(), + 50 + 40, + "the second branch runs only for rows the first did not match" + ); + + let c = ops( + "(query [:find ?e :where [?e :n ?v] (or-join [?v] (and [?f :n ?v] [?f :tag :t0]) (and [?f :n ?v] [?f :tag :t1]))])", + ); + assert!(!c.iter().any(|c| c.op == "Seed"), "hashed: no seed"); + let union = c.iter().find(|c| c.op == "Union").expect("a Union"); + assert_eq!(union.rows_out, 20); + let read: u64 = c.iter().filter(|c| c.op == "Scan").map(|c| c.rows_in).sum(); + assert!(read <= 250, "each branch is read once"); +} diff --git a/src/query/engine/union.rs b/src/query/engine/union.rs new file mode 100644 index 0000000000..1d6e4dbefe --- /dev/null +++ b/src/query/engine/union.rs @@ -0,0 +1,301 @@ +//! `Union` (#546 spec §5.1): `or` and `or-join`. Each outer row, once per row +//! of each branch, extended by the branch's cells of the new variables; a +//! [`Distinct`](super::distinct::Distinct) follows. With no new variable (an +//! `or-join`, or an `or` whose branches bind nothing new) those rows would +//! all equal the outer row, so it is returned once, when some branch has a +//! row. +//! +//! A branch is planned as a `not` body is (decision 4 of the #546 plan): a +//! correlated branch runs once per outer row from a +//! [`Seed`](super::seed::Seed) of the cells it imports; a hashed one runs +//! once, into a table of its rows' new cells by their keys (their cells of +//! the imported variables, as [`JoinKey`]s). + +use super::batch::Batch; +use super::cell::{Cell, JoinKey}; +use super::plan::{Body as Spec, Branch, Key}; +use super::{BATCH_ROWS, Counters, Ctx, Operator, build}; +use anyhow::Result; +use std::collections::HashMap; + +pub(crate) struct Union { + outer: Box, + arms: Vec, + /// Number of new slots. + width: usize, + /// The outer batch being extended. + at: Option, + /// `rows_in` counts the outer rows received. + counters: Counters, +} + +/// Where `Union` is in an outer batch. +struct At { + batch: Batch, + /// The next row whose branch rows are not computed. + next: usize, + /// The row `rows` extend, and the next of them to return. + row: usize, + rows: Vec>, + done: usize, +} + +struct Arm { + body: Body, + /// The body slots of the new cells. + new: Vec, +} + +enum Body { + Correlated { + root: Box, + imports: Vec, + seed: Vec, + }, + Hashed { + root: Box, + keys: Vec, + /// Built on the first pull, then kept: the branch does not depend on + /// the outer row, so a rewind keeps it too. + table: Option, Vec>>>, + }, +} + +impl Union { + pub(crate) fn new(outer: Box, branches: Vec) -> Self { + let width = branches.first().map_or(0, |b| b.new.len()); + let arms = branches + .into_iter() + .map(|Branch { body, new }| Arm { + body: match body { + Spec::Correlated { plan, imports } => Body::Correlated { + root: build(plan.source, plan.steps), + imports, + seed: Vec::new(), + }, + Spec::Hashed { plan, keys } => Body::Hashed { + root: build(plan.source, plan.steps), + keys, + table: None, + }, + }, + new, + }) + .collect(); + Union { + outer, + arms, + width, + at: None, + counters: Counters::new("Union"), + } + } +} + +/// The cell of row `i` in `slot`. +fn cell(batch: &Batch, slot: usize, i: usize) -> Option<&Cell> { + batch.cols.get(slot).and_then(|c| c.get(i)) +} + +impl Arm { + /// Append the new cells of the branch's rows for row `i` of `batch` to + /// `out`; with `one`, at most one row. + fn rows( + &mut self, + batch: &Batch, + i: usize, + one: bool, + out: &mut Vec>, + ctx: &mut Ctx<'_>, + ) -> Result<()> { + let new = &self.new; + match &mut self.body { + Body::Correlated { + root, + imports, + seed, + } => { + seed.clear(); + for &slot in imports.iter() { + // Every imported slot is filled. + if let Some(c) = cell(batch, slot, i) { + seed.push(c.clone()); + } + } + root.rewind(seed); + 'pull: while let Some(b) = root.next_batch(ctx)? { + for j in 0..b.len { + out.push( + new.iter() + .filter_map(|&s| cell(&b, s, j).cloned()) + .collect(), + ); + if one { + break 'pull; + } + } + } + root.close(); + } + Body::Hashed { root, keys, table } => { + if table.is_none() { + *table = Some(collect(root.as_mut(), keys, new, one, ctx)?); + } + let Some(table) = table else { + return Ok(()); + }; + let mut key = Vec::with_capacity(keys.len()); + for k in keys.iter() { + let Some(c) = cell(batch, k.outer, i) else { + return Ok(()); + }; + // A NaN equals nothing a branch row holds. + let Some(j) = JoinKey::of(c, k.normalise, ctx)? else { + return Ok(()); + }; + key.push(j); + } + if let Some(rows) = table.get(&key) { + match rows.first() { + Some(r) if one => out.push(r.clone()), + _ => out.extend(rows.iter().cloned()), + } + } + } + } + Ok(()) + } + + fn root(&self) -> &dyn Operator { + match &self.body { + Body::Correlated { root, .. } | Body::Hashed { root, .. } => root.as_ref(), + } + } + + fn root_mut(&mut self) -> &mut dyn Operator { + match &mut self.body { + Body::Correlated { root, .. } | Body::Hashed { root, .. } => root.as_mut(), + } + } +} + +/// Every row of a hashed branch: its new cells by the keys of `keys`' inner +/// slots. With `one`, one row per key. +fn collect( + root: &mut dyn Operator, + keys: &[Key], + new: &[usize], + one: bool, + ctx: &mut Ctx<'_>, +) -> Result, Vec>>> { + let mut table: HashMap, Vec>> = HashMap::new(); + while let Some(b) = root.next_batch(ctx)? { + 'row: for i in 0..b.len { + let mut key = Vec::with_capacity(keys.len()); + for k in keys { + let Some(c) = cell(&b, k.inner, i) else { + continue 'row; + }; + // A row with a NaN key equals no outer row. + let Some(j) = JoinKey::of(c, k.normalise, ctx)? else { + continue 'row; + }; + key.push(j); + } + let rows = table.entry(key).or_default(); + if !one || rows.is_empty() { + rows.push( + new.iter() + .filter_map(|&s| cell(&b, s, i).cloned()) + .collect(), + ); + } + } + } + root.close(); + Ok(table) +} + +impl Operator for Union { + fn next_batch(&mut self, ctx: &mut Ctx<'_>) -> Result> { + let one = self.width == 0; + let mut out: Option = None; + loop { + if self.at.is_none() { + let Some(batch) = self.outer.next_batch(ctx)? else { + break; + }; + self.counters.rows_in += batch.len as u64; + self.at = Some(At { + batch, + next: 0, + row: 0, + rows: Vec::new(), + done: 0, + }); + } + let Some(at) = self.at.as_mut() else { + break; + }; + let out = out.get_or_insert_with(|| Batch::new(at.batch.cols.len() + self.width)); + while at.done < at.rows.len() && out.len < BATCH_ROWS { + let mut row: Vec> = at + .batch + .cols + .iter() + .map(|c| c.get(at.row).cloned()) + .collect(); + if let Some(new) = at.rows.get(at.done) { + row.extend(new.iter().cloned().map(Some)); + } + out.push(&mut row); + at.done += 1; + } + if out.len >= BATCH_ROWS { + break; + } + if at.next >= at.batch.len { + self.at = None; + continue; + } + at.row = at.next; + at.next += 1; + at.rows.clear(); + at.done = 0; + for arm in &mut self.arms { + arm.rows(&at.batch, at.row, one, &mut at.rows, ctx)?; + if one && !at.rows.is_empty() { + break; + } + } + } + match out { + Some(b) if b.len > 0 => { + self.counters.out(&b); + Ok(Some(b)) + } + _ => Ok(None), + } + } + + fn rewind(&mut self, seed: &[Cell]) { + self.at = None; + self.outer.rewind(seed); + } + + fn close(&mut self) { + self.at = None; + self.outer.close(); + for arm in &mut self.arms { + arm.root_mut().close(); + } + } + + fn counters(&self, out: &mut Vec) { + out.push(self.counters); + for arm in &self.arms { + arm.root().counters(out); + } + self.outer.counters(out); + } +} diff --git a/tests/or_equality_test.rs b/tests/or_equality_test.rs new file mode 100644 index 0000000000..902d494648 --- /dev/null +++ b/tests/or_equality_test.rs @@ -0,0 +1,188 @@ +//! An `or` / `or-join` branch row meets the outer row by join equality (#546, +//! design `docs/superpowers/specs/2026-10-16-negation-disjunction-engine-design.md` +//! §3.5, §3.6 item 3, §5.3): a keyword equal to a ref to the entity it names, +//! floats by IEEE `==`. Before, the path that evaluates branches unseeded and +//! hash-joins their rows compared exact `Value`s, so a keyword never met a ref, +//! while the seeded path (a branch with `not`) matched them: the answer +//! depended on whether a branch held a `not`. +#![cfg(not(target_arch = "wasm32"))] + +use minigraf::{Minigraf, OpenOptions, QueryResult, Value}; + +fn executed(db: &Minigraf, q: &str) -> Vec> { + match db.execute(&format!("(query {q})")).expect("query") { + QueryResult::QueryResults { results, .. } => results, + _ => panic!("expected QueryResults"), + } +} + +fn pulled(db: &Minigraf, q: &str) -> Vec> { + let mut cursor = db.query(&format!("(query {q})")).expect("query"); + let mut rows = Vec::new(); + while let Some(batch) = cursor.next_batch(3).expect("batch") { + rows.extend(batch.rows().iter().cloned()); + } + rows +} + +/// The entity a keyword names, as `edn_to_entity_id` derives it. +fn named(k: &str) -> uuid::Uuid { + uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, k.as_bytes()) +} + +/// Each row of `q` as text (`:k` for a ref to the entity `:k` names, the +/// value otherwise), through `execute` and a cursor (which must agree), sorted. +fn rows(db: &Minigraf, q: &str, names: &[&str]) -> Vec { + let cell = |v: &Value| -> String { + match v { + Value::Ref(u) => names + .iter() + .find(|k| *u == named(k)) + .map_or_else(|| "?".to_string(), |k| k.to_string()), + Value::Keyword(k) => format!("kw{k}"), + Value::String(s) => s.clone(), + Value::Integer(i) => i.to_string(), + _ => "other".to_string(), + } + }; + let text = |rs: Vec>| -> Vec { + let mut t: Vec = rs + .iter() + .map(|r| r.iter().map(cell).collect::>().join(" ")) + .collect(); + t.sort(); + t + }; + let a = text(executed(db, q)); + assert_eq!(a, text(pulled(db, q)), "execute and cursor agree"); + a +} + +const NAMES: &[&str] = &[":alice", ":bob", ":carol", ":dave"]; + +/// `:alice`'s friend is the keyword `:bob`, `:carol`'s the keyword `:dave`. +/// `:bob` has a name, `:dave` an alias. +const PEOPLE: &str = "(transact [[:alice :friend :bob] [:bob :name \"B\"] \ + [:dave :alias \"D\"] [:carol :friend :dave] [:x :blocked true]])"; + +fn people(db: &Minigraf) { + db.execute(PEOPLE).unwrap(); +} + +/// Each query with the rows it returns: the outer `?f` is a keyword, the +/// branch's `?f` an entity (a ref). `?f` keeps the outer row's cell. +const CASES: &[(&str, &[&str])] = &[ + // The unseeded path. + ( + "[:find ?e ?n :where [?e :friend ?f] (or [?f :name ?n] [?f :alias ?n])]", + &[":alice B", ":carol D"], + ), + ( + "[:find ?e ?f :where [?e :friend ?f] (or [?f :name _] [?f :alias _])]", + &[":alice kw:bob", ":carol kw:dave"], + ), + ( + "[:find ?e :where [?e :friend ?f] (or-join [?f] [?f :name _] [?f :alias _])]", + &[":alice", ":carol"], + ), + // The seeded path: a branch holds a `not`. + ( + "[:find ?e ?n :where [?e :friend ?f] \ + (or (and [?f :name ?n] (not [:x :blocked false])) [?f :alias ?n])]", + &[":alice B", ":carol D"], + ), + // The per-row `or-join` path: a branch's expression reads `?f`. + ( + "[:find ?e :where [?e :friend ?f] \ + (or-join [?f] (and [?f :name ?n] [(!= ?f \"none\")]) [?f :alias _])]", + &[":alice", ":carol"], + ), +]; + +fn check(db: &Minigraf) { + for (q, want) in CASES { + assert_eq!(rows(db, q, NAMES), want.to_vec(), "{q}"); + } +} + +#[test] +fn branch_ref_meets_outer_keyword() { + let db = Minigraf::in_memory().unwrap(); + people(&db); + check(&db); +} + +#[test] +fn branch_ref_meets_outer_keyword_after_checkpoint() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("or.graph"); + { + let db = Minigraf::open(&path).unwrap(); + people(&db); + db.checkpoint().unwrap(); + } + let db = OpenOptions::new().path(&path).open().unwrap(); + check(&db); +} + +#[test] +fn branch_float_meets_outer_float_by_ieee_equality() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:a :x 0.0] [:b :x 0.00000000000000000001] [:g :y -0.0]])") + .unwrap(); + for q in [ + "[:find ?e :where [?e :x ?f] (or [?g :y ?f] [?g :z ?f])]", + "[:find ?e :where [?e :x ?f] (or-join [?f] [?g :y ?f] [?g :z ?f])]", + ] { + assert_eq!(rows(&db, q, &[":a", ":b"]), vec![":a"], "{q}"); + } +} + +#[test] +fn branches_naming_different_outer_variables() { + // The unseeded path keyed every branch row on the outer variables any + // branch names, so a row of a branch naming only some of them met no + // outer row; the seeded path (a branch with `not`) matched it (#546). + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:p :link :q] [:p :a 1] [:q :b 2]])") + .unwrap(); + for q in [ + "[:find ?e ?f ?x :where [?e :link ?f] (or [?e :a ?x] [?f :b ?x])]", + "[:find ?e ?f ?x :where [?e :link ?f] \ + (or (and [?e :a ?x] (not [?e :zz 1])) [?f :b ?x])]", + ] { + assert_eq!( + rows(&db, q, &[":p", ":q"]), + vec![":p kw:q 1", ":p kw:q 2"], + "{q}" + ); + } +} + +#[test] +fn or_join_branch_without_a_join_variable() { + // A branch that does not bind `?e` constrains nothing about it: it + // matches every outer row when it has a row. The joined path dropped its + // rows; the per-row path (taken for a branch reading outer metadata or + // an outer variable in an expression) kept them (#546). + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:p :n 1] [:q :n 1] [:q :zz 2] [:r :a 1]])") + .unwrap(); + let names = &[":p", ":q"]; + for (q, want) in [ + ( + "[:find ?e :where [?e :n _] (or-join [?e] [?x :a 1] [?e :zz 9])]", + vec![":p", ":q"], + ), + ( + "[:find ?e :where [?e :n _] (or-join [?e] (and [?x :a 1] (not [?e :zz 2])) [?e :zz 9])]", + vec![":p"], + ), + ( + "[:find ?e :where [?e :n _] (or-join [?e] [?x :b 1] [?e :zz 9])]", + vec![], + ), + ] { + assert_eq!(rows(&db, q, names), want, "{q}"); + } +} diff --git a/tests/plan_independence_test.rs b/tests/plan_independence_test.rs index 5e27042c01..410262c1c5 100644 --- a/tests/plan_independence_test.rs +++ b/tests/plan_independence_test.rs @@ -178,6 +178,25 @@ const MATRIX: &[&str] = &[ r#"[:find ?n :where [?e :name ?n] (not-join [?e] [?x :age 25])]"#, r#"[:find ?n :valid-at "2030-01-01T00:00:00Z" :where [?e :name ?n] (not-join [?e] [?e :db/valid-at ?t] [(> ?t 0)])]"#, r#"[:find ?n :valid-at "2030-01-01T00:00:00Z" :where [?e :name ?n] (not-join [?e] [?e :db/valid-at ?t])]"#, + // #546: `or` / `or-join` by join equality (a keyword meets a ref to the + // entity it names; floats by IEEE `==`), branches naming different outer + // variables or no join variable, a branch with `not`, an `or` with + // nothing before it, a cross product, and what follows an `or`. + r#"[:find ?a ?n :where [?a :friend ?b] (or [?b :name ?n] [?b :motto ?n])]"#, + r#"[:find ?a :where [?a :friend ?b] (or-join [?b] [?b :age 40] [?b :motto _])]"#, + r#"[:find ?a :where [?a :friend ?b] (or-join [?b] [?x :friend ?b] [?b :age 25])]"#, + r#"[:find ?e :where [?e :x ?v] (or-join [?v] [?f :y ?v] [?f :tiny ?v])]"#, + r#"[:find ?e :where [?e :tiny ?v] (or-join [?v] [?f :tiny2 ?v] [?f :x ?v])]"#, + r#"[:find ?e :where [?e :bio ?s] (or-join [?s] [?f :motto ?s] [?f :name ?s])]"#, + r#"[:find ?a ?b ?x :where [?a :friend ?b] (or [?a :age ?x] [?b :age ?x])]"#, + r#"[:find ?n :where [?e :name ?n] (or-join [?e] [?x :score 41] [?e :age 99])]"#, + r#"[:find ?n ?a :where [?e :name ?n] (or (and [?e :age ?a] (not [?e :friend :bob])) [?e :score ?a])]"#, + r#"[:find ?n :where [?e :name ?n] [?e :age ?a] (or [(> ?a 35)] [?e :friend :bob])]"#, + r#"[:find ?e :where (or [?e :age 40] [?e :score 41])]"#, + r#"[:find ?e ?p :where [?e :age 40] (or [?p :score 41] [?p :score 31])]"#, + r#"[:find ?n ?a :where [?e :name ?n] (or [?e :age ?a] [?e :score ?a]) [(> ?a 30)]]"#, + r#"[:find ?n :where [?e :name ?n] (or [?e :age 40] [?e :age 30]) (or-join [?e] [?e :friend :carol] [?e :x _])]"#, + r#"[:find ?n ?t :valid-at "2030-01-01T00:00:00Z" :where [?e :name ?n] (or [?e :db/valid-at ?t] [?e :age ?t])]"#, // Aggregates. r#"[:find ?a (count ?e) :where [?e :age ?a] [?e :name _]]"#, // Per-fact pseudo-attributes (#594): #594's example in both text orders, diff --git a/tests/property_test.rs b/tests/property_test.rs index c5a8f383a9..b33fbe9a92 100644 --- a/tests/property_test.rs +++ b/tests/property_test.rs @@ -4,7 +4,7 @@ //! evaluator. The first three properties write one fact per `transact` and run //! one-pattern queries. The others write random histories (batched transacts, //! retractions, write transactions, checkpoints) and run random queries with -//! joins, `not`/`not-join`, predicates, `:as-of`, `:valid-at` and +//! joins, `not`/`not-join`, `or`/`or-join`, predicates, `:as-of`, `:valid-at` and //! `:any-valid-time`, in memory and against a file that is reopened. //! //! Run: cargo test --test property_test @@ -389,6 +389,19 @@ enum Neg { }, } +/// A disjunction over bound variables (#546): it filters, and the rows it +/// keeps are deduplicated. +#[derive(Clone, Debug)] +enum Disj { + Or(Pat, Pat), + /// `(or-join [?x] [?x a v] [?x a' v'])`, with `v` a fresh `?z` when + /// `None`. + OrJoin { + var: Var, + arms: [(usize, Option); 2], + }, +} + #[derive(Clone, Copy, Debug)] enum CmpOp { Lt, @@ -444,6 +457,7 @@ enum At { struct Query { pats: Vec, neg: Option, + disj: Option, pred: Option, temporal: Temporal, /// The variables in `:find`, in order. @@ -482,6 +496,22 @@ impl Query { clauses.push(format!("(not-join [{x}] [{x} {} {v}])", ATTRS[*a])); } } + match &self.disj { + None => {} + Some(Disj::Or(p, q)) => clauses.push(format!("(or {} {})", p.edn(), q.edn())), + Some(Disj::OrJoin { var, arms }) => { + let x = var.name(); + let arm = |(a, v): &(usize, Option)| { + let v = v.as_ref().map_or("?z".to_string(), V::edn); + format!("[{x} {} {v}]", ATTRS[*a]) + }; + clauses.push(format!( + "(or-join [{x}] {} {})", + arm(&arms[0]), + arm(&arms[1]) + )); + } + } if let Some(p) = &self.pred { let r = match &p.r { Operand::Var(x) => x.name(), @@ -552,6 +582,7 @@ fn arb_cmp() -> impl Strategy { type RawQuery = ( Vec, Option<(bool, Pat, usize, Option)>, + Option<(bool, Pat, Pat, [(usize, Option); 2])>, Option<(CmpOp, bool, V)>, Temporal, Vec, @@ -582,6 +613,18 @@ fn arb_query() -> impl Strategy { prop::option::of(arb_dense_v()), ), ), + prop::option::weighted( + 0.3, + ( + any::(), + arb_pat(), + arb_pat(), + [ + (0..ATTRS.len(), prop::option::of(arb_dense_v())), + (0..ATTRS.len(), prop::option::of(arb_dense_v())), + ], + ), + ), prop::option::weighted(0.35, (arb_cmp(), any::(), arb_dense_v())), arb_temporal(), prop::collection::vec(any::(), 8), @@ -597,7 +640,7 @@ fn pick(vars: &[Var], n: usize, ok: impl Fn(Var) -> bool) -> Option { } fn build_query(raw: RawQuery) -> Query { - let (mut pats, neg, pred, temporal, find_mask, (n1, n2)) = raw; + let (mut pats, neg, disj, pred, temporal, find_mask, (n1, n2)) = raw; // At least one variable, so `:find` is not empty. if bound_vars(&pats).is_empty() { @@ -621,27 +664,42 @@ fn build_query(raw: RawQuery) -> Query { } let bound = bound_vars(&pats); - let neg = neg.and_then(|(plain, mut p, a, v)| { - if plain { - // `not` over bound variables only: an unbound one becomes `_`. - let fix = |t: &mut Term, pos_e: bool| { - if let Term::Var(x) = *t - && (!bound.contains(&x) || (pos_e && matches!(x, Var::V(_)))) - { - *t = if pos_e { Term::Entity(0) } else { Term::Blank }; - } - }; - fix(&mut p.e, true); - fix(&mut p.v, false); - if p.a.is_none() && !bound.contains(&Var::A) { - p.a = Some(a); + // A pattern over bound variables only: an unbound one becomes `_` (an + // entity for the entity position, a constant attribute for `?a`). + let over_bound = |mut p: Pat, a: usize| { + let fix = |t: &mut Term, pos_e: bool| { + if let Term::Var(x) = *t + && (!bound.contains(&x) || (pos_e && matches!(x, Var::V(_)))) + { + *t = if pos_e { Term::Entity(0) } else { Term::Blank }; } - Some(Neg::Not(p)) + }; + fix(&mut p.e, true); + fix(&mut p.v, false); + if p.a.is_none() && !bound.contains(&Var::A) { + p.a = Some(a); + } + p + }; + + let neg = neg.and_then(|(plain, p, a, v)| { + if plain { + Some(Neg::Not(over_bound(p, a))) } else { pick(&bound, n2, |x| matches!(x, Var::E(_))).map(|var| Neg::NotJoin { var, a, v }) } }); + // Branches over bound variables bind nothing new, as every branch of an + // `or` must bind the same new variables (PRS-057). + let disj = disj.and_then(|(plain, p, q, arms)| { + if plain { + Some(Disj::Or(over_bound(p, arms[0].0), over_bound(q, arms[1].0))) + } else { + pick(&bound, n1 ^ n2, |x| matches!(x, Var::E(_))).map(|var| Disj::OrJoin { var, arms }) + } + }); + let pred = pred.and_then(|(op, var_rhs, c)| { // Mostly a value variable: orderings over entities are type errors. let l = pick(&bound, n1, |x| matches!(x, Var::V(_))) @@ -668,6 +726,7 @@ fn build_query(raw: RawQuery) -> Query { Query { pats, neg, + disj, pred, temporal, find, @@ -784,6 +843,28 @@ fn ref_query(model: &Model, q: &Query) -> Vec { }); } } + if let Some(d) = &q.disj { + let arm = |b: &Binding, var: Var, (a, v): &(usize, Option)| { + let x = lookup(b, var); + facts.iter().any(|f| { + x == Some(&B::Val(V::Ref(f.e))) && f.a == *a && v.as_ref().is_none_or(|v| *v == f.v) + }) + }; + bindings.retain(|b| match d { + Disj::Or(p, q) => facts + .iter() + .any(|f| match_fact(b, p, f).is_some() || match_fact(b, q, f).is_some()), + Disj::OrJoin { var, arms } => arms.iter().any(|a| arm(b, *var, a)), + }); + // The rows an `or` keeps are distinct (spec §5.2). + let mut distinct: Vec = Vec::with_capacity(bindings.len()); + for b in bindings { + if !distinct.contains(&b) { + distinct.push(b); + } + } + bindings = distinct; + } if let Some(p) = &q.pred { bindings.retain(|b| { let l = lookup(b, p.l);