diff --git a/.github/workflows/binary-size.yml b/.github/workflows/binary-size.yml index 699f4fa705..643e0b0a1c 100644 --- a/.github/workflows/binary-size.yml +++ b/.github/workflows/binary-size.yml @@ -14,7 +14,10 @@ jobs: name: Check release binary size runs-on: ubuntu-latest env: - SIZE_LIMIT_BYTES: 1228800 # 1200 KiB — raised from 1 MiB for #277's structured error codes; see PHILOSOPHY.md §4 + # 1230 KiB: 1200 KiB (raised from 1 MiB for #277's structured error codes) plus a + # temporary 30 KiB while the streaming engine and the executor both ship (#473). + # Back to 1200 KiB when #551 removes the executor's query path. See PHILOSOPHY.md §4. + SIZE_LIMIT_BYTES: 1259520 steps: - name: Checkout code uses: actions/checkout@v4 diff --git a/CHANGELOG.md b/CHANGELOG.md index a03418f500..0cdfcb3ddb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,7 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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. -- **Aggregate and window answers no longer depend on the order of their input** (#547). Before, aggregates and window functions read their rows in the order the plan produced them, and several answers followed that order. Six cases changed. (1) `sum` over floats is exact: the values are added without rounding and the total is rounded once, so `1e16 + 1.0 + -1e16 + 1.0 + 0.5` gives `2.5` in every order (before, `1.5` or `2.5`). Window `sum` and `avg` likewise. (2) `sum` over integers saturates once, at the end: `i64::MAX + 1 + -1` gives `i64::MAX` (before, `i64::MAX - 1` or `i64::MAX` by order). (3) Window `sum` over integers adds them exactly; before they were added as floats, so a running total above 2^53 lost its low digits. (4) `min` / `max` of floats follow one order: `-0.0` before `0.0`, NaN after every other number (before, the first of two such values seen won). Window `min` / `max` use the same order over any values, so the minimum of keywords is the first in text order. (5) Window functions sort each partition by `:order-by` under one total order of values (numbers by numeric value, an integer before an equal float, then strings, booleans, refs, keywords, `nil`), so keywords, refs and booleans now sort (before, any two of them compared equal and kept their input order). Rows with equal `:order-by` values are peers: `rank` gives them the same rank, and `sum`, `count`, `min`, `max`, `avg` and registered window functions give every peer the value at the last peer, as SQL does; `row-number` numbers peers in the order of the other variables `:find` names. For example, with `?s` of 1.5, 5, 10, 10, `(sum ?s :over (:order-by ?s))` gave 1.5, 6.5, 16.5, 26.5, the 16.5 going to either tied row, and now gives 1.5, 6.5, 26.5, 26.5; ranking `:x :x :y :y` by `:order-by` gave ranks depending on the order the scan met them (1 2 3 4 when interleaved) and now gives 1 1 3 3. (6) In a query with aggregates, a window's argument, `:partition-by` and `:order-by` must be plain `:find` variables, or the query fails at parse time with the new `PRS-082`; before, any other variable read `nil` on every group row. The error a failing aggregate query reports is the first error, in `:find` order, of the first failing group in output order. A registered aggregate still receives its values in input order, which can depend on the plan; one whose result depends on that order may answer equivalent queries differently. +- **Aggregate and window answers no longer depend on the order of their input** (#547). Before, aggregates and window functions read their rows in the order the plan produced them, and several answers followed that order. Six cases changed. (1) `sum` over floats is exact: the values are added without rounding and the total is rounded once, so `1e16 + 1.0 + -1e16 + 1.0 + 0.5` gives `2.5` in every order (before, `1.5` or `2.5`). Window `sum` and `avg` likewise. (2) `sum` over integers saturates once, at the end: `i64::MAX + 1 + -1` gives `i64::MAX` (before, `i64::MAX - 1` or `i64::MAX` by order). (3) Window `sum` over integers adds them exactly; before they were added as floats, so a running total above 2^53 lost its low digits. (4) `min` / `max` of floats follow one order: `-0.0` before `0.0`, NaN after every other number (before, the first of two such values seen won). Window `min` / `max` use the same order over any values, so the minimum of keywords is the first in text order. (5) Window functions sort each partition by `:order-by` under one total order of values (numbers by numeric value, an integer before an equal float, then strings, booleans, refs, keywords, `nil`), so keywords, refs and booleans now sort (before, any two of them compared equal and kept their input order). Rows with equal `:order-by` values are peers: `rank` gives them the same rank, and `sum`, `count`, `min`, `max`, `avg` and registered window functions give every peer the value at the last peer, as SQL does; `row-number` numbers peers in the order of the other variables `:find` names. For example, with `?s` of 1.5, 5, 10, 10, `(sum ?s :over (:order-by ?s))` gave 1.5, 6.5, 16.5, 26.5, the 16.5 going to either tied row, and now gives 1.5, 6.5, 26.5, 26.5; ranking `:x :x :y :y` by `:order-by` gave ranks depending on the order the scan met them (1 2 3 4 when interleaved) and now gives 1 1 3 3. (6) In a query with aggregates, a window's argument, `:partition-by` and `:order-by` must be plain `:find` variables, or the query fails at parse time with the new `PRS-082`; before, any other variable read `nil` on every group row. The error a failing aggregate query reports is the first error, in `:find` order, of the first failing group in output order. A registered aggregate still receives its values in input order, which can depend on the plan; one whose result depends on that order may answer equivalent queries differently. (7) A group whose grouping variable holds floats that are equal as groups compare them (`-0.0` and `0.0`, or NaNs) returns the least of them in that order, so `-0.0` when the group holds it; before, it returned the first one the plan met. ### Added @@ -79,6 +79,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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 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`). +- **Aggregates run on the streaming engine** (#473, part 5: #547, second PR). Queries with aggregates in `:find`, with or without `:with`, now run on the engine when their `:where` does. An `Aggregate` operator keeps one entry per group in a hash table, keyed on the grouping cells as groups compare values, and steps each aggregate as rows arrive: a query with no grouping variable holds one set of accumulators, whatever the input size. `count` reads only whether a cell is `nil` and `count-distinct` keeps the keys of its cells, so neither turns ids into values; other aggregates read values. When the input ends, the groups are sorted by their values, finished in that order and returned in batches. Window functions stay on the executor. Measured (#394 envelope, p50 and peak RSS): `[:find (count ?v) :where [?e ?a ?v]]` 207 ms → 44 ms and 97 → 7 MiB at 100K facts, 3.01 s → 457 ms and 728 → 7 MiB at 1M, 29.6 s → 4.46 s and 6.6 GiB → 7 MiB at 10M; `[:find ?g (count ?e) :where [?e :group ?g]]` 31 → 5.9 ms at 100K, 397 → 61 ms and 97 → 7 MiB at 1M, 4.51 s → 614 ms and 901 → 7 MiB at 10M. Other workloads unchanged. Results are unchanged apart from the float group value above (`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. diff --git a/CLAUDE.md b/CLAUDE.md index 88dd8c4b1b..c6e63cba87 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -140,7 +140,7 @@ cargo run < demos/demo_negation.txt - `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, `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. +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, or aggregates with `:with`; windows stay on the executor), `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), `aggregate.rs` (`Aggregate`, #547: a hash table of groups keyed on cells as `Value`'s `Ord` compares values, one entry when ungrouped; `count`/`count-distinct` on cells, other aggregates on values via `datalog::aggregate::Agg`; groups sorted by value and finished in that order; a float group shows its least value by `value_order`), `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) @@ -205,7 +205,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1616 tests** (1606 passing, 10 ignored; unit + integration + doc). +**1620 tests** (1610 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/PHILOSOPHY.md b/PHILOSOPHY.md index afd7ac3ee6..4b4ed5441a 100644 --- a/PHILOSOPHY.md +++ b/PHILOSOPHY.md @@ -113,7 +113,9 @@ SQLite's success comes from a clear philosophy: be a library, not a server. Be s #277's structured error codes — 130 documented codes across 6 categories cannot fit in 1MB even with opt-level="z", LTO, codegen-units=1, and strip=symbols all already applied; see CI's `binary-size.yml` for the - enforced limit) + enforced limit). On the v3 branch the gate allows a temporary 30 KiB more + (1,230 KiB) while the streaming engine and the old executor both ship + (#473); it returns to 1,200 KiB when #551 removes the executor's query path - No runtime dependencies (no JVM, no Python, no Node.js) **Anti-pattern**: Requiring external services, libraries, or runtimes to function. diff --git a/README.md b/README.md index e56ed5798b..5aa760d3cd 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 1616 tests +cargo test # run 1620 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index c0bfc117e5..0e35f6129e 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -130,6 +130,20 @@ At 10M facts with PR 3 (same server, two rounds; the PR 2 code is unchanged for The pseudo-attribute pattern reads the `:db/tx-count` column that the `:name` probe fills for its one row. +### Aggregates on the streaming engine (#547 PR 2) + +`count` is `[:find (count ?v) :where [?e ?a ?v]]` (every fact, 1 row); `count_grouped` is `[:find ?g (count ?e) :where [?e :group ?g]]` (100 rows). Before PR 2 every aggregate query ran on the executor, which holds every binding before grouping. A/B on the same idle server, `v3` (234cc3e, with the `count` shape added) then PR 2; p50 and peak RSS. + +| Shape | 100K | 1M | 10M | +|---|---:|---:|---:| +| `count` p50, `v3` → PR 2 | 207 → 44 ms | 3.01 s → 457 ms | 29.6 s → 4.46 s | +| `count` peak RSS | 97 → 7 MiB | 728 → 7 MiB | 6,619 → 7 MiB | +| `count_grouped` p50 | 31.4 → 5.9 ms | 397 → 61 ms | 4.51 s → 614 ms | +| `count_grouped` peak RSS | 14 → 5 MiB | 97 → 7 MiB | 901 → 7 MiB | +| every other shape | unchanged | unchanged | unchanged | + +An ungrouped aggregate holds one set of accumulators, and `count` reads no value, so memory is flat across scales; a grouped one holds one entry per group. + ### Python FFI round trip **Command**: `python bench/envelope.py --report envelope.json --scale ` in [minigraf-python](https://github.com/project-minigraf/minigraf-python) (`v3`), on the same fixtures and report. The binding is built with `maturin develop --release` against this commit. It runs the same queries through `db.query(...)`, drains them with `next_batch(1000)`, and decodes each JSON batch with `json.loads`. Python 3.14.7. diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index ea48025f06..a17ab9ec98 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-20 with `cargo test --quiet` -**Result**: 1,606 passing tests and 10 ignored tests (1,616 total) +**Result**: 1,610 passing tests and 10 ignored tests (1,620 total) This covers the unreleased file-format-v8 work (#287, #371): the index-key value-collision fix, the v7→v8 migration, and the drop of formats v1–v6. It otherwise still covers the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Merged from the v2.x line: `tests/point_query_history_test.rs` and new storage unit tests check that attribute-narrowed bound-entity lookups return exactly what a full scan returns, and that `net_asserted_facts` matches its previous implementation on randomized histories (#323). Attribute-scan tests check that the AEVT range covers exactly the queried attribute, including non-ASCII names such as `:丿` and prefix siblings such as `:ab` for `:a` (#381). Incremental B+tree rebuild tests check that checkpoints which copy untouched index leaves produce exactly the entries and file checksum a full rebuild would, including over repeated checkpoints, that single-fact checkpoints do not fragment the index, and that a damaged slot directory is rejected rather than copied (#315). B+tree cursor tests check that every scan walks the tree, not the leaf `next_leaf` chain: full scans and start positions match the input, `seek` from the current position lands where a fresh descent from the root would (randomized, plus within a leaf, to a sibling, across subtrees, past the end, into the gap after a leaf, and backwards as a no-op), a seek to the sibling leaf reads exactly one page, reads are unchanged with every `next_leaf` zeroed, a child pointer into a non-B+tree page is STG-013, and a cycle in child pointers is an error, not a hang (v8 storage format PR 1, #374). Directory-sync unit tests check that creating the `.graph` file or the WAL, and deleting the WAL, fsync the parent directory after the file operation, and that reopening an existing file does not (#389). Disjunction tests check that `or-join` returns an empty result, not INT-031, when no rows reach it: on an empty database, after a pattern that matches nothing, after a `not` that removes every row, and in a rule body (#405). A stratification unit test builds the same two-rule negative cycle 64 times and checks that the INT-054 message names the same predicate pair every time (#410). Magic-sets tests check that a recursive rule with a literal start that recurses through another rule returns the same results as without the literal (#297). API tests check that `execute()` and `WriteTransaction::execute()` reject `$slot` bind tokens in every position with API-010 (#407). The REPL `run()` test now runs in a child process with null stdin, so it no longer hangs when the test runner's stdin is an open non-TTY stream (#415). v8 page-format tests (PR 2, #374, #388) check the 24-byte page header (a flipped bit, a wrong page id and a future generation each give their own STG code, legacy page types fail before the CRC, and a failed page is never cached), meta-page encoding, the free-list chain, WAL v2's base generation, and every row of the meta-selection table: both slots valid, a torn newest slot with the WAL's base generation (opens at the older one), a WAL newer than the valid meta, pages of the next generation on the free list or past `page_count` with no WAL (all STG-033, with the file unmodified), an unknown feature bit (STG-034), and a pre-release v8 single header (STG-032). Fault-injection tests crash `save()` at every page write (cleanly and with torn pages, including the meta write) and every sync, and crash a v7 migration at every write; each reopen finds exactly the old or the new checkpoint, and every reachable page plus the free list covers the file exactly. Twenty-five consecutive saves never write a page the previous meta references. Covering-key tests (PR 3, #433) check that byte order equals logical order for every key component and value type on random tuples (negative, zero and large integers, NaN and ±0.0, strings with 0x00, 64- and 65-byte strings, FOREVER, newest-transaction-first) and that every component round-trips; that prefix-compressed leaves and shortest-separator internal nodes round-trip, agree with a linear scan, keep `max(left) < s ≤ min(right)`, and reject an overflow; that the byte-key B+tree's builds, incremental rebuilds, cursor and `seek` match their expected sets; that dictionary ids are assigned once, never reused, shared between a keyword attribute and value, and deterministic; that a re-asserted or retracted long value writes no new value page and a forced hash collision still finds the right value; that one transaction with two timestamps is STG-037 and a missing dictionary entry STG-036; that committed reads by entity, entity and attribute, attribute, and in full equal an in-memory model across eight checkpoints and a reopen; that short-valued reads touch no value page; that a v7 file with every value type, long strings, refs and retractions migrates to exactly the same facts; that a pre-covering-key v8 file is STG-032; and that string values over 4,068 bytes and attributes or keywords over 1,024 bytes are WAL-003. A WAL test checks that reopening next to a fully checkpointed WAL does not reuse transaction numbers (#447). Copy-on-write checkpoint tests (PR 4, #434) check that lazy free-list pops and pushes conserve every page across page boundaries, partial head pages and chain exhaustion, never hand out a page freed in the same generation, and share unread chain pages unchanged; that a copy-on-write insert equals a sorted merge for random batches (including keys below the first and above the last, many into one leaf, root growth to depth 3, and 1 KB separators that split internal nodes), leaves the old tree readable and unchanged, frees exactly the replaced nodes, writes only new pages, writes exactly one leaf and two internal nodes for one entry in a depth-3 tree, and does not fragment leaves under single inserts; that a checkpoint after 1 or 100 right-edge facts writes at most the tree-depth difference more pages at 100,000 facts than at 10,000, and at most one path per new entry per tree for random keys; and that four reader threads querying throughout 40 checkpoints never fail and never see the fact count go backwards. Hardening tests (PR 5) damage an index leaf, an internal node, a dictionary leaf, a value page and a free-list page in turn. Every committed read or checkpoint that reaches the damaged page fails with STG-029, never with wrong or fewer rows. A query through `Minigraf` on a file with damaged leaves fails with STG-029, and the file still opens at its last checkpoint. A size test measures at most 200 bytes per fact (142 measured) on 144k facts in #433's shape; its 1.15M-fact variant is ignored locally and runs in the nightly smoke workflow. A shared dictionary-cache test checks that cached ident and timestamp lookups return the same facts and that the cache stays bounded. Merged from the v2.x line: storage and `edge_cases_test.rs` tests check that more than 65,535 uncheckpointed facts each resolve to their own fact through entity lookups and attribute scans, in memory and file-backed (#445). Merged from the v2.x line: `tests/golden_corpus_test.rs` opens a copy of each committed golden file in `tests/golden/` (v7 files written by minigraf 2.0.3: one checkpoint, several checkpoints, indexes rebuilt on open, a crash-left WAL, an already-checkpointed WAL, same-transaction multi-values) and checks its manifest's CRC32, `tx_count` and query results after open, after a checkpoint and reopen, and after one more write; a second test checks that every golden file has a manifest (#391). On `v3` the same test checks that each v7 file has a v8 meta page after its first open and gives the same results after reopening the migrated file, and adds seven v8 golden files (one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values at the size limits); the #371 queries, skipped on v2.x, run and pass. `tests/model_based_test.rs` runs random sequences of transacts, retracts, write transactions, checkpoints, reopens and simulated crashes against a file and, after every step, compares the transaction counter, `verify`, full rows with windows and tx counts, and six query shapes under `:as-of N` and `:valid-at T` with a reference model (#385). `tests/property_test.rs` writes random histories (batched transacts, retracts, write transactions, checkpoints) in memory and to a file, and compares random queries (one to three joined patterns, `not` or `not-join`, a comparison predicate, `:as-of`, `:valid-at` or `:any-valid-time`) with a reference evaluator, on the open file and after a reopen; a query error fails the test (#386). `tests/crash_kill_test.rs` kills a child process running a seeded workload (multi-valued batches, batched retracts, five checkpoint modes) at a random point and checks that the reopened file holds exactly the transactions the child logged as committed, or those plus the one in flight, through full-scan, AEVT, AVET, EAVT and `:as-of` queries and `verify`, again after a second reopen and after a checkpoint plus reopen (#384). Integrity tests (#373) check that intact files verify with no problems and an exact fact and page count, and that `verify` reports each kind of damage with its code: an EAVT, AEVT, AVET or VAET leaf missing an entry (STG-038), keys out of order and a page reached from two trees (STG-039), a rotted index leaf (STG-029), a free page still in use and a leaked page (STG-035), a missing transaction entry (STG-036), and an entity id whose UUID maps to another id (STG-040). After each index or free-list damage, `rebuild_indexes` leaves a file that verifies clean, reads back every fact and accounts for every page. The source is an index that agrees with another one, or the only intact one; three intact indexes that all disagree, or a damaged dictionary, give STG-041 with the file unchanged. A rebuild commits pending facts, including new ids and long values. A crash at every write (clean and torn) and every sync of a rebuild reopens either at the old generation with only its old damage or at the new one with none, never losing a fact. Through `Minigraf` (`tests/integrity_test.rs`), a rebuild commits WAL entries and deletes the WAL, and flipping a byte in each leaf of a file in turn is always reported, then either repaired (index leaves) or refused with STG-041 and the file unchanged (dictionary leaves). Page-count tests (#497) check that a CRC-valid meta whose `page_count` is past the end of the file (one page past, 2^50, `u64::MAX`; with the other slot valid or damaged; with or without a WAL) and a file cut short by one page, three pages or down to three pages are `STG-044` at open, with the file unchanged and not grown, while a `page_count` exactly at the end opens; that a checkpoint whose pages did not all reach the backend fails with `INT-049` before writing its meta, and the file reopens at the previous generation; and that `verify` at a meta counting pages past the end reports `STG-044` without scanning to that count. Through `Minigraf` (`tests/integrity_test.rs`), a file truncated by one or three pages and a file whose meta was rewritten with `page_count` 2^50 and a valid CRC are `STG-044` read-write and read-only, with no WAL created and the file length unchanged. The `file_header` fuzz input from #497 is a corpus seed. A sub-page test (#506, `tests/integrity_test.rs`) checks that a file of 1 to 4,095 bytes is `STG-045` read-write and read-only, unchanged and with no WAL, when it is a database cut below one page or foreign bytes, and opens as a new database that takes writes when it is a prefix of the first meta page or all zeros; a file-backend unit test checks that `partial_page` returns the bytes past the last whole page. The `corrupt_file` fuzzer no longer skips files under one page: they must fail to open or open empty, and the #506 input is a corpus seed. Damaged v7 fact page tests (#496) check that a page in the counted fact range whose type byte is anything but the fact-page type (zero, `0x01`, the v2.x B+tree types, `0xFF`, a zeroed page; first and last page) is `STG-014` rather than skipped, while a range derived from the first index root skips only v2.x B+tree pages; that opening such a v7 file read-write or read-only fails with `STG-014` and writes nothing; and, in `tests/migration_matrix_test.rs`, that the golden `v7_basic.graph` with page 1's type byte changed or page 1 overwritten with noise fails both opens with the file unchanged and no WAL created. Both inputs are `fact_page` corpus seeds. Merged from the v2.x line: `tests/edge_cases_test.rs` checks the same refusal and acceptance through `Minigraf::open` on a database checkpointed twice (#506). Torn-WAL-tail tests (#513) check that opening a WAL writer cuts off a partial last entry (cut in the checksum, the header or the payload) or an entry with a bad checksum and everything after it, then appends where replay reaches, and leaves an intact WAL byte for byte; that an append that fails part-way makes every later append `WAL-007` while a rejected oversize fact (`WAL-003`, nothing written) does not; through `Minigraf`, that the failed transaction is not applied, later `transact` and `commit` are `WAL-007`, and a `checkpoint()` makes writes work again; and, in `tests/wal_test.rs`, that a commit made after reopening a crash-left WAL with each kind of torn tail survives a second crash. The fault matrix (#390, `src/fault_matrix.rs`) drives a test-only fault plan through the real file backend, WAL and directory fsync: an EIO, a short or torn write (1, 40 and 4,095 bytes), a full disk that keeps failing every later write, a failed fsync, and a failed fsync that also loses the writes since the last good one ("fsyncgate"), each at every write or sync call of a transact, a transact that creates the WAL, an automatic checkpoint, `checkpoint()`, the close-time checkpoint and `rebuild_indexes()`, on a database committed over two checkpoints with multi-valued, retracted and long values and entries pending in the WAL. After each fault, the handle holds the old facts or those plus the whole transaction, never part of one; after a failed checkpoint another is `STG-046`; a later write succeeds or is `WAL-007`/`STG-046`; a kill and reopen gives exactly the handle's facts, plus the failed transaction whole or not at all, and `verify` finds nothing; and a commit after recovery survives another kill. Two more tests fill the disk halfway through a checkpoint (`STG-046`, reads unchanged, reopen intact), and fail the fsync after a checkpoint's meta write and then retry the checkpoint, crashing at each of its writes: the retry is refused and every reopen is intact (without the refusal, a reopen hits `STG-029`). Unit tests check the fault plan's counting, and that a `rebuild_indexes` refused with `STG-041` leaves the handle usable. Live-read tests (#379) check that `triple_len` ends exactly where `tx↓` begins for every value type and index; that on random histories (several valid-time windows, retractions, re-assertions, several values per attribute, long values, 12 transactions per checkpoint) the committed live read for every scan kind and `:as-of` point is exactly the net-asserted set, that it stays equivalent with pending facts on top, and after reopen; and that a point read on a triple asserted and retracted 2,000 times reads under a third of the pages a history read does, with or without `:as-of`. `tests/live_reads_test.rs` runs the same history in a checkpointed file database and in memory and checks that point, attribute, full-scan, join, valid-time, `:as-of` and rule queries return the same rows, before and after reopen. One-window tests (#435) check that `net_asserted_facts` keeps each triple's newest transaction only (a later window replaces an earlier one, closing an open window, a retraction in the newest transaction hides it, records with two windows in one transaction keep both, once each) against a per-triple model on random histories; that the on-disk key walk agrees at every `:as-of` before and after reopen; and that `API-011` rejects two windows of one fact in one transaction without taking a `tx_count`. `tests/valid_time_window_test.rs` checks replacing, closing, extending, reopening and retract-then-reassert through entity-bound and attribute queries in memory, on a checkpointed file and after reopen, `API-011` from `transact` and from `WriteTransaction::execute`, and a later statement's window committed when two statements of a `WriteTransaction` give one fact different windows. Window-validation tests (#436) check that `check_valid_windows` rejects an empty window, an inverted one, and a `:valid-to` at or before the transaction time when `:valid-from` is left out, but not retractions; that `execute` rejects each such `transact` (both bounds, equal bounds, `:valid-to` only, a per-fact bound inverting the transaction's window) with `API-019` without writing or taking a `tx_count`, in memory, checkpointed and after reopen; that `tx.execute()` rejects them and the transaction still commits its other statements; that `commit()` rejects a default `valid_from` that has passed the `:valid-to` by commit time; and that `FactStorage::transact_batch` takes no `tx_count` on rejection. Statement-order tests (#477, `tests/statement_order_test.rs`) run every mix of two statements on one fact inside a `WriteTransaction` (retract then assert, assert then retract, two retracts, two windows, after a committed assertion and on an empty database) and check that reads inside the transaction and the committed rows agree, in memory, checkpointed and after reopen; that other facts of an overridden statement survive; that the commit is one transaction without the overridden records; and that two windows in one statement are `API-011` from `tx.execute()` while the rest commits. A unit test checks the commit collapse keeps each fact's newest statement in order. A log-writer test checks that an inverted window is `API-019`, a second window of a fact in one transaction `API-011`, and an assertion and a retraction of one fact in one transaction `API-020` in either order, each leaving the writer usable and the output exact, while duplicate retractions, identical repeats and the same fact in the next transaction are accepted. Cursor tests (#432, `tests/cursor_test.rs`) check that `query()` batches partition the `execute()` answer for several batch sizes (never empty, never over `max_rows`, `max_rows == 0` still progresses, `None` stays `None`), that the iterator and aggregates, rules, `:as-of` and `:any-valid-time` match `execute()`, that a cursor opened before a `transact`, a `WriteTransaction` commit, a retract or a checkpoint returns the pre-write answer to the end (in memory and file-backed), that `transact`/`retract`/`rule` are `API-012` and bind slots `API-010`, that a `WriteTransaction` thread gets `INT-001`, that rule limits give `INT-020` as from `execute()`, that `PreparedQuery::query` matches `PreparedQuery::execute`, and that a cursor is `Send` and outlives its database handle. Fact-log tests (#430, `tests/fact_log_test.rs`) check that `fact_log()` returns exactly the records written (assertions and retractions, with `tx_count` and `tx_id`) in memory, with everything pending, half checkpointed, fully checkpointed and after reopen, in both orders, with windows of 1 to 1,000 records and batch sizes of 1 to 1,000, in non-decreasing `tx_count` in Tx order; that every layout gives identical records, including valid-time windows and long string values; that a transaction larger than the window is split with no loss or duplicate; that attribute, attribute-prefix, entity and tx-range filters and their combinations match a model, and unknown names match nothing; that writes after open are not in the log; that `checkpoint()` and `rebuild_indexes()` are `API-013` while a log is open (a checkpoint with nothing to write is allowed), that automatic checkpoints from `execute()` and `WriteTransaction::commit` wait for the log, and that closing, dropping or finishing the log releases the database; that a `WriteTransaction` thread gets `INT-001`; and that a log is `Send`, outlives its database handle, and the deferred writes replay on the next open. Read-only open tests (#429, `tests/read_only_open_test.rs`) check that a read-only handle on a file with checkpointed facts and a pending WAL returns the same query results, `tx_count` and fact log as a read-write open; that queries, a cursor, a fact log, `verify`, `prepare`, rules and a UDF leave the `.graph` and WAL bytes and the `.graph` mtime unchanged, and no WAL is created; that `transact`, `retract`, `begin_write`, `checkpoint` and `rebuild_indexes` are `API-014` without taking a `tx_count`, also on a read-only in-memory database and through the builder path; that a missing file is `STG-042` and nothing is created; that an empty file is an empty database and stays 0 bytes; that read-only handles share a file while a read-write one is refused with `STG-025`, both ways; that a file without write permission opens read-only; and that small and whole-file page caches work. File-backend unit tests check that a shared-mode backend refuses page writes and syncs with `INT-056`, that the in-process registry counts readers and admits readers or one writer (also without kernel locks), and that a reader in another process shares the file with a reader here and refuses a writer here with `STG-026`. Storage unit tests check that a read-only open of a v7 file at every point of an interrupted migration (clean and torn writes) sees every fact and writes nothing, and that an empty backend stays empty. `tests/golden_corpus_test.rs` opens a copy of every golden file read-only first and checks its `tx_count` and queries, and that neither the file nor its WAL changes. Log-writer tests (#431, `tests/log_writer_test.rs`) copy a source's fact log (assertions, retractions, an explicit valid-time window, long strings, refs, keywords, checkpointed and pending facts) through `LogWriter` and check that the new file has no `.partial` or WAL, verifies clean, and gives the source's `tx_count`, fact log and query results (current, `:valid-at`, `:any-valid-time`, every `:as-of`, and entity-, attribute- and value-bound lookups) read-write, read-only and after reopen (#370); that it takes new writes at the source's next `tx_count`; that 90,000 facts over two batch commits verify clean and count correctly at `:as-of`; that a purged middle transaction is a hole whose `:as-of` equals the one before, and trailing holes keep the counter through `advance_tx_count`; that an empty log is an empty database with the counter; that `tx_count` 0, a lower or closed transaction and a backwards advance are `API-015`, a second `tx_id` `API-016`, a second window `API-011`, a retraction of an asserted fact in one transaction `API-020`, an empty window `API-019` and oversize values or idents `WAL-003`, each leaving the writer usable and the output exact, with repeats written once; that an existing target or WAL is `STG-043`, a second writer `STG-025` and `read_only` `API-014`; that a stale `.partial` is reused; that dropping an unfinished writer leaves nothing; that `finish` refuses a target created during the build and leaves it untouched; and that `LogWriter` is `Send`. Unit tests check that a batch commits only when a transaction opens past the batch size, never splitting one, and that `FileBackend::truncate` empties a file. A unit test in `error.rs` checks that `MinigrafError::invalid_argument` and `MinigrafError::closed`, the constructors for language bindings, give API-017 and API-018 with their text. Query-validation tests (#406, #414) check that a plain `:find` variable or a window function's argument, `:partition-by` or `:order-by` variable that no `:where` clause binds (including `?_` wildcards) is `PRS-080` from both `execute()` and `prepare()`, naming the variable, while variables bound by a pattern, an attribute position, a rule call, an expression binding, an `or-join`, every branch of an `or`, a pseudo-attribute or a window spec are accepted, and bind slots are not mistaken for `:find` variables; and that an unknown aggregate is `QRY-010` and an unknown window function `QRY-011` on an empty database, when no row matches, when rows match, through a rule query and through a prepared query, while a registered UDF in either position returns an empty result on an empty database. Coverage-gate tests (#396) check that replay stops at a WAL entry whose first fact is longer than 10 MB or that claims more than 1M facts, that a WAL writer cannot be opened in a missing directory, and that a failed cut of a torn WAL tail fails the open and leaves the file as it was; that a short v7 page and a slot past the record count are `INT-024`; that a migration backup meta of another generation or file length is not used (`STG-032`, file unchanged), and a torn first meta with data in page 1 is `STG-032`, not a new file; that `save` with nothing pending writes nothing, `into_backend` saves pending facts, and `rebuild_indexes` with nothing checkpointed commits the pending facts; and that unsorted or repeated B+tree input and a stored key inserted with another value are `INT-049`, a tree pointer to a free-list page is `STG-013` from `get`, a leaf walk and a copy-on-write insert, and the read-only `MutexStorageBackend` refuses writes, syncs and close. A page-cache test holds two threads in the backend read so both miss the same page, and checks that both get the one cached copy; before it, that path ran only when the scheduler happened to race the threads, and the gate flapped. Three `BrowserDb` tests (wasm32, run with `wasm-bindgen-test` in a browser, not counted above) check that `query()` batches of 1, 7 and 1,000 give the rows of `execute()`, that a cursor keeps the answer from when it opened and returns the end after `close()`, and that a `transact` is API-012. The wasm32 targets run in CI (`.github/workflows/wasm.yml`). In a browser (`wasm-pack test --headless`, Firefox and Chrome): 32 `wasm_bindgen_test` tests: nineteen for `BrowserDb` (including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read, from #470), eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before), and two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. Five of the `BrowserDb` tests (#411, #440) check that opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open; that after each of 60 transacts memory, and at the end IndexedDB, hold exactly the pages not on the free list while the file grows by under one page per transact; that a commit applied in memory but never flushed reopens at the previous one and keeps working; that an export after churn is as long as the meta says and imports back with its free pages dropped; and that `importGraph()` deletes the replaced database's IndexedDB keys. Two buffer tests check that releasing a page drops its bytes and any unflushed write, and that export writes a released page as zeros. A native storage test checks that a file whose free pages are all zeros (as the browser exports them), both just migrated from v7 and after 20 saves, opens, verifies clean and keeps committing, and the free-list test checks that a checkpoint reports exactly the ids it newly lists. On `wasm32-wasip1` under Wasmtime: the unit and integration tests that do not use a file run, 956 passing; ten that spawn threads or a child process are ignored on WASI. These are not counted above. A WAL test checks that a checkpoint with no facts to flush still removes a WAL whose entries are all already in the file, and the golden-corpus test now requires the WAL to be gone after a checkpoint for the `stale_wal` fixtures too (#457). A WAL test checks that closing a handle opened with `wal_checkpoint_threshold(usize::MAX)`, in both sync modes, leaves the `.graph` file byte for byte as it was and keeps the WAL, whose entries replay on the next open, and a unit test closes an in-memory handle under the same setting (#476). A recursive-rule test checks that a rule query on a database with more live facts than `max_results` returns its answer, with a bound and with a free first argument, and that a query deriving more facts than its `:max-results` is still `INT-020` (#528). A log-writer test runs the online backup from `docs/DURABILITY.md`: it copies a read-write handle with an uncheckpointed transaction through `fact_log` and `LogWriter` while another thread writes past the automatic checkpoint threshold, and checks that the copy verifies clean, holds exactly the records the log returned and the counter read after the log opened, and that every concurrent write reaches the source's file once the log is dropped (#398). Rule-body tests in `tests/recursive_rules_test.rs` check that a `:db/valid-at` pattern in a rule definition, in its `not` and `not-join` bodies and in its `or` branches binds the query's valid time, on the semi-naive, stratified and magic-sets paths (#617). Tests in `tests/not_join_test.rs` check that a rule calling a rule with `not-join`, `not` or `or` returns that rule's rows, with a free and a literal argument and through a forwarding rule, and that a rule with its own `not-join` calling one gets the same rows whether or not the query asks for the callee first; stratification unit tests check that such a caller, a rule forwarding to it and a caller of a recursive one sit above the callee, and that recursion through a rule with a `not` still stratifies (#628). Tests in `tests/not_join_test.rs` check that recursion through a rule with `not`, `not-join` or `or`, directly or through another rule, returns every row along a chain, and that the `not` still removes the rows it should; evaluator unit tests check that such recursion stops at its fixpoint that `max_iterations` and `max_results` end one that does not with INT-020, and that `max_results` counts the facts every pass derives, not only the mixed rule's (#633). @@ -22,7 +22,7 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value - **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. - **Disjunction equality** (`tests/or_equality_test.rs`, 5 tests; #546): an `or` / `or-join` branch meets the outer row by join equality on every executor path (a keyword in the outer row meets a ref in a branch; `0.0` and `-0.0`; floats `1e-20` apart do not), branches naming different outer variables each meet the outer row on their own, and an `or-join` branch that does not bind its join variable keeps every outer row when it has a row; through `execute` and a cursor, in memory and after a checkpoint. Engine unit tests run every disjunction shape with each branch form forced and reordering on and off against the executor, and cover routing (rule invocations, nested `or`, registry predicates, branch-local metadata stay on the executor), the branch form the planner picks, `Distinct` (equal rows collapse; a keyword and a ref, `-0.0` and `0.0`), and that a hashed branch is read once and a correlated one runs only for rows earlier branches did not match. -- **Aggregates and windows** (`tests/aggregate_window_rules_test.rs`, 8 tests; #547): exact float `sum` and window `avg`, integer `sum` saturating once, exact window `sum` of integers above 2^53, `min`/`max` of `-0.0` and `0.0`, `rank` by keywords (peers 1 1 3 3), a running `sum` giving peers the value at the last peer, `row-number` breaking ties by the other `:find` variables, and `INT-041` from a failing group. `src/query/datalog/aggregate.rs` (15 unit tests) checks every accumulator over every order of small inputs and that `value_order` is a total order; `tests/window_functions_test.rs` checks `PRS-082` and a window over the groups of an aggregate query, and `tests/plan_independence_test.rs` runs aggregate, window and mixed queries with reordering on and off. +- **Aggregates and windows** (`tests/aggregate_window_rules_test.rs`, 8 tests; #547): exact float `sum` and window `avg`, integer `sum` saturating once, exact window `sum` of integers above 2^53, `min`/`max` of `-0.0` and `0.0`, `rank` by keywords (peers 1 1 3 3), a running `sum` giving peers the value at the last peer, `row-number` breaking ties by the other `:find` variables, and `INT-041` from a failing group. `src/query/datalog/aggregate.rs` (15 unit tests) checks every accumulator over every order of small inputs and that `value_order` is a total order; `tests/window_functions_test.rs` checks `PRS-082` and a window over the groups of an aggregate query, and `tests/plan_independence_test.rs` runs aggregate, window and mixed queries with reordering on and off. `Aggregate` on the engine (#547 PR 2, `src/query/engine/tests.rs`, 3 tests): every built-in aggregate grouped by keywords, refs, booleans, floats and long strings, over `nil` values, keywords and refs, with `:with` and `or`, at six temporal settings in memory, after a checkpoint and after reopen, against the executor; an ungrouped aggregate reads every row and returns one batch of one row; the zero row and empty answers; groups in value order over several batches; `INT-041` from a later group; a group dropped by `min` of no value. `tests/aggregation_test.rs` checks that a group of `0.0` and `-0.0` returns `-0.0` in either insertion order. - **Plan independence** (`tests/plan_independence_test.rs`, 15 tests, `test-oracle` feature only; #596): a matrix of queries (joins in both text orders, cross products, keyword and ref, floats, long strings, filter and binding expressions, recursive rules and rules with `not`, `or`/`or-join` including the #250 short-circuit shapes, placed and deferred `not`/`not-join`, aggregates, `:as-of`, `:valid-at`, `:any-valid-time`), in memory and on file after a checkpoint and a reopen, through `execute` and a cursor, gives the same bag of rows with clause reordering on and off (`minigraf::__reorder`) and with the engine's negation bodies and `or` branches chosen, forced hashed and forced correlated (`minigraf::__subplans`, #546; the matrix gains #546's negation and disjunction shapes); #596's example and the unification cases (an expression whose output is its input, two expressions on one variable, integer vs float, `-0.0` vs `0.0`); and `or` / `or-join` branches whose expressions read or bind from a variable only the outer row binds, nested and in rule bodies (#620); and expressions, chains of them and a `not` after them, reading a variable only an `or` binds, in queries, with rules and in rule bodies (#625; `tests/disjunction_test.rs` repeats them without `test-oracle`). Under `test-oracle` the model-based and property tests also rerun every generated query with reordering off (the property test also with negation bodies and `or` branches forced hashed; it generates `or` / `or-join` over bound variables, #546). Unit tests cover `branch_outer_reads` (#620), the planner deferring an expression only an `or` can bind for, after the expressions placed before it and ahead of the deferred `not`s (#625), `apply_expr` (equal, different, integer vs float, NaN, `-0.0`/`0.0` with and without replacing, keyword vs ref both ways, a failing expression), `Binders::expression`, the switch (source order kept, per thread, restored on drop), and the engine planner's `Bind` modes and build side with the switch off; the engine's join matrix gains six unification shapes. - **Public diagnostics**: structured parser, query, storage, WAL, API, and internal error codes; the error-code registry is checked against [`ERROR_REFERENCE.md`](ERROR_REFERENCE.md). - **Compatibility and quality**: golden-file corpus of released file formats, cross-platform format compatibility, property-based tests, long-haul smoke coverage, a weekly soak at 10M facts with a 5-hour churn (#392), XTDB/Datomic semantic compatibility, grammar conformance, and rustdoc examples. diff --git a/examples/perf_envelope.rs b/examples/perf_envelope.rs index 2377458707..a6d4f02cd9 100644 --- a/examples/perf_envelope.rs +++ b/examples/perf_envelope.rs @@ -553,6 +553,11 @@ fn shapes(e: usize, tx_half: u64, hot_tx_half: u64) -> Vec { ), rows: 1, }, + Shape { + name: "count", + query: "[:find (count ?v) :where [?e ?a ?v]]".into(), + rows: 1, + }, Shape { name: "count_grouped", query: "[:find ?g (count ?e) :where [?e :group ?g]]".into(), diff --git a/src/query/datalog/aggregate.rs b/src/query/datalog/aggregate.rs index fbeaadeb97..5ce24f979c 100644 --- a/src/query/datalog/aggregate.rs +++ b/src/query/datalog/aggregate.rs @@ -9,7 +9,7 @@ use crate::graph::types::Value; use anyhow::Result; use std::any::Any; use std::cmp::Ordering; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; /// The class of a value in [`value_order`]: numbers, strings, booleans, /// refs, keywords, `nil`. @@ -505,6 +505,33 @@ impl Agg { } } +/// The groups of an aggregate query, by their grouping values as `Value`'s +/// `Ord` compares them: the values each group returns, and one accumulator +/// per aggregate, in `:find` order. +pub(crate) type Groups = BTreeMap, (Vec, Vec)>; + +/// Finish `groups` in key order (spec §3.3): each group's values and its +/// aggregates' results. A group whose aggregate gives `INT-042` is dropped; +/// any other error, the first in `:find` order of the first group, fails. +/// `funcs` names each aggregate, for the messages. +pub(crate) fn finish_groups( + groups: Groups, + funcs: &[&str], +) -> Result, Vec)>> { + let mut out = Vec::with_capacity(groups.len()); + 'group: for (shown, accs) in groups.into_values() { + let mut results = Vec::with_capacity(accs.len()); + for (acc, func) in accs.into_iter().zip(funcs) { + match acc.finish(func)? { + Some(v) => results.push(v), + None => continue 'group, + } + } + out.push((shown, results)); + } + Ok(out) +} + /// A window function's running value over a sorted partition (spec §4.2). pub(crate) enum Running { Count(i64), diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 5eb6ea218a..7064c71ad0 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -1,4 +1,4 @@ -use super::aggregate::{Agg, Running, named_vars, value_order}; +use super::aggregate::{Agg, Groups, Running, finish_groups, named_vars, value_order}; use super::evaluator::{StratifiedEvaluator, evaluate_not_join}; use super::functions::FunctionRegistry; use super::matcher::{PatternMatcher, edn_to_entity_id, edn_to_value}; @@ -1673,22 +1673,34 @@ fn compute_aggregation( }) .collect(); - // Groups in key order, as `Value`'s `Ord` compares keys. - use std::collections::BTreeMap; - let mut groups: BTreeMap, Vec> = BTreeMap::new(); + // Groups in key order, as `Value`'s `Ord` compares keys. Each holds the + // values it returns: of the key values `Ord` finds equal (`-0.0` and + // `0.0`, NaNs), the least by `value_order`, whatever the input order. + let mut groups = Groups::new(); for b in bindings { let key: Vec = group_var_names .iter() .map(|v| b.get(*v).cloned().unwrap_or(Value::Null)) .collect(); - let accs = match groups.entry(key) { + let (shown, accs) = match groups.entry(key) { std::collections::btree_map::Entry::Occupied(e) => e.into_mut(), - std::collections::btree_map::Entry::Vacant(e) => e.insert( - aggs.iter() - .map(|(_, func, _)| Agg::new(func, registry)) - .collect::>>()?, - ), + std::collections::btree_map::Entry::Vacant(e) => { + let shown = e.key().clone(); + e.insert(( + shown, + aggs.iter() + .map(|(_, func, _)| Agg::new(func, registry)) + .collect::>>()?, + )) + } }; + for (s, v) in shown.iter_mut().zip(&group_var_names) { + if let Some(v) = b.get(*v) + && value_order(v, s).is_lt() + { + *s = v.clone(); + } + } for (acc, (_, _, var)) in accs.iter_mut().zip(&aggs) { if let Some(v) = b.get(*var) { acc.step(v); @@ -1706,19 +1718,15 @@ fn compute_aggregation( }) .collect(); + let funcs: Vec<&str> = aggs.iter().map(|(_, func, _)| *func).collect(); let mut results: Vec = Vec::new(); - 'group: for (key, accs) in groups { + for (shown, values) in finish_groups(groups, &funcs)? { let mut binding = Binding::new(); - for (v, val) in plain.iter().zip(key) { + for (v, val) in plain.iter().zip(shown) { binding.insert((*v).to_string(), val); } - for (acc, (i, func, _)) in accs.into_iter().zip(&aggs) { - match acc.finish(func)? { - Some(v) => { - binding.insert(format!("__agg_{}", i), v); - } - None => continue 'group, - } + for (v, (i, _, _)) in values.into_iter().zip(&aggs) { + binding.insert(format!("__agg_{}", i), v); } results.push(binding); } diff --git a/src/query/engine/aggregate.rs b/src/query/engine/aggregate.rs new file mode 100644 index 0000000000..a8fe9d0799 --- /dev/null +++ b/src/query/engine/aggregate.rs @@ -0,0 +1,235 @@ +//! `Aggregate` (#547 spec §5): one row per group of its input, with the +//! result of each aggregate of `:find`. +//! +//! Groups are keyed on their cells as `Value`'s `Ord` compares values (spec +//! §2), in a hash table: one entry for a query with no grouping variable, so +//! it runs in constant memory. Cells become values only where an +//! accumulator needs one: `count` reads only whether a cell is `nil`, and +//! `count-distinct` keeps the keys of its cells. When the input ends, the +//! groups are sorted by their values, as the executor's `BTreeMap` orders +//! them, and finished in that order (spec §3.3). A group returns, of the +//! floats its key finds equal (`-0.0` and `0.0`, NaNs), the least by +//! `value_order`, as the executor does. + +use super::batch::Batch; +use super::cell::{Cell, JoinKey, Scalar}; +use super::project::value; +use super::{BATCH_ROWS, Counters, Ctx, Operator}; +use crate::graph::types::Value; +use crate::query::datalog::aggregate::{Agg, Groups, finish_groups, value_order}; +use anyhow::Result; +use std::collections::{HashMap, HashSet}; + +/// One aggregate of one group. +enum Acc { + /// The number of cells that are not `nil`. + Count(i64), + /// The keys of the cells that are not `nil`. + CountDistinct(HashSet), + /// Any other aggregate, over values. + Values(Agg), +} + +impl Acc { + fn new(func: &str, ctx: &Ctx<'_>) -> Result { + Ok(match Agg::new(func, ctx.functions)? { + Agg::Count(_) => Acc::Count(0), + Agg::CountDistinct(_) => Acc::CountDistinct(HashSet::new()), + agg => Acc::Values(agg), + }) + } + + fn step(&mut self, cell: &Cell, ctx: &mut Ctx<'_>) -> Result<()> { + if matches!(cell, Cell::Val(Scalar::Null)) { + return Ok(()); + } + match self { + Acc::Count(n) => *n = n.saturating_add(1), + Acc::CountDistinct(set) => { + set.insert(JoinKey::group(cell)); + } + Acc::Values(agg) => agg.step(&value(cell, ctx)?), + } + Ok(()) + } + + /// The accumulator as an [`Agg`], whose `finish` gives its result. + fn into_agg(self) -> Agg { + match self { + Acc::Count(n) => Agg::Count(n), + Acc::CountDistinct(set) => Agg::Count(i64::try_from(set.len()).unwrap_or(i64::MAX)), + Acc::Values(agg) => agg, + } + } +} + +/// A group: its cells, and one accumulator per aggregate. +struct Group { + cells: Vec, + accs: Vec, +} + +pub(crate) struct Aggregate { + child: Box, + /// The slots of the grouping variables. + groups: Vec, + /// Each aggregate's function and argument slot. + aggs: Vec<(String, usize)>, + zero_row: bool, + /// Each group's index in `rows`, by its key. + table: HashMap, usize>, + rows: Vec, + /// The finished rows, last first, once the input has ended. + out: Option>>, + counters: Counters, +} + +impl Aggregate { + pub(crate) fn new( + child: Box, + groups: Vec, + aggs: Vec<(String, usize)>, + zero_row: bool, + ) -> Self { + Aggregate { + child, + groups, + aggs, + zero_row, + table: HashMap::new(), + rows: Vec::new(), + out: None, + counters: Counters::new("Aggregate"), + } + } + + /// Step the group of each row of `batch`. + fn take(&mut self, batch: &Batch, ctx: &mut Ctx<'_>) -> Result<()> { + let null = Cell::Val(Scalar::Null); + // A slot a row lacks reads `nil`, as a missing binding does on the + // executor. + let cell = |slot: usize, i: usize| batch.cols.get(slot).and_then(|c| c.get(i)); + for i in 0..batch.len { + let key: Vec = self + .groups + .iter() + .map(|&s| JoinKey::group(cell(s, i).unwrap_or(&null))) + .collect(); + let at = match self.table.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => *e.get(), + std::collections::hash_map::Entry::Vacant(e) => { + let accs = self + .aggs + .iter() + .map(|(func, _)| Acc::new(func, ctx)) + .collect::>>()?; + let cells = self + .groups + .iter() + .map(|&s| cell(s, i).unwrap_or(&null).clone()) + .collect(); + self.rows.push(Group { cells, accs }); + *e.insert(self.rows.len() - 1) + } + }; + let Some(group) = self.rows.get_mut(at) else { + continue; + }; + // Of the floats a key finds equal, the group returns the least + // by `value_order`, as the executor does: the only cells that + // are key-equal and not the same value. + for (shown, &s) in group.cells.iter_mut().zip(&self.groups) { + if let (Cell::Val(Scalar::Float(old)), Some(Cell::Val(Scalar::Float(new)))) = + (&*shown, cell(s, i)) + && value_order(&Value::Float(*new), &Value::Float(*old)).is_lt() + { + *shown = Cell::Val(Scalar::Float(*new)); + } + } + for (acc, (_, slot)) in group.accs.iter_mut().zip(&self.aggs) { + if let Some(c) = cell(*slot, i) { + acc.step(c, ctx)?; + } + } + } + Ok(()) + } + + /// The rows of every group, in the order of their values, finished. + fn finish(&mut self, ctx: &mut Ctx<'_>) -> Result>> { + if self.table.is_empty() && self.zero_row { + // `:with` cells, which `:find` does not return, then the zeros. + let mut row = vec![Cell::Val(Scalar::Null); self.groups.len()]; + row.extend(vec![Cell::Val(Scalar::Int(0)); self.aggs.len()]); + return Ok(vec![row]); + } + // Sorted and finished as the executor's groups are. + let mut groups = Groups::new(); + for group in std::mem::take(&mut self.rows) { + let values = group + .cells + .iter() + .map(|c| value(c, ctx)) + .collect::>>()?; + let accs = group.accs.into_iter().map(Acc::into_agg).collect(); + groups.insert(values.clone(), (values, accs)); + } + self.table.clear(); + let funcs: Vec<&str> = self.aggs.iter().map(|(f, _)| f.as_str()).collect(); + let mut rows = Vec::with_capacity(groups.len()); + for (shown, results) in finish_groups(groups, &funcs)? { + rows.push( + shown + .iter() + .chain(&results) + .map(|v| Cell::of_value(ctx.ids, ctx.keys, v)) + .collect::>>()?, + ); + } + rows.reverse(); + Ok(rows) + } +} + +impl Operator for Aggregate { + fn next_batch(&mut self, ctx: &mut Ctx<'_>) -> Result> { + if self.out.is_none() { + while let Some(batch) = self.child.next_batch(ctx)? { + self.counters.rows_in += batch.len as u64; + self.take(&batch, ctx)?; + } + self.out = Some(self.finish(ctx)?); + } + let Some(rows) = self.out.as_mut().filter(|r| !r.is_empty()) else { + return Ok(None); + }; + let width = self.groups.len() + self.aggs.len(); + let mut batch = Batch::new(width); + while batch.len < BATCH_ROWS + && let Some(row) = rows.pop() + { + batch.push(&mut row.into_iter().map(Some).collect::>()); + } + self.counters.out(&batch); + Ok(Some(batch)) + } + + fn rewind(&mut self, seed: &[Cell]) { + self.table.clear(); + self.rows.clear(); + self.out = None; + self.child.rewind(seed); + } + + fn close(&mut self) { + self.table = HashMap::new(); + self.rows = Vec::new(); + self.out = Some(Vec::new()); + self.child.close(); + } + + fn counters(&self, out: &mut Vec) { + out.push(self.counters); + self.child.counters(out); + } +} diff --git a/src/query/engine/cell.rs b/src/query/engine/cell.rs index 670d04cecd..fd3fd39175 100644 --- a/src/query/engine/cell.rs +++ b/src/query/engine/cell.rs @@ -83,7 +83,8 @@ pub(crate) enum JoinKey { Null, Bool(bool), Int(i64), - /// A float's bits, `-0.0` as `0.0`; never NaN. + /// A float's bits, `-0.0` as `0.0`; a NaN only in a [`JoinKey::group`] + /// key, as one NaN. Float(u64), Str(Arc), Long(ValueRef), @@ -109,6 +110,25 @@ impl JoinKey { } } +impl JoinKey { + /// The key of `cell` as `Value`'s `Ord` compares values, for groups and + /// distinct sets (#547 spec §2): as [`JoinKey::of`] without + /// normalising, except that every NaN is one key. + pub(crate) fn group(cell: &Cell) -> JoinKey { + match cell { + Cell::Eid(e) => JoinKey::Eid(*e), + Cell::Iid(i) => JoinKey::Iid(*i), + Cell::Val(Scalar::Null) => JoinKey::Null, + Cell::Val(Scalar::Bool(b)) => JoinKey::Bool(*b), + Cell::Val(Scalar::Int(n)) => JoinKey::Int(*n), + Cell::Val(Scalar::Float(f)) if f.is_nan() => JoinKey::Float(f64::NAN.to_bits()), + Cell::Val(Scalar::Float(f)) => JoinKey::Float(if *f == 0.0 { 0 } else { f.to_bits() }), + Cell::Val(Scalar::Str(s)) => JoinKey::Str(s.clone()), + Cell::Val(Scalar::Long(vref)) => JoinKey::Long(*vref), + } + } +} + /// Whether `a` and `b` are join-equal (#473 spec §5.4). pub(crate) fn join_eq(a: &Cell, b: &Cell, normalise: bool, ctx: &mut Ctx<'_>) -> Result { Ok( diff --git a/src/query/engine/filter.rs b/src/query/engine/filter.rs index b405ac3e69..addac842a6 100644 --- a/src/query/engine/filter.rs +++ b/src/query/engine/filter.rs @@ -31,6 +31,7 @@ impl Apply { Step::Anti(_) => "AntiJoin", Step::Union(_) => "Union", Step::Distinct(_) => "Distinct", + Step::Aggregate { .. } => "Aggregate", }; Apply { child, @@ -129,7 +130,11 @@ fn apply(step: &Step, mut batch: Batch, ctx: &mut Ctx<'_>) -> Result { } // Joins are operators of their own (`join::Join`, `anti::AntiJoin`, // `union::Union`, `distinct::Distinct`). - Step::Join(_) | Step::Anti(_) | Step::Union(_) | Step::Distinct(_) => {} + Step::Join(_) + | Step::Anti(_) + | Step::Union(_) + | Step::Distinct(_) + | Step::Aggregate { .. } => {} } Ok(batch) } diff --git a/src/query/engine/mod.rs b/src/query/engine/mod.rs index ce572ecdd7..52382b5abd 100644 --- a/src/query/engine/mod.rs +++ b/src/query/engine/mod.rs @@ -6,6 +6,7 @@ //! `test-oracle` feature, every query run here is also run by the executor //! and the answers are compared ([`oracle`]). +mod aggregate; mod anti; mod batch; mod cell; @@ -103,7 +104,7 @@ pub(crate) struct Stream { /// registered (`INT-040`), so the answer does not change between pulls. functions: Arc>, root: Box, - /// The slot of each `:find` variable. + /// The column of each `:find` element in the root's rows. find: Vec, vars: Vec, project: Counters, @@ -163,6 +164,11 @@ pub(crate) fn build(source: plan::Source, steps: Vec) -> Box 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)), + plan::Step::Aggregate { + groups, + aggs, + zero_row, + } => Box::new(aggregate::Aggregate::new(root, groups, aggs, zero_row)), step => Box::new(filter::Apply::new(root, step)), }; } diff --git a/src/query/engine/plan.rs b/src/query/engine/plan.rs index b2c943a302..1b2091d9b8 100644 --- a/src/query/engine/plan.rs +++ b/src/query/engine/plan.rs @@ -2,8 +2,9 @@ //! operator trees. //! //! The engine runs a query whose `:where` holds patterns and expression -//! clauses, and whose `:find` holds plain variables (#545). Every other query -//! runs on the existing executor (spec §9). +//! clauses, and whose `:find` holds plain variables (#545), or aggregates +//! with plain variables and a `:with` (#547). Every other query runs on the +//! existing executor (spec §9). //! //! Clauses run in the order `optimizer::plan` gives the executor, so an //! expression sees the same variables as it does there. A binding expression @@ -136,6 +137,16 @@ pub(crate) enum Step { /// 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), + /// The last step of an aggregate query (#547 spec §5): one row per group + /// of the cells at `groups`, holding those cells and then the result of + /// each aggregate `(function, argument slot)`. + Aggregate { + groups: Vec, + aggs: Vec<(String, usize)>, + /// Whether no input row gives one row of zeros: a query of `count`s + /// and `count-distinct`s and no plain `:find` variable. + zero_row: bool, + }, } /// A `not` / `not-join` body (#546 spec §4). @@ -232,7 +243,8 @@ pub(crate) type Vars = Vec<(String, usize)>; pub(crate) struct Plan { pub(crate) source: Source, pub(crate) steps: Vec, - /// The slot of each `:find` variable; empty for a body. + /// The column of each `:find` element in the rows of the last step: a + /// variable's slot, or a column of `Aggregate`; empty for a body. pub(crate) find: Vec, pub(crate) vars: Vec, } @@ -313,13 +325,62 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { b.clause(c)?; } + // The parser rejects a variable no clause binds (PRS-080, PRS-022, + // PRS-023); one only some `or` branches bind has no slot here. + let slot = |var: &String| b.slots.by_var.get(var).copied(); let mut find = Vec::with_capacity(query.find.len()); - for spec in &query.find { - let FindSpec::Variable(var) = spec else { - return None; - }; - // The parser rejects a variable no clause binds (PRS-080). - find.push(*b.slots.by_var.get(var)?); + let aggregate = query + .find + .iter() + .any(|s| matches!(s, FindSpec::Aggregate { .. })); + if aggregate { + // The rows of `Aggregate`: the grouping cells (the plain variables + // in `:find` order, then `:with`), then the aggregates. + let plain: Vec<&String> = query + .find + .iter() + .filter_map(|s| match s { + FindSpec::Variable(v) => Some(v), + _ => None, + }) + .collect(); + let mut groups = Vec::new(); + for var in plain.iter().copied().chain(&query.with_vars) { + groups.push(slot(var)?); + } + let (mut next_plain, mut next_agg) = (0, groups.len()); + let mut aggs = Vec::new(); + for spec in &query.find { + match spec { + FindSpec::Variable(_) => { + find.push(next_plain); + next_plain += 1; + } + FindSpec::Aggregate { func, var } => { + find.push(next_agg); + next_agg += 1; + aggs.push((func.clone(), slot(var)?)); + } + // Windows run on the executor until PR 3 of #547. + FindSpec::Window(_) => return None, + } + } + let zero_row = plain.is_empty() + && aggs + .iter() + .all(|(f, _)| f == "count" || f == "count-distinct"); + b.steps.push(Step::Aggregate { + groups, + aggs, + zero_row, + }); + } else { + for spec in &query.find { + let FindSpec::Variable(var) = spec else { + return None; + }; + find.push(slot(var)?); + } } let mut plan = b.finish()?; plan.find = find; diff --git a/src/query/engine/tests.rs b/src/query/engine/tests.rs index 937dc4ea53..6ba298cf82 100644 --- a/src/query/engine/tests.rs +++ b/src/query/engine/tests.rs @@ -428,14 +428,15 @@ fn engine_reads_many_batches() { assert_eq!(rows(&db, "(query [:find ?e :where [?e :big/n 2999]])"), 1); } -/// The executor still runs what the engine does not: aggregates, `:as-of` a +/// The executor still runs what the engine does not: windows, `:as-of` a /// timestamp. #[test] fn other_queries_stay_on_the_executor() { let db = Minigraf::in_memory().unwrap(); write_round(&db, 0); for q in [ - "(query [:find (count ?e) :where [?e :person/name ?n]])", + "(query [:find ?e (rank :over (:order-by ?n)) :where [?e :person/name ?n]])", + "(query [:find ?n (count ?e) (rank :over (:order-by ?n)) :where [?e :person/name ?n]])", "(query [:find ?e :as-of \"2099-01-01T00:00:00Z\" :where [?e :person/name ?n]])", ] { let before = runs(); @@ -1406,3 +1407,173 @@ fn disjunction_branches_run_per_row_or_once() { let read: u64 = c.iter().filter(|c| c.op == "Scan").map(|c| c.rows_in).sum(); assert!(read <= 250, "each branch is read once"); } + +/// Aggregate shapes (#547 PR 2): ungrouped and grouped, by keywords, refs, +/// booleans, floats (`-0.0` and `0.0` one group) and long strings; every +/// built-in aggregate over each kind of value, `nil` values, `:with`. +fn aggregates() -> Vec<(&'static str, &'static str)> { + vec![ + ("(count ?e)", "[?e :person/name ?n]"), + ("(count ?v) (count-distinct ?v)", "[?e ?a ?v]"), + ("(count ?v) (count-distinct ?v)", "[?e :person/null ?v]"), + ("?s (count ?e)", "[?e :person/status ?s]"), + ( + "?f (count ?e) (min ?g) (max ?g)", + "[?e :person/friend ?f] [?e :person/age ?g]", + ), + ( + "?ok (sum ?g) (sum-distinct ?g)", + "[?e :person/ok ?ok] [?e :person/age ?g]", + ), + ( + "?b (count ?e) (min ?n) (max ?n)", + "[?e :person/bio ?b] [?e :person/name ?n]", + ), + ("?b (count-distinct ?b)", "[?e :person/bio ?b]"), + ("(count-distinct ?b)", "[?e :person/bio ?b]"), + ( + "(sum ?x) (min ?x) (max ?x) (count-distinct ?x) (sum-distinct ?x)", + "[?e :person/score ?x]", + ), + ("?x (count ?e)", "[?e :person/score ?x]"), + ("(count-distinct ?k)", "[?e :person/alias ?k]"), + ( + "(count-distinct ?k)", + "(or [?e :person/alias ?k] [?e :person/boss ?k])", + ), + ("(count-distinct ?a)", "[?e ?a ?v]"), + ("(sum ?g) :with ?e", "[?e :person/age ?g]"), + ( + "?s (sum ?g) :with ?e", + "[?e :person/status ?s] [?e :person/age ?g]", + ), + ("(count ?g) :with ?e", "[?e :person/age ?g] [(> ?g 100)]"), + ( + "(count ?e) (count-distinct ?e)", + "[?e :person/age ?g] [(> ?g 100)]", + ), + ("(sum ?g)", "[?e :person/age ?g] [(> ?g 100)]"), + ("?e (count ?g)", "[?e :person/age ?g] [(> ?g 100)]"), + ("(min ?n) (count ?e)", "[?e :person/null ?n]"), + ] +} + +fn check_aggregates(db: &Minigraf) -> usize { + let tx = db.current_tx_count(); + let mut n = 0; + for (find, clauses) in aggregates() { + for t in temporals(tx) { + n += rows(db, &format!("(query [:find {find} {t} :where {clauses}])")); + } + } + n += rows( + db, + "(query [:find ?e (sum ?t) (max ?t) :any-valid-time :where [?e :person/name ?n] [?e :db/tx-count ?t]])", + ); + n +} + +#[test] +fn aggregates_match_executor() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("agg.graph"); + { + let db = Minigraf::open(&path).unwrap(); + for round in 0..3 { + write_round(&db, round); + } + assert!(check_aggregates(&db) > 0, "some groups"); + db.checkpoint().unwrap(); + write_round(&db, 3); + check_aggregates(&db); + } + let db = Minigraf::open(&path).unwrap(); + check_aggregates(&db); +} + +/// An ungrouped aggregate holds one accumulator: it reads every row and +/// returns one; empty input gives the zero row of a `count`-only query, and +/// no row otherwise (#547 spec §5.2). +#[test] +fn ungrouped_aggregate_returns_one_row() { + let db = Minigraf::in_memory().unwrap(); + let facts: String = (0..3000).map(|i| format!("[:e{i} :n {i}]")).collect(); + db.execute(&format!("(transact [{facts}])")).unwrap(); + let mut cursor = db + .query("(query [:find (count ?e) (sum ?v) :where [?e :n ?v]])") + .unwrap(); + let batch = cursor.next_batch(1).unwrap().expect("a row"); + assert_eq!(batch.len(), 1); + let c = cursor.counters(); + let agg = c + .iter() + .find(|c| c.op == "Aggregate") + .expect("an Aggregate"); + assert_eq!(agg.rows_in, 3000); + assert_eq!(agg.rows_out, 1); + assert_eq!(agg.batches, 1); + + let result = |q: &str| { + let before = runs(); + let QueryResult::QueryResults { results, .. } = db.execute(q).unwrap() else { + panic!("expected query results"); + }; + assert_eq!(runs(), before + 1, "query ran on the engine"); + results + }; + let zero = + result("(query [:find (count ?e) (count-distinct ?v) :where [?e :n ?v] [(< ?v 0)]])"); + assert_eq!( + zero, + vec![vec![crate::Value::Integer(0), crate::Value::Integer(0)]] + ); + let zero = result("(query [:find (count ?e) :with ?v :where [?e :n ?v] [(< ?v 0)]])"); + assert_eq!(zero, vec![vec![crate::Value::Integer(0)]]); + assert!(result("(query [:find (sum ?v) :where [?e :n ?v] [(< ?v 0)]])").is_empty()); + assert!(result("(query [:find ?e (count ?v) :where [?e :n ?v] [(< ?v 0)]])").is_empty()); +} + +/// Groups come out in the order of their values, over several batches; an +/// error in a later group fails the query, and `min` of no value drops its +/// group (#547 spec §3.3, §5.3). +#[test] +fn grouped_aggregate_orders_groups_and_fails_in_a_later_group() { + let db = Minigraf::in_memory().unwrap(); + let facts: String = (0..3000) + .map(|i| format!("[:e{i} :k {}] [:e{i} :n {i}]", 3000 - i)) + .collect(); + db.execute(&format!("(transact [{facts}])")).unwrap(); + let QueryResult::QueryResults { results, .. } = db + .execute("(query [:find ?k (count ?e) :where [?e :k ?k]])") + .unwrap() + else { + panic!("expected query results"); + }; + assert_eq!(results.len(), 3000); + let keys: Vec = results + .iter() + .map(|r| match r.first() { + Some(crate::Value::Integer(k)) => *k, + _ => -1, + }) + .collect(); + assert_eq!(keys, (1..=3000).collect::>(), "groups in key order"); + + db.execute("(transact [[:x :k 2999] [:x :n \"text\"] [:y :k 5] [:y :n nil]])") + .unwrap(); + let before = runs(); + let err = db + .execute("(query [:find ?k (sum ?n) :where [?e :k ?k] [?e :n ?n]])") + .unwrap_err(); + assert_eq!(crate::MinigrafError::from(err).code(), "INT-041"); + assert_eq!(runs(), before + 1, "query ran on the engine"); + + db.execute("(transact [[:z :k 7] [:z :m nil]])").unwrap(); + let QueryResult::QueryResults { results, .. } = db + .execute("(query [:find ?k (min ?m) :where [?e :k ?k] [?e :m ?m]])") + .unwrap() + else { + panic!("expected query results"); + }; + assert!(results.is_empty(), "the group with no value is dropped"); +} diff --git a/tests/aggregation_test.rs b/tests/aggregation_test.rs index 6ef25c9a3c..d24e641cc6 100644 --- a/tests/aggregation_test.rs +++ b/tests/aggregation_test.rs @@ -345,3 +345,41 @@ fn aggregate_with_as_of() { .unwrap(); assert_eq!(results(&r)[0][0], Value::Integer(2)); } + +// ── group values ───────────────────────────────────────────────────────────── + +/// A group of floats `Value`'s `Ord` finds equal returns the least of them +/// by value order (`-0.0` before `0.0`), whatever order the facts are met +/// in (#547 PR 2). +#[test] +fn float_group_returns_least_value() { + for facts in [ + "[[:a :x 0.0] [:b :x -0.0] [:c :x 0.0]]", + "[[:a :x -0.0] [:b :x 0.0] [:c :x 0.0]]", + ] { + let db = db(); + db.execute(&format!("(transact {facts})")).unwrap(); + let r = db + .execute("(query [:find ?v (count ?e) :where [?e :x ?v]])") + .unwrap(); + let rows = results(&r); + assert_eq!(rows.len(), 1, "one group"); + match rows[0].as_slice() { + [Value::Float(v), Value::Integer(3)] => { + assert!(*v == 0.0 && v.is_sign_negative(), "the group shows -0.0") + } + _ => panic!("expected a float and a count"), + } + } + let db = db(); + db.execute("(transact [[:a :x 0.0] [:b :x 0.0]])").unwrap(); + let r = db + .execute("(query [:find ?v (count ?e) :where [?e :x ?v]])") + .unwrap(); + match results(&r)[0].as_slice() { + [Value::Float(v), Value::Integer(2)] => { + assert!(v.is_sign_positive(), "a group of 0.0 shows 0.0") + } + _ => panic!("expected a float and a count"), + } +} diff --git a/tests/plan_independence_test.rs b/tests/plan_independence_test.rs index 66cf401775..280a3d37ae 100644 --- a/tests/plan_independence_test.rs +++ b/tests/plan_independence_test.rs @@ -126,6 +126,9 @@ const MATRIX: &[&str] = &[ r#"[:find ?e (rank :over (:order-by ?b)) (row-number :over (:order-by ?b)) :where [?e :friend ?b]]"#, r#"[:find ?a (count ?e) (row-number :over (:order-by ?a :desc)) :where [?e :age ?a]]"#, r#"[:find ?a (count ?b) :where (knows ?a ?b)]"#, + // A group of `0.0` and `-0.0` returns `-0.0`, the least by value order. + r#"[:find ?v (count ?e) :where [?e ?attr ?v] [(float? ?v)]]"#, + r#"[:find ?v (count ?e) :with ?attr :where [?e ?attr ?v] [(float? ?v)]]"#, // Patterns, joins, cross products. r#"[:find ?n ?a :where [?e :name ?n] [?e :age ?a]]"#, r#"[:find ?n ?a :where [?e :age ?a] [?e :name ?n]]"#,