Skip to content

Fix crash in constraint optimization with correlated subqueries - #106349

Merged
Algunenano merged 8 commits into
ClickHouse:masterfrom
Algunenano:fix-cnf-substitute-correlated-subquery-root
Jun 18, 2026
Merged

Algunenano merged 8 commits into
ClickHouse:masterfrom
Algunenano:fix-cnf-substitute-correlated-subquery-root

Conversation

@Algunenano

@Algunenano Algunenano commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

Constraint-based query optimization (optimize_using_constraints + convert_query_to_cnf + optimize_substitute_columns) could crash the server, or fail a valid query, when a filter contained a correlated subquery.

When constraint reduction proves part of an OR is always false, it collapses a filter such as WHERE (b < d) OR (SELECT a < c) into the bare correlated subquery WHERE (SELECT a < c). Two things then went wrong:

  1. Column substitution only treated subqueries as opaque when they were reached as a child node, so with the subquery now at the clause root it rewrote the subquery's correlated columns into _CAST FunctionNodes. Planning later called ColumnNode::getColumnSource on a non-column node and aborted (signal 6). Subqueries are now treated as opaque boundaries whether they are a clause root or nested in an expression.

  2. The collapse itself leaves a bare correlated subquery as the whole predicate, which cannot be decorrelated and failed with NOT_FOUND_COLUMN_IN_BLOCK, even though the query runs fine with the optimization disabled. This collapse is now detected and the original filter is kept.

cc @novikd

Closes #106118

Changelog category (leave one):

  • Critical Bug Fix (crash, data loss, RBAC)

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

Fix a crash and a possible NOT_FOUND_COLUMN_IN_BLOCK error when constraint-based optimization (optimize_using_constraints) is used with correlated subqueries.

Version info

  • Merged into: 26.6.1.990
  • Backported to: 26.5.3.47, 26.4.5.55, 26.3.14.45, 25.8.25.28

…d subqueries

`ConvertLogicalExpressionToCNFPass` optimizes filters using table constraints. Two problems
show up when a filter references a correlated subquery:

1. Column substitution treated subqueries as opaque only when they were reached as a child
   node. When constraint reduction collapses a filter such as `cond OR (subquery)` into the
   bare subquery, the subquery becomes the clause root, so substitution walked into its
   `correlated_columns_list` and replaced the correlated `ColumnNode`s with `_CAST`
   `FunctionNode`s. Planning then called `ColumnNode::getColumnSource` on a non-column node
   and aborted on an out-of-bounds vector access. Subqueries are now treated as opaque
   boundaries whether they are a clause root or nested inside an expression, via a shared
   `isSubquery` helper.

2. The reduction itself can collapse a filter into a bare correlated subquery (for example
   when the constraint proves the rest of an `OR` is always false). Such a subquery cannot
   be decorrelated and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`, even though it
   runs fine with the optimization disabled. This collapse is now detected in `optimizeNode`
   and the original filter is kept.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1035d9f]

Summary: ✅


AI Review

Summary

This PR makes constraint-based CNF optimization treat subqueries as opaque boundaries, extends the same boundary to replaceTermsToConstants, and keeps the original predicate when reduction would leave a standalone correlated subquery that the current planner cannot always decorrelate. I found no unresolved correctness, safety, metadata, or test-evidence issues in the current diff; the earlier bot finding about replaceTermsToConstants crossing into subqueries is fixed and remains resolved.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! labels Jun 2, 2026
`optimizeNode` checked `isCorrelatedQueryOrUnionNode(new_node)` without guarding against a
null `new_node`. When constraint reduction proves the whole filter always-true it is dropped
and `cnf->toQueryTree` returns null (for example `WHERE b = 1 OR b < 18 OR b > 5` under a
constraint). `isCorrelatedQueryOrUnionNode` dereferences the node, so this segfaulted. Guard
the check with a null test; a dropped filter is fine to apply as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Algunenano and others added 2 commits June 2, 2026 21:46
`replaceToConstants` (used by `optimizeWithConstraints` via `transformAtoms`) recursed into
every child without stopping at subqueries. With a constant-equality constraint such as
`ASSUME a = 'x'`, an atom like `exists(SELECT ... WHERE outer.a = inner.a)` had its correlated
`ColumnNode` replaced by a `ConstantNode`, corrupting the subquery's `correlated_columns_list`.
The planner casts those entries as `ColumnNode`s, raising `Bad cast from type DB::ConstantNode
to DB::ColumnNode` (`LOGICAL_ERROR`).

Make `replaceToConstants` treat subqueries as opaque boundaries, like the other tree walks in
this pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

@groeneai Could you review please?

@clickgapai Could you review please?

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

LGTM. The bot's replaceTermsToConstants concern is already addressed by commit c66735859ffb ("Stop constant substitution from crossing into subqueries"), pushed 2026-06-02 21:46 UTC, ~2.5h after the bot's review. The fix matches what the bot asked for:

  • replaceToConstants now does if (isSubquery(term)) return; at the top (line 175 of the post-merge file). Since the helper recurses by calling itself on every child, the early-return at the root applies symmetrically when (a) the cloned atom IS itself a QUERY/UNION, and (b) when a QUERY/UNION is reached via the child loop from an outer FunctionNode (e.g. the subquery argument of EXISTS). Both directions are covered by a single guard at function entry.
  • The bot's exact scenario, ASSUME a = 'x' + EXISTS(SELECT ... WHERE outer.a = inner.a), is exercised by the new regression tests/queries/0_stateless/04305_constraint_const_substitution_correlated_subquery.sql, with the inverse "optimization disabled must return the same value" check immediately after.
  • isSubquery only matches QueryTreeNodeType::QUERY and UNION. Per src/Analyzer/IQueryTreeNode.h, those are the only node types whose children include a correlated_columns_list (see LAMBDA for contrast — it has its own arguments/expression, not correlated columns), so the predicate covers exactly the right nodes.

A couple of observations not blocking merge:

  1. The header comment on isSubquery is the only place that documents the asymmetry between clause-root and expression-nested subqueries; the per-call-site comments at replaceToConstants, ComponentCollectorVisitor::needChildVisit, SubstituteColumnVisitor::needChildVisit, and the new run_unless_subquery lambda all defer to it via "(see isSubquery)" or no comment at all. The original local comments at the visitors documented the failure mode (bad cast crash in CollectTopLevelColumnIdentifiersVisitor) that the deduplicated header now omits. Either is fine, but if you keep the deduplication, the linked issue numbers / failure-class wording from the old comments could be lifted into the isSubquery header so the trail to the original bad-cast LOGICAL_ERROR isn't lost.

  2. The new optimizeNode guard if (new_node && isCorrelatedQueryOrUnionNode(new_node)) return; reverts to node unchanged when the constraint-reduced filter is exactly a bare correlated subquery. For the tracked shape ((b < d) OR (SELECT a < c) with b<d reducing to false), new_node is the bare correlated subquery and the early-return is correct. For a constraint-reduced filter where new_node is null (the filter was dropped entirely), the comment notes the assignment is fine; that path then runs node = std::move(new_node); and produces a null node, which I assume the surrounding optimizeWithConstraints consumer treats as "drop this filter" — worth a quick verification at the call site that null filter assignment is its happy path here, because the previous behaviour was non-null only.

The Bugfix-validation red is unrelated infrastructure noise: the runner self-terminated with a TCPHandler.2137-5526 core during the final system flush logs shutdown ("Bugfix validation inconclusive: the test runner did not finish; preserving ERROR rather than reporting 'Failed to reproduce the bug'"), not a regression test failure. AST fuzzer (debug, asan_ubsan, msan, tsan) and stress test on every sanitizer pass.

cron:clickhouse-ci-task-worker:20260608-165700

@novikd novikd self-assigned this Jun 9, 2026
@Algunenano
Algunenano requested a review from novikd June 12, 2026 14:55
@Algunenano
Algunenano requested review from novikd and removed request for novikd June 17, 2026 15:28
Algunenano and others added 3 commits June 17, 2026 17:52
Drop the local `isSubquery` helper and call the existing `isSubqueryNodeType` from
`Analyzer/Utils.h`, which has the same semantics. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A standalone correlated subquery predicate is not inherently un-decorrelatable (e.g.
`SELECT * ... WHERE (SELECT a < c)` works). It currently fails only when the outer plan does
not keep the captured columns (e.g. `SELECT count() ... WHERE (SELECT a < c)` raises
NOT_FOUND_COLUMN_IN_BLOCK). Reword the comment to describe that accurately instead of claiming
such subqueries cannot be decorrelated. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickgapai

Copy link
Copy Markdown
Contributor

Reviewed the second half of the fix — the new early-return in optimizeNode — since @groeneai already covered the substitution guards (point 1). It holds up.

Confirmed the bug is real. On the master binary (no fix), the count() reproducer never returns — clickhouse local hung for >3 min on:

SELECT count() FROM t_cr WHERE (b < d) OR (SELECT a < c)
SETTINGS enable_analyzer=1, convert_query_to_cnf=1, optimize_substitute_columns=1, optimize_using_constraints=1;

(constraint forces all columns equal, so b<d collapses and only the bare correlated subquery survives). I couldn't run the PR binary itself — no server is up on :19000 in this env — so I'm validating by code review, not by executing the patched path.

The point-2 guard is correctly narrow. ConvertQueryToCNFPass.cpp uses isCorrelatedQueryOrUnionNode(new_node), not the broader isSubqueryNodeType. That's the right call:

  • isCorrelatedQueryOrUnionNode (Utils.cpp:259) only fires when the node is a QUERY/UNION whose isCorrelated() is true (QueryNode.h:647 / UnionNode.h:187).
  • A non-correlated scalar subquery as a whole predicate decorrelates fine, so suppressing the optimization for it would be a needless miss. Only the correlated case raises NOT_FOUND_COLUMN_IN_BLOCK. The guard targets exactly that.

Scope is honest and conservative. The guard only catches a correlated subquery that is the entire new_node. A wrapped form (WHERE NOT (SELECT…), or a correlated subquery as one CNF conjunct) leaves new_node as a FunctionNode, so the guard won't fire — but those paths aren't newly created by the collapse, and the needChildVisit/run_unless_subquery guards still prevent the bad-cast crash. So worst case is a missed optimization, never a wrong result or crash. The comment says as much.

No new bug found, and I don't think an extra test is warranted — the two shipped tests plus the disabled-optimization cross-checks cover both the substitution and collapse paths. LGTM from me too.

@clickgapai

Copy link
Copy Markdown
Contributor

@Algunenano I reviewed the diff and reproduced the underlying crash. Findings: 1. The documented crash is real — I reproduced it. Running the PR's own repro sql SELECT count() FROM t WHERE (b < d) OR (SELECT a < c) SETTINGS enable_analyzer=1, convert_query_to_cnf=1, optimize_substitute_columns=1, optimize_using_constraints=1; aborts with signal 6, stack: ColumnNode::getColumnSource() GlobalPlannerContext::collectTableExpressionDataForCorrelatedColumns(...) buildPlannerForCorrelatedSubquery(...) Planner::buildPlanForQueryNode() That's exactly crash #1 in the description: substitution rewrote the subquery's correlated column into a non-ColumnNode, and the correlated-subquery planner then called getColumnSource() on it. Caveat: the binary I had access to is pre-fix (it still crashes), so I verified the bug at runtime but the fix only by static analysis — I couldn't run a fixed binary here. 2. The two needChildVisit hunks are behavior-preserving. isSubqueryNodeType(t) is literally t==QUERY || t==UNION (src/Analyzer/Utils.cpp:237), so !isSubqueryNodeType(child) ≡ the old child!=QUERY && child!=UNION. Pure readability refactor, no semantic change — good. 3. The two new guards correctly cover what needChildVisit can't reach. needChildVisit only blocks descent into subquery children; a clause that is itself a subquery is the visit root and bypasses it. run_unless_subquery (substituteColumns) and the isCorrelatedQueryOrUnionNode(new_node) check in optimizeNode plug exactly those root-position holes. groeneai already covered the symmetric early-return in replaceToConstants — agree with that. 4. The isCorrelatedQueryOrUnionNode guard is correctly narrow, which I want to call out as a positive. It only skips when the whole collapsed predicate is a correlated Query/Union node (src/Analyzer/Utils.cpp:259). It deliberately does not fire when: - the root is an uncorrelated scalar subquery (e.g. WHERE (SELECT max(x) FROM other)) — that needs no decorrelation and stays optimized; and - the subquery is nested inside a function ((SELECT …) AND x) — root is a FunctionNode, decorrelation of nested correlated subqueries already works. So the guard avoids both over-skipping and the crash. I couldn't construct a collapse

(trimmed for brevity)

@clickgapai

Copy link
Copy Markdown
Contributor

@Algunenano I reviewed the diff and reproduced both failure modes the PR fixes:

  • 04299 (bare-root collapse): WHERE (b < d) OR (SELECT a < c) with the three optimizer settings on aborts in DB::ColumnNode::getColumnSource() → collectTableExpressionDataForCorrelatedColumns; the same query with the optimizations off returns 1, so it's an optimizer-path crash, not a semantics issue.
  • 04305 (const substitution into subquery): the EXISTS (... WHERE inner.a = outer.a) query throws Bad cast from DB::ConstantNode to DB::ColumnNode (LOGICAL_ERROR) — the constraint a = 'x' gets substituted into the correlated column. Both match the PR description.

Source review of the fix (ConvertQueryToCNFPass.cpp) holds up:

  1. replaceToConstants early-return on isSubqueryNodeType stops constant substitution at the subquery boundary (fixes 04305).
  2. The needChildVisit switch to !isSubqueryNodeType(...) is behavior-identical (isSubqueryNodeType == QUERY || UNION) — a readability refactor.
  3. run_unless_subquery in substituteColumns guards the clause-root case the structural guard can't reach.
  4. The optimizeNode guard only suppresses optimization when the whole predicate collapses to a correlated query/union; non-correlated scalar subqueries still get optimized, and it keeps the original filter, so a working query never becomes failing.

One caveat: I verified the bugs reproduce but couldn't run the patched binary directly, so I'm relying on the CI coverage report and @groeneai's review for the fix side. Optional belt-and-suspenders: a nested-but-non-root correlated case (WHERE (b<d) OR NOT (SELECT a<c)) to pin the guard as intentionally bare-root-only. LGTM on my end.

@clickhouse-gh

clickhouse-gh Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.30% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 27/28 (96.43%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jun 18, 2026
Under `s3 storage` the stateless randomizer could pick a tiny
`index_granularity` (e.g. 19), producing ~31578 marks for the test
tables. On object storage a multi-column read issues roughly one S3 GET
per granule (single-column reads coalesce into a couple of large GETs,
multi-column reads do not), so each string-key `GROUP BY a` plus
aggregate-of-`b` query made ~15792 S3 GET requests and spent ~70s in S3
read initialization. Eight such queries pushed the `long` test past the
600s limit and timed out.

Clamp the randomized `index_granularity` to a floor of 8192 (still
randomized up to 65536) via the `Random settings limits` directive,
keeping coverage while bounding the per-granule read amplification.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106349&sha=1035d9f91c950f79da75fd6429d6c56dfe7999b4&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20parallel%2C%201%2F2%29
PR with the report: ClickHouse#106349

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Algunenano
Algunenano enabled auto-merge June 18, 2026 15:11
@Algunenano
Algunenano added this pull request to the merge queue Jun 18, 2026
Merged via the queue into ClickHouse:master with commit abdb6a3 Jun 18, 2026
322 of 326 checks passed
@Algunenano
Algunenano deleted the fix-cnf-substitute-correlated-subquery-root branch June 18, 2026 16:31
robot-ch-test-poll4 added a commit that referenced this pull request Jun 18, 2026
Cherry pick #106349 to 26.5: Fix crash in constraint optimization with correlated subqueries
robot-clickhouse added a commit that referenced this pull request Jun 18, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 18, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 18, 2026
Algunenano added a commit that referenced this pull request Jun 19, 2026
Backport #106349 to 26.5: Fix crash in constraint optimization with correlated subqueries
robot-ch-test-poll4 added a commit that referenced this pull request Jun 19, 2026
Cherry pick #106349 to 26.3: Fix crash in constraint optimization with correlated subqueries
robot-clickhouse added a commit that referenced this pull request Jun 19, 2026
robot-ch-test-poll4 added a commit that referenced this pull request Jun 19, 2026
Cherry pick #106349 to 26.4: Fix crash in constraint optimization with correlated subqueries
robot-clickhouse added a commit that referenced this pull request Jun 19, 2026
robot-clickhouse added a commit that referenced this pull request Jun 19, 2026
Cherry pick #106349 to 25.8: Fix crash in constraint optimization with correlated subqueries
robot-clickhouse added a commit that referenced this pull request Jun 19, 2026
Algunenano added a commit that referenced this pull request Jun 19, 2026
Backport #106349 to 26.3: Fix crash in constraint optimization with correlated subqueries
Algunenano added a commit that referenced this pull request Jun 19, 2026
Backport #106349 to 26.4: Fix crash in constraint optimization with correlated subqueries
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 19, 2026
Algunenano added a commit that referenced this pull request Jun 19, 2026
Backport #106349 to 25.8: Fix crash in constraint optimization with correlated subqueries
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Jun 22, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…6349

Backport ClickHouse#106349 to 26.4: Fix crash in constraint optimization with correlated subqueries
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…6349

Backport ClickHouse#106349 to 26.3: Fix crash in constraint optimization with correlated subqueries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

Received signal 6 (STID: 3452-4527)

6 participants