Repository navigation
Description
Sibling OPTIONALs are not commutative: LeftJoin(LeftJoin(A, B), C) differs from LeftJoin(LeftJoin(A, C), B) whenever B and C bind a common variable. The planner nonetheless evaluates an OPTIONAL that shares no variable with the required pattern after a later OPTIONAL that does.
Repro
@prefix ex: <http://example.com/> .
ex:a ex:name "A" ; ex:fr ex:b .
ex:b ex:name "B" .
ex:k ex:g "k" .PREFIX ex: <http://example.com/>
SELECT ?s ?f WHERE {
?s ex:name ?n .
OPTIONAL { ex:k ex:g ?f }
OPTIONAL { ?s ex:fr ?f }
}Expected: (a, "k"), (b, "k"). The first OPTIONAL binds ?f = "k" on every row. The second then fails for a, because a ex:fr "k" is absent, and the row keeps "k".
| Result | |
|---|---|
main (09f15cb) |
(a, ex:b), (b, null) |
| #1923 | (a, ex:b), (b, "k") |
Both are wrong. They differ only because #1923 makes an unmatched OPTIONAL leave ?f unbound, not Poisoned, so the late { ex:k ex:g ?f } can still bind it for b.
When both OPTIONALs are correlated with the required pattern, order is preserved. For example, OPTIONAL { ?s ex:g ?f } OPTIONAL { ?s ex:fr ?f } evaluates left to right.
Where
try_place_expander (fluree-db-query/src/planner.rs:2461 on main) only admits an expander whose pattern shares a variable with bound_vars (:2471). An uncorrelated OPTIONAL is therefore ineligible until a later OPTIONAL has bound ?f, and it is placed after it. Among eligible OPTIONALs, orig_index breaks the tie, since every OPTIONAL estimates Expander { multiplier: 1.0 } (:991). That is why the correlated case keeps its order.
Notes for whoever takes it
- W3C
algebra/nested-opt-2has this shape: its first OPTIONAL,{ :x3 :q ?w }, is uncorrelated. It passes on fix(query): unmatched OPTIONAL leaves vars unbound in SPARQL, null in Cypher #1923 only because the swapped order happens to give the same answer on its data. The register comment intestsuite-sparql/tests/registers/mod.rsrecords this. A fix should keep it passing, for the right reason. - Placing an uncorrelated OPTIONAL in written order runs it against every row, which is the intended semantics. Check that doing so doesn't regress plans where a later correlated OPTIONAL would otherwise have narrowed the rows first.
- Likely fixed alongside Planner hoists a triple above a preceding OPTIONAL that binds a shared variable, returning wrong rows #1924, a triple hoisted above an OPTIONAL; both come from
reorder_patternstreating patterns around a left join as freely movable.
Activity