Repository navigation
Faster datalog evaluation: dependency scheduling, semi-naive recursion, closures as paths - #2120
Conversation
…m baselines Derived facts under view policy had no direct regression coverage: the only policy test in the datalog suite checks query-time rule stripping. The new tests use stored rules so stripping cannot make them pass. - it_reasoning_policy_contract: a reader denied a derived predicate sees none of it through a scan, a join, a count or a property path, on novelty-only and indexed storage, with the closure already warm from a root query. A restricted first caller does not narrow the shared closure for root. A viewable head derived from a hidden premise stays visible, as documented. RDFS rewriting and OWL 2 RL materialization answer the same query differently under the same policy, and the test pins both answers. - it_datalog_program_reachability: a program with two independent recursive relations and four non-recursive rules over them, compared against closures computed in test code from the asserted edges, under both rule orderings and both storage modes. - datalog_fixpoint bench: first reasoning query after a commit for linear recursion, nonlinear recursion, and recursion feeding twelve non-recursive rules. Each sample commits an unrelated fact first so the derived-facts cache cannot serve it. Every query carries an explicit per-scale reasoningBudget and panics unless reasoning finished uncapped with exactly the expected derived-fact count, and the preflight counts every derived relation, so a run that derives less fails instead of looking faster. The reasoning and policy docs now state that the two reasoning approaches can disagree under one policy, with the subPropertyOf example.
Each parsed rule now carries a footprint: the graph-qualified predicates and classes its body may read and its heads may write. A rule depends on another when one of its reads may observe one of the other's writes, and the strongly connected components of that graph are the program's recursive groups, listed producers first. The analysis over-approximates wherever it cannot be exact. A variable predicate, a wildcard path, an unmodelled construct or a variable-predicate head reads or writes everything. So does a path that can match zero hops (`p*`, `p?`): a zero-hop match pairs every term in the graph with itself, so a new term under any predicate adds a match. Only two distinct named graphs are treated as disjoint. rdf:type reads and writes are qualified by class, so a rule reading ex:B does not depend on one deriving ex:A, while a read of any type depends on every type writer. Body IRIs are encoded with the encoder the heads use, because JSON-LD keeps object IRIs unencoded until scan time and a class read would otherwise never match its writer. Reads are collected from every place a body can read: triples, property paths including composite steps, EXISTS nested inside FILTER and BIND expressions, subqueries, GRAPH scopes and edge annotations. Each footprint also records whether the rule is repeatable: false when the body calls a function whose result can change between calls, using the same exclusion list the boolean-filter cache uses, or uses a shortest path. Evaluation is unchanged by this commit. The groups are available through DatalogRuleSet::dependencies.
The fixpoint re-ran every rule every round until a round derived nothing, so a rule downstream of a recursion ran once per round of that recursion, against partial input each time. Rules now run in dependency order. The program is split into stages of rule groups, where each group's stage is one past the latest stage of any group it reads from. A non-recursive group runs once, after the stages before it have finished. A recursive group iterates on its own until a pass derives nothing new for it. Groups in one stage never read each other's conclusions, so each pass shares one overlay. Visible consequences: - A non-recursive rule calling NOW(), RAND(), UUID()/STRUUID() or BNODE() is evaluated once per materialization. Re-run every round, a STRUUID() rule never converged and NOW() could add a timestamp per round. A volatile rule inside a recursive group still re-runs each pass; a warning names it. - The iteration bound applies per stage, and the tracked response's `iterations` counts passes across all stages. - Which partial facts a capped run keeps depends on evaluation order, so capped results differ from before. Completed results do not. The deadline is checked before each rule, once its body returns, and every 1,024 rows while heads are instantiated. A non-recursive rule gets a single pass, so without the post-body check a final rule could run past the deadline and still report a completed fixpoint. A body already running is not interrupted, and a rule that finishes deriving after the deadline has derived everything it can, so that run still reports completion. The predicate-count ordering heuristic is gone: DatalogRule loses depends_on/generates, and rule sets keep insertion order. The old evaluation remains available as RuleSchedule::WholeProgram, and DatalogExecutionResult now reports rule_body_runs. Tests in it_datalog_rule_schedule: a recursion with six downstream rules runs each of them exactly once and derives the same facts as the whole-program schedule; a non-recursive STRUUID() rule derives one value per subject where the whole-program schedule hits the iteration cap; and forty seeded random programs, with class reads and writes, one-or-more and zero-length paths, and heads that introduce fresh terms, derive identical facts under both schedules. The random test fails when recursive groups are not iterated, and when zero-length paths are given only their own predicate. A 40,000-fact derivation under a 2ms budget is capped on time; without the post-body check it reported completion.
After a recursive group's first pass, a rule can only derive something new from a match that uses a fact the group derived in the previous pass. Each rule whose reads of its group's facts are all top-level triple patterns now re-runs once per such pattern, with that pattern seeded by a VALUES block of the previous pass's matching facts while the rest of the body reads everything derived so far. A nonlinear rule with two recursive patterns runs twice per pass, so a new fact in either position is extended. The seed replaces the pattern when it matches facts exactly as a scan would; a literal or scan-encoded IRI constant, a datatype constraint or a variable predicate keeps the pattern behind the seed. A rule that reads its group's facts inside a UNION, EXISTS, subquery, property path or the trailing VALUES block re-runs its whole body every pass, as before. The whole-program schedule still runs whole bodies and stays the differential reference. DatalogExecutionResult gains body_rows, the rows rule bodies returned, which shows re-derivation directly. The dependency footprint now also reads the trailing VALUES block and its binds.
A recursive group of one rule shaped as a transitive closure now runs once, as a body with a one-or-more property path, instead of iterating. Over the facts visible when the group starts, the rewritten body derives exactly what the rule's fixpoint derives: T(x,y) . R(y,z) -> R(x,z) runs as T+(x,y) . R(y,z) R(x,y) . T(y,z) -> R(x,z) runs as R(x,y) . T+(y,z) R(x,y) . R(y,z) -> R(x,z) runs as R+(x,y) . R(y,z) T may be written in either direction. The body must be exactly the two triple patterns over three distinct variables with constant predicates and no datatype constraint, and the head exactly R(x,z). The nonlinear form keeps its last hop as a triple pattern so it neither re-derives one-hop asserted facts nor misses literal-valued ones. The path operator follows only IRI-valued objects. The left-linear path ends at the head's object, so that shape compiles only after a scan finds no literal object of T's predicate. A traversal that hits the path operator's visited-node limit falls back to iteration. The datalog_fixpoint bench gains iterated_linear_recursion, a linear recursion that cannot compile to a path, so semi-naive iteration stays measured now that the other recursive programs run as paths.
Seeding a recursive rule with only the previous pass's facts assumes that re-running its body over old matches would give the same rows. A rule whose footprint is not repeatable breaks that: a volatile function such as STRUUID() gives new rows for old matches every pass, so seeding stopped it early and reported a completed fixpoint the whole-program reference never reaches; and a seed carries no transaction metadata, so a filter on t(?z) dropped every match after the first pass and derived an incomplete closure that still reported completion. Such rules now re-run their whole body every pass, as before semi-naive evaluation.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz with #2121 folded in, here's my review of the whole stack in one place. I had reviewed the two halves separately, at e574b9189 and at 9e7e22958, and this head is exactly the second one, so what's below is those two reviews merged, plus one re-check I ran today because your folded-in tests changed the picture. At a design level no pushback on any of it. SCC staging with an over-approximate footprint, and the semi-naive seed as a VALUES block the planner just runs, are both the shapes I'd have asked for, and the numbers hold up when I measure them. Three headline notes:
- The schedule now asserts its fixpoint instead of observing it. The old loop proved convergence: its last round re-ran everything and derived nothing. The dependency schedule asserts it from the footprints, so a read the walk under-models is no longer a slower convergence. It becomes a rule that runs once, too early, and a silently short answer. Your folded-in tests now pin the UNION and subquery reads I'd flagged, but the composite-step read of a
+path still has no test, and reverting it silently drops a consumer's facts (inline). A debug-only closing pass would be cheap insurance on top. - A defect class this stack surfaced but didn't introduce. A reasoning query at the
tof a commit that retracted a fact the rules re-derive drops that fact: derived facts are stamped at the query'st, and the equal-ttie goes to the retraction. It's the third time we've hit the "redundant assert loses a cancelling-pair tie" shape: #1818 (NetChangeAccumulatornetting), #2022 (drop_reversed_facts), and now reasoning's derived facts against a same-tretraction (remove_stale_flakes, onmaintoday). So the class fix isn't this PR's, but the point fix is small and I'd love to see it ride along. - A decision for you and me after this PR, not in it. The new policy tests pin today's documented contract that a derived fact is judged by its own triple, not by its premises (
allowed_head_derived_from_hidden_premise_stays_visible, and RDFS vs OWL 2 RL answering differently under one policy). Pinning it is honest and I'm fine with it as a regression net. It does make "how it works today" a tested promise, so whether materialized reasoning should eventually respect premise visibility is worth settling separately.
Good to merge once the closure-lane budget item is in. CI is green on this head now that it targets main.
Full review below:
✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.
Both halves of this are the win I was hoping for, @bplatz, and I could reproduce them. With the dependency schedule alone (e574b9189, the repo's optimized dev-fast profile, old loop against new in one binary at 100 chains of 16), the recursion feeding 12 run-once rules goes from 3.64 s to 0.68 s, and plain linear and nonlinear recursion are flat to slightly better. The shape that rebuilds the derived overlay most often, two recursions chained through a run-once rule, still comes out ahead (1.27 s → 0.72 s). The semi-naive and closure lanes then take a 300-node nonlinear closure from 39.6 s to 0.38 s in a debug build. On correctness, 17 consumer-first programs at the scheduling commit derived the same facts as main, and a 276-pair schedule differential at this head, plus seeded literal joins, matched the whole-program reference exactly, apart from the two places noted below where this branch is the one that's right. I also checked negation: rule bodies are already monotone by construction (OPTIONAL, MINUS and NOT EXISTS are rejected at parse), so the schedule never has to respect strata.
Must address before merge:
- The closure lane bypasses the reasoning budget (
fluree-db-query/src/datalog_rules/execute.rs:553). The single closure body returns every closure pair beforemax_facts, the memory ceiling or the deadline is checked. On a 2000-node chain with a 20k cap that's 1,999,000 rows and 14.6 s / 437 MB, against 0.9–2.0 s / ~100 MB for the same rules under the dependency schedule alone. Fix path: cap the path's output at the remaining budget and fall back to iteration on overflow, the way the visited-node limit already does. Then the two "budget" sentences in the docs become true.
Should address:
- The composite-step read in the footprint walk has no test (inline on
it_datalog_rule_dependencies.rs:208). Reverting it leaves all 172grp_reasoningtests green while a consumer-first(ex:owns/ex:watched)+rule derives nothing. Your folded-in tests already pin the UNION and subquery reads; a couple of rows close the rest. - A re-derived fact disappears at the
tof the commit that retracted its asserted copy (execute.rs:329; the mechanism is influree-db-core/src/range.rs:491andfluree-db-query/src/reasoning.rs). This is pre-existing, but your seeds fix the fixpoint half, so Dependencies (21 facts) and WholeProgram (17) now disagree there, and the final answer still drops the colliding pair. A one-site probe inReasoningOverlaymade everything agree with the oracle and kept the existing reasoning tests green. I'd love to see it, plus a retraction-at-head case in the random differential, land with this PR.
Optional:
shortestPathrules belong in the "Volatile functions" docs bullet (inline). The PR body's "Completed results are unchanged" needs that carve-out and the equal-tone from item 3. In both cases the change is for the better.- A debug-only closing pass, so every datalog test in CI double-checks the dependency analysis (inline).
has_literal_object(execute.rs:463) materializes the whole predicate to answer a yes/no question (inline).
Adherence to repo commitments:
- Patterns/abstractions: ✔ Extends the existing fixpoint and the shared IR rather than adding an evaluator. The old loop stays as
RuleSchedule::WholeProgramfor differential tests, the seed is aPattern::Values, the closure is aPropertyPathPattern, and all of it runs through the normal planner.repeatablereuses the one volatility list (function_supported_for_bool_cache) instead of a third copy, and both walks are exhaustive matches, so a newPattern/Expressionvariant is a compile error. - Performance (speed first, memory second): ✖ Large wins wherever a closure completes, and nothing got slower under the dependency schedule alone. CRITICAL: the closure lane's cost scales with the closure, not the budget. On a 2000-node chain with a 20k cap it was 7–17× slower and ~4–5× the memory of the dependency schedule alone (item 1).
- Deployment targets: 🔴 Same finding as item 1. This code is embedded in solo's Lambdas through
fluree-db-api, where the reasoning budget is what keeps materialization inside the function's memory and request window. Otherwise it adds no thread, filesystem access or process-lifetime cache, andwasm32is green on this head. - Testing:
⚠️ Strong overall. The new tests are wired throughgrp_reasoning.rs, run by name, and go red under mutation: dropping the stage increment turned 10 red at the scheduling commit, and seeding only the first atom, a stuck delta or no literal check each turn tests red at this head. The gaps are the composite-step read (item 2), and every differential builds insert-only in-memory ledgers, with no index, retraction or time travel, which is how item 3 got past them. - Conventions: ✔ Self-describing commits with thorough bodies, and the PR body was rewritten for the combined scope. CI (
fmt,clippy,test,testsuite-sparql,wasm32,sql-bridge) is green on this head. Docs, the design record and the bench docs are all updated, apart from the two budget sentences in item 1.
Verified locally:
- At
e574b9189: the new scheduling tests by name, four mutations, 17 probe programs againstmain, and the optimized A/B timings above. - At
9e7e22958: 36 reasoning tests including every new one by name, the 276-pair differential and literal joins, a cold-ledger oracle with a retraction at head (item 3), the budget probe againste574b9189(item 1), and three mutations each red and then restored. - Today at this head: the whole
grp_reasoningbinary (172 passed). I also re-ran the walk-arm mutations: UNION gives 2 red, subquery 1 red, and GRAPH, annotation and sequence steps 0 red. Finally, a consumer-first probe for the sequence steps derived no facts under Dependencies, against 3 under WholeProgram.
Approving now so you can merge without waiting on another pass from me. Just be sure the budget cap on the closure lane is in before you do, and ideally the composite-step rows and the equal-t fix with it.
| } | ||
| } | ||
| match self | ||
| .apply(db, rule, closure.body.clone(), env, dict_novelty) |
There was a problem hiding this comment.
🔴 Must address before merge: the closure lane runs the whole closure before the budget sees it, so a closure much bigger than max_facts is slower and larger than under the dependency schedule alone.
apply_closure hands closure.body to apply, which collects every row of the body (run_body → execute_prepared) and only then checks max_facts / max_memory_bytes. The deadline is also only checked after the body returns. The body returns one row per closure pair, however small the budget. The only early exit is the path operator's visited-node limit, and that is per traversal (1M nodes from one start node). A closure that is large in total but shallow per start node never trips it, so the "falls back to iteration, which the reasoning budget then bounds" sentence in docs/design/rules-engine.md:133-134 doesn't hold there.
I measured it with run_fixpoint_with_schedule on an ex:parent chain, same rules at e574b9189 (the dependency schedule alone) and at this head, in a debug build. On a 2000-node chain with max_facts 20,000, the nonlinear rule takes 878 ms / 115 MB at e574b9189 and 14,582 ms / 437 MB here. The right-linear rule takes 1,988 ms / 86 MB at e574b9189 and 14,724 ms / 438 MB here. body_rows is 1,999,000, 100× the cap, before it caps at 20,000. The same rules with an always-true FILTER, which sends them down your semi-naive lane, cap in ~0.7 s / ~90 MB. To be clear, the lane is a huge win whenever the closure finishes: on a 300-node chain, uncapped, nonlinear goes from 39.6 s to 0.38 s, and right-linear at e574b9189 doesn't converge within 100 passes. At the default 1M cap on a 3000-node chain it's still faster than iterating. So what matters is the ratio of closure size to budget. That ratio is exactly the case the budget exists for, and in solo's Lambdas it's the difference between a capped answer and an out-of-memory invocation.
The fallback you already have seems like the natural fix. Give the closure body a cap tied to the remaining budget, and treat hitting it the way you treat the visited-node ResourceLimit: fall back to iteration, which the budget does bound. Something like a total emitted-pairs limit on the path of about max_facts - derived + 1 would do it. I don't think a plain LIMIT on the body is enough, since an unseeded path buffers all its pairs in open(). That keeps the fast lane for every closure that fits, and bounds the wasted work at about one budget's worth of rows. The Budget limits apply bullet in docs/query/datalog-rules.md:591 and the design-doc sentence above would then be true as written.
| ); | ||
| } | ||
|
|
||
| /// Shapes whose reads a constant-predicate collector does not see: a variable |
There was a problem hiding this comment.
🟠 Should address — the composite-step read the walk collects (dependency.rs:257) has no test, and reverting it gives a silently short answer.
Your folded-in tests closed most of what I'd flagged here at e574b9189. I re-ran the same mutations at this head: reverting the UNION arm now turns random_programs_derive_the_same_facts_under_both_schedules and a_rule_reading_its_group_inside_a_nested_pattern_reruns_whole red, and reverting the subquery arm turns the second one red. Nice.
Three arms are still unpinned: the sequence_steps chain on a property path, GRAPH scopes and edge annotations. Reverting all three leaves all 172 grp_reasoning tests green. For the sequence steps that's a wrong answer, not just a gap. With two rules, consumer listed first, CONSTRUCT { ?x ex:q ?y } WHERE { ?x (ex:owns/ex:watched)+ ?y } and CONSTRUCT { ?x ex:watched ?y } WHERE { ?x ex:likes ?y }, the mutated build derives no ex:q facts under RuleSchedule::Dependencies, while WholeProgram derives all three. A fixed-length ex:owns/ex:watched is unaffected. For GRAPH I couldn't build a wrong answer, because derived facts don't show up inside a GRAPH <iri> scope under either schedule, so that one is only a test gap. The edge-annotation arm I only checked against the tests.
A couple more rows here would pin them, e.g. (illustrative):
(
"ex:readsSequence",
sparql("CONSTRUCT { ?x ex:q ?y } WHERE { ?x (ex:owns/ex:watched)+ ?y }"),
),
(
"ex:readsGraph",
sparql("CONSTRUCT { ?x ex:g true } WHERE { GRAPH <http://example.org/g> { ?x ex:watched ?y } }"),
),with each asserting all_writers(&["ex:writesWatched"]) as its producers. A sequence-path body in the random generator would also do it. It's a small addition, and if you agree it's right I'd rather see it here than lost in the backlog.
| let body = match seed { | ||
| None => rule.body.query.clone(), | ||
| Some((atom, delta)) => { | ||
| match atom.seeded(&rule.body.query, &state.derived[delta]) { |
There was a problem hiding this comment.
🟠 Should address: a fact the rules re-derive vanishes from a query at the t of the commit that retracted its asserted copy, and because the seeds bypass that, Dependencies and WholeProgram now disagree in that state.
This is pre-existing on main, not introduced here. Derived facts are stamped with the query's t (the "Derived facts carry the query's t" comment in this file), and ReasoningOverlay::for_each_overlay_flake interleaves them with novelty. Then remove_stale_flakes (fluree-db-core/src/range.rs:491) resolves an equal-t tie to the retraction. So at the retraction's own t the derived assert loses, and one commit later it wins.
What this PR changes is that the seed reads state.derived directly instead of scanning the overlay, and the closure lane derives straight across the hidden fact. The fixpoint is now right in that state, and the reference isn't. Example: a cold-loaded ledger (indexed and novelty-only behave the same) with a 7-node ex:next chain, where ex:n0 ex:reach ex:n2 was asserted and then retracted in the latest commit. The left-linear rule ?x ex:reach ?y . ?y ex:next ?z derives 21 facts under Dependencies and 17 under WholeProgram. Through query_connection the final answer still drops the colliding facts. At head the right-linear, left-linear and nonlinear rules all miss exactly (n0, n2) and (n1, n3), where e574b9189 misses 3–9 pairs; @t:1 and the head one commit later are correct. So "Completed results are unchanged" isn't quite true here (it changes for the better). The differential tests can't see it, because they only build insert-only in-memory ledgers.
I tried the obvious one-site fix as a probe. In ReasoningOverlay::for_each_overlay_flake, drop a base retraction at t == to_t when the derived side asserts the same (s, p, o, dt, m). My oracle test then passed across all six shapes, both schedules agreed (21/21), and the 160 existing it_datalog* / it_reasoning* tests still passed. A real version should only pay for the lookup when a base retraction at to_t is actually in range. It's OWL2-RL's overlay too, so it's arguably bigger than this PR, but it's small. I'd rather see it land with this stack, plus a retraction-at-head case in random_programs_derive_the_same_facts_under_both_schedules, than lost in the backlog. Commenting here because fluree-db-query/src/reasoning.rs and fluree-db-core/src/range.rs are not in this diff.
| - **Rules downstream of a recursion see its complete result.** A rule that | ||
| reads a recursive relation runs once, after that relation stops growing, | ||
| instead of re-running every pass. | ||
| - **Volatile functions run once per materialization in a non-recursive rule.** |
There was a problem hiding this comment.
🟡 Optional — shortest-path rules belong in this bullet too, and the PR body's "Completed results are unchanged" needs the same carve-out.
dependency.rs:234-235 already marks a shortestPath body non-repeatable, and the effect shows up in completed results, not just capped ones. I ran the same program on main and on this branch: ex:a ex:knows ex:b, ex:b ex:knows ex:c, ex:c ex:knows ex:d, ex:a ex:shortcut ex:d, with the rules {"where": [["shortestPath", {"from": "ex:a", "to": "ex:d", "via": "ex:knows", "bind": "?p"}], ["bind", "?hops", "(size (path-pairs ?p))"]], "insert": {"@id": "ex:a", "ex:hopsToD": "?hops"}} and {"where": {"@id": "?x", "ex:shortcut": "?y"}, "insert": {"@id": "?x", "ex:knows": {"@id": "?y"}}}.
main derives both ex:a ex:hopsToD 3 (from the round before the shortcut existed) and ex:a ex:hopsToD 1; this branch derives only 1. This branch is the one that's right, but anyone with a shortest-path rule over derived edges will see a fact disappear, so it's worth saying here, e.g. "A rule calling NOW(), RAND(), UUID() / STRUUID() or BNODE(), or binding a shortestPath / allShortestPaths, derives from a single evaluation over the final state of what it reads." Minor and non-blocking, but if you agree I'd rather see it folded in now.
| } | ||
| } | ||
|
|
||
| let facts = state.derived.len(); |
There was a problem hiding this comment.
🟡 Optional — a debug-only closing pass would turn a missed dependency edge into a loud test failure everywhere.
This is more of a suggestion than a recommendation. The old loop proved its fixpoint: its last round re-ran every rule and derived nothing. The dependency schedule asserts the fixpoint instead, from the footprints, so a read the walk under-models is a silently short answer rather than a slower convergence (see the composite-step comment). Every CI test run is a debug build, so a check here costs nothing in release and would make every datalog program in the suite (JSON-LD forms, cross-ledger rules, annotations, shapes the random generator doesn't produce) double-check the analysis.
Something like this (illustrative). It has to skip non-repeatable rules, and it mustn't count toward rule_body_runs, which the schedule tests assert exactly:
#[cfg(debug_assertions)]
if capped.is_none() && schedule == RuleSchedule::Dependencies {
// Every repeatable rule, once more over everything derived, must add
// nothing: otherwise the dependency analysis missed an edge into it.
// Rebuild the overlay from `state.derived`, run each repeatable rule's
// body, and debug_assert! that every instantiated head is already in
// `state.seen`, naming the rule.
}I prototyped roughly this at e574b9189, before the semi-naive commits. Across all 160 grp_reasoning tests there it stayed silent (no false positives), and with the subquery arm reverted it fired immediately on a consumer-first subquery program, naming the rule. It only fires on a program that actually crosses a missed edge, so it complements the rows in the other comment rather than replacing them. It also still fits with semi-naive evaluation, since it re-checks the final state rather than the delta. None of the 17 consumer-first programs I tried found a missed edge, so this is cheap insurance for the next change to the walk, not a fix for something broken.
| if new_this_round == 0 { | ||
| break; | ||
| /// Whether a fact with predicate `p` visible in `db` has a literal object. | ||
| async fn has_literal_object(db: GraphDbRef<'_>, p: &Sid) -> Result<bool> { |
There was a problem hiding this comment.
🟡 Optional: has_literal_object materializes every fact of the path predicate to answer a yes/no question.
db.range(IndexType::Psot, RangeTest::Eq, …) returns a Vec<Flake> holding all of T's facts before .any(..) looks at the first one. So a left-linear closure over a predicate with a few million edges decodes and allocates all of them once per materialization, on top of the traversal itself. I haven't measured it, and I don't think it dominates, since the path reads most of those edges anyway. An existence probe that stops at the first literal (a FILTER(isLiteral(?o)) body with LIMIT 1, or a bounded range) would make the common all-IRI case nearly free. Minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| } | ||
| } | ||
| } | ||
| let keep_pattern = triple.dtc.is_some() |
There was a problem hiding this comment.
👍 The "the seed replaces the pattern only when it matches exactly as a scan would" rule held up under everything I threw at it. I ran a differential of 23 targeted programs × 12 graphs: constant subjects and objects, a repeated variable, a variable predicate, rdf:type recursion, mutual and three-atom recursion, and rules that re-run whole mixed with seeded ones in one group. I also joined seeded literal bindings of eight datatypes against base literals. All of it matched WholeProgram exactly. Your mutation list holds up too: seeding only the first recursive atom, or leaving the delta stuck at the first pass, each turns your tests red.
| let reasoning = response | ||
| .reasoning | ||
| .unwrap_or_else(|| panic!("{program}: no reasoning outcome was reported")); | ||
| assert!( |
There was a problem hiding this comment.
👍 Rejecting a capped sample, or one that derived a different fact count, instead of timing it is exactly right for this bench. A materialization that quietly does less work is the one regression that would otherwise show up as a speedup.
A rule body ran to completion, collecting every result row, before any head was instantiated and before the fact, memory or time budget was checked. A body that matched far more rows than the budget allowed did all of that work first. The transitive-closure lane made it worse: its one path body returns the whole closure, so on a 2000-node chain with a 20,000-fact budget it produced 1,999,000 rows and took several times the time and memory of iterating, which the budget does bound. Rule bodies now run through the streaming executor, and a sink instantiates heads as each batch arrives. Reaching the fact or memory budget, or the deadline, stops the body. The only work that still runs in full is what an operator does before returning its first row. The one such operator a closure body uses is a property path with both ends free, which computes every pair up front. The execution context gains a path pair limit for it; past the limit the path fails with a resource-limit error. The closure lane sets the limit to one more than the facts (or memory) the budget still has room for, and on overflow the rule iterates instead, as it already did on the visited-node limit. The wasted work is about one budget's worth of pairs. Nothing else sets the limit.
The dependency schedule trusts the footprint walk to see every read: a read it misses makes a rule run once, too early, and derive a short answer. Three arms of the walk had no test, and reverting any of them left the suite green. - A one-or-more path over a sequence, `(ex:owns/ex:watched)+`, reads every step's predicate. Without the later steps, a rule listed before the rule writing `ex:watched` derived nothing under the dependency schedule. The new execution test pins that case, and the random differential gains a sequence-path body. - A GRAPH block reads its named graph. A named graph's IRI may denote the default graph, so the producers cannot tell a scoped read from an unscoped one; the test checks the read's footprint directly. - An edge annotation reads the annotated triple, the reifier predicates and its body.
Derived facts carry the query's `t`, and when two ops on one fact share a `t` the retraction wins. So at the `t` of a commit that retracted the stored copy of a fact the rules derive again, the retraction hid the derived fact. One commit later it was visible again. Rule bodies reading the overlay missed it while the fixpoint ran, and so did the query. Semi-naive seeds read the derived facts directly, so the dependency schedule derived the full answer while the whole-program reference did not. On a seven-node chain with two such retractions that was 21 facts against 17, and the query still dropped the two retracted pairs. The reasoning overlay now drops a stored retraction when the derived side asserts the same fact at the same `t`. The rules derived that fact from the state after the commit, so it holds. The check costs nothing unless both sides have flakes in range and the base side has a retraction, and then it is a binary search per retraction. The overlay is shared with OWL 2 RL, which gets the same fix; reasoning is refused for history queries, so no history view changes. The random schedule differential now retracts some facts in a second commit, and a targeted test checks both the schedules and the query answer for every closure shape.
|
@aaj3f On the premise-visibility question (note 3 in your review): the current contract is fine for now. A derived fact is judged by its own triple, and a conclusion is protected by denying its predicate. We can add an option for premise-respecting materialization later if people want or need it. |
Brings in #2120 (datalog dependency scheduling). Ported to next's annotation links: - the dependency walk reads an edge annotation through its `rdf:reifies` link, so the Reifier footprint also overlaps `rdf:reifies` writes; next has no `AnnotationTarget` pattern, and `TermComponents` reads no facts of its own - `collect_predicates` goes with main's scheduler; next's edge-annotation arm for it is dropped - the annotation_hydration/annotation_planner benches next removed stay removed beside main's new datalog_fixpoint bench - main's new tests await next's async `genesis_ledger`
Brings in 57bf7a9 (#2120, #2009). Two conflicts: - fluree-db-api/src/commit_transfer.rs: #2009 routes a push's graphs to the ids the ledger's graph registry gives them. The push's retraction check reads its slots through that routing as it is; only the routing struct's doc comment conflicted, and main's is kept. - fluree-db-transact/src/parse/jsonld.rs: #2009 reworks JSON-LD graph scoping, and carries the delete templates' `ill_typed_as_stored` that this branch reverts (call 2, aa1b3e6). Main's file is kept and the revert applied to it again: a delete template refuses an ill-typed literal, as #1988 had it.
Summary
Datalog rules are evaluated faster, with the same results apart from the cases under Behavior changes. Two changes:
The previous evaluation stays available as
RuleSchedule::WholeProgramand is the reference the differential tests compare against.Partially addresses #1557: semi-naive seeding and dependency staging cut the work per pass and the number of passes, and the derived overlay is no longer rebuilt after the last pass. Every pass with more to come still rebuilds the overlay from all facts derived so far.
FLUREE_BENCH_SCALE=small cargo bench -p fluree-db-api --bench datalog_fixpoint, 100 chains of 16 nodes, same laptop:The first three programs are transitive closures, so their last column measures closure compilation on top of semi-naive evaluation. The iterated program carries a filter that keeps it off the path lane, so it isolates semi-naive evaluation.
Commits
Derived-fact policy contract and baselines. Tests pin the existing contract: a derived fact is filtered by its own predicate, and the closure is shared across callers. The docs now state that RDFS rewriting and OWL 2 RL materialization can answer the same query differently under one policy. Adds the
datalog_fixpointbench, which measures the first reasoning query after a commit and rejects every sample that was capped or derived an unexpected fact count.Dependency analysis (
fluree-db-query/src/datalog_rules/dependency.rs). Each parsed rule carries a footprint: the graph-qualified predicates and classes its body may read and its heads may write. Strongly connected components of the read/write graph are the recursive groups. The analysis over-approximates wherever it cannot be exact: a variable predicate, a wildcard or zero-length path, a variable-predicate head, or an unmodelled construct counts as touching every predicate.rdf:typeis qualified by class.Scheduling (
execute.rs). Groups run in stages; each group's stage is one past the latest stage it reads from, and groups in a stage share one overlay per pass. The deadline is also checked after each rule body and every 1,024 rows while heads are instantiated; otherwise a single-pass rule could run past the deadline and report completion.Semi-naive evaluation (
delta.rs). A rule's recursive atoms are its top-level triple patterns that may match one of its group's writes. After the group's first pass, the rule runs once per recursive atom, with aVALUESseed binding that atom's variables to the facts its group derived in the previous pass; the rest of the body reads the full overlay.?x anc ?y . ?y anc ?zruns twice per pass, so a new fact in either position is extended.UNION,EXISTS, subquery, property path or trailingVALUESblock re-runs its whole body every pass, as before.Closures as property paths (
closure.rs). Over the facts visible when the group starts, each rewritten body derives exactly what the rule's fixpoint derives:T(x,y) . R(y,z) → R(x,z)T+(x,y) . R(y,z)R(x,y) . T(y,z) → R(x,z)R(x,y) . T+(y,z)R(x,y) . R(y,z) → R(x,z)R+(x,y) . R(y,z)Tmay be written in either direction; the body must be exactly those two patterns with constant predicates, and the head exactlyR(x,z). The nonlinear form keeps its last hop as a triple pattern, sinceR+(x,z)would re-derive one-hop asserted facts the rule never derives. The path operator follows only IRI-valued objects, so the left-linear shape compiles only after a scan finds no literal object ofT's predicate. A traversal that hits the visited-node limit falls back to iteration.Non-repeatable rules re-run in full. A rule calling a volatile function such as
STRUUID(), or readingt/opmetadata a seed does not carry, is never seeded.The budget stops rule bodies (
execute.rs,property_path.rs). A body used to run to completion, buffering every row, before the budget saw any of it. On a 2000-node chain with a 20,000-fact budget the closure lane produced 1,999,000 rows first. Heads are now instantiated as a body's rows arrive through the streaming executor, so reaching the fact, memory or time budget stops the body. A path with both ends free still computes all its pairs before returning a row. For that case the closure lane sets a pair limit one past what the budget has room for, and on overflow the rule iterates instead, as it does on the visited-node limit.Every footprint arm is tested. The sequence steps of a
+path, GRAPH scopes and edge annotations had no test. Without the sequence steps, a rule listed before its producer derived nothing.A derived fact stays visible at the
tof its retraction (reasoning.rs). This was already broken onmain. Derived facts carry the query'st, and an equal-ttie goes to the retraction. So at thetof a commit that retracted the stored copy of a fact the rules derive again, the fact disappeared, and it came back one commit later. The reasoning overlay now drops a stored retraction that a derived fact restates at the samet.docs/query/datalog-rules.mdcovers the behavior and how to write rules that get it;docs/design/rules-engine.mdgives the algorithms and why they derive the same facts.Behavior changes
NOW(),RAND(),UUID()/STRUUID()orBNODE(), or binding ashortestPath/allShortestPaths, is evaluated once per materialization, over the final state of what it reads. Re-run every round, aSTRUUID()rule never converged, and a shortest-path rule over derived edges also kept the lengths it found in earlier rounds. A volatile rule inside a recursive group still re-runs each pass, and a warning names it.tof a commit that retracted the stored copy of a fact the rules derive again, the fact is now visible. This applies to OWL 2 RL too, which shares the overlay.reasoning.iterationscounts passes across all stages, and a transitive-closure group reports one pass.fluree-db-query,DatalogRuledropsdepends_on/generates, and rule sets keep insertion order. New public items:RuleSchedule,run_fixpoint_with_schedule,DatalogExecutionResult::{rule_body_runs, body_rows}, the dependency types, andpath_pair_limitonExecutionContextandContextConfig.Tests
it_datalog_rule_schedule:STRUUID()rule derives one value per subject.+paths over a predicate or a sequence,*paths, fresh-term heads, literal-valued facts, three-pattern chains, variable predicates, repeated variables, constant subjects, reads nested inUNIONandEXISTS, and facts retracted in the latest commit.it_datalog_rule_dependencies: dependencies over rules from the JSON-LD and SPARQL parsers. Covers class qualification, variable predicates, property paths and their sequence steps, GRAPH scopes, edge annotations,EXISTSnested in aFILTER, zero-length paths and repeatability.it_datalog_semi_naive: a recursiveSTRUUID()rule hits the pass limit like the reference, and one filtering ont(?z)derives the complete closure; on a 24-node chain each ancestor fact comes from exactly one body row; a nonlinear rule runs once per recursive pattern per pass; reads in aUNION,EXISTS, subquery or?path still reach the full closure; literal constants and repeated variables still match exactly.it_datalog_closure_paths: all five closure shapes run in one pass and match the whole-program schedule over a graph with a cycle, a self-loop, branching, asserted and literal-valued facts, and edges in a named graph; a left-linear closure over a literal object iterates; five rules one step away from a closure keep iterating; a 79,800-pair closure stops near a 2,000-fact budget. On test-sized data the planner runs the closure path once per row of its triple pattern, so the pair limit is tested at the operator, inproperty_path.rs.it_datalog_program_reachability: a two-recursion program compared against closures computed in test code, under both storage modes and two rule orderings.it_reasoning_policy_contract: denied derived predicates stay hidden through a scan, a join, a count and a property path, on novelty and indexed storage.Each regression test was confirmed to fail with the code it pins broken, including: zero-length paths reading only their own predicate, recursive groups not iterated, no seeding, seeding only the first recursive pattern, ignoring nested reads, always replacing the pattern, seeding non-repeatable rules, skipping the literal check, the
R+(x,z)nonlinear form, ignoring the step's direction, and disabled scan and path policy filters. The same goes for a sink that never stops the body, an ignored pair limit, each footprint arm reverted in turn, and keeping the equal-tretraction.