Skip to content

Share one referenced input subplan across sibling correlated subqueries - #114938

Open
groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-correlated-subquery-sibling-plan-blowup
Open

groeneai wants to merge 11 commits into
ClickHouse:masterfrom
groeneai:fix-correlated-subquery-sibling-plan-blowup

Conversation

@groeneai

@groeneai groeneai commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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_buffer is disabled or correlated_subqueries_default_join_kind is '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 PLAN of a WHERE with six sibling correlated subqueries is OOM-killed at an
8 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 k referenced a subtree
already containing subqueries 1..k-1. When the referenced result is not buffered, the
materialization 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 = 4
rising to 9445 at N = 8, i.e. 2^N, and executing N = 8 exceeds a 20 GB memory limit. The buffer is
also off whenever correlated_subqueries_default_join_kind = 'left', and make_distributed_plan = 1
forces it off (SettingsQuirks.cpp).

Found as a Stress test (arm_tsan) hung check, where a cancelled INSERT ... SELECT sat 426 s in
plan optimization with 1,670,597 plan nodes (N of about 17, for a SELECT repeating one correlated
alias 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/HAVING and HAVING ... WITH TOTALS planner paths. It is used only when the in-memory buffer
is 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]

groeneai and others added 3 commits August 15, 2026 04:58
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent review passes were run against this diff over four rounds. Findings and verdicts:

# Severity Finding Verdict
❌ 1 major The plan-size oracle asserted only count() < 500 on both the unbuffered and the buffered arm, while the measured values are 226 and 218; the buffered bound was weaker than this PR's own claim that the buffered plan is unchanged. AGREE, fixed: structural single-root assertion added over EXPLAIN PLAN optimize = 0, both bounds tightened.
❌ 2 major The arm annotated as covering the shared-root header guard actually hit the pre-existing cross-scope rejection, which errors identically with and without this change, so it could not detect a regression in that guard. AGREE, fixed; that shape is owned by 04502_correlated_subquery_deep_nested_reference.sql.
❌ 3 major The test routed only through WHERE, so it exercised addFilterStep and the scalar decorrelation context. Reverting the addExpressionStep half of the fix, or dropping the shared root from the EXISTS context, left it green. AGREE, fixed: structural arms added for eight sibling subqueries in the SELECT list and for eight sibling correlated EXISTS predicates. Each half of the fix was reverted separately to confirm its own arm reddens.
❌ 4 major The absolute plan-line bound was infeasible under the runner's randomized enable_join_runtime_filters (a measured 48-line spread). AGREE, fixed: replaced by a ratio assertion, so doubling the sibling count must stay below fourfold (measured 1.9, against 16.6-fold unfixed). Both counts move together under randomization, so the ratio is stable where each count alone is not.
❌ 5 major Sharing was never exercised under correlated_subqueries_default_join_kind = 'left'. That setting disables buffering on its own, so it reaches the shared root with correlated_subqueries_use_in_memory_buffer at its default, while every existing arm pinned right and reached sharing only via an explicit = 0. A regression reading the raw buffer setting instead of the join-kind-aware value would have left the whole test green. AGREE, fixed: a left structural arm plus a value arm. Verified by targeted mutation: making the sharing condition read the raw setting reddens only the new arm (1 8 becomes 8 8) and leaves the others green.
❌ 6 major The PR body cited an unrelated PR as provenance. AGREE, fixed before publication: that link is dropped and the canonical CI report URL is cited instead.
⚠️ 7 nit The buffer-sharing rationale appears both in the header's struct documentation and at the sharing site in the .cpp. Noted, not changed. Measured comment budget: 10 added comment lines against 40 added code lines, every block at most three lines, and the cross-file citation is in the commit message.
⚠️ 8 nit std::ranges::all_of is used without a direct <algorithm> include, compiling transitively. Noted, not changed: misc-include-cleaner is disabled repository-wide in .clang-tidy, and there is existing precedent in src/Planner/.
💡 9 nit The UNION arm of a correlated subquery inherits the shared root and has no dedicated test arm. Noted, not changed: a reference reads only the correlated columns, whose values do not depend on how far the referenced root has grown, and 04411_chunk_buffer_correlated_subquery_set_operation passes.
💡 10 nit The NOT_IMPLEMENTED message now reports the shared root's header, so the phrase "Current outer query header" is slightly imprecise. Noted, not changed: the header reported is the one actually checked, so the message is accurate about the failing condition.
💡 11 nit A test comment said the plan "must not double" while quoting its own measured ratio of 1.9 and asserting a fourfold bound. AGREE, fixed.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Result
a Deterministic repro Yes. 04915_correlated_subquery_sibling_plan_blowup reddens on six independent lines before the fix, every run: three structural arms hold 8 referenced roots instead of 1 (WHERE, SELECT list, sibling EXISTS), both plan-size oracles flip, and the left-join-kind arm flips too.
b Root cause explained addExpressionStep validates every sibling correlated subquery against the header captured before the loop, but each subquery referenced the input subplan root as of its own iteration, so subquery k referenced a subtree containing 1..k-1. Unbuffered, the materialization pass clones each root with its nested references, doubling nodes per subquery.
c Fix matches root cause Changes which node is referenced. No node cap, no magic constant, no guard at the symptom site, no setting default change.
d Test intent preserved / new test New regression test asserting the structure directly over EXPLAIN PLAN optimize = 0: one referenced root and eight references unbuffered, on all three surfaces the fix touches, and eight of each on the untouched buffered path. Plan size is asserted as a ratio (doubling the sibling count must keep the plan below fourfold), which is stable under the runner's randomized join settings where an absolute bound is not. No existing test weakened; no .reference file updated outside this test.
e Both directions demonstrated Through clickhouse-test against servers whose SELECT lower(buildId()) was asserted equal to the binary's Build ID: pre-fix [ FAIL ] 0.86 s with the diff covering all six assertions, post-fix [ OK ] 0.38 s. Pre-fix also fails cheaply, so validating against master does not exhaust memory.
f General across code paths Both callers of buildQueryPlanForCorrelatedSubquery are fixed (addExpressionStep, addFilterStep); a grep over src/ shows exactly two callers exist. Both decorrelation kinds that pass the shared root (scalar and EXISTS) have their own assertion, and each half was reverted separately to confirm its own assertion reddens.
g Generalizes across inputs N = 1..8 on all three surfaces; both values of correlated_subqueries_use_in_memory_buffer; both values of correlated_subqueries_default_join_kind, which gates the buffer independently and swaps the join layout; a NULL-bearing oracle where each sibling contributes a distinct value; numbers() and MergeTree sources; make_distributed_plan on (8045 to 261 plan lines) and off.
h Backward compatible No setting default, serialization format or user-visible behavior change. The new parameter is defaulted to nullptr, so other callers are unaffected. No SettingsChangesHistory.cpp entry required.
i Invariants and contracts preserved The shared root is refused when the result is buffered (the buffer optimization replaces the referenced step in place) and when a correlated column is absent from the shared header; both cases fall back to a per-subquery root. The buffered path's structure is asserted unchanged (eight roots, eight references), and the unsupported cross-scope nesting still fails with the same NOT_IMPLEMENTED message as before.

Regression suite: the correlated / chunk_buffer / decorrelated / 04502 selection is 63/67, and
it includes the 14 tests pinning correlated_subqueries_use_in_memory_buffer and
04502_correlated_subquery_deep_nested_reference. Every one of the four failures was re-measured on a
binary without this change and fails there at the same rate or worse: three are the runner injecting
parallel-replicas settings against a single-node config (Code: 701 CLUSTER_DOESNT_EXIST, 5/5 on the
unfixed binary for two of them, 3/20 versus 4/20 for the intermittent one, and no Logical error on
either side), and one needs an HTTP endpoint on port 8123.

Randomized runs: clickhouse-test --test-runs 50 on the new test, 50 passed / 0 failed.

Every assertion was mutation-checked. Perturbing any structural count or either size oracle turns the
test red while the unmutated test stays green; reverting each half of the change separately reds
exactly and only that half's assertion; and making the sharing condition read the raw
correlated_subqueries_use_in_memory_buffer instead of the join-kind-aware value reds the left arm
alone, leaving the others green. No assertion is being carried by another.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1e8785]

Summary: ✅


AI Review

Summary

Reviewed PR #114938 at a1e8785764f872754a8fa5483ac94e90168806b9. Sharing an unbuffered input root prevents recursive duplication across sibling correlated subqueries. No actionable findings identified.

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 Verdict

Status: ✅ Approve

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 15, 2026
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
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.
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict.

The only conflict was in src/Planner/PlannerCorrelatedSubqueries.cpp, where master renamed DecorrelationContext::equivalence_class_stack to scope_stack (std::vector<DecorrelationScope>). Both DecorrelationContext constructions keep master's initializer and add .shared_input_root. Those two lines are the only difference from the head reviewed on 2026-08-15; against master the diff is still 5 files, +152/-9.

Master still has the defect, so this is still worth a look. Run against a master binary at 9da5fe397407, 04915 reports 8 referenced input roots for the 8 sibling subqueries on the unbuffered, projection, EXISTS and left arms, and both plan-growth assertions fail. The same file on this branch matches its reference byte for byte. The rest of the correlated-subquery suite (62 tests, 3 runs each) behaves identically on both binaries.

@clickhouse-gh clickhouse-gh Bot added the comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). label Sep 4, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 15, 2026
groeneai and others added 2 commits October 16, 2026 12:13
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve the conflict. Master moved the referenced-input construction into buildCorrelatedDomainPlan, so the shared root moved there with it; the LATERAL caller of that helper passes no shared root and is unchanged.

Master's new HAVING ... WITH TOTALS path (addTotalsHavingStep) had the same growth: 10210 plan steps for eight sibling subqueries, 330 with the shared root. It now shares the root as well, with a test arm, and the description is updated with current measurements.

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a1e878576 with master 30e5a0e2e (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

47 translation units recompiled, 638 s compile time in total, 47 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f459989

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (arm_binary, 3/4) / test_backward_compatibility/test_custom_s3_disk_remote_url_allow_hosts.py (both tests) not from this PR: red on master from 09:59Z to 17:21Z and on many other PRs. The old server image (26.8.28) now runs the remote_url_allow_hosts check for SQL disks, so the first CREATE fails with Code: 491 ... is not allowed in configuration file. This run started at 14:44Z, before the fix was merged #126289 (mine, merged)
Mergeable Check, PR praktika rollups of the row above #126289 (the owner of the row above)

Session id: cron:our-pr-ci-monitor:20261016-190009

groeneai and others added 2 commits October 31, 2026 12:00
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5a40199

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) / Logical error: Trying to deserialize data into Variant column with not global variants order (STID: 6636-4f2a), Server liveness check failed not from this PR (it changes only the planner's correlated subqueries): the server aborted on a LOGICAL_ERROR while reading a SHARED path of a JSON column from a Wide part (SerializationVariant.cpp:548 <- SerializationDynamic.cpp:714 <- SerializationObjectTypedSharedData.cpp:505), and the liveness check is its collateral; 0 tests failed; seen on 22 other PRs and master since 2026-10-26 #127867 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127867 (the owner of the row above)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261031-153005

groeneai and others added 2 commits November 15, 2026 15:04
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants