Repository navigation
fix(query): unmatched OPTIONAL leaves vars unbound in SPARQL, null in Cypher - #1923
Conversation
aaj3f
left a comment
There was a problem hiding this comment.
This makes sense and looks good, @bplatz, and the design thoughts on Poisoned make sense as well. See my PR review note on #1920 to qualify/calibrate some of what you'll see in the Claude-assisted review below:
This is carefully built, and the shape of it is right: making the unmatched-OPTIONAL fill a property of the surface language rather than of the engine, deciding it at lowering, and folding it in once at the single plan root is the design I'd have wanted, and the one line at operator_tree.rs:2280 is doing a lot of quiet work. What convinced me more than the mechanism is where the unbound column ends up — not a new merge path, but the one #1724 already built for UNION- and VALUES … UNDEF-unbound columns, which is exactly how #1734 framed the remaining gap ("the Poisoned door" after #1724 closed the Unbound ones). The testing is unusually good for a change this size: eight SPARQL/JSON-LD tests across five builder lanes, an indexed-lane test that asserts it's actually indexed, a delete-the-clause property rather than a bare row count, and four Cypher tests where 242 existing ones pinned nothing at all. I re-ran the suite (3,094 tests green) and mutation-checked the Cypher opt-in — flipping stmt.rs:58,154 to Unbound fails three Cypher tests, not two, so the EXISTS one is load-bearing too.
Two things I'd like before it merges, neither of which is a disagreement about the code. First, the SPARQL half of Txn.unmatched_optional has no test: Claude mutated all five lower_sparql_update.rs sites to Poisoned and 1,635 tests across fluree-db-transact, fluree-db-sparql, grp_transact, grp_graphsource and it_optional_after_union stayed green. That's the one path where this change stops being a wrong answer and becomes a different set of flakes on disk, and it's the one you didn't pin — a single test in the shape of cypher_write_where_null_from_optional_match_stays_null would close it. Second, and this is a flag rather than a request: #1734 was triage:needs-decision and this PR makes the decision, inverting a contract #1724 deliberately protected with a test. I think the decision is plainly right — §18.2.4 leaves no room, and Poisoned was never a SPARQL concept — but it changes answers on a shipped product for SPARQL and JSON-LD in both directions, which means solo's SPA and the MCP agent's tool queries move with it too. Worth landing as a ruling we've all seen rather than as a bug fix, and worth expecting a "this query got slow" report, since Poisoned was doubling as a short-circuit and one unbound row can now fan out to the full inner cardinality — spec-mandated, but a cliff rather than a slope, and it lands before #1927 fixes the planner hoist in #1924.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Extends #1724's existing unbound merge instead of adding a parallel one;
UnmatchedOptionalonir::Querymakes every construction site declare itself;OptionalBuilder::unmatched_optionalis required rather than defaulted. One inconsistency atproperty_join.rs:487, noted inline and currently harmless. - Performance (speed first, memory second): ✔ No added per-row work — the fill is materialized once per operator (
optional.rs:2406,property_join.rs:493) or once per batch (optional.rs:1136), and both variants are fieldless so the clone is the same memcpy as before. No new allocations, locks or.collect()in an operator loop;PlanningContextstaysCopy. No performance-degradation risk from the implementation; the added cost is the spec's own fan-out. - Testing:
⚠️ Excellent on reads, both surfaces, both lanes, mutation-verified — and a real hole on SPARQL update, above. - Conventions: ✔ Self-describing title that reads correctly in release notes; thorough multi-line commit bodies; clippy/fmt/testsuite-sparql green at head; W3C register shrinks by one, which is the permitted direction. One stale doc line at
docs/contributing/sparql-compliance.md:542.
Verified locally at branch HEAD 161f8cc3b (diffed against merge-base origin/feat/sparql-update-graph-var, so this layer only): cargo nextest run -p fluree-db-api -p fluree-db-query --test it_optional_after_union --test it_query_cypher --test grp_query_sparql --lib --test correctness_tests → 3,094 passed / 0 failed, all 14 new and renamed tests observed by name; mutation M1 (Cypher opt-in → Unbound) → 3 targeted failures; mutation M2 (SPARQL update → Poisoned) → 0 failures across 1,635 tests. Both mutations reversed, worktree clean.
Approving so you can merge when ready — but I'd really like that one SPARQL-update test in before it goes, and it's worth us being explicit with each other that #1734's ruling is now made rather than letting it ride in as a fix.
Not anchorable inline:
Optional, merge-order — confirming your "Interaction with #1920" read from the other side. I checked, and seed.rs, exists.rs, semijoin.rs and filter.rs are byte-identical to origin/main at this head, so this PR really does revert #1920 wholesale. Claude also reproduced the Cypher regression you describe — #1920's EXISTS over a null returns true at 71797ad3f and false at its merge-base. My worry is only that "merge #1920 only together with this PR" isn't a state the base branches can hold: #1920's base is main and it reports mergeStateStatus: CLEAN today, with #1921 (+1134/−218) sitting between it and this one. Since #1920's lasting contribution after this lands is its two tests and nothing else, folding those into this PR and closing #1920 may be the cleaner shape. Raising it here rather than deciding it — it's your stack.
| delete_templates, | ||
| insert_templates, | ||
| values: None, | ||
| unmatched_optional: Default::default(), |
There was a problem hiding this comment.
Optional (but I'd really like it in this PR) — the SPARQL side of Txn.unmatched_optional has no test: the mode can be set to anything at these five sites and CI stays green.
The Cypher write path is pinned properly by cypher_write_where_null_from_optional_match_stays_null, which is exactly the right test. The SPARQL write path has the symmetric plumbing (ir.rs:133-137 → these five sites → stage.rs:2904) and nothing asserting it.
Claude mutated all five of these (:1081, :1135, :1238, :1302, :1546) to UnmatchedOptional::Poisoned and ran fluree-db-transact (lib + both integration targets), fluree-db-sparql, grp_transact — which wires all 24 transact/update modules including it_transact_conditional — grp_graphsource (46 tests, #1921's SPARQL-UPDATE GRAPH ?g suite included), and it_optional_after_union: 1,635 tests, zero failures. Nothing in the repo has the shape that would notice.
What makes me want this one folded in rather than noted is which path it is. Everywhere else in this PR a wrong mode produces a wrong answer on a screen; here it produces a different set of flakes on disk, because the update WHERE now fans out:
DELETE { ?s ex:tag ?f } INSERT { ?s ex:tagged ?f }
WHERE { ?s schema:name ?n . OPTIONAL { ?s ex:a ?f } OPTIONAL { ?s ex:b ?f } }A subject that misses the first OPTIONAL now contributes one solution per ex:b value instead of one null solution — so the transaction writes and retracts a different set than it did yesterday. A single test in the shape of the Cypher one would pin it, and would also catch anyone later "tidying" Default::default() into an explicit value at one of the five sites.
(Reassuring counterpart, since it's the idiom the transaction docs lead with: insert-if-not-exists via OPTIONAL { … } FILTER(!bound(?probe)) is genuinely unaffected — eval_bound (eval/types.rs:15-21) matches Unbound | Poisoned together, so BOUND() can't tell the modes apart. I checked that by reading and by the mutation leaving it_transact_conditional green both ways.)
There was a problem hiding this comment.
Added in f93589c: sparql_update_second_optional_binds_var_first_left_unbound and a JSON-LD twin in it_optional_after_union.rs. The same two-OPTIONAL WHERE drives an INSERT { ?s ex:tagged ?f }, and the test asserts the written triples. Setting lower_modify to Poisoned fails the SPARQL test, and setting the Txn::insert default to Poisoned fails the JSON-LD one. The other four Default::default() sites are the DATA forms and DELETE WHERE, which have no OPTIONAL to test.
| emitted_required, | ||
| inline_ops, | ||
| mode, | ||
| unmatched: Binding::Unbound, |
There was a problem hiding this comment.
Optional — this is more of a question than a suggestion, and it's about consistency with the rule you set yourself two files over.
OptionalBuilder::unmatched_optional is a required trait method, and the body says why: "required rather than defaulted so a new builder can't silently pick a surface." But new_with_options hardcodes unmatched: Binding::Unbound here with an opt-in with_unmatched_optional at :493, and the other construction site — where_plan.rs:3842, new_with_needed_vars — doesn't call it.
I traced that site and it's safe today: it passes no optional patterns, so every emitted_required entry is true and has_cartesian_row (:689-693) rejects the row before the fill can run. So this isn't a live bug. It's that the safety is a non-local invariant two files away, standing in exactly the spot where the PR's own principle asks for a compiler check.
Would it be cheap to take UnmatchedOptional as a parameter of new_with_options / new_with_needed_vars instead? Then it's the same rule you applied to OptionalBuilder, and a future third construction site can't get it wrong either.
Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
Commenting here because fluree-db-query/src/execute/where_plan.rs:3842 is not in this diff.
There was a problem hiding this comment.
Agreed, done in f5f47ba. The constructors now take the PlanningContext in place of a bare TemporalMode and read unmatched_optional from it. with_unmatched_optional is gone, and where_plan.rs:3842 passes *ctx.planning. Forcing the fill to Poisoned fails the property-join and indexed tests.
| /// OPTIONAL clause. Unlike Unbound, a Poisoned binding **blocks** future | ||
| /// pattern matching - any pattern that uses a Poisoned variable yields | ||
| /// no matches (not "match anything", but "match nothing"). | ||
| /// |
There was a problem hiding this comment.
docs/contributing/sparql-compliance.md:542
Optional, doc drift — the in-code doc got the update and the prose doc didn't.
Amending the Binding::Poisoned comment here is the right move, but docs/contributing/sparql-compliance.md:542 still records "ValuesOperator updated to treat Poisoned (from failed OPTIONAL) as wildcard in is_compatible and merge_rows, fixing values7 (OPTIONAL + VALUES)." It's a historical log entry so the stakes are low, but the parenthetical is now wrong for SPARQL, and that file is where someone goes to learn what the engine's OPTIONAL contract actually is.
A line in the same log noting that #1734 moved SPARQL/JSON-LD off Poisoned entirely would keep the record honest. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
Commenting here because docs/contributing/sparql-compliance.md is not in this diff.
| stats: Option<Arc<StatsView>>, | ||
| planning: &PlanningContext, | ||
| ) -> Result<BoxedOperator> { | ||
| let planning = &planning.with_unmatched_optional(query.unmatched_optional); |
There was a problem hiding this comment.
Praise — one line at one plan root is the whole design, and it's the right one.
I went looking for the failure mode this shape usually has — a subtree that rebuilds a fresh PlanningContext and silently reverts to SPARQL semantics inside a Cypher query — and there isn't one: SubqueryPattern carries Vec<Pattern> rather than a nested Query, SubqueryOperator::new takes *planning by value, and every other PlanningContext::current() in the crate is inside a #[cfg(test)] module.
Putting the field on ir::Query as a plain struct field is what makes it stick, since every construction site had to name it to compile.
| wait_for_index_application(&fluree, ledger_id, ledger.t()).await; | ||
| let view = fluree.db(ledger_id).await.expect("indexed view"); | ||
| assert!( | ||
| view.binary_store().is_some(), |
There was a problem hiding this comment.
Praise — this is the assertion I wish more indexed-lane tests had.
"the indexed lane needs a binary store on the view; without one this test is a duplicate of the novelty-lane one" is the difference between "we have an indexed test" and "we have an indexed test that is still indexed six months from now."
|
|
||
| /// Exact rows, plus the delete-the-clause property: before the fix the second | ||
| /// OPTIONAL contributed nothing and both queries returned the same six rows. | ||
| fn assert_second_optional_contributes(lane: &str, with_second: &[Value], first_only: &[Value]) { |
There was a problem hiding this comment.
Praise — pinning the delete-the-clause property, not just the row set, is what actually encodes #1734.
The old bug's signature was that removing the second OPTIONAL changed nothing, so assert_ne!(with_second, first_only, …) is the assertion that would have caught it. A plain row-count expectation wouldn't have.
| } | ||
| } | ||
|
|
||
| /// What an OPTIONAL that matched nothing writes for its optional-only variables. |
There was a problem hiding this comment.
Praise — routing the unbound column into the merge #1724 already built, rather than inventing a second path, is the right altitude.
UnmatchedOptional::Unbound lands the column in the same merge that already served UNION- and VALUES … UNDEF-unbound columns, which is exactly how #1734 framed the remaining gap — "the Poisoned door" after #1724 closed the Unbound ones. The renamed grouped_subquery_joins_optional_unbound_like_union_unbound is the assertion that says so out loud.
The module-doc rewrite at optional.rs:17-24, replacing "# Poison Binding Semantics" with the per-surface explanation, means the next person reads the current contract instead of the old one.
| // (PR-W1-OPT). filter-nested-2 (nested-group FILTER scope) and join-scope-1 | ||
| // (sub-SELECT merge of an OPTIONAL-produced correlation var) are fixed | ||
| // (PR-W1 Families A/B). | ||
| // (PR-W1 Families A/B). nested-opt-2 passes since #1734 (an unmatched |
There was a problem hiding this comment.
Praise — removing nested-opt-2 and writing down why it passes is a much better outcome than a silent green.
Recording that it "passes partly by coincidence", with #1925 filed against the real cause, is what keeps the register honest. And the register only ever shrinks here, which is the direction check_testsuite allows.
… Cypher An OPTIONAL that matched nothing wrote Binding::Poisoned for its optional-only variables on every surface. Poisoned is Cypher's null: any later pattern using the variable matches nothing. SPARQL leaves the variable unbound (§18.2.4), compatible with any later binding, so a second OPTIONAL over the same variable lost both its bindings and its fan-out. The fill value is now a per-query UnmatchedOptional mode carried on PlanningContext. SPARQL and JSON-LD default to Unbound; Cypher lowering, for reads and for update WHERE clauses, selects Poisoned. OptionalOperator, the grouped builder's batched lane, and PropertyJoinOperator all write the mode's binding. With SPARQL no longer producing Poisoned, EXISTS seeds no longer demote it to Unbound. The demotion was only reachable from Cypher, where a null inside EXISTS must still match nothing. W3C algebra/nested-opt-2 now passes and leaves the skip register.
EXISTS substitutes only the variables a row binds (SPARQL 1.1 §18.6), so a variable an unmatched OPTIONAL left unbound stays free in the EXISTS body. Pins that on the semijoin fallback, the per-row ExistsOperator and the compound-expression evaluator, plus a JSON-LD twin. Carried over from #1920. That PR's engine change, demoting Poisoned to Unbound in EXISTS seeds, is superseded here: SPARQL and JSON-LD no longer produce Poisoned, and the demotion would strip Cypher's null.
The constructors took a bare TemporalMode and defaulted the unmatched-optional fill to Unbound, with an opt-in setter only one call site used. Passing the PlanningContext makes every construction site carry the surface's mode, the same rule OptionalBuilder::unmatched_optional enforces.
The update WHERE plans separately from reads and takes its null semantics from Txn.unmatched_optional, which nothing pinned for SPARQL or JSON-LD. A wrong mode there writes a different set of flakes.
161f8cc to
eee37ef
Compare
6828da3 to
2b2df64
Compare
eee37ef to
6777136
Compare
Fixes #1734
Supersedes #1920 and carries its tests (see "Relation to #1920").
Problem
On the
seed_values_datasetfixture this returned 6 rows: nikola's two greetings, with everyone else null. The §18.2.4 answer is 9. The second OPTIONAL lost both its bindings and its fan-out (liam has three friends).An OPTIONAL that matched nothing wrote
Binding::Poisonedfor its optional-only variables on every surface. Poisoned is Cypher's null: any later pattern that uses the variable matches nothing. SPARQL instead leaves the variable unbound, which is compatible with any later binding of it.Decision
The issue was
triage:needs-decision. What an unmatched OPTIONAL writes is now chosen by the surface language:Unbound, per the spec. The variable then flows into the same merge fix(query): let OPTIONAL extend a row that left the shared variable unbound #1724 built for UNION- andVALUES … UNDEF-unbound columns.Poisoned.OPTIONAL MATCH (a)-->(o) MATCH (o)-->(c)must drop a row whoseois null, and a laterOPTIONAL MATCHonomust stay null.Implementation
UnmatchedOptional { Unbound, Poisoned }mode is carried onPlanningContext.ir::Query.unmatched_optional, folded in once at the single plan root,build_operator_tree.Txn.unmatched_optional, passed toexecute_where_streaming, since the update-WHERE path plans separately from reads.Unbound. Cypher lowering setsPoisonedfor reads (fluree-db-cypher/src/lower/stmt.rs) and for writes (lower_cypher_update.rs).OptionalOperator's no-match row, via a new requiredOptionalBuilder::unmatched_optional. It's required rather than defaulted so a new builder can't silently pick a surface.GroupedPatternOptionalBuilder's batched lane.PropertyJoinOperator, for an optional predicate with no values. Its constructors take thePlanningContextin place of a bareTemporalMode, so every construction site carries the mode, the same rule asOptionalBuilder.Relation to #1920
#1920 fixed an EXISTS bug with the same root cause by demoting
PoisonedtoUnboundin EXISTS seeds. Once SPARQL stops producingPoisoned, that demotion only fires for Cypher, where it is wrong:EXISTS { (o)-[:LOCATED_IN]->(:City) }for a nulloreturnedtrue. So this PR doesn't include #1920's engine change, andseed.rs,exists.rs,semijoin.rsandfilter.rsmatchmain. #1920's SPARQL and JSON-LD EXISTS tests move here and pass, because the variable is now unbound at the source.Performance
No change for SPARQL/JSON-LD queries whose later patterns don't reuse a variable an OPTIONAL left empty.
UnboundandPoisonedbehave the same there: projection, aggregates, group keys and filters already treated them alike.Where a later pattern does reuse it, the engine now does the work the spec requires. Rows that used to short-circuit to "no match" now evaluate the later pattern, which can fan out. Cypher plans are unchanged.
Tests
In
it_optional_after_union.rs, which is #1724's file and whose header called #1734 the uncovered case:PlanTreeOptionalBuilder).COUNT(*).Txn.unmatched_optionalon the write path, where a wrong mode writes a different set of flakes.In
it_query_cypher.rs, Cypher's null rule for a laterMATCH, a laterOPTIONAL MATCH,EXISTS, and a write (SETthrough an update WHERE). No existing Cypher test pinned any of this: all 242 passed with Cypher onUnbound.In
it_query_negation.rs, from #1920: NOT EXISTS over an OPTIONAL-unbound variable on the semijoin fallback, the per-rowExistsOperatorand the compound-expression evaluator, plus a JSON-LD twin.Every test is non-vacuous. I forced each of these back to the old behaviour in turn and confirmed a named test fails:
OptionalOperatorfill → 8 tests fail.Unbound→ both Cypher read tests fail.Unbound→ the write test fails (Bob gets both cities).lower_modify) set toPoisoned→ the SPARQL update test fails.Txn::insertdefault set toPoisoned→ the JSON-LD update test fails.Poisoned→ the fix(query): treat OPTIONAL-unbound vars as free inside EXISTS #1920 EXISTS tests fail, along with the read tests.Changed expectations:
it_query_subquery_unbound.rs::grouped_subquery_distinguishes_union_unbound_from_optional_poisonedexplicitly pinned the old contract. It's nowgrouped_subquery_joins_optional_unbound_like_union_unbound: both routes to an unbound?pmust fan out identically.test_create_unmatched_rowandtest_generate_rows_missing_optional_uses_unmatched_bindingnow cover both modes. The externalNoMatchOptionalBuildermock declaresPoisoned, since that test is about blocking.algebra/nested-opt-2now passes and leaves the skip register. It passes partly by coincidence; the register comment explains why, and it's item 2 below.Run locally after rebasing onto
main, all green:fluree-db-query,-cypher,-transact,-sparqlfluree-db-api:grp_query_sparql,grp_transact,grp_graphsource,it_query_cypher,it_sql_pushdown_lane,it_optional_after_unionfluree-db-query,-transact,-apiNot rerun after the rebase: the W3C suite and the other
fluree-db-apitargets. Both passed before the rebase, and CI covers them.Not in this PR
Existing bugs found while testing this. This PR doesn't make any of them worse.
MATCHtest here uses aWITHfor this reason.nested-opt-2passes here partly by coincidence because of it.RETURN p.name AS p(an alias equal to the node variable) returns zero rows. The new Cypher tests use non-colliding aliases for this reason.