Repository navigation
fix(query): a cyclic datalog rule body derives facts on an indexed ledger - #2368
Conversation
…alization A datalog rule body, and any query over derived facts, runs with eager materialization and is owed decoded bindings. The cyclic join emitted encoded ids regardless, so a triangle rule derived nothing on an indexed ledger and a cyclic query never joined to a derived fact.
…ing the row An operator that ignores eager materialization used to lose derived facts without a trace. It now fails the query.
GroupByOperator hashes rows on a normalized key, which is the encoded form wherever a term has one, and emitted that key as the group's key columns. Under eager materialization that put an encoded binding in front of a caller that is owed decoded ones. A SPARQL rule whose body groups in a subquery without a streamable aggregate (no aggregate at all, GROUP_CONCAT, a DISTINCT sum) reaches this operator. On an indexed ledger its head got an encoded group key and derived nothing; with the rule head now rejecting encoded bindings the same rule failed every reasoning query on the ledger. Under eager materialization the key columns now carry the bindings of the group's first row, as the child bound them. Rows are still grouped on the normalized key, and a caller that is not eager gets the same output as before.
The cyclic rule-body tests compare rows only, and a cycle joined one pattern at a time answers the same. They would have passed with the cyclic join declining every eager caller. Each query now also asserts that the cyclic join ran. A four-edge cycle gets a rule-body test on both surfaces.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz of the two fixes for #2325 this is the one I'd land, and at a design level no pushback from me. Decoding at emit is the same move #2271 made for the join lanes, and it keeps the cyclic join for rule bodies and reasoning queries. #2376's decline gives that up, and Claude timed what it costs on a box: a 20k-node graph with 10 hubs, indexed, reasoning on. A triangle rule body ran in 760 ms here vs 9.36 s on #2376, and a top-level reasoning triangle in 740 ms here vs 9.49 s on #2376 (739 ms on main). This also has the GROUP BY fix #2376 doesn't. So my suggestion would be to close #2376 and bring its test over here with the span assertion flipped (more on that below). One heads-up if both stay open: git merge-tree says they merge cleanly, but #2376's guard sits ahead of this PR's emit setup in open_fast_path. Landing both would quietly make the decode here dead code and turn this PR's nine span assertions red.
Separately, this falls into a class we've now fixed a few times: an operator ignoring the eager-materialization contract and handing an encoded binding to a caller owed a decoded one.
the join lanes and probe helpers in #2271 (
68d4e4cd7); the cyclic join and GROUP BY here; and my own #2214 (ca5cf37a2emits the union cyclic join's rows encoded, which I'll need to carry this decode into when I rebase)
The structural fix would be making each operator declare what it emits under eager (#2271's LaneOutput, but as a required Operator method with no default), plus a debug-build check at the root of every eager plan like the one this PR adds to the rule head. Not for this PR; the point fixes are right here.
Full review below:
✅ Approve.
This is a really nice fix, @bplatz. It puts the decode where the contract says it belongs, leaves the join itself alone, and the span assertions make the tests prove the cyclic join actually ran rather than that some join produced the rows. The GROUP BY catch is the kind of thing only the loud rule-head error would have found, and that error is the right posture: docs/query/reasoning.md already says rules are never skipped silently. Claude went looking for anything else a rule body can reach that would now trip it and didn't find one. That covered GRAPH blocks (the cyclic join doesn't run inside them on any tree, so the open question in the body resolves to "nothing changes there"), count/min/sample subqueries, + paths, annotation shapes (also with FLUREE_ANNOTATION_LANE=enumerate set), and 13 literal kinds closing a cycle, on fully indexed and indexed-plus-novelty ledgers. The notes inline are small: name the rule in the new error and pin it with a unit test, bring #2376's test over, and a question about the cascade's probe admission.
One tiny history note: 8a9cc9e0's message says "a cyclic query never joined to a derived fact", which the body (and #2376's test, and Claude's probe on main) contradicts. Worth a reword if you're rewriting the branch anyway, since it lands in history with the merge commit.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Follows #2271's decode-under-eager direction and reuses the scan's own
materialized_object_binding/resolve_subject_sid. GROUP BY now matchesGroupAggregateOperator's key semantics; nothing parallel is invented. - Performance (speed first, memory second): ✔ Claude measured on a c7i.4xlarge (15 samples per cell, release): rule-body triangle on a skewed graph 760.4 ms vs
main's 743.8 ms (which derives 0 of the 7,583 facts), uniform triangle 96.1 vs 96.0, square 41.6 vs 41.5, top-level reasoning triangle 740.1 vs 738.9, non-reasoning 498.8 vs 500.8. #2376's alternative measured 8.7x to 12.8x slower on every eager row. No performance-degradation risk. - Deployment targets: ✔ Shared
fluree-db-querycode every host runs. Nothing needs a thread, filesystem, background task or process-lifetime cache; the decode memo is per query view. - Testing: ✔ Nine rule-body tests plus two GROUP BY tests, on both surfaces, wired into
grp_reasoning. Each fails without its fix (Claude's mutations: decode off → 9 fail with the new error; GROUP BY off → the SPARQL twin fails).⚠️ The rule-head error itself is unpinned (inline). - Conventions: ✔ Multi-line commit bodies, self-describing subjects, CI green on
e07ee8317(run 43397013173).⚠️ One commit message overstates the symptom (above).
Verified at branch HEAD e07ee8317 on a box: cross-applied suites, mutation checks, the probes above and the three-way timing, plus CI run 43397013173 green.
Approving so you can merge when ready, but maybe worth folding in the small notes first, and closing #2376 once its test is here.
| _ => None, | ||
| Binding::Sid { sid, .. } => Ok(Some(sid.clone())), | ||
| Binding::IriMatch { primary_sid, .. } => Ok(Some(primary_sid.clone())), | ||
| Binding::Iri(iri) => Ok(IriEncoder::encode_iri(snapshot, iri)), |
There was a problem hiding this comment.
Optional. Two small things about the new error.
It doesn't name the rule. docs/query/reasoning.md:241-245 says a rule that can't run "fails the query with an error naming the rule and the offending construct", and the validation errors do (datalog rule <iri>: …). This one reads datalog rule head: the rule body produced an encoded binding, so on a ledger with a dozen stored rules the caller can't tell which body to look at. HeadSink::derive has self.rule.name in hand at the instantiate(...)? call (execute.rs:972), so a map_err there that prefixes datalog rule {name}: would cover both it and explain.rs:257's caller.
Nothing pins it either. Claude turned the arm back into a silent Ok(None) (encoded if encoded.is_encoded() && false =>) and every suite stayed green except #2376's test, which fails on this branch regardless. A unit test that hands instantiate a one-row batch with Binding::encoded_sid(1) in the head's subject column and expects Err would keep the next refactor from quietly undoing the loud failure.
Both are minor and non-blocking, but if you agree they're right I'd rather see them folded in now than lost in the backlog.
| .unwrap(); | ||
| drop(guard); | ||
| assert!( | ||
| spans.has_span("cyclic_enumerate"), |
There was a problem hiding this comment.
Optional. Asserting cyclic_enumerate on every query here is a really good call. It's what makes these tests tell #2368's design from #2376's: Claude ran all nine against #2376's code and they fail on this assertion while their rows pass.
I'd bring #2376's a_cycle_under_reasoning_is_joined_step_by_step over too, with its !store.has_span(CYCLIC) flipped to store.has_span(CYCLIC). It covers a path the tests here don't. Its ?z in ?x ex:advisor ?y . ?y ex:teacherOf ?z . ?x ex:takesCourse ?z is object-only and an IRI, so it decodes through EncObj::to_binding(view, true)'s IRI_REF arm rather than ref_binding. It also covers a closing edge derived by a second rule, at 40 subjects, against a never-indexed copy. Claude ran it against this branch with span assertions off and its rows pass (64 passed, 0 failed across the three suites). If you agree, I'd rather see it land here than leave it behind on #2376.
| .with_namespace_codes_fallback(ctx.namespace_codes_fallback.clone()) | ||
| .with_tracker(ctx.tracker.clone()) | ||
| }); | ||
| self.emit_decoded = ctx.eager_materialization; |
There was a problem hiding this comment.
Question. This is more of a question than a suggestion. The cascade's probe admission still passes LaneOutput::Encoded (cyclic_bgp.rs:1162), so an eager caller with an overlay full-scans every edge, which made sense while emit couldn't decode. Now that every row this operator emits goes through ref_binding / to_binding(…, emit_decoded), is there a reason not to declare DecodesForEager there, as #2271 did for the join lanes?
For scale: on main the same skewed triangle takes 738.9 ms under reasoning and 500.8 ms without it (Claude's box, 15 samples each). Claude didn't measure the flip, so I don't know how much of that gap it buys back. There may also be a cold-translation reason I'm not seeing for keeping the cascade off the reasoning ops. Commenting here because cyclic_bgp.rs:1162 is not in this diff.
There was a problem hiding this comment.
Addressed in 5f47a9a. No reason I know of to keep the cascade off eager callers now that emit decodes; admitted, unmeasured (noted in the body).
| keys_as_bound: bool, | ||
| ) -> Vec<Binding> { | ||
| let mut output = Vec::with_capacity(schema_len); | ||
| let first_row = group_rows.first().filter(|_| keys_as_bound); |
There was a problem hiding this comment.
Praise / FYI. Taking the group's first row as bound under eager matches what the streaming GroupAggregateOperator already does for every caller (group_aggregate.rs:1166-1169), so the two group operators now agree. Claude went looking for a group whose rows carry different decoded forms of one normalized key, since then the reported key would depend on row order. The only pair it found was "0.0"^^xsd:double / "-0.0"^^xsd:double. The result follows the index, which stores -0.0 as 0.0 anyway, and main's plain GROUP BY shows the same split against a never-indexed copy. No change needed.
…es the cyclic join Carried over from #2376 with its span assertion flipped: the cyclic join runs under reasoning and decodes what it emits. The closing variable is an object-only IRI, which decodes through the object arm, and some closing edges are derived by a second rule; the rows are checked against a never-indexed copy.
A ledger can hold many rules; the error that stops a reasoning query says which body produced the binding its head could not use. A unit test pins that it is an error, not a dropped row.
Probe admission still declared the cascade an encoded lane, so an eager caller with an overlay full-scanned every edge. The operator decodes every row it emits for an eager caller now, so its probes merge the resolved ops like any other decoding lane.
…indexed # Conflicts: # fluree-db-api/tests/it_datalog_rules.rs
Brings #2296, #2309, #2313, #2315, #2316, #2317, #2367, #2368, #2369, #2373, #2374, #2378 and #2379. Ports onto next: - #2374 (bound-object probe reads POST): main's POST walk and per-type flush replace next's OPST walk. The lane keys (o_type, o_key), so next's triple-term handles are one more covered type (object_probe_covers takes TripleTermDict) rather than a flush per type; a term's matches are read whole, as a ref's are. The wildcard cursor still keys refs only. Pooled graphs decline through dedicated_branch(Post); o_i is 64-bit. Next's pair join keys its subject through the shared LaneKey. - #2373 (leaflet type constant under replay): replays_history and o_type_const_for beside next's may_hold_keys; the row-labelling lanes take main's const-unless-replaying form over next's always-read-column. - #2368: the cyclic join decodes for eager callers with next's list index sentinel; both reasoning tests kept (cyclic operator and pair lane). - #2317 (GRAPH streams): main's work queue and InnerStream with next's pooled-graph pruning before each enumerated graph. - #2315: list predicates are an ordered set in next's multi-ledger view; the annotation edge probe stays deleted (no bundle lane on next). - #2296 (rebase reads its new line): ported onto next's fenced resets, erasure checks and peer sync (follow_record keeps next's unchanged-head arm); a non-fast-forward rebase moves head and index in one fenced reset. - Main's new tests: async genesis_ledger, graph_source_store for mapping writes, leaf_rows for leaflets-per-leaf, storage lock off for two file instances. New pattern/function matches cover TermComponents and the triple-term functions; AnnotationTarget arms dropped.
Fixes #2325
Problem
A datalog rule whose body is a cycle (a triangle or a square) derived nothing once the ledger was indexed. Nothing errored; the derived facts were just missing. A never-indexed copy of the same ledger derived all of them.
A SPARQL rule that groups in a subquery with no aggregate, or with
GROUP_CONCAT, lost its facts the same way.Cause
Rule bodies run with eager materialization, which promises decoded
Sid/Litbindings.CyclicBgpOperatornever looked at that flag and always emittedEncodedSid/EncodedLit. Head instantiation cannot build a fact from an encoded binding and skipped the row silently.Top-level reasoning queries were not affected, which answers the open question in the issue. A cyclic BGP in the query itself joined correctly to a derived fact about the same node before this change, with the cyclic join running and with subjects both in the index and after it. Only a rule head was unable to use the encoded bindings.
GroupByOperatorhad the same defect. It groups rows on a normalized key, which is the encoded form, and emitted that key. A SPARQL rule that groups in a subquery with no aggregate, or withGROUP_CONCAT, reaches it: on an indexed ledger its head got an encoded group key and derived nothing. A count goes through the streaming aggregate operator and was not affected, and a JSON-LD rule of the same shape already derived its facts.Changes
instantiatenow returns an internal error, naming the rule, for an encoded binding instead of skipping the row. Any other operator that ignores eager materialization inside a rule body will fail the query rather than lose facts quietly.Behaviour change
The last change turns a silent loss into a hard error. A rule body that reaches an operator with the same defect now fails with
datalog rule <name>: the rule body produced an encoded binding for its headwhere it previously returned fewer derived facts. The error fails the whole reasoning query, not just the one rule.It found the GROUP BY case above, which is fixed here. A read of the other sites in
fluree-db-querythat build an encoded binding found no other one that a rule body can reach while eager. It did not settle aGRAPHblock inside a rule body.Tests
Nine tests in
it_datalog_rules.rs, each on a ledger with indexed data plus data committed after the index:OPTIONALto a fact the triangle rule derivesit_reasoning_batched_probe::a_cycle_under_reasoning_takes_the_cyclic_join(carried over from #2376, which this PR supersedes): a triangle rule body closing on an object-only IRI, some of whose closing edges a second rule derives, checked against a never-indexed copy; the cyclic join is stamped as running. A unit test pins that a rule head handed an encoded binding is an error naming the rule.Each fails without the operator change. The last one fails only because its derived fact comes from the triangle rule. Every query in these tests also asserts that the cyclic join ran, so none can pass by joining the cycle one pattern at a time.
Two tests in
it_datalog_aggregates.rs, over novelty and over an index: a rule that groups in a subquery with no aggregate and one withGROUP_CONCAT, as JSON-LD rules and as SPARQL rules. The SPARQL test fails without the GROUP BY change. The JSON-LD test passes either way and pins the two surfaces to the same answer.Not covered