Repository navigation
perf(query): let LIMIT stop property joins and OPTIONAL early - #1936
Conversation
- PropertyJoinOperator reads a bound-object anchor a chunk of subjects at a time (1,024 at first, growing eightfold to 100,000) and hands each chunk's rows over before reading the next, so an outer LIMIT stops the work. The chunks ramp without a row budget, so DISTINCT ... LIMIT stops too. Historical reads, range anchors, and stars with a predicate that needs a full scan keep the single pass. Rows and their order are unchanged. - The SPOT star walk skips leaflets whose directory keys hold none of the probed subjects, so adjacent chunks don't reread each other's leaflets. - OPTIONAL sizes its first coalesced seed to the LIMIT budget and copies only those rows out of the scan batch. - FlushSchedule sizes the batches for all three lanes; the nested-loop join keeps its previous behavior.
…gestion - LeafScan::load_leaflet loads one leaflet, through the leaflet cache when the store has one, and replays it on a historical read. The four batched walks in join.rs and the range semijoin each repeated that sequence. - Injected-bound checks, probe object bindings, and probe filters decode novelty-minted ids through one helper. - OPTIONAL's two identical subject-id lookups become one function. - Property join ingests SPOT-walk and PSOT-probe matches through one helper that looks the subject up by id; the probe lanes only run over chunks whose keys are all ids. - OPTIONAL builds its coalesced seed with Batch::from_parts, which keeps a zero-column batch's row count. No behavior change.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is obviously excellent (just from the numbers themselves) though the behavior on main surprised me slightly. I even dug into this because I was fairly certain I'd seen these kinds of scan loop improvements before in fluree-db-query/src/join.rs. Then I realized that was only setting chunk size, not the early termination on LIMIT etc. I also then was surprised (but satisfied) that the work of this PR deliberately didn't hinge its gathering/draining ramp on the row budget itself, given issues that would have involved with, say, DISTINCT etc. Anyway, it's a neat design. No headline notes from me. Full review is below but I think most of Claude's concerns have more to do w/ the CI not having run (until it targets main), which seems quite obvious to me:
"The operator can't produce its first row until it has produced all of them" is the worst shape a query engine can have, and the fix is the one I'd have reached for: chunk the gather geometrically so a small LIMIT is satisfied from the first window and a full drain pays only a few extra flushes. What raises it further is that the ramp is deliberately decoupled from the row budget — DISTINCT correctly swallows the budget, so a design that keyed chunking off it would have missed the single most common shape a user types, and FlushSchedule::ramped covers it for free. LeafScan::load_leaflet and FlushSchedule are both the generalize-the-shared-mechanism move rather than a fourth parallel policy, and chunked_rows_match_the_full_drain is a properly-built differential test — I mutation-checked it and a one-subject chunk-boundary loss turns it red.
I went looking hard for the case where an early exit changes an answer and I didn't find one. The important thing is that the row budget never truncates in the property join — it only sizes the first chunk, and chunks keep growing until the driver is exhausted — so ORDER BY / DISTINCT / GROUP BY / OFFSET are safe even before you get to the fact that all four explicitly swallow the budget with a written rationale, and offset.rs:154 adds the offset before forwarding. The OPTIONAL seed doesn't truncate either; it cuts an oversized batch and replays the remainder. And the chunker's one real hazard — a driver row adding an object to a subject whose value vectors were already cleared — is closed by streamable requiring a bound-object driver, which forces emit_object = false. The full walk is in the summary file.
So what I'm holding on is the two things that haven't happened rather than anything that's wrong. First, this head has no CI at all: check-runs for 6828a9cff returns 8 entries — plan plus seven skipped release jobs — where #1933's head returns 16 with the full suite green. The part that decided it for me is that #1923 also returns 16, and #1923 is stacked too (base feat/sparql-update-graph-var). Same repo, same week, same workflow file, one stacked PR gets the whole suite and this one gets nothing — so we can't treat "it's stacked" as the explanation and move on. Concretely it means 328 lines of new tests, testsuite-sparql, and grp_query_history (which holds the only coverage of your new !needs_history_replay gate) have never executed against this code. Land #1933, retarget this to main, let CI run. Second, your own body says the full-drain star walk goes 20 → 23 leaflets and calls the effect "within run-to-run noise (±5% on this machine)" — but query_hot_fanout_star and query_hot_optional are both budgeted at 3% at medium in regression-budget.json, so the noise floor is wider than the thing we gate on, and since db#1802 there's no bench job in ci.yml to catch it downstream. Neither branch in this stack has a bench.yml dispatch on it; gh workflow run bench.yml --ref perf/property-join-streaming -f compare_only=true would settle it. I deliberately didn't produce a number myself — this machine was running a dozen parallel jobs and a prior sweep of ours recorded a fake 4× regression from exactly that, so anything I measured would have been noise dressed up as evidence.
Adherence to repo commitments:
- Patterns/abstractions: ✔
FlushScheduleandLeafScan::load_leafletboth consolidate rather than add a parallel construct, and the three decode helpers become onedecode_overlay_object. Verified the consolidations are behaviour-identical. - Performance (speed first, memory second):
⚠️ Direction is right and theLIMITwins are large, memory is better (emitted chunks free their value vectors). But the acknowledged 20→23 leaflet cost on the full-drain star sits inside an author-machine noise estimate wider than the 3% bench budget, with no in-repo bench run on either layer of the stack. Not a regression I can demonstrate — an unmeasured one I'd like measured. - Testing:
⚠️ The new suite is genuinely good and both my mutations went red for the right reasons — but no CI job has ever run it, and the historical-read gate on the leaflet skip has no test that names it. - Conventions: ✔ Two well-split commits with substantive bodies, the second correctly claiming "No behavior change" (I checked it).
docs/design/performance.mdupdated for the newPropertyJoinOperatorbehaviour.cargo fmt --checkand a scopedclippy -D warningsare clean locally. The "Not in this PR" section namingUNION,GRAPHand the unbudgeted nested-loop join is exactly the kind of scoping note that saves the next reader an afternoon.
Verified locally at 6828a9cff: grp_query_sparql 393 passed (all five new it_limit_stops_work tests by name), grp_query + grp_query_history 536 passed including time_travel_property_join_spot_walk_respects_t, cargo fmt --all -- --check clean, cargo clippy -p fluree-db-query -p fluree-db-api --all-targets -- -D warnings clean; two mutations (streaming disabled; chunk end off by one) both red for the expected tests and both restored with the worktree left clean.
Requesting changes only so this doesn't merge without a CI run of its own — land #1933, retarget to main, and if the bench comparison comes back flat I'm a happy approve on the next pass.
Not anchorable inline:
Blocking — this PR's head has never been built by CI, and the comparison is what makes that worth acting on. gh api repos/fluree/db/commits/6828a9cff45108d43f8602571c07cee0e2ffa8b6/check-runs returns 8 entries: plan, plus announce, host, build-global-artifacts, build-local-artifacts, publish-aur, publish-docker and publish-homebrew-formula, all skipped. There is no fmt, no clippy, no test, no testsuite-sparql, no sql-bridge, no wasm32 on this SHA at all. actions/runs?head_sha=… confirms it: one run, Release.
The same query on #1933's head (77c7dc8b8) returns 16, with fmt, clippy, test, testsuite-sparql, sql-bridge, wasm32, wasm-smoke and workflow-lint all green. And so does #1923's head (161f8cc3b) — which is also a stacked PR, based on feat/sparql-update-graph-var rather than main. Same repo, same week, same ci.yml, one stacked PR gets the whole suite and this one gets nothing. So "it's stacked, that's just how it is" isn't an explanation any of us can lean on, and a green-looking checks tab on a stacked db PR tells you nothing until you count the runs.
What it costs here specifically: it_limit_stops_work is 328 new lines and has never run in CI; testsuite-sparql has never run against a change that alters which rows come back under LIMIT; and grp_query_history — which holds time_travel_property_join_spot_walk_respects_t, the only coverage of the !needs_history_replay gate on the new leaflet skip — has never run either. Nothing has run --all-features.
The fix is just sequencing: land #1933, retarget this to main, and let CI run before merging. I ran what I could locally and it's all green — grp_query_sparql 393 passed with the five new tests by name, grp_query + grp_query_history 536 passed, cargo fmt --all -- --check clean, cargo clippy -p fluree-db-query -p fluree-db-api --all-targets -- -D warnings clean — but that's 3 targets out of ~10 and not --all-features, so please don't take my run as a substitute for the real one.
| a bound object or a range filter (`?s a :Person ; :name ?n ; :email ?e`) instead | ||
| of a join chain. One scan of the anchor seeds the subjects; the other predicates | ||
| are looked up for just those subjects, by batched PSOT probes or a single SPOT | ||
| walk. On a current-state read, a bound-object anchor is read a chunk of subjects |
There was a problem hiding this comment.
Blocking-adjacent — the full-drain cost of chunking is acknowledged in the PR body and measured only against a noise floor wider than the budget we gate on. (Real locations: fluree-db-api/benches/query_hot_fanout_star.rs and regression-budget.json.)
This paragraph now documents the chunking, and the PR body documents its price: on a 100,000-subject full star the walk reads 20 leaflets in a single pass, 50 when chunked, and 23 when chunked with the new directory-key skip. That's a ~15% increase in leaflet reads on the product's headline star path, covered by the sentence "within run-to-run noise (about ±5% on this machine)."
A ±5% noise floor can't resolve the budget the repo actually gates on: regression-budget.json sets 3% at medium for query_hot_fanout_star and query_hot_optional — the two benches that exist precisely to measure the shapes this PR changes. And since db#1802 there's no bench job in ci.yml at all, so nothing catches it downstream either. Neither branch in this stack has a bench.yml dispatch on it.
Could we run gh workflow run bench.yml --ref perf/property-join-streaming -f compare_only=true before this merges? You dispatched it on perf/rdf12-annotation-chain-planning on 2026-09-15, so I know the gesture works. Heads-up that the nightly on main has failed on 09-21, 09-23, 09-24 and 09-25, so the baseline may want a look first.
I didn't produce a number myself on purpose — the machine I reviewed on was running a dozen parallel jobs, and a prior sweep of ours recorded a fake 4× regression from exactly that, so anything I measured would have been noise dressed up as evidence. I'd rather have the real number than either of our estimates, because this is the one change in the PR that could plausibly make the common case slower.
Commenting here because fluree-db-api/benches/query_hot_fanout_star.rs and regression-budget.json are not in this diff.
|
|
||
| let mut driver = self.predicate_scan(ctx, driver_idx); | ||
| driver.open(ctx).await?; | ||
| self.driver = Some(driver); |
There was a problem hiding this comment.
Optional — open() now assigns self.driver without closing whatever was there before.
close() does the right thing (property_join.rs:1481-1483), so the only exposure is an open() without an intervening close(), which I looked for and didn't find a caller doing.
Still, this is the first time the operator holds an open child across its own open(), and every other piece of state in that function is explicitly reset a few lines earlier. Adding
if let Some(mut d) = self.driver.take() {
d.close();
}at the top would make the reset block complete, and it costs three lines.
Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
|
|
||
| enum PredicateLane { | ||
| /// Batched PSOT probe over the chunk's subjects. | ||
| Probe { |
There was a problem hiding this comment.
Optional — the invariant that licenses sharing a reconciler lost the comment that carried it.
The old code said it right where it mattered: "One reconciler per predicate, shared across its chunks: chunked subject sets are disjoint, so consumed-state never collides." That comment went out with the code it annotated, and ProbeOps now lives here in PredicateLane::Probe and is shared across driver chunks as well as probe sub-chunks.
The invariant still holds — each subject lands in exactly one driver chunk, so a reconciler can't be asked about the same subject twice — and novelty_in_later_chunks_matches_the_reindexed_ledger proves the behaviour. But it's now a wider claim resting on an unwritten property of the chunker, and the next person to touch fill_chunk has nothing telling them what they'd be breaking.
Worth restating on the Probe variant.
| None => batch, | ||
| // Without replay the directory keys bound the leaflet's rows, so a | ||
| // leaflet holding none of the probed subjects is skipped unread. | ||
| if !needs_history_replay { |
There was a problem hiding this comment.
Optional — this is the one line in the leaflet skip doing correctness work rather than optimization, and I couldn't find a test that would go red if it were deleted.
The comment above it explains the why well: replayed rows can fall outside the directory keys, so the skip can only be trusted on a current-state read. Everything in it_limit_stops_work is current-state, so none of the new tests exercise it. The coverage that does exist — it_query_time_travel_bgp::time_travel_property_join_spot_walk_respects_t — predates this PR, targets the at_latest_t gate rather than this one, and lives in grp_query_history, which CI has never run on this head.
I didn't mutation-check it: it needs a leaflet whose probed subject appears only in the history sidecar, which I couldn't construct cheaply.
Would it be worth a case in it_limit_stops_work that drives the star walk at a historical t over a ledger with retractions, so the gate has a test that names it? Same question for the !replay conjunct at property_join.rs:1379, though that one's rationale is performance rather than correctness, so it matters less.
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn chunked_rows_match_the_full_drain() { |
There was a problem hiding this comment.
Praise — this is the test this class of change needs, and it's built right.
Four LIMIT/OFFSET windows, each of which starts the join over with a different first chunk, asserted positionally against the full drain rather than as a sorted bag. That's what makes it a differential test and not just a row-count check.
I mutation-checked it. Changing self.chunk = chunk_start..self.subject_values.len() to ….saturating_sub(1) — dropping the last subject of every chunk, which is exactly the off-by-one this design has to rule out — turns this test red along with driver_revisiting_a_subject_joins_it_once and novelty_in_later_chunks_matches_the_reindexed_ledger. And disabling streaming entirely turns only limit_stops_the_driver_after_one_chunk red while leaving the four content tests green, which is the correct split: chunking must change when rows arrive, never which ones.
| pub(crate) const FLUSH_GROWTH: usize = 8; | ||
|
|
||
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| pub(crate) struct FlushSchedule { |
There was a problem hiding this comment.
Praise — three ad-hoc window-sizing policies become one tested type.
The nested-loop join's MIN_ADAPTIVE_FLUSH / ADAPTIVE_FLUSH_GROWTH / row_budget: Option / mutable-threshold quartet, OPTIONAL's fixed cap, and the new property-join chunker all collapse onto fixed / ramped / budgeted.
I checked the nested-loop conversion is byte-for-byte the same policy — fixed(cap).advance() is a no-op because size is already cap, and budgeted(b, BATCHED_JOIN_SIZE) computes b.clamp(MIN_FLUSH.min(cap), cap), which is exactly the old b.clamp(MIN_ADAPTIVE_FLUSH, BATCHED_JOIN_SIZE) since MIN_FLUSH == MIN_ADAPTIVE_FLUSH == 1024. That equivalence is the part that's easy to get subtly wrong in a refactor like this, and the four unit tests below pin the ramp for whoever changes it next.
| && !replay; | ||
| self.chunk_schedule = streamable.then(|| match self.row_budget { | ||
| Some(budget) => FlushSchedule::budgeted(budget, BATCHED_JOIN_SIZE), | ||
| None => FlushSchedule::ramped(BATCHED_JOIN_SIZE), |
There was a problem hiding this comment.
Praise — ramping the chunk schedule independently of the row budget is the detail that makes this work.
DistinctOperator::set_row_budget (distinct.rs:100) correctly swallows the budget, since dedup can collapse arbitrarily many rows into one. So a design that keyed chunking off the budget would have left SELECT DISTINCT ?n … LIMIT 1 — arguably the most common shape a user actually types — still paying for the full star.
FlushSchedule::ramped covers it for free, and it's the reason your own ("SELECT DISTINCT ?n", dense, "LIMIT 1") case in it_limit_stops_work passes.
| pub(crate) sidecar_bytes: Option<Vec<u8>>, | ||
| } | ||
|
|
||
| impl LeafScan { |
There was a problem hiding this comment.
Praise — LeafScan::load_leaflet doesn't just deduplicate five copies, it fixes a drift between them.
Two of the five had diverged: the SPOT walk and the subject probe hardcoded decode_set: ColumnSet::ALL in the cached arm while passing ColumnProjection::all() to the uncached one. Folding them onto proj.effective() reconciles that without changing the decode set at any site — ColumnProjection::all().effective() is ColumnSet::ALL.union(EMPTY) = ColumnSet::ALL (fluree-db-binary-index/src/read/column_types.rs:246-256), which I checked rather than assumed.
Same for the three per-row object-decode helpers becoming decode_overlay_object: they were byte-identical apart from their error strings.
…reaming # Conflicts: # fluree-db-query/src/property_join.rs
…r walk open() now closes any driver still held before resetting, completing the reset block. The invariant that lets a lane's reconciler be shared across chunks (each subject lands in exactly one driver chunk) is restated on ChunkLanes. A new test reads a star at a t before its subjects were deleted, after a reindex, so their rows sit only in the last leaflet's history past its live rows. The leaflet skip stays sound through two layers, index writers widening leaflet keys over history and the walk never skipping a leaflet it must replay; the test fails with both removed.
|
Thanks for the thorough review. Both blocking items are done, plus the three optional ones. CI. Retargeting to Bench.
The remaining overlay_matrix scenarios are within ±1.1%. ¹ In the six-round run, The full-drain star you flagged comes out 13–30% faster despite the extra leaflet reads; I haven't profiled which part of the change accounts for that. The only consistent slowdowns are Optional items, in
|
Stacked on #1933.
An outer
LIMITdidn't stopPropertyJoinOperatoror the coalesced OPTIONAL seed. Both read their whole input before handing over the first row, so?p a ex:Person ; ex:name ?n LIMIT 10cost as much as the full star.Property join. On a current-state read with a bound-object anchor such as
?p a ex:Person, the driver is now read a chunk of subjects at a time. Chunks start at 1,024 subjects and grow eightfold up to 100,000. Each chunk's rows are handed over before the next chunk is read, so a selective star can satisfy theLIMITfrom the first chunk. The chunks grow without a row budget, soDISTINCT … LIMITstops early too;DISTINCTabsorbsset_row_budget, so the budget never reaches the join. The subject map is kept across chunks, so a driver that revisits a subject still joins it once. That happens with@listvalues, which sort byo_iin POST. These cases keep the single pass:Rows and their order are unchanged. A test pages through a 12,000-subject star using
LIMIT/OFFSETwindows that cross chunk boundaries, and checks the pages against the full result.SPOT star walk. Without pruning, adjacent chunks re-read the leaflets they share. The walk now skips a leaflet when its directory keys hold none of the probed subjects. This applies only to current-state reads, because replayed rows can fall outside the directory keys. On a 100,000-subject full star, the walk reads 20 leaflets in a single pass, 50 when chunked, and 23 when chunked with the skip.
OPTIONAL. Under a row budget, the first coalesced seed is sized to the budget, and only those rows are copied out of the scan batch, which can be a whole leaflet. The rest of the batch is kept as
(Batch, cursor)for the next pull.FlushSchedule(fixed, ramped or budgeted) now sizes the batches in all three places. The nested-loop join behaves as before: it grows its batches only under a budget, because each flush walks its key batch's whole range.Cleanup in the same code. The second commit changes no behavior:
LeafScan::load_leafletreplaces five copies of the "load through the cache, then replay" sequence: four injoin.rsand one in the range semijoin.Timings
100,000 people, file-backed and indexed, median of repeated runs:
SELECT ?p ?n WHERE { ?p a ex:Person ; ex:name ?n } LIMIT 10SELECT DISTINCT ?n WHERE { ?p a ex:Person ; ex:name ?n } LIMIT 1SELECT DISTINCT ?c WHERE { ?p a ex:Person ; ex:city ?c } LIMIT 1SELECT ?p ?n ?e WHERE { ?p a ex:Person ; ex:name ?n ; ex:email ?e } LIMIT 10ASK { ?p a ex:Person ; ex:email ?e }SELECT ?p ?e WHERE { ?p ex:name ?n OPTIONAL { ?p ex:email ?e } } LIMIT 10SELECT ?p ?e WHERE { ?p a ex:Person OPTIONAL { ?p ex:email ?e } } LIMIT 10Queries without a
LIMITreturn the same row counts; those covered stars,MINUS,NOT EXISTS,GROUP BY, OPTIONAL and multi-hop joins. On a dedicated EC2 box at medium scale, the budgeted benches (query_hot_fanout_star,query_hot_optional,query_overlay_matrix) are within the 3% budget or faster (full-drain stars 13–30% faster; see the review thread for the table).Tests
it_limit_stops_workchecks early stop through the join's debug event, which reports subjects read and whether the driver was exhausted. Fuel can't show it, because fuel is charged per leaflet. The tests cover:DISTINCTand sparse stars underLIMITEach test fails when its code path is reverted.
Not in this PR
LIMITstill doesn't stop these:UNION, which drains each branchGRAPH, which drains its inner planDISTINCTorFILTER, which gets no budget and still flushes at 100,000 rows