Skip to content

Reject MATERIALIZED CTE references with inconsistent inferred types - #103879

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3520-3e11-materialized-cte-type-mismatch
May 8, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3520-3e11-materialized-cte-type-mismatch

Conversation

@groeneai

@groeneai groeneai commented May 1, 2026 •

Copy link
Copy Markdown
Collaborator

A MATERIALIZED CTE body that references an identifier resolved from outer scope (e.g. a projection alias of the calling subquery) was inlined as different constants in different references, producing different inferred projection types per reference. The single shared storage was created from the first reference's types while the materializer pipeline could end up using a later reference's types — the resulting block was written into the storage with mismatched column types and any reader that relied on the storage metadata then crashed in MemorySource::fillPhysicalColumns → SerializationNullable::enumerateStreams while trying to assert_cast a non-Nullable column to ColumnNullable.

Reproducer (issue #103813)

WITH t AS MATERIALIZED (SELECT a + number AS x FROM numbers(65536))
SELECT * FROM (
    SELECT NULL AS a, x FROM t LIMIT 791
    UNION ALL
    SELECT 2147483647 AS a, x FROM t
) ORDER BY a DESC, x ASC LIMIT 942
SETTINGS enable_analyzer = 1, enable_materialized_cte = 1;

Without this commit the server aborts with Logical error: 'Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnNullable'. (variants seen across UInt64, Int64, Float64 and String columns depending on the body expression). With this commit the analyzer detects the type drift across references and rejects the query with a clear TYPE_MISMATCH error explaining that materialized CTE bodies cannot depend on the calling context.

Approach

Both code paths that materialize a temporary table for a CTE clone — resolveExpressionNode (identifier-resolution path) and resolveQueryJoinTreeNode (join-tree path) — now run the same verification after updateStorage: compare the cloned subquery's projection columns to the storage's column types via IDataType::equals, and throw TYPE_MISMATCH on a divergence with a message that names the column, both types, and the offending scope.

The check is a defense-in-depth guard at the analyzer level. The deeper issue — that the analyzer allows a materialized CTE body to look up identifiers in the calling scope's projection aliases at all — is documented in the error message but not fixed here; that requires a more invasive change to the scope-resolution rules. The targeted check turns a LOGICAL_ERROR server abort into a clean analysis-time rejection, which is what the user expects when they wrote a query that has no consistent meaning.

Tests

  • All existing materialized_cte tests (03801, 03821, 03927, 03928 …) continue to pass.
  • New regression test 04148_stid_3520_3e11_materialized_cte_outer_alias covers the original reproducer plus two further fuzzer variants (Float64, swapped column order) and three sanity-check shapes that must continue to succeed (single-reference, JOIN, no outer dependency).

CI report (most recent failure)

AST fuzzer (amd_debug, targeted) on PR #101155

Closes #103813.

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):

Reject MATERIALIZED CTE queries whose body resolves to different inferred column types in different references with a clear TYPE_MISMATCH error instead of crashing the server with a Bad cast LOGICAL_ERROR. This previously happened when the CTE body referenced identifiers from outer scope (for example an alias from the calling subquery's projection) that were inlined as different constants per reference.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.447

A `MATERIALIZED` CTE body that references an identifier resolved from
outer scope (e.g. a projection alias of the calling subquery) was inlined
as different constants in different references, producing different
inferred projection types per reference. The single shared storage was
created from the first reference's types while the materializer pipeline
could end up using a later reference's types — the resulting block was
written into the storage with mismatched column types and any reader that
relied on the storage metadata then crashed in
`MemorySource::fillPhysicalColumns` →
`SerializationNullable::enumerateStreams` while trying to `assert_cast`
a non-Nullable column to `ColumnNullable`.

Reproducer (issue ClickHouse#103813):

```sql
WITH t AS MATERIALIZED (SELECT a + number AS x FROM numbers(65536))
SELECT * FROM (
    SELECT NULL AS a, x FROM t LIMIT 791
    UNION ALL
    SELECT 2147483647 AS a, x FROM t
) ORDER BY a DESC, x ASC LIMIT 942
SETTINGS enable_analyzer = 1, enable_materialized_cte = 1;
```

Without this commit the server aborts with `Logical error: 'Bad cast from
type DB::ColumnVector<unsigned long> to DB::ColumnNullable'.` (variants
seen across `UInt64`, `Int64`, `Float64` and `String` columns depending
on the body expression). With this commit the analyzer detects the type
drift across references and rejects the query with a clear
`TYPE_MISMATCH` error explaining that materialized CTE bodies cannot
depend on the calling context.

Both code paths that materialize a temporary table for a CTE clone
(`resolveExpressionNode` and `resolveQueryJoinTreeNode`) now run the same
verification after `updateStorage`. Existing materialized-CTE tests
(03801, 03821, 03928 …) continue to pass; the new test
`04148_stid_3520_3e11_materialized_cte_outer_alias` covers the original
reproducer plus two further fuzzer variants and three sanity-check
shapes that must continue to succeed.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101155&sha=d9c05998ed23a22f2bccf3a5f87bc414e451908b&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Closes ClickHouse#103813.
@groeneai

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd — could you review this? It guards MATERIALIZED CTE resolution: when the body resolves an outer-scope alias to a different constant per reference, the analyzer used to silently create a storage with the first reference's types and then crash at read time with Bad cast from DB::ColumnVector to DB::ColumnNullable (issue #103813, STID 3520-3e11). The fix detects the type drift across clones in both resolveExpressionNode and resolveQueryJoinTreeNode and rejects with TYPE_MISMATCH. cc @vdimir @yakov-olkhovskiy as comp-query-analyzer experts in case you have context on a deeper scope-level fix.

@groeneai

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per worker checklist):

a) Deterministic repro? YES.

WITH t AS MATERIALIZED (SELECT a + number AS x FROM numbers(65536))
SELECT * FROM (
    SELECT NULL AS a, x FROM t LIMIT 791
    UNION ALL
    SELECT 2147483647 AS a, x FROM t
) ORDER BY a DESC, x ASC LIMIT 942
SETTINGS enable_analyzer = 1, enable_materialized_cte = 1;

Crashes 100% of the time on master without the fix; passes (with TYPE_MISMATCH) every time with the fix.

b) Root cause explained? YES.
Each reference to a MATERIALIZED CTE clones the body subquery and re-resolves it in a child of the calling scope. When the body references an identifier (a) that is undefined inside, the resolver climbs to the parent scope and finds the alias in the calling subquery's projection. Because the alias is a constant (NULL, 2147483647, …), it gets inlined; no correlated column is recorded so the existing is_correlated check passes. Each reference therefore infers a different projection type for x (Nullable(Nothing) for the NULL branch, UInt64 for the integer branch). The single shared storage is created from the first reference's types (e.g. Nullable(Nothing)), but addBuildSubqueriesForMaterializedCTEsIfNeeded builds the materializer plan from one specific clone's subquery (e.g. the one with UInt64). The materializer writes UInt64 data into a storage whose metadata says Nullable(Nothing); StorageMemorySink::consume doesn't catch this because it builds the block from getHeader() (metadata types) and chunk.getColumns() (data) before calling metadata->check, so the block's declared type matches the metadata. At read time, MemorySource::fillPhysicalColumns → fillMissingColumns → collectOffsetsColumns calls SerializationNullable::enumerateStreams which assert_cast<const ColumnNullable &> on a ColumnVector<UInt64> and aborts.

c) Fix matches root cause? YES, with a documented limitation.
The patch detects exactly the divergence described in (b) — projection types of a subsequent clone vs. the storage created from an earlier clone — and rejects the query before any data is materialized. It is an analysis-time guard, not a deeper fix to the analyzer's scope rules. The cleanest "real" fix would prevent alias lookup from outer scope into a MATERIALIZED CTE body in the first place; that requires reshaping IdentifierResolveScope semantics for CTE bodies and is out of scope for this PR. The check turns a LOGICAL_ERROR server abort into a clear TYPE_MISMATCH whose message points the user at the mechanism (outer-scope alias inlining) so they can rewrite the query.

d) Test intent preserved? / New tests added? YES.
All existing materialized_cte stateless tests (03801, 03821, 03927, 03928, …) pass. A new regression test 04148_stid_3520_3e11_materialized_cte_outer_alias.sql covers:

  • Original reproducer from Logical error: Bad cast from type A to B (STID: 3520-3e11) #103813 (UInt64 storage drift) → expect TYPE_MISMATCH
  • Variant with DISTINCT and swapped column order in the second branch → expect TYPE_MISMATCH
  • Float64 variant via number / a → expect TYPE_MISMATCH
  • Three sanity-check shapes (no outer dep, single reference, JOIN within same scope) that must continue to succeed.

e) Demonstrated in both directions? YES.
Without the patch (enable_materialized_cte = 1 is required to reach the bug code path):

[ip-10-4-8-166] 2026.05.01 17:26:23.865492 [ 878006 ] {…} <Fatal> : Logical error: 'Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnNullable'.

Server died. With the patch:

Code: 53. DB::Exception: Materialized CTE 't' has inconsistent column types across references: column 'x' has type Nullable(Nothing) in storage but this reference resolved to type UInt64. … (TYPE_MISMATCH)

Server stays up. Verified for UInt64, Float64, and the swapped-column shapes.

f) Fix is general, not narrow patch? YES for the narrow goal.
Both materialization code paths are covered: resolveExpressionNode (identifier-resolution path, line ~3010) and resolveQueryJoinTreeNode (join-tree path, line ~5268). They share the helper verifyMaterializedCTESubqueryMatchesStorage. The check uses IDataType::equals and so handles every column type, not just Nullable vs non-Nullable (the original symptom). The 5 distinct STID 3520 sub-variants (3e11, 3e90, 43e0, 4237, 3244) all stem from the same family of analyzer behaviors; this PR addresses 3e11 specifically (storage type drift across references). The other sub-variants involve different cast sites and may need separate fixes.

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

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [98760f1]

Summary: ✅


AI Review

Summary

This PR adds an analyzer-time guard for MATERIALIZED CTE clones so mismatched inferred projection types across references are rejected with TYPE_MISMATCH instead of reaching a later internal LOGICAL_ERROR path. The fix is applied in both materialization flows (resolveExpressionNode and resolveQueryJoinTreeNode) and is covered by focused regression tests plus sanity cases; I did not find correctness, safety, or rollout 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-bugfix Pull request with bugfix, not backported by default label May 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 87.80% (36/41) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

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

This is a good fix, thank you! Reviewed code, and everything looks alright.
As a small improvement - we can unify the types of referenced columns from different places. However, it will be too much for the fix here, we can do it later.

@alexey-milovidov alexey-milovidov self-assigned this May 8, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 8, 2026
Merged via the queue into ClickHouse:master with commit c895494 May 8, 2026
165 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 8, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — could this be a backport candidate for 26.4, 26.3 (LTS)? No backport label was found, and the affected code appears to exist in those branches based on a file/function presence check.

Affected code: verifyMaterializedCTESubqueryMatchesStorage in QueryAnalyzer.cpp - code paths in resolveExpressionNode and resolveQueryJoinTreeNode where MATERIALIZED CTE storage is reused — introduced in 26.3.

Why this might apply: The enable_materialized_cte setting was added in version 26.3 (found at SettingsChangesHistory.cpp:131). The bug only exists in branches that have this feature. Branches 25.8 and 26.2 don't have MATERIALIZED CTE support, so they are unaffected and don't need the fix.

Other supported branches (26.2, 25.8) predate 26.3 and do not contain this code.

Caveat: I verified that the modified code exists in those branches, but not whether the bug is actually reachable there — a new caller in master may be what makes this newly observable. If older branches can't reach the affected path, please ignore this; otherwise consider pr-must-backport or a version label like v26.4-must-backport.

@novikd novikd added the post-rejected Should've been rejected, but got merged. label May 8, 2026
@novikd

novikd commented May 8, 2026

Copy link
Copy Markdown
Member

I think the fix is incorrect, because such queries are invalid, not because of type mismatch, but because a materialized CTE query can not be correlated. Also, a materialized CTE subquery must have the same semantics across all usages.
I'll revert it and fix it properly.

pull Bot pushed a commit to weiyilai/ClickHouse that referenced this pull request Jul 1, 2026
…t64 drift)

STID 2241-3a03 ('Bad cast from type DB::ColumnVector<unsigned long> to
DB::ColumnVector<long>', issue ClickHouse#103814) is the non-nullable Int64/UInt64
variant of the materialized-CTE outer-scope type-drift bug fixed by ClickHouse#103879.
The analyzer guard verifyMaterializedCTESubqueryMatchesStorage rejects it
with TYPE_MISMATCH, but 04148 only pinned Nullable/Float64 shapes. Add the
issue ClickHouse#103814 shape (signed -1 vs unsigned-inducing 257 for the outer alias
a, driving x to Int64 in storage and UInt64 in the second reference) so the
exact ColumnVector<long>/ColumnVector<unsigned long> pair is covered.

Test-only, no source change.

Closes ClickHouse#103814.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t64 drift)

STID 2241-3a03 ('Bad cast from type DB::ColumnVector<unsigned long> to
DB::ColumnVector<long>', issue ClickHouse#103814) is the non-nullable Int64/UInt64
variant of the materialized-CTE outer-scope type-drift bug fixed by ClickHouse#103879.
The analyzer guard verifyMaterializedCTESubqueryMatchesStorage rejects it
with TYPE_MISMATCH, but 04148 only pinned Nullable/Float64 shapes. Add the
issue ClickHouse#103814 shape (signed -1 vs unsigned-inducing 257 for the outer alias
a, driving x to Int64 in storage and UInt64 in the second reference) so the
exact ColumnVector<long>/ColumnVector<unsigned long> pair is covered.

Test-only, no source change.

Closes ClickHouse#103814.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 post-rejected Should've been rejected, but got merged. 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.

Logical error: Bad cast from type A to B (STID: 3520-3e11)

5 participants