Skip to content

fix(datalog): cross-ledger rules travel, a query can pin the rules it uses, and a run record says what ran - #2466

Open
aaj3f wants to merge 15 commits into
mainfrom
fix/cross-ledger-rules-travel
Open

aaj3f wants to merge 15 commits into
mainfrom
fix/cross-ledger-rules-travel

Conversation

@aaj3f

@aaj3f aaj3f commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2460: all four items. Item 3 (a pinned rules read) is a per-query rulesFrom, the option decided on the issue (#2460 (comment)), root-only for now.

Follow-up (not filed yet): letting a policy-restricted caller pick a rules source the data ledger's config trusts, and an audit of how view policy applies to rule premises and to derived facts.

Problem

A ledger's own f:rule values and the ones a cross-ledger f:rulesSource reads were read by two separate pieces of code, and they had drifted: the local extractor learned f:sparql (and refuses any other datatype by name), while the cross-ledger materializer kept only @json values and skipped the rest without a word. The same SPARQL rule ran when stored in the data ledger and vanished when stored in a rules ledger, which the cross-ledger docs call "the worst failure mode". Cross-ledger rules also travelled as anonymous query-time JSON (_:query_rule_N in errors), and were checked as query-time rules, whose stricter checks can flip a stored rule from valid to invalid as the data ledger changes.

Separately, nothing in a response said which rules ran. The tracked reasoning block carried the evaluation time but not the rule set or where it came from, so a caller recording "rules as of t = R over data as of t = D" had to trust its own bookkeeping; and rules_fired, which docs/query/reasoning.md describes, was never actually reported.

The same "asked for it, silently didn't get it" shape had two more members: a query that names a reasoning mode the ledger's config won't let it turn on (datalog with f:datalogEnabled false, a mode outside the config's forced set, or "none" against a forced set, all under an override control that denies the request) got an answer without that reasoning, and no error.

What changed

One reading of an f:rule value. stored_rule_source (fluree-db-query/src/datalog_rules/mod.rs) reads a value by its datatype (@json → JSON-LD, f:sparql → SPARQL, anything else None), and parse_stored_rule parses it. The local extractor and the cross-ledger materializer (cross_ledger/rules_materializer.rs) both use them, so they can't drift again.

  • The wire (RulesArtifactWire) carries each rule's IRI, language and source (ImportedRule). A value of any other datatype fails the request naming the rule and the datatype (TranslationFailed, 502), as malformed JSON already did; a malformed JSON body still fails closed, now naming the rule.
  • Cross-ledger rules arrive as ReasoningConfig::imported_rules, not appended to the query-time rules: they parse as stored rules, named by their IRI, and an invalid one fails the query naming it and its ledger (400). As before, the policy gate that strips caller-supplied rules doesn't touch them (it runs before they are attached); now that is by type rather than by ordering.

The tally says what ran. ReasoningTally gains:

  • rule_set: a SHA-256 over the rule set's names and per-rule digests. It changes when any rule changes, wherever it is stored. It is not the reasoning cache's key (that is a DefaultHasher value, and the standard library does not promise that hasher's output is stable across releases, which a run record has to be compared across); an explanation of a derived fact reports the same rule_set.
  • rules: each rule by name with the SHA-256 of its text, sorted by name, so one rule can be shown unchanged from one run to the next.
  • rules_source: where the stored rules were read, when not the queried graph: another ledger's graph, the t it resolved to and that ledger's commit_id (from the cross-ledger resolver, which already had it), or this ledger's own f:rulesSource graph at the query's t. Per request, not cached: two sources can share a rule set's content.
  • data: the ledger the rules ran over, its t, and its commit_id. At the head the loaded state already knows its commit, so there's no lookup; off the head it is one POST lookup on txn-meta (resolve_t_to_commit_id, made generic over the overlay rather than copied), run only for a tracked query that reasoned, never on the untracked lanes. A rebased ledger can have two commits at one t; then commit_id is left out rather than guessed. For a dataset it names the primary ledger.
  • rules_fired, the per-rule derived-fact counts the docs already described.

These reach the server's tracked response, the x-fdb-reasoning header (without rules_fired and rules, which grow with the program; they stay in the body) and Python: the binding's stats now include the reasoning block, as QueryProfile.reasoning. The Raft-recorded tally mirror does not carry the new fields, for the reason it gives for the others (the positional wire form of records already in the log).

Query-time rules are refused, not dropped, where they can't run (item 4). Under a non-root view policy, and where the ledger's config denies them for the request (f:allowQueryTimeRules false under an override control that does not allow the caller), a query that supplies rules used to have them stripped with a tracing::debug!, so a query reading a derived predicate came back empty, which reads as "the rules derived nothing". It is now a 400 saying why, and pointing at stored rules (f:rule), which run under policy. The security posture is unchanged: query-time rules still never run under a restrictive policy.

Reasoning a query asks for that the config won't run is refused. apply_reasoning_to_executable records what the query itself asked for before any defaults apply; when the ledger's config decides the request's reasoning, asking for something it won't run is a 400 naming the mode: a mode outside the config's forced set, "none" against a forced set, datalog where f:datalogEnabled false applies (asked for by name or implied by rules), and query-time rules or an inline ontology under forced modes (the mode replacement used to drop them; carrying them through would widen what a denied request can do). A query that asks for nothing, or for a subset of what the config runs, runs as before, and datalog a config default turned on is still switched off quietly. An embedder's own with_reasoning_precedence(Force) keeps its documented behavior; only config-derived forcing refuses. Covered on the single view, the connection from path, multi-ledger datasets, streaming plans and explain_derived, in JSON-LD (top level and opts.reasoning) and SPARQL (pragma). History queries already refuse any reasoning mode.

A query can name the rules it reasons with, pinned (rulesFrom, item 3). "rulesFrom": "<ledger>[:branch][@t:N|@commit:<id>|@time:…|@recorded:…][#<graph IRI>]" at top level or in opts, or # PRAGMA rules-from: <same address> in SPARQL. The address goes through LedgerRef::parse once, into ir::RulesFrom. No pin reads the rules ledger's head; no #graph reads its default graph; #txn-meta/#config (or those graphs by IRI) are a 400. It turns datalog on, as rules does.

  • It replaces, it doesn't add. The stored rules in that graph at that state stand in for the ledger's own f:rules and its configured f:rulesSource (local or cross-ledger, which isn't even read) for this query. Query-time rules, if also given, add on top. They arrive as imported_rules with ImportOrigin::RulesFrom, so they parse as stored rules, named by IRI, and an invalid one fails naming its ledger.
  • Resolution reuses the cross-ledger resolver (resolve_at, shared with resolve_graph_ref). A pin goes through resolve_time_spec; a t past the head is a 400. The commit at that t comes from resolve_t_to_commit_id and goes in the tally's rules_source; if it's ambiguous, it's left out and the read stays out of the governance cache.
  • It is applied while the query's reasoning settles, by changing what the settled config carries (rules_source_g_id cleared, the imported rules set), not as a side channel. On main, the reasoning cache key already hashes rules_source_g_id and the rule set's contents, so a rulesFrom query and a configured-rules query never share an entry.
  • Root-only, refused (400, naming rulesFrom) wherever query-time rules are: under a non-root view policy, where the config denies query-time rules for the request, under config-forced modes, where config turns datalog off, on history queries, and as a SPARQL update pragma. A ledger or graph it names that isn't there is a 404 (LedgerNotFound / GraphNotFound), the same as a query's own from; a configured f:rulesSource keeps its 502.

Two sibling fixes on the same path: explain_derived now passes the request's verified identity to override control (it always ran as anonymous), and the mode replacement carries the query's reasoningTime (it was dropped, so NOW() read the commit time).

Along the way, compute_derived_facts and explain_derived_facts take the query's ReasoningConfig rather than its modes and rules graph separately, so every source of rules travels as one value.

Breaking changes

  • A query that supplies rules under a non-root view policy, or where the ledger's config denies query-time rules for the request, fails with a 400 instead of answering without them.
  • Under a config that denies reasoning overrides, a query that asks for a mode the config won't run (including "none" against forced modes, and datalog where f:datalogEnabled false applies) fails with a 400 instead of answering without it. The override-control truth table in the docs, and the tests that pinned the old silent behavior, change with it.
  • New query option rulesFrom / pragma rules-from; added to REASONING_KEYS (now pub), so the write-side refusal of reasoning keys covers it once that lands.
  • docs/ledger-config/setting-groups.md said f:datalogEnabled defaults to false; the code has always defaulted it to true (now pinned by datalog_enabled_defaults_to_true), and the docs say so.
  • An f:sparql rule in a rules ledger now runs, where it was skipped, so queries reasoning with it derive more. An f:rule value there that is neither @json nor f:sparql now fails the request.
  • Rust API: RulesArtifactWire::rules is Vec<ImportedRule> and parsed_rules is imported_rules; compute_derived_facts, explain_derived_facts take &ReasoningConfig; load_rule_set takes the imported rules; ReasoningTally and ReasoningDiagnostics gain fields (ReasoningDataTally for data); GraphDb records its head commit; PreparedExecution is exported from fluree_db_query::execute; ImportedRules gains an ImportOrigin; TrackingTally::reasoning is Option<Box<ReasoningTally>>. Additive for JSON consumers.
  • Why the box: the tally grew by about 100 bytes, and a TrackingTally rides inline in the consensus AppliedReceipt::Transact variant, which then crossed clippy's large_enum_variant threshold (528 vs 256 bytes). A transaction never carries a reasoning block, so boxing it (8 bytes) leaves that record smaller than it was on main; serde writes a Box<T> exactly as T, so neither the JSON nor the receipt's wire form changes, and the Raft log uses its own mirror (RecordedTally) regardless.

Tests

  • it_rules_cross_ledger (grp_reasoning):

    • cross_ledger_sparql_rules_run_and_the_response_says_what_ran, the issue's repro: ex:r1 (@json) and ex:r2 (f:sparql) in the rules ledger. Both derive; the tally names the rules ledger, its t and commit, a SHA-256 rule set, and ex:r1/ex:r2 with SHA-256 text digests; rules_fired names ex:r2 by IRI. A cached repeat reports the same; adding ex:r3 changes the rule set and the t, adds alice as a candidate (the read is still at head: pinning is item 3), and leaves ex:r1's and ex:r2's digests unchanged.
    • a_cross_ledger_rule_of_another_datatype_fails_the_query, an_invalid_cross_ledger_rule_is_named_with_its_ledger, cross_ledger_rules_are_checked_as_stored_rules (a filter operand in a namespace the data ledger has never seen runs, where a query-time rule would be refused).
    • imported_rules_fail_closed_on_malformed_json (was parsed_rules_…).
  • it_datalog_rules::datalog_query_time_rules_refused_under_non_root_policy (was …stripped…): a 400 naming the reason under an allow-all non-root policy; the same rule stored in the ledger runs under the same policy. it_config_graph's override-control test: an identity outside the allow-list, and an anonymous request, get the config refusal (they had the rule dropped).

  • it_rules_source::the_tally_names_the_rule_set_and_a_rules_source_graph: a local f:rulesSource graph is reported with the query's t; the same rule in the queried graph reports no source and the same rule_set.

  • fluree-db-server extract::tracking: the header carries rule_set and rules_source, not rules_fired.

  • Python test_profile_reports_which_rules_ran.

  • The consensus round-trip test opts the new fields out explicitly, as it is built to force.

  • The config refusals: API tests per mode case on each surface listed above, in JSON-LD and SPARQL, and an HTTP 400 in fluree-db-server/tests/override_control_identity.rs; a_requested_time_holds_under_a_configured_default_mode; a_callers_force_wrapper_still_ignores_the_querys_modes; reasoning_override_identity_restricted_explain.

  • the_tally_names_the_data_commit_the_rules_ran_over: the head, @t:, @commit:, a dataset at the head and a dataset at @t:; Python test_profile_names_the_data_the_rules_ran_over.

  • it_rules_from (grp_reasoning, 11 tests): pinned by @commit: and by @t: (a rule added after the pin doesn't run; the tally names the pinned t and commit), the head, replacement of the ledger's own rules and of a local and a cross-ledger source, back-to-back with and without rulesFrom cold and warm, query-time rules alongside, the SPARQL twin, an invalid rule named with its ledger, missing ledger/graph matching from's 404s, a future pin, system graphs, a bad address, every refusal above, and explain_derived. datalog_enabled_defaults_to_true (grp_graphsource).

Non-vacuity, each committed-then-restored: reading only @json in the materializer (the old behavior) fails the SPARQL, datatype and stored-check tests; parsing imported SPARQL rules as query-time fails cross_ledger_rules_are_checked_as_stored_rules; dropping rules_source from the tally fails the repro test.

Suites run locally at the head (after merging origin/main), all green: fluree-db-api grp_reasoning 283, grp_query_reason 106, grp_graphsource 283, grp_policy 148, grp_query 614 (1 ignored), it_reasoning_lane_cache 2; fluree-db-query lib 1866 (2 ignored); fluree-db-reasoner 86; fluree-db-core lib 894; fluree-db-consensus lib with all features 345; fluree-db-server lib 239, grp_query 195, grp_http 126; Python (built with maturin) test_features.py + test_query_controls.py 35. cargo clippy --all-features --all-targets --no-deps -D warnings is clean on every crate that names the tally (core, reasoner, query, api, server, consensus, python, sparql, transact, cli), and cargo fmt --all --check is clean. The workspace-wide gate is CI's. Non-vacuity for the later commits: restoring the silent strip fails both refusal tests; emptying the per-rule list fails the repro test. For the config refusals and the data commit: turning off the forced-mode / none refusal fails 7 API and 4 server tests; the rules-and-ontology and datalog-gate refusals each fail their test; dropping the carried reasoningTime, ignoring the config marker and reverting explain_derived's identity each fail theirs; turning off the data-commit hook fails the head, dataset and @t: cases in turn (the head case passes with the lookup off, which is the point of the head shortcut); a Python build with the hook off fails its test. For rulesFrom: no replacement in load_rule_set fails 5 tests; not marking the origin fails 5; ignoring the pin fails 3; leaving the rule set out of the cache key fails the cache and pin tests (the rulesFrom query got the configured answer); removing each gate fails its test; the old 502s for a missing ledger, a missing graph and a system graph by IRI each fail the status test.

rulesFrom suites at the head: grp_reasoning 296, grp_query_reason 106, grp_graphsource 291, grp_policy 148, grp_query_history 70, grp_query_sparql 581, grp_query 614, grp_misc 351, api lib 860; query lib 1869; sparql 696 + 6; server lib 239, grp_query 195, grp_http 126, grp_policy 95; clippy --all-features clean on query, sparql, api, server; mdbook build passes.

Earlier suites: fluree-db-api grp_reasoning 285, grp_query_reason 106, grp_graphsource 290, grp_policy 148, grp_query 614, grp_query_history 70, grp_query_sparql 581, grp_misc 351, lib 860; fluree-db-server grp_policy 95 plus the above; Python 36; clippy --all-features --all-targets --no-deps -D warnings clean on core, query, api, consensus, server and python; fmt clean.

Merging into next

On next, a query is matched to a materialized reasoning index by a digest over its settled reasoning (reasoning_index/program.rs, settled_value), which covers modes.rules and rules_source_g_id but not imported_rules. This PR carries both a configured cross-ledger source's rules and rulesFrom's in imported_rules. So when main merges into next, settled_value has to digest imported_rules (with its origin), and serving from an index has to account for it; otherwise a query reasoning with imported rules could be answered from an index built on different ones. it_rules_from's back-to-back test (different rules, cache warm, different answers and rule_set) is the check that catches it there.

Not in this PR

🤖 Generated with Claude Code

https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9

aaj3f and others added 3 commits November 19, 2026 13:05
…and the tally says what ran

A ledger's own `f:rule` values and the ones a cross-ledger `f:rulesSource`
reads were read by two pieces of code that had drifted: the local extractor
learned `f:sparql` and refuses any other datatype by name, while the
cross-ledger materializer kept only `@json` values and skipped the rest
without a word. A SPARQL rule ran when stored in the data ledger and vanished
when stored in a rules ledger. Cross-ledger rules also travelled as anonymous
query-time JSON (`_:query_rule_N` in errors), checked as query-time rules,
whose stricter checks can flip an admin-authored rule from valid to invalid
as the data ledger changes.

One reading of an `f:rule` value now serves both: `stored_rule_source` reads
it by datatype (`@json` or `f:sparql`; anything else is refused naming the
rule) and `parse_stored_rule` parses it. The wire carries each rule's IRI,
language and source, and cross-ledger rules arrive as
`ReasoningConfig::imported_rules`, parsed as stored rules under their own
names. `compute_derived_facts` and `explain_derived_facts` take the query's
`ReasoningConfig`, so every source of rules travels as one value.

Nothing in a response said which rules ran, so a caller recording "rules as
of R over data as of D" had to trust its own bookkeeping. The tracked
reasoning block gains `rule_set` (the content hash the reasoning cache keys
on and an explanation reports; in the cached diagnostics), `rules_source`
(another ledger's graph and the `t` it resolved to, or this ledger's own
`f:rulesSource` graph at the query's `t`; per request, since two sources can
share content) and `rules_fired`, which the docs described but no response
carried. They reach the server's tracked response, the `x-fdb-reasoning`
header (without `rules_fired`, which grows with the program) and Python's
`QueryProfile.reasoning`. The Raft-recorded tally mirror does not carry them,
for the reason it gives for the other datalog fields.

Partially addresses #2460 (items 1 and 2); pinning the rules read and the
policy-stripped query-time rules await a decision on the issue.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
The reasoning block grew by about 100 bytes (`rules_fired`, `rule_set`,
`rules_source`), and a `TrackingTally` rides inline in the consensus
`AppliedReceipt::Transact` variant, which then crossed clippy's
`large_enum_variant` threshold (528 bytes against 256). A transaction never
carries a reasoning block: writes evaluate no reasoning. Boxing it leaves
that record 8 bytes for the field instead of 232, smaller than before the
block grew. Serde writes a `Box<T>` exactly as `T`, so the JSON a tracked
response carries is unchanged, and the Raft log records its own mirror
(`RecordedTally`) either way. `TrackedQueryResponse::reasoning` stays
unboxed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
@aaj3f aaj3f added bug Something isn't working as expected breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section area:datalog Reasoner, rules, reasoningDefaults labels Nov 19, 2026
@aaj3f
aaj3f requested a review from bplatz November 19, 2026 18:21
aaj3f and others added 3 commits November 19, 2026 16:58
… dropped

Query-time `rules` are admin-only: under a non-root view policy a caller-
written rule could derive a visible fact from data the policy hides, and a
ledger's config can deny them for a request (`f:allowQueryTimeRules false`
under an override control that does not allow the caller). In both cases
they were dropped with a `tracing::debug!`, so a query reading a derived
predicate came back empty, which reads exactly as "the rules derived
nothing". Both are now a 400 saying why, pointing at rules stored in the
ledger (`f:rule`), which run under policy. Nothing more runs than before:
the rules still never run where they may not.

The two tests that pinned the silent strip now expect the refusal; the
policy one also shows the same rule stored in the ledger running under the
same policy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
… commit

A caller recording a rule run needs to show which rules ran and that one
rule's text is unchanged from one run to the next, and needs a name for the
rules' state that survives the rules ledger being rebuilt under the same
name, which reuses its `t` values.

- The tracked `reasoning` block lists `rules`: each rule's name with the
  SHA-256 of its text, sorted by name.
- `rule_set` is a SHA-256 over those, not the reasoning cache key's
  `DefaultHasher` value, whose output the standard library does not promise
  to keep across releases; a run record has to compare across them. An
  explanation's `rule_set` is the same value. The cache keeps its own hash.
- `rules_source.commit_id` is the rules ledger's commit at the `t` it was
  read at, which the cross-ledger resolver already had.
- The `x-fdb-reasoning` header leaves out the per-rule lists, which grow with
  the program; they stay in the body.

For the data side, the docs recommend pinning a ledger that may be rebuilt
by commit (`@commit:<cid>`) rather than by `t`; looking the data's commit up
would cost a txn-meta scan per reasoning query. The compatibility entry also
records the previous commit's refusal of query-time rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
Derived facts are never committed, so a runner that has to keep what a
rule run concluded writes the conclusions and a record itself. Document the
pattern the tracked reasoning block now supports: pin the data by commit
(a ledger rebuilt under the same name reuses its `t` values), run the rules
tracked, write the conclusions to a ledger or graph the rules don't read,
and write the record last, keyed by the rule set and the data's commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9

@bplatz bplatz 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.

Approving. Please review the inline comments before merging.

Optional: the PR body disagrees with the code in three places: the first tally bullet calls rule_set the 16-hex cache key (it is a SHA-256, separate from that key); the header leaves out rules as well as rules_fired; and "Remaining" lists item 4 as awaiting a decision, though this PR implements it. Worth correcting before merge, since #2460 stays open on this body.

graph: db
.snapshot
.graph_registry
.iri_for_graph_id(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.

When f:rulesSource selects the default graph (or has no selector, which resolves to Some(0)) and the query reads a named graph, iri_for_graph_id(0) is always None, so the tally leaves rules_source out, which reads as "the rules are in the graph the query reads". Name the default graph explicitly here (the f:defaultGraph IRI, say) rather than returning None.

@@ -1778,8 +1778,8 @@ impl Fluree {
if !db.datalog_enabled() {
executable.reasoning.modes.datalog = false;

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.

Two paths still drop query-time rules without a word. Here, with f:datalogEnabled false under an override control that denies the caller, datalog is switched off while the rules pass the check below, so a query reading a derived predicate comes back empty. And under Force precedence, executable.reasoning.modes = effective.clone() (line 1760) replaces the caller's rules with the config's modes. Both should refuse as the new checks do.

for rule in &self.rules {
// Named by its IRI as written in the rules ledger, which this
// ledger's namespace table need not hold.
let rule_id = Sid::new(0, rule.id.as_str());

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.

Sid::new(0, iri) never equals the namespace-encoded Sid of a rule D stores on the same IRI, so add_rule's duplicate check doesn't fire: both rules run, rules lists the IRI twice with different hashes, and rules_fired (keyed by name) sums them into one count. Encoding the IRI through D's snapshot, falling back to Sid::new(0, …) only when D has no namespace for it, keeps one name to one rule.

fields.remove("rules_fired");
fields.remove("rules");
}
if let Ok(value) = HeaderValue::from_str(&json.to_string()) {

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: rules_source puts a ledger name and graph IRI in this header, and HeaderValue::from_str rejects non-ASCII, so a rules ledger or graph with a non-ASCII name drops the whole header, capped included, without a word. Escaping non-ASCII as \uXXXX when serializing the header JSON keeps it.

// (incomplete) closure is visible to clients, not just in logs, and so is
// what ran: the rule set by content, and where its stored rules came from.
if let (Some(diag), Some(tracker)) = (&prepared.reasoning_diagnostics, config.tracker) {
tracker.record_reasoning(fluree_db_core::ReasoningTally {

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: an untracked query passes a disabled tracker, so this builds rules_fired and clones every rule's id and hash on every datalog query, cache hits included, only for record_reasoning to discard it. Checking tracker.is_enabled() first skips the O(rules) allocations for untracked queries.

// Non-Json values are silently skipped, mirroring the
// same-ledger extractor's `if let FlakeValue::Json(...)`
// guard.
let id = m_db

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 and the datatype lookup below repeat datalog_rules::rule_iri (decode_sid(..).unwrap_or_else(|| sid.to_string())), which the local extractor uses for the same names. Making rule_iri public and calling it here keeps the two readers' rule names from drifting.

/// `executable.reasoning.rules`. Short-circuits when:
/// and attach M's rules, with the ledger, graph and `t` they were
/// read at, as `executable.reasoning.imported_rules`. They are not
/// query-time rules: the policy gate that strips caller-supplied

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 gate refuses now rather than strips; the same wording is at lines 1632 and 1726, dataset_query.rs:608, and in the strip_query_rules parameter name.

aaj3f and others added 8 commits November 20, 2026 10:10
…is refused

Where a ledger's config decides a request's reasoning (its
f:reasoningDefaults under an f:overrideControl that does not allow the
request, or f:datalogEnabled false likewise), a query that asked for other
reasoning was answered with the config's instead, without a word: a mode it
named ("reasoning": "datalog", opts.reasoning, a SPARQL reasoning pragma)
came back as if it had derived nothing, and "none" came back with derived
facts. It is now a 400 naming what the query asked for, as query-time rules
the config denies already are:

- a mode the config's forced modes leave out (each one named), and "none"
  where they turn reasoning on;
- query-time rules or an inline ontology under forced modes, which would
  have been replaced along with the query's modes;
- datalog, by name or by supplying rules, where the datalog group turns it
  off.

What the config's own defaults supply is not the query's doing: a query
that asks for nothing, or only for modes the config runs anyway, runs as
before, and datalog a reasoning default turned on is still switched off
quietly. A caller's own Force wrapper (with_reasoning_precedence) keeps its
documented behavior of ignoring the query's modes; the view now records
whether its reasoning came from the config.

All surfaces prepare through apply_reasoning_to_executable: single view,
connection and dataset queries, streaming plans and datalog explanations,
JSON-LD and SPARQL alike. A history query already refuses any mode.
explain_derived now passes the request's verified identity to override
control, as a query does, instead of treating every explanation as
anonymous.

Along the way, the mode replacement carries the query's reasoningTime as it
already carried its budget: a query that named no mode but a time ran the
config's default mode with NOW() at the commit time.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
The override-control truth table, the reasoning and datalog setting groups,
the reasoning and datalog query pages and the compatibility notes say what a
query that asks for reasoning its ledger's config won't run gets now: a 400
naming what it asked for, where it used to get the config's reasoning without
a word. The table's denied rows read 400; rows for a query that asks for
nothing or for the configured mode show those still run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
The tracked reasoning block named the rule set and, for another ledger's
rules, that ledger's commit, but for the data only the query's own pin, so
a caller recording "rules R over data D" had to bring D's commit itself.
ReasoningTally gains `data`: the queried ledger (a dataset's primary one),
the `t` it was read at, and the commit that produced that `t`.

- At the ledger's head the loaded state already knows its commit: a view
  built from a ledger state carries it (`GraphDb::head_commit`), used while
  the view's `t` is still the head's.
- Off the head, the existing single POST-index lookup,
  `ledger_view::resolve_t_to_commit_id`, resolves it, now generic over the
  view's overlay rather than duplicated. An ambiguous `t` (a rebased history
  can hold two commits at one `t`) or a failed lookup leaves `commit_id`
  out rather than guessing.
- The lookup runs only on the tracked execution lanes
  (`execute_view_tracked_with_r2rml`, `execute_dataset_tracked_with_r2rml`),
  between preparing and executing, and only when a materialization ran
  (`name_reasoned_data_commit`). Untracked, fuel-limit-only and streaming
  queries never reach it; their tally is not reported.

The block reaches the server's tracked body and the `x-fdb-reasoning`
header (three short values, unlike the per-rule lists the header leaves
out), and Python's `QueryProfile.reasoning`. The Raft-recorded mirror keeps
its positional wire form and does not carry it, like the other new
tally fields. `PreparedExecution` is exported from
`fluree_db_query::execute` so a host can set `data_commit_id`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
…lesFrom)

A rule run someone audits later is "these rules, as of the rules
ledger's t = R, over this data as of t = D". The data side pins with the
query's own `from`; the rules side could not: a cross-ledger
f:rulesSource reads its ledger's head, and only a runner that copied
the rule text into query-time `rules` could pin it.

A query now names its rules source itself: JSON-LD "rulesFrom" (top
level or in opts, like the other reasoning keys) and SPARQL
`# PRAGMA rules-from:`, both a ledger address,
`<ledger>[:branch][@t:N | @commit:<id> | @time: | @recorded:][#<graph IRI>]`,
parsed once by the address grammar (LedgerRef). No pin reads the rules
ledger's head; no graph, its default graph; #txn-meta and #config are
refused.

- Semantics: the rules stored in that graph, at that state, replace
  every stored rule the queried ledger's config would run: its own
  f:rule values, a local f:rulesSource graph, and a cross-ledger
  f:rulesSource, which is not read. Query-time `rules` still run beside
  them. Like `rules`, a rulesFrom turns datalog on.
- Settled, not a side channel: apply_reasoning_to_executable puts the
  rules in ReasoningConfig::imported_rules marked
  ImportOrigin::RulesFrom and clears rules_source_g_id; load_rule_set
  then reads no stored rules of the queried ledger. Everything keyed on
  settled reasoning sees it there: on this branch the reasoning cache
  (its key hashes the loaded rule set by id and text), and a digest of
  settled reasoning elsewhere has to cover imported_rules, origin
  included.
- Resolution reuses the cross-ledger resolver and materializer: the
  ledger is canonicalized through the nameservice, a missing ledger or
  graph fails as a configured source's does (CrossLedger, 502), and the
  rules are parsed as stored rules named by their IRI, an invalid one
  failing the query naming it and its ledger (400). An unpinned read
  shares the request's head capture for that ledger; a pinned one
  resolves the pin against the ledger (resolve_time_spec), refuses a t
  past the head as reading there is refused (400), names the commit at
  that t (left out where a rebased history holds two), and is cached
  under that commit (kept out of the governance cache without one).
- Gates: a rulesFrom is refused exactly where query-time rules are,
  naming it: under a non-root view policy, where the config denies
  query-time rules to the request (f:allowQueryTimeRules false), and
  under config-forced reasoning modes; datalog the config turns off is
  refused saying rulesFrom turned it on. A history query refuses it as
  it refuses any reasoning. A SPARQL update refuses the pragma.
  `rulesFrom` joins the query parser's REASONING_KEYS, which an
  explanation of derived facts now reads too rather than keeping its
  own list.
- The tally's rules_source names the rulesFrom ledger, graph, the t it
  resolved to and that t's commit; rule_set and rules are the rulesFrom
  rules.

Tests (grp_reasoning it_rules_from): pinned by @commit: and by @t: (a
rule added after the pin does not run; the tally names the pinned t and
commit) and at the head; the queried ledger's own rule and its
cross-ledger and local f:rulesSource do not run; the same ledger with
and without rulesFrom, back to back and with the cache warm, keeps two
answers and two rule sets; query-time rules beside it, from opts; the
SPARQL pragma twin; an invalid rule named with its ledger; a missing
ledger and graph (502), a pin past the head, a system graph and a bad
address (400); refusals under policy, config denial, forced modes,
datalog off, a history query and a SPARQL update; an explanation reads
it. Unit tests for the address parsing on both surfaces.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
The setting-groups table said `false`. merge_datalog_opts reads a
missing f:datalogEnabled as `true`, and a view with no config has
datalog enabled too, so a ledger that leaves the field out runs its
stored rules when a query asks for datalog, even where no request may
override the group.

datalog_enabled_defaults_to_true (grp_graphsource) pins it: a ledger
with no config, then with an f:datalogDefaults group that sets only
f:overrideControl f:OverrideNone, answers a datalog query from its
stored rule. Reading the missing field as `false` makes the second
query a 400.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
- datalog-rules.md: a third way to provide rules, `rulesFrom` (and
  `# PRAGMA rules-from:`): the address grammar, that the named rules
  replace the configured ones while query-time rules run beside them,
  pinning (prefer @commit:), the default graph and refused system
  graphs, the admin-only gates, and the errors. "Recording a rule run"
  now pins the rules as well as the data, and notes the tally names the
  pinned commit.
- reasoning.md: rulesFrom among the reasoning keys accepted in opts,
  among what config-set reasoning refuses, in the SPARQL pragma list,
  in rules_source, in the run record, the cache-key note, and the
  admin-only note under policy.
- cross-ledger-policy.md: a "Naming the rules per query" section (same
  resolver, replaces D's rules, pins, gates, failures) and a pointer
  from the f:atT limitation. The design doc's resolution-time table
  gains the pinned rulesFrom row, and drops a stale "pending" entry for
  cross-ledger f:rulesSource, which is implemented.
- compatibility.md, sparql.md, policy-in-queries.md, setting-groups.md
  and override-control.md: the new key and pragma, and the places it is
  refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
every_pragma_reaches_its_translators walks fluree_db_sparql::pragma_names()
and fails on a pragma it does not list, so a new one is wired into each
translator its JSON-LD twin reaches. `rules-from`, like the reasoning
pragmas, is applied where the query is lowered: no header, no policy
selection, no tracking, no multi-query opts key. Also a clippy fix in
the rulesFrom options test (a redundant closure).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
…a 404

A rulesFrom names its ledger and graph in the request, so naming one
that is not there is the caller's mistake, not a configured upstream
gone missing. It was reported as the cross-ledger 502 a configured
f:rulesSource gets; it is now reported as the same mistake in a query's
own `from` / `FROM` is:

- a ledger that is not on this instance (or was dropped):
  ApiError::NotFound, 404, err:db/LedgerNotFound;
- a graph the ledger does not hold at the state read:
  ApiError::GraphNotFound, 404, err:db/GraphNotFound, as a `from`,
  `fromNamed` or `FROM NAMED` naming a missing graph of an existing
  ledger is;
- a system graph named by its IRI (urn:fluree:<ledger>#config): a 400,
  as the #config / #txn-meta keywords already were.

resolve_rules_from maps those three resolver failures
(rules_from_error); anything else (an f:rule value of another
datatype, a cycle, a failed read) is the rules ledger's and stays a
CrossLedger 502. A configured f:rulesSource is untouched and keeps its
502s.

what_rules_from_names_has_to_exist asserts the status and error type
and compares each with what the query's own `from` naming the same
missing ledger or graph returns; it adds the system graph by IRI.
Mapping the failures back to CrossLedger fails it (502 against 404 for
the ledger, then for the graph, and 502 against 400 for the system
graph by IRI, each mutation alone). Docs and the compatibility note say
404 for rulesFrom and keep the 502 for a configured source.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9
@aaj3f aaj3f changed the title fix(datalog): rules from another ledger run as they do in their own, and the tally says what ran fix(datalog): cross-ledger rules travel, a query can pin the rules it uses, and a run record says what ran Nov 20, 2026
… ledger in fromNamed

The dataset cases of the_tally_names_the_data_commit_the_rules_ran_over
ran datalog rules over `from: [data, other]`, a default graph of two
ledgers. #2463 refuses that shape (rules run over one graph), so the test
would fail whichever of the two lands second. The other ledger is now a
named graph, the shape both accept, and the query still goes through the
dataset path, so "for a dataset it names the primary ledger" is still what
it checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:datalog Reasoner, rules, reasoningDefaults breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Datalog: a cross-ledger f:rulesSource is read at its head under a pinned query, and drops f:sparql rules silently

2 participants