Repository navigation
perf(query): skip unprobed leaves and shard the leaflet cache - #2405
Conversation
The three subject-probe loops (the nested-loop join's scan_matches, batched_subject_probe_binary behind the OPTIONAL, EXISTS and property-join lanes, and the property join's SPOT star walk) opened every leaf between the lowest and highest probed subject: a leaf-cache lookup plus a header and directory decode per leaf, before the leaflet skip could decline anything inside it. psot_leaf_may_hold_subjects and spot_leaf_may_hold_subjects judge a leaf from its branch keys first. A PSOT leaf's keys bound the probed predicate's subjects, open-ended where the leaf starts or ends inside another predicate; a SPOT leaf's bound its subjects directly. As with the leaflet skip, a history replay opens every leaf. The writers widen keys over the history they keep (#1624), but the probe does not rely on that. holds_any_subject now takes one binary search instead of two. Each lane's debug event reports leaves_opened.
The leaflet cache was one moka cache, and moka records every hit in a single bounded channel shared by all threads. In a 64-core BSBM profile, contention on that channel's tail took about 28% of server CPU. The pool is now a moka SegmentedCache: one shard per core, each with its own channel, admission and eviction. Shards keep at least 256 MiB, since moka never caches an entry heavier than its shard and a vector shard can weigh tens of megabytes. Budgets under 512 MiB stay one pool. The server's periodic cache stats line now reports the shard count.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz both halves look right to me. The leaf check reads branch keys only as bounds (open-ended where a leaf straddles predicates, which is the subtle line, and it's correct), and the sharded pool is a clear win: Claude measured +33% queries/s at 16 clients, and at 16 threads the sharded hit path does 6× the single pool's throughput. The one thing I'd want before merging is perf, not correctness: the leaf check costs the dense NLJ probe 8.5–11.7% on a three-step chain in every session Claude ran, and a once-per-scan gate removes it. Details below.
Full review below:
✅ Approving to unblock: please get the dense-probe gate (or a BSBM run showing the dense case flat) in before merging. Both halves are carefully built. The leaf check reads routing keys as bounds and nothing else, which is exactly what #2402 established they are. The shard floor is the detail that makes SegmentedCache safe here: without it, a 64-core host would quietly stop caching a 48 MiB vector shard.
Before merging:
fluree-db-query/src/join.rs:2523: gate the NLJ leaf check onunique_s_ids.len() < leaf_range.len(). The unconditional check costs dense probes about 10% (measured).
Notes:
- #2404's must applies to these lanes too:
psot_p_runtrustsp_conston a replayed leaflet, and on an index built before v4.1.6 that returns another predicate's values through this PR's NLJ and OPTIONAL lanes as well. Claude ran #2404's suggested patch at this head: every row on the v4.1.5-written ledgers comes back correct, and this PR's tests pass. - On "the bypass is pinned by the unit test only": that's enough for the helper, not for its call sites. A call site that passed
falsewould pass every test, because no index the current writers produce can tell the difference (Claude's mutation: the unit test goes red and the integration test stays green). The bypass is load-bearing on indexes built before v4.1.6. Claude showed that at the leaflet level, where removing #2404's twin of this guard loses a history-only subject at an earliert. On the 10-subject fixture the single leaf spans three predicates, so the open-ended bound admitted the subject anyway and the leaf-level mutation couldn't show it. So keep it. The durable pin is #2375's single per-leaflet decision, not another test here. - Neither commit depends on #2403. Both cherry-pick onto
origin/mainafter #2404's, and all the tests pass there. The one conflict is #2404's (load_leaflet's tracker argument, from #2214, merged today). #2214 also editsdocs/design/performance.md, but a different section; the file merges cleanly. - Perf beyond the must:
- The SPOT star walk is about 25% faster on a sparse probe.
- Single-client sharding is within −2.5% to +4.2%; the star rows' +3% matches about 6 ns per hit for picking a segment. At 2 cores (2 shards), every row is within ±3%.
- Up front, each shard costs 31.8 KB, as you estimated.
- On a Zipf trace, the overall hit ratio is flat to slightly up, but vector-shard-sized entries lose hit ratio (21%→13% and 26%→12% at the 1 GiB floor), since a 256 MiB shard holds only a handful of them.
- Claude couldn't reproduce the 32- and 64-core BSBM 100M figures (32 vCPU cap, no BSBM data on the box), so those stay yours. Full tables are in the summary.
Adherence: Patterns ✔ · Performance 🔴 · Deployment targets ✔ · Testing ✔ · Conventions ✔ · verification
- Patterns/abstractions: ✔ The leaf helpers share
holds_any_subjectwith #2404's leaflet helper, and the pool uses moka's ownSegmentedCacherather than a hand-rolled shard map. - Performance (speed first, memory second): 🔴 Dense NLJ probe: +8.5% to +11.7% (three steps) and +3.2% to +4.8% (one step) from the leaf check, in four sessions; the once-per-scan gate removes it. Elsewhere: star sparse −25%; +33% queries/s at 16 clients; single-client sharding within noise. Memory: about 32 KB per shard up front, and the transient overshoot grows with the shard count.
- Deployment targets: ✔ The leaf skip is host-neutral. The pool shards by
available_parallelism, which honours cgroup quotas and affinity, so small hosts get one or two shards, and budgets under 512 MiB stay one pool. wasm32 keeps its stand-in, andavailable_parallelism'sErrthere maps to 1. - Testing: ✔ The leaf skip and the floor are each pinned (they go red under mutation). The open-ended bound and the replay bypass are unit-pinned only; see the note and the inline comment.
- Conventions: ✔ Two well-separated commits with full rationale; the stats line gains
cache_shards. CI's jobs atd6951064a(gate-stack) all pass, nextest 16,199 of 16,199.
Verified at d6951064a: Claude reran the PR's four tests and checked each against a mutation: the leaf skip off fails the integration and helper tests, the bypass removed or the open bound closed fails the helper test, and the floor cut fails both cache tests. Claude's model-checked probe passes across a rebuild, novelty, time travel, an incremental build and a final rebuild, here and with the commits cherry-picked onto origin/main. Release A/B on 3M subjects (single-client, 2-core, 16-client), with all builds returning identical results. The dense-probe attribution was checked with three variants over four sessions. The leaflet-cache micro-benchmarks covered the hit path, up-front memory, hit ratio and overshoot.
Approving to unblock: just be sure to get the dense-probe gate in (and #2404's psot_p_run fix underneath it) before this merges. The rest is take-or-leave, though I'd fold in the edge-subject test while you're there.
| for leaf_idx in leaf_range { | ||
| ctx.check_cancelled()?; | ||
| let leaf_entry = &branch.leaves[leaf_idx]; | ||
| if !psot_leaf_may_hold_subjects(leaf_entry, p_id, unique_s_ids, need_replay) { |
There was a problem hiding this comment.
Blocking (performance): the leaf check makes the dense NLJ probe 8.5–11.7% slower on a three-step chain, a case where it can't skip anything.
When every leaf in range holds a probed subject, the check is pure overhead, and the body budgets that as "one binary search per leaf". In Claude's release A/B it costs far more than that, and only here in scan_matches. The setup was 3,000,000 subjects at default leaflet sizes (12 leaves per predicate), fat LTO, c7i.4xlarge, single client, p50. A 3,000-subject probe through three NLJ steps (chain3_Dense) ran +11.7%, +8.5%, +10.1% and +9.6% slower than at #2404 in four separate sessions. One step (nlj_Dense) ran +4.8%, +3.2%, +3.8% and +4.1%. The OPTIONAL and SPOT-star lanes show no such cost on the same dense sets. Twelve holds_any_subject calls per step can't cost about 90 µs, so this is codegen: the extra call in the leaf loop changes how scan_matches compiles. Claude couldn't attribute it further, but it reproduces in the build this PR ships.
What Claude tried, each as a variant of 7d8f0e09c:
- Removing just this check brings both rows back to within −0.5% to +3.2% of perf(query): the nested-loop subject probe skips leaflets with no probed subject #2404, over three sessions.
- Moving it into
leaf_range.filter(…)doesn't help (+4.8% / +11.7%). - Gating it once per scan on the one case where a leaf is guaranteed skippable brings both back (−0.2% / +2.0%). The sparse rows and the star lane's −25% are unchanged:
// Fewer probed subjects than leaves is the only case where some
// leaf must hold none of them; otherwise every leaf is opened.
let check_leaves = unique_s_ids.len() < leaf_range.len();
for leaf_idx in leaf_range {
ctx.check_cancelled()?;
let leaf_entry = &branch.leaves[leaf_idx];
if check_leaves && !psot_leaf_may_hold_subjects(leaf_entry, p_id, unique_s_ids, need_replay) {
continue;
}The gate gives up skipping when the probes outnumber the leaves but cluster; that case just falls back to #2404's behaviour. If you'd rather keep the check unconditional, it would be worth showing on your BSBM box that the dense case doesn't move there. The harness is a self-contained example (rv2404_ab.rs, 3M subjects, about 6 s to import), and I'm happy to share it.
There was a problem hiding this comment.
Addressed in 0be986f — gated at twice the leaf range rather than once. At 1× the check would be off for nearly half of BSBM Explore Q10's calls at 100M (1–58 offers per product, median 20, over about 21 leaves); at 2× it stays on for about 99% of them, and the dense case you measured (about 250×) stays excluded.
| let fluree = FlureeBuilder::memory().build_memory(); | ||
| let ledger_id = "it/join-batched-leaf-skip:main"; | ||
| let ledger = genesis_ledger_for_fluree(&fluree, ledger_id); | ||
| let probed = [5, 60, 115]; |
There was a problem hiding this comment.
Optional: This is more of a suggestion than a concern: the open-ended PSOT bound in psot_leaf_may_hold_subjects (join.rs:392-401) is, I think, the most consequential line in this PR, and only the unit test pins it. Claude closed it (lo/hi always taken from the keys) and both integration tests still pass, since 5, 60, 115 are all interior to ex:val's partition. Claude's probe, which also probes the partition's first subject, drops s000 from a plain ex:hub ex:ref ?s . ?s ex:val ?v at head on a full rebuild: that subject's leaf starts in the previous predicate. Adding 0 (or 119) to probed would pin the bound end-to-end; the per-lane leaf ceilings may need one more. It's minor and non-blocking, but if you agree it's right, I'd rather see it in this PR than lost in the backlog.
| /// every shard at least [`MIN_SEGMENT_BYTES`]; budgets under twice that stay | ||
| /// one pool. Always a power of two, as moka rounds up to one. | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| fn pool_segments(max_bytes: u64, cores: usize) -> usize { |
There was a problem hiding this comment.
Optional (memory): This is more of an observation than a request: sharding also multiplies how far the pool can run over its budget between housekeeping passes. moka applies a segment's pending inserts, and evicts for them, once that segment has 64 queued writes or 300 ms have passed (housekeeper.rs:77-103). With n shards, up to about 64 × n freshly inserted entries can sit above the budget at once, instead of 64. Claude measured it with an insert-only stream of 768 KiB entries into a 2 GiB pool on 16 vCPU, which gets 8 shards. Live bytes peaked at 2,379 MB (+16.2%) against 2,146 MB (+4.8%) for the single pool, and were still 2,291 MB against 2,096 MB when the stream ended. At the 35% default that's probably fine, but it's real headroom the budget doesn't show, and on a 64-shard host the bound is about 4,000 entries. We may want a sentence in this doc comment, and in docs/design/performance.md's paragraph, saying the budget is enforced per shard at housekeeping, so the transient overshoot grows with the shard count. It's minor and non-blocking, but if you agree it's right, I'd rather see it in this PR than lost in the backlog.
…ntention # Conflicts: # fluree-db-query/src/join.rs
…he leaf range The leaf check in `scan_matches` cost a dense probe, where every leaf in range holds a probed subject and nothing is skipped, about 10% on a three-step nested-loop chain and about 4% on one step (release A/B, 3M subjects at 3,000 probed subjects over 12 leaves). Twelve binary searches per step don't account for that; the extra call changes how the leaf loop compiles. Moving the check into the range filter didn't help. The loop now checks leaves only while the probe set is under twice the leaf range, decided once per scan. Gating at the leaf count itself would drop the check for nearly half of BSBM Explore Q10's calls at 100M: a product has 1 to 58 offers (median 20) over about 21 leaves. At twice the range the check stays on for about 99% of them, and the products it leaves out have offers enough that the check would skip only around a tenth of the leaves. The measured dense case is about 250 times the range, so it no longer pays for the check. A probe set past the gate opens every leaf in range, as before the leaf check; the leaflet check still declines the leaflets it can. The OPTIONAL and SPOT-star lanes showed no such cost and keep their check.
…ip lane The PSOT leaf check bounds the probed predicate's subjects by the leaf's branch keys, open-ended where the leaf starts or ends inside another predicate. Only the unit test pinned that: the integration test probed subjects inside the partition, so taking the bound from the keys alone still passed it. The test now also probes `s000`, the first subject of `ex:val`'s partition, whose leaf starts in the previous predicate. With the lower bound closed, the nested-loop lane drops it. The leaves each lane may open rise by one subject's worth.
…ards moka applies a shard's pending inserts, and evicts for them, at that shard's housekeeping: once it has queued 64 writes or a short interval has passed. Between passes, fresh inserts sit above the budget. With the pool split into `n` shards, up to about 64 × n entries can be pending at once instead of 64, so a burst of inserts overshoots the budget further on a host with more cores. The pool's shard-count doc and the caching paragraph of the performance design doc now say so.
|
From the review summary:
Addressed in 0be986f (at twice the leaf range; see the inline reply).
Addressed in e0388b0 (merge of |
Brings #2405. The leaflet cache: next splits the leaflet budget into stages, a pool per reservation level for storage that decrypts on read, while main made the pool a sharded `SegmentedCache`. Each stage's pool is now a sharded pool, its shard count from `pool_segments` on that stage's capacity; the core count is carried on `Stages` so a later stage shards the same way and main's shard tests can still pick it. `shard_count` reads the current stage's pool. The subject probes: main's leaf-level skips (`psot_leaf_may_hold_subjects`, `spot_leaf_may_hold_subjects`, and the nested-loop gate at twice the leaf range) come in alongside next's leaflet-level `may_hold_keys`; main's leaflet helper stays out, as in the previous merge. The new integration test awaits next's async genesis and sizes leaves by `with_leaf_rows(8)` (two four-row leaflets), next's leaf sizing; it fails with the leaf skip disabled.
Problem
Two costs remain on the subject-probe lanes after #2404. Both grow with core count.
Leaf opens. #2404 stops the nested-loop subject probe from loading leaflets that hold none of the probed subjects. Before that leaflet check runs, though, all three subject-probe loops still open every leaf between the lowest and highest probed subject. Each open costs a leaf-cache lookup plus a header and directory decode. The three loops are:
NestedLoopJoinOperator::scan_matchesbatched_subject_probe_binary, behind the OPTIONAL, EXISTS and property-join lanesbatched_subject_star_spot, the property join's SPOT walkLeaflet cache contention. The leaflet cache is one moka cache, and moka records every hit in a single bounded channel that all threads share. In a 64-core BSBM profile with the leaf skip applied, moka's hit path was still 30% of server CPU. Nearly all of it was threads contending on that channel's tail.
Fix
Leaf skip
psot_leaf_may_hold_subjectsandspot_leaf_may_hold_subjectscheck a leaf's branch keys before the leaf is opened:As with the leaflet check, a history replay opens every leaf. The writers widen keys over the history they keep (#1624), but the probes don't rely on that.
holds_any_subjectnow uses one binary search instead of two. It is shared with #2404's leaflet check. Each lane's debug event now reportsleaves_opened; for the PSOT probe that event (batched subject probe complete) is new.What it changes: the savings are leaf opens: leaf-cache lookups, header and directory decodes, and directory walks. It doesn't reduce decoded-column cache lookups any further than #2404 already does.
Dense probes: a probe set where every leaf holds a probed subject skips nothing. In the nested-loop lane the check still cost such a probe about 10% on a three-step chain (3,000 subjects over 12 leaves), from how the leaf loop compiles. That lane checks leaves only while the probe set is under twice the leaf range, decided once per scan, and opens every leaf in range past that, as after #2404. At 100M, BSBM Explore Q10 probes 1 to 58 offers over about 21 leaves, so the check stays on for about 99% of its calls. The OPTIONAL and SPOT-star lanes showed no such cost and check every leaf.
Sharded leaflet cache
The pool is now a moka
SegmentedCache, split by key hash. Each shard has its own read channel, admission and eviction.LeafletCache statsline now reportscache_shards.Tests
subject_probes_open_only_leaves_holding_probed_subjectsprobes four subjects over two-leaflet leaves through each lane. One is the first subject of the predicate's partition, whose leaf starts inside the previous predicate, so the open-ended lower PSOT bound is pinned end to end (the upper one by the unit test):The test also reads at an earlier
tthrough each lane. That read must restore a changed value and a subject whose only value was later retracted.leaf_keys_decline_only_leaves_without_a_probed_subjectunit-tests the helpers: inclusive endpoints, open-ended PSOT bounds, leaves wholly outside the predicate, an empty probe set, and the replay bypass.pool_has_a_shard_per_core_within_the_shard_floorchecks shard counts across budgets and core counts, and that every shard stays at or above the floor.sharded_pool_still_caches_an_entry_heavier_than_a_core_sharecaches a 48 MiB entry in a 1 GiB pool on 64 cores, which gets 4 shards. With the floor removed, the pool gets 64 shards of 16 MiB and the entry is not cached.Results so far
BSBM 100M:
The leaf-skip and sharded-cache figures in each row come from the same session, except for 1 client and 32 cores. The 64-core figures are the means of two runs each: sharded 2,551,430 and 2,538,263, with no timeouts. The #2404 column comes from an earlier session.
At 64 cores the sharded cache adds 58%. Going from 16 to 32 cores gives 1.94× with it, and 32 to 64 cores 1.68×; without it, 32 to 64 cores gave 1.16×.
Not verified
Follow-up: #2375