Skip to content

Attach the correlated-subquery set builder below the materialized CTE steps - #117311

Open
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-set-builder-below-materialized-cte
Open

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-correlated-set-builder-below-materialized-cte

Conversation

@groeneai

@groeneai groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A correlated subquery whose IN subquery reads an experimental MATERIALIZED CTE now runs when its decorrelated body is duplicated (correlated_subqueries_use_in_memory_buffer = 0 or correlated_subqueries_default_join_kind = 'left'), instead of failing with a DelayedPortsProcessor gate is missing logical error.

Description

Reported by @ zlareb1 on #115868 (comment). Related: #116343. Filed as Improvement because enable_materialized_cte is experimental.

What breaks. With enable_materialized_cte = 1, a valid query is rejected with Code: 49 ... DelayedPortsProcessor gate is missing in the query plan:

WITH mat AS MATERIALIZED (SELECT 2 AS y)
SELECT * FROM (SELECT (SELECT x) AS s, m FROM (SELECT arrayJoin([1,2,3]) AS x, x IN (SELECT y FROM mat) AS m GROUP BY x, m)) ORDER BY s
SETTINGS correlated_subqueries_use_in_memory_buffer = 0;

Root cause. When a decorrelated body is duplicated, optimizeTreeSecondPass takes the IN sets out of the fragments and re-attaches one DelayedCreatingSetsStep above the plan root. With a top-level MATERIALIZED CTE, that root is the DelayedMaterializingCTEsStep chain, so the set builder lands above the CTE gate. Both steps schedule through addPipelineBefore, so the set plans run before the CTE writer, while makePlansForSets has already stripped the set plan's own gate on the premise that the outer gate dominates it. Its source then reads an unmaterialized StorageMemory.

The change. Attach the builder below every DelayedMaterializingCTEsStep on the plan's single-child spine, which is where Planner.cpp already puts the plan's own set builder. With no materialized CTE on the spine the behaviour is unchanged.

Validation. Both settings above reproduce the logical error before the fix and pass after it; the buffer = 1 control is unchanged. Eight arms were added to 05029_correlated_subquery_materialized_in_set, one a structural EXPLAIN PLAN arm pinning the CTE gate at the root. They abort a pre-fix debug server and pass 60/60 randomized runs after it. make_distributed_plan = 1 clears the same flag, and a plan it cannot distribute now runs locally (distributed_plan_fallback_to_local_execution), so it reaches the same hoist and has its own arm.


Workflow [PR]
Sync PR [sync-upstream/pr/117311]

… steps

When `correlated_subqueries_use_in_memory_buffer` is off, a decorrelated subquery
body is duplicated by cloning it, so `optimizeTreeSecondPass` first takes the
`IN` sets out of the fragments and then re-attaches them in a single
`DelayedCreatingSetsStep`. That step was attached above the plan root. With a
top-level `MATERIALIZED` CTE the root at that moment is the
`DelayedMaterializingCTEsStep` chain the planner pushed, so the set builder
landed above the CTE gate.

Both `CreatingSetsStep::updatePipeline` and `MaterializingCTEsStep::updatePipeline`
end in `addPipelineBefore`, whose `DelayedPortsProcessor` marks the main pipe's
output ports delayed and leaves the "before" branch as the non-delayed side, so a
node's child 0 runs after its siblings. With the set gate on top, the set plans
became the "before" branch and ran before the CTE writer, while
`makePlansForSets` had already stripped the set plan's own
`DelayedMaterializingCTEsStep` on the premise that the outer step dominates every
reader. The set source then read an unmaterialized `StorageMemory` and
`ReadFromMemoryStorageStep` reported the missing gate as a `LOGICAL_ERROR`.

Attach the builder below every `DelayedMaterializingCTEsStep` on the plan's
single-child spine instead. That is the position
`addBuildSubqueriesForSetsStepIfNeeded` already uses for the plan's own set
builder, immediately below the CTE chain added on the next line. With no
materialized CTE on the spine the resulting plan is unchanged.

The same failure is reachable a second way, because the optimizer-side flag is
also cleared by `correlated_subqueries_default_join_kind = 'left'`; the new test
arms cover both settings, each read against the same query with neither setting applied. One arm is
structural and asserts via `EXPLAIN PLAN` that the CTE gate stays at the plan
root with the set gate under it, so the ordering is pinned rather than inferred
from values. `make_distributed_plan = 1` clears the same flag and so enters the
same hoist, but every shape of this query measured under it is rejected before
execution by the exchange guard in `convertToDistributed`, identically with and
without this change, so it gets no arm.

Reported by zlareb1 on ClickHouse#115868.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 2 gate runs, 1 finding then 0
findings) plus 3 independent cold reviews of the resulting code, with 2 fix rounds in between. No
finding in either channel was against the src/ hunk, which is unchanged since the first review.

# Sev Finding Verdict Evidence / action
1 ⚠️ The validation notes and the changelog entry claimed this fix covers make_distributed_plan = 1 with nothing measured behind the claim AGREE, fixed Measured on both binaries, three query shapes including a MergeTree-backed one: Code: 344 SUPPORT_IS_DISABLED from QueryPlan::convertToDistributed, identical with and without the change, while two buffer = 0 sensitivity controls on the same harness do diverge. Claim dropped from the changelog entry, the commit message and the notes. No test arm added: it would read the same rejection on both binaries and could never fail
2 ⚠️ Four sentences in the internal validation notes asserted a code mechanism the source refutes: that the distributed branch does not invoke resolveMaterializingCTEs, that optimizeTree.cpp is the only site wrapping a plan root with a delayed set builder, that plan serialization rejects the delayed steps, and a wrong count of the pre-existing reference lines AGREE, fixed resolveMaterializingCTEs has two call sites (QueryPlan.cpp:850 and :888, the second being the distributed local-execution fallback); seven sites wrap a plan root, of ten that construct the step; Serialization.cpp:134-138 skips both delayed steps rather than rejecting them; the file has 77 pre-existing reference lines, byte-identical after the change. Each sentence argued toward the same conclusion, so no code change follows
3 💡 The structural EXPLAIN PLAN arm matches MaterializingCTEs% without a leading wildcard DISAGREE That is the point of the arm: only the root step is unindented, so the match isolates the root. Measured 0 1 before the change and 1 1 after, so it fails if the change is reverted, and it is not the sole carrier (three value arms cover the same ordering)
4 💡 The comment above the insertion is longer than the per-block budget DISAGREE It states why a set reading a materialized CTE has to be built after it, and why only single-child nodes are descended. Neither follows from the code below it and neither refers to this fix, so it is the kind of comment that has to stay. Six added comment lines against seventeen added code lines

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260831-100002

@clickhouse-gh clickhouse-gh Bot closed this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 31, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One query, no concurrency and no fuzzer: WITH mat AS MATERIALIZED (SELECT 2 AS y) SELECT * FROM (SELECT (SELECT x) AS s, m FROM (SELECT arrayJoin([1,2,3]) AS x, x IN (SELECT y FROM mat) AS m GROUP BY x, m)) ORDER BY s SETTINGS correlated_subqueries_use_in_memory_buffer = 0 with enable_materialized_cte = 1 fails every time. On a debug build the message needs --logger.console=1, otherwise only the exit code is visible.
b Root cause explained? Yes. The hoist attaches the extracted IN sets in one DelayedCreatingSetsStep above the plan root; with a top-level MATERIALIZED CTE that root is the DelayedMaterializingCTEsStep chain, so the builder ends up above the CTE gate. Both steps schedule via addPipelineBefore, so the set plans then run before the CTE writer, and makePlansForSets has already stripped the set plan's own gate on the premise that the outer gate dominates it. The set's source reads an unmaterialized StorageMemory and the fail-fast check in ReadFromMemoryStorageStep reports the missing gate.
c Fix matches root cause? Yes. The defect is the relative position of two plan nodes, so the misplaced node is moved. No widened bound, no no-random-* tag, no data-size reduction, and no defensive check at the throw site: the throw stays the fail-fast it is meant to be.
d Test intent preserved / new tests added? Yes. The 77 existing reference lines are byte-identical, no arm was weakened or removed, and 7 statements covering 4 carriers were added to 05029_correlated_subquery_materialized_in_set, the file that owned the gap. One arm is structural (EXPLAIN PLAN) and pins the ordering directly rather than relying on values.
e Both directions demonstrated? Yes, on two Build-ID-verified binaries. The three value arms return the logical error before the fix and the expected rows after it; the structural arm reads 0 1 before and 1 1 after; the buffer = 1 control is identical in both directions. The new test file aborts a pre-fix server and passes afterwards.
f Fix is general across code paths? Yes. Seven sites in src/ wrap a plan root with a delayed set builder, and only one of them can wrap a root that carries a CTE gate: optimizeTree.cpp, which this fix changes. DelayedMaterializingCTEsStep is constructed at exactly one place, Planner.cpp:2130, and Planner.cpp:3066-3067 adds the plan's own set builder immediately below it, so that path is correct by construction. QueryPlan.cpp:1029 wraps the root of the read_from_distributed stub built just above it at QueryPlan.cpp:1005-1012, whose root is a ReadFromPreparedSource with no CTE gate below it. SetsSerialization.cpp:319 wraps a deserialized root, and serialization skips both delayed steps (Serialization.cpp:134-138), so neither is ever restored. InterpreterSelectQuery.cpp:3866 is the old analyzer, and MutationsInterpreter.cpp:2356 with CreatingSetsStep.cpp:302, whose helper only it calls, is the mutation path; neither plans a materialized CTE. Every consumer that must still find the moved node is a whole-tree or root-to-leaf walk, including extractSetsForDistributedPlan, addStepsToBuildSets, plan serialization, parallel-replica analysis and optimizeReadInOrder. The insertion walks the spine rather than testing only the root because other steps are legitimately added above a CTE chain after it exists.
g Fix generalizes across inputs (params/datatypes/wrappers)? The change is plan-shape only and touches no type, storage or replication path, so type wrappers are not a carrier here. The input axis that matters is the way into the hoist. Two are covered by arms: correlated_subqueries_use_in_memory_buffer = 0, and correlated_subqueries_default_join_kind = 'left' with the buffer left at its default. A third setting, make_distributed_plan = 1, also clears the buffer flag and therefore reaches the same hoist, but it is deliberately not claimed: every shape of this query measured under it is rejected before execution with Code: 344 SUPPORT_IS_DISABLED by convertToDistributed, identically on the pre-fix and post-fix binaries, so there is no behaviour there for an arm to pin. Also covered: the CTE read only inside the duplicated body, and read on both sides of the set gate.
h Backward compatible? (maintainer-approved exception only) Yes. No setting is added, no default changes, and no serialization format is touched, so SettingsChangesHistory.cpp needs no entry. Plan serialization skips both delayed steps wherever they sit (Serialization.cpp:134-138 descends to children.front()), so moving one node is invisible to it.
i Invariants and contracts preserved? Yes. DelayedCreatingSetsStep's output header equals its input header, so a mid-spine insertion is header-neutral and the debug-build header check stays quiet on every arm above. The node list is a std::list, so appending never invalidates existing node pointers. DelayedMaterializingCTEsStep has exactly one child at this point by construction, and the pass that turns it into the multi-child form runs later. The no-CTE branch is behaviourally identical to the previous code, so any query without a materialized CTE on the spine is unaffected. No new error code and no new throw.

Session id: cron:clickhouse-impl-slot-4:20260831-094600

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1c546da]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Cannot start clickhouse-server FAIL cidb
Server failed to start (see application_errors.txt and clickhouse-server.clean.log) FAIL cidb
Check failed FAIL cidb

AI Review

Summary

The PR places the extracted IN set builder below the materialized CTE gate chain, ensuring CTE materialization finishes before set construction while keeping the builder above every duplicated reader. No actionable findings. The focused regression test 05029_correlated_subquery_materialized_in_set passes at head 1c546dabf173f28379dc4dde38f5022de92e8bcb in Fast test.

Final Verdict

✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@groeneai

groeneai commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir, could you review this? When a decorrelated subquery body is duplicated, optimizeTreeSecondPass re-attached the extracted IN sets above the plan root, and with a top-level MATERIALIZED CTE that root is the DelayedMaterializingCTEsStep chain, so the set plans ran before the CTE writer and the set source read an unmaterialized StorageMemory. This attaches the builder below the CTE steps instead, which is where Planner.cpp already puts the plan's own set builder, so no materialized CTE on the spine means an unchanged plan.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1c546dabf173f28379dc4dde38f5022de92e8bcb was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fc2c5eb1f337013e4fee4297a575a8dedc676765

CI is fully finished on this head. 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 (amd_asan_ubsan, db disk, old analyzer, 2/6) / Container memory budget exceeded (/docker) /docker cgroup leaf OOM kills the concurrent shutdown gdb attaches; job ERROR, no test failed #117202 (external, merged 2026-08-31), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) same leaf OOM as above #117202 (external, merged 2026-08-31), absent from this tree
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) same leaf OOM as above #117202 (external, merged 2026-08-31), absent from this tree; a fix task owns the 6/6 residual noted below

The three Container memory budget exceeded (/docker) rows are one signature, not three. The
/docker cgroup leaf that bounds the nested test containers is capped at 40.78 GiB, and
docker compose stop signals every node of a cluster at once, so each node that outlives the
60 s deadline attaches gdb at the same moment. On an ASan build each attach holds about 3.4 GiB
of anonymous memory, so a nine-node cluster asks for roughly the whole leaf and the kernel kills
the debuggers. #117202 serializes that attach. It is merged, but it is outside the tree this
run built: the fix symbol GDB_ATTACH_LOCK is absent at fc2c5eb1f337 and present at the merge
commit 7fc3004ed25a. So the run predates the fix. These rows clear when the branch next picks
master up. I am not merging master here purely to re-run CI, to keep the review load down.

Measured caveat: on true-master trees that DO contain #117202, the 2/6 and 5/6 shards are
clean (0 of 13 post-fix trees) but 6/6 still fires (13 of 13). So a 6/6 row may return after
the master merge. A fix task owns that residual and its fixing-PR link will be posted here when
one opens.

Two things in the check list are artifacts of this head having been built twice, and neither is a
defect. Two PR workflow runs were triggered nine seconds apart, 33382952934 and
33382964461. Stateless tests (arm_binary, parallel) is red only in the second, where the job
ended after 47 s without starting a test; in the first it is success with 13428 passing test
rows and no failing row at this commit. Finish Workflow is likewise red only in the second,
reporting that run's integration rows. The three integration rows above failed in both runs,
which is why they are the only ones owed an owner.

None of these rows is reachable from this diff, which attaches the correlated-subquery set
builder below the materialized CTE steps.

Mergeable Check and PR are praktika aggregators. Config Workflow, Style check and
CH Inc sync are all success on this head.

Session id: cron:our-pr-ci-monitor:20260831-203000

groeneai and others added 2 commits September 27, 2026 12:19
`make_distributed_plan = 1` also clears `correlated_subqueries_use_in_memory_buffer`,
so it reaches the same `IN`-set hoist. Before the master merge such a query was refused
with `SUPPORT_IS_DISABLED` on both binaries, so it had no arm. Master now falls back to
local execution when a plan cannot be distributed
(`distributed_plan_fallback_to_local_execution`, on by default), and the query runs.

Measured on the master debug snapshot `e5b8853baca3`: the new arm aborts the server with
`Reading from materialized CTE 'mat' before its materialization completed -
DelayedPortsProcessor gate is missing in the query plan`. With this branch it returns
`1 0 / 2 1 / 3 0`, and 60/60 randomized runs of the whole file pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 81dd802

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
Performance Comparison (arm_release, master_head, 6/6) / lower_upper_utf8_mixed_ascii #4 dashboard confirmed_regression, client_time 0.0125 -> 0.0148 s (+18.0%), while the shard's own report calls the query success (4 too long only). The dashboard scored it without master history: its C3, C4 and C5 modules are unavailable, so the bar was its 2% floor. The query is lowerUTF8 over a column of an ENGINE = Memory table, with no subquery, while the only product change in this PR is where optimizeTree.cpp attaches the set builder of a correlated IN subquery the question for exactly this class (rows the dashboard scores without master history) is posted to its owner: #119556 (comment). Either the dashboard restores the history, or I send the in-tree fallback described there
Mergeable Check, PR rollups, red only because of the row above the same owner question as the row above: #119556 (comment)

All 172 check runs completed (128 pass, 41 not selected, 3 red: the row above and its two rollups),
Finish Workflow is green and CH Inc sync passed. CIDB has no FAIL or ERROR test row on this
head. The shard's 4 too long is informational: in master_head mode only run errors and dashboard
confirmed_regression rows fail a shard.

Session id: cron:our-pr-ci-monitor:20260927-173207

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the lower_upper_utf8_mixed_ascii #4 (arm_release 6/6) perf red: #122782, which reruns dashboard-confirmed rows after a server restart. Here the reference server was the outlier: 0.0125 s, against a median of 0.0146 s for the same reference build over its 9 runs, while this PR measured 0.0148 s.

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-optimizer Query plan optimization: physical plan steps, plan-level rewrites and optimizations (QueryPlan pa... groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants