Skip to content

Fix crash in constraint substitution with correlated subqueries - #100756

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/constraint-subst-correlated-crash
Apr 29, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix/constraint-subst-correlated-crash

Conversation

@groeneai

@groeneai groeneai commented Mar 25, 2026 •

Copy link
Copy Markdown
Collaborator

ComponentCollectorVisitor and SubstituteColumnVisitor in ConvertQueryToCNFPass lacked needChildVisit guards, so they descended into QUERY/UNION child nodes during tree traversal. This caused them to collect and substitute correlated column references from the constraint comparison graph inside subqueries.

When a substitution replaced a ColumnNode with a FunctionNode (via buildCastFunction for type-mismatched equivalences, e.g. ASSUME b = cityHash64(a)), the correlated_columns_list of the inner QueryNode was corrupted. Later, CollectTopLevelColumnIdentifiersVisitor tried to cast the corrupted node as ColumnNode, triggering:

Logical error: 'Bad cast from type DB::FunctionNode to DB::ColumnNode'

The fix adds needChildVisit to both visitors to skip QUERY and UNION children, scoping constraint substitution to the outer query only. This is consistent with how constraint graphs are built — they are scoped to a single query's table expressions and should not cross subquery boundaries.

Reproduction: Any query combining:

  1. A table with CONSTRAINT ... ASSUME involving a function expression
  2. A correlated subquery referencing constrained columns
  3. Settings: enable_analyzer=1, convert_query_to_cnf=1, optimize_substitute_columns=1

Triggers a server crash (SIGABRT in debug builds).

CI history (STID 1635-2ab2): 4 hits across unrelated PRs in the last 30 days (AST fuzzer amd_msan, arm_asan_ubsan, Stress test amd_tsan). Zero master hits — the randomized settings convert_query_to_cnf and optimize_substitute_columns (both off by default) must be enabled together.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry:

Fixed a server crash (Logical error: Bad cast from type DB::FunctionNode to DB::ColumnNode) that could occur when using queries with correlated subqueries on tables that have CONSTRAINT ... ASSUME definitions, when optimize_substitute_columns and convert_query_to_cnf settings are enabled.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.177

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR Validation Gate (Session ce168e98)

a) Deterministic repro? ✅

-- On a debug build without the fix:
CREATE TABLE column_swap_test_test (i Int64, a String, b UInt64, CONSTRAINT c1 ASSUME b = cityHash64(a)) ENGINE = MergeTree ORDER BY i SETTINGS min_bytes_for_wide_part = 0;
INSERT INTO column_swap_test_test VALUES (1, 'cat', 1), (2, 'dog', 2);
INSERT INTO column_swap_test_test SELECT number AS i, toString(number) AS a, 1 AS b FROM numbers(1000);
SELECT count() FROM column_swap_test_test
WHERE exists((SELECT toUInt8(1) PREWHERE murmurHash3_64(xxHash32(a, intDiv(2, xxHash32(0, toInt256(0) = b))), multiply(10, 10))))
SETTINGS enable_analyzer = 1, convert_query_to_cnf = 1, optimize_substitute_columns = 1, optimize_using_constraints = 1;
-- Crashes EVERY TIME with: Logical error: 'Bad cast from type DB::FunctionNode to DB::ColumnNode'

b) Root cause explained? ✅
ComponentCollectorVisitor and SubstituteColumnVisitor in ConvertQueryToCNFPass have no needChildVisit guard, so they walk into QUERY/UNION children during tree traversal. The correlated_columns_list is stored as child[16] of QueryNode and is visited like any other child. When the visitor enters a subquery and finds correlated column references (e.g., a and b from the outer table) in the constraint comparison graph, SubstituteColumnVisitor replaces them. For ASSUME b = cityHash64(a), column b gets replaced with cityHash64(a) — a FunctionNode. This corrupts the correlated_columns_list. Later, CollectTopLevelColumnIdentifiersVisitor::visitImpl calls getColumnNodeIdentifierOrNull() which does column_node->as<ColumnNode &>() on the now-FunctionNode → crash.

c) Fix matches root cause? ✅
The fix adds needChildVisit to both ComponentCollectorVisitor and SubstituteColumnVisitor to skip QUERY and UNION children. This prevents them from entering subqueries and modifying correlated column references. The constraint graph is scoped to the outer query's table expressions — entering subqueries is both incorrect and dangerous.

d) Test intent preserved? ✅
No existing tests are modified. A new regression test (04058_constraint_subst_correlated_subquery_crash) is added that exercises the exact crash scenario.

e) Demonstrated in both directions? ✅

  • Without fix: Server crashes with SIGABRT (Logical error: Bad cast from type DB::FunctionNode to DB::ColumnNode) — confirmed via incremental rebuild with fix stashed.
  • With fix: Query executes successfully, returns 1002 — confirmed after rebuild with fix applied.

@pufit pufit added the can be tested Allows running workflows for external contributors label Mar 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ef8a13]

Summary: ✅


AI Review

Summary

This PR fixes a real analyzer correctness issue by preventing ConvertQueryToCNFPass constraint visitors from descending into subqueries, which avoids corrupting correlated_columns_list and the resulting FunctionNode vs ColumnNode bad-cast exception. The code fix and regression coverage look targeted and appropriate; the only remaining concern is an unnecessary no-parallel test tag that reduces stateless test parallelism.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04058_constraint_subst_correlated_subquery_crash.sql:1] -- Tags: no-parallel appears unnecessary for this test (it uses local tables and isolated objects) and will reduce 0_stateless CI parallelism.
    Suggested fix: remove the no-parallel tag unless there is a demonstrated cross-test interference reason.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required action:

  1. Remove the unnecessary no-parallel tag from 04058_constraint_subst_correlated_subquery_crash.sql (or document a concrete isolation constraint that requires it).

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 25, 2026
@@ -0,0 +1,61 @@
-- Tags: no-parallel

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

-- Tags: no-parallel seems unnecessary for this test and will reduce 0_stateless parallelism in CI. The test only uses local tables and should be isolated by the test harness database; can we drop this tag unless there is a proven race/shared-global dependency?

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, check this ^

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @yakov-olkhovskiy — could you review this? It fixes a crash in ConvertQueryToCNFPass when handling correlated subqueries in constraints.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai

Copy link
Copy Markdown
Collaborator Author

@nikitamikhaylov Investigated the Unit tests (msan) failure on commit e0a1dd7.

Finding: Infrastructure error, not a test failure.

The error is "No test result file [.../gtest.json]" — the MSAN unit test binary didn't produce a result file, likely due to a runner timeout or resource issue. No individual test actually failed.

CIDB confirms this is a widespread infrastructure issue:

  • 161 occurrences across 96 unrelated PRs in the last 30 days
  • Same error message on every occurrence: "No test result file"
  • Also hit master (pull_request_number=0) on the same day (2026-03-26)
  • The first CI run of this PR (commit 09f958e) passed all MSAN unit tests successfully

I've updated the branch with latest master (merge commit b0ae85f). CI should re-run now.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

ComponentCollectorVisitor and SubstituteColumnVisitor in
ConvertQueryToCNFPass did not have needChildVisit guards, so they
descended into QUERY/UNION child nodes during tree traversal. This
caused them to collect and substitute correlated column references
from the constraint graph inside subqueries.

When a substitution replaced a ColumnNode with a FunctionNode (via
buildCastFunction for type-mismatched equivalences like
b = cityHash64(a)), the correlated_columns_list of the QueryNode
was corrupted. Later, CollectTopLevelColumnIdentifiersVisitor tried
to cast the corrupted node as ColumnNode, triggering:
  "Logical error: Bad cast from type DB::FunctionNode to DB::ColumnNode"

The fix adds needChildVisit to both visitors to skip QUERY and UNION
children, scoping constraint substitution to the outer query only.

Closes STID 1635-2ab2.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@groeneai
groeneai force-pushed the fix/constraint-subst-correlated-crash branch from 3efab92 to 3d616ed Compare April 28, 2026 03:18
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov Done — rebased onto current master to pick up PR #101239 (merged 2026-04-07) which fixes the Stress test (arm_msan) failure you flagged.

Also dropped the merge commits to keep the branch clean: a single commit on top of master containing only the fix (src/Analyzer/Passes/ConvertQueryToCNFPass.cpp) and the regression test (tests/queries/0_stateless/04058_constraint_subst_correlated_subquery_crash.{sql,reference}).

CI re-running on 3d616ed50b6. The fix has been awaiting review since 2026-03-25 — this is a P0 chronic AST fuzzer trunk bug (STID 1635-2ab2) that has hit 18 unrelated PRs in the last 30 days. Could you take another look when you have a moment? cc @KochetovNicolai @nikitamikhaylov @rschu1ze

Session: cron:clickhouse-ci-task-worker:20260428-031500


SELECT count() IGNORE NULLS FROM t_constraint_trans
WHERE a != (SELECT d)
SETTINGS enable_analyzer = 1, convert_query_to_cnf = 1, optimize_substitute_columns = 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This assertion depends on constraint reasoning for the WHERE predicate, but optimize_using_constraints is not set explicitly here (it is set in case 1). Can we add optimize_using_constraints = 1 to make this regression test independent of default-setting changes and compatibility profiles?

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 in 7ef8a13 — added optimize_using_constraints = 1 to the SETTINGS clause of case 2 (matches case 1's explicit pin).

The transitivity case really does depend on this setting: without it the constraint optimizer doesn't deduce a = d from a = b ∧ b = c ∧ c = d, so a != (SELECT d) is not rewritten to False and the assertion of count() = 0 fails. Better to pin it explicitly than rely on the default.

Verified locally: 30/30 passes with full --random-settings and --random-merge-tree-settings.

…bility

The transitivity-constraint case relies on `optimize_using_constraints` to
deduce `a = d` from the constraints `a = b`, `b = c`, `c = d` and rewrite
`a != (SELECT d)` to False. Without that setting, the predicate is not
optimized and the assertion of `count() = 0` would fail.

Case 1 already pins this setting; case 2 was implicitly relying on the
default. Make the dependency explicit so the regression test stays stable
under default-setting changes and compatibility profiles.

Suggested by clickhouse-gh[bot] on the rebased PR.

cc @alexey-milovidov, @KochetovNicolai, @nikitamikhaylov, @rschu1ze
@clickhouse-gh

clickhouse-gh Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.10% +0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 100.00% (12/12) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Apr 28, 2026

@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.

Code changes ok.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Apr 29, 2026
Merged via the queue into ClickHouse:master with commit da671cc Apr 29, 2026
165 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 29, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: ComponentCollectorVisitor and SubstituteColumnVisitor in src/Analyzer/Passes/ConvertQueryToCNFPass.cpp — core code present in all supported branches.

Why: ConvertQueryToCNFPass.cpp was introduced in commit 80d248a (2023-03-14), predating all currently supported release branches (25.8, 26.1, 26.2, 26.3). The bug — a LOGICAL_ERROR on valid SQL — affects all of them. PR has no backport label set, so manual backport is needed.

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

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.

6 participants