Repository navigation
Reject MATERIALIZED CTE references with inconsistent inferred types - #103879
Conversation
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.
|
cc @KochetovNicolai @novikd — could you review this? It guards |
|
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 b) Root cause explained? YES. c) Fix matches root cause? YES, with a documented limitation. d) Test intent preserved? / New tests added? YES.
e) Demonstrated in both directions? YES. Server died. With the patch: Server stays up. Verified for f) Fix is general, not narrow patch? YES for the narrow goal. |
|
Workflow [PR], commit [98760f1] Summary: ✅ AI ReviewSummaryThis PR adds an analyzer-time guard for ClickHouse Rules
Final Verdict
|
LLVM Coverage Report
Changed lines: 87.80% (36/41) | lost baseline coverage: 3 line(s) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
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.
|
Hi — could this be a backport candidate for Affected code: Why this might apply: The Other supported branches ( 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 |
|
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. |
…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]>
…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]>
A
MATERIALIZEDCTE 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 inMemorySource::fillPhysicalColumns→SerializationNullable::enumerateStreamswhile trying toassert_casta non-Nullable column toColumnNullable.Reproducer (issue #103813)
Without this commit the server aborts with
Logical error: 'Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnNullable'.(variants seen acrossUInt64,Int64,Float64andStringcolumns depending on the body expression). With this commit the analyzer detects the type drift across references and rejects the query with a clearTYPE_MISMATCHerror 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) andresolveQueryJoinTreeNode(join-tree path) — now run the same verification afterupdateStorage: compare the cloned subquery's projection columns to the storage's column types viaIDataType::equals, and throwTYPE_MISMATCHon 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_ERRORserver abort into a clean analysis-time rejection, which is what the user expects when they wrote a query that has no consistent meaning.Tests
materialized_ctetests (03801, 03821, 03927, 03928 …) continue to pass.04148_stid_3520_3e11_materialized_cte_outer_aliascovers 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reject
MATERIALIZEDCTE queries whose body resolves to different inferred column types in different references with a clearTYPE_MISMATCHerror instead of crashing the server with aBad castLOGICAL_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
Version info
26.5.1.447