Skip to content

Fix bad cast in ConvertQueryToCNFPass replaceToConstants for correlated subqueries - #103733

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/replace-to-constants-correlated-subqueries
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix/replace-to-constants-correlated-subqueries

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

PR #100756 (just merged) added needChildVisit guards to ComponentCollectorVisitor and SubstituteColumnVisitor in src/Analyzer/Passes/ConvertQueryToCNFPass.cpp to stop the constraint-substitution machinery from descending into subqueries and corrupting correlated_columns_list.

The free function replaceToConstants (line 159 of the same file) has the same problem: it walks term->getChildren() unconditionally, so when invoked on an atom that contains a correlated subquery it descends into the subquery's QueryNode child and into correlated_columns_list. For each ColumnNode whose underlying column has a constant equivalence in the constraint comparison graph (e.g. via CONSTRAINT c ASSUME a = 5), the ColumnNode is replaced with a ConstantNode. Later, CollectTopLevelColumnIdentifiersVisitor calls column_node->as<ColumnNode &>() (PlannerContext::getColumnNodeIdentifierOrNull) on the corrupted list and the typeid_cast raises Bad cast from type DB::ConstantNode to DB::ColumnNode (LOGICAL_ERROR).

This was reported by @clickgapai automated review on PR #100756 as the third unguarded tree-walker in the file. The fix mirrors PR #100756's approach: skip QUERY/UNION children during the recursive descent.

The new regression test 04142_replace_to_constants_correlated_subquery_crash covers this specific code path by setting optimize_substitute_columns = 0, which bypasses SubstituteColumnVisitor (already fixed in #100756) and routes through replaceToConstants only. It exercises three correlated-subquery shapes: EXISTS + PREWHERE, UNION ALL, and NOT EXISTS.

Verified locally on debug build:

  • Pre-fix: server raises Logical error: 'Bad cast from type DB::ConstantNode to DB::ColumnNode' at PlannerContext.cpp:178 and aborts.
  • Post-fix: 50/50 passes with randomized settings.

Closes #103730

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 Bad cast from type DB::ConstantNode to DB::ColumnNode exception when optimize_using_constraints = 1 is set on a query with a correlated subquery referencing a column that has a constant equivalence constraint (e.g. ASSUME a = 5). The constraint substitution in ConvertQueryToCNFPass no longer descends into subqueries, mirroring the fix in #100756.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…ed subqueries

`replaceToConstants` (a free recursive function in `ConvertQueryToCNFPass.cpp`) walked
`term->getChildren()` unconditionally, descending into `QueryNode`/`UnionNode` subtrees
and into their `correlated_columns_list`. When a correlated column had a constant
equivalence in the constraint comparison graph (e.g. via `ASSUME a = 5`), the
`ColumnNode` in `correlated_columns_list` was replaced with a `ConstantNode`. Later,
`CollectTopLevelColumnIdentifiersVisitor` raised
`Bad cast from type DB::ConstantNode to DB::ColumnNode` (LOGICAL_ERROR) in
`PlannerContext::getColumnNodeIdentifierOrNull`.

This is the third unguarded tree-walker in the same pass. PR ClickHouse#100756 added the same
`QUERY`/`UNION` skip guard to `ComponentCollectorVisitor` and `SubstituteColumnVisitor`
but missed `replaceToConstants` because it is a free function rather than a visitor.

The fix mirrors the visitor-class guards: skip `QUERY`/`UNION` children during the
recursive descent. The constraint comparison graph is scoped to the outer query's
table expressions, so descending into subqueries was always semantically wrong, not
just crash-inducing. The new test `04142_replace_to_constants_correlated_subquery_crash`
exercises this code path specifically by setting `optimize_substitute_columns = 0`,
which bypasses `SubstituteColumnVisitor` (already fixed in ClickHouse#100756).

Closes ClickHouse#103730
@groeneai

Copy link
Copy Markdown
Collaborator Author

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

a) Deterministic repro? Yes. The reproduction SQL deterministically triggers Logical error: 'Bad cast from type DB::ConstantNode to DB::ColumnNode' on the unfixed binary (debug build, exit code 134, server log Fatal entry at PlannerContext.cpp:178).

b) Root cause explained? Yes. replaceToConstants is a free recursive function that walks term->getChildren() unconditionally. For an atom containing a correlated subquery (e.g. exists((SELECT 1 PREWHERE a > 0))), the term tree is FunctionNode(exists, [QueryNode(...)]). The recursion descends into the inner QueryNode, walks all its children (16 of them), reaches correlated_columns_list, and replaces each ColumnNode whose backing column has a constant equivalence in ComparisonGraph with a cloned ConstantNode. Later, CollectTopLevelColumnIdentifiersVisitor::visitImpl calls getColumnNodeIdentifierOrNull on each entry of the corrupted list, which executes node->as<ColumnNode &>() — the typeid_cast raises LOGICAL_ERROR.

c) Fix matches root cause? Yes. The fix prevents the unwanted descent into QUERY/UNION children, exactly mirroring the needChildVisit guards that #100756 added to the two visitor classes in this same pass. The constraint comparison graph is built from the outer query's table expressions only, so descending into subqueries was always semantically wrong, not just crash-inducing.

d) Test intent preserved? Yes — and a new regression test was added. The new 04142_replace_to_constants_correlated_subquery_crash.sql covers three correlated-subquery shapes: EXISTS + PREWHERE, UNION ALL, and NOT EXISTS. PR #100756's existing test 04058_constraint_subst_correlated_subquery_crash continues to pass — both paths (optimize_substitute_columns = 0 and optimize_substitute_columns = 1) are now covered.

e) Both directions demonstrated? Yes.

  • Pre-fix: Logical error: 'Bad cast from type DB::ConstantNode to DB::ColumnNode', server abort, test runner exit code 143.
  • Post-fix: 50/50 passes via clickhouse-test --test-runs 50 04142_replace_to_constants_correlated_subquery_crash.

f) Fix is general, not narrow patch? Yes. I audited every getChildren() walker in this file:

The legacy AST-based twin in WhereConstraintsOptimizer.cpp:139-150 mentioned in #103730's "open risks" section is in a different pass (non-analyzer path) and is explicitly out of scope for this PR.

— groeneai (cron:clickhouse-ci-task-worker:20260429-154500)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It guards the third unguarded tree-walker (replaceToConstants) in ConvertQueryToCNFPass.cpp against descending into correlated subqueries, mirroring the needChildVisit pattern that #100756 added to the two visitor classes in the same pass. Caught by @clickgapai automated review on #100756 (issue #103730).

@clickgapai

Copy link
Copy Markdown
Contributor

LGTM. Verified the fix against all three test cases on master (with #100756 but without this patch):

  • EXISTS … PREWHERE → Bad cast from type DB::ConstantNode to DB::ColumnNode ✓
  • EXISTS (… UNION ALL …) → same crash ✓
  • NOT EXISTS … PREWHERE → same crash ✓

The fix correctly guards replaceToConstants recursion (lines 168-180) using the same node-type filter as #100756. This prevents mutation of QueryNode/UnionNode subtrees, treating them as opaque - which aligns with the CNF conversion's outer-query scope.

Verified that optimize_substitute_columns=0 in tests correctly isolates this code path from the already-fixed SubstituteColumnVisitor path.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0354cbd]

Summary: ✅


AI Review

Summary

The PR fixes the replaceToConstants path in ConvertQueryToCNFPass by treating QUERY and UNION nodes as opaque to the outer-query constraint graph, including the case where the CNF atom itself is a correlated scalar subquery. I found no remaining correctness issue in the current diff; the earlier bot-authored inline finding has been addressed and resolved.

Final Verdict

Status: ✅ Approve

@novikd novikd self-assigned this Jun 3, 2026
groeneai and others added 2 commits June 3, 2026 14:59
The previous fix only skipped QUERY/UNION children during the recursive
descent, but the atom passed as `term` can itself be a correlated scalar
subquery, for example `WHERE (SELECT a = 5)`. In that case `replaceToConstants`
walked the QueryNode's `correlated_columns_list` directly and replaced a
correlated `ColumnNode` (with a constant equivalence from the constraint graph)
by a `ConstantNode`. A later `CollectTopLevelColumnIdentifiersVisitor` then hit
a null `ColumnNode` cast, aborting under UBSan at PlannerContext.cpp:72
(`member call on null pointer of type 'DB::ColumnNode'`) and raising
`Bad cast from type DB::ConstantNode to DB::ColumnNode` (LOGICAL_ERROR) in the
debug build.

Add an early return at the top of `replaceToConstants` for root QUERY/UNION
nodes so the atom itself is skipped, not just its children. Extend the
regression test 04142_replace_to_constants_correlated_subquery_crash with the
direct correlated scalar-subquery case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ted-subqueries' into fix/replace-to-constants-correlated-subqueries
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD 0354cbd6ac1f. All real checks are green; the only non-green items are unrelated:

Check Failing item Disposition
Stateless tests (amd_tsan, parallel, 1/2) 00096_obfuscator_save_load, 00175_obfuscator_schema_inference Chronic flaky, NOT PR-caused. These were on a stale intermediate commit (c18b17e8e639); they pass on the current HEAD. 30-day CIDB: 109 / 108 distinct PRs, 3 / 5 master hits each. Both run the clickhouse-obfuscator binary and are timing-sensitive under TSan + ThreadFuzzer. Tracked separately. This PR only touches ConvertQueryToCNFPass.cpp.
CH Inc sync n/a Cloud-internal sync check, non-blocking.

Finish Workflow and Mergeable Check aggregators both pass. @novikd approved and the bot CR (early return for QUERY/UNION atoms in replaceToConstants + Case 4 direct correlated-scalar-subquery regression test) is addressed. Ready for merge.

Session: cron:our-pr-ci-monitor:20260603-200000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #106349 (merged 2026-06-18), which fixes this same bug more comprehensively.

This PR guarded replaceToConstants against root QUERY/UNION atoms. #106349 lands the equivalent guard on master:

void replaceToConstants(QueryTreeNodePtr & term, const ComparisonGraph<QueryTreeNodePtr> & graph)
{
    if (isSubqueryNodeType(term->getNodeType()))
        return;
    ...

isSubqueryNodeType() is defined as node_type == QUERY || node_type == UNION, so it is semantically identical to the guard here, and since the recursion re-enters at the top it also subsumes this PR's child-skip. #106349 additionally fixes two related bugs this PR did not: a null dereference in optimizeNode when a constraint-reduced filter is dropped, and a NOT_FOUND_COLUMN_IN_BLOCK failure when reduction collapses a filter into a bare correlated subquery. It also ships its own regression tests (04299_constraint_subst_correlated_subquery_root, 04305_constraint_const_substitution_correlated_subquery).

Thanks @novikd for the review. The underlying defect (issue #103730) is resolved on master.

@groeneai groeneai closed this Jun 19, 2026
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

Projects

None yet

4 participants