Skip to content

fix(query): keep left joins in written order when they share a variable - #1927

Merged
bplatz merged 3 commits into
mainfrom
fix/optional-ordering-1924-1925
Sep 25, 2026
Merged

bplatz merged 3 commits into
mainfrom
fix/optional-ordering-1924-1925

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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) ⋈ 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.

Fix

This fix is contained in reorder_patterns (fluree-db-query/src/planner.rs).

  • left_join_order_barriers pairs 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.
  • Two cases are exempt:
    • A variable certainly bound before the pair, because the OPTIONAL only restricts it there, and restricting a required variable commutes.
    • A FILTER as the earlier side, because a FILTER constrains its whole group wherever it's written.
  • RankedPattern gains after_indices, which DeferredPattern already 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.
  • The forced-placement fallback, which fires when nothing is eligible (as with an uncorrelated OPTIONAL), used to take sources[0] regardless of order. When a barrier is active, it now picks the earliest unblocked pattern in written order.
  • If every candidate is held behind a pattern that is itself deferred, the loop releases that blocker at its written position. For example, an OPTIONAL written before an uncorrelated sub-SELECT whose output it reads is deferred as the sub-SELECT's pipeline consumer while the barrier holds the sub-SELECT behind it. The loop never exits with patterns left; an unconditional force-placement is the last resort, behind a 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

  • Groups with no OPTIONAL: the barrier returns immediately and nothing else runs.
  • Well-designed groups, where every variable an OPTIONAL shares with its group is bound by a required pattern written before it: no barrier fires, so plans are unchanged. That covers the common required-star-plus-trailing-OPTIONAL shape, including property-join tails.
    • The one edge in that case holds the OPTIONAL behind the first binder of its correlation variable, which is where the planner already puts it.
    • left_join_barrier_leaves_well_designed_groups_free pins this: ?s p ?o . OPTIONAL { ?s q ?x } . ?s r ?y still places both triples ahead of the OPTIONAL.
  • Changed plans: only groups that actually had an unsound reorder, which now run in written order. Some of these can be slower: a selective triple after an OPTIONAL it shares an unbound variable with can no longer be hoisted to seed it, and a leading OPTIONAL now runs unseeded. That is the cost of the correct answer. Worth knowing when fielding a "this query got slower" report.

Behaviour change

An OPTIONAL written first in a group is now evaluated as written. { OPTIONAL { ?s ex:fr ?x } ?s ex:name ?n } is LeftJoin({}, 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 ?s came back with ?x unbound where there was no match.

planner::tests::test_reorder_expander_after_sources asserted 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:

it_query_cypher.rs: cypher_null_from_optional_match_matches_nothing_in_later_match no longer needs the WITH it used to work around #1924.

planner.rs unit tests pin which barriers fire:

To confirm the tests aren't vacuous, I reverted each piece:

  • Barrier off → the seven new ordering integration tests fail, plus the Cypher later-MATCH test.
  • Naive forced placement → the forced-placement and leading-OPTIONAL tests fail.
  • The stall exiting the loop (None => break) → both stall unit tests and both sub-SELECT integration tests fail, returning (ex:b, "B") too.

Verification

On the current head, locally:

  • fmt and clippy.
  • 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. Two it_fwd_pack_compaction tests 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.

@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 25, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 25, 2026 03:45
@bplatz
bplatz added this pull request to stack #1922 September 25, 2026 03:45
@bplatz
bplatz force-pushed the fix/optional-ordering-1924-1925 branch from 5631f8d to 72a833b Compare September 25, 2026 10:24

@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 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_indices and reuses after_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 a planner.rs-only revert to base — that part is exemplary. Missing is a case for the None => break arm, which no test reaches today.
  • Conventions: ✔ Self-describing subjects, thorough multi-line bodies, clippy/fmt/W3C green on 72a833b54 with 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.

Comment thread fluree-db-query/src/planner.rs Outdated
Some((_, 0, idx)) => sources.remove(idx),
Some((_, 1, idx)) => reducers.remove(idx),
Some((_, _, idx)) => expanders.remove(idx),
None => break,

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 — 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread fluree-db-query/src/r2rml/rewrite.rs Outdated
// 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());

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 — 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:

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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(

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 — 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() {

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 — 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 {

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 — 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() {

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 — 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.

@bplatz
bplatz removed this pull request from stack #1922 September 25, 2026 18:27
@bplatz
bplatz force-pushed the fix/optional-ordering-1924-1925 branch from 72a833b to 1753df9 Compare September 25, 2026 19:15
@bplatz
bplatz added this pull request to stack #1947 September 25, 2026 19:15
@bplatz
bplatz force-pushed the fix/optional-ordering-1924-1925 branch 3 times, most recently from 2984380 to 8cc8738 Compare September 25, 2026 21:21
Base automatically changed from fix/graph-routing-ledger-ids to main September 25, 2026 21:31
@bplatz
bplatz force-pushed the fix/optional-ordering-1924-1925 branch from 8cc8738 to ca55b50 Compare September 25, 2026 21:31
@bplatz

bplatz commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f thanks. The blocking break is fixed in 55af5c6 (details on the thread): a stall now releases the blocking pattern at its written position rather than dropping anything. assert_eq! and the MINUS/EXISTS doc sentence are in the same commit.

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 bug label, so it lands under fixes in the release notes.

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.
@bplatz
bplatz force-pushed the fix/optional-ordering-1924-1925 branch from 55af5c6 to bfa453d Compare September 25, 2026 23:11
@bplatz
bplatz merged commit dc86a6e into main Sep 25, 2026
16 checks passed
@bplatz
bplatz deleted the fix/optional-ordering-1924-1925 branch September 25, 2026 23:13
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

2 participants