8000 fix(rules): bind the query's valid time for :db/valid-at in rule definitions (#617) by adityamukho · Pull Request #619 · project-minigraf/minigraf · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
< 10BC8 td class="blob-code blob-code-context js-file-line"> - **A prepared query keeps a literal `:as-of`, `:valid-at` or `:any-valid-time`** (#603). Binding a prepared query's slots dropped any `:as-of` or `:valid-at` that was not itself a slot, so `PreparedQuery::execute` and `PreparedQuery::query` ran at the current transaction time and valid now: `(query [:find ?v :as-of 1 :where [:a :n ?v]])` prepared returned the current rows, not those at transaction 1, and a prepared per-fact pseudo-attribute query with `:any-valid-time` failed with `INT-026`. Slot forms (`:as-of $tx`, `:valid-at $t`) were not affected. Present since 2026-04-04; fixed on v2.x too.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- **Rule queries with a literal argument return every row** (#608). Magic-sets rewriting restricts a rule to the facts its callers demand, but it took each rule's bound arguments from the first call it saw and assumed every other call matched. A call that did not — the same rule called with free arguments elsewhere in the query, a call inside `or` or `not`, a call from a rule the query calls with free arguments, or a rule-body call whose argument nothing bound yet — either failed with `INT-022` (`(chain ?x :c)` with `(chain ?x ?y) :- (link ?x ?m) (chain ?m ?y)`) or silently returned too few rows (`(link ?x :c) (link ?p ?q)` returned only the `:c` edges for `?p ?q`). A query with both arguments literal next to another rule call also lost its rows. The demand on each rule is now the one every call site supplies, and a rule some call site reads in full is evaluated in full. Present since v1.2.0.
- **A `:db/valid-at` pattern in a `not-join` body binds the query's valid time on every path** (#615). When the body also held an expression, sat in an `or` branch, or ran in a query that invokes a rule, the body bound `nil`, so `(not-join [?e] [?e :db/valid-at ?t] [(> ?t 0)])` never matched and excluded nothing; without the expression the same body excluded every entity. It now binds the query's `:valid-at` value (or the current time) as the other paths do. Present since v0.13.1; v2.x is affected too.
- **A `:db/valid-at` pattern in a rule definition binds the query's valid time** (#617). The rule evaluators never received it, so in a rule body the pattern bound `nil` and the query failed with `INT-022`; in a rule's `not` / `not-join` body it bound `nil`, so the negation never matched on it; and in a rule's `or` branch it bound the current time instead of the query's `:valid-at`. Rule bodies, their negation bodies and `or` branches now bind the query's `:valid-at` value, the current time without one, and `nil` under `:any-valid-time`, as patterns outside rules do. v2.x is affected too.
- **An `or` that shares no variable with the earlier clauses returns its cross product** (#610). Such an `or` — `[?x :edge ?z] (or [?p :edge :b] [?p :edge :c])` — returned no rows when no branch had `not`, `not-join` or a pseudo-attribute, because the incoming rows were replaced by the branch results. Each incoming row now joins every branch row, in queries and rule bodies. `or-join` still refuses a join variable no earlier clause binds (INT-018): it filters, it does not bind.
- **The wasm32 builds are tested again, and the browser layer no longer panics or drops pages.** The repo split (#231) moved the browser and WASI CI jobs to minigraf-wasm, which only builds the package, so core's own wasm tests stopped running and the wasm32 test build broke unnoticed. A new `wasm.yml` workflow runs the `wasm-bindgen` tests in headless Firefox and Chrome, runs the unit and integration tests on `wasm32-wasip1` under Wasmtime, and lints both targets with `clippy -D warnings`. Fixes found on the way: `BrowserDb` skipped any dirty page it could not read when flushing to IndexedDB and still reported success, and now returns the error (also fixed in v2.0.4, #470). The IndexedDB upgrade callback, the IndexedDB backend handle and the page-buffer lock no longer `unwrap()` (on wasm32 a panic aborts the whole instance). IndexedDB keys that are not whole page numbers are rejected instead of truncated. The nine `BrowserBufferBackend` tests used `#[test]`, which the wasm test runner never runs, and now run. File-only modules (`wal`, `storage::verify`, `storage::dir_sync`) are no longer compiled for wasm32, so the wasm32 builds have no warnings.
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ Auto-migrates v7 → v8 on open (spec §9, with a backup meta page). v1–v6 are

## Test Coverage

**1554 tests** (1544 passing, 10 ignored; unit + integration + doc).
**1564 tests** (1554 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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ let r2 = pq.execute(&[("tx", BindValue::TxCount(2)), ("entity", BindValue::Entit

```bash
cargo run # interactive Datalog REPL
cargo test # run 1554 tests
cargo test # run 1564 tests
cargo run < demos/demo_recursive.txt # recursive rules demo
```

Expand Down
4 changes: 2 additions & 2 deletions docs/TEST_COVERAGE.md

Large diffs are not rendered by default.

49 changes: 42 additions & 7 deletions src/query/datalog/evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
use super::functions::FunctionRegistry;
use super::matcher::{Bindings, PatternMatcher, edn_to_entity_id, edn_to_value};
use super::rules::RuleRegistry;
use super::types::{AttributeSpec, EdnValue, Pattern, Rule, WhereClause};
use super::types::{AttributeSpec, EdnValue, Pattern, Rule, ValidAt, WhereClause};
use crate::error::{ErrorCode, err_coded};
use crate::graph::FactStorage;
use crate::graph::types::{Fact, Value};
Expand Down Expand Up @@ -70,6 +70,8 @@ pub struct RecursiveEvaluator {
max_derived_facts: usize,
/// Maximum facts the rules may derive in one evaluation; base facts do not count
max_results: usize,
/// The value a `:db/valid-at` pattern in a rule body binds (#617)
valid_at: Value,
}

impl RecursiveEvaluator {
Expand Down Expand Up @@ -97,9 +99,17 @@ impl RecursiveEvaluator {
max_iterations,
max_derived_facts,
max_results,
valid_at: Value::Null,
}
}

/// Set the value a `:db/valid-at` pattern in a rule body binds: the
/// query's valid time (#617). Without it the pattern binds `nil`.
pub fn with_valid_at(mut self, valid_at: Value) -> Self {
self.valid_at = valid_at;
self
}

/// Evaluate rules for given predicates using semi-naive fixed-point iteration.
///
/// # Arguments
Expand Down Expand Up @@ -286,7 +296,8 @@ impl RecursiveEvaluator {
return Ok(derived);
}

let matcher = PatternMatcher::new(current_facts.clone());
let matcher =
PatternMatcher::new(current_facts.clone()).with_valid_at(self.valid_at.clone());
let bindings = if patterns.is_empty() {
// Expr-only rule body: seed with empty binding
vec![Bindings::new()]
Expand Down Expand Up @@ -607,6 +618,8 @@ pub struct StratifiedEvaluator {
max_iterations: usize,
max_derived_facts: usize,
max_results: usize,
/// The value a `:db/valid-at` pattern in a rule body binds (#617)
valid_at: Value,
}

impl StratifiedEvaluator {
Expand All @@ -625,9 +638,18 @@ impl StratifiedEvaluator {
max_iterations,
max_derived_facts,
max_results,
valid_at: Value::Null,
}
}

/// Set the value a `:db/valid-at` pattern binds in rule bodies and their
/// `not` / `not-join` bodies and `or` branches: the query's `:valid-at`
/// value, the current time without one, `nil` for `:any-valid-time` (#617).
pub fn with_valid_at(mut self, valid_at: Value) -> Self {
self.valid_at = valid_at;
self
}

/// Derive all facts for the given predicates, respecting stratification order.
pub fn evaluate(&self, predicates: &[String]) -> Result<FactStorage> {
use crate::query::datalog::stratification::DependencyGraph;
Expand Down Expand Up @@ -727,7 +749,8 @@ impl StratifiedEvaluator {
self.max_iterations,
self.max_derived_facts,
self.max_results,
);
)
.with_valid_at(self.valid_at.clone());
let derived = sub_eval.evaluate_recursive_rules(&stratum_preds)?;
// Snapshot existing fact keys so we only load truly new (derived) facts
let existing: HashSet<(uuid::Uuid, String, Vec<u8>)> = accumulated
Expand Down Expand Up @@ -829,7 +852,10 @@ impl StratifiedEvaluator {
// Compute once; reuse for plan loop, apply_or_clauses, not-body matching.
BD0 let accumulated_facts: Arc<[Fact]> = Arc::from(accumulated.get_asserted_facts()?);

let matcher = PatternMatcher::from_slice(accumulated_facts.clone());
let matcher = PatternMatcher::from_slice_with_valid_at(
accumulated_facts.clone(),
self.valid_at.clone(),
);

// Plan: assigns index hints + pushes Expr to earliest binding position.
// Not/NotJoin are excluded from plan_clauses above, so `deferred` is
Expand Down Expand Up @@ -880,13 +906,19 @@ impl StratifiedEvaluator {
// FunctionRegistry (UDF registration happens at the db layer). Use the
// built-in-only registry so or-branches can still use built-in predicates.
let fn_registry = FunctionRegistry::with_builtins();
// An or branch binds `:db/valid-at` from a `ValidAt`, the
// inverse of the executor's mapping to `self.valid_at`.
let branch_valid_at = match &self.valid_at {
Value::Integer(t) => ValidAt::Timestamp(*t),
_ => ValidAt::AnyValidTime,
};
let expanded = apply_or_clauses(
&rule.body,
candidates,
accumulated_facts.clone(),
&registry_guard,
None,
None,
Some(branch_valid_at),
&fn_registry,
)?;
drop(registry_guard);
Expand Down Expand Up @@ -941,7 +973,10 @@ impl StratifiedEvaluator {
})
.collect();

let not_matcher = PatternMatcher::from_slice(accumulated_facts.clone());
let not_matcher = PatternMatcher::from_slice_with_valid_at(
accumulated_facts.clone(),
self.valid_at.clone(),
);
let mut not_bindings: Vec<Bindings> = if substituted.is_empty() {
vec![binding.clone()]
} else {
Expand Down Expand Up @@ -987,7 +1022,7 @@ impl StratifiedEvaluator {
nj_clauses,
&binding,
accumulated_facts.clone(),
Value::Null,
self.valid_at.clone(),
&fn_guard,
) {
continue 'binding;
Expand Down
3 changes: 2 additions & 1 deletion src/query/datalog/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -829,7 +829,8 @@ impl DatalogExecutor {
1000, // max iterations
effective_max_derived,
effective_max_results,
);
)
.with_valid_at(valid_at_value.clone());

let derived_storage = evaluator.evaluate(&predicates)?;

Expand Down
7 changes: 7 additions & 0 deletions src/query/datalog/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl PatternMatcher {
/// asserted facts. The caller is responsible for ensuring the slice contains
/// only currently asserted facts (equivalent to `FactStorage::get_asserted_facts()`
/// at the snapshot moment). No additional filtering is applied at match time.
#[cfg(test)]
pub(crate) fn from_slice(facts: Arc<[Fact]>) -> Self {
PatternMatcher {
storage: MatcherStorage::Slice(facts),
Expand All @@ -51,6 +52,12 @@ impl PatternMatcher {
}
}

/// Set the value a `:db/valid-at` pattern binds.
pub(crate) fn with_valid_at(mut self, valid_at: Value) -> Self {
self.valid_at_value = valid_at;
self
}

fn get_facts(&self) -> Cow<'_, [Fact]> {
match &self.storage {
MatcherStorage::Owned(s) => Cow::Owned(s.get_asserted_facts().unwrap_or_default()),
Expand Down
118 changes: 118 additions & 0 deletions tests/recursive_rules_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -503,3 +503,121 @@ fn test_max_results_counts_derived_facts_not_base_facts() {
.unwrap_err();
assert_eq!(err.code(), "INT-020");
}

/// 2030-01-01T00:00:00Z in Unix ms.
const VALID_AT_2030: i64 = 1_893_456_000_000;

fn result_rows(r: QueryResult) -> Vec<Vec<Value>> {
match r {
QueryResult::QueryResults { results, .. } => results,
_ => panic!("expected QueryResults"),
}
}

/// #617: a `:db/valid-at` pattern in a rule body binds the query's valid time,
/// not `nil` (which failed the head with INT-022).
#[test]
fn test_rule_body_valid_at_binds_query_valid_time() {
let db = Minigraf::in_memory().unwrap();
exec(&db, "(transact [[:a :n 1]])");
exec(&db, "(rule [(vt ?e ?t) [?e :n _] [?e :db/valid-at ?t]])");

let rows = result_rows(exec(
&db,
r#"(query [:find ?t :valid-at "2030-01-01" :where (vt ?e ?t)])"#,
));
assert_eq!(rows, vec![vec![Value::Integer(VALID_AT_2030)]]);

// Bound first argument: the magic-sets path.
let rows = result_rows(exec(
&db,
r#"(query [:find ?t :valid-at "2030-01-01" :where (vt :a ?t)])"#,
));
assert_eq!(rows, vec![vec![Value::Integer(VALID_AT_2030)]]);

// No :valid-at: the current time, as outside a rule.
let rows = result_rows(exec(&db, "(query [:find ?t :where (vt ?e ?t)])"));
assert_eq!(rows.len(), 1, "one row");
assert!(
matches!(rows[0][0], Value::Integer(t) if t > VALID_AT_2030 / 2),
"current time bound"
);
}

/// #617: the same in a recursive rule, evaluated semi-naively.
#[test]
fn test_recursive_rule_body_valid_at_binds_query_valid_time() {
let db = Minigraf::in_memory().unwrap();
exec(&db, "(transact [[:a :next :b] [:b :next :c]])");
exec(
&db,
"(rule [(reach ?x ?y) [?x :next ?y] [?x :db/valid-at ?t] [(> ?t 0)]])",
);
exec(&db, "(rule [(reach ?x ?y) [?x :next ?z] (reach ?z ?y)])");

let rows = result_rows(exec(
&db,
r#"(query [:find ?y :valid-at "2030-01-01" :where (reach :a ?y)])"#,
));
assert_eq!(rows.len(), 2, ":a reaches :b and :c");
}

/// #617: a `not` body inside a rule binds the query's valid time, so it
/// excludes the entity whose `:t` equals it.
#[test]
fn test_rule_not_body_valid_at_binds_query_valid_time() {
let db = Minigraf::in_memory().unwrap();
exec(
&db,
"(transact [[:a :t 1893456000000] [:a :n 1] [:b :t 5] [:b :n 2]])",
);
exec(
&db,
"(rule [(other ?e ?v) [?e :t ?t] [?e :n ?v] (not [?e :db/valid-at ?t])])",
);

let rows = result_rows(exec(
&db,
r#"(query [:find ?v :valid-at "2030-01-01" :where (other ?e ?v)])"#,
));
assert_eq!(rows, vec![vec![Value::Integer(2)]], "not body excludes :a");
}

/// #617: the same for a `not-join` body inside a rule.
#[test]
fn test_rule_not_join_body_valid_at_binds_query_valid_time() {
let db = Minigraf::in_memory().unwrap();
exec(&db, "(transact [[:a :n 1] [:b :n 2]])");
exec(
&db,
"(rule [(fresh ?e) [?e :n _] (not-join [?e] [?e :db/valid-at ?t] [(> ?t 0)])])",
);

let rows = result_rows(exec(
&db,
r#"(query [:find ?e :valid-at "2030-01-01" :where (fresh ?e)])"#,
));
assert_eq!(rows.len(), 0, "not-join body excludes both");
}

/// #617: an `or` branch inside a rule binds the query's valid time, not the
/// current time.
#[test]
fn test_rule_or_branch_valid_at_binds_query_valid_time() {
let db = Minigraf::in_memory().unwrap();
exec(&db, "(transact [[:a :n 1] [:b :n 2]])");
exec(
&db,
"(rule [(vt ?e ?t) [?e :n _] (or (and [?e :n 1] [?e :db/valid-at ?t]) (and [?e :n 2] [?e :db/valid-at ?t]))])",
);

let rows = result_rows(exec(
&db,
r#"(query [:find ?t :valid-at "2030-01-01" :where (vt ?e ?t)])"#,
));
assert_eq!(
rows,
vec![vec![Value::Integer(VALID_AT_2030)]; 2],
"one row per entity"
);
}
Loading
0