Skip to content

VALUES after OPTIONAL cross-products instead of joining (silent wrong results) #1690

Closed

Description

@bplatz

Summary

A VALUES clause placed after an OPTIONAL that binds its variable cross-products instead of joining, returning every row of the driving pattern instead of the rows the VALUES selects. Silent wrong results — no error, no warning.

Reported by @aaj3f while reviewing #1681; confirmed independently and confirmed pre-existing (reproduces on that branch with its planner change reverted, and the shape never reached that change in the first place).

Reproduction

On a ledger with 1500 ns:entity1 edges, where exactly one edge has ns:entity2 = <B>:

PREFIX ns: <http://example.org/ns#>
SELECT ?ev ?b WHERE {
  ?ev ns:entity1 ?a ; ns:snap ?s .
  OPTIONAL { ?ev ns:entity2 ?b }
  VALUES ?b { <B> }
}

Returns 1500 rows. The semantically equivalent form:

  ?ev ns:entity1 ?a ; ns:snap ?s .
  OPTIONAL { ?ev ns:entity2 ?b }
  FILTER(?b = <B>)

Returns 1 row, which is the correct answer.

Per SPARQL 1.1 §18.2.4, a trailing VALUES joins with the group's solutions on shared variables, so ?b bound by the OPTIONAL must be constrained to <B>. Rows where the OPTIONAL bound ?b to something else must not survive, and rows where it left ?b unbound join as match-any only against an UNDEF cell.

The reviewer measured the same defect at 3000 rows vs an expected 2 on a comparable fixture, so the multiplier tracks the driving pattern's cardinality rather than being a fixed factor.

Why it matters

  • It is wrong answers, not slow answers, and nothing signals it.
  • The correct-looking rewrite (FILTER) and the broken one (VALUES) are shapes a user would consider interchangeable.
  • VALUES after OPTIONAL is a natural way to write a parameterized query, so this is reachable from ordinary usage rather than an exotic corner.

Where to look

The suspect is the interaction between the trailing-VALUES placement and OPTIONAL's produced variables in fluree-db-query/src/execute/where_plan.rs — specifically whether the ValuesOperator is being seeded at the base of the plan (a cartesian product) rather than joined above the OPTIONAL that produces ?b. The block-assembly comments already flag the seed-vs-defer hazard for disconnected VALUES; this looks like the same hazard on a variable that is produced, but produced optionally.

Not scoped to a fix here deliberately — the correct join placement for a VALUES over an optionally-bound variable is a semantics decision worth making on purpose.

Activity

  1. added
    bug
    on Aug 25, 2026
  2. added
    area:query
    P1
    on Aug 26, 2026
  3. aaj3f commented on Aug 26, 2026

    @aaj3f
    Contributor

    Ran this through the triage sweep's verification protocol (claude-assisted) since it came in fresh — confirmed at a824bbfd1, and I think it's worse than the report has it, plus two corrections that matter for whoever writes the guard test.

    The defect is a fabricated binding, not just a cross-product. On a 6-row fixture where the OPTIONAL binds ?b to ns:X0..X5/ns:B, the in-group VALUES form returns all six rows reporting ?b = ns:B. So the surviving rows don't merely multiply — they report a value the data never had.

    Mechanism is upstream of where the body points. reorder_patterns (fluree-db-query/src/planner.rs) classifies Pattern::Values as an exact-cardinality source and hoists it to seed position — EXPLAIN's logical plan lists source values first even for a VALUES written last. The order-sensitivity guard at planner.rs:1316-1341 defers Minus/Exists/NotExists and correlated subqueries precisely so the reorder can't outrun what feeds them, but a Values whose variable is produced by a preceding Optional isn't covered. The physical plan confirms the consequence: OptionalOperator > ValuesOperator, so the OPTIONAL runs against an already-bound variable and, being a left join, drops nothing.

    Correction 1 — this isn't an open semantics question. testsuite-sparql/rdf-tests/sparql/sparql11/bindings/values07 is this exact shape, isn't in the skip register, and its .srx pins the answer. It passes today only because it uses the post-query spelling (} VALUES …), which we plan correctly — verified by moving the VALUES outside the braces on the same ledger: right answer, ValuesOperator above OptionalOperator. The correct behavior already exists in-engine on the sibling path.

    Correction 2 — and this one is a trap for the fix. The expected counts in the body hold only when the variable is bound on every row. Per §18.2.4 join compatibility, a row whose OPTIONAL left ?b unbound is compatible with a VALUES row binding ?b, so it survives and adopts the value. On the 1500-edge fixture, if 1498 rows have no ns:entity2, the spec answer for VALUES ?b { <B> <C> } is 2998, not 2 — and FILTER is not the equivalent rewrite, since FILTER drops unbound rows where VALUES adopts them. A guard test needs to pin both shapes, otherwise a "drop the unbound rows" over-fix will look green.

    Both surfaces are affected — the JSON-LD ["values", …] form after ["optional", …] clobbers identically, consistent with the planner-level cause — so the fix wants a JSON-LD twin test per the parity rule. Bumping to P1 given the silent-wrong-results shape.

  4. bplatz commented on Aug 28, 2026

    @bplatz
    ContributorAuthor

    Correction to the repro while reviewing #1701, because as filed it teaches the wrong diagnostic.

    The bug is real, but this repro doesn't demonstrate it.

    The shape described here — 1500 driving rows, exactly one of which has the OPTIONAL predicate at all — returns the correct answer. I modelled it exactly on seed_values_dataset (ex:cool is only on ex:nikola, so four driving rows leave ?c unbound and one binds it) against pristine main (fe3c198c8):

    SELECT ?s ?c WHERE { ?s schema:name ?name . OPTIONAL { ?s ex:cool ?c } VALUES ?c { true } }
    in-group   VALUES:  5 rows
    post-query VALUES:  5 rows   <- identical
    

    The post-query spelling (} VALUES …) has always planned correctly and is the reference. Buggy and correct paths agree here.

    In this issue's numbers: per §18.2.4 the trailing VALUES is Join(…, ToMultiSet(data)), and Join keeps a solution when the two mappings are compatible — which for a variable the OPTIONAL left UNBOUND is trivially true. So the 1499 unbound rows survive and adopt <B>, and the one bound row is kept. 1500 is the correct answer, and it's what the engine returned.

    The "correct answer is 1" above is the FILTER answer. FILTER(?b = <B>) evaluates to a type error on an unbound ?b and drops the row; VALUES adopts it. They aren't interchangeable, which is the point #1701's trailing_values_is_a_join_not_a_filter pins.

    What the defect actually is. It only surfaces when the OPTIONAL binds a different value, and then it's a fabricated binding rather than an extra row. On the same fixture:

    SELECT ?s ?f WHERE { ?s schema:name ?name . OPTIONAL { ?s ex:friend ?f } VALUES ?f { ex:alice } }
    main, in-group   VALUES:  5 rows, including ["ex:alice","ex:alice"]   <- fabricated
    main, post-query VALUES:  4 rows                                       <- correct
    main, FILTER:             2 rows
    

    ex:alice's only ex:friend is ex:brian, so no solution may report her with ?f = ex:alice. Two spellings of one query disagreeing is the cleanest statement of it.

    Nothing changes about the fix or its priority — #1701 is correct and its fixture is the right one. Recording this so the repro here isn't reused as a regression check, since it passes both before and after.

  5. aaj3f commented on Aug 28, 2026

    @aaj3f
    Contributor

    Correcting the repro in this issue, because it doesn't actually demonstrate the bug — confirmed by construction while fixing it.

    Modelling the filed shape exactly (one subject has the OPTIONAL predicate; every other driving row leaves the variable unbound), the two spellings agree on main:

    main, in-group VALUES:   5 rows
    main, post-query VALUES: 5 rows   <- identical
    

    Buggy and correct paths return the same answer. In this issue's own numbers: 1 bound-compatible row + 1499 unbound-and-adopting rows = 1500, which is what the engine returned. The defect is invisible whenever every non-matching driving row leaves the variable unbound, because the fabricated rows and the legitimately-adopting rows are then indistinguishable by count.

    The defect only surfaces once the OPTIONAL binds a different value than the VALUES supplies. That's the fixture the fix is pinned against, and it's the load-bearing part rather than an incidental detail.

    One more correction, to this issue's expected answer: the "correct answer is 1" here is the FILTER answer. Per §18.2.4 join compatibility, a row whose OPTIONAL left the variable unbound is compatible with a VALUES row binding it, so it survives and adopts the value — VALUES is a join, not a filter. trailing_values_is_a_join_not_a_filter in #1701 pins exactly that distinction, precisely because the FILTER rewrite is the tempting-but-wrong equivalence.

    Leaving this here rather than silently fixing it, so the repro doesn't teach the wrong diagnostic to whoever reads the issue next. Credit to @bplatz for catching that the fixture was coincidentally clean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1area:querybug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions