Repository navigation
Conversation
…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
… 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
left a comment
There was a problem hiding this comment.
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)? |
There was a problem hiding this comment.
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; | |||
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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()) { |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
…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
… 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
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:rulevalues and the ones a cross-ledgerf:rulesSourcereads were read by two separate pieces of code, and they had drifted: the local extractor learnedf:sparql(and refuses any other datatype by name), while the cross-ledger materializer kept only@jsonvalues 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_Nin 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
reasoningblock carried the evaluation time but not the rule set or where it came from, so a caller recording "rules as oft= R over data as oft= D" had to trust its own bookkeeping; andrules_fired, whichdocs/query/reasoning.mddescribes, 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:rulevalue.stored_rule_source(fluree-db-query/src/datalog_rules/mod.rs) reads a value by its datatype (@json→ JSON-LD,f:sparql→ SPARQL, anything elseNone), andparse_stored_ruleparses it. The local extractor and the cross-ledger materializer (cross_ledger/rules_materializer.rs) both use them, so they can't drift again.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.ReasoningConfig::imported_rules, not appended to the query-timerules: 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.
ReasoningTallygains: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 aDefaultHashervalue, 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 samerule_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, thetit resolved to and that ledger'scommit_id(from the cross-ledger resolver, which already had it), or this ledger's ownf:rulesSourcegraph at the query'st. Per request, not cached: two sources can share a rule set's content.data: the ledger the rules ran over, itst, and itscommit_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 onet; thencommit_idis 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-reasoningheader (withoutrules_firedandrules, which grow with the program; they stay in the body) and Python: the binding's stats now include thereasoningblock, asQueryProfile.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 falseunder an override control that does not allow the caller), a query that suppliesrulesused to have them stripped with atracing::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_executablerecords 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 wheref:datalogEnabled falseapplies (asked for by name or implied byrules), and query-timerulesor an inlineontologyunder 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 ownwith_reasoning_precedence(Force)keeps its documented behavior; only config-derived forcing refuses. Covered on the single view, the connectionfrompath, multi-ledger datasets, streaming plans andexplain_derived, in JSON-LD (top level andopts.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 inopts, or# PRAGMA rules-from: <same address>in SPARQL. The address goes throughLedgerRef::parseonce, intoir::RulesFrom. No pin reads the rules ledger's head; no#graphreads its default graph;#txn-meta/#config(or those graphs by IRI) are a 400. It turns datalog on, asrulesdoes.f:rules and its configuredf:rulesSource(local or cross-ledger, which isn't even read) for this query. Query-timerules, if also given, add on top. They arrive asimported_ruleswithImportOrigin::RulesFrom, so they parse as stored rules, named by IRI, and an invalid one fails naming its ledger.resolve_at, shared withresolve_graph_ref). A pin goes throughresolve_time_spec; atpast the head is a 400. The commit at thattcomes fromresolve_t_to_commit_idand goes in the tally'srules_source; if it's ambiguous, it's left out and the read stays out of the governance cache.rules_source_g_idcleared, the imported rules set), not as a side channel. On main, the reasoning cache key already hashesrules_source_g_idand the rule set's contents, so arulesFromquery and a configured-rules query never share an entry.rulesFrom) wherever query-timerulesare: 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 ownfrom; a configuredf:rulesSourcekeeps its 502.Two sibling fixes on the same path:
explain_derivednow passes the request's verified identity to override control (it always ran as anonymous), and the mode replacement carries the query'sreasoningTime(it was dropped, soNOW()read the commit time).Along the way,
compute_derived_factsandexplain_derived_factstake the query'sReasoningConfigrather than its modes and rules graph separately, so every source of rules travels as one value.Breaking changes
rulesunder 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."none"against forced modes, and datalog wheref:datalogEnabled falseapplies) 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.rulesFrom/ pragmarules-from; added toREASONING_KEYS(nowpub), so the write-side refusal of reasoning keys covers it once that lands.docs/ledger-config/setting-groups.mdsaidf:datalogEnableddefaults tofalse; the code has always defaulted it totrue(now pinned bydatalog_enabled_defaults_to_true), and the docs say so.f:sparqlrule in a rules ledger now runs, where it was skipped, so queries reasoning with it derive more. Anf:rulevalue there that is neither@jsonnorf:sparqlnow fails the request.RulesArtifactWire::rulesisVec<ImportedRule>andparsed_rulesisimported_rules;compute_derived_facts,explain_derived_factstake&ReasoningConfig;load_rule_settakes the imported rules;ReasoningTallyandReasoningDiagnosticsgain fields (ReasoningDataTallyfordata);GraphDbrecords its head commit;PreparedExecutionis exported fromfluree_db_query::execute;ImportedRulesgains anImportOrigin;TrackingTally::reasoningisOption<Box<ReasoningTally>>. Additive for JSON consumers.TrackingTallyrides inline in the consensusAppliedReceipt::Transactvariant, which then crossed clippy'slarge_enum_variantthreshold (528 vs 256 bytes). A transaction never carries a reasoning block, so boxing it (8 bytes) leaves that record smaller than it was onmain; serde writes aBox<T>exactly asT, 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) andex:r2(f:sparql) in the rules ledger. Both derive; the tally names the rules ledger, itstand commit, a SHA-256 rule set, andex:r1/ex:r2with SHA-256 text digests;rules_firednamesex:r2by IRI. A cached repeat reports the same; addingex:r3changes the rule set and thet, adds alice as a candidate (the read is still at head: pinning is item 3), and leavesex:r1's andex: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(wasparsed_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 localf:rulesSourcegraph is reported with the query'st; the same rule in the queried graph reports no source and the samerule_set.fluree-db-serverextract::tracking: the header carriesrule_setandrules_source, notrules_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:; Pythontest_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 pinnedtand commit), the head, replacement of the ledger's own rules and of a local and a cross-ledger source, back-to-back with and withoutrulesFromcold and warm, query-timerulesalongside, the SPARQL twin, an invalid rule named with its ledger, missing ledger/graph matchingfrom's 404s, a future pin, system graphs, a bad address, every refusal above, andexplain_derived.datalog_enabled_defaults_to_true(grp_graphsource).Non-vacuity, each committed-then-restored: reading only
@jsonin the materializer (the old behavior) fails the SPARQL, datatype and stored-check tests; parsing imported SPARQL rules as query-time failscross_ledger_rules_are_checked_as_stored_rules; droppingrules_sourcefrom the tally fails the repro test.Suites run locally at the head (after merging
origin/main), all green:fluree-db-apigrp_reasoning283,grp_query_reason106,grp_graphsource283,grp_policy148,grp_query614 (1 ignored),it_reasoning_lane_cache2;fluree-db-querylib 1866 (2 ignored);fluree-db-reasoner86;fluree-db-corelib 894;fluree-db-consensuslib with all features 345;fluree-db-serverlib 239,grp_query195,grp_http126; Python (built with maturin)test_features.py+test_query_controls.py35.cargo clippy --all-features --all-targets --no-deps -D warningsis clean on every crate that names the tally (core,reasoner,query,api,server,consensus,python,sparql,transact,cli), andcargo fmt --all --checkis 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 /nonerefusal fails 7 API and 4 server tests; the rules-and-ontology and datalog-gate refusals each fail their test; dropping the carriedreasoningTime, ignoring the config marker and revertingexplain_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. ForrulesFrom: no replacement inload_rule_setfails 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 (therulesFromquery 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.rulesFromsuites at the head:grp_reasoning296,grp_query_reason106,grp_graphsource291,grp_policy148,grp_query_history70,grp_query_sparql581,grp_query614,grp_misc351, api lib 860; query lib 1869; sparql 696 + 6; server lib 239,grp_query195,grp_http126,grp_policy95; clippy--all-featuresclean on query, sparql, api, server;mdbook buildpasses.Earlier suites:
fluree-db-apigrp_reasoning285,grp_query_reason106,grp_graphsource290,grp_policy148,grp_query614,grp_query_history70,grp_query_sparql581,grp_misc351, lib 860;fluree-db-servergrp_policy95 plus the above; Python 36; clippy--all-features --all-targets --no-deps -D warningsclean on core, query, api, consensus, server and python; fmt clean.Merging into
nextOn
next, a query is matched to a materialized reasoning index by a digest over its settled reasoning (reasoning_index/program.rs,settled_value), which coversmodes.rulesandrules_source_g_idbut notimported_rules. This PR carries both a configured cross-ledger source's rules andrulesFrom's inimported_rules. So when main merges intonext,settled_valuehas to digestimported_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 andrule_set) is the check that catches it there.Not in this PR
rulesFromis refused once fix(transact): a write that asks for reasoning is refused, not ignored #2464 (which refuses reasoning keys on writes) merges; this PR addsrulesFromto the list it reads. The SPARQL update pragma is refused here.🤖 Generated with Claude Code
https://claude.ai/code/session_018gr44QJuUPpGdwWfXE9Bz9