Repository navigation
perf(query): bound subquery buffering and stream independent scopes - #1828
Conversation
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.
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
left a comment
There was a problem hiding this comment.
@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
Operatortrait with one honest predicate rather than adding a parallel dispatch;MatchCursorgeneralizes the existing probe instead of special-casing Q8; theindexmapdependency is justified by the resumable-by-position requirement and is the reasonCargo.lockmoved. - 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:656is O(schema width);unbound.containsat:243is 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-52with 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 -- --checkandcargo clippy -p fluree-db-query --all-targets -- -D warningsboth 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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| } | ||
| let capacity: usize = columns.iter().map(Vec::capacity).sum(); | ||
| if capacity > output_capacity { | ||
| output_memory.add( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| .iter() | ||
| .zip(inner_key) | ||
| .enumerate() | ||
| .all(|(col, (p, s))| p == s || unbound.contains(&col)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
| } | ||
| } | ||
|
|
||
| fn add(&mut self, ctx: &ExecutionContext<'_>, bytes: usize) -> Result<()> { |
There was a problem hiding this comment.
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.
| .is_none_or(|n| n >= SUBQUERY_MATERIALIZE_MIN_PARENT_ROWS)) | ||
| }; | ||
|
|
||
| let stream_identity = join_mode && child.is_identity_seed(); |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
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
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
Local performance comparison
Compared optimized
dev-fastbuilds of parent5529b53eaand 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.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)