Repository navigation
fix(query): keep left joins in written order when they share a variable - #1927
Conversation
5631f8d to
72a833b
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz the issues behind this + this PR all reason correctly over a clear issue. Good fix. Spent a second dusting-off my SPARQL algebra to make sure I was following correctly. I think the only note below in the full review I want to double-click on is that the planning-specific update does seem to enable an a real & reachable correctness issue given how it exits the loop while dropping unresolved loop-internal patterns. More details below:
The diagnosis and the shape of this fix all excellent — a positional barrier computed once per group, generalising the VALUES barrier from #1690 onto every pattern pair and reusing after_indices, with the placement functions and their tie-breaks left untouched, is the design I'd have wanted. The two exemptions are argued from the algebra rather than from whatever made a test pass, and left_join_barrier_leaves_well_designed_groups_free pinning both the barrier set and the resulting plan position is the right way to make the "well-designed groups keep their plans" claim checkable. I confirmed the tests aren't vacuous: with planner.rs alone reverted to the merge base, all seven new ordering tests go red and the pre-existing ones stay green.
The one thing blocking is the new forced-placement fallback at planner.rs:2114. None => break exits the greedy loop with patterns still in sources/reducers/expanders, and the after-loop only re-appends deferred — so those patterns are dropped from the plan entirely. It is reachable: a barrier edge can point at a pattern that got classified deferred, and if that pattern's required_vars can only be satisfied by the pattern it is blocking, neither moves. The shape is an OPTIONAL referencing an uncorrelated sub-SELECT's output variable with the sub-SELECT written after it — deferred as a WITH-pipeline consumer on that variable at :1941-1969, while the sub-SELECT sits in sources with after_indices = [optional_index]. On this PR's own seed data, SELECT ?s ?nm WHERE { OPTIONAL { ?s ex:name ?nm } { SELECT ?s WHERE { ?s ex:fr ?z } } } returns two rows at HEAD and the correct one row at the merge base — a query we answer correctly today and get wrong after this change. It isn't limited to a leading OPTIONAL; with a required triple in front, reorder_patterns still returns 2 of 3 patterns. The fix is small: when pick is None, fall back to the pre-existing unconditional force-placement so the plan stays complete, with a debug_assert! to surface the shape in CI. The worst case then is the old unsound-but-complete ordering, which is what ships today — strictly better than a missing join.
On performance, I want to be explicit since it isn't a regression to be fixed: the barrier adds no per-row work and returns immediately for groups without an OPTIONAL, but it does change which plans get chosen. A query with a selective required triple after an OPTIONAL it shares an introduced variable with can no longer hoist that triple, and a leading OPTIONAL now runs unseeded — #1924's own repro is the first shape. Both are the price of the right answer, and the body says so; I'd just make sure that lands with whoever fields the first "this query got slower" report.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Generalises
values_optional_barrier_indicesand reusesafter_indices; no parallel ordering mechanism.try_fuse_wildcard_class's&mut [Pattern]narrowing is a real tightening. - Performance (speed first, memory second): ✔ No per-row cost; barrier computation is planner-only and early-outs for
OPTIONAL-free groups. Plan changes are correctness-mandated and confined to groups that were planned unsoundly — worth flagging in release notes, not fixing. - Testing:
⚠️ Seven new integration tests plus four unit tests, all running and all red under aplanner.rs-only revert to base — that part is exemplary. Missing is a case for theNone => breakarm, which no test reaches today. - Conventions: ✔ Self-describing subjects, thorough multi-line bodies, clippy/fmt/W3C green on
72a833b54with no skip-register changes.
Verified locally at branch HEAD: cargo nextest run -p fluree-db-api --features native --test it_optional_after_union → 25 passed, all seven new tests by name; planner.rs reverted to base → the seven go red; the dropped-pattern regression reproduced at both the reorder_patterns level and end-to-end, base-vs-HEAD in both directions.
Requesting changes only for the break at planner.rs:2114 — everything else here I'd merge as-is, and once that arm can't drop a pattern I'm happy to re-approve immediately.
| Some((_, 0, idx)) => sources.remove(idx), | ||
| Some((_, 1, idx)) => reducers.remove(idx), | ||
| Some((_, _, idx)) => expanders.remove(idx), | ||
| None => break, |
There was a problem hiding this comment.
Blocking — the new forced-placement fallback can exit the greedy loop with patterns still in sources/reducers/expanders, and those are never emitted, so the plan silently loses a join.
The mechanism: left_join_order_barriers records an edge from a later index to an earlier one without restricting the earlier pattern's class, and park_blocked only asks whether that index is in placed_indices. So a barrier can point at a pattern that got classified deferred. If that deferred pattern's required_vars can only be satisfied by the pattern it is blocking, neither moves: every try_place_* returns false, barrier_bound is true, pick finds nothing ready, and we break. The after-loop at :2143-2147 re-appends deferred — but not sources/reducers/expanders — so whatever was still parked is gone from result. Before this PR the same situation force-placed sources.remove(0) and the plan stayed complete.
The shape that reaches it is an OPTIONAL that references an uncorrelated sub-SELECT's output variable, with the sub-SELECT written after it. The OPTIONAL is deferred as a WITH-pipeline consumer at :1941-1969 on that variable; the sub-SELECT is a source carrying after_indices = [optional_index], because they share a variable nothing certainly binds before the OPTIONAL. Both wait forever.
Repro, on this PR's own it_optional_after_union seed data (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 ?nm WHERE {
OPTIONAL { ?s ex:name ?nm }
{ SELECT ?s WHERE { ?s ex:fr ?z } }
}FAILS at HEAD (72a833b54) → [(ex:a,"A"), (ex:b,"B")]. PASSES at merge base (c72baaa70) → [(ex:a,"A")], which is also the algebraically correct answer (LeftJoin({}, O) joined with the sub-SELECT's {?s = ex:a}). The sub-SELECT's restriction on ?s is simply not in the plan. So this is a query the engine answers correctly today and answers incorrectly after this change.
At the planner level, reorder_patterns on [Optional{?m ex:p ?x}, Subquery{select ?m}] returns 1 pattern at HEAD and 2 at the merge base. It is not confined to a leading OPTIONAL either — [?a ex:p ?b, Optional{?m ex:q ?b}, Subquery{select ?m}] returns 2 of 3.
Fix: never break with work remaining. Falling back to the pre-existing unconditional force-placement keeps the plan complete, and the worst case is then the old unsound-but-complete ordering for a shape the barrier genuinely cannot satisfy — which is exactly what ships today:
match pick {
Some((_, 0, idx)) => sources.remove(idx),
Some((_, 1, idx)) => reducers.remove(idx),
Some((_, _, idx)) => expanders.remove(idx),
// No unblocked candidate: a barrier points at a deferred
// pattern that cannot become ready. Placing in written
// order is unsound here, but dropping the pattern is
// worse — fall back to the pre-barrier behaviour.
None if !sources.is_empty() => sources.remove(0),
None if !reducers.is_empty() => reducers.remove(0),
None if !expanders.is_empty() => expanders.remove(0),
None => break,
}A debug_assert!(false, "left-join barrier deadlock") alongside it would surface the shape in CI without costing correctness in release. Worth a regression test for the sub-SELECT shape above, since that is the one I could construct and there may be others.
There was a problem hiding this comment.
Good catch, thanks. Fixed in 55af5c6, with a slightly different fallback. Falling back to sources.remove(0) keeps the plan complete, but it places the sub-SELECT first, which is the reorder this PR removes. It happens to give the right rows here only because the OPTIONAL always binds ?s.
Instead, when nothing is ready, the loop now releases the deferred pattern a held candidate is waiting on (release_barrier_blocker) and places it at its written position. Barriers only point backwards, so written order satisfies all of them, and it is the algebraic order: the OPTIONAL runs unseeded and the sub-SELECT then restricts ?s. The pipeline-consumer deferral exists for Cypher WITH, where the producer is always written before its consumer, so only SPARQL reaches this consumer-first shape.
Your unconditional force-placement stays as the last resort behind debug_assert!(false, …), so the loop never exits with work left.
Tests: both of your planner-level shapes (reorder_patterns must return every pattern in written order), plus your repro end to end on SPARQL and JSON-LD. With None => break restored, all four fail, and both surfaces return your two rows.
| // An OPTIONAL is evaluated where it is written relative to the patterns it | ||
| // shares a variable with, so restore written order around it. | ||
| if patterns.iter().any(|p| matches!(p, Pattern::Optional(_))) { | ||
| debug_assert_eq!(origins.len(), result_patterns.len()); |
There was a problem hiding this comment.
Optional — zip after a debug_assert_eq! truncates silently in release. This is the same failure mode as the planner.rs:2114 finding, one file over, and I mention it mostly because the two together make a pattern worth naming.
origins and result_patterns are two parallel vectors maintained by hand across ~10 push sites plus a paired retain at :597-602, and the invariant is checked with debug_assert_eq! and then consumed by origins.into_iter().zip(result_patterns). zip stops at the shorter side, so in a release build any drift drops the tail of result_patterns — patterns vanishing from the plan, with no assertion to catch it.
Every push looks correctly paired to me today, and the &mut Vec<Pattern> → &mut [Pattern] change on try_fuse_wildcard_class is a good tightening precisely because the slice can no longer push or remove behind the caller's back. So this is about the class, not a live bug. Cheapest fix:
| debug_assert_eq!(origins.len(), result_patterns.len()); | |
| assert_eq!(origins.len(), result_patterns.len()); |
Cleaner still would be carrying Vec<(usize, Pattern)> from the start so the two can't drift at all. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Done: assert_eq! now, in the same commit.
| /// the exemption hold in the reordered plan too. | ||
| /// | ||
| /// A FILTER is never the earlier side: it constrains the whole group wherever | ||
| /// it is written, so an OPTIONAL after it must not be held behind it. |
There was a problem hiding this comment.
Nit — worth saying why MINUS/EXISTS don't need a barrier edge.
MINUS, EXISTS and NOT EXISTS are order-sensitive in the same algebraic way a left join is, and the barrier only fires when one side is Pattern::Optional.
I think the answer is that they're already handled by being deferred on the variables of all preceding patterns (:1843 onward), and I couldn't find a case where that's insufficient — but this doc comment explains the OPTIONAL-only scope only implicitly, and a reader reaching for "why isn't MINUS here?" deserves the sentence. Not a behaviour change, just documentation of a deliberate boundary.
There was a problem hiding this comment.
Added to the doc comment: only an OPTIONAL anchors an edge, because reorder_patterns already defers MINUS, EXISTS and NOT EXISTS until every variable produced by the patterns written before them is bound, which keeps them behind those patterns.
| /// | ||
| /// A FILTER is never the earlier side: it constrains the whole group wherever | ||
| /// it is written, so an OPTIONAL after it must not be held behind it. | ||
| fn left_join_order_barriers( |
There was a problem hiding this comment.
Praise — this generalises the existing VALUES barrier instead of adding a second ordering system.
Turning values_optional_barrier_indices (#1690) into a positional barrier over every pattern pair, and reusing the after_indices field DeferredPattern already had, is exactly the "extend the shared mechanism" move — and it's why the placement functions and their position-dependent tie-breaks could be left completely untouched.
The two exemptions — a certainly-bound variable, and never treating a FILTER as the earlier side — are the right ones, and each is argued in the doc comment from the algebra rather than from whatever made a test pass.
| /// the first binder of `?s`, so the trailing `?s r ?y` may still be hoisted | ||
| /// into the star ahead of the OPTIONAL and the plan is unchanged. | ||
| #[test] | ||
| fn left_join_barrier_leaves_well_designed_groups_free() { |
There was a problem hiding this comment.
Praise — asserting both the barrier set and the resulting plan position is the right way to guard a performance claim.
left_join_barrier_leaves_well_designed_groups_free checking barriers == [vec![], vec![0], vec![]] and that the OPTIONAL still lands last is what let me believe "well-designed groups keep their plans" without re-deriving it myself. A barrier-set-only assertion would have left the interesting half unpinned.
| } | ||
|
|
||
| /// Outcome of [`try_fuse_wildcard_class`]. | ||
| enum WildcardClassFusion { |
There was a problem hiding this comment.
Praise — the bool → WildcardClassFusion and &mut Vec<Pattern> → &mut [Pattern] changes are a real tightening, not just plumbing.
Narrowing the parameter to a slice means try_fuse_wildcard_class can no longer push or remove behind the caller's back, which is precisely the thing that would silently desynchronise the new origins bookkeeping. Nicer than threading a flag through and hoping.
| @@ -10955,16 +10955,16 @@ async fn seed_works_for_graph( | |||
| async fn cypher_null_from_optional_match_matches_nothing_in_later_match() { | |||
There was a problem hiding this comment.
Praise — good catch that the WITH was a symptom.
Deleting the WITH p, o that cypher_null_from_optional_match_matches_nothing_in_later_match used as a planner workaround, and replacing the comment with the #1924 explanation, is the kind of thing that usually gets left behind once the real fix lands. It also makes the test prove more than it did before.
72a833b to
1753df9
Compare
2984380 to
8cc8738
Compare
8cc8738 to
ca55b50
Compare
|
@aaj3f thanks. The blocking I also added your performance point to the description's Performance section: some of the changed plans can be slower, and that's the cost of the correct answer. The PR has the |
The planner reordered patterns across an OPTIONAL as if it were an inner
join. `LeftJoin(A, O) ⋈ P` equals `LeftJoin(A ⋈ P, O)` only when every
variable P shares with O is already certainly bound by A; otherwise hoisting
P seeds a variable the left join then matches against, and the left join
keeps every row it fails on.
Two shapes did this. A triple after an OPTIONAL that binds a shared variable
was hoisted above it, fabricating rows on SPARQL, JSON-LD, and Cypher
(`OPTIONAL MATCH … MATCH`). An OPTIONAL sharing nothing with the required
pattern was ineligible until a later OPTIONAL had bound its variable, and ran
after it.
reorder_patterns now computes a positional barrier for every pair of an
OPTIONAL and another pattern that share a variable not bound by required
patterns written before the earlier of the two, and holds the later one
behind it. Groups without an OPTIONAL, and groups whose shared variables are
bound by earlier required patterns, get no barrier and keep their plans. The
forced-placement fallback picks the earliest unblocked pattern.
An OPTIONAL written first in a group is now evaluated as written:
`LeftJoin({}, O)` joined with what follows, not a left join of the later
patterns.
The R2RML rewrite emits same-subject star and class scans after its pass over
the group, so a required triple written before an OPTIONAL reached the planner
behind it. The planner used to hoist it back; now that an OPTIONAL keeps its
written position relative to patterns it shares a variable with, the group ran
as `LeftJoin({}, O) ⋈ A` and dropped every row the OPTIONAL did not match.
Each rewritten pattern now carries the input position of its first member, and
a group containing an OPTIONAL is restored to that order. A triple joins a star
opened before an OPTIONAL only if the OPTIONAL does not also reference its
object variable; otherwise the merge hoists it above the OPTIONAL and fabricates
rows, as in #1924.
…rops patterns When every candidate was held behind an earlier pattern that was itself deferred, the forced-placement fallback broke out of the greedy loop and the patterns still waiting were never emitted. An OPTIONAL written before an uncorrelated sub-SELECT whose output it reads reaches this: the OPTIONAL waits for the sub-SELECT as its pipeline consumer, and the barrier holds the sub-SELECT behind the OPTIONAL. The sub-SELECT's restriction then vanished from the plan. The stall now places the deferred pattern a held candidate is waiting on, at its written position. Written order satisfies every barrier and is the algebraic order. An unconditional force-placement stays as the last resort behind a debug_assert, so the loop never exits with work left. Also: the r2rml origin/pattern pairing is checked with assert_eq!, since zip would otherwise truncate silently in release, and the barrier doc says why MINUS and EXISTS need no edge.
55af5c6 to
bfa453d
Compare
Fixes #1924
Fixes #1925
Problem
The planner reordered patterns across an OPTIONAL as if it were an inner join. Inner joins commute; a left join does not.
LeftJoin(A, O) ⋈ PequalsLeftJoin(A ⋈ P, O)only when every variablePshares withOis already certainly bound byA. Otherwise, hoistingPseeds a variable the left join then matches against, and the left join keeps every row it fails on.?p ex:knows ?f . OPTIONAL { ?p ex:worksFor ?org } ?y ex:worksFor ?orgreturned a fabricated(carol, acme, bob)row. The same happened in Cypher, whereOPTIONAL MATCH (p)-[:WORKS_FOR]->(o) MATCH (o)-[:LOCATED_IN]->(c)returned every person×city pair.OPTIONAL { ex:k ex:g ?f } OPTIONAL { ?s ex:fr ?f }returned(a, ex:b)where(a, "k")is correct.Fix
This fix is contained in
reorder_patterns(fluree-db-query/src/planner.rs).left_join_order_barrierspairs every OPTIONAL with each other pattern in its group. When the two share a variable that isn't certainly bound by required patterns written before the earlier of them (must_bind_vars), the later one is held behind the earlier. This generalises the existing VALUES barrier (VALUES after OPTIONAL cross-products instead of joining (silent wrong results) #1690) to every pattern, and applies it in both directions.RankedPatterngainsafter_indices, whichDeferredPatternalready had. Blocked candidates are parked before each greedy step and restored in original order afterwards, so the placement functions and their tie-breaks are untouched. When nothing is blocked, the lists are never modified.sources[0]regardless of order. When a barrier is active, it now picks the earliest unblocked pattern in written order.debug_assert!.Every barrier edge points from a later index to an earlier one, so the constraints are acyclic and the written order always satisfies them.
Performance
left_join_barrier_leaves_well_designed_groups_freepins this:?s p ?o . OPTIONAL { ?s q ?x } . ?s r ?ystill places both triples ahead of the OPTIONAL.Behaviour change
An OPTIONAL written first in a group is now evaluated as written.
{ OPTIONAL { ?s ex:fr ?x } ?s ex:name ?n }isLeftJoin({}, O)joined with the triple, so it returns only the subjects the OPTIONAL found. Previously the triple was hoisted into a plain left join, so every?scame back with?xunbound where there was no match.planner::tests::test_reorder_expander_after_sourcesasserted that hoist. It now places a required triple first, which keeps its intent ("an OPTIONAL is placed after the sources") on a query where the reorder is sound.Tests
it_optional_after_union.rs, new section:COUNT(*)for both shapes, so a count fast path can't answer from the reordered plan.it_query_cypher.rs:cypher_null_from_optional_match_matches_nothing_in_later_matchno longer needs theWITHit used to work around #1924.planner.rsunit tests pin which barriers fire:To confirm the tests aren't vacuous, I reverted each piece:
None => break) → both stall unit tests and both sub-SELECT integration tests fail, returning(ex:b, "B")too.Verification
On the current head, locally:
fluree-db-query,-cypher,-transact,-sparql: all green.fluree-db-api, all targets except the Docker-backed Iceberg-direct and S3 testcontainers binaries (the local Docker daemon was unresponsive): 4,393 passed. Twoit_fwd_pack_compactiontests timed out under full-suite load; they contain no OPTIONAL and pass on their own (90 s and 118 s).CI runs the full workspace and the W3C suite.