Repository navigation
Reject correlated MATERIALIZED CTE used in IN at analysis time - #105518
Conversation
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
|
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 (b) Root cause explained? Yes. The inplace set-building paths (c) Fix matches root cause? Yes — the patch moves the existing (d) Test intent preserved? / New tests added? Yes — the change is purely additive (a short-circuit before adding the (e) Demonstrated in both directions? Same caveat as (a). Without the guard, the failing master (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 ( |
|
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 |
|
Workflow [PR], commit [bc4d6b5] Summary: ✅
AI ReviewSummaryThis PR rejects correlated PR Metadata💡 The Fix an exception ( Final VerdictStatus: ✅ Approve |
… 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.
|
Bugfix validation was failing because the SQL test Dropped the SQL test (commit Awaiting CI re-run on |
|
@groeneai merge with master |
…creating-sets-build
|
Merged |
| /// 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())) |
There was a problem hiding this comment.
@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
left a comment
There was a problem hiding this comment.
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:
- the original fuzzer query (3-tuple LHS, 2-column
MATERIALIZEDCTE overzeros(), whose innernumberaccidentally correlates against the outernumbers(8)) - the simplified single-column variant over
primes()that the fuzzer also hit - 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 - 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.
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]>
|
@clickhouse-gh both bot concerns addressed in 1. Moved the 2.
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260604-073000 |
|
CI fully finished on ad69a66. Triage: CI Ledger — covered SHA: ad69a66
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 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).
Pre-PR validation gate
Bugfix validation noteBugfix validation has been failing on this PR because the SQL test @ novikd / @ vdimir — could you either request a maintainer override on Session id: cron:clickhouse-ci-task-worker:20260605-011400 |
|
CI ledger — covered SHA: CI fully finished on this HEAD (Finish Workflow ✅, 162/166 pass).
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. |
CI Ledger — covered SHA:
|
| # | 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.
| /// 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())) |
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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.
…/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]>
Pre-PR validation gate
Session id: cron:clickhouse-worker-slot-17:20260610-184200 |
|
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):
|
|
Additional provenance: this change also fixes a second AST-fuzzer symptom of the same root cause, STID 2508-37d4 ( Same root cause (a correlated Verified both directions on master HEAD
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. |
|
Additional provenance: this also fixes a third AST-fuzzer symptom of the same root cause, STID Same root cause (correlated Verified both directions on master WITH t AS MATERIALIZED (SELECT number FROM zeros_mt(1))
SELECT * FROM numbers(1) WHERE number IN (t) SETTINGS enable_materialized_cte = 1;
CIDB: STID Session: cron:clickhouse-worker-slot-2:20260612-230800 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Very good fix, LGTM!
|
@groeneai, investigate and fix the abort here: Stateless tests (arm_asan_ubsan, azure, sequential) |
…-placeholder-action-in-creating-sets-build
|
@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. |
LLVM Coverage Report
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 |
|
CI finished green on HEAD |
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRReject correlated MATERIALIZED CTE used in IN at analysis time ClickGap verified: reproduced it with the script below on ReproductionBisect
Affects
Suggested next stepThe bisect boundary above narrows the search in Component: cc fix PR author: @groeneai ClickGap · Finding: Triage metadata
|
|
Hi — this looks like a backport candidate for |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a server crash (
Trying to execute PLACEHOLDER actionlogical error) when aMATERIALIZEDCTE whose body is a correlated subquery is used as the right-hand side ofIN. Such a CTE is now rejected at analysis time, consistent with how the same pattern is already rejected when the CTE is referenced directly inFROM.Description
Issue #105501 (STID 1611-343c). A
MATERIALIZEDCTE 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 ofIN(... WHERE x IN (t)), was not guarded. Withenable_materialized_cte = 1such a query reaches the planner with aPLACEHOLDER-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_METHODcode and message). The earlier defensive guard inFutureSetFromSubquery::buildis removed andPreparedSets.cppreverts to master; the build-path unit test is dropped with it.New regression test
04322_105501_correlated_materialized_cte_in_subqueryexercises the IN path (which aborts on master without this change) and confirms a non-correlatedMATERIALIZEDCTE inINstill works.Closes #105501
Version info
26.6.1.1086