Repository navigation
perf: fold a one-row VALUES into its object and cost nested UNION honestly - #1659
Conversation
… honestly
Two independent planner defects made a bound-subject claim lookup ~500x
slower than the same query with the IRI written inline.
A VALUES binding a leaf object var was deferred above the star, so
PropertyJoinOperator drove off whatever else was bound and drained that
predicate's whole extent before the one-row VALUES filtered it. The plan
read Project -> Values -> PropertyJoin. A one-row VALUES *is* a constant,
so inline_singleton_values_objects folds it into the object position of
same-list triples and keeps the VALUES pattern, leaving the variable bound
for projection and FILTERs. Gated to one row, reference cells, object
position, a single pattern list, and only ahead of MINUS/EXISTS/NOT EXISTS
-- reorder_patterns orders those on the variables their predecessors
produce, so a trailing VALUES would shrink that set and let the anti-join
float ahead of the binding that correlates it.
estimate_branch_cardinality scaled every triple-free branch by the
unknown-property-scan default. A chained {A} UNION {B} UNION {C} parses as
Union([[Union([[A],[B]])],[C]]), so the outer branch owns no triples and a
30-row union costed 20,000,010 -- placed behind every real scan. Since
UnionOperator is correlated (it rebuilds and re-runs each branch per input
row) that misplacement is superlinear. A branch whose non-triple members
report sized Sources now costs those; the default still applies when only
Expander/Deferred patterns are present.
Measured on a 200k-claim ledger (values_object_scan_probe), row counts
unchanged throughout:
VALUES + dimension 54.3ms -> 0.0ms
VALUES + 4 more predicates 239.3ms -> 0.1ms
VALUES + 4 preds + 2 OPTIONAL 147.7ms -> 0.1ms
broad triple, then 3-way UNION 8.2s -> 0.1ms
200k-row triple, then 3-way UNION 53.0s -> 0.1ms
Multi-row VALUES on an object var is unchanged (~92ms): seeding it is a
cost decision, and blanket seeding regressed a 21k-row Cypher UNWIND
before.
batched_object_join_merges_novelty asserted the batched-object lane for a
one-row VALUES, which now folds to a constant scan; it gets a two-row
VALUES to keep exercising the lane, plus the folded form as a third case so
the @list retraction fate check covers both plans.
aaj3f
left a comment
There was a problem hiding this comment.
This is great, @bplatz
I verified the order-preservation argument end-to-end (reorder_patterns builds anti-join required_vars from preceding produced_vars, and the retained VALUES keeps producing the folded var), ran the full fluree-db-query suite (1412 green, all 8 new unit tests present by name), the SPARQL values integration tests (31 green incl. the 9 new ones), the JSON-LD grp_query suite for shared-IR parity (422 green), and the probe — VALUES-vs-inlined pairs match in rows and time, and the chained-UNION-after-200k-scan case runs in single-digit ms dev-profile.
The two inline notes (pinning the FILTER/BNODE coupling with a test, and a question about SERVICE branches under the new sized-source costing) are both optional, but if you agree on them, would rather fold them in here rather than as follow-ups.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Extends the existing pre-planning-rewrite mechanism (sits beside
elide_redundant_type_filters), reuses the constant-object scan path rather than adding a lane; shared-IR, so JSON-LD inherits the win for free. - Performance (speed first, memory second): ✔ Query-planner hot path, strictly positive: plan-build-time O(patterns) pass, no per-row work; measured 54ms/240ms/8.2s/53s → ≤0.1ms with row counts unchanged; multi-row VALUES deliberately untouched.
- Testing: ✔ 8 unit + 9 integration tests, all wired into live grp targets and confirmed running by name; batched-overlay lane coverage preserved; CI ran the full gauntlet including the W3C suite (test/clippy/fmt/testsuite-sparql all pass), which covers the PR body's honest caveat about the final region rewrite not being locally re-run against the full workspace.
- Conventions: ✔ Thorough multi-line commit body, self-describing title, fmt/clippy clean against the denied-lint set,
docs/design/performance.mdupdated with the new "Pre-planning rewrites" section.
Verified locally at branch HEAD (a8e7d797f): cargo test -p fluree-db-query 1412/1412 · grp_query_sparql values 31/31 · grp_misc batched 4/4 · grp_query 422/422 · probe reproduces all claimed shapes · fmt --check + clippy --all-targets -- -D warnings clean.
Approving so you can merge when ready — the two optional notes are cheap insurance additions
| } | ||
| } | ||
|
|
||
| let is_inner_join_member = |p: &Pattern| { |
There was a problem hiding this comment.
Praise. The region-boundary design is the right shape of gate: deriving soundness from "compound patterns are not inner-join members" means the fold can't straddle a MINUS/EXISTS/subquery by construction, rather than by a list of special cases that would rot. The doc comment explaining why each relaxation is deliberately not taken is exactly what the next person needs.
| p, | ||
| Pattern::Triple(_) | Pattern::Values { .. } | Pattern::Bind { .. } | Pattern::Filter(_) | ||
| ) | ||
| }; |
There was a problem hiding this comment.
Optional. The "Note for reviewers" coupling you called out (variable-free FILTER and BIND(BNODE(..)) are order-sensitive in reorder_patterns but inner-join members here, so folding can shrink their preceding-produced set) is real, and I agree it's benign today — a variable-free FILTER is row-independent, and the retained one-row VALUES removes no rows.
But nothing pins it: if someone adds a third order-sensitive Deferred classification at planner.rs:1398-1402 that IS an inner-join member, the fold silently starts shrinking its ordering set with no test going red. A cheap insurance move would be a unit test asserting the fold still fires with a variable-free FILTER in the region (documenting the coupling as intended), plus a one-line cross-reference comment at planner.rs:1398 pointing back at is_inner_join_member.
There was a problem hiding this comment.
Agreed, and folded in as 219c39388.
fold_survives_a_variable_free_filter_in_its_region asserts the fold still fires with FILTER(true) in the region, and — the part that seemed more worth pinning than "it still folds" — that both the VALUES and the FILTER survive the rewrite. The retained VALUES is the actual reason the coupling is benign, since it goes on producing the variable the ordering set is built from, so that is the invariant a future change would break.
Also added the cross-reference you suggested at planner.rs, and a matching one on is_inner_join_member pointing back, so whichever site someone edits first leads to the other.
| // rebuilt and re-ran all three branches once per driving row. | ||
| // | ||
| // With no sized source (only OPTIONAL/MINUS/FILTER/BIND) nothing is known, | ||
| // so the unknown-scan default still applies. |
There was a problem hiding this comment.
Optional, more of a question than a suggestion. With has_sized_source, a triple-free branch whose only sized member is a Service (or a Graph wrapper) is now costed at DEFAULT_SERVICE_ROW_COUNT (or the recursive estimate) instead of that × the 20M unknown-scan default — so a SERVICE-bearing union can now be placed much earlier.
I think that's the safe direction given UnionOperator is correlated (earlier placement means fewer driving rows and fewer branch re-runs), and the estimate is more honest either way, but it did widen the change beyond the nested-UNION shape in the PR title. If you've thought about the SERVICE case and are comfortable, no action needed.
There was a problem hiding this comment.
Good catch, and digging into it I think the answer is narrower than "is earlier placement safe" — Service should not have been satisfying has_sized_source at all. Fixed in 219c39388.
DEFAULT_SERVICE_ROW_COUNT is FULL_SCAN, and its own doc comment says that value is chosen "high to place them late since they involve network calls to remote endpoints" — so it is a placement sentinel, not an estimate of what the endpoint returns. has_sized_source means "this branch knows its own cardinality, do not invent rows on top of it", which is exactly what SERVICE does not know. Counting it read "unknown, and expensive" as "known to be big".
So the widening you spotted was unintended rather than a deliberate call I had thought through. Pattern::Service no longer sets the flag, which keeps the documented late placement exact. The nested-UNION shape this PR is actually about is unaffected — those branches are sized by Union/Values/Subquery estimates, which are real recursive counts, and there is now a test for that shape alongside the SERVICE one plus a case showing the exclusion is SERVICE-specific (a sized member next to a SERVICE still sizes the branch).
Both new planner tests were checked against the unfixed code first and do go red, so they are not passing vacuously.
Since this is a behaviour change you raised as a question rather than asked for, worth a look before merge.
| 2, // (bob, b3 injected) + (grace novelty-only, b4 injected); | ||
| // b2 retracted, b1/d1 authors not known by alice | ||
| // b2 retracted, b1/d1 authors not known by alice | ||
| true, |
There was a problem hiding this comment.
Praise. Reworking batched_object_join_merges_novelty to a two-row VALUES so the batched-object lane stays exercised, and adding the folded form as a third case so the @list retraction fate check covers both plans, is exactly the "don't lose the lane under the optimization" discipline that keeps these tests meaningful.
…known default Both from review of the one-row VALUES fold. The fold's region gate counts FILTER and BIND as inner-join members, while `reorder_patterns` treats two of their shapes — a variable-free FILTER and a `BIND(BNODE(..))` — as order-sensitive, ordering them against everything their predecessors produce. Folding across them is safe today for a reason that was written down in the PR but pinned nowhere: the rewrite replaces triple objects only and keeps every pattern, so the retained one-row VALUES goes on producing its variable and no preceding-produced set shrinks. A third order-sensitive classification that was also an inner-join member would break that silently. A unit test now asserts the fold still fires across a variable-free FILTER and that both the VALUES and the FILTER survive the rewrite, and the two sites carry comments pointing at each other. `has_sized_source` let any `PatternEstimate::Source` mean "this branch knows its own cardinality, so do not multiply in the unknown-scan default". SERVICE is the one Source for which that is false: `DEFAULT_SERVICE_ROW_COUNT` is `FULL_SCAN`, chosen — as its own doc comment says — to sort remote calls last, so it is a placement sentinel rather than knowledge of what the endpoint returns. Counting it read "unknown, and expensive" as "known to be big", which let a triple-free SERVICE branch skip the default and sort ahead of local work in a tie. It no longer sets the flag. The nested-UNION shape the fold's companion fix targets is unaffected: those branches are sized by Union, Values and Subquery estimates, which are real recursive counts. Both new planner tests were confirmed to fail against the unfixed code rather than passing vacuously.
Two independent planner defects, reported together: a bound-subject claim
lookup ran ~500x slower than the identical query with the IRI written inline,
and UNION-ing three inlined IRIs instead timed out at the gateway.
Both reproduce on a synthetic 200k-claim ledger — see the added
values_object_scan_probeexample.A VALUES binding a leaf object var never reached the scan
split_values_seeding_staronly seeds a VALUES that binds the star'ssubject; everything else defers, and
build_property_join_blockdefersunconditionally. So
PropertyJoinOperatordrove off whatever else was bound,drained that predicate's whole extent, and only then let the one-row VALUES
filter it. Explain showed it plainly:
Project -> Values -> PropertyJoin.That deferral was deliberate — seeding a leaf-object VALUES costs the star
fusion. The fix isn't to seed it: a one-row VALUES is a constant, so
inline_singleton_values_objectsfolds it into the object position ofsame-list triples and keeps the VALUES pattern, leaving the variable bound for
projection and FILTERs.
Gated to one row, reference cells, object position, and a single contiguous
inner-join region. The region boundary is what makes it sound: compound
patterns are not inner-join members, so no region straddles a
MINUS/EXISTS/NOT EXISTS. A folded triple's donor VALUES is therefore always on
the same side of every order-sensitive boundary, which leaves those patterns'
order-preservation sets (built from preceding
produced_vars) unchanged —and covers
subquery_correlation_vars, which reads the same thing. Withoutthat gate a trailing VALUES could shrink the set and let an anti-join float
ahead of the binding that correlates it, degenerating into a disjoint-domain
no-op.
Chained UNION was costed 1e6x too high
{A} UNION {B} UNION {C}parses asUnion([[Union([[A],[B]])],[C]]), so theouter branch holding the inner UNION owns no triples of its own.
estimate_branch_cardinalityscaled every triple-free branch by theunknown-property-scan default, so a 30-row union costed 20,000,010 against
a 20,000-row triple and was placed behind every real scan. A 4-way union
compounds to 1e12.
That misplacement is superlinear because
UnionOperatoris correlated — itrebuilds and re-runs each branch once per input row. A branch whose non-triple
members report sized
Sourceestimates now costs those; the default stillapplies when only Expander/Deferred patterns (OPTIONAL/MINUS/FILTER/BIND) are
present, where nothing is known.
Measured
200k claims, 20k subjects. Row counts identical before and after in every case.
VALUES ?sub+ dimensionVALUES ?sub+ 4 more predicatesVALUES+ 4 preds + 2 OPTIONALDeliberately not covered
genuine cost decision, and blanket seeding regressed a 21k-row Cypher UNWIND
previously. It needs a stats-driven gate, not a threshold guess.
UnionOperatorre-planning per input row. The estimator fix keeps unionsearly, which is where the 53 s came from, but a union that legitimately runs
second still rebuilds its operator tree per driving row.
Note for reviewers
Two patterns are classified order-sensitive in
reorder_patterns(planner.rs:1398-1402) but are inner-join members, so they do not break a
region: a variable-free FILTER and
BIND(BNODE(..)). Folding can shrink theirpreceding-produced-vars set. It is benign today — a variable-free filter is
row-independent, and the retained one-row VALUES removes no rows, so both see
an identical solution set either way — but it is a coupling across two files
worth knowing about if another order-sensitive classification is ever added.
batched_object_join_merges_noveltyasserted the batched-object lane for aone-row VALUES, which now folds to a constant scan. It gets a two-row VALUES to
keep exercising the lane, plus the folded form as a third case so the
@listretraction fate check covers both plans.
Validation
fmt --checkandclippy --all --all-features --all-targetsclean;fluree-db-query1501/1501,grp_query_sparql349/349, batched-overlay green.The full workspace suite (11,140) and the W3C SPARQL suite (36 suites, 0
failures) last ran green immediately before the final region rewrite of
inline_singleton_values_objectsand have not been re-run locally since —leaving that to CI.