From 7f096cbd13285ae291d63d911e0e7a3d35733896 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 15:43:39 +0530 Subject: [PATCH 1/5] feat(engine): window functions on the streaming engine (#547) Window holds each input row's passed-on cells and its named variables' values, then computes every window with aggregate::windows, the code the executor now calls too, and returns the rows in input order. The planner routes window queries and windows over an aggregate's groups; with windows, :with does not group, as on the executor. Envelope gains a `window` shape. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- CLAUDE.md | 6 +- README.md | 2 +- docs/TEST_COVERAGE.md | 2 +- examples/perf_envelope.rs | 7 ++ src/query/datalog/aggregate.rs | 101 +++++++++++++++++++- src/query/datalog/executor.rs | 123 +++++-------------------- src/query/engine/filter.rs | 4 +- src/query/engine/mod.rs | 4 + src/query/engine/plan.rs | 74 ++++++++++++--- src/query/engine/tests.rs | 164 ++++++++++++++++++++++++++++++++- src/query/engine/window.rs | 135 +++++++++++++++++++++++++++ 11 files changed, 497 insertions(+), 125 deletions(-) create mode 100644 src/query/engine/window.rs diff --git a/CLAUDE.md b/CLAUDE.md index c6e63cba87..f463d19a0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -131,7 +131,7 @@ cargo run < demos/demo_negation.txt - `parser.rs`: EDN/Datalog parser — `transact`, `retract`, `query`, `rule`, `:as-of`, `:valid-at`, `not`, `not-join`; `resolve_pseudo_sources` names each per-fact pseudo-attribute's source (nearest earlier same-entity pattern, lexical scope) and its hidden metadata variable `?#.`, else PRS-081 (#594) - `executor.rs`: Query executor — temporal filter (tx-time → net-assert → valid-time), not/not-join post-filter - `matcher.rs`: Pattern matching with variable unification; `edn_to_value`, `edn_to_entity_id` - - `aggregate.rs`: `Agg` (one aggregate of one group) and `Running` (a window's running value), shared by the executor and the engine; exact sums (`i128` integers saturated once, fixed-point floats rounded once), `value_order` (one total order of values for window sorts, peers, `rank` and `min`/`max`), `named_vars` (a window's tie-break variables) (#547) + - `aggregate.rs`: `Agg` (one aggregate of one group) and `Running` (a window's running value), shared by the executor and the engine; exact sums (`i128` integers saturated once, fixed-point floats rounded once), `value_order` (one total order of values for window sorts, peers, `rank` and `min`/`max`), `named_vars` (a window's tie-break variables), `windows` (each window's value per row: partitions, sort, peers) (#547) - `evaluator.rs`: `RecursiveEvaluator` (semi-naive), `StratifiedEvaluator` (repeats a stratum whose rules recurse through a `not`/`or` rule until it derives nothing new, #633), `evaluate_not_join` - `stratification.rs`: `DependencyGraph`, `stratify()` — negative edges + cycle detection; a positive edge to a rule with `not`/`not-join`/`or`/`or-join` also raises the caller, off a cycle (#628) - `rules.rs`: `RuleRegistry` — thread-safe rule management @@ -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, 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. +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, aggregates with `:with`, and window functions, over an aggregate's groups too), `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`), `window.rs` (`Window`, #547: holds each input row's passed-on cells and its named variables' values, then computes every window with `datalog::aggregate::windows`, the executor's code, and returns the rows in input 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 -**1620 tests** (1610 passing, 10 ignored; unit + integration + doc). +**1623 tests** (1613 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 5aa760d3cd..0d06f780a1 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ let r2 = pq.execute(&[("tx", BindValue::TxCount(2)), ("entity", BindValue::Entit ```bash cargo run # interactive Datalog REPL -cargo test # run 1620 tests +cargo test # run 1623 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index a17ab9ec98..d83d0ab2a4 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-20 with `cargo test --quiet` -**Result**: 1,610 passing tests and 10 ignored tests (1,620 total) +**Result**: 1,613 passing tests and 10 ignored tests (1,623 total) This covers the unreleased file-format-v8 work (#287, #371): the index-key value-collision fix, the v7→v8 migration, and the drop of formats v1–v6. It otherwise still covers the public database API, the Datalog engine, storage and recovery paths, v2.0.0's locking and structured-error-code changes, and v2.0.1's regression test for rebuilding indexes on open after several checkpoints (#370). Merged from the v2.x line: `tests/point_query_history_test.rs` and new storage unit tests check that attribute-narrowed bound-entity lookups return exactly what a full scan returns, and that `net_asserted_facts` matches its previous implementation on randomized histories (#323). Attribute-scan tests check that the AEVT range covers exactly the queried attribute, including non-ASCII names such as `:丿` and prefix siblings such as `:ab` for `:a` (#381). Incremental B+tree rebuild tests check that checkpoints which copy untouched index leaves produce exactly the entries and file checksum a full rebuild would, including over repeated checkpoints, that single-fact checkpoints do not fragment the index, and that a damaged slot directory is rejected rather than copied (#315). B+tree cursor tests check that every scan walks the tree, not the leaf `next_leaf` chain: full scans and start positions match the input, `seek` from the current position lands where a fresh descent from the root would (randomized, plus within a leaf, to a sibling, across subtrees, past the end, into the gap after a leaf, and backwards as a no-op), a seek to the sibling leaf reads exactly one page, reads are unchanged with every `next_leaf` zeroed, a child pointer into a non-B+tree page is STG-013, and a cycle in child pointers is an error, not a hang (v8 storage format PR 1, #374). Directory-sync unit tests check that creating the `.graph` file or the WAL, and deleting the WAL, fsync the parent directory after the file operation, and that reopening an existing file does not (#389). Disjunction tests check that `or-join` returns an empty result, not INT-031, when no rows reach it: on an empty database, after a pattern that matches nothing, after a `not` that removes every row, and in a rule body (#405). A stratification unit test builds the same two-rule negative cycle 64 times and checks that the INT-054 message names the same predicate pair every time (#410). Magic-sets tests check that a recursive rule with a literal start that recurses through another rule returns the same results as without the literal (#297). API tests check that `execute()` and `WriteTransaction::execute()` reject `$slot` bind tokens in every position with API-010 (#407). The REPL `run()` test now runs in a child process with null stdin, so it no longer hangs when the test runner's stdin is an open non-TTY stream (#415). v8 page-format tests (PR 2, #374, #388) check the 24-byte page header (a flipped bit, a wrong page id and a future generation each give their own STG code, legacy page types fail before the CRC, and a failed page is never cached), meta-page encoding, the free-list chain, WAL v2's base generation, and every row of the meta-selection table: both slots valid, a torn newest slot with the WAL's base generation (opens at the older one), a WAL newer than the valid meta, pages of the next generation on the free list or past `page_count` with no WAL (all STG-033, with the file unmodified), an unknown feature bit (STG-034), and a pre-release v8 single header (STG-032). Fault-injection tests crash `save()` at every page write (cleanly and with torn pages, including the meta write) and every sync, and crash a v7 migration at every write; each reopen finds exactly the old or the new checkpoint, and every reachable page plus the free list covers the file exactly. Twenty-five consecutive saves never write a page the previous meta references. Covering-key tests (PR 3, #433) check that byte order equals logical order for every key component and value type on random tuples (negative, zero and large integers, NaN and ±0.0, strings with 0x00, 64- and 65-byte strings, FOREVER, newest-transaction-first) and that every component round-trips; that prefix-compressed leaves and shortest-separator internal nodes round-trip, agree with a linear scan, keep `max(left) < s ≤ min(right)`, and reject an overflow; that the byte-key B+tree's builds, incremental rebuilds, cursor and `seek` match their expected sets; that dictionary ids are assigned once, never reused, shared between a keyword attribute and value, and deterministic; that a re-asserted or retracted long value writes no new value page and a forced hash collision still finds the right value; that one transaction with two timestamps is STG-037 and a missing dictionary entry STG-036; that committed reads by entity, entity and attribute, attribute, and in full equal an in-memory model across eight checkpoints and a reopen; that short-valued reads touch no value page; that a v7 file with every value type, long strings, refs and retractions migrates to exactly the same facts; that a pre-covering-key v8 file is STG-032; and that string values over 4,068 bytes and attributes or keywords over 1,024 bytes are WAL-003. A WAL test checks that reopening next to a fully checkpointed WAL does not reuse transaction numbers (#447). Copy-on-write checkpoint tests (PR 4, #434) check that lazy free-list pops and pushes conserve every page across page boundaries, partial head pages and chain exhaustion, never hand out a page freed in the same generation, and share unread chain pages unchanged; that a copy-on-write insert equals a sorted merge for random batches (including keys below the first and above the last, many into one leaf, root growth to depth 3, and 1 KB separators that split internal nodes), leaves the old tree readable and unchanged, frees exactly the replaced nodes, writes only new pages, writes exactly one leaf and two internal nodes for one entry in a depth-3 tree, and does not fragment leaves under single inserts; that a checkpoint after 1 or 100 right-edge facts writes at most the tree-depth difference more pages at 100,000 facts than at 10,000, and at most one path per new entry per tree for random keys; and that four reader threads querying throughout 40 checkpoints never fail and never see the fact count go backwards. Hardening tests (PR 5) damage an index leaf, an internal node, a dictionary leaf, a value page and a free-list page in turn. Every committed read or checkpoint that reaches the damaged page fails with STG-029, never with wrong or fewer rows. A query through `Minigraf` on a file with damaged leaves fails with STG-029, and the file still opens at its last checkpoint. A size test measures at most 200 bytes per fact (142 measured) on 144k facts in #433's shape; its 1.15M-fact variant is ignored locally and runs in the nightly smoke workflow. A shared dictionary-cache test checks that cached ident and timestamp lookups return the same facts and that the cache stays bounded. Merged from the v2.x line: storage and `edge_cases_test.rs` tests check that more than 65,535 uncheckpointed facts each resolve to their own fact through entity lookups and attribute scans, in memory and file-backed (#445). Merged from the v2.x line: `tests/golden_corpus_test.rs` opens a copy of each committed golden file in `tests/golden/` (v7 files written by minigraf 2.0.3: one checkpoint, several checkpoints, indexes rebuilt on open, a crash-left WAL, an already-checkpointed WAL, same-transaction multi-values) and checks its manifest's CRC32, `tx_count` and query results after open, after a checkpoint and reopen, and after one more write; a second test checks that every golden file has a manifest (#391). On `v3` the same test checks that each v7 file has a v8 meta page after its first open and gives the same results after reopening the migrated file, and adds seven v8 golden files (one checkpoint, seven copy-on-write checkpoints, a crash-left v2 WAL, an already-checkpointed v2 WAL, same-transaction multi-values, a v7 file migrated in place, and long values at the size limits); the #371 queries, skipped on v2.x, run and pass. `tests/model_based_test.rs` runs random sequences of transacts, retracts, write transactions, checkpoints, reopens and simulated crashes against a file and, after every step, compares the transaction counter, `verify`, full rows with windows and tx counts, and six query shapes under `:as-of N` and `:valid-at T` with a reference model (#385). `tests/property_test.rs` writes random histories (batched transacts, retracts, write transactions, checkpoints) in memory and to a file, and compares random queries (one to three joined patterns, `not` or `not-join`, a comparison predicate, `:as-of`, `:valid-at` or `:any-valid-time`) with a reference evaluator, on the open file and after a reopen; a query error fails the test (#386). `tests/crash_kill_test.rs` kills a child process running a seeded workload (multi-valued batches, batched retracts, five checkpoint modes) at a random point and checks that the reopened file holds exactly the transactions the child logged as committed, or those plus the one in flight, through full-scan, AEVT, AVET, EAVT and `:as-of` queries and `verify`, again after a second reopen and after a checkpoint plus reopen (#384). Integrity tests (#373) check that intact files verify with no problems and an exact fact and page count, and that `verify` reports each kind of damage with its code: an EAVT, AEVT, AVET or VAET leaf missing an entry (STG-038), keys out of order and a page reached from two trees (STG-039), a rotted index leaf (STG-029), a free page still in use and a leaked page (STG-035), a missing transaction entry (STG-036), and an entity id whose UUID maps to another id (STG-040). After each index or free-list damage, `rebuild_indexes` leaves a file that verifies clean, reads back every fact and accounts for every page. The source is an index that agrees with another one, or the only intact one; three intact indexes that all disagree, or a damaged dictionary, give STG-041 with the file unchanged. A rebuild commits pending facts, including new ids and long values. A crash at every write (clean and torn) and every sync of a rebuild reopens either at the old generation with only its old damage or at the new one with none, never losing a fact. Through `Minigraf` (`tests/integrity_test.rs`), a rebuild commits WAL entries and deletes the WAL, and flipping a byte in each leaf of a file in turn is always reported, then either repaired (index leaves) or refused with STG-041 and the file unchanged (dictionary leaves). Page-count tests (#497) check that a CRC-valid meta whose `page_count` is past the end of the file (one page past, 2^50, `u64::MAX`; with the other slot valid or damaged; with or without a WAL) and a file cut short by one page, three pages or down to three pages are `STG-044` at open, with the file unchanged and not grown, while a `page_count` exactly at the end opens; that a checkpoint whose pages did not all reach the backend fails with `INT-049` before writing its meta, and the file reopens at the previous generation; and that `verify` at a meta counting pages past the end reports `STG-044` without scanning to that count. Through `Minigraf` (`tests/integrity_test.rs`), a file truncated by one or three pages and a file whose meta was rewritten with `page_count` 2^50 and a valid CRC are `STG-044` read-write and read-only, with no WAL created and the file length unchanged. The `file_header` fuzz input from #497 is a corpus seed. A sub-page test (#506, `tests/integrity_test.rs`) checks that a file of 1 to 4,095 bytes is `STG-045` read-write and read-only, unchanged and with no WAL, when it is a database cut below one page or foreign bytes, and opens as a new database that takes writes when it is a prefix of the first meta page or all zeros; a file-backend unit test checks that `partial_page` returns the bytes past the last whole page. The `corrupt_file` fuzzer no longer skips files under one page: they must fail to open or open empty, and the #506 input is a corpus seed. Damaged v7 fact page tests (#496) check that a page in the counted fact range whose type byte is anything but the fact-page type (zero, `0x01`, the v2.x B+tree types, `0xFF`, a zeroed page; first and last page) is `STG-014` rather than skipped, while a range derived from the first index root skips only v2.x B+tree pages; that opening such a v7 file read-write or read-only fails with `STG-014` and writes nothing; and, in `tests/migration_matrix_test.rs`, that the golden `v7_basic.graph` with page 1's type byte changed or page 1 overwritten with noise fails both opens with the file unchanged and no WAL created. Both inputs are `fact_page` corpus seeds. Merged from the v2.x line: `tests/edge_cases_test.rs` checks the same refusal and acceptance through `Minigraf::open` on a database checkpointed twice (#506). Torn-WAL-tail tests (#513) check that opening a WAL writer cuts off a partial last entry (cut in the checksum, the header or the payload) or an entry with a bad checksum and everything after it, then appends where replay reaches, and leaves an intact WAL byte for byte; that an append that fails part-way makes every later append `WAL-007` while a rejected oversize fact (`WAL-003`, nothing written) does not; through `Minigraf`, that the failed transaction is not applied, later `transact` and `commit` are `WAL-007`, and a `checkpoint()` makes writes work again; and, in `tests/wal_test.rs`, that a commit made after reopening a crash-left WAL with each kind of torn tail survives a second crash. The fault matrix (#390, `src/fault_matrix.rs`) drives a test-only fault plan through the real file backend, WAL and directory fsync: an EIO, a short or torn write (1, 40 and 4,095 bytes), a full disk that keeps failing every later write, a failed fsync, and a failed fsync that also loses the writes since the last good one ("fsyncgate"), each at every write or sync call of a transact, a transact that creates the WAL, an automatic checkpoint, `checkpoint()`, the close-time checkpoint and `rebuild_indexes()`, on a database committed over two checkpoints with multi-valued, retracted and long values and entries pending in the WAL. After each fault, the handle holds the old facts or those plus the whole transaction, never part of one; after a failed checkpoint another is `STG-046`; a later write succeeds or is `WAL-007`/`STG-046`; a kill and reopen gives exactly the handle's facts, plus the failed transaction whole or not at all, and `verify` finds nothing; and a commit after recovery survives another kill. Two more tests fill the disk halfway through a checkpoint (`STG-046`, reads unchanged, reopen intact), and fail the fsync after a checkpoint's meta write and then retry the checkpoint, crashing at each of its writes: the retry is refused and every reopen is intact (without the refusal, a reopen hits `STG-029`). Unit tests check the fault plan's counting, and that a `rebuild_indexes` refused with `STG-041` leaves the handle usable. Live-read tests (#379) check that `triple_len` ends exactly where `tx↓` begins for every value type and index; that on random histories (several valid-time windows, retractions, re-assertions, several values per attribute, long values, 12 transactions per checkpoint) the committed live read for every scan kind and `:as-of` point is exactly the net-asserted set, that it stays equivalent with pending facts on top, and after reopen; and that a point read on a triple asserted and retracted 2,000 times reads under a third of the pages a history read does, with or without `:as-of`. `tests/live_reads_test.rs` runs the same history in a checkpointed file database and in memory and checks that point, attribute, full-scan, join, valid-time, `:as-of` and rule queries return the same rows, before and after reopen. One-window tests (#435) check that `net_asserted_facts` keeps each triple's newest transaction only (a later window replaces an earlier one, closing an open window, a retraction in the newest transaction hides it, records with two windows in one transaction keep both, once each) against a per-triple model on random histories; that the on-disk key walk agrees at every `:as-of` before and after reopen; and that `API-011` rejects two windows of one fact in one transaction without taking a `tx_count`. `tests/valid_time_window_test.rs` checks replacing, closing, extending, reopening and retract-then-reassert through entity-bound and attribute queries in memory, on a checkpointed file and after reopen, `API-011` from `transact` and from `WriteTransaction::execute`, and a later statement's window committed when two statements of a `WriteTransaction` give one fact different windows. Window-validation tests (#436) check that `check_valid_windows` rejects an empty window, an inverted one, and a `:valid-to` at or before the transaction time when `:valid-from` is left out, but not retractions; that `execute` rejects each such `transact` (both bounds, equal bounds, `:valid-to` only, a per-fact bound inverting the transaction's window) with `API-019` without writing or taking a `tx_count`, in memory, checkpointed and after reopen; that `tx.execute()` rejects them and the transaction still commits its other statements; that `commit()` rejects a default `valid_from` that has passed the `:valid-to` by commit time; and that `FactStorage::transact_batch` takes no `tx_count` on rejection. Statement-order tests (#477, `tests/statement_order_test.rs`) run every mix of two statements on one fact inside a `WriteTransaction` (retract then assert, assert then retract, two retracts, two windows, after a committed assertion and on an empty database) and check that reads inside the transaction and the committed rows agree, in memory, checkpointed and after reopen; that other facts of an overridden statement survive; that the commit is one transaction without the overridden records; and that two windows in one statement are `API-011` from `tx.execute()` while the rest commits. A unit test checks the commit collapse keeps each fact's newest statement in order. A log-writer test checks that an inverted window is `API-019`, a second window of a fact in one transaction `API-011`, and an assertion and a retraction of one fact in one transaction `API-020` in either order, each leaving the writer usable and the output exact, while duplicate retractions, identical repeats and the same fact in the next transaction are accepted. Cursor tests (#432, `tests/cursor_test.rs`) check that `query()` batches partition the `execute()` answer for several batch sizes (never empty, never over `max_rows`, `max_rows == 0` still progresses, `None` stays `None`), that the iterator and aggregates, rules, `:as-of` and `:any-valid-time` match `execute()`, that a cursor opened before a `transact`, a `WriteTransaction` commit, a retract or a checkpoint returns the pre-write answer to the end (in memory and file-backed), that `transact`/`retract`/`rule` are `API-012` and bind slots `API-010`, that a `WriteTransaction` thread gets `INT-001`, that rule limits give `INT-020` as from `execute()`, that `PreparedQuery::query` matches `PreparedQuery::execute`, and that a cursor is `Send` and outlives its database handle. Fact-log tests (#430, `tests/fact_log_test.rs`) check that `fact_log()` returns exactly the records written (assertions and retractions, with `tx_count` and `tx_id`) in memory, with everything pending, half checkpointed, fully checkpointed and after reopen, in both orders, with windows of 1 to 1,000 records and batch sizes of 1 to 1,000, in non-decreasing `tx_count` in Tx order; that every layout gives identical records, including valid-time windows and long string values; that a transaction larger than the window is split with no loss or duplicate; that attribute, attribute-prefix, entity and tx-range filters and their combinations match a model, and unknown names match nothing; that writes after open are not in the log; that `checkpoint()` and `rebuild_indexes()` are `API-013` while a log is open (a checkpoint with nothing to write is allowed), that automatic checkpoints from `execute()` and `WriteTransaction::commit` wait for the log, and that closing, dropping or finishing the log releases the database; that a `WriteTransaction` thread gets `INT-001`; and that a log is `Send`, outlives its database handle, and the deferred writes replay on the next open. Read-only open tests (#429, `tests/read_only_open_test.rs`) check that a read-only handle on a file with checkpointed facts and a pending WAL returns the same query results, `tx_count` and fact log as a read-write open; that queries, a cursor, a fact log, `verify`, `prepare`, rules and a UDF leave the `.graph` and WAL bytes and the `.graph` mtime unchanged, and no WAL is created; that `transact`, `retract`, `begin_write`, `checkpoint` and `rebuild_indexes` are `API-014` without taking a `tx_count`, also on a read-only in-memory database and through the builder path; that a missing file is `STG-042` and nothing is created; that an empty file is an empty database and stays 0 bytes; that read-only handles share a file while a read-write one is refused with `STG-025`, both ways; that a file without write permission opens read-only; and that small and whole-file page caches work. File-backend unit tests check that a shared-mode backend refuses page writes and syncs with `INT-056`, that the in-process registry counts readers and admits readers or one writer (also without kernel locks), and that a reader in another process shares the file with a reader here and refuses a writer here with `STG-026`. Storage unit tests check that a read-only open of a v7 file at every point of an interrupted migration (clean and torn writes) sees every fact and writes nothing, and that an empty backend stays empty. `tests/golden_corpus_test.rs` opens a copy of every golden file read-only first and checks its `tx_count` and queries, and that neither the file nor its WAL changes. Log-writer tests (#431, `tests/log_writer_test.rs`) copy a source's fact log (assertions, retractions, an explicit valid-time window, long strings, refs, keywords, checkpointed and pending facts) through `LogWriter` and check that the new file has no `.partial` or WAL, verifies clean, and gives the source's `tx_count`, fact log and query results (current, `:valid-at`, `:any-valid-time`, every `:as-of`, and entity-, attribute- and value-bound lookups) read-write, read-only and after reopen (#370); that it takes new writes at the source's next `tx_count`; that 90,000 facts over two batch commits verify clean and count correctly at `:as-of`; that a purged middle transaction is a hole whose `:as-of` equals the one before, and trailing holes keep the counter through `advance_tx_count`; that an empty log is an empty database with the counter; that `tx_count` 0, a lower or closed transaction and a backwards advance are `API-015`, a second `tx_id` `API-016`, a second window `API-011`, a retraction of an asserted fact in one transaction `API-020`, an empty window `API-019` and oversize values or idents `WAL-003`, each leaving the writer usable and the output exact, with repeats written once; that an existing target or WAL is `STG-043`, a second writer `STG-025` and `read_only` `API-014`; that a stale `.partial` is reused; that dropping an unfinished writer leaves nothing; that `finish` refuses a target created during the build and leaves it untouched; and that `LogWriter` is `Send`. Unit tests check that a batch commits only when a transaction opens past the batch size, never splitting one, and that `FileBackend::truncate` empties a file. A unit test in `error.rs` checks that `MinigrafError::invalid_argument` and `MinigrafError::closed`, the constructors for language bindings, give API-017 and API-018 with their text. Query-validation tests (#406, #414) check that a plain `:find` variable or a window function's argument, `:partition-by` or `:order-by` variable that no `:where` clause binds (including `?_` wildcards) is `PRS-080` from both `execute()` and `prepare()`, naming the variable, while variables bound by a pattern, an attribute position, a rule call, an expression binding, an `or-join`, every branch of an `or`, a pseudo-attribute or a window spec are accepted, and bind slots are not mistaken for `:find` variables; and that an unknown aggregate is `QRY-010` and an unknown window function `QRY-011` on an empty database, when no row matches, when rows match, through a rule query and through a prepared query, while a registered UDF in either position returns an empty result on an empty database. Coverage-gate tests (#396) check that replay stops at a WAL entry whose first fact is longer than 10 MB or that claims more than 1M facts, that a WAL writer cannot be opened in a missing directory, and that a failed cut of a torn WAL tail fails the open and leaves the file as it was; that a short v7 page and a slot past the record count are `INT-024`; that a migration backup meta of another generation or file length is not used (`STG-032`, file unchanged), and a torn first meta with data in page 1 is `STG-032`, not a new file; that `save` with nothing pending writes nothing, `into_backend` saves pending facts, and `rebuild_indexes` with nothing checkpointed commits the pending facts; and that unsorted or repeated B+tree input and a stored key inserted with another value are `INT-049`, a tree pointer to a free-list page is `STG-013` from `get`, a leaf walk and a copy-on-write insert, and the read-only `MutexStorageBackend` refuses writes, syncs and close. A page-cache test holds two threads in the backend read so both miss the same page, and checks that both get the one cached copy; before it, that path ran only when the scheduler happened to race the threads, and the gate flapped. Three `BrowserDb` tests (wasm32, run with `wasm-bindgen-test` in a browser, not counted above) check that `query()` batches of 1, 7 and 1,000 give the rows of `execute()`, that a cursor keeps the answer from when it opened and returns the end after `close()`, and that a `transact` is API-012. The wasm32 targets run in CI (`.github/workflows/wasm.yml`). In a browser (`wasm-pack test --headless`, Firefox and Chrome): 32 `wasm_bindgen_test` tests: nineteen for `BrowserDb` (including IndexedDB persistence, the cursor, and the flush returning every dirty page and failing on one it cannot read, from #470), eleven for `BrowserBufferBackend` (which used `#[test]` and never ran before), and two checking that IndexedDB page keys accept only whole numbers from 0 to 2^53. Five of the `BrowserDb` tests (#411, #440) check that opening a v7 store written straight into IndexedDB stores a v8 meta page and only the live pages, with nothing written on the next open; that after each of 60 transacts memory, and at the end IndexedDB, hold exactly the pages not on the free list while the file grows by under one page per transact; that a commit applied in memory but never flushed reopens at the previous one and keeps working; that an export after churn is as long as the meta says and imports back with its free pages dropped; and that `importGraph()` deletes the replaced database's IndexedDB keys. Two buffer tests check that releasing a page drops its bytes and any unflushed write, and that export writes a released page as zeros. A native storage test checks that a file whose free pages are all zeros (as the browser exports them), both just migrated from v7 and after 20 saves, opens, verifies clean and keeps committing, and the free-list test checks that a checkpoint reports exactly the ids it newly lists. On `wasm32-wasip1` under Wasmtime: the unit and integration tests that do not use a file run, 956 passing; ten that spawn threads or a child process are ignored on WASI. These are not counted above. A WAL test checks that a checkpoint with no facts to flush still removes a WAL whose entries are all already in the file, and the golden-corpus test now requires the WAL to be gone after a checkpoint for the `stale_wal` fixtures too (#457). A WAL test checks that closing a handle opened with `wal_checkpoint_threshold(usize::MAX)`, in both sync modes, leaves the `.graph` file byte for byte as it was and keeps the WAL, whose entries replay on the next open, and a unit test closes an in-memory handle under the same setting (#476). A recursive-rule test checks that a rule query on a database with more live facts than `max_results` returns its answer, with a bound and with a free first argument, and that a query deriving more facts than its `:max-results` is still `INT-020` (#528). A log-writer test runs the online backup from `docs/DURABILITY.md`: it copies a read-write handle with an uncheckpointed transaction through `fact_log` and `LogWriter` while another thread writes past the automatic checkpoint threshold, and checks that the copy verifies clean, holds exactly the records the log returned and the counter read after the log opened, and that every concurrent write reaches the source's file once the log is dropped (#398). Rule-body tests in `tests/recursive_rules_test.rs` check that a `:db/valid-at` pattern in a rule definition, in its `not` and `not-join` bodies and in its `or` branches binds the query's valid time, on the semi-naive, stratified and magic-sets paths (#617). Tests in `tests/not_join_test.rs` check that a rule calling a rule with `not-join`, `not` or `or` returns that rule's rows, with a free and a literal argument and through a forwarding rule, and that a rule with its own `not-join` calling one gets the same rows whether or not the query asks for the callee first; stratification unit tests check that such a caller, a rule forwarding to it and a caller of a recursive one sit above the callee, and that recursion through a rule with a `not` still stratifies (#628). Tests in `tests/not_join_test.rs` check that recursion through a rule with `not`, `not-join` or `or`, directly or through another rule, returns every row along a chain, and that the `not` still removes the rows it should; evaluator unit tests check that such recursion stops at its fixpoint that `max_iterations` and `max_results` end one that does not with INT-020, and that `max_results` counts the facts every pass derives, not only the mixed rule's (#633). diff --git a/examples/perf_envelope.rs b/examples/perf_envelope.rs index a6d4f02cd9..c51ad87f40 100644 --- a/examples/perf_envelope.rs +++ b/examples/perf_envelope.rs @@ -563,6 +563,13 @@ fn shapes(e: usize, tx_half: u64, hot_tx_half: u64) -> Vec { query: "[:find ?g (count ?e) :where [?e :group ?g]]".into(), rows: 100.min(e), }, + // #547: a window over every row of an attribute, held until the + // input ends. + Shape { + name: "window", + query: "[:find ?e (rank :over (:order-by ?a)) :where [?e :age ?a]]".into(), + rows: e, + }, Shape { name: "hot_current", query: "[:find ?v :where [:hot :counter ?v]]".into(), diff --git a/src/query/datalog/aggregate.rs b/src/query/datalog/aggregate.rs index 5ce24f979c..7ada445f5c 100644 --- a/src/query/datalog/aggregate.rs +++ b/src/query/datalog/aggregate.rs @@ -3,7 +3,7 @@ //! does not depend on the order of its input. use super::functions::{AggImpl, Builtin, FunctionRegistry, UdfFinaliseFn, UdfStepFn}; -use super::types::{FindSpec, WindowSpec}; +use super::types::{FindSpec, Order, WindowFunc, WindowSpec}; use crate::error::{ErrorCode, err_coded}; use crate::graph::types::Value; use anyhow::Result; @@ -591,6 +591,105 @@ impl Running { } } +/// The value of each window of `find` for each row (spec §4), one list per +/// window in `:find` order, by row position. `rows` holds each row's +/// values of the [`named_vars`] of `find`, which hold every variable a +/// window reads. +/// +/// Each partition (by `Value`'s `Ord`) is sorted by its `:order-by` value +/// under [`value_order`], then by the named variables, then by position +/// (spec §4.1). Rows with order-equal `:order-by` values are peers: `rank` +/// is equal for them, and a running aggregate gives every peer its value at +/// the last peer (spec §4.2). Used by the executor and the engine. +pub(crate) fn windows( + find: &[FindSpec], + rows: &[Vec], + registry: &FunctionRegistry, +) -> Result>> { + static NULL: Value = Value::Null; + let named = named_vars(find); + let col = |var: &str| named.iter().position(|v| v == var); + let read = |r: usize, c: Option| { + rows.get(r) + .zip(c) + .and_then(|(row, c)| row.get(c)) + .unwrap_or(&NULL) + }; + let mut out = Vec::new(); + for spec in find { + let FindSpec::Window(ws) = spec else { + continue; + }; + let var = ws.var.as_deref().and_then(col); + let order = col(&ws.order_by); + let mut partitions: BTreeMap<&Value, Vec> = BTreeMap::new(); + for r in 0..rows.len() { + let part = ws.partition_by.as_deref().and_then(col); + partitions.entry(read(r, part)).or_default().push(r); + } + + let mut values = vec![Value::Null; rows.len()]; + for mut keyed in partitions.into_values() { + keyed.sort_by(|&a, &b| { + let by_key = match ws.order { + Order::Asc => value_order(read(a, order), read(b, order)), + Order::Desc => value_order(read(b, order), read(a, order)), + }; + by_key + .then_with(|| { + rows.get(a) + .into_iter() + .flatten() + .zip(rows.get(b).into_iter().flatten()) + .map(|(x, y)| value_order(x, y)) + .find(|o| o.is_ne()) + .unwrap_or(Ordering::Equal) + }) + .then(a.cmp(&b)) + }); + + let mut running = match ws.func { + WindowFunc::Rank | WindowFunc::RowNumber => None, + _ => Some(Running::new(ws, registry)?), + }; + let mut start = 0; + while let Some(&first) = keyed.get(start) { + let end = keyed + .iter() + .skip(start + 1) + .position(|&r| value_order(read(r, order), read(first, order)).is_ne()) + .map_or(keyed.len(), |n| start + 1 + n); + let peers = keyed.get(start..end).unwrap_or(&[]); + if let Some(acc) = running.as_mut() { + for &r in peers { + acc.step(read(r, var)); + } + } + for (pos, &r) in (start..end).zip(peers) { + let value = match (&running, &ws.func) { + (Some(acc), _) => acc.value(), + (None, WindowFunc::RowNumber) => position(pos)?, + (None, _) => position(start)?, + }; + if let Some(v) = values.get_mut(r) { + *v = value; + } + } + start = end; + } + } + out.push(values); + } + Ok(out) +} + +/// The 1-based position `pos + 1` as an integer. +fn position(pos: usize) -> Result { + i64::try_from(pos + 1) + .map(Value::Integer) + .map_err(|_| err_coded!(ErrorCode::Int032, "row number overflow")) +} + /// The variables a window's tie-break reads (spec §2, "named variables"), /// in `:find` order, each once. pub(crate) fn named_vars(find: &[FindSpec]) -> Vec { diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 7064c71ad0..6dab13390d 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -1,12 +1,12 @@ -use super::aggregate::{Agg, Groups, Running, finish_groups, named_vars, value_order}; +use super::aggregate::{Agg, Groups, finish_groups, named_vars, value_order, windows}; use super::evaluator::{StratifiedEvaluator, evaluate_not_join}; use super::functions::FunctionRegistry; use super::matcher::{PatternMatcher, edn_to_entity_id, edn_to_value}; use super::optimizer; use super::rules::RuleRegistry; use super::types::{ - AsOf, AttributeSpec, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, Order, - Pattern, Rule, Transaction, UnaryOp, ValidAt, WhereClause, WindowFunc, + AsOf, AttributeSpec, BinOp, DatalogCommand, DatalogQuery, EdnValue, Expr, FindSpec, Pattern, + Rule, Transaction, UnaryOp, ValidAt, WhereClause, WindowFunc, }; use crate::error::{ErrorCode, bail_coded, err_coded}; use crate::graph::FactStorage; @@ -1735,119 +1735,38 @@ fn compute_aggregation( } /// Compute window function values for each row and store under `"__win_{i}"`. -/// Modifies `bindings` in place; rows keep their order. -/// -/// Each partition (by `Value`'s `Ord`) is sorted by its `:order-by` value -/// under [`value_order`], then by the named variables, then by input -/// position (#547 spec §4.1). Rows with order-equal `:order-by` values are -/// peers: `rank` is equal for them, and a running aggregate gives every -/// peer its value at the last peer (spec §4.2). +/// Modifies `bindings` in place; rows keep their order. The values come +/// from [`windows`], over each binding's named variables (`nil` when +/// absent). fn apply_window_functions( bindings: &mut [Binding], find_specs: &[FindSpec], registry: &FunctionRegistry, ) -> Result<()> { let named = named_vars(find_specs); - let read = |b: &Binding, var: &str| b.get(var).cloned().unwrap_or(Value::Null); - // Each row's named-variable values, for the tie-break. - let tiebreak: Vec> = bindings + let rows: Vec> = bindings .iter() - .map(|b| named.iter().map(|v| read(b, v)).collect()) + .map(|b| { + named + .iter() + .map(|v| b.get(v).cloned().unwrap_or(Value::Null)) + .collect() + }) .collect(); - - for (i, spec) in find_specs.iter().enumerate() { - let FindSpec::Window(ws) = spec else { - continue; - }; + let positions = find_specs + .iter() + .enumerate() + .filter(|(_, s)| matches!(s, FindSpec::Window(_))) + .map(|(i, _)| i); + for (i, values) in positions.zip(windows(find_specs, &rows, registry)?) { let key = format!("__win_{}", i); - - let mut partitions: std::collections::BTreeMap> = - std::collections::BTreeMap::new(); - for (row, binding) in bindings.iter().enumerate() { - let part = ws - .partition_by - .as_ref() - .map_or(Value::Null, |pv| read(binding, pv)); - partitions.entry(part).or_default().push(row); - } - - let mut out: Vec<(usize, Value)> = Vec::with_capacity(bindings.len()); - for rows in partitions.into_values() { - let mut keyed: Vec<(Value, usize)> = rows - .into_iter() - .filter_map(|r| bindings.get(r).map(|b| (read(b, &ws.order_by), r))) - .collect(); - keyed.sort_by(|(a, ra), (b, rb)| { - let by_key = match ws.order { - Order::Asc => value_order(a, b), - Order::Desc => value_order(b, a), - }; - by_key - .then_with(|| { - let (ta, tb) = (tiebreak.get(*ra), tiebreak.get(*rb)); - ta.into_iter() - .flatten() - .zip(tb.into_iter().flatten()) - .map(|(x, y)| value_order(x, y)) - .find(|o| o.is_ne()) - .unwrap_or(std::cmp::Ordering::Equal) - }) - .then(ra.cmp(rb)) - }); - - let mut running = match ws.func { - WindowFunc::Rank | WindowFunc::RowNumber => None, - _ => Some(Running::new(ws, registry)?), - }; - let mut start = 0; - while start < keyed.len() { - let peers_end = keyed - .iter() - .skip(start + 1) - .position(|(k, _)| { - keyed - .get(start) - .is_none_or(|(s, _)| value_order(k, s).is_ne()) - }) - .map_or(keyed.len(), |n| start + 1 + n); - let peers = keyed.get(start..peers_end).unwrap_or(&[]); - if let Some(acc) = running.as_mut() { - for (_, r) in peers { - let v = ws - .var - .as_ref() - .and_then(|var| bindings.get(*r).and_then(|b| b.get(var))) - .unwrap_or(&Value::Null); - acc.step(v); - } - } - for (pos, (_, r)) in (start..peers_end).zip(peers) { - let value = match (&running, &ws.func) { - (Some(acc), _) => acc.value(), - (None, WindowFunc::RowNumber) => position(pos)?, - (None, _) => position(start)?, - }; - out.push((*r, value)); - } - start = peers_end; - } - } - for (r, value) in out { - if let Some(b) = bindings.get_mut(r) { - b.insert(key.clone(), value); - } + for (b, v) in bindings.iter_mut().zip(values) { + b.insert(key.clone(), v); } } Ok(()) } -/// The 1-based position `pos + 1` as an integer. -fn position(pos: usize) -> Result { - i64::try_from(pos + 1) - .map(Value::Integer) - .map_err(|_| err_coded!(ErrorCode::Int032, "row number overflow")) -} - /// Project binding maps to output rows in find-spec order. fn project_find_specs(bindings: &[Binding], find_specs: &[FindSpec]) -> Vec> { let mut results = Vec::new(); diff --git a/src/query/engine/filter.rs b/src/query/engine/filter.rs index addac842a6..436838fbc1 100644 --- a/src/query/engine/filter.rs +++ b/src/query/engine/filter.rs @@ -32,6 +32,7 @@ impl Apply { Step::Union(_) => "Union", Step::Distinct(_) => "Distinct", Step::Aggregate { .. } => "Aggregate", + Step::Window { .. } => "Window", }; Apply { child, @@ -134,7 +135,8 @@ fn apply(step: &Step, mut batch: Batch, ctx: &mut Ctx<'_>) -> Result { | Step::Anti(_) | Step::Union(_) | Step::Distinct(_) - | Step::Aggregate { .. } => {} + | Step::Aggregate { .. } + | Step::Window { .. } => {} } Ok(batch) } diff --git a/src/query/engine/mod.rs b/src/query/engine/mod.rs index 52382b5abd..5a4fa2d69d 100644 --- a/src/query/engine/mod.rs +++ b/src/query/engine/mod.rs @@ -23,6 +23,7 @@ mod seed; #[cfg(all(test, not(target_arch = "wasm32")))] mod tests; mod union; +mod window; use crate::error::{ErrorCode, err_coded}; use crate::graph::storage::Snapshot; @@ -169,6 +170,9 @@ pub(crate) fn build(source: plan::Source, steps: Vec) -> Box Box::new(aggregate::Aggregate::new(root, groups, aggs, zero_row)), + plan::Step::Window { find, named, keep } => { + Box::new(window::Window::new(root, find, named, keep)) + } step => Box::new(filter::Apply::new(root, step)), }; } diff --git a/src/query/engine/plan.rs b/src/query/engine/plan.rs index 1b2091d9b8..a8bc87ef26 100644 --- a/src/query/engine/plan.rs +++ b/src/query/engine/plan.rs @@ -23,6 +23,7 @@ use super::cell::Scalar; use crate::graph::types::{EntityId, Value}; +use crate::query::datalog::aggregate::named_vars; use crate::query::datalog::executor::Binders; use crate::query::datalog::matcher::edn_to_entity_id; use crate::query::datalog::optimizer; @@ -147,6 +148,14 @@ pub(crate) enum Step { /// and `count-distinct`s and no plain `:find` variable. zero_row: bool, }, + /// The last step of a query with windows (#547 spec §4): each row once, + /// in input order, holding its cells at `keep` and then the value of + /// each window of `find`, over the named variables at `named`. + Window { + find: Vec, + named: Vec, + keep: Vec, + }, } /// A `not` / `not-join` body (#546 spec §4). @@ -328,14 +337,17 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { // 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()); + // The column of each `:find` element that is not a window. + let mut cols: Vec> = Vec::with_capacity(query.find.len()); let aggregate = query .find .iter() .any(|s| matches!(s, FindSpec::Aggregate { .. })); + let window = query.find.iter().any(|s| matches!(s, FindSpec::Window(_))); if aggregate { // The rows of `Aggregate`: the grouping cells (the plain variables - // in `:find` order, then `:with`), then the aggregates. + // in `:find` order, then `:with`), then the aggregates. With + // windows, `:with` does not group, as on the executor. let plain: Vec<&String> = query .find .iter() @@ -344,8 +356,9 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { _ => None, }) .collect(); + let with: &[String] = if window { &[] } else { &query.with_vars }; let mut groups = Vec::new(); - for var in plain.iter().copied().chain(&query.with_vars) { + for var in plain.iter().copied().chain(with) { groups.push(slot(var)?); } let (mut next_plain, mut next_agg) = (0, groups.len()); @@ -353,16 +366,15 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { for spec in &query.find { match spec { FindSpec::Variable(_) => { - find.push(next_plain); + cols.push(Some(next_plain)); next_plain += 1; } FindSpec::Aggregate { func, var } => { - find.push(next_agg); + cols.push(Some(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, + FindSpec::Window(_) => cols.push(None), } } let zero_row = plain.is_empty() @@ -376,12 +388,52 @@ pub(crate) fn plan(query: &DatalogQuery) -> Option { }); } else { for spec in &query.find { - let FindSpec::Variable(var) = spec else { - return None; - }; - find.push(slot(var)?); + cols.push(match spec { + FindSpec::Variable(var) => Some(slot(var)?), + _ => None, + }); } } + let mut find = Vec::with_capacity(query.find.len()); + if window { + // A named variable's column: in an aggregate query, the plain + // variable's column of `Aggregate` (the parser allows no other, + // PRS-082); otherwise its slot. + let column = |var: &String| { + if aggregate { + query + .find + .iter() + .zip(&cols) + .find(|(s, _)| matches!(s, FindSpec::Variable(v) if v == var)) + .and_then(|(_, c)| *c) + } else { + slot(var) + } + }; + let named = named_vars(&query.find) + .iter() + .map(column) + .collect::>>()?; + let keep: Vec = cols.iter().flatten().copied().collect(); + let (mut next_kept, mut next_window) = (0, keep.len()); + for c in &cols { + if c.is_some() { + find.push(next_kept); + next_kept += 1; + } else { + find.push(next_window); + next_window += 1; + } + } + b.steps.push(Step::Window { + find: query.find.clone(), + named, + keep, + }); + } else { + find = cols.into_iter().collect::>>()?; + } let mut plan = b.finish()?; plan.find = find; plan.vars = query.find.iter().map(FindSpec::display_name).collect(); diff --git a/src/query/engine/tests.rs b/src/query/engine/tests.rs index 6ba298cf82..e2c8ae8faf 100644 --- a/src/query/engine/tests.rs +++ b/src/query/engine/tests.rs @@ -434,11 +434,7 @@ fn engine_reads_many_batches() { fn other_queries_stay_on_the_executor() { let db = Minigraf::in_memory().unwrap(); write_round(&db, 0); - for q in [ - "(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]])", - ] { + for q in ["(query [:find ?e :as-of \"2099-01-01T00:00:00Z\" :where [?e :person/name ?n]])"] { let before = runs(); db.execute(q).unwrap(); assert_eq!(runs(), before, "query stayed on the executor"); @@ -1577,3 +1573,161 @@ fn grouped_aggregate_orders_groups_and_fails_in_a_later_group() { }; assert!(results.is_empty(), "the group with no value is dropped"); } + +/// Window shapes (#547 PR 3): every built-in window over each kind of +/// value, partitions by keywords, refs, booleans, floats (`-0.0` and `0.0` +/// one partition) and long strings, ties broken by the named variables, +/// `:desc`, and windows over an aggregate's groups. +fn windows() -> Vec<(&'static str, &'static str)> { + vec![ + ( + "?e (row-number :over (:order-by ?g))", + "[?e :person/age ?g]", + ), + ( + "?e ?g (rank :over (:order-by ?g :desc)) (sum ?g :over (:order-by ?g))", + "[?e :person/age ?g]", + ), + ( + "?s (count ?e :over (:partition-by ?s :order-by ?n)) (min ?n :over (:partition-by ?s :order-by ?n))", + "[?e :person/status ?s] [?e :person/name ?n]", + ), + ( + "?f (max ?b :over (:partition-by ?f :order-by ?b :desc))", + "[?e :person/friend ?f] [?e :person/bio ?b]", + ), + ( + "?x (sum ?x :over (:order-by ?x)) (avg ?x :over (:order-by ?x)) (row-number :over (:partition-by ?x :order-by ?x))", + "[?e :person/score ?x]", + ), + ( + "?ok ?k (rank :over (:partition-by ?ok :order-by ?k))", + "[?e :person/ok ?ok] [?e :person/alias ?k]", + ), + ( + "?v (count ?v :over (:order-by ?v)) (min ?v :over (:order-by ?v)) (max ?v :over (:order-by ?v))", + "[?e ?a ?v]", + ), + ( + "?n (row-number :over (:order-by ?n))", + "[?e :person/null ?n]", + ), + ( + "?s (count ?e) (rank :over (:order-by ?s :desc))", + "[?e :person/status ?s]", + ), + ( + "?f (sum ?g) (sum ?f2 :over (:order-by ?f2)) ?f2", + "[?e :person/friend ?f] [?e :person/age ?g] [?e :person/age ?f2]", + ), + ( + "?s (sum ?g) (row-number :over (:order-by ?s)) :with ?e", + "[?e :person/status ?s] [?e :person/age ?g]", + ), + ] +} + +fn check_windows(db: &Minigraf) -> usize { + let tx = db.current_tx_count(); + let mut n = 0; + for (find, clauses) in windows() { + for t in temporals(tx) { + n += rows(db, &format!("(query [:find {find} {t} :where {clauses}])")); + } + } + n +} + +#[test] +fn windows_match_executor() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("win.graph"); + { + let db = Minigraf::open(&path).unwrap(); + for round in 0..3 { + write_round(&db, round); + } + assert!(check_windows(&db) > 0, "some rows"); + db.checkpoint().unwrap(); + write_round(&db, 3); + check_windows(&db); + } + let db = Minigraf::open(&path).unwrap(); + check_windows(&db); +} + +/// `Window` returns each input row once, in input order, over several +/// batches; every row of a partition sees the whole partition, and peers +/// share a running value (#547 spec §4.2). +#[test] +fn window_returns_every_row_in_input_order() { + let db = Minigraf::in_memory().unwrap(); + let facts: String = (0..3000) + .map(|i| format!("[:e{i} :k {}] [:e{i} :n {}]", i % 3, i / 2)) + .collect(); + db.execute(&format!("(transact [{facts}])")).unwrap(); + let mut cursor = db + .query( + "(query [:find ?e (sum ?n :over (:partition-by ?k :order-by ?n)) \ + (row-number :over (:order-by ?n)) :where [?e :k ?k] [?e :n ?n]])", + ) + .unwrap(); + let mut rows = cursor.next_batch(1000).unwrap().expect("rows").into_rows(); + let c = cursor.counters(); + let window = c.iter().find(|c| c.op == "Window").expect("a Window"); + assert_eq!(window.rows_in, 3000, "the whole input is held"); + assert_eq!(window.batches, 1, "one batch passed on so far"); + while let Some(batch) = cursor.next_batch(1000).unwrap() { + rows.extend(batch.into_rows()); + } + assert_eq!(rows.len(), 3000); + + let mut numbers: Vec = rows + .iter() + .map(|r| match r.get(2) { + Some(crate::Value::Integer(n)) => *n, + _ => -1, + }) + .collect(); + numbers.sort_unstable(); + assert_eq!( + numbers, + (1..=3000).collect::>(), + "each row numbered once" + ); + // A partition's last peers' running sum is the sum of the partition. + let total = |k: i64| -> i64 { (0..3000).filter(|i| i % 3 == k).map(|i| i / 2).sum() }; + let max = rows + .iter() + .filter_map(|r| match r.get(1) { + Some(crate::Value::Integer(n)) => Some(*n), + _ => None, + }) + .max(); + assert_eq!( + max, + (0..3).map(total).max(), + "the last peers see the whole partition" + ); +} + +/// Windows run on the engine, over an aggregate's groups too, and an empty +/// input gives no row. +#[test] +fn window_routing() { + let db = Minigraf::in_memory().unwrap(); + write_round(&db, 0); + for q in [ + "(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]])", + ] { + assert!(rows(&db, q) > 0, "rows"); + } + assert_eq!( + rows( + &db, + "(query [:find ?e (rank :over (:order-by ?n)) :where [?e :person/name ?n] [(= ?n \"none\")]])", + ), + 0 + ); +} diff --git a/src/query/engine/window.rs b/src/query/engine/window.rs new file mode 100644 index 0000000000..fa91192166 --- /dev/null +++ b/src/query/engine/window.rs @@ -0,0 +1,135 @@ +//! `Window` (#547 spec §4): each input row once, in input order, with the +//! value of each window of `:find`. +//! +//! A window's value depends on every row of its partition, so `Window` +//! holds its input: each row's passed-on cells, and the values of its +//! named variables (spec §2), which the windows sort and partition by and +//! accumulate. When the input ends, the values come from +//! [`windows`](crate::query::datalog::aggregate::windows), the code the +//! executor runs. + +use super::batch::Batch; +use super::cell::{Cell, Scalar}; +use super::project::value; +use super::{BATCH_ROWS, Counters, Ctx, Operator}; +use crate::graph::types::Value; +use crate::query::datalog::aggregate::windows; +use crate::query::datalog::types::FindSpec; +use anyhow::Result; + +pub(crate) struct Window { + child: Box, + find: Vec, + /// The slots of the named variables. + named: Vec, + /// The slots passed on, before the windows' columns. + keep: Vec, + /// Each input row's cells at `keep`, in input order. + cells: Vec>, + /// Each input row's values of the named variables. + values: Vec>, + /// The finished rows, last first, once the input has ended. + out: Option>>, + counters: Counters, +} + +impl Window { + pub(crate) fn new( + child: Box, + find: Vec, + named: Vec, + keep: Vec, + ) -> Self { + Window { + child, + find, + named, + keep, + cells: Vec::new(), + values: Vec::new(), + out: None, + counters: Counters::new("Window"), + } + } + + /// Hold 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)).unwrap_or(&null); + for i in 0..batch.len { + self.cells + .push(self.keep.iter().map(|&s| cell(s, i).clone()).collect()); + self.values.push( + self.named + .iter() + .map(|&s| value(cell(s, i), ctx)) + .collect::>>()?, + ); + } + Ok(()) + } + + /// Every row, in input order, with its windows' cells. + fn finish(&mut self, ctx: &mut Ctx<'_>) -> Result>> { + let values = std::mem::take(&mut self.values); + let mut rows = std::mem::take(&mut self.cells); + for column in windows(&self.find, &values, ctx.functions)? { + for (row, v) in rows.iter_mut().zip(&column) { + row.push(Cell::of_value(ctx.ids, ctx.keys, v)?); + } + } + rows.reverse(); + Ok(rows) + } +} + +impl Operator for Window { + 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.keep.len() + + self + .find + .iter() + .filter(|s| matches!(s, FindSpec::Window(_))) + .count(); + 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.cells.clear(); + self.values.clear(); + self.out = None; + self.child.rewind(seed); + } + + fn close(&mut self) { + self.cells = Vec::new(); + self.values = Vec::new(); + self.out = Some(Vec::new()); + self.child.close(); + } + + fn counters(&self, out: &mut Vec) { + out.push(self.counters); + self.child.counters(out); + } +} From 1cc8ff83b7da9963c25dc2ed0d15dd3aa4db8f9c Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 15:47:19 +0530 Subject: [PATCH 2/5] test(engine): window shapes with a repeated :find variable, an or-bound order key, a pseudo-attribute (#547) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- src/query/engine/tests.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/query/engine/tests.rs b/src/query/engine/tests.rs index e2c8ae8faf..8b0902ad55 100644 --- a/src/query/engine/tests.rs +++ b/src/query/engine/tests.rs @@ -1624,6 +1624,14 @@ fn windows() -> Vec<(&'static str, &'static str)> { "?s (sum ?g) (row-number :over (:order-by ?s)) :with ?e", "[?e :person/status ?s] [?e :person/age ?g]", ), + ( + "?g ?g (rank :over (:order-by ?g)) ?e", + "[?e :person/age ?g]", + ), + ( + "?e (row-number :over (:order-by ?k))", + "(or [?e :person/alias ?k] [?e :person/boss ?k])", + ), ] } @@ -1635,6 +1643,11 @@ fn check_windows(db: &Minigraf) -> usize { n += rows(db, &format!("(query [:find {find} {t} :where {clauses}])")); } } + n += rows( + db, + "(query [:find ?e (max ?t :over (:partition-by ?e :order-by ?t)) :any-valid-time \ + :where [?e :person/name ?n] [?e :db/tx-count ?t]])", + ); n } From 96cb8942dc4bd9daf14685415447d327191d32ad Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 16:20:16 +0530 Subject: [PATCH 3/5] docs: Window on the engine, envelope numbers (#547) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- CHANGELOG.md | 3 ++- docs/BENCHMARKS.md | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cdfcb3ddb..4eae5e3e79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,7 +79,8 @@ 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`). +- **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. 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`). +- **Window functions run on the streaming engine** (#473, part 5: #547, third PR). Queries with window functions in `:find`, alone or over an aggregate's groups, now run on the engine when their `:where` does. A `Window` operator holds each input row's returned cells and the values of the variables the windows read, then computes every window with the code the executor runs (partitions, the sort, peers) and returns the rows in input order. Measured (#394 envelope, p50 and peak RSS): `[:find ?e (rank :over (:order-by ?a)) :where [?e :age ?a]]` 41 → 48 ms and 19 → 17 MiB at 100K facts, 600 → 593 ms and 140 → 113 MiB at 1M, 7.91 s → 7.32 s and 1,257 → 1,044 MiB at 10M. The engine turns each row's ids into values twice (once for the windows, once to return the row), which costs more than it saves at 100K; it holds every row by nature, so memory grows with the input either way. 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. diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 0e35f6129e..dc772d345c 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -144,6 +144,18 @@ The pseudo-attribute pattern reads the `:db/tx-count` column that the `:name` pr 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. +### Windows on the streaming engine (#547 PR 3) + +`window` is `[:find ?e (rank :over (:order-by ?a)) :where [?e :age ?a]]` (every `:age` row: 16,666, 166,666 and 1,666,666 rows). Before PR 3 every window query ran on the executor. A/B on the same idle server, `v3` (58c19dd, with the `window` shape added) and PR 3 run in parallel on different sockets, swapping nodes between the two rounds; p50 and peak RSS, mean of the rounds. + +| Shape | 100K | 1M | 10M | +|---|---:|---:|---:| +| `window` p50, `v3` → PR 3 | 41.2 → 48.2 ms | 600 → 593 ms | 7.91 → 7.32 s | +| `window` peak RSS | 19 → 17 MiB | 140 → 113 MiB | 1,257 → 1,044 MiB | +| every other shape | unchanged | unchanged | unchanged | + +A window needs its whole partition, so `Window` holds every row and memory grows with the input. It turns each row's ids into values for the windows' sort, and the projection turns them again when the row is returned; at 100K that second conversion costs more than the engine's scan saves. + ### 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. From 06af6d2774197597f6a64514ae0a2e4e1d675c2e Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 16:25:44 +0530 Subject: [PATCH 4/5] perf(engine): a Window stream keeps its DICT lookups until it ends (#547) Window turns every row's ids into values in its first pull; the rows it returns later read the same ids again. Clearing the cache after each pull made each lookup twice. Peak memory is unchanged: the first pull already holds every lookup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- src/query/engine/ids.rs | 3 +++ src/query/engine/mod.rs | 14 ++++++++++++-- src/query/engine/tests.rs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/query/engine/ids.rs b/src/query/engine/ids.rs index b08dc463d4..5e49bb1156 100644 --- a/src/query/engine/ids.rs +++ b/src/query/engine/ids.rs @@ -9,6 +9,9 @@ //! or ident keeps its id. DICT lookups are only cached until the next pull //! ([`IdSpace::end_pull`]): a DICT id never changes, and a cache that grew //! with every row a cursor returns would hold the whole answer. +//! A stream that ends in a `Window` keeps them until it ends: the window +//! already looked up every row's ids in its first pull, and holds the whole +//! answer anyway (#547). use crate::error::{ErrorCode, err_coded}; use crate::graph::types::EntityId; diff --git a/src/query/engine/mod.rs b/src/query/engine/mod.rs index 5a4fa2d69d..2249708de4 100644 --- a/src/query/engine/mod.rs +++ b/src/query/engine/mod.rs @@ -109,6 +109,10 @@ pub(crate) struct Stream { find: Vec, vars: Vec, project: Counters, + /// Keep the DICT lookups until the stream ends: a `Window` turns every + /// row's ids into values in its first pull, and the rows it returns + /// later read the same ids again (#547). + hold_ids: bool, closed: bool, } @@ -140,6 +144,7 @@ pub(crate) fn open( find, vars, } = plan; + let hold_ids = steps.iter().any(|s| matches!(s, plan::Step::Window { .. })); let root = build(source, steps); Some(Stream { snapshot, @@ -149,6 +154,7 @@ pub(crate) fn open( find, vars, project: Counters::new("Project"), + hold_ids, closed: false, }) } @@ -191,6 +197,7 @@ impl Stream { find: vec![0], vars: vec!["?x".to_string()], project: Counters::new("Project"), + hold_ids: false, closed: false, } } @@ -203,8 +210,11 @@ impl Stream { return Ok(None); } let rows = self.pull(); - self.ids.end_pull(); - if !matches!(rows, Ok(Some(_))) { + let more = matches!(rows, Ok(Some(_))); + if !self.hold_ids || !more { + self.ids.end_pull(); + } + if !more { self.close(); } rows diff --git a/src/query/engine/tests.rs b/src/query/engine/tests.rs index 8b0902ad55..6904c7bdab 100644 --- a/src/query/engine/tests.rs +++ b/src/query/engine/tests.rs @@ -701,6 +701,36 @@ fn dict_cache_is_dropped_after_each_pull() { assert_eq!(rows, 3002); } +/// A stream that ends in a `Window` keeps its DICT lookups until it ends: +/// the window looked up every row's ids in its first pull, and the rows it +/// returns later read them from the cache (#547). +#[test] +fn window_stream_keeps_dict_cache_until_it_ends() { + let dir = tempfile::tempdir().unwrap(); + let db = Minigraf::open(dir.path().join("ids.graph")).unwrap(); + let facts: String = (0..3000) + .map(|i| format!("[:p{i} :person/age {}]", i % 7)) + .collect(); + db.execute(&format!("(transact [{facts}])")).unwrap(); + db.checkpoint().unwrap(); + let mut cursor = db + .query("(query [:find ?e (rank :over (:order-by ?a)) :where [?e :person/age ?a]])") + .unwrap(); + let mut rows = 0; + while let Some(batch) = cursor.next_batch(500).unwrap() { + rows += batch.len(); + if let Some(stream) = cursor.stream_mut() + && rows < 3000 + { + assert!(stream.ids.dict_cached() >= 3000, "every row's entity kept"); + } + } + assert_eq!(rows, 3000); + if let Some(stream) = cursor.stream_mut() { + assert_eq!(stream.ids.dict_cached(), 0, "dropped at the end"); + } +} + /// The planner's join choice (decision 3 of the #545 plan): an /// `IndexNestedLoopJoin` when the entity is bound, a `HashJoin` otherwise, /// built on the side with the smaller estimate. From c87f2b41b2ca8bde71a56d7c5f156ab103aec37c Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Tue, 20 Oct 2026 17:23:35 +0530 Subject: [PATCH 5/5] docs: window envelope numbers with the held DICT cache (#547) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PtCdzbJMSS1V8qEPaJ4jXz --- CHANGELOG.md | 2 +- docs/BENCHMARKS.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4eae5e3e79..d599d0b426 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,7 +80,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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. 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`). -- **Window functions run on the streaming engine** (#473, part 5: #547, third PR). Queries with window functions in `:find`, alone or over an aggregate's groups, now run on the engine when their `:where` does. A `Window` operator holds each input row's returned cells and the values of the variables the windows read, then computes every window with the code the executor runs (partitions, the sort, peers) and returns the rows in input order. Measured (#394 envelope, p50 and peak RSS): `[:find ?e (rank :over (:order-by ?a)) :where [?e :age ?a]]` 41 → 48 ms and 19 → 17 MiB at 100K facts, 600 → 593 ms and 140 → 113 MiB at 1M, 7.91 s → 7.32 s and 1,257 → 1,044 MiB at 10M. The engine turns each row's ids into values twice (once for the windows, once to return the row), which costs more than it saves at 100K; it holds every row by nature, so memory grows with the input either way. Other workloads unchanged. Results are unchanged (`test-oracle`). +- **Window functions run on the streaming engine** (#473, part 5: #547, third PR). Queries with window functions in `:find`, alone or over an aggregate's groups, now run on the engine when their `:where` does. A `Window` operator holds each input row's returned cells and the values of the variables the windows read, then computes every window with the code the executor runs (partitions, the sort, peers) and returns the rows in input order. Measured (#394 envelope, p50 and peak RSS): `[:find ?e (rank :over (:order-by ?a)) :where [?e :age ?a]]` 41.5 → 32.8 ms and 19 → 16 MiB at 100K facts, 601 → 434 ms and 140 → 109 MiB at 1M, 7.89 s → 5.65 s and 1,257 → 1,030 MiB at 10M. A window holds every row by nature, so memory still grows with the input. 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. diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index dc772d345c..5c9c941b5b 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -150,11 +150,11 @@ An ungrouped aggregate holds one set of accumulators, and `count` reads no value | Shape | 100K | 1M | 10M | |---|---:|---:|---:| -| `window` p50, `v3` → PR 3 | 41.2 → 48.2 ms | 600 → 593 ms | 7.91 → 7.32 s | -| `window` peak RSS | 19 → 17 MiB | 140 → 113 MiB | 1,257 → 1,044 MiB | +| `window` p50, `v3` → PR 3 | 41.5 → 32.8 ms | 601 → 434 ms | 7.89 → 5.65 s | +| `window` peak RSS | 19 → 16 MiB | 140 → 109 MiB | 1,257 → 1,030 MiB | | every other shape | unchanged | unchanged | unchanged | -A window needs its whole partition, so `Window` holds every row and memory grows with the input. It turns each row's ids into values for the windows' sort, and the projection turns them again when the row is returned; at 100K that second conversion costs more than the engine's scan saves. +A window needs its whole partition, so `Window` holds every row and memory grows with the input. It turns each row's ids into values in its first pull, for the windows' sort; the stream keeps those DICT lookups until it ends, so returning the rows does not look them up again. Without that, the first measurement of PR 3 was 17% slower than the executor at 100K (48.2 ms). ### Python FFI round trip