Repository navigation
Reasoning stops with its query and counts as its fuel; explain derived facts; compact JSON-LD graph names - #2126
Conversation
82e3d1b to
c07b301
Compare
…ts fuel OWL 2 RL and datalog materialize while a query is prepared, before its execution context exists, so a client disconnect or query timeout could not stop them and their work was not charged as the query's fuel. Preparation now takes the request's tracker and cancellation handle (PrepareConfig::for_request, carried as QueryRequest), and every API query path passes them. Each rule body runs under a handle from the new QueryCancellation::with_deadline_inside: it reports the query's cancellation and also times out at the reasoning budget's deadline without cancelling the query. A body stopped by the query's cancellation fails the run with Cancelled; one stopped by the deadline caps it, as before. Rule bodies' scans charge the query's tracker. OWL 2 RL takes the handle and tracker in ReasoningOptions, checks for cancellation at each round and every 1,024 facts within one, and charges one micro-fuel per fact a round processes; its Cancelled and FuelExceeded errors fail the query instead of letting it continue without OWL entailments. A materialization is cached and shared, so the query that computes it pays for it and queries that reuse it do not. A query with a fuel limit can now fail while materializing, and a tracked reasoning query reports more fuel when it materializes than when it reads the cached result. A cancelled or out-of-fuel run caches nothing.
["graph", "ex:g", ...] in a JSON-LD where clause compared the name as written against the ledger's graphs, so a compact IRI matched nothing while SPARQL's GRAPH ex:g matched the graph, and a rule body reading a named graph had to spell out its IRI. A compact IRI whose prefix the query's @context defines now expands, as CONSTRUCT templates already did. A name that is not an IRI (a fromNamed alias, a ledger or graph source name) is kept as written, and is not resolved against @base; so is any name the query's own fromNamed spells exactly that way, so an alias that reads like a compact IRI keeps meaning the alias.
Fluree::explain_derived reports, for a subject and predicate (optionally an object and a named graph), every rule body row that derives the facts: the rule, the row's bindings, the body's triple patterns with the row substituted as premises, each marked derived when reasoning produced it so explaining it in turn walks back to asserted facts, the negated patterns the row found empty with the graph searched, and for an aggregating subquery the solutions in the row's group. It also records the snapshot t, a hash of the rule set, the evaluation time and whether the run completed. The request carries a query's @context and reasoning keys, merged with the ledger's reasoning settings as a query's are, and an "explain" node map naming the facts. It materializes as the query would, from the reasoning cache when it can, then re-runs the bodies of the rules whose heads can produce the facts. Premises appear whatever a policy would hide, so a view under a non-root policy is refused. The result's shape is experimental.
An explanation re-ran every rule that could derive the target and reported whatever its rows concluded, so a capped run explained a conclusion it never reached. It now starts from the matching facts the run derived and keeps a replayed row only when its conclusion is one of them. A rule whose body is not repeatable (RAND, UUID, STRUUID, BNODE, transaction metadata) cannot be replayed to the rows that derived a fact; it is named in not_replayed instead, and a fact only it derived, or one OWL 2 RL entailed, is listed without derivations. Facts that differ only in language tag were merged into one, and the asserted check compared values alone. Both now compare the full term: value, datatype and language tag. A grouped subquery inside a GRAPH block had its inputs reconstructed against the rules' graph. They are now read from the enclosing graph, which the group reports.
The property path operator read edges with range_with_overlay and charged nothing, so a path query, and a rule materialized through a path (an explicit path body or a transitive closure compiled to one), cost no fuel for its traversal. Each edge read and each emitted row is now charged one row of fuel, as scans charge theirs.
An update's where clause is parsed by the query parser, so it already expands a compact graph name. Its parse context now also carries the update's fromNamed aliases, so a name spelled like one keeps meaning the alias, as in a query. Tests the update that read and wrote one graph by its compact name and committed nothing.
c07b301 to
a02cc13
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a really nice set of follow-ups, and at a design level no pushback from me on the request limits. Threading the request into prep and giving each rule body a child handle from with_deadline_inside (the query's cancellation fails the run, the reasoning deadline still just caps it) is exactly the split I'd want. Two headline notes:
(1) The graph-name commit overlaps my #2009. #2009 gives the templates and the node-level @graph in a where one resolution order (classify_written_graph_name, with the aliases carried in a graph_names field it adds to JsonLdParseCtx) and leaves the ["graph", …] form (#1993) for later. This PR resolves that form with a second resolver and a second field (JsonLdParseCtx::graph_name, dataset_names), and the two answer a bare name differently: here it's an alias kept as written, there it's an identifier that @base applies to (and a relative one is refused), and only #2009 consults the keyword table (default, config, txn-meta). A trial merge of the two heads conflicts in five files. I don't think either PR should be held for it, but whichever lands second should route ["graph", …] through the one classifier (if #2009 goes second I'm happy to do that there), and the bare-name rule is a call for the two of us rather than something merge order should decide. It's also the same "one concept, read per surface" shape #2080 tracks: rule heads' own @graph parser, and a query's fromNamed graph selectors taken as written while an update's are expanded.
(2) Refusing a restricted view is the right call for explanations while the premise-visibility question is open. It does mean that decision now also decides whether a restricted caller can ever get an explanation (premises filtered, or refused), which feels like one for you and me rather than for this PR.
Full review below:
✅ Approving to unblock you — with 2 things that need to be addressed before this merges.
The request plumbing is carefully built, @bplatz, and I could reproduce what it promises: at this head a client cancellation stops both engines mid-run, fuel now covers OWL rounds, rule bodies and path traversal, and a cancelled or out-of-fuel run caches nothing (both caches return before cache.insert, and neither shares an in-flight run, so a cancelled run can't hand a partial closure to a waiting query). I also checked the shape where that matters most: a fuel stop or a cancellation inside a recursive stratum or inside OWL 2 RL, ahead of a NOT EXISTS or a grouped count, fails the query rather than letting the negation answer from partial input. Both musts are on the new explain entry point, and both are small:
explain_derivedreplays rule bodies with no deadline and no cancellation (fluree-db-query/src/datalog_rules/explain.rs:287, andQueryRequest::default()atfluree-db-api/src/view/explain.rs:105). With your slow-rule shape over 2,000 nodes andmaxSeconds: 1, the query caps at 1.0 s and the explanation takes 14.3 s, for a fact that was never derived. Fix path: return early when nothing was materialized, run the replays under the run's own deadline, and give the API an options form so a host's cancellation and tracker reach it.explain_derivedchecksis_root()before the ledger's configured policy defaults are applied (fluree-db-api/src/view/explain.rs:51). On a ledger whose config hides the premise,fluree.db(id)reports root and the explanation returns the hidden value, whilefluree.graph(id).query()returns nothing for it.Fluree::explainalready wraps the defaults before its own root check (fluree-db-api/src/view/query.rs:796), and the samewrap_policy_defaultscall here fails closed.
The rest are inline and smaller: a dataset built outside the query body no longer protects an alias spelled like a compact IRI (["Carol"] at the base, [] here); stored f:query policies and updates pick up the new expansion, which I think is right but is an access change on upgrade that the behavior-changes list should name; UNION and property-path bodies explain with an empty premise list; and the update alias line in a02cc13b6 has no test.
Adherence to repo commitments:
- Patterns/abstractions: ✔ for the request plumbing:
QueryRequestrides onPrepareConfig, the child handle extendsQueryCancellation, and fuel uses the existingPER_ROW_MICRO_FUELschedule rather than a second meter.⚠️ for graph names:JsonLdParseCtx::graph_nameis a second resolver beside #2009's classifier (headline note 1). - Performance (speed first, memory second): ✔ Neutral. The new checks sit outside the per-row work: OWL charges fuel once per round on
delta.len()and polls cancellation every 1,024 facts on the tick counter the budget already keeps, rule bodies poll every 1,024 rows, and the path operator adds one relaxedfetch_addper edge read and per emitted batch, a no-op when fuel isn't tracked. In an interleaved A/B of base and head test binaries in one machine window (debug build), an OWL 2 RL transitive closure over a 600-node chain ran 49.4–54.5 s on both, and an all-pairspartOf+of 180,300 rows ran ~247 ms median on both, tracked and untracked. What moves is fuel, by design: that path query reports 181.9 fuel here against 1.0 at the base, the cold OWL query 181.3 against 1.6, and a closure-lane query capped at 20k facts 40.8 against 1.0, so a client whosemax-fuelwas sized to the old numbers will now seeFuel limit exceeded. - Deployment targets:
⚠️ All of this is influree-db-query/fluree-db-api, so it reaches solo's Lambdas and standalone binary as well as the server, and the plumbing helps the Lambda host: solo's deadline watchdog cancels aQueryCancellation, which now reaches materialization. Solo sets no default query fuel (only the caller'sfluree-max-fuelheader), so no default can trip, but since materialization is charged only on a cache miss and each Lambda keeps its own reasoning cache, a header-limited reasoning query can fail on a cold instance and pass on a warm one. The evidence is in-process tests; must 1 is the piece that could run into the 15-minute ceiling once a host wiresexplain_derived. - Testing: ✔ Every new test runs in CI by name on this head (nextest, 14,428 passed), and I re-ran them locally (
grp_reasoning239 passed,it_query_graph_names4 passed). Dropping the explain root check failsa_restricted_view_cannot_ask_for_an_explanation, and removing the path operator's three fuel charges fails both path-fuel tests.⚠️ Dropping the update alias line ina02cc13b6leaves everything green (inline). - Conventions: ✔ Multi-line commit bodies that carry the rationale, with the docs moved alongside each change (
rules-engine.md,reasoning.md,tracking-and-fuel.md,datalog-rules.md,jsonld-query.md); clippy and fmt green in CI.⚠️ A stale comment atfluree-db-transact/src/parse/jsonld.rs:708-710and the update docs (inline).
Verified locally at a02cc13b6 (debug): the PR's tests, three mutation checks, and base-vs-head runs against 49727f055 for the closure lane, graph names, stored policies, explanations, negation behind a fuel stop or cancellation, and performance. I also checked that an explanation at the t of a commit that retracted the stored copy of a re-derived fact still finds the derivation.
Approving now so you can merge without waiting on another pass from me — just be sure the two explain items are in before you do, and ideally the dataset-alias one with them.
| env: RuleExecutionEnv<'_>, | ||
| ) -> Result<Vec<Batch>> { | ||
| let config = ContextConfig { | ||
| cancellation: Some(env.request.cancellation.cloned().unwrap_or_default()), |
There was a problem hiding this comment.
🔴 Must address before merge: an explanation replays rule bodies with no deadline and no cancellation, so it can run far past the budget the materialization honored.
body_rows runs each replay under env.request.cancellation.cloned().unwrap_or_default(), and Fluree::explain_derived passes QueryRequest::default() (fluree-db-api/src/view/explain.rs:105), so the handle is disabled: the fixpoint's bodies get the reasoning deadline from with_deadline_inside(self.deadline), the replays get neither that nor anything a host can cancel. explain_facts also replays every rule whose head can produce the target, over its whole unseeded body, even when materialized is empty (explain.rs:191-204).
I ran it with your slow-rule shape (2,000 nodes, the pairwise FILTER that keeps nothing) and "reasoningBudget": {"maxSeconds": 1}. The query caps at 1,006 ms; explain_derived on {"@id": "ex:a1", "ex:sameKind": "?y"} with the same budget takes 14,312 ms and returns complete: false with no facts. On a host with a request ceiling (solo's Lambdas stop at 15 minutes) a heavier rule turns one explain call into a dead invocation, which is exactly the shape your first commit removes for queries.
Fix path, smallest first: return early when materialized is empty; run the replays under the run's own budget (the same with_deadline_inside(deadline) the fixpoint uses, reporting complete: false if it trips); and take execution options on the API (an explain_derived_with_options, or QueryExecutionOptions on this method) so a host's cancellation and tracker reach both the materialization and the replays. Seeding each replay with the target's subject (a VALUES on the head's subject variable, like the semi-naive seed) would also make the cost scale with the fact rather than the rule, but that one is optional.
| /// An explanation shows premises whatever a policy would hide, so a view | ||
| /// under a non-root policy is refused. | ||
| pub async fn explain_derived(&self, db: &GraphDb, request: &JsonValue) -> Result<Explanation> { | ||
| if !db.is_root() { |
There was a problem hiding this comment.
🔴 Must address before merge: the root check runs before the ledger's configured policy defaults are applied, so on a governed ledger an explanation returns premises the configured policy hides.
explain_derived checks db.is_root() on the view as handed in. A view from fluree.db(id) has its config attached but no policy wrapper, so it reports root even when the ledger's config sets f:policyDefaults. Fluree::explain (the plan explain) handles exactly this by wrapping the defaults first (prepare_explain_view → wrap_policy_defaults, fluree-db-api/src/view/query.rs:796), and an explanation discloses more than a plan does.
I checked it with a ledger whose config default policy denies ex:risk, holding ex:acct1 ex:risk "high", and a query-time rule deriving ex:Flagged from it. fluree.graph(id).query() returns nothing for the premise. fluree.db(id).is_root() is true, and explain_derived(&fluree.db(id), …) returns the derivation with the premise acct1 risk "high". On wrap_policy_defaults(db) (is_root() false) the same request is refused, as intended. To be fair, fluree.query(&fluree.db(id), …) also reads that premise today, so this isn't a new hole in fluree.db(); but the root check is the whole safety story for this API, so I think it should fail closed the way the plan explain does:
let db = &self.wrap_policy_defaults(db.clone()).await?;
if !db.is_root() {Unconfigured ledgers come back unwrapped, so none of the existing tests change.
| let path_aliases = extract_path_aliases(context_val, &context, parse_policy)?; | ||
| let ctx = JsonLdParseCtx::new(context.clone(), path_aliases, parse_policy); | ||
| let ctx = JsonLdParseCtx::new(context.clone(), path_aliases, parse_policy) | ||
| .with_dataset_names(dataset_names(obj)); |
There was a problem hiding this comment.
🟠 Should address: a dataset built outside the query body no longer protects its aliases, so a query that named one now silently matches nothing.
dataset_names(obj) reads only the query's own fromNamed / from-named. The Rust API also builds datasets out of band (DatasetSpec::with_named, build_dataset_view, DataSetDb::with_named) and runs a query that carries no fromNamed (query_dataset(&dataset, &query)), and the graph-source member a from registers under its id (fluree-db-api/src/view/dataset_builder.rs:46) isn't read either. For those, a name that spells a compact IRI whose prefix the context defines now expands, and the lookup misses the key the dataset registered.
Repro: a dataset whose alias ex:people selects urn:g2 (spec built with DatasetSpec::from_json from one JSON), queried with ["graph", "ex:people", {…}], "ex" in @context, and no fromNamed in the query. At the PR's base that returns ["Carol"]; at this head [], with no error. The same query with fromNamed in its body returns Carol at both.
The narrow fix is to let the dataset the query runs against contribute its names: I think the dataset query paths have it in hand when they parse (query_dataset_with_options_impl takes the DataSetDb), so its named keys could go into with_dataset_names beside the body's. A sturdier one is to resolve at lookup, trying the name as written before its expansion, so parse doesn't need to know the dataset at all. Either way I'd add the out-of-band case to it_query_graph_names.
| .patterns | ||
| .push(UnresolvedPattern::graph(graph_name, graph_patterns)); | ||
| query.patterns.push(UnresolvedPattern::graph( | ||
| ctx.graph_name(graph_name), |
There was a problem hiding this comment.
🟠 Should address: this expansion also reaches stored access policies and updates, and both change behavior on upgrade, so I'd say so in the behavior changes and the docs.
A JSON-LD policy f:query goes through the same parse_query (fluree-db-query/src/policy/executor.rs:430), and an update's where through the same where parser. So an f:query that names its graph compactly used to evaluate against a graph literally called ex:acl (none) and deny; it now evaluates against http://…/acl. With an f:required view policy on ex:ssn whose f:query is [["graph", "ex:acl", {"@id": "?$identity", "ex:mayRead": {"@id": "?$this"}}]] (with ex in its @context), alice reads no SSNs at the base and ex:p1's at this head; the same policy spelled with the full IRI grants at both.
That's what the author of such a policy meant, so I don't think the behavior should change. But it's an access change a ledger admin gets on upgrade without editing anything, and the behavior-changes bullet says only "a JSON-LD where clause". Minimally: a bullet that names stored f:query policies and updates (an update whose where named its graph compactly committed nothing and now writes), and a sentence beside f:query in docs/security/policy-model.md.
Commenting here because fluree-db-query/src/policy/executor.rs and docs/security/policy-model.md are not in this diff.
There was a problem hiding this comment.
Addressed in b0bf3cf; the upgrade note is in the PR description's Behavior changes.
| name: GraphName::Iri(iri), | ||
| patterns, | ||
| } => walk(patterns, Some(iri.clone()), visit), | ||
| other => visit(other, graph.clone()), |
There was a problem hiding this comment.
🟠 Should address: a derivation lists no premises for a UNION body or a property-path body, so the explanation reads as a conclusion drawn from nothing.
walk visits top-level patterns and GRAPH blocks and hands everything else to the visitor, which keeps only Triple, NotExists, negating Filters and grouped subqueries. Rule bodies may use UNION and property paths (validate.rs rejects OPTIONAL and MINUS, not those), so both drop out. With two stored rules: CONSTRUCT { ?x a ex:Flagged } WHERE { { ?x ex:a ?v } UNION { ?x ex:b ?v } } explains ex:x1 a ex:Flagged with bindings ?x and ?v = "one" and premises: [], and CONSTRUCT { ?x ex:within ?y } WHERE { ?x ex:partOf+ ?y } explains ex:n0 ex:within ex:n2 with premises: []. A NOT EXISTS inside a UNION branch would be missing from absences the same way. The user docs say premises are "the body's triple patterns with the row substituted — the facts it matched"; the design doc says top-level, which is closer to what the code does.
We may want to descend into Union, keeping the branch whose patterns the row binds and that matched, and to report a path pattern as a premise with its endpoints substituted and a marker that it's a path rather than a stored fact. Minimally, the user docs could say which patterns are reported. I recognize the shape is experimental, but someone reading an empty premise list is exactly who this is for, so if you agree I'd rather see it in this PR than lost in the backlog.
| // A `["graph", …]` name the update's `fromNamed` spells is that alias, | ||
| // even where it reads as a compact IRI; any other compact IRI expands. | ||
| let ctx = JsonLdParseCtx::new(context.clone(), PathAliasMap::new(), parse_policy) | ||
| .with_dataset_names(from_named_aliases.keys().cloned().collect()); |
There was a problem hiding this comment.
🟡 Optional: this line has no test, and the comment it makes true sits stale further down the file.
Dropping .with_dataset_names(...) here leaves all four it_query_graph_names tests green, since an_update_where_clause_names_its_graph_compactly has no fromNamed. With the line removed, an update whose fromNamed is [{"graph": "urn:g2", "alias": "ex:people"}] and whose where reads ["graph", "ex:people", …] commits nothing; at this head it copies Carol's name. A test of that shape would pin it.
Also, fluree-db-transact/src/parse/jsonld.rs:708-710 still says an alias makes ["graph", "ex:g2", ...] usable "even though GRAPH names are not expanded via @context", which is no longer true, and docs/transactions/update-where-delete-insert.md:176 still lists only an alias or a graph IRI for a where graph name. 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.
…-explanations # Conflicts: # docs/query/jsonld-query.md # fluree-db-query/src/parse/mod.rs # fluree-db-query/src/parse/policy.rs # fluree-db-query/src/parse/where_clause.rs # fluree-db-transact/src/parse/jsonld.rs
explain_derived replayed rule bodies with no deadline and no cancellation: with a 1s budget, a query over a slow rule capped at 1.0s while explaining a fact the run never derived took 14.3s. Replays now run only when the run derived a matching fact, under the reasoning budget's deadline measured from the start of the explanation, and under the request's cancellation and tracker. The deadline marks the explanation incomplete; a cancellation fails it. explain_derived_with_options takes a host's QueryExecutionOptions and tracker. The root check also ran before the ledger's configured default policy was applied, so on a ledger whose config hides a premise, a view from fluree.db() reported root and the explanation showed the premise. The view is now wrapped in the configured defaults first, as the plan explain does, and refused when that restricts it. a_replay_stops_at_the_reasoning_deadline replays a nonlinear closure whose traversal materializes in well under the budget but whose replay joins the closure with itself (about 26s without the deadline).
A ["graph", …] name that spells a compact IRI with a defined prefix is expanded unless the query's own fromNamed spells it. A dataset built outside the body (DatasetSpec, build_dataset_view, DataSetDb::with_named, or a graph source a `from` registers under its id), queried with query_dataset and no fromNamed in the body, therefore lost an alias like ex:people: the name expanded, the lookup missed the key the dataset registered, and the query returned nothing. The dataset query paths now parse with parse_query_in_dataset, which keeps any name the DataSetDb registers as written, beside the body's own fromNamed names.
an_update_alias_spelled_like_a_compact_iri_is_the_alias reads ["graph", "ex:people", …] through a fromNamed alias spelled like a compact IRI and copies the value; without the update's dataset names it commits nothing, and the suite stayed green before. The comment on fromNamed's implicit alias still said WHERE graph names are not expanded via @context, and the update docs listed only an alias or a graph IRI as a where graph name. Both now say a compact IRI expands unless a fromNamed entry spells it. The policy docs say the same of a ["graph", …] pattern in a JSON-LD f:query.
The derivation walker visited only top-level patterns and GRAPH blocks, so a rule body written as a UNION, or reading through a property path, explained its conclusion with an empty premise list, and a NOT EXISTS inside a UNION branch was missing from the absences. Each UNION now contributes the branch the row satisfies: every triple bound by the row and holding over asserted and derived facts, every path's ends bound. A property path is listed as a premise with its ends substituted, marked `path`, its predicate the path in SPARQL syntax. A body with more than 64 branch choices reports only what lies outside its unions.
Brings in main through #2137, including #2009's graph scope and explicit SHACL, the storage root lock (#2131) and reasoning limits (#2126). Ported to next's annotation links: - main's annotation lowering (annotation nodes included in their edge's subject, `GraphScope::emit` as the one `f:reifiesGraph` writer) keeps next's link fold: the slots fold into `rdf:reifies` links after the variable-graph refusal, and the fold drops the anchors - a selector-form annotation delete matches the edge through its link, scoped with main's node-level `@graph` - `@reifies` with several triples includes the extra ones in the reifier (main's `@included`) rather than as top-level siblings - triple-term objects keep their shape under main's forward/reverse edge classification, and `rdf:reifies` stays refused as a key - main's parser tests that read `f:reifies*` slots and anchors read the link and the annotation's graph instead Also: - JSON-LD expansion keeps next's triple-term `@id` and value-object `@annotation` under main's `Path`; CONSTRUCT templates keep `TripleTermValue` - the JSON-LD adapter keeps next's quads, `@reverse` and `@included`, and refuses `@graph` for a sink without named graphs with main's error - file builds migrate the nameservice after main's WAL replay, with the root lock held - the cross-ledger shape cache key keeps `model_instance` - the error table counts both sides' variants; consensus and the server map Fenced, LifecycleConflict and ConfigUnavailable - main's new tests await next's async `genesis_ledger`; a next SHACL test enables SHACL, as #2009 requires; the reasoning-limit tests suffix the ledger name, not the branch
|
|
Summary
Three follow-ups to the rules engine:
Fluree::explain_derivedreports why the rules concluded a fact: the rule, the body row, the facts it read, the negations it found empty, and an aggregate's group inputs.whereclauses.["graph", "ex:g", …]now expands against@context, as SPARQL'sGRAPH ex:gand JSON-LD CONSTRUCT templates already did. This touches JSON-LD query parsing generally, not only rules.Stacked on #2122.
Fixes #1993. Partially addresses #2080: this resolves its #1993 item; datalog rule heads still read
@graphwith their own parser rather than the shared classifier.Commits
Request limits. Preparation takes the request's tracker and cancellation handle (
PrepareConfig::for_request, carried asQueryRequestintocompute_derived_factsandRuleExecutionEnv), and every API query path passes them. Each rule body runs under a handle from the newQueryCancellation::with_deadline_inside: it reports the query's cancellation and also times out at the reasoning budget's deadline without cancelling the query. A body stopped by the query's cancellation fails the run withCancelled; one stopped by the deadline caps it, as before. Rule bodies' scans charge the query's tracker. OWL 2 RL takes the handle and tracker inReasoningOptions, checks for cancellation at each round and every 1,024 facts within one, and charges one micro-fuel per fact a round processes;ReasonerError::{Cancelled, FuelExceeded}fail the query instead of letting it continue without OWL entailments.Graph names. A compact IRI whose prefix the query's
@contextdefines now expands. A name that is not an IRI (afromNamedalias, a ledger or graph source name) is kept as written and is not resolved against@base; so is any name the query's ownfromNamedspells exactly that way, or the dataset the query runs against registers (a RustDataSetDb, or a graph source afromregisters under its id), so an alias that reads like a compact IRI keeps meaning the alias. An update'swhereclause, parsed by the same code, now expands too, keeping the update'sfromNamedaliases the same way, so an update that reads and writes one graph by its compact name no longer commits nothing.Explanations (
fluree-db-query/src/datalog_rules/explain.rs,fluree-db-api/src/view/explain.rs). The request carries a query's@contextand reasoning keys, merged with the ledger's reasoning settings as a query's are, and anexplainnode map naming the facts by subject and one predicate, optionally an object and a named graph:{"@context": {"ex": "http://example.org/"}, "reasoning": "datalog", "explain": {"@id": "ex:acct2", "@type": "ex:Candidate"}}It materializes as the query would, from the reasoning cache when it can, takes the matching facts the run derived, then re-runs the bodies of the rules whose heads can produce them and keeps the rows whose conclusion is one of those facts, compared by value, datatype and language tag. A capped run therefore never explains a conclusion it did not reach. A rule that is not repeatable (
RAND,UUID,STRUUID,BNODE, transaction metadata) is named innot_replayedrather than replayed, and a fact only it derived, or one OWL 2 RL entailed, is listed without derivations. Each derivation lists the body's triple patterns with the row substituted as premises, each markedderivedwhen reasoning produced it so explaining it in turn walks back to asserted facts (aUNIONcontributes the branch the row satisfies; a property path is a premise markedpath, its predicate the path in SPARQL syntax); the negated patterns the row found empty, with the graph searched; and for a grouped subquery, the solutions in the row's group, read from theGRAPHblock that encloses the subquery when there is one. The result also records the snapshott, a hash of the rule set, the evaluation time and whether it is complete. Replays run only when the run derived a matching fact, under the reasoning budget's deadline measured from the start of the explanation and under the request's cancellation and tracker (explain_derived_with_options): the deadline leaves the explanation incomplete, a cancellation fails it. Premises appear whatever a policy would hide, so a view under a non-root policy is refused, checked after the ledger's configured default policy is applied. The result's shape is experimental.Property path fuel. The property path operator read edges without charging anything, so path queries, and rules materialized through a path (an explicit path body or a compiled closure), cost no fuel for their traversal. Each edge read and each emitted row is now charged one row of fuel, as scans charge theirs.
Behavior changes
["graph", "prefix:local", …]in a JSON-LDwhereclause now names the expanded IRI when the context definesprefix. A query that relied on the name matching as written (for example, a graph source namedprefix:localwhile the same query's context definesprefix, and not registered in its dataset) now looks for the expanded IRI instead. The same expansion reaches a stored JSON-LDf:querypolicy and an update'swhere: a policy whosef:querynamed its graph compactly evaluated against no graph and denied, and now reads the expanded IRI and may grant; an update whosewherenamed its graph compactly committed nothing and now writes.QueryRequest,PrepareConfig::for_request,QueryCancellation::with_deadline_inside,ReasoningOptions::{cancellation, tracker},ReasonerError::{Cancelled, FuelExceeded},Fluree::{explain_derived, explain_derived_with_options}and the explanation types,parse_query_in_dataset.Tests
it_reasoning_request_limits: a query cancelled 100 ms in stops a rule body that runs for about half a minute, and an OWL 2 RL closure of 4.5 million facts, each failing with the cancellation rather than answering; a cold query reports more fuel than the same query served from the cache, for iterated datalog, for OWL 2 RL, for an explicit property-path body and for a compiled closure (the last two by at least a row per derived fact), and a fuel limit between the two stops the cold query.owl2rl_property_rules_integration_tests: the reasoner stops withCancelledfor a cancelled request andFuelExceededat its fuel limit, and caches neither result.it_datalog_run_contract: a request cancelled while a body runs ends the fixpoint with the cancellation, not a capped result.it_query_graph_names: a compact graph name matches like SPARQL's; an undefined prefix does not expand; afromNamedalias spelled like a compact IRI keeps meaning the alias; a rule body names its graph compactly; an update that reads and writes one graph by its compact name copies the value.it_datalog_explain, over the acceptance program: a candidate is explained by the count and threshold it read and the exception it did not find; a count by the transactions in its window and not the one outside it; coverage step by step down the ownership chain, with an OWL entailment marked derived; an underived fact has nothing to explain; a restricted view is refused. Also: a capped run does not explain the conclusion it did not reach; aSTRUUID()rule is named as not replayed; a count insideGRAPH ex:gis explained by that graph's items;"chat"@frand"chat"@enstay two facts, each with its own derivation and asserted status.Each test was confirmed to fail with the code it pins broken, including: rule bodies ignoring the request's cancellation, a request cancellation mapped to a capped run, no fuel charged for rule bodies or OWL rounds, no cancellation check in OWL rounds, the request never passed to preparation, graph names not expanded,
fromNamednames ignored, absences not reported, group inputs not filtered to the group, premises never marked derived, and the policy check removed. The capped-run, not-replayed, named-graph-count, language-tag and path-fuel tests each fail on this PR's code before its last two commits. Mapping an OWL 2 RL cancellation or fuel error to the query's error at preparation is not observable through a query, since execution checks the same handle and tracker right after; the reasoner-level test covers that contract instead.