Skip to content

perf(query): probe bound objects in the predicate's POST partition - #2374

Merged
bplatz merged 8 commits into
mainfrom
perf/bound-object-probe-post
Nov 13, 2026
Merged

bplatz merged 8 commits into
mainfrom
perf/bound-object-probe-post

Conversation

@bplatz

@bplatz bplatz commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A nested-loop join that probes a bound object (?s <p> ?o, with ?o bound by the driving side) got slower the more edges that object has under other predicates.

On the WGPB Wikidata benchmark (21.1B triples) this is what made the small-row-goal rule from #1959 a net loss. Where the rule picks a nested loop over a hash join, 81 of the 260 affected queries were slower than with the hash join, several by more than 10x.

Root cause

The bound-object lane (for_each_object_probe_match, shared by the nested-loop join and OPTIONAL) walked OPST. OPST orders rows by (o_type, o_key, o_i, p_id, s_id), so all of an object's rows sit together whatever their predicate. The lane found the object's run and then stepped over every row in it, checking p_id one at a time. Profiles of the worst queries put 49–65% of server CPU in that loop.

Fix

Read the predicate's POST partition instead. POST orders rows by (p_id, o_type, o_key, o_i, s_id), so among the predicate's ref rows an object's run is exactly its matches.

  • Only leaves and leaflets that can hold one of the probed objects are read.
  • Each leaflet's o_key column is binary-searched per object.
  • For a fixed predicate and object, both orders visit rows by (o_i, s_id), so row order is unchanged.
  • The overlay merge and novelty injection are as before.

The join-strategy decision is not touched: every plan is the same as on main.

One case needs care. A leaflet's type constant describes its live rows only, so a history replay can bring back a ref of a type the constant no longer reports (a mixed-type predicate whose refs in that leaflet were later retracted). Under replay the lane does not skip by the constant. It does keep pruning by the leaflet's own first and last keys: both writers widen those over the history the leaflet keeps (#1624), as the OPST lane on main already relied on, so a replayed leaflet is read only when one of the probed objects falls in its range. An index written before #1624 whose leaflets no incremental build has rewritten has narrow keys, and this lane is no safer there than the OPST lane was. The generic cursor's handling of the type constant is a separate, existing problem and is not changed here.

The walk reads POST keys and takes the branch from its caller; a debug assertion checks it is the graph's POST branch.

Results

Same machine (r7a.8xlarge) and ledger, main against this branch, one warm-up and three measured runs per query, medians. Plans are identical and response bodies byte-identical for every query in both sets.

Full benchmark, 850 queries at LIMIT 1000:

main this PR
Total 107.85 s 68.97 s
Geomean 22.63 ms 17.39 ms
Median 16.90 ms 13.05 ms
260 queries where the rule fires 77.38 s 38.98 s
590 other queries 30.47 s 29.99 s

The 260 queries at other limits (the rule fires at 1024 and below):

LIMIT main this PR
1 61.44 s 35.56 s
10 70.90 s 37.03 s
100 75.53 s 37.72 s
1024 79.73 s 38.93 s
1025 58.49 s 46.34 s

On main the rule costs 21.2 s on these queries (58.49 s without it, 79.73 s with it). With this change it saves 7.4 s (46.34 s to 38.93 s). LIMIT 1025 improves too, because those plans still contain nested loops the cost model chose on its own.

Not addressed

  • 27 of the 260 queries are still more than 1.25x slower under the nested loop than under the hash join, 2.54 s in total. Most join two patterns on a shared string-literal object, which this lane (refs only) does not serve.
  • One query is 5–11 ms slower with this change (about 42 ms to 47–54 ms) in both runs. The cause is not established.

Tests

batched_object_join_reads_refs_among_literals covers a predicate whose leaflet holds numbers, strings, refs and language-tagged strings, so its object keys are not ordered as a whole. It checks four states: indexed, with novelty, reindexed, and reindexed but queried at the earlier t, in SPARQL and JSON-LD. Every case also asserts that the lane's span fired, so none can pass through the generic scan.

batched_object_join_reads_refs_among_literals_across_small_leaflets runs the same phases over an index of two-row leaflets, two to a leaf, so an object's run spans leaflets and leaves and the walk jumps between leaves.

Two mutations each fail it: dropping the restriction to the predicate's ref rows, and applying the leaflet's type constant under replay.

The bound-object lane shared by the nested-loop join and OPTIONAL walked
OPST, where all of an object's rows sit together whatever their
predicate, and stepped over each one to find those of the probed
predicate. Its cost tracked the object's edges under other predicates.

Read the predicate's POST partition instead. Its rows are ordered by
(o_type, o_key), so an object's run among the ref rows is exactly its
matches, and each leaflet's key column is binary-searched per object.
Join plans, results and row order are unchanged.

A history replay can bring back rows that a leaflet's type constant and
own keys do not describe, since both cover live rows only; the lane then
bounds the leaflet by the leaf's routing keys.
@bplatz bplatz added area:query Query execution, planning, fast paths, overlay, result formatting performance Performance improvement (release notes: Performance) labels Nov 13, 2026
@bplatz
bplatz requested a review from a team November 13, 2026 02:36
The bound-object lane took refs only, so a join on a shared string
object (two patterns meeting at the same label or identifier) opened a
scan per left row. The lane now keys a string term on the exact
(o_type, o_key) the per-row scan seeks for it, groups a window's objects
by type, and walks the predicate's POST rows once per type. Overlay ops
are held in (o_type, o_key, s_id, o_i) order to match. Other literals
compare across datatypes and stay on the per-row scan; OPTIONAL's use of
the lane stays refs-only.

A flush built every combined row before returning any, so an object with
a million subjects cost a million rows under a LIMIT that reads a
thousand. The flush now keeps the matched subject ids per distinct
object, and rows are built a batch at a time in the same left-row order.
A consumer that stops early leaves the rest unbuilt.

The probe reads only the leaflets that hold its objects, so its first
flush window is taken in steps: it opens at the row budget and widens 8x
up to the window a budgeted schedule would have used. A LIMIT the first
few left rows satisfy stops there, and no left row is read that the
single window would not have read.

The lane charges fuel at the flush for the matches it read, before
inline filters and whether or not a LIMIT lets them all become rows.
Joins without an inline filter are charged what they were.
A batched join stores the left batch its accumulated rows refer to and
releases it at the flush. The store was a deep copy, taken again by every
window that started inside the same batch, so a 25,000-row scan batch was
copied once per flush: about half a millisecond each, whatever the window
held. A small first window under a LIMIT paid that several times before
producing a row.

The current left batch is now held in an Arc and a window takes a
reference to it.
A bound-object flush reads each object's matches whole before the first
row is built, so a LIMIT on a string shared by many subjects waited for
the string's entire run, where the per-row scan it replaced would have
stopped after a batch. A string object with more than 65,536 live
matches is now left out of the flush: each left row on it opens the
per-row scan in its turn, in the same left-row order, and the walk does
not read a leaf or leaflet that holds only such objects. Which path an
object takes follows from its live match count, so pages stay slices of
the full drain. Refs are still read whole. The matches read before an
object is handed over are charged fuel.

The row builder ran its inline operators over every pending match
without a cancellation check, so a filter that rejects most of them
could hold a cancelled query for a whole flush. It now checks every
4,096 matches on that path.

A probe reconciled against every type's novelty at once. It now takes
only the ops of the type it reads, and none when that type has no
novelty, so a ref probe (OPTIONAL's included) no longer allocates or
searches over string ops.

@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 the right index for this probe, and a nice, contained change. ?s <p> ?o with ?o bound is a POST lookup everywhere else (IndexType::for_query, and the comment at binary_scan.rs:725 explains why), so the lane walking OPST was the odd one out. Because #1973's OPTIONAL lane (95f7d632d) shares for_each_object_probe_match, one fix covers both. Claude's box A/B reproduces the win on a hub object, about 49× warm and 10× cold, with identical results and row order on every shape it tried. A few headline notes:

(1) One element shouldn't merge as-is. At a past t the lane stops pruning replaying leaflets by their own keys, and a sparse probe gets about 8× slower than main. Details and a short fix are below.

(2) The lane walking OPST is one instance of a class, "a lane picks its own index order and ignores a key IndexType::for_query would use". collect_subjects_for_predicate_object_ref_opst (fast_star_const_order_topk.rs:154) still walks OPST for a bound ?s <p> <ref>, the same shape as this one. In history mode, pick_order (binary_history.rs:152) sends a bound predicate + object to PSOT. The class fix would be lanes asking for_query for their order rather than hard-coding one. That's not for this PR; the point fix is right here.

(3) Merge order. This and #2373 conflict in for_each_object_probe_match, mechanically. I'd land #2373 first and have this adopt its replays_history / o_type_const_for helpers on rebase; this adds a sixth hand-written copy of the predicate #2373 consolidates. My own #2214 extends this same function, so I'll rebase it onto this one and point its union callers at POST.

Good to merge once the replay prune is back.

Full review below:


✅ Approving to unblock: please get the replay prune (B1, join.rs:3410) in before merging.

This is really nice, @bplatz. Reading the predicate's POST partition is the right index for the bound-object probe, and the walk is carefully built: one routed range with a jump past empty leaves, the (p_id, IRI_REF) run narrowed before the o_key search so mixed-type POST leaflets stay correct, and the overlay merge untouched. Claude's A/B on a 6.4M-triple ledger confirms the head-t story. A hub object goes from 2,588 µs to 53 µs warm and from 36.5 ms to 3.6 ms cold, OPTIONAL gets the same win, and sparse probes are 5–8% faster or within noise. Results match main in all 29 cells. The one must is B1. At a past t the replay branch drops the leaflet's own key prune on a premise 25e0721c4 retired, and sparse probes regress 2.4× to 7.9×. The fix is a few lines and keeps your test green. O1 and O2 are small hardening items.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ The lane now agrees with IndexType::for_query and the generic scan. It reuses ObjectProbeOps, ProbeLanePlan and branch_or_none rather than adding a parallel mechanism. ⚠️ The replay predicate is hand-written again (#2373's replays_history consolidates it), and the walker's branch order is implicit (O1).
  • Performance (speed first, memory second): 🔴 CRITICAL at a past t: sparse bound-object probes regress 2.4× to 7.9× (B1). At the head it's a large win on hubs (about 49× warm, 10× cold), about 5× with novelty, and 5–8% better or within noise on sparse and long-run shapes. No new allocation on the per-row path.
  • Deployment targets: ✔ n/a. Query-engine internals only, with no I/O pattern, threads or process-lifetime state added. It's host-neutral across the embedded library, server and wasm32, and wasm32/wasm-smoke are green on this head.
  • Testing: ✔ The new test runs in grp_misc and passed in CI on 8b7beab06. Claude re-ran it on a box with each of the body's two mutations, and both fail. Dropping the (p_id, IRI_REF) restriction fails at indexed/topic-sparql, and applying o_type_const under replay fails at reindexed, at the base t/tag-sparql. It passes with the B1 fix, and it also passes against main's OPST lane, so it guards the new lane's hazards rather than reproducing a bug on main. ⚠️ The fixture is a single leaflet, so the leaf jump, runs that span leaflets, and the replay prune aren't exercised (O2).
  • Conventions: ✔ The commit body is multi-line and explains the replay case. The PR title is self-describing for release notes. clippy and fmt are green in CI.

Verified at branch HEAD: CI run 43353392971 on 8b7beab06 (test, clippy, fmt, testsuite-sparql, wasm32, wasm-smoke green); a box A/B of main against this head over 35 cells (6 warm rounds plus 4 cold), with identical results in every verify cell; the mutation check above; and a git merge-tree against #2373, #2368, #2376, #2201 and #2214.

Approving so you can merge once B1 is in. O1 and O2 are worth considering while you're there.

Comment thread fluree-db-query/src/join.rs Outdated
// rows; a replay can bring back a retracted ref they do not cover
// (a mixed-type predicate whose last ref in the leaflet is gone),
// so only the leaf's routing bounds it then.
let in_leaflet = if needs_history_replay {

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 (CRITICAL, performance). At a past t, a leaflet that replays history is no longer pruned by its own key range. Sparse bound-object probes get 2.4× to 7.9× slower than on main.

Under needs_history_replay, in_leaflet = in_leaf.clone() hands the leaflet every object routed to its leaf. Every leaflet of the predicate in that leaf with history newer than to_t is then decoded with ColumnProjection::all() and run through replay_leaflet_at_t. That replay isn't cached, so it runs again on every query. That's up to leaflets_per_leaf replays per probed object instead of about one. Main's OPST lane kept the leaflet's own key prune under replay (join.rs:3316-3330 at 467f0da4d).

The comment's premise holds for o_type_const but not for the keys. Since 25e0721c4, both writers grow a leaflet's own first/last keys over the history it keeps: LeafWriter::commit_history_entry → flush_leaflet in leaf.rs, and widen_leaflet_keys_over_history in incremental_leaf.rs. build_leaf_from_group then re-derives the leaf header, which is the bound this falls back to, from those same leaflet keys. So the leaf bound isn't any safer than the leaflet's own keys, only wider. On an index written before my #1624 (8ac57d75a/25e0721c4) whose leaflets no incremental has rewritten since, the leaf bound only partly helps. It catches a retracted key that falls between two leaflets inside the leaf, but not one past the leaf's own ends, which came from the same narrow keys. Main's OPST lane already relied on the leaflet's keys here. If you keep the prune, a sentence in the PR body saying the lane relies on the writers' widening since #1624 would make that explicit.

Claude measured it on a c7i.4xlarge box: main 467f0da4d against this head, six interleaved rounds, identical results. The setup was a predicate with 4.2M POST rows over 2M ref targets, about 2,100 retractions spread across it, a reindex, then a read at the pre-retraction t. Eight bound objects went from 12.4 ms on main to 97.9 ms here (7.9×), and 64 went from 86.9 ms to 209.3 ms (2.4×). Reads of 1,024 objects, which touch every leaflet either way, didn't move, and none of the head-t shapes regressed.

Suggested fix: keep the type constant off under replay and keep the key prune on.

            // `o_type_const` describes live rows only, so a replay can't skip by
            // it; the leaflet's own keys span the history it keeps (25e0721c4).
            if !needs_history_replay && entry.o_type_const.is_some_and(|ot| ot != iri_ref) {
                continue;
            }
            let first = read_ordered_key_v2(RunSortOrder::Post, &entry.first_key);
            let last = read_ordered_key_v2(RunSortOrder::Post, &entry.last_key);
            let in_leaflet = match post_o_key_bounds(&first, &last, want) {
                Some(bounds) => objs_within(objs, in_leaf.clone(), bounds),
                None => continue,
            };

After #2373 lands, the first check becomes entry.o_type_const_for(needs_history_replay).is_some_and(|ot| ot != iri_ref). Claude reran the box with this change, as a 3×3 Latin square against main and this head over six rounds. Eight objects at the past t came back to 12.2 ms, against 11.9 ms on main in that run: about 2% behind, consistently, and not chased further. 64 objects came back to 83.0 ms against 83.7 ms. The past-t hub read ended up 2.7× faster than main (8.5 ms → 3.2 ms). Results stayed identical to main in all 29 cells, and batched_object_join_reads_refs_among_literals still passes with the change.

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 b1edac4. Type constant off under replay, key prune kept; the body now says the lane relies on the writers' widening since #1624. Not re-measured here.

/// or the edges the object has under other predicates (which an object-major
/// OPST walk steps over row by row). Shared by the nested-loop join's
/// bound-object lane and OPTIONAL's.
pub(crate) fn for_each_object_probe_match(

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.

This is more of a suggestion than a must. for_each_object_probe_match now walks POST, but it takes branch: &BranchManifest from the caller, and nothing ties that branch to an order. Both callers here fetch RunSortOrder::Post (join.rs:2839, optional.rs:501), so it's right today. My #2214 adds two more callers, union probes over several graphs, that fetch OPST branches (join.rs:3104 and :3184 at 29026b2f2). A rebase that keeps them would hand OPST leaves to a POST walker with no compile error, just wrong rows. I'll switch them when I rebase #2214, but we could make the mistake impossible here. The function could resolve its own branch (branch_or_none(store, ctx.binary_g_id, RunSortOrder::Post, merging), with callers passing merging). Minimally, it could debug_assert! that branch is the one store.branch_for_order(ctx.binary_g_id, RunSortOrder::Post) returns. 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 b1edac4 (debug assertion that the branch is the graph's POST branch).

/// leaves its leaflet holding strings alone: a query at the earlier `t` needs
/// rows that neither the leaflet's type constant nor its keys describe.
#[tokio::test]
async fn batched_object_join_reads_refs_among_literals() {

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.

Not a big deal, but the fixture fits in one leaflet per predicate, so three parts of the new walk never run here. Those are the leaf jump (join.rs:3386-3392), an object run that spans leaflets or leaves, and the replay prune from the comment above. Claude's box harness checked the first two against main on a 6.4M-triple ledger and got identical results, so they're right today. A variant reindexed with IndexerConfig::default().with_leaflet_rows(2).with_leaflets_per_leaf(2) (as it_fastpath_1652_regression.rs:520 does with with_leaflet_rows) would pin them. If the lane also logged leaflets_read / leaflets_replayed / leaflets_skipped the way the SPOT star walk does (join.rs:4024-4031), the past-t case could assert the prune, not only the rows. Minor and non-blocking, but 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 72ea436 (small-leaflet variant). The prune counters are not logged or asserted; the past-t case pins rows only.

The probe walk called its visitor once per matching row. With the match
cap checked inside that call, a flush that reads many matches for a few
objects paid for it on every row: a join whose flush reads 1.6 million
matches went from 3.9 to 8.7 ns a match and ran about 1.7x slower.

The walk now passes each object's subjects a leaflet run at a time: the
stored column slice when the overlay has nothing to reconcile for the
object, otherwise the rows it keeps. The flush checks the cap once per
run and copies the run in one step. An object is still held or streamed
by its total live match count, and the fuel charged for a streamed
object is unchanged. OPTIONAL's use of the walk takes the same slices.
Under history replay the bound-object walk bounded a leaflet by its leaf's
routing keys, so every leaflet of the predicate in the leaf with newer
history was decoded and replayed per probed object. Only the type constant
describes live rows alone; both writers widen a leaflet's keys over the
history it keeps, so the key prune holds under replay. A debug assertion
checks the walk is handed the graph's POST branch.
An object's run spans leaflets and leaves and the walk jumps between
leaves, which the one-leaflet fixture never exercised.
…be-post

# Conflicts:
#	fluree-db-query/src/join.rs
@bplatz
bplatz merged commit 29069fb into main Nov 13, 2026
19 checks passed
@bplatz
bplatz deleted the perf/bound-object-probe-post branch November 13, 2026 20:12
bplatz added a commit that referenced this pull request Nov 13, 2026
Brings #2296, #2309, #2313, #2315, #2316, #2317, #2367, #2368, #2369,
#2373, #2374, #2378 and #2379.

Ports onto next:

- #2374 (bound-object probe reads POST): main's POST walk and per-type
  flush replace next's OPST walk. The lane keys (o_type, o_key), so next's
  triple-term handles are one more covered type (object_probe_covers takes
  TripleTermDict) rather than a flush per type; a term's matches are read
  whole, as a ref's are. The wildcard cursor still keys refs only. Pooled
  graphs decline through dedicated_branch(Post); o_i is 64-bit. Next's
  pair join keys its subject through the shared LaneKey.
- #2373 (leaflet type constant under replay): replays_history and
  o_type_const_for beside next's may_hold_keys; the row-labelling lanes
  take main's const-unless-replaying form over next's always-read-column.
- #2368: the cyclic join decodes for eager callers with next's list index
  sentinel; both reasoning tests kept (cyclic operator and pair lane).
- #2317 (GRAPH streams): main's work queue and InnerStream with next's
  pooled-graph pruning before each enumerated graph.
- #2315: list predicates are an ordered set in next's multi-ledger view;
  the annotation edge probe stays deleted (no bundle lane on next).
- #2296 (rebase reads its new line): ported onto next's fenced resets,
  erasure checks and peer sync (follow_record keeps next's unchanged-head
  arm); a non-fast-forward rebase moves head and index in one fenced
  reset.
- Main's new tests: async genesis_ledger, graph_source_store for mapping
  writes, leaf_rows for leaflets-per-leaf, storage lock off for two file
  instances. New pattern/function matches cover TermComponents and the
  triple-term functions; AnnotationTarget arms dropped.
aaj3f added a commit that referenced this pull request Nov 13, 2026
Brings in main through f42ea37, with #2374, which moves the one-graph
bound-object probe from OPST to POST, hands its matches over a run of
subjects at a time and builds rows from them on demand. join.rs and
optional.rs conflicted:

- The one-graph flush, the walk and the row builder (next_object_probe_step)
  are main's.
- The union object probe keeps its member walk, which hands over each
  match's list position for the union's fact identity, as
  for_each_object_probe_match_by_fact. Its matches, one per fact of the union,
  now land in main's per-object subject lists, so the union and the one graph
  share main's row building and charging. It probes ref objects; a left row
  on a string object, which main's lane now keys too, goes to the per-row
  scan, which reads the union.
- optional.rs takes main's call of the POST walk.
aaj3f added a commit that referenced this pull request Nov 13, 2026
The batched probes read the index through LeafScan::load_leaflet: the
subject probe and the subject star, the bound-object walk (POST, #2374's
design) and the union's by-fact walk, the semijoin's index walk and
scan_matches. They charged their matched rows, but not the leaflets they
read, where the scan's cursor charges each one. load_leaflet now takes the
query's tracker and charges one index touch per leaflet (charge_leaflet: an
inlined enabled check, the charge itself out of line), so a probe that
loads a leaflet is charged by construction.

it_fast_path_fuel gains a batched subject probe and a bound-object probe:
with the charge removed, the 3-row leaflets cost what the left scan's
leaflets alone add (a gap of about 1, against 1.5 wanted).
aaj3f added a commit that referenced this pull request Nov 13, 2026
Since #2374 the bound-object lane keys string terms, and over a union the
probe sent a left row on a string object to the per-row scan after
keying it, which cost a union string join 2.6% more instructions than
before that merge (790M to 811M a query at 7,500 rows). The members share
one store and its dictionary novelty, so a string's key is one key in
every member: the union's walk now takes the object type and walks any
type the lane keys, keeping one match per fact as it does for refs.

a_string_object_joins_across_a_union_once_per_fact now runs through the
walk: with its fact dedup dropped, ex:b, whose alias both graphs hold,
answers twice on the indexed fast-path run.
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