Skip to content

perf(query): the nested-loop subject probe skips leaflets with no probed subject - #2404

Merged
bplatz merged 4 commits into
mainfrom
perf/nlj-leaflet-subject-skip
Nov 18, 2026
Merged

bplatz merged 4 commits into
mainfrom
perf/nlj-leaflet-subject-skip

Conversation

@bplatz

@bplatz bplatz commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The nested-loop join's batched subject probe (NestedLoopJoinOperator::scan_matches) took the PSOT leaves for the range from the lowest to the highest probed subject. It then loaded every leaflet in them, including leaflets that held none of the probed subjects. For each loaded leaflet it also walked every row to find the predicate's run.

When the probed subjects are scattered, that range covers nearly the whole predicate partition. BSBM Explore Q10 at 100M is an example: it reads five properties of about 19 offers, chained one nested-loop step per property, over predicates of about 5.7M rows each. Every step read the whole partition to match those 19 subjects. Each of those leaflet loads is also a lookup in the shared leaflet cache.

batched_subject_probe_binary, used by the property-join and exists lanes, got a directory-level skip for this in 668285a; scan_matches did not.

Fix

Both loops now share two helpers:

  • psot_leaflet_may_hold_subjects declines a leaflet before its columns load when its directory keys can hold none of the probed subjects.
  • psot_p_run returns the whole leaflet as the predicate's run when the leaflet holds only that predicate, so there's no row walk. A leaflet whose history was replayed is always walked, since replay can restore another predicate's rows into it on an index built before v4.1.6. The walk also no longer adds the run's start offset twice when finding its end.

The guards are the ones the property-join lane already had. Only single-predicate leaflets are judged, since a mixed leaflet's key range isn't a subject interval. A history replay is never skipped, since a key range describing the current state can leave out subjects from an earlier t.

The leaflets_scanned field on join batched binary scan complete now counts only the leaflets actually loaded.

Tests

batched_subject_join_loads_only_leaflets_holding_probed_subjects (in it_join_batched_overlay) probes three subjects across a 30-leaflet partition. It checks that three leaflets are loaded on the indexed lane and with uncommitted changes on top. It also checks the rows on a time-travel read, where replay restores a changed value, and after a reindex. With the skip disabled the test loads 30 leaflets and fails.

Unit tests in join.rs pin what no current writer's index reaches: p_run_walks_mixed_and_replayed_leaflets covers a mixed leaflet, the last predicate in one, and a replayed leaflet whose p_const no longer describes its rows. leaflet_keys_decline_only_at_head_and_only_when_homogeneous covers the guard's bypasses for replay and for mixed leaflets.

Follow-up: #2375 (the cursor and the other batched lanes still trust p_const under replay)

…bed subject

The nested-loop join's batched subject probe (scan_matches) loaded every
PSOT leaflet between the lowest and highest probed subject and walked
each one's rows to find the predicate run. A scattered probe set spans
nearly the whole predicate partition, so each probe step read the
partition to match a handful of subjects: BSBM Q10's offer properties
are about 228 leaflets each at 100M, for about 19 offers.

batched_subject_probe_binary got the directory-level skip and the
homogeneous p-run shortcut in 668285a; scan_matches did not. Both now
share psot_leaflet_may_hold_subjects and psot_p_run, so the two lanes
judge leaflets the same way. A history replay is never skipped.
leaflets_scanned now counts only the leaflets actually loaded.
@bplatz bplatz added the performance Performance improvement (release notes: Performance) label Nov 14, 2026
@bplatz
bplatz requested a review from a team November 14, 2026 20:17

@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 pulling the property-join lane's leaflet guard into helpers both PSOT probe lanes share is the right altitude (and a real step toward #2375's one per-leaflet decision). The one thing I don't think should merge as-is: psot_p_run trusts p_const on a replayed leaflet. On an index built before v4.1.6, a fully retracted predicate's history sits in the next predicate's leaflet, so Claude got that predicate's values, other subjects' included, back from a time-travel NLJ read. The fix is two lines in psot_p_run, and it also clears an older off-by-offset there that made the base panic on the same index. Patch below.

Full review below:


✅ Approving to unblock: please get the psot_p_run replay fix in before merging. The skip is carefully guarded: keys are read as bounds only, mixed and replaying leaflets are always loaded, and the mutation check shows the test pins it (30 leaflets for 3 with the skip off). The must is a small one, in the helper this PR made the single place both lanes decide the p-run.

Before merging:

  1. fluree-db-query/src/join.rs:381: skip the p_const shortcut on a replayed leaflet, and drop the double p_start offset at :388.

Notes:

  • This is the fifth face of the class #2375 tabulates: a leaflet-directory fact that describes the live rows, trusted by a read that replays to an earlier t (#1223, #1624, #2373, and o_type_const/row_count/keys/HAS_O_I in #2375's table). p_const isn't in that table. On the same v4.1.5 index, a plain ?s ex:aaa ?v scan at t=3 also returns nothing, which is the reader-side skip-by-p_const; this PR doesn't touch that path. Neither belongs in this PR beyond the point fix. The class fix is #2375's single per-leaflet decision, and it would subsume the psot_p_run guard.
  • Stack altitude: neither this PR nor #2405 depends on #2403. Claude cherry-picked this commit and #2405's two onto origin/main (88c3cf134), and the PR tests, #2405's unit tests and Claude's probe pass there. The one conflict comes from #2214, merged today: e99940414 gives load_leaflet the query's tracker. The resolution keeps leaflets_scanned += 1; ahead of main's load_leaflet(store, leaflet_idx, &proj, replay_to, &ctx.tracker)?, and with #2214's per-leaflet charge the skip now also lowers the probe's fuel to what it reads. So these two could land ahead of the result cache, along with whatever above them only needs them.
  • Perf: Claude's release A/B on 3M subjects at default leaflet sizes. A 20-subject NLJ probe goes from 1,719 to 57 µs, a three-step chain from 5,172 to 137 µs, and a 3,000-subject probe from 2,478 to 804 µs. The 3,000-subject case still loads every leaflet, so that gain is psot_p_run's homogeneous shortcut. The OPTIONAL and star lanes are unchanged within noise. The BSBM 100M numbers are still yours to fill in; full table in the summary.
Adherence: Patterns ✔ · Performance ✔ · Deployment targets ✔ · Testing ⚠️ · Conventions ✔ · verification
  • Patterns/abstractions: ✔ It extends 668285a6a's guard into helpers both PSOT subject-probe lanes share, rather than adding a second copy.
  • Performance (speed first, memory second): ✔ The NLJ lane is 67–97% faster single-client on Claude's 3M-subject A/B. Other lanes are within noise, and no allocation is added.
  • Deployment targets: ✔ This is shared engine code with no thread, filesystem or clock use. Evidence covers in-memory and file-backed ledgers on Linux, and gate-stack covers the wasm32 compile.
  • Testing: ⚠️ The skip is pinned (it goes red under mutation). The leaflet replay bypass isn't, and no test reads an index from before v4.1.6, which is the only kind where the bypass or the p_const guard matters.
  • Conventions: ✔ Multi-line commit message with the rationale. CI's jobs at 538af308b (gate-stack): fmt, clippy, the no-default checks, doctests, the W3C SPARQL suite, wasm32 and python all pass. nextest: 16,191 passed, 1 failed, 3 timed out. The failure is it_historical_uses_index::historical_view_uses_index_when_target_below_index_t (index_t 3 for 2), a timing race outside this diff; it passed 20 of 20 reruns at this head on Claude's box and passes in #2405's run, which contains this commit. The 3 timeouts are the LocalStack aws_testcontainers tests, which are environmental.

Verified at 538af308b: Claude reran the PR's test, which goes red with the skip forced off (30 leaflets for 3). Claude's model-checked probe passes across a rebuild, novelty, time travel, an incremental build and a final rebuild, at the base, at this head, at #2405's head and on origin/main. On a v4.1.5-written index, the replay bug reproduces and the patch above fixes it. Release A/B on 3M subjects; gates per gate-stack.

Approving so you can merge once the psot_p_run fix is in. The rest is take-or-leave, but I'd fold in the bypass test while you're there.

Comment thread fluree-db-query/src/join.rs Outdated
p_id: u32,
) -> (usize, usize) {
let row_count = batch.row_count;
if entry.p_const == Some(p_id) {

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.

Blocking: psot_p_run trusts p_const on a leaflet that has just been replayed, and on an index built before v4.1.6 that returns another predicate's values, other subjects' included.

p_const describes the leaflet's live rows. Before #1624 (8ac57d75a, first shipped in v4.1.6), a full rebuild filed a fully retracted predicate's history under the next predicate's leaflet. So replaying that leaflet to an earlier t restores the retracted predicate's rows into a batch whose p_const names the next predicate. The shortcut then hands the whole batch to the row loop as the probed predicate's run, and the subject binary search runs over s_ids that aren't monotone. Both call sites (:2498, :4072) reach it right after load_leaflet(…, replay_to), three lines below entry.o_type_const_for(needs_history_replay), which makes exactly this distinction for the type constant. scan_matches always walked rows before this PR, so the shortcut is new to the NLJ lane. The OPTIONAL/EXISTS lane has had it since 668285a6a (v4.1.2).

Claude reproduced it on a ledger written and fully reindexed by v4.1.5. ex:aaa was set on s0..s9 at t2, ex:val at t3, and every ex:aaa was retracted at t4. Reading ex:hub ex:ref ?s . ?s ex:val ?v at t=3 returns [0..9, 111..120] at this head and at #2405's. With s0 probed alone, it returns [0, 111, …, 120]: ten ex:aaa values, nine of them other subjects'. The OPTIONAL lane does the same. The format versions are unchanged since v4.1.5, so this binary reads such an index as-is.

There's a second, older bug one line down that the guard would otherwise start reaching. In (p_start..row_count).position(|i| batch.p_id.get_or(p_start + i, 0) > p_id) (:388, unchanged since the v4 baseline), i already starts at p_start, so the offset is added twice. On the same index at the stack's base (747990fd5), the NLJ read panics with index out of bounds: the len is 20 but the index is 20. With the guard alone, it would go back to panicking.

Fix (Claude ran this patch at this head and at #2405's head). Every NLJ and OPTIONAL row on the v4.1.5 ledgers comes back correct, and it_join_batched_overlay and the new tests still pass:

fn psot_p_run(
    entry: &fluree_db_binary_index::format::leaf::LeafletDirEntryV3,
    batch: &fluree_db_binary_index::ColumnBatch,
    p_id: u32,
    replays_history: bool,
) -> (usize, usize) {
    let row_count = batch.row_count;
    // `p_const` is taken over the live rows; a replay can restore rows of
    // another predicate (indexes built before #1624), so walk them.
    if entry.p_const == Some(p_id) && !replays_history {
        return (0, row_count);
    }
    let p_start = (0..row_count)
        .position(|i| batch.p_id.get_or(i, 0) >= p_id)
        .unwrap_or(row_count);
    let p_end = (p_start..row_count)
        .position(|i| batch.p_id.get_or(i, 0) > p_id)
        .map_or(row_count, |offset| p_start + offset);
    (p_start, p_end)
}

Both call sites pass needs_history_replay. Head reads keep the shortcut. The walk costs only leaflets a time-travel read has just replayed: two linear passes over a batch that the replay has already rebuilt row by row.

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 ec78fff

use fluree_db_binary_index::format::run_record_v2::read_ordered_key_v2;
use fluree_db_binary_index::RunSortOrder;

if entry.p_const != Some(p_id) || replays_history {

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 more of an observation than a request: the leaflet helper's replay bypass (|| replays_history) is load-bearing, but nothing pins it. With it removed, this PR's test and Claude's probe pass on every index the current writers produce. That's expected, since those writers widen keys over history (#1624). On the v4.1.5-written ledger, where s0's only ex:val was retracted before the build, removing it makes the probe for s0 alone at t=3 return [] instead of [0]: the history sorts outside the leaflet's live-row keys. #2405 adds a unit test for its leaf helper's bypass. We may want the same for this helper: a hand-built LeafletDirEntryV3 whose keys exclude a probed subject should be declined at head and loaded under replay. 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.

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 553b723

Base automatically changed from feat/query-result-cache to main November 18, 2026 13:33
…ect-skip

# Conflicts:
#	fluree-db-query/src/join.rs
`psot_p_run` returned a predicate-homogeneous leaflet whole as the probed
predicate's run. `p_const` is taken over the live rows, and on an index
built before v4.1.6 a full rebuild filed a fully retracted predicate's
history under the next predicate's leaflet. A time-travel read that
replays such a leaflet gets those rows back, so the shortcut handed
another predicate's values, other subjects' included, to the subject
probe. The shortcut now applies only when the leaflet replays no history.

The walk that replaces it found the run's end with the start offset
added twice, which read past the run (or the batch) whenever the
predicate did not start at row 0. It now indexes rows directly.

A unit test covers a mixed leaflet, the last predicate in one, and a
replayed leaflet whose `p_const` no longer describes its rows.
… bypasses

`psot_leaflet_may_hold_subjects` declines a leaflet whose directory keys
leave out every probed subject. The keys describe the live rows, so a
history replay, which can restore subjects they omit, always loads the
leaflet; and a mixed leaflet's keys are no subject interval. Current
writers widen keys over history, so no index they produce reaches the
replay case, and the integration test passes without the bypass.

A unit test on hand-built directory entries checks that the guard
declines at head only for a predicate-homogeneous leaflet, with both
key endpoints inclusive, and loads every leaflet under replay.
@bplatz
bplatz merged commit 596a4fd into main Nov 18, 2026
21 checks passed
@bplatz
bplatz deleted the perf/nlj-leaflet-subject-skip branch November 18, 2026 15:56
bplatz added a commit that referenced this pull request Nov 18, 2026
Brings #2404. next already skips leaflets that hold none of the probed
subjects through `LeafletDirEntryV3::may_hold_keys`, so main's
`psot_leaflet_may_hold_subjects` (and its unit test) is dropped in its
favour; the new integration test passes on next's guard and fails
without it. main's fix to the predicate-run helper lands in next's
`psot_predicate_run`: a replayed leaflet is walked rather than trusted
by `p_const`, the walk no longer adds the start offset twice, and all
three callers pass the replay flag, including next's union probe. The
new test awaits next's async genesis.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance improvement (release notes: Performance)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants