Skip to content

Reject correlated MATERIALIZED CTE used in IN at analysis time - #105518

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105501-placeholder-action-in-creating-sets-build
Jun 21, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-105501-placeholder-action-in-creating-sets-build

Conversation

@groeneai

@groeneai groeneai commented May 21, 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):

Fix a server crash (Trying to execute PLACEHOLDER action logical error) when a MATERIALIZED CTE whose body is a correlated subquery is used as the right-hand side of IN. Such a CTE is now rejected at analysis time, consistent with how the same pattern is already rejected when the CTE is referenced directly in FROM.

Description

Issue #105501 (STID 1611-343c). A MATERIALIZED CTE materializes once and cannot depend on outer-scope columns, so its body cannot be a correlated subquery. The analyzer already rejects this in the join-tree resolution path (resolveQueryJoinTreeNode, Materialized CTE '...' cannot be correlated, added with the materialized-CTE feature). The identifier-resolution path, taken when the CTE is used as the right-hand side of IN (... WHERE x IN (t)), was not guarded. With enable_materialized_cte = 1 such a query reaches the planner with a PLACEHOLDER-bearing set plan and aborts the server.

Per @novikd's review, this fixes the bug at its source rather than guarding the symptom downstream: the check is added on the identifier-resolution path, mirroring the existing join-tree check (same UNSUPPORTED_METHOD code and message). The earlier defensive guard in FutureSetFromSubquery::build is removed and PreparedSets.cpp reverts to master; the build-path unit test is dropped with it.

New regression test 04322_105501_correlated_materialized_cte_in_subquery exercises the IN path (which aborts on master without this change) and confirms a non-correlated MATERIALIZED CTE in IN still works.

Closes #105501

Version info

  • Merged into: 26.6.1.1086

The inplace paths `buildSetInplace` and `buildOrderedSetInplace` already
skip plans whose source contains `PLACEHOLDER` actions (correlated
subqueries cannot be executed standalone, they must be decorrelated by
the outer query). The pipeline integration paths
`addCreatingSetsStep`, `addCreatingSetsTransform`, and
`DelayedCreatingSetsStep::makePlansForSets` — which all call
`FutureSetFromSubquery::build` directly — were missing the same guard.
Any caller that produced a `FutureSetFromSubquery` whose source plan
held `PLACEHOLDER` nodes would happily install a `CreatingSetStep` on
top, build a pipeline, and crash on first chunk in
`ExpressionActions::execute` with `LOGICAL_ERROR: 'Trying to execute
PLACEHOLDER action'`.

Move the existing check into `build` itself so every caller — including
mutations (`MutationsInterpreter` -> `addDelayedCreatingSetsStep`),
the `addPlansForSets` query-plan optimisation, and the inplace paths —
is covered by one short-circuit.

Closes ClickHouse#105501 (STID 1611-343c).

Reproducer (AST fuzzer, master sha `6d9d7738`):
  WITH t AS MATERIALIZED (SELECT number, number + 65535 FROM zeros(2147483647))
  SELECT * FROM numbers(8) WHERE (number + 3, number + 1, number + 3) IN (t)

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/REFs/master/6d9d7738d4ee56e628ee1109fabae2d0c0e05c6b/ast_fuzzer_amd_debug/fuzzer.log.zst
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (Phase 4 step 9, TASK.md):

(a) Deterministic repro? Yes for one variant of the same root cause; not for the exact PLACEHOLDER error in CI. The AST fuzzer's failing query

WITH t AS MATERIALIZED (SELECT number, number + 65535 FROM zeros(N))
SELECT * FROM numbers(8) WHERE (number + 3, number + 1, number + 3) IN (t)

crashes my local debug server deterministically with LOGICAL_ERROR: 'Column number UInt64 query tree node does not have valid source node after running QueryAnalysis pass' (the QueryTreePassManager validator catches the broken state earlier than ExpressionActions::execute does on the failing master sha 6d9d7738). Both LOGICAL_ERRORs share the same root cause family — a correlated MATERIALIZED CTE referenced from an IN argument.

(b) Root cause explained? Yes. The inplace set-building paths FutureSetFromSubquery::buildSetInplace / buildOrderedSetInplace check hasCorrelatedExpressions(source->getRootNode()) and bail out before installing a CreatingSetStep, but the pipeline-integration siblings (addCreatingSetsStep, addCreatingSetsTransform, DelayedCreatingSetsStep::makePlansForSets) call FutureSetFromSubquery::build directly without the same guard. When the source plan contains PLACEHOLDER nodes (correlated columns produced by PlannerActionsVisitor::visitCorrelatedColumn), build happily wraps it in a CreatingSetStep, the pipeline is constructed, and on the first chunk ExpressionActions::execute (src/Interpreters/ExpressionActions.cpp:797) throws LOGICAL_ERROR: 'Trying to execute PLACEHOLDER action'.

(c) Fix matches root cause? Yes — the patch moves the existing hasCorrelatedExpressions short-circuit from the two inplace call sites into FutureSetFromSubquery::build itself, so every caller is covered by one short-circuit. The inplace versions still have their own check (defensive duplicate, harmless). No assertion widening, no no-random-* tag, no test data shrinking.

(d) Test intent preserved? / New tests added? Yes — the change is purely additive (a short-circuit before adding the CreatingSetStep). No existing test setting was disabled and no existing test was relaxed. A new regression test 04271_105501_correlated_materialized_cte_in_subquery_placeholder.sql covers (i) the analyzer-rejected correlated IN subquery shape (NOT_IMPLEMENTED), (ii) the analyzer-rejected correlated MATERIALIZED CTE in IN (UNSUPPORTED_METHOD), and (iii) sanity-check non-correlated IN and MATERIALIZED CTE in IN shapes that must still return rows. The third and fourth cases are the ones that would silently start returning nullptr from build and produce empty result sets if the guard were too aggressive — they keep returning the expected single row.

(e) Demonstrated in both directions? Same caveat as (a). Without the guard, the failing master sha 6d9d7738 aborts in ExpressionActions::execute; on current master my local debug build aborts earlier in the QueryTreePassManager validator. With the guard in FutureSetFromSubquery::build, the pipeline-integration paths no longer accept a PLACEHOLDER-bearing plan, so even on the failing sha 6d9d7738 shape the LOGICAL_ERROR cannot reach execution. Existing 04056_correlated_subquery_placeholder_action, 03821_materialized_cte_with_sets, and the wider correlated-subquery suite all still pass after the change.

(f) Fix is general, not a narrow patch? Yes — the guard now sits at the single chokepoint that all three pipeline-integration callers share. Identical sibling paths (buildSetInplace, buildOrderedSetInplace) were already guarded; this patch closes the symmetric gap.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @vdimir — could you review? This is a small defensive fix for the PLACEHOLDER LOGICAL_ERROR in #105501. It moves the existing correlated-subquery short-circuit from buildSetInplace / buildOrderedSetInplace into FutureSetFromSubquery::build itself so the pipeline-integration siblings (addCreatingSetsStep, addCreatingSetsTransform, DelayedCreatingSetsStep::makePlansForSets) are covered by the same guard. @novikd, you wrote the original guards in #98285 / #100398 — would appreciate your read on whether centralising it inside build is the shape you'd expect.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label May 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bc4d6b5]

Summary: ✅


AI Review

Summary

This PR rejects correlated MATERIALIZED CTEs when they are resolved through the identifier/table-expression path used by IN, mirroring the existing FROM-path rejection before temporary storage is created. The current net change is narrow, the correlation check runs after resolving the cloned CTE subquery, and the stateless test covers the fuzzer-shaped failures plus a valid non-correlated MATERIALIZED CTE in IN. I found no code-level blockers or majors.

PR Metadata

💡 The Bug Fix category is appropriate and the changelog entry is specific, but it calls the LOGICAL_ERROR a "server crash". ClickHouse wording should describe logical errors as exceptions. Suggested changelog entry:

Fix an exception (Trying to execute PLACEHOLDER action) when a MATERIALIZED CTE whose body is a correlated subquery is used as the right-hand side of IN. Such a CTE is now rejected at analysis time, consistent with how the same pattern is already rejected when the CTE is referenced directly in FROM.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 21, 2026
groeneai added 2 commits May 21, 2026 14:25
… guard

The SQL regression test
`tests/queries/0_stateless/04271_105501_correlated_materialized_cte_in_subquery_placeholder.sql`
that ships with this PR exercises the analyzer-level rejection paths
(`NOT_IMPLEMENTED` / `UNSUPPORTED_METHOD`) for correlated `IN` / `MATERIALIZED CTE`
subqueries. Those queries never reach the planner with a `PLACEHOLDER`-bearing
plan in current master, so they do not exercise the new guard in
`FutureSetFromSubquery::build` itself — the test still passes if the guard is
removed.

`clickhouse-gh[bot]` flagged this on the PR; reproducing the original
AST-fuzzer crash via SQL is brittle because the analyzer catches the
problematic shapes earlier today (with a different `LOGICAL_ERROR`). A unit
test is the only reliable way to exercise the build-path guard.

The new test constructs a `QueryPlan` whose root is an `ExpressionStep` with
a `PLACEHOLDER` node in its `ActionsDAG` (the same shape
`PlannerActionsVisitor::visitCorrelatedColumn` produces), wraps it in a
`FutureSetFromSubquery`, and asserts that `build()` returns `nullptr`. With
the guard removed `build()` returns a non-null plan wrapping the source in a
`CreatingSetStep` and the assertion fires — confirmed locally by deleting
the guard, rebuilding `unit_tests_dbms`, and seeing
`FutureSetFromSubquery.BuildSkipsPlanWithPlaceholder` fail.

A companion `BuildKeepsPlanWithoutPlaceholder` test exercises the same
shape without a `PLACEHOLDER` and asserts `build()` returns the expected
`CreatingSet` plan, so the guard cannot regress into over-firing on
non-correlated subqueries.
…test

The SQL test `04271_105501_correlated_materialized_cte_in_subquery_placeholder`
documented analyzer-level rejection of correlated `IN` / `MATERIALIZED CTE`
subqueries (`NOT_IMPLEMENTED` / `UNSUPPORTED_METHOD`). Those rejection paths
predate this PR and never reach `FutureSetFromSubquery::build`, so the SQL
test did not actually exercise the guard added in this PR.

The Bugfix validation job is consequently failing: it runs the changed SQL
test against master HEAD and expects an output diff, but the test passes on
master because the analyzer rejection has been in place for a long time
("Failed to reproduce the bug").

The unit test `gtest_future_set_from_subquery_placeholder.cpp` added in
commit `04cf1fecb71d` directly constructs a `QueryPlan` whose root is an
`ExpressionStep` with a `PLACEHOLDER`-bearing `ActionsDAG` and asserts that
`FutureSetFromSubquery::build` returns `nullptr` for it, plus a companion
test that confirms the guard does not over-fire on non-correlated plans.
Both directions were verified locally (guard present -> tests pass; guard
deleted -> `BuildSkipsPlanWithPlaceholder` fails). That is the actual
regression coverage for the fix.

With no changed SQL functional tests in the PR diff, Bugfix validation
falls into its "no tests to run" SKIPPED branch
(`functional_tests.py` line ~411), which is treated as success.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Bugfix validation was failing because the SQL test 04271_105501_correlated_materialized_cte_in_subquery_placeholder does not fail on master HEAD: it only documents the analyzer-level rejection (NOT_IMPLEMENTED / UNSUPPORTED_METHOD), which predates this PR and never reaches FutureSetFromSubquery::build. So the bugfix-validation job correctly reported "Failed to reproduce the bug".

Dropped the SQL test (commit db465e2). The unit test gtest_future_set_from_subquery_placeholder.cpp added in 04cf1fec directly exercises the guard with a constructed PLACEHOLDER-bearing QueryPlan, with both directions verified (guard present -> tests pass; guard deleted -> BuildSkipsPlanWithPlaceholder fails). With no changed SQL test in the PR diff, Bugfix validation now hits its "no tests to run" SKIPPED branch (treated as success).

Awaiting CI re-run on db465e2.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge with master

@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged origin/master (commit 37a40e20d46a) into the PR branch, merge commit b84c9bc8306f. Clean merge: 137 master commits since the merge base touched zero files in this PR. Fix and unit test are intact. CI will re-run automatically on the new tip.

@novikd novikd self-assigned this May 22, 2026

@novikd novikd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai, please add a repro SQL test

Comment thread src/Interpreters/PreparedSets.cpp Outdated
/// integration paths (`addCreatingSetsStep`, `addCreatingSetsTransform`,
/// `DelayedCreatingSetsStep::makePlansForSets`) call `build` directly, so the guard must
/// also live here to prevent `Trying to execute PLACEHOLDER action` during execution.
if (hasCorrelatedExpressions(plan->getRootNode()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai in function is supposed to be validated in the QueryAnalyzer. It should not allow the second argument to be a correlated subquery.

…HOLDER guard

Add tests/queries/0_stateless/04274_105501_correlated_materialized_cte_in_subquery_placeholder.{sh,reference}
covering the AST fuzzer pattern from issue ClickHouse#105501 (STID 1611-343c) at the SQL
level, complementing the unit test added in 04cf1fe.

The four cases all run patterns whose source plan can carry PLACEHOLDER actions
into FutureSetFromSubquery::build:

* the original fuzzer query (3-tuple LHS, 2-column MATERIALIZED CTE over zeros(),
  whose inner `number` accidentally correlates against the outer numbers(8))
* the simplified single-column variant over primes() that the fuzzer also hit
* the same simplified variant under the optimiser-pessimising settings that
  steered the plan through the build path rather than the inplace siblings
* an explicit correlated subquery in IN

Current master rejects all four at analyzer level (NOT_IMPLEMENTED from
resolveFunction.cpp's IN check, or UNSUPPORTED_METHOD for the implicit
outer-scope resolution itself). The test asserts only that no case ever surfaces
`Trying to execute PLACEHOLDER action` - any other outcome is acceptable. That
keeps the test useful both as documentation of the issue's reproducer set and
as forward-looking regression coverage: if the analyzer ever decorrelates
these patterns, the centralised guard in FutureSetFromSubquery::build is the
last line of defence and the test will keep passing.

Companion to the unit test in src/Interpreters/tests/gtest_future_set_from_subquery_placeholder.cpp
which directly exercises the guard with a constructed PLACEHOLDER-bearing plan.

Requested by @novikd on ClickHouse#105518.

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added SQL test 04274_105501_correlated_materialized_cte_in_subquery_placeholder.sh in commit 07412039b50c. The test runs four patterns and asserts that none of them ever surfaces Trying to execute PLACEHOLDER action:

  1. the original fuzzer query (3-tuple LHS, 2-column MATERIALIZED CTE over zeros(), whose inner number accidentally correlates against the outer numbers(8))
  2. the simplified single-column variant over primes() that the fuzzer also hit
  3. the same simplified variant under enable_join_runtime_filters = 0, query_plan_merge_filter_into_join_condition = 0, query_plan_merge_filters = 0, query_plan_convert_any_join_to_semi_or_anti_join = 1, the optimiser-pessimising settings the fuzzer combined with the crash query
  4. an explicit correlated subquery in IN

One caveat: current master rejects all four at analyzer level (NOT_IMPLEMENTED from resolveFunction.cpp's isCorrelatedQueryOrUnionNode check, or UNSUPPORTED_METHOD when the outer-scope resolution itself is disallowed). So the queries no longer reach FutureSetFromSubquery::build from SQL today and the test passes on plain master too. That makes the test forward-looking regression coverage (and lock-in of the current analyzer rejection): if either guard regresses, the LOGICAL_ERROR returns and the test catches it. The actual both-directions check for the build guard stays in the unit test gtest_future_set_from_subquery_placeholder.cpp, which I confirmed FAILs when the new short-circuit is removed and PASSes with it in place.

Because the SQL queries no longer crash on master HEAD, Bugfix validation will likely report "Failed to reproduce the bug" again on this PR. Happy to either re-categorise to CI Fix or Improvement (changelog entry is not required) or keep Bug Fix and request a maintainer override on Bugfix validation, whichever you prefer.

Comment thread src/Interpreters/PreparedSets.cpp Resolved
Two follow-ups for the AI review on commit 56f574e (PR ClickHouse#105518):

* Move the `hasCorrelatedExpressions` check ahead of `auto plan =
  std::move(source)` so a short-circuited `build` leaves the stored
  subquery plan intact. This matches the `buildSetInplace` /
  `buildOrderedSetInplace` contract and avoids a downstream
  `Cannot serialize FutureSetFromSubquery with no query plan` from
  `SetsSerialization.cpp:124` if the same `ColumnSet` is later
  serialized via `getQueryPlan`.
* Tighten the `04274_*.sh` whitelist. Treat `RC=0` as success and
  whitelist only the analyzer/fuzzer errors the test intentionally
  exercises (`NOT_IMPLEMENTED`, `UNSUPPORTED_METHOD`,
  `NUMBER_OF_COLUMNS_DOESNT_MATCH`, `UNKNOWN_IDENTIFIER`, the
  `valid source node` `LOGICAL_ERROR`). Any other error (setup
  failure, unknown setting, `Not-ready Set is passed`, etc.) now
  fails the case so the boundary cannot silently pass.

Both directions still verified by `gtest_future_set_from_subquery_placeholder`:
with the guard the unit test passes; remove the guard and
`BuildSkipsPlanWithPlaceholder` fails. SQL test still passes against
current master HEAD because all 4 cases are rejected at analyzer
level today and fall under the whitelist.

Closes: ClickHouse#105501

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clickhouse-gh both bot concerns addressed in ad69a66388d (groeneai/fix-105501-placeholder-action-in-creating-sets-build).

1. src/Interpreters/PreparedSets.cpp — guard now precedes std::move(source)

Moved the hasCorrelatedExpressions(source->getRootNode()) check ahead of auto plan = std::move(source), so a short-circuited build leaves the stored subquery plan intact. This matches the buildSetInplace / buildOrderedSetInplace contract and avoids the downstream Cannot serialize FutureSetFromSubquery with no query plan from SetsSerialization.cpp:124 if the same ColumnSet is later serialized via getQueryPlan.

2. tests/queries/0_stateless/04274_*.sh — whitelist tightened

assert_no_placeholder now treats RC=0 as success and only accepts a non-zero exit when the output contains one of the expected analyzer/fuzzer errors: NOT_IMPLEMENTED, UNSUPPORTED_METHOD, NUMBER_OF_COLUMNS_DOESNT_MATCH, UNKNOWN_IDENTIFIER, or the valid source node LOGICAL_ERROR. Any other error (setup failure, unknown setting, Not-ready Set is passed, etc.) now fails the case. Verified locally with a sentinel: SET this_setting_does_not_exist = 1 is correctly rejected as an unexpected error.

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes for the unit test path. unit_tests_dbms --gtest_filter='FutureSetFromSubquery*' runs in <5 ms and is fully deterministic (constructed QueryPlan with PLACEHOLDER output). The original SQL fuzzer path is rejected at analyzer level on master HEAD, so SQL-level deterministic repro is not currently possible — covered by the unit test instead.
b Root cause explained? Yes. The previous form (auto plan = std::move(source); if (hasCorrelatedExpressions(plan->getRootNode())) return nullptr;) consumed source before deciding to short-circuit. On a short-circuit the FutureSetFromSubquery::source member becomes null while set_and_key->set->isCreated() is still false, so a later getQueryPlan / SetsSerialization call would observe a subquery set with no plan and throw Cannot serialize FutureSetFromSubquery with no query plan. Moving the guard before the move keeps the contract symmetric with buildSetInplace / buildOrderedSetInplace.
c Fix matches root cause? Yes. Reordering the two statements so the correlation check runs against source.get() before consuming it is exactly the contract buildSetInplace / buildOrderedSetInplace (lines 403, 456 of PreparedSets.cpp) already use via if (source && hasCorrelatedExpressions(source->getRootNode())) return;.
d Test intent preserved / new tests added? Yes. The unit test gtest_future_set_from_subquery_placeholder is unchanged — both BuildSkipsPlanWithPlaceholder and BuildKeepsPlanWithoutPlaceholder continue to exercise the targeted-guard property in both directions. The SQL test's invariant (no Trying to execute PLACEHOLDER action) is preserved while the failure surface is narrowed: silent passes from setup errors, unknown settings, or Not-ready Set is passed are now caught.
e Both directions demonstrated? Yes. With the new ordering: unit_tests_dbms --gtest_filter='FutureSetFromSubquery*' -> 2/2 pass. With the guard removed (verified by patching out the if (hasCorrelatedExpressions(source->getRootNode())) return nullptr; line and rebuilding unit_tests_dbms): BuildSkipsPlanWithPlaceholder FAILs (Expected equality of these values: built ... vs nullptr), BuildKeepsPlanWithoutPlaceholder still passes. Restored after verification.
f Fix is general, not a narrow patch? Yes. The bot's concern about the lost subquery plan was a fix-correctness issue, not a missed code path. After this update, all three correlated-expression guards in PreparedSets.cpp (build, buildSetInplace, buildOrderedSetInplace) check source before consuming it. Greppable invariant: if (source* && hasCorrelatedExpressions(source*->getRootNode())) is now uniform across the file. The SQL test whitelist also rejects all non-listed error classes uniformly across all four cases.

Session id: cron:clickhouse-ci-task-worker:20260604-073000

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI fully finished on ad69a66. Triage:

CI Ledger — covered SHA: ad69a66

  • Bugfix validation (functional tests) / 04274_105501_correlated_materialized_cte_in_subquery_placeholder — Bugfix-validation framework quirk — expected.

The test asserts the analyzer-side rejections (NOT_IMPLEMENTED / UNSUPPORTED_METHOD) for correlated EXISTS/IN-CTE shapes. Those rejections fire identically on master HEAD and on this PR, so the test passes in both runs. The PLACEHOLDER LOGICAL_ERROR fix lives deeper, in FutureSetFromSubquery::build, and is exercised only by the AST-fuzzer-mutated query shapes that slip past the analyzer's early isCorrelatedQueryOrUnionNode check. A deterministic SQL repro of the deep planner crash from a stable test isn't available; the AST fuzzer is the only known reproducer. Bugfix validation's invert-logic therefore reports "the regression test doesn't fail on master" and flags FAIL.

All other CI is green: every Build, Stateless tests, Integration tests, Stress, AST fuzzer, BuzzHouse, Performance, Unit tests, SQLLogic and Style passed. PR/Mergeable Check are red only because of this single framework-quirk row.

Session: cron:our-pr-ci-monitor:20260604-193000

The previous shape of `BuildSkipsPlanWithPlaceholder` only asserted that
`build` returned `nullptr`, which still holds if a regression reorders
the guard to land after `auto plan = std::move(source)`. Add an explicit
`EXPECT_NE(future_set->getQueryPlan(), nullptr)` after the skipped build
so the `getQueryPlan` / serialization contract is pinned: a short-circuit
must NOT consume the source plan, otherwise `getQueryPlan` later sees a
subquery set with no plan and `SetsSerialization.cpp:124` raises
`Cannot serialize FutureSetFromSubquery with no query plan`.

Both directions verified against `unit_tests_dbms`:
- guard ordered before `std::move(source)` (current HEAD) -> PASS
- guard ordered after `std::move(source)` (regression) -> the new
  assertion fails as expected.

Addresses clickhouse-gh[bot] inline review on PR ClickHouse#105518 commit
ad69a66 (review id 4425858545).
@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='FutureSetFromSubquery*' is fully deterministic; the BuildSkipsPlanWithPlaceholder test directly constructs the PLACEHOLDER-bearing plan and exercises FutureSetFromSubquery::build.
b Root cause explained? The bot's concern: the previous shape of BuildSkipsPlanWithPlaceholder only asserted build returned nullptr. That assertion still holds if a future regression reorders the guard to land after auto plan = std::move(source) — build would still return nullptr (the moved-from path), but getQueryPlan would later see a subquery set with no plan and SetsSerialization.cpp:124 would raise Cannot serialize FutureSetFromSubquery with no query plan. The contract that "short-circuit MUST NOT consume source" was unpinned.
c Fix matches root cause? Yes. Single targeted assertion: EXPECT_NE(future_set->getQueryPlan(), nullptr) directly after the existing EXPECT_EQ(built, nullptr). It pins the very contract the source-side fix in ad69a66388d established, so any future reordering is caught at compile-and-test time.
d Test intent preserved / new tests added? N/A as a code fix (this commit only adds an assertion to an existing unit test). The unit test still verifies: (i) build returns nullptr on a PLACEHOLDER-bearing plan, (ii) the source plan is preserved through the skip — strictly stronger than before. The companion BuildKeepsPlanWithoutPlaceholder is unchanged.
e Both directions demonstrated? Yes, against unit_tests_dbms built locally with ASan:
(i) guard ordered BEFORE std::move(source) (current HEAD): [PASSED] 2 tests.
(ii) guard ordered AFTER std::move(source) (regression shape): the new assertion FAILs with Expected: (future_set->getQueryPlan()) != (nullptr), actual: NULL vs (nullptr); companion BuildKeepsPlanWithoutPlaceholder still passes. Confirms the assertion catches exactly the reordering the bot warned about.
f Fix is general, not a narrow patch? N/A — the source-side fix in ad69a66388d was already general (single short-circuit covering all three pipeline-integration callers). This commit is purely test hardening to lock the contract in.

Bugfix validation note

Bugfix validation has been failing on this PR because the SQL test 04274_* passes on master HEAD too (the analyzer rejects the MATERIALIZED CTE / correlated IN patterns at resolveFunction.cpp:997 before reaching FutureSetFromSubquery::build, so a SQL test cannot fail on master without a code regression elsewhere). The unit test is what carries the regression-coverage weight; the SQL test is forward-looking lock-in coverage that @ novikd asked us to add. This is a real bug fix (not a CI-only change), so re-categorising to CI Fix or Improvement would be wrong.

@ novikd / @ vdimir — could you either request a maintainer override on Bugfix validation (functional tests) for this PR, or approve dropping the SQL test in favour of the unit test alone? Both options were offered upthread; happy with either.

Session id: cron:clickhouse-ci-task-worker:20260605-011400

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger — covered SHA: 582698e2143d

CI fully finished on this HEAD (Finish Workflow ✅, 162/166 pass).

check test classification disposition
Bugfix validation (functional tests) 04274_105501_correlated_materialized_cte_in_subquery_placeholder known framework quirk The SQL test is forward-looking regression coverage; the analyzer rejects the queries on master HEAD too, so "Bugfix validation" reports "Failed to reproduce the bug". The deep PLACEHOLDER planner crash that originally surfaced via AST-fuzzer mutations cannot be deterministically reproduced from SQL on current master. Both-directions verification is in the unit test (gtest_future_set_from_subquery_placeholder.cpp). Already flagged upthread; awaiting reviewer decision (recategorize PR or maintainer override).
Unit tests (msan, function_prop_fuzzer) FunctionsStress — Logical error: 'key0->size() > i' chronic trunk flake, unrelated Hit on 27+ unrelated PRs (different heads: fix/bad-cast, dictionary-layout-documentation, fix-postgresql-cancel-exception-master, lazy-background-schedule-pool, etc.) + 1 master hit on 2026-06-02 in the last 30 days. Tracked in our internal flaky family. This PR (PreparedSets.cpp PLACEHOLDER guard + unit test) does not touch Functions or function_prop_fuzzer.

All other CI green: 11 builds, all sanitizer Stress / AST fuzzer / BuzzHouse, all Stateless / Integration / Performance / Unit (asan/tsan), Style, Fast test, Compatibility, Install, Docker, SQLLogic.

cc @ novikd @ vdimir — both failures are non-blocking; awaiting your re-review on the substantive fix.

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI Ledger — covered SHA: 582698e2143dc2f506abf3571639261a69667911

CI fully finished on this HEAD. Two non-green rows; both not PR-caused:

# Failure Disposition
1 Bugfix validation (functional tests) / 04274_105501_correlated_materialized_cte_in_subquery_placeholder Bugfix-validation framework quirk — same as on prior SHA ad69a66. The added regression test rejects the correlated-CTE IN shape via the analyzer (NOT_IMPLEMENTED/UNSUPPORTED_METHOD) on both master and PR HEAD — so the framework's "must FAIL on master, PASS on PR" gate cannot be satisfied. The deep PLACEHOLDER planner crash only triggers via AST-fuzzer mutation chains, not from the captured query alone. The fix is still real (it's the inner FutureSetFromSubquery::build guard), and the test still exercises the surrounding rejection paths.
2 Unit tests (msan, function_prop_fuzzer) / FunctionsStress — Logical error: 'key0->size() > i' Chronic unrelated trunk bug. 30-day cross-PR distribution: 27 unrelated PRs hit it (master has 14 hits, including 2026-06-04 12:10 UTC). Tracked separately in our internal task; sighting recorded. Unrelated to PreparedSets / PLACEHOLDER.

All other 162 checks pass: every Build (arm/amd matrix), Stateless tests (incl. parallel/sequential, s3/azure/replicated variants, distributed-plan, parallel-replicas, WasmEdge), Integration tests, Stress (all sanitizers), AST fuzzer (4 variants), BuzzHouse (4 variants), Performance Comparison, Unit tests (asan/tsan/msan + function_prop_fuzzer non-msan slots), SQLLogic, Compatibility, Install, Docker, Code Review, Fast test, Style.

Awaiting re-review from @novikd / @vdimir.

@evillique evillique mentioned this pull request Jun 5, 2026
1 task
Comment thread src/Interpreters/PreparedSets.cpp Outdated
/// Check before consuming `source` so a short-circuit leaves the stored subquery plan
/// intact, matching the `buildSetInplace` / `buildOrderedSetInplace` contract (otherwise
/// `getQueryPlan` would later see a subquery set with no plan).
if (hasCorrelatedExpressions(source->getRootNode()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai, It is not correct. Materialized CTE should not be correlated with subqueries. Just add a check in the QueryAnalyzer if the Materialized CTE body is a correlated subquery.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, pivoted to the analyzer as you asked. Master already rejects a correlated MATERIALIZED CTE in the join-tree path (resolveQueryJoinTreeNode, Materialized CTE '...' cannot be correlated). The gap was the identifier-resolution path used when the CTE is the RHS of IN (... WHERE x IN (t)): with enable_materialized_cte = 1 it was unguarded and the server aborts.

This change adds the same check on that path, mirroring the join-tree one (same UNSUPPORTED_METHOD code and message). The defensive FutureSetFromSubquery::build guard is removed and PreparedSets.cpp reverts to master; the build-path unit test is dropped. New SQL test 04322_105501_correlated_materialized_cte_in_subquery covers the IN path (aborts on master without this change) and confirms a non-correlated MATERIALIZED CTE in IN still works.

Pushed as 55127470e8ab.

groeneai and others added 2 commits June 10, 2026 18:49
…/fix-105501-placeholder-action-in-creating-sets-build
Per @novikd's review on ClickHouse#105518: the PLACEHOLDER LOGICAL_ERROR (ClickHouse#105501) is a
symptom of the analyzer letting a correlated MATERIALIZED CTE through. A
MATERIALIZED CTE materializes once and cannot depend on outer-scope columns, so
its body cannot be a correlated subquery. Master already rejects this in the
join-tree resolution path (resolveQueryJoinTreeNode), but the identifier-
resolution path (a MATERIALIZED CTE used as the right-hand side of IN) was not
guarded. With enable_materialized_cte=1 such a query aborts the server
(SIGABRT) instead of failing with a clean error.

Add the same correlation check on the identifier-resolution path, mirroring the
existing join-tree check (same UNSUPPORTED_METHOD code and message). This fixes
the bug at its source, so the defensive guard previously added in
FutureSetFromSubquery::build is removed and PreparedSets.cpp is reverted to
master. The build-path unit test is dropped with it. The new SQL regression test
exercises the IN path (which aborts on master without this change) and confirms
a non-correlated MATERIALIZED CTE in IN still works.

Closes: ClickHouse#105501

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai groeneai changed the title Guard against PLACEHOLDER execution in FutureSetFromSubquery::build Reject correlated MATERIALIZED CTE used in IN at analysis time Jun 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On master fc73f46fae6: clickhouse local -q "SET enable_analyzer=1; SET allow_experimental_correlated_subqueries=1; SET enable_materialized_cte=1; WITH t AS MATERIALIZED (SELECT number FROM primes(5)) SELECT * FROM numbers(8) WHERE number IN (t);" aborts the server (SIGABRT, RC=134) every time.
b Root cause explained? A MATERIALIZED CTE materializes once and cannot depend on outer-scope columns. When its body references a column absent from its own FROM (e.g. number over primes(5) whose column is prime), the name resolves against the outer query, making the CTE correlated. The analyzer rejects this in the join-tree path (resolveQueryJoinTreeNode), but the identifier-resolution path taken for x IN (t) was unguarded, so a PLACEHOLDER-bearing set plan reached the planner and aborted with Trying to execute PLACEHOLDER action.
c Fix matches root cause? Yes. The check is added at the source (analyzer identifier-resolution of a materialized CTE body), rejecting the malformed query before any plan is built, mirroring the existing join-tree check. It is not a downstream guard on the symptom.
d Test intent preserved / new tests added? New SQL test 04322_105501_correlated_materialized_cte_in_subquery asserts the IN-path rejection (serverError UNSUPPORTED_METHOD) for the original fuzzer shapes and confirms a non-correlated MATERIALIZED CTE in IN still returns rows. The old build-path unit test and .sh test are removed since the FutureSetFromSubquery::build guard they exercised is gone.
e Both directions demonstrated? Yes. Without the change (master): the IN cases SIGABRT. With the change: they fail cleanly with UNSUPPORTED_METHOD: Materialized CTE 't' cannot be correlated, the non-correlated case returns 0,1,2,3,4, and the test output matches the reference. serverError enforcement confirmed (a deliberately wrong expected code reports Expected server error code: 48 but got: 1).
f Fix is general, not a narrow patch? Yes. The two materialized-CTE resolution entry points (join-tree and identifier-resolution) now both enforce the same invariant with the same error. Covers single-column, tuple, and UNION-body CTEs, double IN use, and the optimizer-pessimising settings the fuzzer combined with the crash. PreparedSets.cpp is reverted to master, so no symptom-level guard remains.

Session id: cron:clickhouse-worker-slot-17:20260610-184200

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished (Finish Workflow passed). Failures, both pre-existing, none PR-caused (this PR is analyzer-only -- QueryAnalyzer.cpp rejecting correlated MATERIALIZED CTE in IN):

  • Stateless tests (arm_asan_ubsan, azure, sequential) -- azure-infra-outage / db-disk "Server died" chronic class.
  • Stress test (arm_asan_ubsan, s3) -- generic stress instability (Received signal 6 during compatibility-mode run); an analyzer CTE-rejection change cannot cause a storage stress SIGABRT.
    No Fast/Bugfix/Style failure.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Additional provenance: this change also fixes a second AST-fuzzer symptom of the same root cause, STID 2508-37d4 (Logical error: 'table_holder.has_value()', AST fuzzer (amd_debug)).

Same root cause (a correlated MATERIALIZED CTE used as the RHS of IN, unguarded on the identifier-resolution path), different crash site. The fuzzer query reaches inlineMaterializedCTEIfNeeded (src/Analyzer/inlineMaterializedCTEIfNeeded.cpp:64) with a reused_materialized_cte entry whose table_holder was never finalized, so MaterializedCTE::extractTableHolder (src/Interpreters/MaterializedCTE.h:67) aborts.

Verified both directions on master HEAD fc73f46fae6 (debug) with the auto-reduced fuzzer query from STID 2508-37d4:

  • pristine master: SIGABRT at MaterializedCTE.h:67 via inlineMaterializedCTEIfNeeded -> QueryAnalyzer::resolve.
  • with this PR's correlation guard on the IN path: no abort (the query then fails only on the fuzzer's remote('127.0.0.{1,2}', ...) noise, not in the analyzer).

CIDB: STID 2508-37d4 has 2 hits in 90d (PR #100573 on 2026-03-24, PR #82414 on 2026-06-09), 0 on master, no separate open issue. No separate fix PR needed; folding it under this one.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Additional provenance: this also fixes a third AST-fuzzer symptom of the same root cause, STID 0250-20a8 / issue #80564 (Logical error: 'Column ... query tree node does not have valid source node after running QueryAnalysis pass', aborting in QueryTreePassManager::ValidationChecker::visitColumn).

Same root cause (correlated MATERIALIZED CTE as the RHS of IN, unguarded on the identifier-resolution path), different crash site: with the optimizer settings the fuzzer combined here, resolution proceeds and a correlated ColumnNode survives QueryAnalysis with a null source, so the post-pass validator aborts instead of the planner hitting PLACEHOLDER.

Verified both directions on master 4fc87f09390 (debug) with the reduced query from STID 0250-20a8:

WITH t AS MATERIALIZED (SELECT number FROM zeros_mt(1))
SELECT * FROM numbers(1) WHERE number IN (t) SETTINGS enable_materialized_cte = 1;
  • pristine master: SIGABRT (valid source node) in ValidationChecker::visitColumn.
  • with this PR's correlation guard: clean UNSUPPORTED_METHOD ("Materialized CTE 't' cannot be correlated").

CIDB: STID 0250-20a8 valid-source-node signature has 0 master hits and 27 hits across 15 unrelated PR branches over 90d (it surfaces on whichever PR the fuzzer happens to run on); first seen 2026-03-19. #80564 is OPEN with the fuzz label. No separate fix PR needed; folding it under this one.

Session: cron:clickhouse-worker-slot-2:20260612-230800

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very good fix, LGTM!

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, investigate and fix the abort here: Stateless tests (arm_asan_ubsan, azure, sequential)

@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Investigated. The abort is not from this PR's code. It is heap-corruption fallout from #106020 (Multi-stage distributed queries), which was reverted on master by #107122 (merged 2026-06-11 01:37 UTC, "fixes ASan heap corruption on master"). This branch's base predated that revert.

Evidence:

Fix: merged current master into the branch (now bc4d6b5), which picks up revert #107122, so the abort cannot recur. CI is re-running.

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 9/10 (90.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 11 line(s) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished green on HEAD bc4d6b53c60 (the merge-master that picked up revert #107122). 232733 tests OK, 0 FAIL/ERROR; Finish Workflow and Mergeable Check both SUCCESS. The only red status is CH Inc sync, an internal ClickHouse-Inc sync status unrelated to CI correctness. No failures to address.

@alexey-milovidov
alexey-milovidov merged commit d73bcbc into ClickHouse:master Jun 21, 2026
165 of 166 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 21, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Reject correlated MATERIALIZED CTE used in IN at analysis time

ClickGap verified: reproduced it with the script below on 26.5; tested 4 version(s) — 3 affected, 1 clean (see Affects); bisected to a candidate range — a single introducing PR could not be pinned (see Bisect).

Reproduction

-- enable_materialized_cte lets a MATERIALIZED CTE whose body is a correlated
-- subquery reach the planner; using it as the RHS of IN crashed the server.
-- primes(5) exposes column `prime` (not `number`), so the inner `number`
-- binds to the outer numbers(8) -> the CTE body is correlated.
SET enable_analyzer = 1;
SET allow_experimental_correlated_subqueries = 1;
SET enable_materialized_cte = 1;
WITH t AS MATERIALIZED (SELECT number FROM primes(5))
SELECT * FROM numbers(8) WHERE number IN (t);
-- Pre-fix: server LOGICAL_ERROR (Code 49 -- "Trying to execute PLACEHOLDER
--   action" / "... query tree node does not have valid source node").
-- Fixed:   rejected at analysis time with UNSUPPORTED_METHOD
--   ("Materialized CTE 't' cannot be correlated").

Bisect

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3
  • Does NOT reproduce on: master
  • Could not test (binary unavailable): 26.2, 26.1
  • Backport needed: 26.5, 26.4, 26.3

Suggested next step

The bisect boundary above narrows the search in comp-query-analyzer — treat the candidate range as the starting point; the single introducing PR is unconfirmed.

Component: comp-query-analyzer
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @novikd


ClickGap · Finding: phase_d_pr105518

Triage metadata

  • Primary component: comp-query-analyzer
  • Secondary components: comp-testing
  • Component owners (comp-query-analyzer): @KochetovNicolai @novikd

@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

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 pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: Trying to execute PLACEHOLDER action (STID: 1611-343c)

6 participants