Skip to content

fix: two v4.1.6 planner regressions — star-join reorder and membership-join admission - #1674

Merged
bplatz merged 6 commits into
mainfrom
fix/planner-fanout-and-membership-gate
Aug 25, 2026
Merged

bplatz merged 6 commits into
mainfrom
fix/planner-fanout-and-membership-gate

Conversation

@bplatz

@bplatz bplatz commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Two independent query-planner regressions between v4.1.2 and v4.1.6, found by the SPARQLoscope dblp-core and BSBM regression runs. Neither is a correctness issue — results are identical across both releases — both are planner misses.

1. Star joins stopped reordering (dblp optional-join-3-star-2, 2.4x)

estimate_triple_row_count rounded the bound-subject multiplier count/ndv_subjects up to an integer. With the v4.1.6 import statistics signatureDblpName (1.004/subject) and rdf:type (1.96/subject) both became 2, the seed ranking tied, and source order ran the 127M-row rdf:type probe second. The statistics were not the bug: ndv_subjects is an HLL256 estimate (σ≈6.5%), so a one-per-subject predicate's ratio lands anywhere in ~[0.9, 1.1] — v4.1.2 sketched it just above the flake count (→ 1), v4.1.6 just below (→ 2). The plan should not depend on which side of an integer the sketch falls.

Fix: keep the bound-subject / bound-object multiplier fractional, floored at 1.0. Unit test pins the dblp shape with both releases' exact statistics.

2. BSBM Q10 at 1M (0.66 ms → 9.6 ms warm, 16x)

The membership-join lane's small-driving-side gate read left.estimated_rows(), which DatasetOperator and NestedLoopJoinOperator both return as None; None is treated as unbounded, so ~21 offers of one product drained the entire dc:publisher extension into a hash set. At 100M the build exceeds the 250k ceiling, which is why the report saw Q10 flat there.

Fix: fall back to HashJoinPlanner::step_est() — the running chain estimate the object hash-join gate is already costed against (EXPLAIN's driving-est) — when the operator has no estimate. Tests build the Q10 prefix and pin decline at ~20 driving rows / admission at ~5.6k.

Not caused by 3ecb8ac8e (the star top-k decline) as the report suspected — that gates a GROUP BY path and Q10 has no GROUP BY. The Sort/Limit nodes "missing" from the committed v4.1.2 plan are a rendering artifact: the v4.1.2 release binary against the same ledger produces them too; the only physical difference is MembershipJoinOperator.

Measurements

BSBM 1M, same ledger, one warm server per binary, median of 30 requests:

query v4.1.2 v4.1.6 this branch
Q10 0.66 ms 9.64 ms 0.60 ms
Q1–Q9, Q11, Q12 — flat flat (±0.05 ms)
Q7 0.68 0.60 0.72

Q7's +0.1 ms is the same HLL noise class: two exactly-one-per-subject predicates (publisher 1.007 vs vendor 1.069) now tie-break the other way. The dblp side can't be re-measured locally (561M triples) and is worth confirming on the benchmark box.

Other query shapes checked

cargo test -p fluree-db-query (1,419), grp_query, grp_policy, grp_query_sparql, grp_query_history, grp_query_reason, grp_transact, it_query_cypher*, it_policy_cypher, it_query_sparql_indexed, it_query_explain, it_fastpath_1652_regression, it_cyclic_bgp_probe, it_exists_semijoin_correlation — all green; clippy -D warnings clean.

bplatz added 4 commits August 21, 2026 08:23
estimate_triple_row_count rounded the per-row multiplier count/ndv up to
the next integer. For a star join the seed ranking compares that number
across the remaining probes, so two predicates at 1.004 and 1.96 rows
per subject both read as 2 and the tie-break kept source order — dblp
`optional-join-3-star-2` ran the 127M-row rdf:type probe before the
29M-row signatureDblpName probe, 2.4x slower than v4.1.2.

The ratio is an HLL256 estimate (σ≈6.5%), so a one-value-per-subject
predicate lands anywhere in ~[0.9, 1.1]: v4.1.2 happened to sketch
ndv_subjects above the flake count (ceil → 1) and v4.1.6 just below it
(ceil → 2). Neither figure is wrong; the plan should not depend on which
side of an integer the sketch falls.

Keep the multiplier fractional, floored at 1.0, for both bound-subject
and bound-object probes. The test pins the dblp shape with both
releases' statistics.
…ng estimate

membership_join_key_vars declines when the driving side is small, but
it read the size from left.estimated_rows(), and both DatasetOperator
and NestedLoopJoinOperator report None there. None is treated as
unbounded, so every plain scan chain admitted the lane: BSBM Q10 at 1M
(~21 offers of one product, then `?offer dc:publisher ?vendor` with both
vars bound) drained the whole dc:publisher extension into a hash set to
answer 21 rows — 0.66 ms → 9.6 ms warm. At 100M the build exceeded the
250k ceiling, which is why the regression only showed at 1M.

Fall back to HashJoinPlanner::step_est(), the running chain estimate the
object hash-join gate is already costed against (EXPLAIN's driving-est),
when the operator has no estimate of its own. VALUES/subquery producers
still supply theirs. Two tests build the Q10 prefix and pin decline at
~20 driving rows and admission at ~5.6k.
`probe_helpers_merge_novelty` pinned the batched-EXISTS lane on
`ex:alice ex:knows ?b . ?b ex:age 26`, but the two patterns' seed
estimates were means that landed 0.08 apart (knows 1.33 =
count/ndv_subjects, age 1.25 = count/ndv_values). They tied only
because the fan-out was rounded up; with fractional fan-out the age
check wins the seed, the driver becomes the check, and the exists lane
never runs — the row counts stay correct, so only the span assertion
notices.

Give ex:age eight filler subjects sharing one value. The seed race is
now 1.33 vs 2.60, so the knows driver seeds on a ~2x margin rather
than on which side of an integer the estimate rounds to.
The CompositeList fixture's `@list` arrays hold string literals (the terms
are not `@type: @id`) while s1's `ex:authoredBy` is an IRI, so s1 never
joins; s2's duplicate lists pair 2×2 and s3 pairs once — 5 rows. The old
pin of 3 was the membership lane answering the shape as a semi-join (one
row per driving row); with the lane gated on driving size the generic join
runs and the pin records what a var-object join over list elements means.
@bplatz
bplatz force-pushed the fix/planner-fanout-and-membership-gate branch from 6f1a9c1 to f41e33b Compare August 21, 2026 12:35
@bplatz
bplatz changed the base branch from main to fix/literal-identity-lang-and-list-position August 21, 2026 12:35

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

Good catches & nice diagnoses, @bplatz. The notes below are all optional, and the one hard constraint is merge order rather than code.

Merge order (load-bearing, but already what the stack encodes): this PR depends on #1676 landing first. I cherry-picked these four commits onto origin/main without #1676 and the 1652 target fails — composite join, no arena values returns [6] against the pinned [5], which is the d-5 "bob"@en / "bob"@fr pair joining in the generic pipeline once the membership lane declines at the fixture's small driving set (the exact unmasking #1676's body describes). At HEAD, with #1676 underneath, it passes. So this one should stay stacked and be retargeted to main only after #1676 merges — never merged standalone.

On CI: the current head did get a real run (the force-push beat the retarget by one second, so the synchronize event fired with base = main and the merge ref carried the whole stack — test/clippy/fmt/sparql all green, 1652 target visible in the log), but any further push here gets no CI since ci.yml only fires on PRs into main, so the green checks after that point would be absence, not passage.

Two things I'd like your read on, neither blocking:

(1) the .or_else order at where_plan.rs:2800 still lets the NestedLoopJoinOperator ×10 heuristic (join.rs:1520) override step_est once a VALUES/subquery seeds a chain — I probed VALUES ?a {30 rows} . ?a :knows ?b . ?b :knows ?a and the lane fires at a planner-estimated 30 driving rows; pre-existing, but this PR is the natural place to make the gate and EXPLAIN's driving-est agree by consulting step_est first.

(2) The fractional fan-out shrinks every multi-hop chain estimate ceil used to inflate, and HASH_JOIN_MAX_SCAN_RATIO was tuned against the inflated numbers — BSBM flat is good evidence for the shapes we bench, dblp's many-probe stars are the ones that would show a hash-join → NLJ flip, so I'd second the benchmark-box run you propose. There's also a comment-wording nit on the list-rows pin (it reads the bag-join count as the settled meaning while #1676 defers that call).

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends HashJoinPlanner with a one-line accessor over state it already tracks; no parallel cost model, no operator-level changes; the class-fallback ceil at planner.rs:197 is correctly left alone (total-rows, not a multiplier).
  • Performance (speed first, memory second): ✔ plan-time only, no hot-path work; positive on Q10 (16× recovered) and the dblp star (2.4×); residual plan-flip risk on many-probe star + object→subject hash-join chains is real but bounded and unmeasured — no bench covers Q10 or that shape.
  • Testing: ✔ unit pins for both fixes that go red under the reverse mutation; the two touched integration tests run in real targets (it_fastpath_1652_regression is its own [[test]]; it_join_batched_overlay is wired via grp_misc) and pass at HEAD; the full stack passed the one real CI run this head got. ⚠️ the membership lane's list-rows answer at ≥256 driving rows is no longer pinned anywhere.
  • Conventions: ✔ four well-factored, multi-line commit messages; clippy -D warnings and fmt clean at package scope; the two new repo-memory facts are accurate and under the 750-char cap.

Verified locally at branch HEAD (f41e33b2b): cargo nextest run -p fluree-db-query 1470/1470; mutation A (restore .ceil()) → 1 red, mutation B (drop the step_est fallback) → 1 red; it_fastpath_1652_regression and grp_misc probe_helpers_merge_novelty green at HEAD, 1652 red on main + this PR alone; cargo fmt --check and cargo clippy -p fluree-db-query --all-targets -- -D warnings clean.

Approving so you can merge when ready (after #1676), but maybe worth considering the step_est-first ordering and the comment wording before this lands.

// is what the hash-join gate below is costed against. Scans and
// nested loops report `None`, and reading that as "large" built
// a whole-predicate hash set for ~20 driving rows (BSBM Q10).
let driving_rows = left

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 (pre-existing ordering, not introduced here). This is more of a question than a suggestion. The comment says the fallback is "the planner's running chain estimate, which is what the hash-join gate below is costed against" — but because left.estimated_rows() is consulted first, the planner only gets a say when the operator has nothing. NestedLoopJoinOperator::estimated_rows is left × 10 (join.rs:1520), so once a VALUES or subquery seeds a chain, every subsequent probe's gate reads the ×10-per-hop heuristic rather than step_est. I probed it at HEAD: VALUES ?a { 30 rows } . ?a :knows ?b . ?b :knows ?a with a 100k :knows extension — at the second probe left.estimated_rows() = Some(300), step_est() = 30.0, and MembershipJoinOperator fires, i.e. the lane drains 100k rows for what the planner (and EXPLAIN's driving-est) says is 30 driving rows, under the 256 floor. Your code didn't introduce this — the same Some(300) reached the gate before — but since this PR is the one making the gate and EXPLAIN agree, I wonder if we want step_est first and the operator estimate as the fallback. I don't think anything is lost for VALUES/subquery producers, since with_left_estimate already folds their estimate into step_est (I checked EmptyOperator returns Some(1) so a leading VALUES does seed it). Something like:

                let driving_rows = hash_planner
                    .step_est()
                    .map(|e| e.round().max(1.0) as usize)
                    .or_else(|| left.estimated_rows());

The magnitude is bounded either way (≤250k drain vs a few dozen reopens), so this is 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.

Addressed in fcd594a — flipped to step_est first, operator estimate as the fallback, exactly as you wrote it.

Your reasoning checks out and I went looking for a reason not to. Two things settled it: with_left_estimate does fold producer estimates into driving_est, so nothing is lost for VALUES/subqueries; and after this PR step_est is already the load-bearing input for the majority of chains anyway, since scans report None — so preferring it isn't a new dependency, just an existing one extended to producer-seeded chains.

The one asymmetry worth naming, since it isn't symmetric the way the bounded-magnitude argument suggests: ×10^n over-estimating means over-admission, capped by the 250k build ceiling, while step_est under-estimating means declining and taking unbounded per-row reopens — the pathology the lane exists to prevent. It's the same exposure every no-estimate chain already has, so I don't think it argues against the change, but it's why I added a test rather than just flipping the two lines.

New test is your probe: VALUES ?a { 30 rows } . ?a :knows ?b . ?b :knows ?a over a 100k :knows, built through build_scan_or_join. Restoring the old ordering fails it with your exact finding — MembershipJoinOperator at 30 planner-estimated driving rows. The other six membership_lane_* tests pass under both orderings, so the flip doesn't disturb the Q10 pins.

@@ -201,7 +209,6 @@ pub(crate) fn estimate_triple_row_count(
if let Some(prop) = property_stats(s, &pattern.p) {
if prop.ndv_subjects > 0 {
return (prop.count as f64 / prop.ndv_subjects as f64)

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 / question. I'm not raising this as a concern with the fix — fractional-with-a-floor is clearly the right estimate — just noting the residual so it's written down. Dropping ceil shrinks every multi-hop chain estimate that used to be inflated: five ~1.0-per-subject star probes read as 32× before and ~1× now. The object→subject hash-join gate's HASH_JOIN_MAX_SCAN_RATIO = 1024 (hash_join.rs:143, applied at :463) was tuned against those inflated drives, so a downstream object→subject probe that cleared the cap by less than that factor could now land on ScanRatioTooHigh and take the nested loop. BSBM 1M being flat across Q1–Q12 is reassuring for the shapes we bench; dblp's own star shapes are exactly the ones that would show it, so I'd second the benchmark-box run you already propose — and fwiw, no bench here covers Q10 or a many-probe star (query_hot_bsbm is Q3/Q5/Q9 only, and the per-PR bench-compare "+45–94% advisory" lines on this run are host-class mismatch, not this change).

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.

Noted and left alone — agreed the fix is right and this is a residual to have written down rather than something to change.

On the benchmark-box run: we've decided against re-running dblp for this. The BSBM 1M evidence across Q1–Q12 stands, and re-measuring dblp is a large amount of machine time for a risk that is bounded and, as you say, unmeasured either way. Recording the reasoning here so the decision is visible rather than silent — if a many-probe star does flip to ScanRatioTooHigh later, this thread is the pointer to HASH_JOIN_MAX_SCAN_RATIO being tuned against the pre-ceil-removal numbers.

// each side pair up 2×2 = 4, s3 pairs its single shared `r-1` once,
// and s1 never matches (see the fixture). The count lane cannot
// express that in an (s, o_type, o_key) key, so it must decline and
// agree with the generic join. (The membership lane used to answer

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. The new comment reads the bag-join count as "what a var-object join over list elements means", while #1676's "Not in this PR" explicitly defers whether list position is part of a literal's identity as an unsettled semantics call. Since after this PR the membership lane's semi-join answer on list rows isn't pinned anywhere (the fixture is now below the 256-row gate, and there's no ≥256-row list fixture), I'd soften the comment to "what the generic join yields today" so the pin doesn't read as the ruling when the ruling is still open. Minor and non-blocking — if you agree, I'd rather see the wording folded in here than have the next reader take the pin as settled.

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.

Addressed in fcd594a — you're right, and the second half of your note was the more interesting half.

Reworded so the case reads as what the generic pipeline yields today rather than as the ruling, with the open question named and pointed at #1676.

For the coverage gap you flagged in the review body — the lane's list-rows answer at or above the gate now being unpinned — I filed #1687 rather than adding a fixture. Adding one now would pin either 5 or 3 as correct before the semantics call is made, which is the same reason the comment needed softening. The issue sequences it: settle the identity question first, then pin the lane to whatever the generic pipeline answers (or make it decline on list rows, if they're meant to agree).

Also worth recording here: your merge-order constraint is resolved — #1676 is merged, and this branch now has origin/main merged in. That mattered for a reason beyond staleness: these four commits sat on #1676's pre-review tip, so they were missing the two commits added during that review, one of which rewrote the EncodedLit arm in join.rs — the same literal-object lane this gate admits or declines. I re-ran the shared targets after the merge: 1652 regression, it_literal_identity, grp_misc probe_helpers_merge_novelty, it_query_explain, it_exists_semijoin_correlation, it_cyclic_bgp_probe all green, and fluree-db-query 1509/1509.

/// estimate read both as 2 and kept source order, putting the 127M-row
/// predicate second (2.4x slower); the fractional fan-out orders them.
#[test]
fn star_join_fractional_fanout_orders_near_tied_bound_subject_probes() {

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.

Pinning the dblp shape with both releases' ndv_subjects (the v4.1.2 one sitting above the flake count) is exactly the right test: it proves the order no longer depends on which side of the integer the sketch lands, not just that one set of numbers happens to sort. Restoring .ceil() fails precisely this test and nothing else.

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.

Thanks — that was the intent exactly, and it's the part of the diagnosis I'd have been least confident about without pinning both sketches.

/// so the gate used to read the driving side as unbounded and drain the whole
/// `dc:publisher` extension to answer ~20 offers. The planner's running
/// chain estimate (≈20 here) must stand in, keeping the nested loop.
fn bsbm_q10_prefix(product_ndv: u64) -> BoxedOperator {

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.

Building the real Q10 prefix through build_scan_or_join with with_left_estimate(None) and pinning both sides of the floor (≈20 → NLJ, 5,570 → membership) is the test I'd have asked for; dropping the .or_else fails the first and leaves the second green, so the pair genuinely brackets the gate.

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.

Appreciated — bracketing it from both sides was the only way I could convince myself the floor was in the right place rather than just that the symptom went away.

Base automatically changed from fix/literal-identity-lang-and-list-position to main August 25, 2026 20:41
…n's fan-out

The small-driving-side gate consulted `left.estimated_rows()` first and fell
back to the planner only when the operator had nothing. Because
`NestedLoopJoinOperator` reports `left × 10` per hop and propagates `Some`,
one VALUES or subquery at the head of a chain meant every later probe was
weighed against a compounding heuristic instead of the statistics:
`VALUES ?a { 30 rows } . ?a :knows ?b . ?b :knows ?a` reaches the second
probe with an operator estimate of 300, clears the 256 floor, and drains a
100k `:knows` extension to answer 30 driving rows — while EXPLAIN reports
`driving-est` 30 for the same step.

Consult `step_est` first, keeping the operator estimate as the fallback for
ledgers without statistics. Nothing is lost for producers: `with_left_estimate`
already folds their estimate into the running chain estimate, so a leading
VALUES still seeds it. This finishes what the previous commit started — the
gate and the number EXPLAIN reports for it are now the same number in every
case, not just when the operator declines to guess.

Also softens the list-rows pin in `it_fastpath_1652_regression`: it records
what the generic pipeline yields today, not a ruling on whether list position
belongs to a literal's identity, which is still open. The membership lane's
own answer on that shape is unpinned above the gate — see #1687.
@bplatz
bplatz merged commit 3f56a6c into main Aug 25, 2026
14 checks passed
@bplatz
bplatz deleted the fix/planner-fanout-and-membership-gate branch August 25, 2026 20:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants