Skip to content

Stratified datalog programs: evaluation time, negation, aggregates, named graphs - #2122

Merged
bplatz merged 13 commits into
mainfrom
feat/datalog-run-contract
Oct 19, 2026
Merged

bplatz merged 13 commits into
mainfrom
feat/datalog-run-contract

Conversation

@bplatz

@bplatz bplatz commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Datalog rule programs can negate, aggregate, and derive into and read from named graphs, under a run contract that makes those conclusions trustworthy:

  • One evaluation time per run. NOW() and TODAY() in rule bodies return a single time for the whole materialization: the commit time of the queried snapshot, or the time the query requests.
  • Stratified negation and aggregates. NOT EXISTS and grouped subqueries in rule bodies, as long as a rule negates or counts only facts that are complete before it runs.
  • Named graphs. A head can derive into a named graph, and a body can read one.
  • No conclusion from partial input. A run whose budget cuts off a negating or aggregating rule, or the OWL 2 RL closure it reads, fails instead of answering.

Stacked on #2120.

Commits

  1. Run contract. NOW()/TODAY() read ExecutionContext::evaluation_time, which rule bodies always set: the query's "reasoningTime" (also accepted in opts) or SPARQL # PRAGMA reasoning-time:, else the commit time of the queried snapshot, so a query asOf an earlier commit evaluates at that commit's time. A snapshot with no commit of its own fails a program that reads the clock, rather than falling back to the wall clock. A requested time is part of the reasoning cache key. QueryCancellation::with_deadline in fluree-db-core lets the time budget interrupt a running rule body at its next checkpoint. ReasoningDiagnostics and ReasoningTally gain capped_rules, pending_rules and evaluation_time; the Raft-recorded tally mirror deliberately does not carry them, since adding fields would change the positional wire form of records already in the log. A bare query-time rule's @id now names it.
  2. Stratified negation. NOT EXISTS — JSON-LD ["not-exists", …], SPARQL FILTER NOT EXISTS, or !EXISTS as a filter condition. Reads under a negation are recorded as negated_reads and stay ordinary reads too, so a negating rule's stage comes after every rule that can write what it reads. RuleDependencies::unstratified rejects a negation of the rule's own recursive group and spells out the cycle (ex:a -not-> ex:b -> ex:a). A variable a negation shares with the rest of its group must be bound by a positive pattern.
  3. Grouped aggregates. A grouped subquery in the body — SPARQL { SELECT ?k (COUNT(?x) AS ?n) WHERE { … } GROUP BY ?k }, JSON-LD ["query", {…, "groupBy": […]}] — with any aggregate and HAVING, under the same stratification (-agg->). Counting follows query semantics: a group exists only when some solution falls in it, solutions are a bag (COUNT(DISTINCT …) counts entities), a fact both asserted and derived counts once, and owl:sameAs aliases are counted as stated.
  4. Named graphs. A head names its graph with GRAPH <iri> { … } in a SPARQL CONSTRUCT template, "@graph": "<iri>" on a JSON-LD insert node, or a named graph object {"@id": <iri>, "@graph": [ … ]} (that shape used to derive into the default graph, ignoring its @id). The graph must be an existing user named graph; the default graph, system graphs, missing graphs and variable graphs are refused by name. DerivedFactsOverlay partitions facts by graph; the same triple derived into two graphs is two facts. A rule reading a named graph runs after the rules deriving into it, and datasets see derived facts through their named graphs.
  5. Acceptance program. A program combining recursive ownership (partly OWL 2 RL entailments), a count of transactions within a window of the evaluation time, and a negation over exceptions at or above an account's holder, checked state by state against plain GROUP BY / FILTER NOT EXISTS / property-path queries. The negative-cycle error now names the facts the rule negates or aggregates, with IRIs spelled out. A negating or aggregating program also fails when OWL 2 RL fails outright, as it already did when OWL 2 RL is capped; a positive program still runs without the OWL facts.

Behavior changes

  • NOW()/TODAY() in rule bodies return the commit time (or the requested time) instead of the wall clock; a program calling them on a snapshot with no commit time needs reasoningTime.
  • A capped run that leaves a negating or aggregating rule unfinished, or an OWL 2 RL cap or failure ahead of such a program, fails with an error naming the rule. Positive programs still answer capped.
  • RuleSchedule::WholeProgram refuses programs with negation or aggregation.
  • Under rdfs or owl2ql without owl2rl, a program with a rule that negates or aggregates is refused with an error naming the rule. Rule bodies don't see those rewrites, so the rule would read an entailed fact as absent and contradict the query's answer. With owl2rl the entailments are materialized and the rewrite is skipped, so the two agree. This applies when the modes come from f:reasoningDefaults too.
  • Still rejected in rule bodies: MINUS (the error points at NOT EXISTS), OPTIONAL, top-level GROUP BY (the error points at the subquery form), LIMIT/OFFSET.
  • A JSON-LD rule whose insert names a graph, written {"@id": "ex:g", "@graph": [ … ]} or with "@graph": "ex:g" on an insert node, used to derive into the default graph. Its facts now go into ex:g, and if the ledger has no ex:g, every datalog query on the ledger fails with an error naming the graph. A head naming the graph the query runs against derives into it, as a head with no graph does.
  • Reasoning keys are read key by key: each from the top level when it is there, else from opts. A top-level reasoningBudget or reasoningTime beside opts.reasoning used to make the top level the only source and drop the mode in silence.
  • JSON-LD where clauses in this PR's tests name graphs by full IRI; a compact graph name was matched as written. Reasoning stops with its query and counts as its fuel; explain derived facts; compact JSON-LD graph names #2126 fixes that.

Follow-up: #2139, running rule bodies under the query's rdfs/owl2ql rewrites so the refusal above can go.

Fixes #1883.

Tests

  • it_datalog_run_contract: a recursive NOW() rule converges with one stamp per node; the default time falls inside the commit's window and is stable across reruns; a query of an earlier commit evaluates at that commit's time; an empty ledger needs a requested time; two requested times answer differently and are cached apart; the pragma sets the same clock; a 20 ms budget stops a body that runs for about 28 seconds uninterrupted; a capped run names the rules it cut short and those it never ran.
  • it_datalog_negation: negation over a recursive closure reads it only once complete; JSON-LD and SPARQL spellings agree; negation stacks across three strata; a recursive rule may negate a lower stratum; cycles, unbound negated variables and MINUS are rejected; a budget or capped OWL closure ahead of a negating rule fails the run.
  • it_datalog_aggregates: counts per group on novelty and indexed storage with a SPARQL twin; a count over a recursive closure counts the finished closure; bag versus DISTINCT; duplicates of asserted facts count once; the implicit group counts zero; SUM with HAVING; sameAs aliases are not inflated; a budget that stops before an aggregating rule fails.
  • it_datalog_named_graphs: SPARQL and JSON-LD heads derive into the named graph and nowhere else; a chain stages facts in one graph and reads them into another, with recursion inside the named graph; a dataset sees the facts; one triple in two graphs stays two facts; bad graphs are refused by name; a group writing into both graphs matches the whole-program reference.
  • it_reasoning_policy_contract: for facts derived by negation, by an aggregate and into a named graph, a reader who cannot see a premise still gets the conclusions the shared closure computes from all the data (the restricted reader queries first, so it is the one that materializes), and a reader denied the derived predicate sees none of it; on novelty and on an index.
  • it_datalog_program_assessment: the acceptance program as JSON-LD and as SPARQL rules, over novelty and over an index with later commits in novelty, through an exception added two levels up and retracted, a contributing transaction deleted, the clock moving a transaction out of the window with nothing committed, and a late transaction dated inside it. A sweep over every fact budget checks that a run stopped in the OWL pass, the recursion, the count or the negation fails rather than answers. An exemption that negates candidacy is rejected as a cycle, with the rules and the negated predicate named. On file storage, the stored rules conclude the same in a new instance (asked about a time the first never was, so the rules load from storage) and after a reindex.
  • it_datalog_named_graphs also runs named-graph rules over a published index, then after a commit lands in novelty.

Each test was confirmed to fail with the code it pins broken, including: no deadline on rule bodies, NOW() ignoring the evaluation time, the wall clock as the default, a cache key without the requested time, negated or aggregated reads creating no dependency edge, the stratification or safety check skipped, no failure on an unfinished non-monotone rule or a capped OWL closure, derived facts not routed by graph, a dedup key without the graph, seeds taken from any graph, OWL entailments hidden from datalog, and the pinned clock ignored. The refusal when OWL 2 RL fails outright has no test: only a storage read failure triggers it.

@bplatz bplatz added enhancement New feature or request area:datalog Reasoner, rules, reasoningDefaults labels Oct 15, 2026
@bplatz
bplatz requested a review from a team October 15, 2026 09:45
@bplatz
bplatz added this pull request to stack #2125 October 15, 2026 09:45
@bplatz
bplatz removed this pull request from stack #2125 October 15, 2026 11:34
Base automatically changed from feat/datalog-semi-naive to feat/datalog-dependency-scheduling October 15, 2026 11:36
@bplatz bplatz changed the title Datalog runs: one evaluation time, deadline-bound rule bodies, cap attribution Stratified datalog programs: evaluation time, negation, aggregates, named graphs Oct 15, 2026
@bplatz
bplatz added this pull request to stack #2128 October 15, 2026 11:39
@bplatz
bplatz force-pushed the feat/datalog-run-contract branch from bd41cc5 to b52ac39 Compare October 15, 2026 20:08
Base automatically changed from feat/datalog-dependency-scheduling to main October 15, 2026 21:25
…s, cap attribution

NOW() and TODAY() in rule bodies read one evaluation time for the whole
materialization instead of the wall clock on every call. The time is the
query's "reasoningTime" (SPARQL: # PRAGMA reasoning-time:), else the
commit time of the queried snapshot, so a query asOf an earlier commit
evaluates at that commit's time. A snapshot with no commit of its own (an
empty ledger, uncommitted changes) fails a program that reads the clock
instead of silently using the wall clock. A requested time is part of the
reasoning cache key. With one time per run, both functions count as
repeatable, so such rules schedule like any other.

Each rule body now runs under a cancellation handle that times out at
the reasoning budget's deadline (QueryCancellation::with_deadline), so a
body that outlasts the budget stops at its next checkpoint instead of
running to completion.

A capped run names the rules the cap cut short (capped_rules) and the
rules it kept from running (pending_rules) in its diagnostics and the
tracked response's reasoning block, along with the evaluation_time used.
The Raft-recorded tally mirror does not carry the new fields, so its
positional wire form is unchanged. A query-time rule's @id now names it.
Rule bodies may now use NOT EXISTS: JSON-LD ["not-exists", ...], SPARQL
FILTER NOT EXISTS, or !EXISTS as a filter condition. A negating rule runs
only after every rule that can derive what it negates has finished, so a
negation never sees a partial result, and negation stacks across strata.

Reads under a negation are recorded as negated reads in the rule's
footprint and still create ordinary dependency edges. A program in which
a rule negates facts that depend on its own conclusions has no
stratification and is rejected with the cycle spelled out
(ex:a -not-> ex:b -> ex:a). A variable a negation shares with the rest of
its group must be bound by a positive pattern of that group.

A capped run that leaves a negating rule unfinished fails with a resource
limit error naming the rule instead of answering from partial
conclusions, as does an OWL 2 RL cap ahead of a negating program, since
the OWL closure is datalog's input. Positive programs still answer capped.
The whole-program reference schedule refuses programs with negation.

MINUS and OPTIONAL stay rejected; MINUS's error now points at NOT EXISTS.
A rule may now aggregate in a subquery of its body and use the results in
its head: SPARQL { SELECT ?k (COUNT(?x) AS ?n) WHERE { ... } GROUP BY ?k },
JSON-LD ["query", {..., "groupBy": [...]}], with any aggregate function
and HAVING. GROUP BY at the top of a body stays rejected, now with a
pointer to the subquery form; LIMIT and OFFSET stay rejected everywhere.

Aggregation is stratified like negation. Reads inside a grouped subquery
are recorded as aggregated reads and order the rule after everything it
counts, so a count over a recursive relation counts the finished closure.
A rule that aggregates facts depending on its own conclusions is rejected
with the cycle named (ex:a -agg-> ex:b -> ex:a). A capped run that leaves
an aggregating rule unfinished fails, as does an OWL 2 RL cap ahead of one.

Counting follows query semantics: a missing group derives no fact, an
implicit group over nothing counts zero, subquery solutions are a bag
unless DISTINCT is written, a fact both asserted and derived counts once,
and owl:sameAs aliases are counted as stated.
A rule head can name the graph it derives into: a CONSTRUCT template's
GRAPH <iri> { ... } block, or "@graph": "<iri>" on a JSON-LD insert node
as in a transaction (a JSON-LD named graph object
{"@id": <iri>, "@graph": [...]} assigns its nodes). That JSON-LD shape
previously derived into the default graph, ignoring its @id.

Derived facts are visible only in their graph: to GRAPH patterns in
queries and rule bodies, and through a dataset's named graphs, where the
executor now splices the reasoning overlay into every graph of the ledger
that holds derived facts. A rule reading a named graph runs after the
rules deriving into it, so programs can stage results in one graph and
build on them in another, and recursion can reach its closure inside a
named graph. The same triple derived into two graphs is two facts.

DerivedFactsOverlay now partitions facts by graph id; OWL 2 RL facts stay
in the default graph, and a datalog fact with no graph belongs to the
graph the rules run against. A head graph must be a constant IRI naming a
user named graph the ledger already has; the default graph, system graphs
and unknown graphs are refused with the graph named. Semi-naive seeds
hold only facts of the graph the rules run against, and a transitive
closure with a graph head is not compiled to a path.
A program that combines recursion over ownership (partly OWL 2 RL
entailments), a count of transactions within a window of the evaluation
time, and a negation over exceptions held at or above an account's
holder. Each state is compared with the same answer from ordinary queries
(GROUP BY, FILTER NOT EXISTS, a property path) over the asserted facts and
with spelled-out expectations, as JSON-LD and as SPARQL rules, over
novelty and over an index with later commits in novelty. The states are
the ones a commit or the clock changes: an exception added two levels up
and retracted, a contributing transaction deleted, the clock moving a
transaction out of the window with nothing committed, and a late
transaction dated inside it. A sweep over every fact budget checks that a
run stopped in the OWL pass, the recursion, the count or the negation
fails instead of answering.

A negative cycle now names the facts the offending rule negates or
aggregates, with IRIs spelled out, as well as the rules on the cycle.

When OWL 2 RL fails outright, a program that negates or aggregates now
fails too, as it already did when OWL 2 RL is capped: it would read the
missing entailments as absent. A positive program still runs without
them.

Also pins that a query of an earlier commit evaluates NOW() at that
commit's time.
The reasoning tally gained capped_rules, pending_rules and
evaluation_time, which grew AppliedReceipt past clippy's limit on the
size gap between WaiterOutcome's variants. Box it: the outcome is sent
once per transaction.
…lies

Like reasoning and the reasoning budget pragmas, reasoning-time is
applied where the query is lowered, not by the header translators.
…t, reindex, index

Three gaps in what the stratified features were tested against:

- Policy. For facts derived by negation, by an aggregate and into a named
  graph, a reader who cannot see a premise still gets the conclusions the
  shared closure computes from all the data (the restricted reader queries
  first, so it is the one that materializes), and a reader denied the
  derived predicate sees none of it. On novelty and on an index.
- Restart and reindex. The acceptance program's stored rules, on file
  storage, conclude the same in a new instance over the same directory,
  asked about a time the first instance never was so the rules load from
  storage rather than the process-wide cache, and after a reindex.
- Named graphs over an index. Rules derive into and read from named
  graphs over a published index, and again after a commit lands in
  novelty.
@bplatz
bplatz force-pushed the feat/datalog-run-contract branch from b52ac39 to 49727f0 Compare October 15, 2026 21:25

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bplatz this is carefully built, and at a design level I have no pushback. One evaluation time per run, pinned to the queried commit, is what makes stratified answers safe to cache; partitioning the derived overlay by graph is the right shape for named-graph heads; and negation and aggregates reuse #2120's footprints and stages rather than adding a scheduler. I tried to break the stratification from the outside (composite and inverse paths, alternatives, sub-selects, variable heads, two recursive strata, aggregates inside a seeded recursion) and every shape agreed with a plain FILTER NOT EXISTS / GROUP BY oracle. Two notes:

  1. Rule bodies run with reasoning off, so under query-time rdfs/owl2ql a negation or count reads less than the query that asks for its conclusions. A ledger that defaults to rdfs hits this with a query that only says "datalog". Your call whether rules read through the query's rewrite modes or non-monotone programs are refused there; either is fine with me as long as the contradiction can't come back quietly.
  2. #1883 is yours to decide, and reasoningTime adds a second modifier key to its all-or-nothing election. A top-level reasoningTime beside opts.reasoning silently runs without reasoning (I checked). This seems like the cheapest moment to settle #1883 rather than add to it.

Good to merge once the must is in.

Full review below:


✅ Approving to unblock you — with 1 thing that needs to be addressed before this merges.

This is really nice work, @bplatz, and most of it held up everywhere I pushed. The run contract: on a cold published index the default evaluation time matches what novelty reports, at head and at @t:1, still right after a commit lands in novelty above the index, and two branches with their own commits at the same t evaluate at their own commit times. The named-graph partitioning: rules that read a named graph, recurse inside the head graph and derive a triple also asserted there agreed across novelty, a cold index and index-plus-novelty. The stratification: negated and aggregated reads stay ordinary reads, so the stage order falls out of #2120's stages, cycles through -not-> and -agg-> are refused with the path spelled out, and a run that can't finish a negating or aggregating rule fails instead of answering. And the tests have teeth: dropping the requested time from the cache key turns six red, taking the deadline off rule bodies turns the_deadline_interrupts_a_running_rule_body red, stopping negated reads from creating edges turns ten red, and taking aggregates out of the cap check turns two red.

The equal-t tie and the closure-lane cap I flagged on #2120, which you fixed before it merged, hold up through this PR too. At the t of a commit that retracted an asserted copy of a fact the rules re-derive, NOT EXISTS, a grouped COUNT and a head deriving into a named graph all see the derived fact now. And with a 20k-fact budget the 2000-node closure lane stops at 0.24 s and 58 MB.

The one thing I'd want in before merge is about what a negation or count reads, not about how the program is ordered:

  1. Under query-time rdfs or owl2ql, a rule's negation or count contradicts the query in the same request (fluree-db-query/src/execute/reasoning_prep.rs:425). Rule bodies run with reasoning off. With ["rdfs", "datalog"], a rule concludes ex:ann is an ex:Contractor (no ex:Employee type), while the same query returns ex:ann as an ex:Employee. A rule's count of employees also disagrees with the query's COUNT. The minimal fix is to refuse a non-monotone program under rdfs/owl2ql without owl2rl, the same way an OWL 2 RL failure is refused. Running bodies under the query's rewrites is the fuller option, and that's your call.

Should address:

  • 🟠 A head that names the query's own graph fails the whole query (fluree-db-query/src/datalog_rules/execute.rs:524, inline). A stored rule that derives into ex:inferred has to name it, so every reasoning query with ex:inferred as its default graph errors out, even one that reads no derived predicate. Treating that head as "derive into the graph the rules run against" looks like a few lines.
  • 🟠 reasoningTime joins the #1883 trap (fluree-db-query/src/parse/options.rs:540, inline): a top-level reasoningTime next to opts.reasoning runs with no reasoning and raises no error.

Optional:

  • ❓ Time travel by @iso: evaluates NOW() at the commit it lands on, not the instant it names; in my probe the two were 17 months apart (inline on execute.rs:449).
  • 🟡 This fixes "datalog with a named graph as the query's default graph derives nothing", which is broken on main. Nice! But nothing pins it: routing those facts back to graph 0 leaves all 223 grp_reasoning tests green (inline on reasoning_prep.rs:532).
  • 🟡 Nothing in this PR pins the equal-t case under a negation. I reverted main's fix (1d9231f53) on this branch: at the t of a commit that retracted ex:a ex:knows ex:b while a rule re-derives it from ex:friend, a NOT EXISTS { ?x ex:knows ?y } rule makes ex:a a loner again, a grouped count of its ex:knows disappears, and a head deriving the fact into a named graph loses it, yet every test this PR adds stays green; only main's two schedule tests go red, and those are positive programs. One row at the retracting t in it_datalog_negation (or it_datalog_named_graphs) would keep a negation from quietly concluding from a dropped fact again.
  • 🟡 Behavior changes in the PR body doesn't list the head-graph change for JSON-LD rules, though "Commits" item 4 mentions it. A stored rule written as {"@id": "ex:g", "@graph": [ … ]}, or with "@graph": "ex:g" on a node, used to derive into the default graph; now its facts move into ex:g, and if the ledger has no ex:g, every datalog query on that ledger fails. Release notes come from PR titles and there's no changelog, so the body is the only place someone upgrading would find that out.
  • 🟡 A few lines below the new NOW() paragraph, the docs still list NOW() among the functions that make a recursive rule re-run its whole body (inline on datalog-rules.md:722).
  • 🟡 A negation or aggregate over a variable predicate, a */? path or a !(…) set is always refused. The error message names the rule's own head rather than what was negated (dependency.rs:604). The docs still say such a footprint "costs speed, never correctness".
  • 🟡 "What absence means" could say that OWL 2 RL never runs over rule conclusions (docs/query/datalog-rules.md:398).

What I checked and found holding:

  • A fact cap in an unrelated recursion that shares a stage with an already-finished negation answers capped, and the negation's conclusions are right.
  • An iteration cap ahead of a negation fails the run.
  • A fact cap that fires inside a negating rule's own body or a counting rule's own body, and the deadline passing while a count is still grouping its input, all fail the query rather than answer from part of it.
  • Cycles through -agg->, through a three-rule mixed path and through a variable-predicate head are refused with the right path.
  • An aggregate never sees a semi-naive delta: a recursive rule counting a lower stratum matched a hand oracle across seeded passes.
  • owl:sameAs counts match a plain GROUP BY under both datalog and owl2rl.
  • A NOT EXISTS written before its binding pattern answers the same as after it.
  • A staged preview with a NOW() rule fails with the documented error, and works with reasoningTime.
  • Novelty, a cold index and index-plus-novelty all agree on derived counts, including a named-graph COUNT.
  • At a retracting commit's t, with the retraction in novelty and the assert in novelty or in a published index, the negation and the count come out as they do one commit later.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ It extends what's there rather than building beside it: #2120's footprints and stages, not a second scheduler; DerivedFactsOverlay partitions by graph behind the same OverlayProvider lookup; the deadline is a new constructor on QueryCancellation; reasoningTime and # PRAGMA reasoning-time: both lower to ReasoningModes::evaluation_time; and FILTER NOT EXISTS, !EXISTS, sub-SELECT and JSON-LD not-exists / ["query", …] lower to the same IR, tested on both surfaces.
  • Performance (speed first, memory second): ✔ No regression for positive programs. I timed four of them at main and here, 15 runs each, in five interleaved rounds: closure lane, iterated semi-naive, a recursion plus 12 acyclic rules, and a join-heavy downstream rule. Medians are within ±2.5%, with the same facts and body runs. This was a debug build, so the clock read the deadline adds at each checkpoint is if anything understated. Checkpoints happen per batch or per left row, never per flake. On the non-reasoning path nothing runs per row: one Option<DateTime> on ExecutionContext, one branch per checkpoint for handles without a deadline, and a find over a few graph partitions per overlay range call.
  • Deployment targets: ✔ This is shared engine code: solo's Lambdas and standalone binary reach it through fluree-db-api, and so does fluree-db-server. No background tasks, the deadline is a per-body handle, the reasoning cache stays an in-process LRU (now keyed by a requested time), and on wasm32 the deadline reads clock::Instant; wasm32 and wasm-smoke are green. The Raft RecordedReasoningTally is unchanged, so the recorded wire form is too. A request's own cancellation doesn't reach a rule body yet; #2126 adds that.
  • Testing: ⚠️ The new suites run in CI by name (nextest at 49727f055, 14,406 passed, all 9 it_datalog_run_contract and 8 it_datalog_named_graphs tests among them) and fail under mutation. Missing: the query-time-mode case above, the equal-t case under a negation, and the named-graph-as-default fix.
  • Conventions: ⚠️ Thorough multi-line commit bodies and docs, fmt and clippy green. Two misses: the stale NOW() sentence, and the Behavior changes bullet for JSON-LD head graphs.

Verified locally at 49727f055:

  • grp_reasoning: 223 passed, the new it_datalog_negation, it_datalog_aggregates, it_datalog_program_assessment, it_datalog_run_contract and it_datalog_named_graphs tests seen by name.
  • Mutations, each restored afterwards: requested time out of the cache key (6 red), no deadline on rule bodies (1 red), negated reads without edges (10 red), aggregates out of the cap check (2 red), aggregates out of the cycle check (1 red), derived facts routed back to graph 0 (0 red, the gap above), and main's equal-t fix reverted (2 red, both main's).
  • About 40 adversarial programs checked against plain-query oracles, plus probes on a cold index, across branches, under @iso: time travel and on the 2000-node closure.

Approving now so you can merge without waiting on another pass from me. Just be sure the must is in before you do.

// A positive program over a missing closure only derives
// less; one that negates or counts would read the missing
// entailments as absent.
if let Some((rule, construct)) = rule_set

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Must address before merge — under query-time rdfs or owl2ql, a negating or aggregating rule reads less than the query that asks for its conclusions, so one answer contradicts itself.

Rule bodies run with reasoning off (ExecutableQuery::new(body, ReasoningConfig::default()), fluree-db-query/src/datalog_rules/execute.rs:1005). OWL 2 RL entailments reach a body through the overlay, but rdfs and owl2ql are query rewrites, so a body never sees the subclass, subproperty or inverse entailments those modes give the outer query. A positive rule just derives less (pre-existing). A negation reads the missing entailment as absent, which is the same reasoning this block applies when OWL 2 RL fails.

What I ran at 49727f055 with "reasoning": ["rdfs", "datalog"]: ex:Manager rdfs:subClassOf ex:Employee, ex:ann a ex:Manager ; ex:worksAt ex:acme, and a rule deriving ex:Contractor for ?x ex:worksAt ?c with NOT EXISTS { ?x a ex:Employee }. The query ?x a ex:Contractor . ?x a ex:Employee returns ex:ann. A rule counting ex:Employee derives 1, while COUNT(?e) over ?e a ex:Employee in the same request returns 2, so "counting follows query semantics" doesn't hold here either. Same shape under owl2ql with owl:inverseOf: a rule concludes ex:bo has no ex:childOf while the query returns ex:bo ex:childOf ex:ann. With owl2rl on, the answers agree, since those entailments are materialized. And because ledger f:reasoningDefaults modes merge with the query's (docs/query/reasoning.md:279-284), a ledger defaulting to rdfs plus a query that only says "datalog" lands here.

Minimally, we could refuse a negating or aggregating program here when rdfs or owl2ql is on without owl2rl, naming the rule and pointing at owl2rl, the same way this block refuses one when OWL 2 RL fails. The fuller alternative is running rule bodies under the query's rewrite modes so a rule reads what the query reads; that would also change what positive programs derive under rdfs, so it's more of a call for you. Either way, "What absence means" in docs/query/datalog-rules.md should say which entailments a rule reads. Commenting here because execute.rs:1005 is outside this diff's hunks.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in c81d6ac

if g_id < FIRST_USER_GRAPH_ID {
return Err(refuse("a system graph, which rules cannot write"));
}
if g_id == db.g_id {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Should address: a head that names the query's own graph fails the whole query, not just that rule — and a stored rule can't avoid it.

HeadGraphs::resolve refuses a head graph equal to db.g_id ("leave the graph out to derive into it"). For a query-time rule that's fair advice, but stored rules serve every query on the ledger: a rule that derives into ex:inferred has to name it to be useful from the default graph, and then every reasoning query whose default graph is ex:inferred errors out, including one that never reads a derived predicate.

I reproduced it with the it_rules_source setup (rule stored in a rules graph wired by f:rulesSource, head "@graph": "ex:inferred"): {"from": {"@id": <ledger>, "graph": "http://example.org/inferred"}, "select": ["?x", "?y"], "where": {"@id": "?x", "ex:parent": "?y"}, "reasoning": "datalog"} fails with datalog rule http://example.org/kinRule derives into graph <http://example.org/inferred>, the graph the rules run against; leave the graph out to derive into it, while the same derived facts read from the default graph through ["graph", …] come back fine.

I think the refusal is there because a fact carrying g = Some(<run graph>) would be skipped by DeltaAtom::row (delta.rs:175) and deduplicated apart from the same fact with g = None. If so, a narrower fix is to treat such a head as deriving into the run graph: resolve it to "no graph" here (e.g. sids: HashMap<Arc<str>, Option<Sid>> with None for the run graph, and flake.g = state.head_graphs.sids.get(graph).cloned().flatten() at :953), so the fact is routed, seeded and deduplicated like any other run-graph fact and the refusal can go. If you disagree on the substance, happy to talk it through.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 7adb397

"rules",
"ontology",
"reasoningBudget",
"reasoningTime",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Should address: reasoningTime joins #1883's all-or-nothing election, so a top-level reasoningTime beside opts.reasoning runs with no reasoning, silently.

parse_reasoning elects the top level as the only source as soon as any key in REASONING_KEYS is present there. reasoningTime, like reasoningBudget, enables no mode by itself, but it still wins that election.

I ran {"from": <ledger>, "select": "?t", "where": {"@id": "?x", "ex:stampedAt": "?t"}, "reasoningTime": "2026-01-01T00:00:00Z", "opts": {"reasoning": "datalog", "rules": [ … ]}}: zero rows, no error. With reasoningTime moved into opts it returns the stamped row.

The PR body names this and points at #1883, which I appreciate. But #1883 is a decision about this surface, which is yours, and this PR adds the second modifier key to the trap; "time at the top level, mode in opts" is exactly the split someone writes after reading the new docs. I'd rather settle it here than grow it: #1883's option 1 (per-key merge: the top level wins key by key, opts fills the rest) fixes both modifiers in parse_reasoning, and its pinning test inverts as the issue describes. If you'd rather not change precedence yet, a narrower step is option 2 limited to modifiers: reject a query whose top level carries only reasoningBudget/reasoningTime while opts carries a mode, so nothing is dropped silently.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 9df833a

continue;
};
let facts = match negated.predicate {
PredicateFootprint::Any => write.describe(&iri),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional — a negation or aggregate over a variable predicate, a */? path or a !(…) property set is always refused, and the message names the rule's own head rather than what was negated.

An Any read observes every write, including the rule's own head, so every such rule is its own negative cycle. For a variable predicate that's the honest answer (ex:n0 ?p ?n can match a fact the rule derives). For a path with a constant endpoint it's stricter than it needs to be: the zero-hop match of ex:n0 (ex:edge/ex:link)* ?n is just ex:n0, which doesn't depend on new terms. I ran ?n a ex:Node FILTER NOT EXISTS { ex:n0 (ex:edge/ex:link)* ?n } in a rule deriving ?n a ex:Flag and got datalog rule ex:rule00 negates rdf:type http://example.org/Flag facts, which depend on its own conclusions (ex:rule00 -not-> ex:rule00; …). The user never wrote ex:Flag in the negation, so it reads like a bug in their program rather than a limit of the analysis. docs/query/datalog-rules.md:738-741 also still says an everything-footprint "costs speed, never correctness", which isn't the whole story once it can refuse a program.

Maybe for an Any read the message could say what the read was (e.g. "negates facts of any predicate (a variable predicate, a */? path or a negated property set), which include the rdf:type ex:Flag facts it derives"), and the docs line could add that a negation or aggregate over such a read is refused. Narrowing a constant-endpoint path's zero-hop read could come with it if you think it's worth it. This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 2e27fba

}
```

**What absence means.** A negation matches when nothing matches it in the

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional — "What absence means" could say that the OWL 2 RL entailments a rule reads are those of the stored data, never of other rules' conclusions.

OWL 2 RL runs once, before datalog, so a negation over an OWL consequence of another rule's conclusion reads it as absent. With ["owl2rl", "datalog"], ex:Manager rdfs:subClassOf ex:Employee, a rule deriving ex:ann a ex:Manager from ex:manages, and a rule deriving ex:Contractor for anyone with NOT EXISTS { ?x a ex:Employee }, ex:ann comes out an ex:Contractor. The final answer is self-consistent (ex:ann a ex:Employee is never materialized either), and the order is documented under "Interaction with OWL 2 RL", but with negation the result is a conclusion the ontology contradicts rather than just a missing fact.

One sentence here would make it visible, something like "OWL 2 RL entailments of the stored data (OWL 2 RL does not run again over rule conclusions, so a rule cannot negate an OWL consequence of another rule's conclusion)". Minor and non-blocking, but I'd rather see it folded in now than lost in the backlog.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in c81d6ac

/// one, else the commit time of the snapshot at `db.t`. A snapshot with no
/// commit at that `t` (an empty ledger, a staged view) has no time of its
/// own, and the wall clock would make the result depend on when it ran.
async fn resolve_evaluation_time(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ Question: should time travel by @iso: set the clock to the instant it names?

This is more of a question than a suggestion. resolve_evaluation_time takes the db:time of the commit at db.t, which is exactly right for @t:. For @iso:, though, the query names an instant and lands on the last commit at or before it, so NOW() can be a long way from the instant asked about.

I committed with event times 2020-01-01 (t1) and 2022-01-01 (t2) and queried <ledger>@iso:2021-06-01T00:00:00Z: evaluation_time came back 2020-01-01T00:00:00Z, 17 months before the instant in the query. So "what was overdue on 2021-06-01", asked the way time travel reads most naturally, answers as of January 2020.

I can see the case for the commit time (the cache key already pins it through to_t, while an @iso default would have to put the instant in the key). If you keep it, maybe one sentence where reasoningTime is introduced (docs/query/datalog-rules.md:722-732): time travel by @iso: evaluates at the commit it lands on, so pass the same instant as reasoningTime to evaluate at it. If you'd rather @iso: set the clock, the resolved instant would need to reach ReasoningModes::evaluation_time where the time spec is resolved; the cache key already covers a requested time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept the commit time and documented it; addressed in 2e27fba

let derived_overlay = Arc::new(builder.build_routed(
same_as,
overlay.epoch(),
crate::datalog_rules::derived_fact_graph(snapshot, g_id),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Optional: this fixes "datalog with a named graph as the query's default graph derives nothing", but no test pins it.

👍 first: on main, DerivedFactsOverlay::for_each_overlay_flake returns nothing for any g_id != 0, so a query with "from": {"@id": <ledger>, "graph": <named graph>} and "reasoning": "datalog" derives nothing at all. Routing g-less facts to g_id here (and to db.g_id in the fixpoint's overlay, execute.rs:380) fixes it: a two-rule ancestor program over a chain in ex:side, queried with ex:side as the default graph, now returns all three pairs, on novelty and on a cold published index.

But nothing holds it in place: I changed both sites to route to graph 0 and all 223 grp_reasoning tests still pass, because every test queries the default graph, where g_id is 0 anyway. One row in it_datalog_named_graphs with a named graph as the query's default graph would pin it.

Separately, and not introduced here: OWL 2 RL still derives nothing in that setup (a subClassOf in either graph), so ["owl2rl", "datalog"] can't chain there either. That's a gap in the OWL path rather than this PR's.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 7adb397

derives from a single evaluation. Inside a recursive group such a rule is
re-evaluated every pass and can keep deriving new values until the budget
stops it; Fluree logs a warning naming the rule.
- **`NOW()` and `TODAY()` read one evaluation time per run.** Every rule

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit: a few lines further down, the docs still describe the pre-run-contract behavior.

With NOW() and TODAY() now repeatable (dependency.rs, the reads_clock branch), :785-787 still lists NOW() among the functions "whose result changes between calls" that make a recursive rule re-run its whole WHERE every pass. Per this paragraph that's no longer the case, so maybe (RAND(), STRUUID(), …) there.

The list just above it (:783-784, "inside a UNION, EXISTS, subquery or property path") could also add GRAPH: a recursive rule reading its group's facts inside GRAPH ex:g { … } re-runs whole too, since only a top-level pattern is seeded (delta.rs:175).

Commenting here because those lines aren't in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 2e27fba

if self.aggregated && !self.footprint.aggregated_reads.contains(&access) {
self.footprint.aggregated_reads.push(access.clone());
}
if !self.footprint.reads.contains(&access) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Keeping negated and aggregated reads as ordinary reads is what makes the stratification hold.

The stage order falls straight out of #2120's dependency stages, so there's no second scheduler to drift. I reverted it (negated reads stop creating edges) and ten tests went red, including the three-strata and acceptance programs. I also tried to break it from the outside, with the negating or counting rule listed first each time: the derived predicate read only through (a/b)+ in either step position, ^p, (^p)+, (a|b), (a|b)+, a/b, a sub-select, a UNION, a nested EXISTS, and written by a variable-predicate or variable-class head. Every one agreed with a plain FILTER NOT EXISTS / GROUP BY query over the stored positive program, as did a recursive negating group over a recursive lower stratum.

…hout owl2rl

rdfs and owl2ql widen the query's own patterns; rule bodies run without
them. A rule that negates or counts then reads an entailment the query
sees as absent. With ex:Manager rdfs:subClassOf ex:Employee, a rule
concluded that a stored manager was a contractor because she was not an
employee, while the same response listed her as an employee, and a rule's
headcount disagreed with the query's COUNT. The query widens rule
conclusions too, so a derived manager met the same contradiction.

compute_derived_facts now refuses such a program with an InvalidQuery
that names the rule and points at owl2rl, which materializes those
entailments where rules read them and makes the rewrite step aside. The
check runs before the reasoning cache lookup, whose key leaves out rdfs
and owl2ql, so a cached datalog-only run of the same rules cannot answer
for them. Positive programs still run.

The reasoning docs said a query's modes merge with f:reasoningDefaults
and that RDFS rewriting runs after OWL 2 RL. A query's modes replace the
defaults, and the rewrite is skipped under owl2rl.
HeadGraphs::resolve refused a head graph equal to the graph the rules run
against. A stored rule serves every query on the ledger, and one deriving
into ex:inferred has to name it to be useful from the default graph, so
every reasoning query with ex:inferred as its default graph failed, even
one that read no derived predicate.

Such a head now resolves to no graph: its facts are routed, seeded and
deduplicated like any other fact of the run graph. The dependency analysis
already lets a default-graph read observe a named-graph write, so no
ordering edge is lost.

rules_run_over_a_named_graph_as_the_default_graph pins that rules over a
named default graph derive into it, on novelty and on a published index;
routing g-less derived facts to graph 0 left every reasoning test green
before it.
parse_reasoning made the top level the only source of reasoning keys as
soon as it carried any of them, so a modifier there beside a mode in opts
dropped the mode in silence: {"reasoningBudget": {...}, "opts":
{"reasoning": "datalog"}} ran without reasoning, and reasoningTime joined
reasoningBudget as a second key that did this.

Each key is now read from the top level when present and from opts
otherwise, so a request reads as if every key were written at the top
level. opts_ignored_when_any_top_level_reasoning_key_present inverts into
opts_fills_keys_the_top_level_omits, the_top_level_wins_key_by_key pins
the precedence for a key both carry, and the reasoning docs describe the
opts alias, which they never mentioned.
…ate reads

a_fact_retracted_at_the_query_t_is_still_negated_and_counted runs a
negation and a grouped count at the t of a commit that retracted the
stored copy of a fact the rules derive again, with the asserted copy in
novelty and in a published index. With the reasoning overlay's equal-t
fix reverted, the negation concludes from the dropped fact; before, only
two positive-program schedule tests noticed.

A negation or aggregate over a read of every predicate (a variable
predicate, a * or ? path, a negated property set) observes the rule's own
head, so it is refused. The error used to name only the head's facts, as
if the rule negated what it derives; it now says what read every
predicate, and which facts close the cycle.

Docs: that refusal joins the note that the dependency analysis costs
speed, never correctness; NOW() and TODAY() leave the list of functions
that make a recursive rule re-run its whole body, and a GRAPH block joins
the constructs that do; and time travel by @iso: evaluates at the commit
it lands on, so the instant goes in reasoningTime.
@bplatz
bplatz merged commit 87f5841 into main Oct 19, 2026
19 checks passed
@bplatz
bplatz deleted the feat/datalog-run-contract branch October 19, 2026 20:25
aaj3f added a commit that referenced this pull request Oct 20, 2026
…ferences

Brings in #2122, #2126, #2127, #2131 and #2133. The one conflict is in
fluree-db-api's re-exports, where #2131's `SharedFluree` / `SharedOptions`
and this branch's `target_dataset` items both land.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:datalog Reasoner, rules, reasoningDefaults enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

opts reasoning alias: a top-level reasoningBudget silently disables opts.reasoning

2 participants