Skip to content

fix(query): treat OPTIONAL-unbound vars as free inside EXISTS - #1920

Closed
bplatz wants to merge 1 commit into
mainfrom
fix/exists-optional-unbound-free
Closed

bplatz wants to merge 1 commit into
mainfrom
fix/exists-optional-unbound-free

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

With ex:alice ex:knows ex:bob . ex:bob ex:worksFor ex:acme .:

SELECT ?p ?org WHERE {
  ?p ex:knows ?f .
  OPTIONAL { ?p ex:worksFor ?org }
  FILTER NOT EXISTS { ?p ex:knows ?x . ?x ex:worksFor ?org }
}

We return alice but the correct answer is to return nothing. EXISTS substitutes only the variables the row actually binds (SPARQL 1.1 §18.6). So for alice the body becomes ex:alice ex:knows ?x . ?x ex:worksFor ?org, with ?org free. That matches through bob/acme, so NOT EXISTS should remove the row.

Cause

A failed OPTIONAL marks ?org as Binding::Poisoned, which by design blocks any later pattern that uses it (NestedLoopJoinOperator::has_poisoned_binding drops the row). The EXISTS paths seed their body from the outer row as-is. The inner ?x ex:worksFor ?org therefore matched nothing, and NOT EXISTS came out true.

Both lanes of FLUREE_DISABLE_QUERY_FAST_PATHS return the same wrong answer, because the defect is in the plan they share.

Fix

A new SeedOperator::for_exists_from_batch_row demotes Poisoned to Unbound and leaves the schema unchanged. The three per-row EXISTS seed sites now use it:

  • SemijoinOperator::per_row_has_match: the fallback for rows with an unbound key variable. This is the path the query above takes.
  • ExistsOperator::has_match
  • filter.rs eval_exists_for_row: EXISTS inside a larger expression.

The cached EXISTS shortcut in filter.rs (try_eval_simple_exists_semijoin) already treats an OPTIONAL-unbound object as free, and its comment makes the same argument. This change brings the other paths into line with it. Joins and OPTIONAL keep their Poisoned semantics.

Performance

Queries without this shape are unaffected:

  • The semijoin hash probe is untouched. Rows reach the changed code only when a key variable is unbound.
  • The only added cost is one scan over the seeded row's bindings. It runs only in paths that already build and run an inner operator tree per row.
  • No plan changes.

The rows that were wrong now evaluate their body instead of short-circuiting.

Tests

it_query_negation.rs gets sparql_not_exists_treats_optional_unbound_var_as_free and a JSON-LD twin. The data covers three cases:

  • ?org unbound, body matches: alice, removed.
  • ?org bound to a different org: carol, kept.
  • ?org unbound, body doesn't match: dave, kept.

The SPARQL test routes the same NOT EXISTS through the semijoin, the per-row ExistsOperator, and the compound-expression evaluator, and reports every lane that disagrees. It also checks the positive EXISTS case.

To confirm the tests aren't vacuous, I reverted each seed site on its own. Each time, exactly the matching lane failed.

Run locally, all green:

  • fluree-db-query lib tests
  • grp_query_sparql
  • it_exists_semijoin_correlation
  • the full W3C suite in testsuite-sparql, with no stale register entries

Not in this PR

Related: #1734. That issue covers the same Poisoned-vs-unbound mismatch for a second OPTIONAL on the same variable. It's a design decision and is left open.

Also seen while probing, not yet filed: ?p ex:knows ?f . OPTIONAL { ?p ex:worksFor ?org } ?y ex:worksFor ?org returns an extra (carol, acme, bob) row. The planner moves the trailing triple ahead of the OPTIONAL even though they share ?org.

A failed OPTIONAL marks its variables Poisoned, which blocks any later
pattern that mentions them. EXISTS / NOT EXISTS seeded their body from
the outer row verbatim, so a Poisoned var made every inner pattern using
it match nothing: NOT EXISTS became true and kept rows it should remove.

EXISTS substitutes only bound variables (SPARQL 1.1 §18.6), so the per-row
seeds for the semijoin fallback, ExistsOperator, and expression-level
EXISTS now demote Poisoned to Unbound.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bplatz this makes sense and is a good fix. You'll see that Claude, below, is quite concerned about the fact that this introduces a regression only for #1923 to fix it (its main concern being that main will have a regression for at least a few commits if these are split across 1920 and 1923). I'm not, personally, very worried about this, so I'm happy if you take-or-leave its recommendations to close this, re-stack, and fold this PR's durably-valuable tests into 1923 etc. I'll leave the whole review for you to consider, but just want to reiterate that I imagine 1920 and 1923 will be merged within minutes of each other and won't, for example, span a release boundary


The diagnosis here is exactly right and the fix is about as surgical as it could be — a second SeedOperator constructor so the three EXISTS call sites declare their own semantics, with everything else (MINUS, the membership join, the Cypher comprehension, the hash-probe fast path) left alone. I checked all fourteen from_batch_row call sites and you found precisely the three that matter, and the §18.6 reasoning in seed.rs:58-63 is the kind of comment that makes the next person's job easy. My only reason for not approving is a merge-order one rather than a disagreement about the code: on this branch, in main's world where an unmatched OPTIONAL MATCH still writes Poisoned, the demotion also strips Cypher's null — and Claude confirmed by porting #1923's test that EXISTS { (o)-[:LOCATED_IN]->(:City) } over a null o returns true at 71797ad3f and false at the merge-base. I know #1923 documents this and removes the demotion, but #1923 is two layers up behind #1921, so "merge them together" isn't something the base branches can actually enforce — whenever this lands first, main carries the regression in the gap. Since #1923 reverts this PR's engine change wholesale, my suggestion would be to fold these two tests into #1923 and close this one; failing that, the constraint belongs in this commit's body, since right now neither the body nor the commit message mentions Cypher.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends SeedOperator with a second constructor rather than threading a flag through build_where_operators_seeded; MINUS keeps its own operator and the join-shaped seeds are untouched.
  • Performance (speed first, memory second): ✔ One linear scan over the seeded row, only on rows that already build and run a per-row inner operator tree; the all_keys_bound hash-probe gate (semijoin.rs:97) and every plan shape are unchanged. No performance-degradation risk.
  • Testing: ⚠️ The two new tests are wired into grp_query_sparql and are non-vacuous (each seed site reverted → the matching lane fails), and there's a JSON-LD twin per the parity rule. But nothing covers the second surface this change silently redefines.
  • Conventions: ✔ Multi-line commit body carrying the rationale; clippy/fmt/testsuite-sparql green at head; W3C skip register untouched, which is the allowed direction.

Verified locally at branch HEAD 71797ad3f: cargo nextest run -p fluree-db-api --test it_query_cypher --test grp_query_sparql -E 'test(~optional_unbound) + test(~null_from_optional)' → 5 passed / 1 failed (the ported Cypher EXISTS case); the same run with the three seed sites reverted inverts to 4 passed / 2 failed, which pins both the non-vacuity of your tests and the Cypher regression in one shot. Worktree restored clean.

Not blocking on the code — just on the order. Easiest path is probably folding these tests into #1923 and closing this; if you'd rather keep the stack, let's at least get the "don't merge without #1923" constraint into the commit body before it goes in.

Not anchorable inline:

Optional, housekeeping — two lines in the PR body have gone stale since you wrote them. Under "Not in this PR", the "also seen while probing, not yet filed" extra-row bug is now filed as #1924, and #1734 is listed as "left open" but #1923 closes it. Worth a quick edit so the body doesn't outlive its own accuracy.

/// §18.6), so a variable left unbound by an unmatched OPTIONAL is free inside
/// the body. `Poisoned` would instead make every inner pattern mentioning it
/// match nothing, so it is demoted to `Unbound` here.
pub fn for_exists_from_batch_row(batch: &Batch, row_idx: usize) -> Self {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking — this demotion is unconditional, so it also strips Cypher's null, and on this branch that makes EXISTS over a null answer true.

Binding::Poisoned isn't only SPARQL's unmatched-OPTIONAL marker on main — it's also what an unmatched OPTIONAL MATCH writes for Cypher, and Cypher's contract is that a null matches nothing. Because for_exists_from_batch_row demotes every Poisoned in the row regardless of surface, a Cypher EXISTS { (o)-[:LOCATED_IN]->(:City) } on a row whose o is null stops asking "does this null node have a city" and starts asking "does any node have a city".

Claude reproduced it rather than inferring it — I ported #1923's cypher_null_from_optional_match_matches_nothing_inside_exists into a worktree at this head:

MATCH (p:Person)
OPTIONAL MATCH (p)-[:WORKS_FOR]->(o)
RETURN p.name AS person, EXISTS { (o)-[:LOCATED_IN]->(:City) } AS located

FAILS at 71797ad3f (Bob → true), PASSES with these three seed sites reverted, i.e. at merge-base 09f15cb33. So it's a regression this PR introduces, and CI can't see it: all 246 existing it_query_cypher tests pass at this head, because none of them pinned the behaviour.

I know from #1923's description that you already have this mapped — "#1920 on its own therefore regresses Cypher" — and that the intent is to merge the two together. The problem is that "together" isn't a state GitHub can express here. This PR's base is main and it currently reports mergeable: MERGEABLE, mergeStateStatus: CLEAN — it can merge today, on its own, with one click. #1923 sits two layers up behind #1921 (+1134/−218), which is its own substantial review. So whenever this one is ready first, main carries the regression until #1921 and #1923 both land.

The arithmetic that makes me raise it as more than a preference: git diff origin/main...refs/pr-review/1920 touches seed.rs (+16) and exists.rs/filter.rs/semijoin.rs (one line each), and those same four files at #1923's head are byte-identical to origin/main — so the engine change is fully undone two layers up, and what actually survives the stack is the 122 lines of test. The option I'd lean toward is folding sparql_not_exists_treats_optional_unbound_var_as_free and its JSON-LD twin into #1923 and closing this PR, which leaves main correct at every commit. If you'd rather keep the stack as it is, then at minimum the constraint needs to live in this commit's body rather than only in a sibling PR's description — git log is what a future bisect reads, and right now the commit message doesn't mention Cypher at all.

"expression-level NOT EXISTS should equal pattern-level NOT EXISTS"
);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional — the three-lane harness is genuinely good, but the one lane it doesn't cover is the one whose meaning changed.

I verified each lane routes where the comments say it does: all_keys_bound at semijoin.rs:97 gates the semijoin fallback, choose_exists_strategy at where_plan.rs:585 picks ExistsOperator for the outer-only-?f case, and the compound FILTER reaches eval_exists_for_row.

What's missing is a Cypher case — here, or in it_query_cypher.rs. A single one would have turned the blocking finding above into a red CI run instead of a cross-PR note.

This is minor and non-blocking on its own, but if you agree it's right I'd rather see it folded in now than tracked and forgotten.

}
}

/// Seed for an EXISTS / NOT EXISTS body.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise — putting the §18.6 argument in the doc comment, right next to the code that acts on it, is what makes this reviewable at all.

And the observation that try_eval_simple_exists_semijoin had already made the same argument in its own comment is the right kind of find. I checked it: the cached lane genuinely can't disagree with the per-row lanes, because build_exists_semijoin_cache (filter.rs:230-240) declines to build an entry whenever the object var is in the batch schema, so it never sees a poisoned object at all.

planning: &crate::temporal_mode::PlanningContext,
) -> Result<bool> {
let seed = SeedOperator::from_batch_row(batch, row_idx);
let seed = SeedOperator::for_exists_from_batch_row(batch, row_idx);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree-db-query/src/filter.rs:362

Praise — leaving eval_pattern_comprehension_for_row on from_batch_row is the right call, and easy to have gotten wrong in a sweep.

A comprehension is join-shaped, not EXISTS-shaped, so the blocking behaviour belongs there. Same for membership_join.rs:239. I enumerated all fourteen from_batch_row call sites and the three you changed really are the only EXISTS ones.

Commenting here because fluree-db-query/src/filter.rs:362 is not in this diff.

bplatz added a commit that referenced this pull request Sep 25, 2026
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.
@bplatz
bplatz removed this pull request from stack #1922 September 25, 2026 18:27
@bplatz

bplatz commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #1923. Once SPARQL and JSON-LD leave an unmatched OPTIONAL's variables Unbound at the source, this PR's EXISTS-seed demotion only fires for Cypher, where it's wrong (per the review). The tests are the part worth keeping, and they moved to #1923 unchanged.

@bplatz bplatz closed this Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants