Skip to content

Fix vector OOB in ConvertQueryToCNFPass when WHERE is a correlated subquery (STID 3452-4527) - #103738

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:stid-3452-4527-fix-cnf-correlated-substitute
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:stid-3452-4527-fix-cnf-correlated-substitute

Conversation

@groeneai

@groeneai groeneai commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

Fix STID 3452-4527 (P0 AST fuzzer crash in correlated-subquery planning).

Root cause

The constraint-substitution visitors in ConvertQueryToCNFPass (ComponentCollectorVisitor, ColumnNameCollectorVisitor, SubstituteColumnVisitor) only filtered subquery children — needChildVisit checked child_type == QUERY/UNION but ignored the parent. When the visitor is invoked directly on a QueryNode (e.g. CNF + constraints reduce a multi-atom WHERE down to a single correlated subquery), the visitor enters the QueryNode and the parent of its children is the QueryNode. The child filter cannot help — the children (projection, correlated_columns_list, etc.) are ListNode instances, not QueryNode/UnionNode. So the visitor traverses inside the subquery and operates on its correlated_columns_list.

For mixed-type constraints (a UInt16, b String, ... CONSTRAINT ASSUME a <= b ...), the substitution wraps the canonical class member in a _CAST(...) FunctionNode because types differ. The planner later iterates correlated_columns_list expecting ColumnNode, calls column->as<ColumnNode>() on a FunctionNode (returns nullptr), and dereferences the null this inside getSourceWeakPointer. libc++ hardening catches this as vector[] index out of bounds inside std::vector<std::weak_ptr<DB::IQueryTreeNode>>::operator[], surfacing as Received signal 6 (Aborted) on the MSAN AST fuzzer.

Fix

Add a parent-type check to each visitor's needChildVisit: if the parent is a QueryNode/UnionNode, return false. Constraint substitution is scoped to the current query — nested subqueries are processed independently when the outer ConvertQueryToCNFVisitor recurses into them via enterImpl.

ColumnNameCollectorVisitor previously had no QUERY/UNION filtering at all (only the existing query_node_to_component check); the same parent-and-child check is added there.

Reproduction

The exact fuzzer-generated AST that crashed on PR #103539 (commit 14d6e0f6):

CREATE TABLE constraint_test_strong_connectivity__fuzz_4
(`a` UInt16, `b` LowCardinality(Nullable(String)), `c` LowCardinality(String), `d` String NULL,
 CONSTRAINT c1 ASSUME (a <= b) AND (b <= c) AND (c <= d) AND (d <= a)) ENGINE = TinyLog;

SELECT sumKahanDistinctOrNull(1025)
FROM constraint_test_strong_connectivity__fuzz_4
PREWHERE (c = a) AND (d = b)
WHERE (a >= c) AND (SELECT b >= d)
LIMIT 2147483648;
-- Before: libc++ hardening assertion `__n < size()` failed → SIGABRT
-- After:  raises NOT_FOUND_COLUMN_IN_BLOCK (a separate planner issue, not a crash)

The fix turns the crash into a regular planner exception. The remaining NOT_FOUND_COLUMN_IN_BLOCK is an independent pre-existing planner issue: when CNF reduces WHERE to a single correlated-subquery atom, collectTableExpressionData skips the WHERE because its top-level node is a QUERY. That registration gap is unrelated to the crash and can be addressed separately.

Tests

tests/queries/0_stateless/04143_constraint_correlated_subquery_substitute_columns_crash.sql exercises:

  1. The crash-triggering pattern (UInt16 + String columns with constraint, correlated subquery in WHERE) — must not crash; expects NOT_FOUND_COLUMN_IN_BLOCK.
  2. The same with PREWHERE — same expectation, plus ILLEGAL_PREWHERE allowed (depends on planner ordering).
  3. Sanity check: same constraint + correlated-subquery code path with all-String columns (no _CAST wrapping) should execute correctly and return the expected count.

Context

Found by AST fuzzer (amd_msan) on PR #103539. Per @alexey-milovidov's directive on PR #103539, this fix is sent as a separate PR.

Related (different crash, same file area, my own open PR): #103733 fixes the analogous "Bad cast from ConstantNode to ColumnNode" path in the recursive replaceToConstants function.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103539&sha=14d6e0f664204a8815f9bf7fd496e90a83efd434&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…bquery

The constraint-substitution visitors in `ConvertQueryToCNFPass`
(`ComponentCollectorVisitor`, `ColumnNameCollectorVisitor`, and
`SubstituteColumnVisitor`) descend into subquery scopes when the visitor is
invoked directly on a `QueryNode`/`UnionNode`. Their `needChildVisit` only
filtered children with `child_type == QUERY/UNION`, so when the visit root
was itself a `QueryNode` (e.g. when CNF reduces a multi-atom WHERE down to a
single correlated subquery), the visitors traversed the subquery's children,
including its `correlated_columns_list`.

For mixed-type constraints, the substitution wraps the canonical column in
a `_CAST(...)` `FunctionNode`. The planner later iterates the correlated
columns expecting `ColumnNode`, calls `column->as<ColumnNode>()` on a
`FunctionNode` (returns nullptr), and dereferences the null `this` inside
`getSourceWeakPointer`. libc++ hardening catches this as a `vector[]`
out-of-bounds — surfacing as a `Received signal 6` crash on the MSAN AST
fuzzer (STID 3452-4527).

The fix adds a parent-type check to each visitor's `needChildVisit`: when
the parent is a `QueryNode`/`UnionNode`, do not descend. Constraint
substitution is scoped to the current query — nested subqueries have their
own scope and are processed independently when the outer
`ConvertQueryToCNFVisitor` recurses into them.

The regression test (`04143_constraint_correlated_subquery_substitute_columns_crash`)
mirrors the exact AST fuzzer query that crashed on PR ClickHouse#103539
(`MasterCI` AST fuzzer, amd_msan, commit 14d6e0f).

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103539&sha=14d6e0f664204a8815f9bf7fd496e90a83efd434&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

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

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? Adds a parent-type check to needChildVisit in three ConvertQueryToCNFPass visitors so they don't traverse into a subquery's correlated_columns_list when the visitor is invoked directly on a QueryNode. Fixes STID 3452-4527 (vector OOB / SIGABRT) found by AST fuzzer (amd_msan) on PR #103539.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per TASK.md Phase 4 Step 9):

(a) Deterministic repro? Yes. Triggered locally (debug build, libc++ hardened mode) with:

CREATE TABLE t (a UInt16, b String, c String, d String,
    CONSTRAINT c1 ASSUME (a <= b) AND (b <= c) AND (c <= d) AND (d <= a)) ENGINE = TinyLog;
INSERT INTO t VALUES (1, '2', '3', '4');
SELECT count() FROM t WHERE (a >= c) AND (SELECT b >= d)
SETTINGS convert_query_to_cnf=1, optimize_using_constraints=1, optimize_substitute_columns=1, allow_experimental_correlated_subqueries=1;
-- Aborts: libc++ Hardening assertion `__n < size()` failed: vector[] index out of bounds

(b) Root cause explained? Yes.

  1. CNF + optimize_using_constraints filter the always-true atom (a >= c) (constraint a <= ... <= a makes them equal). WHERE collapses to a single atom: the subquery (SELECT b >= d).
  2. optimize_substitute_columns invokes SubstituteColumnVisitor::visit(getWhere()). The argument is the cloned subquery QueryNode.
  3. needChildVisit(parent, child) previously only filtered child_type == QUERY/UNION. The visitor's children at this level are ListNode (correlated_columns_list, projection, etc.) — ListNode is not QUERY/UNION, so traversal proceeded.
  4. Inside correlated_columns_list, the visitor finds ColumnNode b (String), looks up the canonical class member (a, UInt16), wraps in _CAST(a, 'String') because types differ, and assigns node = buildCastFunction(...). The list now contains a FunctionNode.
  5. Later, GlobalPlannerContext::collectTableExpressionDataForCorrelatedColumns iterates the list expecting ColumnNode. column->as<ColumnNode>() returns nullptr on the FunctionNode. nullptr->getColumnSource() reads weak_pointers at offset N from null. libc++ hardening sees size() == 0 and aborts.

(c) Fix matches root cause? Yes. Adds the missing parent-type check: when parent_type == QUERY/UNION, return false. This stops traversal at subquery boundaries regardless of whether the subquery is a child or the visit root. The same check is applied to all three visitors in the file (ComponentCollectorVisitor, ColumnNameCollectorVisitor, SubstituteColumnVisitor) since they share the same scope-bleed problem.

(d) Test intent preserved? / New tests added? New regression test 04143_constraint_correlated_subquery_substitute_columns_crash.sql exercises:

  1. The exact AST fuzzer pattern (UInt16 + String columns, mixed-type constraint, correlated scalar subquery in WHERE) — must not crash. Expects NOT_FOUND_COLUMN_IN_BLOCK.
  2. The same with PREWHERE (matches the original fuzzer query). Expects NOT_FOUND_COLUMN_IN_BLOCK or ILLEGAL_PREWHERE.
  3. Sanity check: same code path with all-String columns (no _CAST wrapping) executes correctly and returns the expected count — guards against the fix breaking the homogeneous-type substitution path.

Existing tests in the constraint substitution area (01622_constraints_simple_optimization) continue to pass.

(e) Both directions demonstrated? Yes.

  • Without fix: clickhouse local aborts with libc++ Hardening assertion __n < size() failed: vector[] index out of bounds (matches the exact CI stack trace ColumnNode::getSourceWeakPointer → getColumnSource → collectTableExpressionDataForCorrelatedColumns).
  • With fix: same query raises Code: 10 NOT_FOUND_COLUMN_IN_BLOCK (a regular planner exception, not a crash).
  • Built with the same toolchain CI uses (Clang 21, debug, libc++ hardening). The MSAN-only manifestation in CI is the same code path; libc++ hardening catches it deterministically in any build with _LIBCPP_HARDENING_MODE.

(f) Fix is general, not a narrow patch? Yes.

  • The fix is applied to all three visitors in the file, not just the one that caused the observed crash. ComponentCollectorVisitor and ColumnNameCollectorVisitor had the same scope-bleed pattern; if a future query triggered them through the same path, they would corrupt correlated_columns_list similarly.
  • replaceToConstants (a recursive free function in the same file) has the same class of bug and is addressed in Fix bad cast in ConvertQueryToCNFPass replaceToConstants for correlated subqueries #103733 (a separate PR for a different concrete failure: "Bad cast from ConstantNode to ColumnNode"). Both fixes are necessary for full coverage of the constraint-substitution → subquery-scope-bleed bug class.
  • The fix is at the source of the corruption (don't enter foreign scopes), not a defensive check at the crash site (e.g. converting as<ColumnNode>() callsites to handle FunctionNode would mask the underlying invariant violation).

Session: cron:clickhouse-ci-task-worker:20260429-191500

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Apr 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [89065eb]

Summary: ❌

job_name test_name status info comment
Unit tests (asan_ubsan, function_prop_fuzzer) FAIL

AI Review

Summary

This PR fixes a real planner safety issue in ConvertQueryToCNFPass by preventing constraint-substitution visitors from descending into subquery scopes when invoked on QUERY/UNION roots, and adds a focused regression test that reproduces the failing pattern and verifies non-regression of the homogeneous-type path. The change is targeted, consistent with existing traversal patterns, and I did not find additional correctness or safety issues in the patch.

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: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

Closing as superseded. This crash (STID 3452-4527) is already fixed on master by the constraint-optimization correlated-subquery work in c667358, 55a371b, and 7e7720a (merged 2026-06-02), refined in 259e104 and 1035d9f (2026-06-17).

Master guards the bare-correlated-subquery-as-clause-root case at the invocation site (run_unless_subquery over projection/where/prewhere/having), plus isSubqueryNodeType child guards in each visitor and in replaceToConstants. That is strictly more complete than this PR's per-visitor parent check, and it is covered by the 04299_constraint_subst_correlated_subquery_root test.

CIDB shows STID 3452-4527 with 0 occurrences in the last 60 days (last seen 2026-05-29, before the master fix merged) and 0 on master at any point. The branch also has unrelated drift conflicts after 13.5k commits. Nothing left to add.

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-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants