Skip to content

perf(query): bound subquery buffering and stream independent scopes - #1828

Merged
bplatz merged 4 commits into
mainfrom
perf/subquery-bounded-streaming
Sep 15, 2026
Merged

bplatz merged 4 commits into
mainfrom
perf/subquery-bounded-streaming

Conversation

@bplatz

@bplatz bplatz commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

BSBM BI Q8 can retain its entire offer-level intermediate at an anonymous group boundary, then copy matching and merged rows before the outer filter and aggregation consume them. The reported 200M-triple concurrent replay exhausted server memory. This change preserves the scope boundary while removing that whole-result buffering where it is unnecessary.

Stacked on #1827 (fix/subquery-unbound-join-keys) so the combined performance and correctness changes can be tested together.

Changes

  • Stream a subquery when its parent is structurally guaranteed to be the single empty solution. This uses an explicit operator contract, never an estimated row count.
  • Stream correlated subqueries with their existing pruning seeds. Keep independent grouping, DISTINCT, ordering, OFFSET, and LIMIT semantics in the shared inner-plan construction.
  • Resume reusable hash-join probes across output batches of at most 1,024 rows, without copying whole match sets or buffering the full join product. Preserve duplicate solutions, partial/unbound keys, poisoned-key behavior, and reconciliation of other shared variables.
  • Account retained input batches, materialized rows/indexes, and output capacity for their lifetimes. Release only owned charges on close, cancellation, or failure. Close the inner plan before building the materialized index to avoid overlapping those allocation phases.

Planner join ordering and selectivity thresholds are unchanged. The implementation applies to subquery execution generally, without recognizing Q8-specific predicates or rewriting SPARQL groups.

Validation

  • 2,918 passing tests across the query library and API query, SPARQL, history, reasoning, policy, and Cypher suites.
  • Final focused rerun: 7 operator tests and 32 API subquery tests passed.
  • Added coverage for bounded output, duplicate and empty-schema multiplicity, partially bound probes, cancellation/close cleanup, memory-budget errors, and Q8's original versus flattened group shape on both novelty and indexed data.
  • Query library/test-target and SPARQL API test-target Clippy passed with warnings denied; formatting and diff checks passed.

Local performance comparison

Compared optimized dev-fast builds of parent 5529b53ea and this change, running sequentially on the same synthetic Q8 fixture. Each process runs one initial request followed by two measured warm requests; values below are the median of those two warm requests.

Offers Parent This change
24,000 57.1 ms 52.9 ms
480,000 1.21 s 1.13 s

At 480,000 offers, sampled process RSS during the query window fell from 4.47 GiB to 3.76 GiB, with roughly 3.6 GiB attributable to the resident in-memory fixture baseline. The additional RSS rise was approximately 0.88 GiB versus 0.18 GiB. The flattened diagnostic stayed around 3.8 GiB. Whole-process peaks were approximately 5.15 GiB in both builds during fixture setup; these are query-window measurements, not a lower lifetime RSS peak or an exact live-heap census. Tiny-query timings remained around 0.4 ms in both builds. Probe results were checked against independently calculated vendor ratios.

The original unchanged 200M-triple / 32-client replay has not been rerun. These local results do not establish a production OOM pass. Shared concurrency memory admission remains separate work, and allocation accounting still uses approximate binding-size estimates.

Follow-up: #1841 (memory accounting ignores heap behind bindings)

Stream identity-seeded scopes and correlated subqueries while preserving independent solution modifiers. Resume materialized join probes without copying whole match sets, and account retained buffers for their lifetimes.
@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 12, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 12, 2026 18:35
Base automatically changed from fix/subquery-unbound-join-keys to main September 14, 2026 20:32
Keep the resumable match cursor from this branch and carry main's
partial-key change into it: the cursor stores the bound key columns
and compares only those.

@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 looks very good & no top-level notes from me!


I'm quite happy with this one. Replacing the whole-join-product buffer with a resumable cursor plus a hard 1,024-row output cap is the right shape, and tying every charge to a Drop impl is what makes it safe — I went looking specifically for charge/release asymmetry on early LIMIT, cancellation mid-batch, and an error mid-probe, and there's nothing to find because none of those paths has to remember to release. Deleting the error-path close is caught by three tests, including one that pins the exact post-error counter value. I also chased the streaming gate hard, since "structurally the single empty solution" is the kind of claim that's usually an estimate in disguise, and it isn't: is_identity_seed has one true implementation and nothing delegates it, so a VALUES or BIND above an EmptyOperator can't sneak through. On the numbers, I could only confirm what you already said — at 24k and 144k offers in debug builds the RSS difference is 0.3–0.5% and warm time is ~2% better, which matches your own note that the fixture dominates and the whole-process peaks were equal. No regression; the win itself still needs the 200M replay, and you say so plainly in the body, which I appreciate.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends the Operator trait with one honest predicate rather than adding a parallel dispatch; MatchCursor generalizes the existing probe instead of special-casing Q8; the indexmap dependency is justified by the resumable-by-position requirement and is the reason Cargo.lock moved.
  • Performance (speed first, memory second): ✔ 2% faster warm Q8 at both fixture sizes, no measured RSS regression, and the structural retention fix is the point. ⚠️ per-row capacity recomputation at :656 is O(schema width); unbound.contains at :243 is a linear scan inherited from #1827.
  • Testing: ✔ seven new unit tests covering bounded output, empty-schema multiplicity, duplicate-bucket resume, budget enforcement, and close/cancel release, plus a Q8-shaped API test wired at grp_query_sparql.rs:51-52 with an execution-independent ratio oracle. A mutation on the error path goes red in three of them.
  • Conventions: ✔ multi-line conventional commit, no AI attribution, cargo fmt --all -- --check and cargo clippy -p fluree-db-query --all-targets -- -D warnings both clean.

Verified locally at branch HEAD 3ce528455: 8 fluree-db-query subquery unit tests pass; removing the error-path release at subquery.rs:525-527 fails 3 of them; q8_scope_memory_probe measured under /usr/bin/time -l against parent 5529b53ea at 24,000 and 144,000 offers; git merge-tree --write-tree origin/main 3ce528455 is conflict-free, though subquery.rs at this PR's base already carries #1827's +118/−11, so this one genuinely has to follow #1827.

Approving so you can merge when ready, but maybe worth folding in the comment on :570 and the capacity tweak on :656 first — both are a few lines.

(0..self.in_schema.len()).map(|_| Vec::new()).collect();
// Charge the output columns as they grow, and release on handoff.
// Tiny results do not reserve a full 1024-row window.
let mut output_memory = MemoryCharge::new(ctx);

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.

fluree-db-query/src/subquery.rs:570 — optional. output_memory is released when next_bounded_batch returns, but the Batch it accounted for lives on downstream, so the context counter under-reports live memory by up to one in-flight batch per subquery operator. I think that's the right call — nothing else charges the batches it receives, and charging them here without a matching release would be worse — but the comment says "release on handoff" without saying that the handoff is where the accounting deliberately stops. Could you extend it to name that? One sentence, and it saves the next person the twenty minutes I spent convincing myself it wasn't a leak in the other direction.

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.

Extended the comment in 4b921f9 to say accounting stops at handoff deliberately and under-reports by at most one in-flight batch per subquery operator.

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 4b921f9

}
let capacity: usize = columns.iter().map(Vec::capacity).sum();
if capacity > output_capacity {
output_memory.add(

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.

fluree-db-query/src/subquery.rs:656 — optional. columns.iter().map(Vec::capacity).sum() runs per emitted row, so the capacity recomputation is O(schema width) per row where the rest of the loop is O(1). It's a handful of pointer reads and I don't think it's measurable — my Q8 runs came out 2% faster, not slower — but on a wide schema at a million rows it's real work for an estimate that only changes on geometric growth. Tracking the previous capacity per column, or only recomputing when emitted crosses a power of two, would get it to amortized O(1). 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.

Done in 4b921f9: the sum is recomputed only when a column reallocates, so it's amortized O(1). There was no test covering output-batch charging at all (disabling the charge kept every test green), so I added output_batch_growth_is_charged_against_budget, which fails with the charge skipped.

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 4b921f9

Comment thread fluree-db-query/src/subquery.rs Outdated
.iter()
.zip(inner_key)
.enumerate()
.all(|(col, (p, s))| p == s || unbound.contains(&col))

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.

fluree-db-query/src/subquery.rs:243 — optional, pre-existing. unbound.contains(&col) is a linear Vec scan in the innermost comparison of the partial probe. This came over from #1827 unchanged, so it isn't yours in this PR — but since you're rewriting this code anyway, a u64 bitmask would make it a single &. Same note I left on #1827; folding it in here instead would be just as good.

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.

Already covered by #1827's final commit (288da4f), which came in with the main merge: Partial now precomputes the bound column indices and compares only those, so the inner loop has no contains. The remaining one runs once per probe setup over the join-key count.

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 288da4f

}
}

fn add(&mut self, ctx: &ExecutionContext<'_>, bytes: usize) -> Result<()> {

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.

fluree-db-query/src/subquery.rs:141-146 — optional. BINDING_EST_BYTES is size_of::<Binding>(), so every charge in this file ignores the heap owned behind each binding — a query whose bindings carry long strings is accounted far below its real footprint. You name this in the PR body ("allocation accounting still uses approximate binding-size estimates"), so this isn't a surprise, and fixing it is clearly out of scope here. This one I'd genuinely punt, but to an issue rather than to memory: the whole budget mechanism inherits the approximation, and it'll be easier to reason about when someone can point at a ticket.

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.

Filed #1841.

.is_none_or(|n| n >= SUBQUERY_MATERIALIZE_MIN_PARENT_ROWS))
};

let stream_identity = join_mode && child.is_identity_seed();

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.

fluree-db-query/src/subquery.rs:391 — praise. I went looking for the hole in this gate — specifically a parent that is structurally {} at plan time but bound at runtime through VALUES or BIND above it — and there isn't one, because is_identity_seed has exactly one true implementation (EmptyOperator, seed.rs:237), the trait default at operator.rs:61-68 is false, and no operator delegates it to its child. A VALUES above an EmptyOperator is a different operator and inherits false. "An explicit operator contract, never an estimated row count" is exactly right, and the doc comment warning that zero-column operators must keep the default is what makes it stay right.

/// Own only this operator's allocation charges. Dropping a batch or a complete
/// materialization releases its charge; never subtract a context-wide delta
/// across streaming yields, since downstream operators also use that counter.
struct MemoryCharge {

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.

fluree-db-query/src/subquery.rs:128-152 — praise. Tying the charge to Drop rather than to explicit release calls is what makes the error paths uninteresting, and that's the whole reason this PR is reviewable. Worth keeping in mind as the pattern for the concurrency-admission work the body mentions as separate.

}
Ok(())
}
.await;

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.

fluree-db-query/src/subquery.rs:869-871 — praise. Closing and dropping the inner plan before building the materialized index, with a comment saying why, is the kind of thing that gets "simplified" away in six months. The comment earns its place.

Recompute the output-column capacity sum only when a column reallocates,
instead of on every emitted row. Document that output accounting stops at
batch handoff by design, and cover output-batch charging with a budget test
that fails when the charge is skipped.
@bplatz
bplatz merged commit 6a2a976 into main Sep 15, 2026
16 checks passed
@bplatz
bplatz deleted the perf/subquery-bounded-streaming branch September 15, 2026 02:15
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 bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants