Repository navigation
Conversation
The correlated subqueries of one expression are all validated against the header captured before the decorrelation loop starts (Planner.cpp), but each iteration referenced context.query_plan.getRootNode() as it stood at that iteration. Sibling k therefore referenced a subtree that already contained siblings 1..k-1, and materializeQueryPlanReferences clones each referenced root together with the references inside it, so the node count doubled per sibling. Measured EXPLAIN PLAN output for N sibling scalar correlated subqueries with correlated_subqueries_use_in_memory_buffer = 0, before -> after: N=3 199 -> 91, N=5 847 -> 145, N=8 6895 -> 226, N=12 timeout -> 334, N=20 timeout -> 550. Exponential becomes linear. At N=8 the old plan also reached 68 GB of resident memory, which no memory setting bounded because the cost is 2^N discarded decorrelation-join hash tables. This is reachable at otherwise-default settings: make_distributed_plan = 1 forces correlated_subqueries_use_in_memory_buffer off in SettingsQuirks.cpp, and an unwrapped EXPLAIN under that setting goes from 8045 to 261 lines. The shared root is created lazily and only when the referenced result is not buffered: useMemoryBufferForCommonSubplanResult replaces the referenced step, so every buffered reference needs a root of its own. It is also skipped when a correlated column is missing from the shared root's header, which means the subquery references a preceding sibling's output and needs the grown root. EXPLAIN output with the buffer enabled is byte-identical before and after. The regression test asserts the structure directly, over EXPLAIN PLAN with optimize = 0 so the references are still visible: one referenced root and eight references without the buffer, and eight of each with it. Those counts do not move under the test runner's randomized settings, whereas the optimized plan's line count varies by up to 48 lines because of enable_join_runtime_filters, so the line-count assertion is kept as a coarse blow-up bound only. The test also pins join_algorithm = 'hash' so that a build without this change reddens it in under a second instead of allocating tens of gigabytes through parallel_hash; the plan it measures is the same either way (6895 versus 226 lines). Co-Authored-By: Claude Opus <[email protected]>
The regression test only routed through WHERE, so it exercised addFilterStep and the SCALAR decorrelation context. Reverting the addExpressionStep half of the fix, or dropping shared_input_root from the EXISTS context, left it green. Adds a structural roots/refs assertion for eight sibling scalar subqueries in the SELECT list and for eight sibling correlated EXISTS predicates, and a scaling assertion that doubling the sibling count must not double the optimized plan. The scaling form replaces the absolute line-count bound that the runner's randomized enable_join_runtime_filters made infeasible: the same randomized settings apply to both subquery counts, so their ratio is stable where each count alone is not. Each new arm was verified to fail on a binary without the fix, and each half of the fix was reverted separately to confirm its own arm reddens.
The unbuffered path is gated on the join kind in two independent places: the planner's would_buffer and the optimizer's own flag both require 'right'. So correlated_subqueries_default_join_kind = 'left' reaches the shared referenced root with correlated_subqueries_use_in_memory_buffer left at its default true, which is the blow-up path reachable by changing one ordinary setting. Every pre-existing structural arm pins 'right' and reaches sharing only through an explicit correlated_subqueries_use_in_memory_buffer = 0, so a regression that read the raw buffer setting instead of the join-kind-aware value would have left the whole test green. Verified: making the sharing condition read the raw setting reds only the new arm (1 8 -> 8 8) and leaves the others green. The value arm on the same shape checks that the swapped join layout preserves results, not just the plan shape. Also fix the plan-size comment, which said the optimized plan "must not double" while quoting its own measured ratio of 1.9 and asserting a fourfold bound.
Internal second-model reviewIndependent review passes were run against this diff over four rounds. Findings and verdicts:
|
Pre-PR validation gate
Regression suite: the Randomized runs: Every assertion was mutation-checked. Perturbing any structural count or either size oracle turns the |
|
Workflow [PR], commit [a1e8785] Summary: ✅
AI ReviewSummaryReviewed PR #114938 at The review covered the changed planner entry points, correlated-column preservation, node ownership, cloning and reference remapping, materialization, and buffered-mode exclusion. The added structural and result assertions, together with the recorded before/after measurements, support the fix. Tests were not rerun locally because no ClickHouse binary or configured build is available. Final VerdictStatus: ✅ Approve |
|
cc @KochetovNicolai @vdimir, could you review this? Sibling correlated subqueries in one expression each referenced the input subplan root as it stood during their own iteration, so subquery k referenced a subtree already containing subqueries 1..k-1, and the unbuffered materialization pass then cloned each root with its nested references, doubling plan nodes per sibling. This shares one referenced root per expression, keeping a per-subquery root only when the result is buffered or a correlated column is missing from the shared header. |
Resolves the conflict in src/Planner/PlannerCorrelatedSubqueries.cpp created by master renaming DecorrelationContext::equivalence_class_stack to scope_stack (std::vector<DecorrelationScope>). Both DecorrelationContext constructions keep master's .scope_stack initializer and add this branch's .shared_input_root. The file was reseeded from master 9da5fe3 and this branch's change re-applied, so the delta against master is exactly the shared referenced-input root and nothing else. The two patched Planner.cpp functions (addExpressionStep, addFilterStep) are unchanged on master, so they auto-merged. Verified before merging that master still has the defect: 04915 run against a master binary reports 8 referenced roots for 8 sibling subqueries on the unbuffered, projection, EXISTS and left-join arms, and both plan-growth arms fail; the same file on this branch matches its reference byte for byte.
|
Merged master to resolve the conflict. The only conflict was in Master still has the defect, so this is still worth a look. Run against a master binary at |
Master moved the referenced-input construction of `decorrelateQueryPlan` into `buildCorrelatedDomainPlan`, so the shared-root choice moves there with it. The helper's other caller (`LATERAL` aggregates restoring empty groups) runs with a null `shared_input_root` and keeps building its own root. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`addTotalsHavingStep` decorrelates the correlated subqueries of `HAVING` the same way `addFilterStep` does, but built a referenced root per subquery, so eight siblings still grew the plan to 10210 lines (330 with the shared root). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Merged master to resolve the conflict. Master moved the referenced-input construction into Master's new |
…XISTS join TPC-H Q21 has two sibling correlated subqueries (EXISTS and NOT EXISTS on lineitem), and the test pins `correlated_subqueries_use_in_memory_buffer = 0` under `make_distributed_plan = 1`. Before this PR the NOT EXISTS decorrelation took the outer plan as of the previous iteration as its correlated input, so its `Distinct` domain re-built the whole EXISTS join (3 `Distinct` steps). With the shared correlated input root both subqueries read the same pre-loop input, so the domain is built from lineitem/supplier/nation/orders only (2 `Distinct` steps). On the smaller plan the optimizer also picks a single-stage aggregation after the gather. The new reference is the binary's output byte for byte and equals the CI diff of Fast test on 2a1e26c. Q21 results on generated data (10127 lineitem rows, 41 result rows) are identical between this PR and master, with the test's settings and with the default buffered path. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units47 translation units recompiled, 638 s compile time in total, 47 of them have a recent master baseline. |
CI finish ledger - f459989Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261016-190009 |
Conflict only in the generated 03836_tpch_join_order_plans.reference; took master's side here, the Q21 block is regenerated in the next commit. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master changed the Q21 `DISTINCT` to `Distinct (Shuffle ...)`; this PR still builds the EXISTS join once and shares it with the NOT EXISTS input, so the block keeps 2 `Distinct` and 5 `default.lineitem` reads (master: 3 and 7). Only the Q21 block differs from master's reference. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 5a40199Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261031-153005 |
The only conflict was in src/Planner/PlannerCorrelatedSubqueries.cpp, next to master's `uses_correlated_domain` (NULL outer values in the correlated domain). Both members of `DecorrelationContext` are kept, and `buildCorrelatedDomainPlan` sets `uses_correlated_domain` before it picks the shared or a new referenced root. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The header comment on SharedCorrelatedInputRoot already says why a buffered reference needs its own root; the call site keeps only the correlated-column condition. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a query plan growing exponentially with the number of correlated subqueries in one expression when
correlated_subqueries_use_in_memory_bufferis disabled orcorrelated_subqueries_default_join_kindis'left', which made such a query spend minutes in planning or run out of memory. The plan now grows linearly with the number of subqueries.Description
On 26.8.18.2,
EXPLAIN PLANof aWHEREwith six sibling correlated subqueries is OOM-killed at an8 GB limit when
correlated_subqueries_default_join_kind = 'left'.Several correlated subqueries in one expression are decorrelated one at a time. Each referenced the
input subplan root as it stood during its own iteration, so subquery
kreferenced a subtreealready containing subqueries
1..k-1. When the referenced result is not buffered, thematerialization pass clones each referenced root together with the references nested inside it, and
the node count doubles per subquery.
Measured on master with
correlated_subqueries_use_in_memory_buffer = 0: 565 plan steps at N = 4rising to 9445 at N = 8, i.e.
2^N, and executing N = 8 exceeds a 20 GB memory limit. The buffer isalso off whenever
correlated_subqueries_default_join_kind = 'left', andmake_distributed_plan = 1forces it off (
SettingsQuirks.cpp).Found as a
Stress test (arm_tsan)hung check, where a cancelledINSERT ... SELECTsat 426 s inplan optimization with 1,670,597 plan nodes (N of about 17, for a
SELECTrepeating one correlatedalias 20 times). CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114072&sha=08c0cd1e799e63d9cf42a2402776fa2ce09c9bc7&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
The fix creates one referenced root per expression and reuses it for every sibling, in the
SELECT,WHERE/HAVINGandHAVING ... WITH TOTALSplanner paths. It is used only when the in-memory bufferis not in play, because the buffer optimization replaces the referenced step in place, and only when
the shared root's header already carries the subquery's correlated columns. Both cases fall back to
today's per-subquery root. After the fix the same plans are 306 steps at N = 8 and grow linearly.
The default buffered path is untouched, and results are unchanged over both settings values.
Cancellation inside the materialization pass is still not checked; with the plan now linear that
pass takes milliseconds, so it is not addressed here.
Workflow [PR]
Sync PR [sync-upstream/pr/114938]