Skip to content

perf(query): batched probes skip empty leaflets and gallop subject runs - #2050

Merged
bplatz merged 3 commits into
nextfrom
perf/batched-probe-gallop
Oct 14, 2026
Merged

bplatz merged 3 commits into
nextfrom
perf/batched-probe-gallop

Conversation

@bplatz

@bplatz bplatz commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two changes to batched subject probes, the lookups behind wildcard expansion, traversals and batched joins:

  1. Skip leaflets that hold no wanted key. The batched cursor groups wanted ids into chunks that allow gaps between ids, then decoded every leaflet in a chunk's span. BinaryCursor::set_wanted_keys now checks each leaflet's directory key range first and skips the leaflet when no wanted id falls inside it. The check, LeafletDirEntryV3::may_hold_keys, works by subject for SPOT, by the filter predicate's subjects for PSOT (or the leaflet's own predicate when none is pinned), and by object for single-type OPST. The join's PSOT and SPOT-star probes had their own copies of it; all three now call the one method. Batched-join leaf scans also reuse the cached leaf directory instead of decoding it on every probe.
  2. Forward search over subject runs. For each wanted subject, the PSOT probe ran two binary searches over the predicate's whole run. SubjectRuns now gallops forward from where the previous subject's run ended. Dense wanted sets cost O(1) per subject, sparse ones O(log gap). The change applies at all three probe sites.

Neither changes the index format or query results.

Measurements

  • Leaflet skip: matters most when leaflets are small. At 25,000 rows nearly every leaflet in a span holds a wanted id; at 4,096 rows most don't. On the Pokec graph, fully cached, with 4,096-row leaflets, shortest path went from 1.49× to 1.20× of its time at 25,000 rows.
  • Forward search: a small gain. Measured with 4,096-row leaflets on DBLP-core (561M triples, 105 SPARQLoscope queries, 4 restarts × 3 runs):
    • Queries of 20 ms or more: geometric mean 0.99×. strstarts was the largest single gain.
    • All 105 queries: 1.00×.
    • Fully cached Pokec traversals: unchanged.
    • All 105 responses: byte-identical to the build without this change.

Notes

  • SubjectGroups in count_plan_exec.rs gains #[allow(clippy::large_enum_variant)]. The cursor's new wanted_keys field pushed the cursor variant past clippy's size threshold. One value exists per query, so its size doesn't matter.

Tests

  • subject_runs_match_full_searches compares galloping runs against the two full searches over random run lengths and gaps.
  • subject_runs_on_const_column covers the single-subject case.
  • wanted_keys_skip_leaflets_without_a_wanted_subject checks that the cursor skips leaflets whose directory key range holds no wanted subject and still returns every wanted row, including wanted keys equal to a leaflet's first or last subject.
  • psot_may_hold_keys_reads_subject_bounds_per_predicate and spot_and_opst_may_hold_keys cover the shared check: inclusive bounds, leaflets spanning other predicates, and mixed-o_type OPST leaflets. Making either bound exclusive turns all three tests red.

@bplatz bplatz added area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Oct 10, 2026
@bplatz
bplatz requested a review from a team October 10, 2026 15:58
@bplatz
bplatz force-pushed the perf/batched-probe-gallop branch from 0acb1af to 1da649a Compare October 11, 2026 17:44
BatchedWildcardCursor and the PSOT predicate-refs lookup chunk wanted
ids with a 4096-id gap tolerance, then decoded every leaflet in each
chunk's span. BinaryCursor::set_wanted_keys skips a leaflet whose
directory key range holds no wanted key (SPOT s_id, single-predicate
PSOT s_id, single-o_type OPST o_key) before any cache probe or decode.

Batched-join leaf scans also take the leaf directory from the shared
cache instead of decoding it on every probe.
Batched subject probes searched the whole predicate run twice per wanted
subject. Wanted subjects ascend, so each search now gallops forward from
where the previous run ended: O(1) per subject for dense sets, O(log gap)
for sparse ones.
@bplatz
bplatz force-pushed the perf/batched-probe-gallop branch from 1da649a to 582cbba Compare October 11, 2026 18:08

@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 this is nice, and the cursor is the right altitude for the skip: every batched consumer gets it, behind the same has_ov/replay guards as the existing pre-skips. I measured both halves. The skip takes a scattered one-chunk probe from 235 to 25 decoded leaflets (11.0 → 1.19 ms) at 4,096-row leaflets and costs nothing on dense spans. The gallop is a big win for dense wanted sets and a small loss (~+23 ns per id) for very sparse ones, which fits your 1.00×. One headline note, above this PR: none of this is a format change. It's on next only because its prerequisites are next-only (BatchedWildcardCursor in 0de62a331, the join's subject-lane skip in b91e779af); a cherry-pick onto main conflicts in batched_lookup.rs and join.rs. With main still shipping minors, is the plan for this perf line to wait for the major, or to port it to main along with those prerequisites? Good to merge to next once it's ready either way.

Full review below:


✅ Approve with nits.

This is nice, @bplatz. Skipping by directory keys inside BinaryCursor::next_batch, gated exactly like leaflet_out_of_range, gives every batched consumer the win in one place. Galloping from the previous run's end is the right search for ascending targets. I found nothing that needs to land first.

What I checked:

  • The skip can't hide a wanted row. Both consumers filter to the wanted keys (for_each_subject_run, for_each_wanted_run), and both pass sorted, deduped chunks. An overlay op for a wanted id sitting in a gap belongs to the next leaflet (has_ov is "next pending op ≤ this leaflet's last key") or to the overlay-only tail. Replay leaflets are never skipped. A scratch differential test over 360 random cases (SPOT/PSOT/OPST; gap ids, exact leaflet edges, overlay asserts in gaps, retracts of existing facts) returned identical rows for wanted keys with and without the skip, while skipping 5,451 leaflets. That test does catch both edge off-by-ones, which yours doesn't yet (inline).
  • The gallop. Correct given strictly ascending targets, and unique_s_ids is sort + dedup at all three probe sites. subject_runs_match_full_searches fails under a gallop off-by-one.
  • Performance, measured. Leaflet skip (dev-fast, BinaryCursor over a 1M-row SPOT leaf, no cache): a scattered one-chunk set goes from 235 to 25 decoded leaflets and 11.0 to 1.19 ms at 4,096-row leaflets, and 10.2 to 6.95 ms at 25,000 rows; dense spans are unchanged. Gallop (standalone microbench with both functions copied verbatim): up to ~12× faster per wanted id when dense, 1.7× slower (+23 ns per id) when wanted subjects are ~1,000 rows apart. I also tried an O(1)-check-then-binary-search hybrid, and it did worse in the middle densities, so I'd keep the gallop.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends BinaryCursor's existing pre-skip chain with the same guards. ⚠️ It's the third copy of the directory-key check (inline; optional).
  • Performance (speed first, memory second): ✔ large wins for scattered probes over small leaflets, neutral elsewhere. The sparse-gallop cost is a few ns per wanted id. No regression risk.
  • Deployment targets: ✔ pure cursor/query logic, no threads, clock or filesystem. wasm32 clippy and wasm-smoke were green in CI on this head.
  • Testing: ✔ the new tests run in CI by name and the gallop test has teeth. ⚠️ The skip test doesn't pin the inclusive edges (a three-line fix inline).
  • Conventions: ✔ thorough commit bodies; the large_enum_variant allow is explained in the body and on the line.

Verified locally at 582cbbafc: cargo fmt --check; cargo test -p fluree-db-binary-index -p fluree-db-query --lib (370 + 1,659 passed, wanted_keys_skip_leaflets_without_a_wanted_subject, subject_runs_match_full_searches and subject_runs_on_const_column by name). CI's nextest (14,152 passed) covers the fluree-db-api suites on this exact head.

Approving so you can merge when ready, but maybe worth folding in the edge case first.

};

assert_eq!(scan(None).0, 50);
let (batches, s_ids) = scan(Some(&[10, 150]));

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: this test doesn't pin the inclusive edges of the skip.

Wanted keys 10 and 150 both sit in the middle of their leaflets. So making either bound exclusive leaves the test green: keys[i] < hi at :190, or partition_point(|&k| k <= lo) at :189. I tried both. A wanted key equal to a leaflet's first or last subject is exactly the case where an off-by-one would quietly drop a leaflet and its rows.

Adding a case with the last subject of one leaflet and the first of the next pins both. I ran it at this head (passes) and under each mutation (fails):

let (batches, s_ids) = scan(Some(&[12, 13]));
assert_eq!(batches, 2, "a wanted key equal to a leaflet's last or first subject keeps it");
assert_eq!(s_ids, (9..=16).collect::<Vec<u64>>());

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 7db90d7

}

/// Whether a leaflet's directory key range can hold a wanted key.
fn leaflet_may_hold_wanted(

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: this is the third copy of "do a leaflet's directory keys bound one of these sorted ids".

The other two are in the join: psot_leaflet_may_hold at fluree-db-query/src/join.rs:297-323 (from b91e779af), and the SPOT inline in the star probe at join.rs:3897-3906. All three agree on the leaflets current writers produce. The one difference is that this copy passes a mixed-predicate PSOT leaflet through, while psot_leaflet_may_hold bounds it by whichever end carries p_id. LeafWriter and the incremental re-encode both segment POST/PSOT leaflets per predicate, so that only matters for older data.

This is more of a suggestion than a finding. With the check now living in binary-index, the join's helper could move here, and all three sites could call one function. The cursor could also use the predicate-aware form when its filter pins p_id, as batched_lookup_predicate_refs does. 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 7db90d7

fn lower_bound_s_id(
batch: &fluree_db_binary_index::ColumnBatch,
start: usize,
/// Successive subject runs within the subject-sorted rows `[start, end)` of a

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: an orphaned doc line for the function this PR deletes.

fluree-db-query/src/join.rs:295-296 still reads "/// Binary search for the first row in batch.s_id[start..end] where s_id >= target." followed by #[inline], stacked on top of psot_leaflet_may_hold's doc. That line already sat there on next, but it describes lower_bound_s_id, which SubjectRuns replaces here. So this seems the natural PR to drop those two lines. Commenting here because join.rs:295 is not in this diff.

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 7db90d7

The cursor's wanted-key skip, the join's PSOT probe and its SPOT star
probe each read a leaflet's directory keys their own way. All three now
call `LeafletDirEntryV3::may_hold_keys`. The cursor passes its filter's
predicate, so a mixed-predicate PSOT leaflet is bounded by that
predicate's subjects rather than passed through, as the join already did.

The cursor test now covers wanted keys equal to a leaflet's first and
last subject, which an exclusive bound on either side would drop. Also
removes a doc line orphaned by the deleted `lower_bound_s_id`.
@bplatz
bplatz merged commit e88d2ec into next Oct 14, 2026
19 checks passed
@bplatz
bplatz deleted the perf/batched-probe-gallop branch October 14, 2026 01:39
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 performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants