Repository navigation
fix(query): NOT EXISTS after a GRAPH block reads its own group's graph - #2367
Conversation
…ng GRAPH or SERVICE body A deferred pattern that became ready right after a GRAPH or SERVICE block was nested into the block's body, where it ran against that graph or endpoint instead of its own group's. A NOT EXISTS written after a GRAPH block matched nothing there and filtered nothing; EXISTS, MINUS, correlated subqueries and filters embedding EXISTS were routed the same way. Only a FILTER, BIND or UNWIND with no embedded pattern is nested now.
…the dataset Whether something reads the dataset rather than its row alone decides whether it can move into a scope that switches the active graph or source. The planner's GRAPH/SERVICE nesting and the annotation-chain filter sink each answered it by hand, by looking for an embedded EXISTS. Pattern, Expression and Function now each carry an exhaustive reads_dataset, so a new kind is a decision made there, and both sites call it. That also covers what an embedded-pattern check misses: fulltext(), the Cypher functions that look facts up (labels, keys, properties, type, startNode, endNode) and node property access, none of which are moved into another graph's scope any more. contains_exists is now built on for_each_embedded_patterns instead of keeping its own walk.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is great, and at a design level no pushback from me. try_nest_deferred is the one place that moves a group's pattern into a container body, and an exhaustive reads_dataset with no wildcard arm is the right altitude for "may this move into another graph's scope". It also quietly fixes the orphan query we document in turtle.md, whose per-graph form had been checking references in the block's own graph instead of the default graph.
Claude found one thing in the same rule that I'd like folded in here, even though your PR didn't introduce it. The body of GRAPH ?g { … } doesn't have ?g in scope (the graph-variable-scope rule from #1442), so a FILTER(?g = ex:g) or BIND(STR(?g) AS ?name) after the block still gets nested and sees ?g unbound: empty or unbound results, in SPARQL and JSON-LD. It's a five-line guard next to yours, and it turns out to be what W3C pp35 has been skipped for (details below).
I'll also note this is now the third time we've fixed "a pattern moved into a container body that changes what it sees": #1690's VALUES barrier, the annotation-sink EXISTS gate from b8f33a31a, and now #2328. Your reads_dataset is the right class fix for the active-graph half, and with the ?g guard I don't think it needs to go further in this PR. No merge-order concerns with #2202 or #2214 either.
Full review below:
✅ Approving to unblock: please get the GRAPH ?g guard (and the pp35 register removal that comes with it) in before merging.
Really nice fix, @bplatz. The cause is exactly where the body says: GRAPH/SERVICE nesting in try_nest_deferred was unconditional, so anything deferred until after the block (NOT EXISTS, EXISTS, MINUS, correlated subqueries, triples consuming a sub-SELECT's output) ran against the named graph. Claude reproduced it at the merge base after a GRAPH ?g block, after a SERVICE block, inside an OPTIONAL, and in a Datalog rule body, and all four answer correctly at this head. The second commit is the part I like most. Pattern/Expression/Function::reads_dataset with no wildcard arm turns the next new kind into a compile error instead of a silent nest, and the annotation sink now asks the same question rather than its own contains_exists gate. The one must is the graph-variable guard inline, which is pre-existing but lives in the same rule. The rest are test gaps (the embedded-EXISTS arm survives mutation) and a docs sentence for the fulltext change.
Adherence to repo commitments:
- Patterns/abstractions: ✔ One exhaustive classification on the IR enums, called from both sites that move patterns into a scope-switching container;
contains_existsnow reusesfor_each_embedded_patternsinstead of a second walk. - Performance (speed first, memory second): ✔ Plan-time only. Plain FILTER/BIND/UNWIND still nest into
GRAPH/SERVICEbodies (test_filter_pushed_into_graph/_servicegreen) and UNION nesting is unchanged. What stops nesting was being evaluated in the wrong graph, so no correct plan is lost.contains_existsruns at construction or once per batch, not per row. No performance-degradation risk. - Deployment targets: ✔ n/a. Planner/IR only, identical on the embedded, server and wasm32 hosts (wasm32 jobs green on the head).
- Testing:
⚠️ The new integration, planner and sink tests run in CI (grp_query_sparql, by name in the head'stestjob) and go red when the guard or theFulltextarm is reverted, but theExpression::Existsarm survives mutation. There's no rule-level,GRAPH ?gor integration-levelSERVICEcase, and the graph-variable fix needs its own regression test plus thepp35register removal. - Conventions: ✔ Multi-line commit bodies, fmt/clippy green on the head.
⚠️ The fulltext behaviour change isn't in the title (release notes) or infulltext.md.
Verified at fe0d01bf5: CI is green on the exact head SHA (the test job ran all three new tests by name). Claude re-ran the PR's tests on an EC2 box, mutation-checked them (guard removed → red; Fulltext row-only → red; Exists row-only → still green), compared probes at the merge base and the head (NOT EXISTS / MINUS after GRAPH ?g and SERVICE, inside OPTIONAL, a Datalog rule body, the turtle.md orphan query, ?g filters/binds), and ran the candidate ?g guard against fluree-db-query --lib, grp_query_sparql, grp_query and the full W3C SPARQL suite.
Approving so you can merge once the ?g guard is in, but maybe worth folding the test gaps in at the same time.
| /// another graph or endpoint, and a pattern nested there would read that one | ||
| /// instead of its own group's. | ||
| fn try_nest_deferred(compound: &mut Pattern, deferred: &DeferredPattern) -> bool { | ||
| if matches!(compound, Pattern::Graph { .. } | Pattern::Service(_)) |
There was a problem hiding this comment.
Blocking, though your PR didn't introduce it: the body of GRAPH ?g { … } also hides ?g, and this guard doesn't check for that. A FILTER or BIND after the block that reads ?g is still nested into the body, where ?g is unbound, so it filters everything out or binds nothing. That's silent wrong results for a pretty standard idiom, in SPARQL and JSON-LD alike.
Mechanism: since #1442, GraphOperator follows the W3C graph-variable-scope rule: ?g is not in scope inside the body, the {?g → graph} binding is joined at merge time, and it's seeded into the body only when the body itself always binds ?g (graph.rs:125-133, seed_graph_var). GRAPH ?g produces ?g for the planner (Pattern::produced_vars), so a filter on ?g becomes ready the moment the block is placed, result.last() is the block, and try_nest_deferred pushes it in. A filter nested there doesn't make the body bind ?g, so the seed doesn't happen.
Scenario: Claude ran these on a box at this head, over a ledger with GRAPH ex:g { ex:note ex:label "in-g" } and GRAPH ex:h { ex:memo ex:label "in-h" }. The merge base gives the same answers, so this predates the PR:
| Query body | Result | Expected |
|---|---|---|
GRAPH ?g { ?n ex:label ?l } FILTER(?g = ex:g) |
[] |
ex:note |
the same filter over { SELECT ?n ?g WHERE { GRAPH ?g { … } } } (not nestable) |
ex:note |
ex:note |
GRAPH ?g { ?n ex:label ?l } BIND(STR(?g) AS ?gs) |
?gs null on both rows |
the graph IRIs |
GRAPH ?g { ?n ex:label ?l } FILTER(BOUND(?g)) |
[] |
both rows |
FILTER(?g = ex:g) written before the block |
[] |
ex:note |
JSON-LD ["graph", "?g", {…}], ["bind", "?gs", "(str ?g)"] |
?gs null |
the graph IRIs |
W3C pp35 (property-path/path-ng-02.rq: GRAPH ?g { ?s :p1* ?t } FILTER (?g = <ng-01.ttl>)) is exactly this shape. It sits in the skip register (testsuite-sparql/tests/registers/mod.rs:488) under a different diagnosis, and with the guard below it passes, so the suite reports it as a stale skip entry.
Fix: a second guard beside yours.
// `?g` is not in scope inside `GRAPH ?g { … }`: the operator joins it at
// merge time, so a pattern that reads it has to stay outside the body.
if let Pattern::Graph { name: crate::ir::GraphName::Var(g), .. } = compound {
if deferred.pattern.referenced_vars().contains(g) {
return false;
}
}With that guard every row above answers correctly. fluree-db-query --lib (1744 passed), grp_query_sparql (562 passed) and grp_query (558 passed) stay green. The full W3C SPARQL suite is 35 of 36 with the guard alone (the one failure is pp35, "unexpectedly PASSED but is in the skip register") and 36 of 36 once pp35 comes out of SPARQL11_PROPERTY_PATH. So the register entry has to go in the same commit, and the comment above it (mod.rs:481-486) with it, since its diagnosis no longer holds. A probe for the table above would make a good regression test next to not_exists_reads_the_default_graph_after_a_graph_block. SERVICE ?svc { … } has the same shape (ServicePattern::produced_vars includes the endpoint variable). Claude didn't probe that one, but the same check on ServiceEndpoint::Var costs nothing.
There was a problem hiding this comment.
Addressed in 05deb00 (SERVICE ?e covered too; pp35 out of the register).
| let graph = "GRAPH ex:g { ?n ex:label ?l }"; | ||
| let people = "?p a ex:Person . FILTER(?p != ex:alice)"; | ||
| let negation = "FILTER NOT EXISTS { ex:alice ex:knows ?p }"; | ||
| let in_an_expression = "FILTER(?p = ex:nobody || NOT EXISTS { ex:alice ex:knows ?p })"; |
There was a problem hiding this comment.
Optional (test gap): the in-expression case doesn't reach the nesting decision, so nothing in this test pins the Expression::Exists arm of reads_dataset. Claude mutated Expression::Exists { .. } to return false (row-only) and this test still passes, as does the planner test.
The reason: FILTER(?p = ex:nobody || NOT EXISTS { ex:alice ex:knows ?p }) reads only ?p, so it becomes ready right after ?p a ex:Person and is placed after that triple, never after the GRAPH block. An embedded EXISTS that reads a GRAPH-bound variable does reach it. With ex:alice ex:knows ex:note in the default graph, GRAPH ex:g { ?n ex:label ?l } FILTER(?l = "none" || NOT EXISTS { ex:alice ex:knows ?n }) returned memo, note at the merge base, returns memo at this head, and goes back to memo, note under that mutation (same for BIND(EXISTS { ex:alice ex:knows ?n } AS ?k)).
While you're here, three cases from the issue and the body would each be a few lines. (1) A Datalog rule body: GRAPH ex:stage { ?m ex:note ?n } ?x ex:parent ?y . ?y ex:parent ?z FILTER NOT EXISTS { ?x ex:blocked ?z } derived the blocked (a, c) at the merge base and doesn't at this head. (2) NOT EXISTS after a GRAPH ?g block. (3) An integration-level SERVICE case: SERVICE <fluree:ledger:beta> { ?s ex:rank ?r } FILTER NOT EXISTS { ?s ex:rank 2 } and the MINUS twin answered from the service ledger at the merge base. This is minor and non-blocking, but if you agree it's right, I'd rather see it in this PR than lost in the backlog.
| Pattern::NotExists(vec![Pattern::Triple(make_pattern(s, "knows", o))]), | ||
| Pattern::Exists(vec![Pattern::Triple(make_pattern(s, "knows", o))]), | ||
| Pattern::Minus(vec![Pattern::Triple(make_pattern(s, "knows", o))]), | ||
| Pattern::Filter(Expression::Exists { |
There was a problem hiding this comment.
Optional (test gap): same gap at the unit level. This EXISTS reads ?o (VarId(1)), which nothing in the group binds, so the filter is never ready during placement and is appended at the end whatever reads_dataset says. That's why the Expression::Exists → false mutation survives here too. Reading only body-bound variables makes it bite, e.g. make_pattern(s, "knows", VarId(2)). Minor and non-blocking, but if you agree, I'd rather see it folded in now than tracked-and-forgotten.
| /// is taken to. | ||
| pub fn reads_dataset(&self) -> bool { | ||
| match self { | ||
| Function::Fulltext |
There was a problem hiding this comment.
Optional (docs): say where fulltext() goes for a named graph. This is more of a docs note than a code one. Moving fulltext() out of a preceding GRAPH body is the right call, but docs/indexing-and-search/fulltext.md doesn't say where to write the call to score against a named graph. Its "Per-graph overrides" section describes per-graph languages and property lists, e.g. a Spanish product catalog graph. Per the PR body, GRAPH <catalog> { … } FILTER(fulltext(?n, "zapato") > 0) used to score against the catalog graph when the planner happened to place the block last, and now always scores against the group's graph. One sentence under "Combining with graph patterns" or "Per-graph overrides" saying to put the fulltext() filter inside the GRAPH block would cover it, and since the PR title feeds the release notes and doesn't mention fulltext, the docs are where a user would find out. Minor, but I'd rather see it in this PR than lost in the backlog. (Commenting here because docs/indexing-and-search/fulltext.md is not in this diff.)
| pub fn reads_dataset(&self) -> bool { | ||
| match self { | ||
| Function::Fulltext | ||
| | Function::Labels |
There was a problem hiding this comment.
Optional (nit). So minor, but is_metadata_function (eval/metadata.rs:1033) is now a second list of these same six Cypher functions, and it's a non-exhaustive matches!. A metadata function added there but classified false here would compile and nest. A one-line test that every is_metadata_function variant reads_dataset() (or having is_metadata_function reuse this list) would keep the two from drifting. Minor and non-blocking, but if you agree, I'd rather see it folded in now. (Commenting here because eval/metadata.rs is not in this diff.)
There was a problem hiding this comment.
Addressed in b679c60 (is_metadata_function now derives from reads_dataset).
The graph variable is bound when the block's rows merge, never inside the
body, so a FILTER or BIND over it that was nested into the body saw it
unbound: FILTER(?g = ex:g) after GRAPH ?g { … } matched nothing, and
BIND(STR(?g) AS ?gs) bound nothing. The same held for SERVICE ?e. The
planner now keeps a pattern that references the block's own variable
outside it. W3C pp35 passes and leaves the skip register.
…ision The embedded-EXISTS cases read a variable the GRAPH block binds, so they are placed right after it; a rule body, a GRAPH ?g block and a SERVICE block each get a case. is_metadata_function is derived from Function::reads_dataset so the two lists cannot drift, and the fulltext docs say to write fulltext() inside a GRAPH block to score a named graph.
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 #2328
The bug
Inside one group, a
FILTER NOT EXISTS { … }over the default graph stopped filtering when aGRAPH <g> { … }block was written before it. The same query with theGRAPHblock last was correct. JSON-LD (["graph", …]before["not-exists", …]) behaved the same way, and so did anything else that plans through the same path, including Datalog rule bodies.Cause
When a deferred pattern becomes ready, the planner tries to nest it into the compound pattern placed just before it, which is how a
FILTERgets pushed intoUNIONbranches or aGRAPHbody. ForGRAPHandSERVICEthat nesting was unconditional. ANOT EXISTSnested into aGRAPHbody is evaluated with that graph active, so it looked for its triples in the named graph, found none, and removed nothing.EXISTS,MINUS, correlated subqueries and filters with an embeddedEXISTStook the same route.Fix
A deferred pattern is nested into a
GRAPHorSERVICEbody only when it reads nothing but its row. A plainFILTER/BIND/UNWINDstill nests, so filter pushdown into those bodies is unchanged, as is allUNIONnesting.GRAPH ?gandSERVICE ?eThe graph (or endpoint) variable is bound when the block's rows merge, never inside its body. A
FILTERorBINDthat reads it was nested into the body all the same, where it was unbound:GRAPH ?g { … } FILTER(?g = ex:g)matched nothing andBIND(STR(?g) AS ?gs)bound nothing, in SPARQL and JSON-LD alike. A pattern that references the block's own variable now stays outside it. W3Cpp35(GRAPH ?g { ?s :p1* ?t } FILTER (?g = <ng-01.ttl>)) passes and leaves the skip register.Consolidation
"Does this read the dataset, or only its row?" was being answered by hand in more than one place, each by looking for an embedded
EXISTS: the planner nesting above, and the filter sink into annotation chains.Pattern,ExpressionandFunctionnow each have an exhaustivereads_dataset(), with no wildcard arm, and both sites call it. A new pattern, expression or function kind has to be classified there to compile.contains_existsis rebuilt onfor_each_embedded_patternsrather than keeping its own walk.Behaviour change to be aware of
An embedded-pattern check misses expressions that look facts up without embedding a pattern:
fulltext(), the Cypher functionslabels(),keys(),properties(),type(),startNode(),endNode(), and node property access on a loop-local. These are now treated as reading the dataset, so a filter or bind using one is no longer moved into a precedingGRAPH/SERVICEbody or an annotation wrapper.Concretely,
GRAPH ex:g { ?d ex:body ?b } FILTER(fulltext(?b, "q") > 0)used to score againstex:g, but only when theGRAPHblock happened to be the last pattern placed before the filter. It now always evaluates against the group's own graph. To score againstex:g, write the filter inside theGRAPHblock.Tests
it_query_negation:NOT EXISTSin three positions relative to theGRAPHblock, the in-expression form,MINUS, and the JSON-LD twin. An embeddedEXISTSthat reads aGRAPH-bound variable (placed right after the block, so it reaches the nesting decision).NOT EXISTSandMINUSafter aSERVICEblock, over a two-ledger dataset.FILTER,BINDandNOT EXISTSreading?gafterGRAPH ?g, in SPARQL and JSON-LD.it_datalog_rules: a rule body whoseNOT EXISTSfollows aGRAPHblock.NOT EXISTS,EXISTS,MINUS, filter-embeddedEXISTS, afulltext()filter, alabels()bind) stay outside a precedingGRAPHorSERVICE, each reading only body-bound variables so the nesting decision is what keeps it out; a pattern reading?gstays outsideGRAPH ?g/SERVICE ?gwhile a plain filter still nests; the existing tests that a plain filter is pushed in still hold.fulltext()filter is not sunk into the wrapper.fulltext.mdsays to writefulltext()inside aGRAPHblock to score a named graph.is_metadata_functionis derived fromFunction::reads_dataset, so the two lists cannot drift.