diff --git a/CHANGELOG.md b/CHANGELOG.md index 94519de939..17d24c591c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **An unknown aggregate or window function is an error whatever the data** (#414). Aggregate and window function names in `:find` are now resolved before the query runs: an unknown aggregate fails with the new `QRY-010` and an unknown window function with the new `QRY-011`, even on an empty database or when no row matches. Before, such a query returned no results until a row matched and then failed with `INT-029`/`INT-030`, which stay registered for internal inconsistencies only. - **One current valid-time window per fact** (#435). At any transaction time, each `(entity, attribute, value)` now has exactly one current valid-time window: the one from its latest `transact`. A later assertion of the same fact replaces the earlier window, which stays visible through `:as-of` of the earlier transaction. Before, every window ever asserted stayed live until a `retract`, so closing an open window with `(transact {:valid-from vf :valid-to D} ...)` left the open one live and `:valid-at` after `D` still found the fact. Closing, extending or reopening a window is now a plain `transact` with the new bounds; `retract` still withdraws the fact. **This changes query results for existing data:** a fact asserted in several transactions with different windows is now valid only in its latest window at the current transaction time. A fact that was true over two separate periods can no longer have both windows live at once; model each period as its own entity, or read earlier periods with `:as-of`. Asserting one fact with two different windows in one `transact` is rejected with the new `API-011`, and nothing is written. Data written before this check with two windows in one transaction keeps both. - **The `uuid` dependency no longer enables `v4`** (#439). The library only makes v5 UUIDs, so the `v4` feature and, on browser wasm, `js` are gone from its `uuid` dependency, and with them `getrandom`. A crate that called `Uuid::new_v4` only because Cargo feature unification turned `v4` on through minigraf must now enable `uuid/v4` itself. The release binary shrinks by 48 bytes. +- **Join answers no longer depend on the query plan** (#545). Two cases changed. A join on a float value now pairs `0.0` with `-0.0`, as a shared variable compared after the join key already did; before, `Value`'s hash told them apart, so the join key never paired them. NaN still equals nothing. Float constants in a pattern still match within `f64::EPSILON`. And a variable bound to a keyword by one pattern and to the ref of the entity the keyword names by another, which already joined, now returns the kind from the first of those patterns in the `:where` text. Before, it returned the kind from the pattern the planner ran first, so the answer could change with the selectivity of the other patterns, and differed under the `wasm` feature, which does not reorder. For example, with `[:alice :friend :bob]` stored as a keyword, `[:find ?b :where [?a :friend ?b] [?b :name "Bob"]]` returned the ref of `:bob`, because the planner runs the pattern with two constants first, and now returns the keyword `:bob`. An expression that binds a variable still sets its value where it runs, and later patterns keep that value. The rule covers the top-level `:where` of queries with and without rules; inside `or`, `not` and rule bodies the kinds are unchanged. ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 82dd7ecadb..13e060bc3a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -204,7 +204,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are ## Test Coverage -**1489 tests** (1479 passing, 10 ignored; unit + integration + doc). +**1500 tests** (1490 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 1d2caea753..35c603a7ec 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 1489 tests +cargo test # run 1500 tests cargo run < demos/demo_recursive.txt # recursive rules demo ``` diff --git a/docs/TEST_COVERAGE.md b/docs/TEST_COVERAGE.md index c2a8ec6bc5..ba2d2e5728 100644 --- a/docs/TEST_COVERAGE.md +++ b/docs/TEST_COVERAGE.md @@ -4,7 +4,7 @@ **Verified**: 2026-10-14 with `cargo test --quiet` -**Result**: 1,479 passing tests and 10 ignored tests (1,489 total) +**Result**: 1,490 passing tests and 10 ignored tests (1,500 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). @@ -15,6 +15,7 @@ This covers the unreleased file-format-v8 work (#287, #371): the index-key value - **Storage correctness**: packed pages, B+tree indexes and range scans, cache behavior, file-header validation, migration (including v7→v8 index rebuild and v1–v6 rejection via `STG-028`), WAL replay, checksums, corruption handling, and fault injection. - **Reliability and concurrency**: concurrent reads and writes, rollback behavior, same-process handle exclusion, cross-process locking, PID namespaces, NFS and container lock behavior, SIGKILL recovery, and queries seeing each concurrent transaction whole and reading one state for all their patterns, including while a checkpoint runs (`tests/snapshot_atomicity_test.rs`, #554, #555, #558). Generation pins (#543): a pinned generation's pages are never written by later saves or index rebuilds and are reused once the pin is dropped (by page id, `storage::persistent_facts`, `storage::pins`, `storage::page`); fact logs stay correct while checkpoints, rebuilds and concurrent writers run, and see whole transactions only (`tests/fact_log_test.rs`). Query and prepared-query cursors keep their answer and their pages across writes, checkpoints and index rebuilds, and the file stops growing once they close (`tests/cursor_test.rs`); a snapshot leaves out facts appended after it on every scan (`graph::storage`); a crash at every write point of a save with a pinned generation loses no fact and no page, and the reopened database reuses the quarantined ids (`storage::persistent_facts`); the browser withholds free pages a pinned generation may read and releases them once out of force (`storage::pins::split_released`, and a `#[wasm_bindgen_test]` with an open `BrowserDb` cursor). - **Streaming query engine** (#473, #544): every query the engine runs is also run by the existing executor under `cfg(test)` and the `test-oracle` feature, and the answers must agree (`query::engine::oracle`); CI runs the whole suite with the feature, so the model-based, property, golden-corpus and integration suites check the engine. `query::engine::tests` reaches every index choice, net-assert of pending records over committed ones, `:as-of`, valid time, long strings and reads of several batches, in memory, across checkpoints and after reopen, expression filters and bindings (including rebinding and failing expressions), pseudo-attribute columns, keyword/UUID/float constants against keywords, refs and UUID-named keywords, and checks which queries stay on the executor and that INT-026 and QRY-007 come first. Resumed `live_keys` reads equal one live read over random histories (`storage::persistent_facts`). Lazy cursors (`cursor::tests`, #544 PR 3): one pull reads one internal batch of the scan (operator counters), rows left in a batch need no pull, a closed stream reads nothing more, a filter's counters chain, and a cursor's answer is unchanged by writes and by checkpoints that free the leaves it has yet to read (file-backed) or by later writes (in memory); a read error after some rows are gathered comes on the next call, then the cursor ends (`query::engine::tests`). DICT lookups are cached for one pull only, and provisional ids keep their values across pulls (`query::engine::ids`). +- **Join rules** (`tests/join_rules_test.rs`, 10 tests; #545): a join on a float value pairs `0.0` with `-0.0`, through the hash key and as a shared variable, and a float constant still matches within epsilon; a variable bound to a keyword by one pattern and to the ref of the same entity by another returns the kind from the first pattern in `:where` text order, when the planner runs the patterns in another order, through the attribute position, before and after a rule call, and with a repeated pattern; an expression binding is kept by a later join, and a pseudo-attribute pattern never replaces a value. A unit test checks that `-0.0` and `0.0` hash alike. - **Public diagnostics**: structured parser, query, storage, WAL, API, and internal error codes; the error-code registry is checked against [`ERROR_REFERENCE.md`](ERROR_REFERENCE.md). - **Compatibility and quality**: golden-file corpus of released file formats, cross-platform format compatibility, property-based tests, long-haul smoke coverage, a weekly soak at 10M facts with a 5-hour churn (#392), XTDB/Datomic semantic compatibility, grammar conformance, and rustdoc examples. diff --git a/docs/superpowers/plans/2026-10-14-545-joins.md b/docs/superpowers/plans/2026-10-14-545-joins.md new file mode 100644 index 0000000000..5ab8ea8a54 --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-545-joins.md @@ -0,0 +1,218 @@ +# Joins (#545) — Plan + +Spec: `docs/superpowers/specs/2026-10-11-streaming-engine-design.md` §5.4, §6.1, §6.2, +§6.3 (#473, part 3 of 9). PRs target `v3`; no closing keyword for #473. #545 closes by +hand (`gh issue close`) when the last PR merges. + +| PR | Steps | Branch | +|---|---|---| +| 1 | 1–3: the executor's join rules settled (floats, keyword or ref), `CHANGELOG.md` | `feat/545-join-rules` | +| 2 | 4–9: join keys, `IndexNestedLoopJoin`, `HashJoin`, planner v2, oracle tests | `feat/545-joins` | +| 3 | 10–13: pseudo-attributes across joins, `:db/valid-at`, measurement, docs | `feat/545-pseudo-joins` | + +Each PR leaves `v3` with no unused code, and updates the test counts and `CHANGELOG.md` +for what it ships. + +## Today's join rules + +`PatternMatcher::join_with_pattern` (`src/query/datalog/matcher.rs`) joins the rows so far +with the next pattern in `optimizer::plan` order, in one of two ways: + +- **Hash path.** Taken when the pattern's entity, or else its value, is a variable the + rows already bind (the join variable). The pattern is matched against every fact + without the rows, and the matches are hashed on `normalize_join_value` of the join + variable (a keyword becomes the ref of the entity it names, `edn_to_entity_id`). Other + shared variables are compared after the same normalisation. A merged row keeps the + row's value for every variable the row binds. +- **Nested-loop path.** Taken otherwise: no shared variable, or one in the attribute + position only, and for pseudo-attribute patterns. Bound variables are substituted into + the pattern as constants (`apply_binding_to_component`) and matched with the constant + rules of `match_component`: a keyword constant matches the keyword or the ref of the + entity it names, a UUID constant a ref or a keyword naming it, a float constant any + float within `f64::EPSILON`. A substituted variable is not rebound, so the row's value + is kept. + +Both paths compare `norm(a) == norm(b)`, with `norm` the keyword-to-ref normalisation. +The nested-loop path never compares a bound float: a bound entity or value variable +always takes the hash path, and the attribute position holds keywords only. Two answers +still depend on the plan (which differs under the `wasm` feature, where patterns are not +reordered): + +- **Floats.** `Value`'s `Hash` hashes `-0.0` and `0.0` differently although `==` holds + for them, so a hash join on a float key never pairs them, while the same pair as a + non-key shared variable (compared with `==`) does. Elsewhere bound floats are compared + within `f64::EPSILON` only where a `not` / `not-join` body substitutes them as + constants (`substitute_pattern`), which is #546's anti-join. +- **Keyword or ref.** A variable bound to a keyword by one pattern and to the ref of the + same entity by another returns the kind of whichever pattern ran first. In the + nested-loop path this happens through the attribute position: a variable bound to a + ref matches the attribute whose keyword names that entity. + +## Design decisions not fixed by the spec + +Settled with the maintainer on 2026-10-14. + +1. **Float joins use IEEE `==`** (§5.4). Two bound floats are join-equal when `==` holds: + `0.0` equals `-0.0`, and NaN equals nothing, NaN included. A float *constant* in a + pattern keeps the `f64::EPSILON` match (spec §5.4, unchanged). In the executor this + is a fix to `Value`'s `Hash`, which breaks the `Hash`/`Eq` contract for `-0.0` today: + it now hashes `-0.0` as `0.0`. That covers every hash-keyed comparison of values: the + pattern hash join, and the `not`, `not-join` and `or` keys. The epsilon comparison + of bound floats substituted into `not` / `not-join` bodies is #546's to settle with + the same rule (comment on #546). +2. **Keyword or ref: the first pattern in `:where` text order** (§5.4). When a variable + is bound by several patterns, its value comes from the first of them in the query + text. An expression binding (`[(f …) ?v]`) still overwrites the variable where + `optimizer::plan` places it, and later joins keep the expression's value. The rule + applies to the top-level `:where` of a query (the plan loops of + `execute_query_on_executor` and `execute_query_with_rules`). `or` branches, `not` + bodies and rule bodies keep today's rule; #546 and #548 decide theirs when they move + to the engine. + Pseudo-attribute patterns never replace a value: they read metadata of an entity + the query has bound, and bind their entity variable only when nothing has. +3. **`IndexNestedLoopJoin` probes the entity position only.** The join is an + `IndexNestedLoopJoin` when the inner pattern's entity is a variable the outer rows + bind: one EAVT range per outer row, committed and pending. Every other join, including + a join on the value or attribute position and a join with no shared variable (a cross + product), is a `HashJoin`. Deviation from spec §6.3, which probes any position an + index covers. Two reasons: the pending store has EAVT and AEVT indexes but no AVET, + so a value probe reads the attribute's whole pending range once per outer row (every + fact of an in-memory database); and a ref probe into the value position must also + find the keyword values that name the entity, which no index holds. +4. **Pseudo-attributes keep today's plan-dependent rule, and a follow-up issue tracks + it.** `:db/valid-from`, `:db/valid-to`, `:db/tx-count` and `:db/tx-id` read the fact + of the last real pattern, in `optimizer::plan` order, that matched the same entity + (the matcher's hidden `__f*_` keys, overwritten by each match). The engine + reproduces that. `:db/valid-at` joins with every visible fact of the entity, one row + per fact. The issue is filed with PR 3. +5. **Join keys** (§5.4). Two cells are join-equal when: + - both are `Eid`, or both `Iid`: the same id; + - one is `Iid(k)` and the other `Eid(e)`: `e` is the id of `edn_to_entity_id(k)` + (`IdSpace::keyword_eid`, a DICT id or a provisional one, cached like other DICT + lookups); + - both are `Val`: the same scalar, floats by decision 1. Long strings are one form: + `Scan` turns a pending string over 64 bytes into `Long(vref)` when the committed + value pages hold it (`KeySource::long_value_ref`), so equal long strings are equal + cells (the #544 plan, decision 2, left this to #545). + The planner normalises a slot's `Iid` cells only where the two sides can hold + different kinds: an entity position holds `Eid`, an attribute position `Iid`, a value + position or an expression binding either. +6. **Which cell a join keeps** (decision 2). The planner records, for each slot, the + `:where` index of the pattern that bound it (or "expression"). When a pattern earlier + in the text joins on that slot, the output row takes the pattern's cell; otherwise + the outer row's. Static per join, no per-row cost. +7. **`HashJoin` build side.** The side with the smaller estimate: `optimizer`'s + `pattern_cost` for the inner pattern against the smallest `pattern_cost` of the outer + patterns (`branch_cost`). Ties build on the inner pattern. A key cell that contains a + NaN never matches, so such rows are dropped on both sides. Bytes held are counted + with #549. +8. **Join order** stays `optimizer::plan`'s (selectivity order; source order under + `wasm`, spec §6.3). With decisions 1 and 2 the answer no longer depends on it, except + for pseudo-attributes (decision 4). +9. **`PreparedQuery` plans per execution**, as in #544 (decision 10 there). Planning is + a walk over the clauses; caching the operator tree with bind values as parameters + waits for a measurement that shows planning matters. Deviation from spec §6.3's last + paragraph, recorded on the issue. + +## Steps + +### 1. Float joins in the executor (PR 1) +- `Value`'s `Hash`: `-0.0` hashes as `0.0` (decision 1). +- Unit test in `types.rs`: equal values hash equally, `-0.0` and `0.0` included. +- Integration tests (`tests/join_rules_test.rs`): a join on a float value pairs `0.0` + with `-0.0`, as the join key and as a shared variable after an entity key; a float + constant still matches within epsilon. (A NaN cannot be stored: the parser has no + NaN literal.) +- Comment on #546: the substituted-float epsilon in `not` bodies. + +### 2. Keyword or ref by `:where` order in the executor (PR 1) +- `PatternMatcher::match_with_hint_seeded` takes the set of variables the pattern + rebinds (decision 2). The hash path inserts the pattern's value for them; the + nested-loop path takes the fact's value at the variable's first position (entity, + attribute, value). +- The two executor plan loops track, per variable, the `:where` index of its binding + pattern (expressions mark it as fixed) and pass the set. +- Integration tests: `[?a :friend ?b] [?b :name "Bob"]` (keyword-valued `:friend`) + returns the keyword whatever the plan, and the reversed text the ref; the same through + the attribute position and with a rule call; an expression's value is kept by a later, + text-earlier pattern. They also pass with `--features wasm` (no reordering). + +### 3. PR 1 checks +- `CHANGELOG.md` (v3.0.0, Breaking changes): the two rules and the queries whose answers + change. +- `cargo fmt`, clippy (native, `wasm`, `browser`/wasm32), `cargo test`, + `cargo test --features test-oracle`. + +### 4. Join keys (PR 2) +- `IdSpace::keyword_eid`; `Scan` canonicalises pending long strings (decision 5). +- `cell::join_eq` and a hashable `JoinKey` (decisions 1, 5). +- Unit tests: keyword vs ref of the same entity (DICT and provisional), long strings + committed vs pending, floats. + +### 5. `IndexNestedLoopJoin` (PR 2) +- `src/query/engine/join.rs`. `Scan` takes a seed row: its `Term::Eq` positions compare + with the seed's cells by `join_eq` (a new `Term::Join(slot)`, keeping `Term::Eq` for a + variable repeated inside one pattern, which compares exactly as `match_fact_against_pattern` + does), its entity range is the probe, and it keeps or replaces each joined cell by + decision 6. A provisional entity id has only pending facts. +- Per outer batch: probes in row order; an outer row with many matches resumes the inner + scan across output batches. `close` closes the outer side and the current probe. +- Counters: outer rows in, inner keys and facts read, rows out. + +### 6. `HashJoin` (PR 2) +- Builds on one side (decision 7), streams the other, emits rows in the streamed side's + order. An empty key is a cross product. + +### 7. Planner v2 (PR 2) +- Eligible: every clause is a pattern with a real attribute, an expression, or a + pseudo-attribute pattern on the first pattern's entity (#544's shapes); `:find` plain + variables; as #544 otherwise. Pseudo-attribute patterns anywhere else wait for PR 3. +- Clauses in `optimizer::plan` order; the first pattern is a `Scan`, each later pattern an + `IndexNestedLoopJoin` or a `HashJoin` (decision 3), each expression a `Filter`/`Bind`. + +### 8. Oracle tests (PR 2) +- `tests/engine_oracle_test.rs`: two- and three-pattern joins on entity, value and + attribute positions; cross products; keyword vs ref in both text orders; floats + `0.0`/`-0.0`/NaN; long strings committed vs pending; pending shadowing committed in + the inner pattern; in-memory and file-backed, before and after a checkpoint and a + reopen; `:as-of` and `:valid-at` on joins. +- `cargo test --features test-oracle` over the whole suite: most multi-pattern queries in + the existing suites now run on the engine. + +### 9. PR 2 checks +- As step 3, plus binary size (`binary-size.yml`) and the #394 envelope at 100K/1M on the + bench machine for the three join shapes and the #379 point queries. + +### 10. Pseudo-attributes across joins (PR 3) +- Each real pattern's scan fills metadata columns only when a pseudo-attribute pattern + may read it. A pseudo-attribute pattern reads, per row, the metadata of the last real + pattern before it in plan order whose entity cell is join-equal to its entity + (decision 4). +- Eligible when its entity term is the entity term of a real pattern planned before it + (the matcher's fast path then always applies), or when no real pattern is planned + before it (it then matches every visible fact of the entity: a `Scan` of `[e _ _]` + with the metadata column). Other shapes stay on the executor. +- `:db/valid-at`: a join with `[e _ _]` and a constant column (the query's valid time, + `Null` under `:any-valid-time`). + +### 11. Follow-up issue (PR 3) +- Pseudo-attribute metadata depends on plan order (decision 4); milestone v3.0.0, label + `query`. + +### 12. Measurement (PR 3) +- #394 envelope at 100K, 1M and 10M on the bench machine, idle: the join shapes + (`follows_name`, `manager_peers`, `group_members`), point queries, peak RSS. + `docs/BENCHMARKS.md` rows. + +### 13. Docs (PR 3) +- `CHANGELOG.md`: multi-pattern queries stream. +- `CLAUDE.md` module list (`join.rs`), test count; `ROADMAP.md`; `docs/TEST_COVERAGE.md`; + `README.md` count. +- Docs site (`../minigraf-docs`): `content/architecture.md` query-engine section, and + `content/datalog-reference.md` for the join rules (decisions 1, 2), under + `@since v3.0.0`. +- Comment on #545 for decisions 3 and 9. + +## Bindings + +No public API change and no new error code, so no binding cascade. diff --git a/src/graph/types.rs b/src/graph/types.rs index 6f6d14af8c..9db81ca514 100644 --- a/src/graph/types.rs +++ b/src/graph/types.rs @@ -96,6 +96,10 @@ impl std::hash::Hash for Value { Value::Float(f) => { if f.is_nan() { 0_u8.hash(state); + } else if *f == 0.0 { + // `-0.0 == 0.0`, so both must hash alike (#545). + 2_u8.hash(state); + 0_u64.hash(state); } else if f.is_sign_negative() { 1_u8.hash(state); (-f).to_bits().hash(state); @@ -728,4 +732,21 @@ mod tests { } } } + + /// Equal values hash alike (#545): `-0.0 == 0.0`. + #[test] + fn equal_floats_hash_alike() { + use std::hash::{BuildHasher, RandomState}; + let h = RandomState::new(); + assert_eq!( + h.hash_one(Value::Float(-0.0)), + h.hash_one(Value::Float(0.0)), + "-0.0 and 0.0" + ); + assert_ne!( + h.hash_one(Value::Float(-1.0)), + h.hash_one(Value::Float(1.0)), + "-1.0 and 1.0" + ); + } } diff --git a/src/query/datalog/evaluator.rs b/src/query/datalog/evaluator.rs index 1986ed9253..13db500611 100644 --- a/src/query/datalog/evaluator.rs +++ b/src/query/datalog/evaluator.rs @@ -858,6 +858,8 @@ impl StratifiedEvaluator { &p, hint.as_ref() .unwrap_or(&crate::query::datalog::optimizer::IndexHint::Eavt), + // Rule bodies keep today's rule until #548. + &[], ); } WhereClause::Expr { expr, binding: out } => { diff --git a/src/query/datalog/executor.rs b/src/query/datalog/executor.rs index 90b663c6dd..c9bc3fb4f2 100644 --- a/src/query/datalog/executor.rs +++ b/src/query/datalog/executor.rs @@ -662,6 +662,7 @@ impl DatalogExecutor { .cloned() .collect(); + let mut binders = Binders::new(&query.where_clauses, Vec::new()); let (planned, deferred_not_clauses) = optimizer::plan(plan_clauses); // Process planned clauses in order: Pattern → expand bindings, Expr → filter/extend, @@ -670,13 +671,18 @@ impl DatalogExecutor { for (clause, hint) in planned { match clause { WhereClause::Pattern(p) => { + let rebind = binders.pattern(&p); bindings = matcher.match_with_hint_seeded( bindings, &p, hint.as_ref().unwrap_or(&optimizer::IndexHint::Eavt), + &rebind, ); } WhereClause::Expr { expr, binding: out } => { + if let Some(var) = &out { + binders.expression(var); + } bindings = bindings .into_iter() .filter_map(|mut b| match eval_expr(&expr, &b, Some(®istry)) { @@ -881,7 +887,18 @@ impl DatalogExecutor { .cloned() .collect(); - for (predicate, args) in query.get_top_level_rule_invocations() { + let rule_positions = query + .where_clauses + .iter() + .enumerate() + .filter(|(_, c)| matches!(c, WhereClause::RuleInvocation { .. })) + .map(|(i, _)| i); + let mut rule_patterns = Vec::new(); + for ((predicate, args), at) in query + .get_top_level_rule_invocations() + .into_iter() + .zip(rule_positions) + { let pattern = match args.len() { 1 => { #[allow(clippy::indexing_slicing)] @@ -903,9 +920,11 @@ impl DatalogExecutor { return Err(err_coded!(ErrorCode::Int028, predicate, n)); } }; + rule_patterns.push((pattern.clone(), at)); plan_clauses.push(WhereClause::Pattern(pattern)); } + let mut binders = Binders::new(&query.where_clauses, rule_patterns); let (planned, deferred_not_clauses) = optimizer::plan(plan_clauses); // Process planned clauses in order: Pattern → expand, Expr → filter/extend, @@ -914,13 +933,18 @@ impl DatalogExecutor { for (clause, hint) in planned { match clause { WhereClause::Pattern(p) => { + let rebind = binders.pattern(&p); bindings = matcher.match_with_hint_seeded( bindings, &p, hint.as_ref().unwrap_or(&optimizer::IndexHint::Eavt), + &rebind, ); } WhereClause::Expr { expr, binding: out } => { + if let Some(var) = &out { + binders.expression(var); + } bindings = bindings .into_iter() .filter_map(|mut b| match eval_expr(&expr, &b, Some(®istry)) { @@ -1461,6 +1485,84 @@ fn extract_variables( type Binding = std::collections::HashMap; +/// Which clause of a query's top-level `:where` gave each variable its value +/// (#545, #473 spec §5.4). +/// +/// A variable that several patterns bind takes its value from the first of +/// them in the query text, whatever order the planner runs them in: a +/// keyword and the ref of the entity it names are equal in a join, but are +/// returned as they were bound. An expression binding overwrites the value +/// where the planner places it, and later patterns keep it. A +/// pseudo-attribute pattern never replaces a value. +struct Binders { + /// Each top-level pattern (rule calls as patterns) and its position in + /// `:where`; taken as the planner hands them out. + text: Vec<(Pattern, usize)>, + /// The position of the pattern each variable's value came from; `None` + /// once an expression has bound it. + by_var: HashMap>, +} + +impl Binders { + fn new(where_clauses: &[WhereClause], rule_patterns: Vec<(Pattern, usize)>) -> Self { + let mut text: Vec<(Pattern, usize)> = where_clauses + .iter() + .enumerate() + .filter_map(|(i, c)| match c { + WhereClause::Pattern(p) => Some((p.clone(), i)), + _ => None, + }) + .collect(); + text.extend(rule_patterns); + Binders { + text, + by_var: HashMap::new(), + } + } + + /// Record the pattern `p`, run next, and return the variables whose + /// value it replaces. + fn pattern(&mut self, p: &Pattern) -> Vec { + let at = match self.text.iter().position(|(q, _)| q == p) { + Some(i) => self.text.swap_remove(i).1, + None => usize::MAX, + }; + let real = matches!(p.attribute, AttributeSpec::Real(_)); + let attribute = match &p.attribute { + AttributeSpec::Real(a) => Some(a), + AttributeSpec::Pseudo(_) => None, + }; + let mut rebind = Vec::new(); + for c in [Some(&p.entity), attribute, Some(&p.value)] + .into_iter() + .flatten() + { + let EdnValue::Symbol(v) = c else { continue }; + if !v.starts_with('?') || v.starts_with("?_") { + continue; + } + match self.by_var.get(v) { + None => { + self.by_var.insert(v.clone(), Some(at)); + } + Some(Some(b)) if real && at < *b => { + self.by_var.insert(v.clone(), Some(at)); + if !rebind.contains(v) { + rebind.push(v.clone()); + } + } + Some(_) => {} + } + } + rebind + } + + /// Record an expression binding `var`. + fn expression(&mut self, var: &str) { + self.by_var.insert(var.to_string(), None); + } +} + /// Unified post-processing: handles plain-variable extraction, aggregation, /// window functions, and mixed (aggregate + window) queries. /// diff --git a/src/query/datalog/matcher.rs b/src/query/datalog/matcher.rs index c401dd3898..d8f1f58921 100644 --- a/src/query/datalog/matcher.rs +++ b/src/query/datalog/matcher.rs @@ -246,7 +246,7 @@ impl PatternMatcher { // Join with each subsequent pattern for pattern in patterns.get(1..).unwrap_or(&[]) { - results = self.join_with_pattern(results, pattern); + results = self.join_with_pattern(results, pattern, &[]); } results @@ -267,7 +267,7 @@ impl PatternMatcher { // Join with each subsequent pattern for (pattern, _hint) in patterns.get(1..).unwrap_or(&[]) { - results = self.join_with_pattern(results, pattern); + results = self.join_with_pattern(results, pattern, &[]); } results @@ -282,11 +282,16 @@ impl PatternMatcher { /// - Empty seed (`[]`): returns empty immediately. /// /// Used by the executor and evaluator incremental plan loops introduced in #207. + /// + /// `rebind` names variables the seed binds whose value this pattern + /// replaces with its own (#545): an equal value of another kind, a keyword + /// for a ref or the reverse. pub(crate) fn match_with_hint_seeded( &self, seed: Vec, pattern: &Pattern, hint: &IndexHint, + rebind: &[String], ) -> Vec { if seed.is_empty() { return vec![]; @@ -296,7 +301,7 @@ impl PatternMatcher { self.match_pattern_with_hint(pattern, hint) } else { // Subsequent pattern — join_with_pattern uses hash-join when possible. - self.join_with_pattern(seed, pattern) + self.join_with_pattern(seed, pattern, rebind) } } @@ -325,7 +330,7 @@ impl PatternMatcher { let mut results = seed; for pattern in patterns { - results = self.join_with_pattern(results, pattern); + results = self.join_with_pattern(results, pattern, &[]); } results } @@ -341,6 +346,7 @@ impl PatternMatcher { &self, existing_bindings: Vec, pattern: &Pattern, + rebind: &[String], ) -> Vec { if existing_bindings.is_empty() { return vec![]; @@ -389,7 +395,7 @@ impl PatternMatcher { // No join variable detected: fall back to nested-loop scan. let mut results = Vec::new(); for existing in existing_bindings { - let new_matches = self.match_pattern_with_bindings(pattern, &existing); + let new_matches = self.match_pattern_with_bindings(pattern, &existing, rebind); results.extend(new_matches); } return results; @@ -419,7 +425,7 @@ impl PatternMatcher { for existing in existing_bindings { let Some(probe_val) = existing.get(&jvar) else { // Outer binding doesn't have the join var yet — fall back to scan for this row. - let new_matches = self.match_pattern_with_bindings(pattern, &existing); + let new_matches = self.match_pattern_with_bindings(pattern, &existing, rebind); results.extend(new_matches); continue; }; @@ -445,6 +451,9 @@ impl PatternMatcher { consistent = false; break; } + if rebind.contains(var) { + merged.insert(var.clone(), val.clone()); + } } else { merged.insert(var.clone(), val.clone()); } @@ -477,7 +486,12 @@ impl PatternMatcher { /// Match a pattern given existing variable bindings /// Returns new bindings that extend the existing ones - fn match_pattern_with_bindings(&self, pattern: &Pattern, existing: &Bindings) -> Vec { + fn match_pattern_with_bindings( + &self, + pattern: &Pattern, + existing: &Bindings, + rebind: &[String], + ) -> Vec { // Fast path for pseudo-attr patterns: when a preceding real-attr pattern stored // hidden fact-metadata keys (e.g. `__fvf_`), use them directly instead of // scanning all facts and cross-joining. This ensures pseudo-attr patterns are @@ -501,7 +515,7 @@ impl PatternMatcher { // the normal scan path so each fact produces one binding (all // identical). Task 5 (executor) will inject the correct value. PseudoAttr::ValidAt => { - return self.match_pattern_with_bindings_scan(pattern, existing); + return self.match_pattern_with_bindings_scan(pattern, existing, rebind); } }; if let Some(stored_value) = existing.get(&hidden_key) { @@ -515,7 +529,7 @@ impl PatternMatcher { } // Default: scan all facts - self.match_pattern_with_bindings_scan(pattern, existing) + self.match_pattern_with_bindings_scan(pattern, existing, rebind) } /// Default join implementation: iterate all facts and try to match. @@ -523,6 +537,7 @@ impl PatternMatcher { &self, pattern: &Pattern, existing: &Bindings, + rebind: &[String], ) -> Vec { let mut results = Vec::new(); @@ -556,6 +571,13 @@ impl PatternMatcher { if consistent { // Merge bindings (hidden keys are overwritten by the new fact's values) new_bindings.extend(additional_bindings); + // A substituted variable matched as a constant; take the + // fact's value at its first position instead. + for var in rebind { + if let Some(v) = Self::fact_value_of(pattern, fact, var) { + new_bindings.insert(var.clone(), v); + } + } results.push(new_bindings); } } @@ -564,6 +586,21 @@ impl PatternMatcher { results } + /// The value `fact` gives the variable `var` at its first position in + /// `pattern` (entity, attribute, value). + fn fact_value_of(pattern: &Pattern, fact: &Fact, var: &str) -> Option { + let is_var = |c: &EdnValue| matches!(c, EdnValue::Symbol(s) if s == var); + if is_var(&pattern.entity) { + return Some(Value::Ref(fact.entity)); + } + if let AttributeSpec::Real(a) = &pattern.attribute + && is_var(a) + { + return Some(Value::Keyword(fact.attribute.clone())); + } + is_var(&pattern.value).then(|| fact.value.clone()) + } + /// Apply existing bindings to a pattern, replacing bound variables with their values fn apply_bindings_to_pattern(&self, pattern: &Pattern, bindings: &Bindings) -> Pattern { let attribute = match &pattern.attribute { @@ -1282,7 +1319,7 @@ mod tests { EdnValue::Symbol("?v".to_string()), ); let unit_seed = vec![HashMap::new()]; - let results = matcher.match_with_hint_seeded(unit_seed, &p, &IndexHint::Aevt); + let results = matcher.match_with_hint_seeded(unit_seed, &p, &IndexHint::Aevt, &[]); assert_eq!( results.len(), 1, @@ -1313,7 +1350,7 @@ mod tests { m.insert("?other".to_string(), Value::Integer(99)); m }]; - let results = matcher.match_with_hint_seeded(seed, &p, &IndexHint::Eavt); + let results = matcher.match_with_hint_seeded(seed, &p, &IndexHint::Eavt, &[]); assert_eq!( results.len(), 1, @@ -1335,7 +1372,7 @@ mod tests { EdnValue::Symbol("?v".to_string()), ); // Completely empty seed (no rows at all) - let results = matcher.match_with_hint_seeded(vec![], &p, &IndexHint::Aevt); + let results = matcher.match_with_hint_seeded(vec![], &p, &IndexHint::Aevt, &[]); assert!(results.is_empty(), "empty seed must produce empty results"); } } diff --git a/tests/join_rules_test.rs b/tests/join_rules_test.rs new file mode 100644 index 0000000000..fa05a86248 --- /dev/null +++ b/tests/join_rules_test.rs @@ -0,0 +1,178 @@ +//! Join rules that do not depend on the query plan (#545, #473 spec §5.4): +//! bound floats are equal by IEEE `==`, and a variable bound to both a +//! keyword and a ref returns the kind from the first pattern, in `:where` +//! text order, that binds it. + +use minigraf::{Minigraf, QueryResult, Value}; + +fn rows(r: QueryResult) -> Vec> { + match r { + QueryResult::QueryResults { results, .. } => results, + _ => panic!("expected QueryResults"), + } +} + +fn query(db: &Minigraf, q: &str) -> Vec> { + rows(db.execute(&format!("(query {q})")).expect("query")) +} + +/// The entity a keyword names, as `edn_to_entity_id` derives it. +fn named(k: &str) -> uuid::Uuid { + uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, k.as_bytes()) +} + +fn is_keyword(v: &Value, k: &str) -> bool { + matches!(v, Value::Keyword(x) if x == k) +} + +fn is_ref_to(v: &Value, k: &str) -> bool { + matches!(v, Value::Ref(u) if *u == named(k)) +} + +#[test] +fn float_join_pairs_zero_with_negative_zero() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:a :x 0.0] [:b :y -0.0] [:c :x 1.5] [:d :y 1.5]])") + .unwrap(); + // `?v` is the join key: entity unbound, value bound. + let r = query(&db, "[:find ?e ?f :where [?e :x ?v] [?f :y ?v]]"); + assert_eq!(r.len(), 2, "0.0 joins -0.0, 1.5 joins 1.5"); + // `?e` is the join key and `?v` a shared variable compared after it. + db.execute("(transact [[:a :y -0.0]])").unwrap(); + let r = query(&db, "[:find ?e :where [?e :x ?v] [?e :y ?v]]"); + assert_eq!(r.len(), 1, "a's 0.0 and -0.0 agree"); +} + +#[test] +fn float_constant_keeps_epsilon_match() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:a :x 1.0]])").unwrap(); + let r = query(&db, "[:find ?e :where [?e :x 1.0000000000000001]]"); + assert_eq!(r.len(), 1, "a float constant matches within epsilon"); +} + +fn friends_db() -> Minigraf { + let db = Minigraf::in_memory().unwrap(); + // `:friend` holds a keyword that names `:bob`. + db.execute(r#"(transact [[:alice :friend :bob] [:bob :name "Bob"]])"#) + .unwrap(); + db +} + +#[test] +fn keyword_or_ref_follows_where_order_not_plan() { + let db = friends_db(); + // The planner runs `[?b :name "Bob"]` first (two constants), which + // binds `?b` to a ref; the first pattern in the text binds a keyword. + let r = query(&db, r#"[:find ?b :where [?a :friend ?b] [?b :name "Bob"]]"#); + assert_eq!(r.len(), 1); + assert!( + is_keyword(&r[0][0], ":bob"), + "keyword from the first pattern" + ); + + let r = query(&db, r#"[:find ?b :where [?b :name "Bob"] [?a :friend ?b]]"#); + assert_eq!(r.len(), 1); + assert!(is_ref_to(&r[0][0], ":bob"), "ref from the first pattern"); +} + +#[test] +fn keyword_or_ref_same_order_both_ways() { + let db = friends_db(); + // Same selectivity: plan order is text order, as before. + let r = query(&db, "[:find ?b :where [?a :friend ?b] [?b :name ?n]]"); + assert_eq!(r.len(), 1); + assert!(is_keyword(&r[0][0], ":bob")); + let r = query(&db, "[:find ?b :where [?b :name ?n] [?a :friend ?b]]"); + assert_eq!(r.len(), 1); + assert!(is_ref_to(&r[0][0], ":bob")); +} + +#[test] +fn keyword_or_ref_through_the_attribute_position() { + let db = Minigraf::in_memory().unwrap(); + // `:ptr` refers to the entity that the keyword `:color` names, and + // `:color` is also an attribute. + db.execute(&format!( + r#"(transact [[:e1 :ptr #uuid "{}"] [:e2 :color "red"]])"#, + named(":color") + )) + .unwrap(); + // The planner runs `[?x :ptr ?a]` first (one constant), binding `?a` to + // a ref; the first pattern in the text binds the attribute keyword. + let r = query(&db, "[:find ?a :where [?e ?a ?v] [?x :ptr ?a]]"); + assert_eq!(r.len(), 1); + assert!(is_keyword(&r[0][0], ":color"), "attribute keyword first"); + let r = query(&db, "[:find ?a :where [?x :ptr ?a] [?e ?a ?v]]"); + assert_eq!(r.len(), 1); + assert!(is_ref_to(&r[0][0], ":color"), "ref first"); +} + +#[test] +fn expression_binding_is_kept_by_later_joins() { + let db = Minigraf::in_memory().unwrap(); + db.execute("(transact [[:f :m 0.0] [:e :n 0.0] [:g :k 0.0]])") + .unwrap(); + // Plan: `[:f :m ?v]` binds `?v`, `[:e :n ?w]`, the expression + // overwrites `?v` with -0.0, then `[?g :k ?v]` joins on it. That pattern + // comes first in the text, but an expression's value is kept. + let r = query( + &db, + "[:find ?v :where [?g :k ?v] [:f :m ?v] [:e :n ?w] [(* ?w -1.0) ?v]]", + ); + assert_eq!(r.len(), 1); + assert!( + matches!(r[0][0], Value::Float(f) if f == 0.0 && f.is_sign_negative()), + "the expression's -0.0" + ); +} + +#[test] +fn keyword_or_ref_in_a_rule_query() { + let db = friends_db(); + db.execute("(rule [(knows ?a ?b) [?a :friend ?b]])") + .unwrap(); + let r = query(&db, r#"[:find ?b :where (knows ?a ?b) [?b :name "Bob"]]"#); + assert_eq!(r.len(), 1); + assert!(is_keyword(&r[0][0], ":bob"), "keyword from the rule call"); +} + +#[test] +fn keyword_or_ref_after_a_rule_call() { + let db = friends_db(); + db.execute("(rule [(knows ?a ?b) [?a :friend ?b]])") + .unwrap(); + let r = query(&db, r#"[:find ?b :where [?b :name "Bob"] (knows ?a ?b)]"#); + assert_eq!(r.len(), 1); + assert!(is_ref_to(&r[0][0], ":bob"), "ref from the first pattern"); +} + +#[test] +fn keyword_or_ref_with_a_repeated_pattern() { + let db = friends_db(); + let r = query( + &db, + r#"[:find ?b :where [?a :friend ?b] [?b :name "Bob"] [?a :friend ?b]]"#, + ); + assert_eq!(r.len(), 1); + assert!( + is_keyword(&r[0][0], ":bob"), + "keyword from the first pattern" + ); +} + +#[test] +fn pseudo_attribute_pattern_never_replaces_a_value() { + let db = friends_db(); + // `[?b :db/valid-at ?t]` is first in the text and the planner runs it + // last, matching every fact of `:bob`; it keeps `?b` as bound. + let r = query( + &db, + r#"[:find ?b ?t :where [?b :db/valid-at ?t] [?a :friend ?b] [?b :name "Bob"]]"#, + ); + assert_eq!(r.len(), 1); + assert!( + is_keyword(&r[0][0], ":bob"), + "keyword from the first real pattern" + ); +}