Repository navigation
Fix classification of a parameterized view whose SELECT body is not a flat UNION list - #112211
Conversation
… flat UNION list ASTSelectWithUnionQuery::hasQueryParameters() inspected a list_of_selects child only when child->as<ASTSelectQuery>() matched. IAST::as<T>() is typeid_cast, an exact typeid match, so a child of any other type was skipped silently and its query parameters became invisible. Two interpreter passes create such children: SelectIntersectExceptQueryVisitor substitutes an ASTSelectIntersectExceptQuery (which derives from ASTSelectQuery, so the exact check does not match it), and NormalizeSelectWithUnionQueryVisitor nests a fresh ASTSelectWithUnionQuery for a chain that mixes UNION DISTINCT with UNION ALL. The second carrier involves no INTERSECT or EXCEPT at all. The two code paths ask the question in opposite orders. On CREATE, classification runs before both rewrites and is memoized, so the metadata written is correct for a parameterized view. On startup load, DatabaseOrdinary::loadTablesMetadata runs both rewrites before any classification, so the answer is computed on the already-rewritten tree and comes out false. createTableFromAST then keeps has_columns = true, finds no column list and no engine, and throws LOGICAL_ERROR at DatabaseOnDisk.cpp:137-139. A logical error aborts at construction in debug and sanitizer builds, before the AsyncLoader worker's catch(...), so one such view stopped the whole server from starting, even under FORCE_ATTACH. Make both hasQueryParameters() and getQueryParameters() answer for the whole SELECT body, reusing the existing analyzeReceiveQueryParams helpers that ASTSelectQuery::hasQueryParameters() already uses. Both accessors have to change: fixing only the first would let the view load while system.tables.parameterized_view_parameters still reported no parameters. The fix is at the accessor rather than at the throw site because every consumer already calls these two functions and already expects the whole-body answer. Reordering the visitors would add a third classification point and leave system.tables wrong, and relaxing the DatabaseOnDisk.cpp check would leave the view unloadable while removing a guard that legitimately detects hand-edited metadata. A directory written by an unpatched binary loads with a patched one, because the classification is recomputed when the metadata is parsed again, so existing broken views recover on upgrade. The metadata format is unchanged. A view written with explicit parentheses is nested by the parser rather than by a rewrite, so its parameter was invisible at CREATE time too and the parameter was substituted instead of being kept. It never wrote unreadable metadata, but the same accessor governs it, so it is now preserved as a parameterized view, matching what the equivalent flat spelling already did. The test covers that shape. Related: ClickHouse#111542
Review follow-up to the previous commit; no behaviour change. The regression test carried a no-fasttest tag whose stated reason was that it spawns clickhouse-local and writes an on-disk metadata directory. Neither half of that gates the Fast test job. clickhouse-local is part of clickhouse-bundle, which the Fast test build produces, and the test only uses the Atomic database engine and system.tables, so nothing it needs is compiled out when libraries are disabled. It runs in about a second against a 60 second timeout, and most existing shell tests that drive clickhouse-local with a persistent --path carry no such tag either. Keeping the tag hid a parser and AST regression from the cheapest job that could catch it, so it is removed. No replacement tag is needed: every path the test touches is scoped to CLICKHOUSE_TEST_UNIQUE_NAME, it needs no server, and it mutates no shared server state. Verified by running the test harness with --fast-tests-only: the test is now selected and passes, where with the tag restored the same command skips it with "running fast tests only". The comment above the two file-local helpers is also trimmed to the one fact that is not visible at the call site. The rest of it repeated this commit's predecessor message, and it implied that all three dispatch arms are required for correctness, which is not true: the general branch alone would already handle a nested union node, because QueryParameterVisitor recurses over all children. The first two arms exist to preserve the per-node memo. Related: ClickHouse#111542 Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review (2 review rounds, 3 second-model passes, 8 findings adjudicated)Before opening this PR I ran an independent cold review of the resulting code plus three
Verified independently rather than taken from the change: the exact-typeid behaviour of Because the test now runs in the Fast test job, the two things that break only there were Session id: cron:clickhouse-review-slot-9:20260728-015000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260727-224000 |
|
cc @evillique @SmitaRKulkarni - could you review this? |
|
Workflow [PR], commit [9cef8f7] Summary: ❌
AI ReviewSummaryThis PR fixes the original Findings❌ Blockers
Final Verdict
|
| for (const auto & child : list_of_selects->children) | ||
| { | ||
| if (auto * select_node = child->as<ASTSelectQuery>()) | ||
| if (childHasQueryParameters(child)) |
There was a problem hiding this comment.
ParserQueryWithOutput still attaches query-level trailing SETTINGS to ASTQueryWithOutput::settings_ast, and this loop never looks at that child. That means a union view whose only placeholder is in ... SETTINGS max_threads = {threads:UInt64} is still classified as an ordinary view, unlike the single-SELECT form, and mixed cases will still omit that parameter from system.tables.parameterized_view_parameters. The accessor needs to include settings_ast (or otherwise scan the whole ASTSelectWithUnionQuery subtree) in both hasQueryParameters and getQueryParameters, plus a regression test for the union-level SETTINGS shape.
There was a problem hiding this comment.
The asymmetry this describes does not exist, and the accessor cannot reach settings_ast from where it sits. Measured on the pristine merge-base and on this PR's head, both debug builds.
1. A placeholder in a flat trailing SETTINGS is already found, for both shapes. EXPLAIN AST shows why: ParserSelectQuery consumes it onto the innermost ASTSelectQuery, not onto the outer ASTSelectWithUnionQuery.
CREATE VIEW v AS SELECT 1 AS x UNION ALL SELECT 2 SETTINGS max_threads = {t:UInt64}
CreateQuery v (children 2)
SelectWithUnionQuery (children 1)
ExpressionList (children 2)
SelectQuery (children 1) ...
SelectQuery (children 2) ...
Set <-- child of the LAST SelectQuery
QueryParameterVisitor::visitSetQuery (src/Parsers/QueryParameterVisitor.cpp:43-58) already discovers placeholders inside an ASTSetQuery, so the per-child recursion reaches it. system.tables.parameterized_view_parameters, single session, identical on master and on this PR:
| view body | master | this PR |
|---|---|---|
SELECT 1 AS x SETTINGS max_threads = {t:UInt64} |
[('t','UInt64')] |
[('t','UInt64')] |
SELECT 1 AS x UNION ALL SELECT 2 SETTINGS max_threads = {t:UInt64} |
[('t','UInt64')] |
[('t','UInt64')] |
SELECT {n:UInt64} AS x UNION ALL SELECT 2 SETTINGS max_threads = {t:UInt64} |
[('t','UInt64'),('n','UInt64')] |
[('t','UInt64'),('n','UInt64')] |
The mixed case reports both parameters. And this PR is what makes the INTERSECT spelling of the same shape work at all: SELECT 1 AS x INTERSECT SELECT 2 SETTINGS max_threads = {t:UInt64} reloads as [('t','UInt64')] here versus rc=134 on master.
2. A view's inner ASTSelectWithUnionQuery can never own a settings_ast. ParserSelectWithUnionQuery contains no SETTINGS handling at all (whole-file grep), and it is the parser used for the AS body (src/Parsers/ParserCreateQuery.cpp:1782, inside ParserCreateViewQuery). The node that can own one is ASTCreateQuery, a level above: with parenthesized branches, EXPLAIN AST puts Set as a direct child of CreateQuery, a sibling of SelectWithUnionQuery. Adding settings_ast to these two accessors would therefore be reaching for a child that is not in the subtree they traverse.
3. There is a real defect nearby, but it is pre-existing and in that layer above. A CREATE VIEW whose only placeholder is in a query-level trailing SETTINGS persists it unsubstituted, and the resulting metadata can never be attached:
Code: 695 ... Load job 'load table d.u_set' failed: Code: 456 ... Substitution `t` is not set:
Cannot attach table `d`.`u_set` from metadata file ... AS SELECT 1 AS x UNION ALL SELECT 2
SETTINGS max_threads = {t:UInt64}
Reload rc=210, byte-for-byte the same on master and on this PR head, and the same for the single-SELECT form, so it is neither UNION-specific nor touched by this change. The reason it cannot work today is that with no parameter supplied, every SETTINGS-placeholder shape already fails at CREATE with Code: 456, while every body-placeholder shape creates fine: a SETTINGS placeholder is substituted at CREATE time rather than being a view parameter. Whether it should become one is a semantics question for the owners, and the fix site is ASTCreateQuery/ParserQueryWithOutput, not ASTSelectWithUnionQuery.
So: agreed that the shape deserves attention, and I have filed a separate fix task for it with the measurements above. I am keeping it out of this PR, which fixes one root cause (the union-child classification) in one accessor.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code |
CI finish ledger - 9cef8f7CI has fully finished on this head: 174 check-runs, 0 queued, 0 in progress,
Not caused by this PR. The failing statement is Breadth over 30 days for this exact signature, excluding flaky-check jobs: 74 hits across 66 Session id: cron:our-pr-ci-monitor:20260728-140000 |
Pull Request is not mergeable
3989bff
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a parameterized view whose
SELECTbody usesINTERSECT/EXCEPT, or aUNIONchain that mixesUNION DISTINCTwithUNION ALL, being classified as an ordinary view. Such a view was created successfully but its metadata could not be read back: loading it threwInvalid storage definition in metadata file, which made the view permanently unloadable and aborted a debug or sanitizer server on startup.system.tables.parameterized_view_parametersalso reported no parameters for those views.Description
Related: #111542
ASTSelectWithUnionQuery::hasQueryParameters()inspected alist_of_selectschild only whenchild->as<ASTSelectQuery>()succeeded.IAST::as<T>()istypeid_cast, an exact typeid match, so a child of any other type was skipped silently and its query parameters became invisible. Two child kinds reach that hole, and interpreter passes create both:ASTSelectIntersectExceptQuery, whichSelectIntersectExceptQueryVisitorsubstitutes into the list. It derives fromASTSelectQuery, so the exact typeid check does not match it.ASTSelectWithUnionQuery, whichNormalizeSelectWithUnionQueryVisitorcreates for a chain that mixesUNION DISTINCTwithUNION ALL. This carrier involves noINTERSECTorEXCEPTat all.The two code paths ask the question in opposite orders. On
CREATE, classification runs before both rewrites and is memoized, so the answer is correct and the metadata written is correct for a parameterized view. On startup load,DatabaseOrdinary::loadTablesMetadataruns both rewrites before any classification, so the answer is computed on the already-rewritten tree and comes out false.createTableFromASTthen keepshas_columns = true, finds no column list and (for a view) no engine, and throwsLOGICAL_ERRORatDatabaseOnDisk.cpp:137-139. Because a logical error aborts at construction in debug and sanitizer builds, that happens before theAsyncLoaderworker'scatch(...), so a single such view stops the whole server from starting, even underFORCE_ATTACH.The fix makes both
hasQueryParameters()andgetQueryParameters()answer for the wholeSELECTbody, reusing the existinganalyzeReceiveQueryParams/analyzeReceiveQueryParamsWithTypehelpers thatASTSelectQuery::hasQueryParameters()already uses. Both accessors are changed, otherwise a view would load butsystem.tables.parameterized_view_parameterswould still report nothing for it.The accessor is the single point of truth: every consumer (
isParameterizedView(), the create-time substitution gate,system.tables,createTableFromAST) already calls these two functions and already expects the whole-body answer. Reordering the visitors would add a third classification point and leavesystem.tableswrong; relaxing theDatabaseOnDisk.cppcheck would leave the view unloadable while removing a guard that legitimately detects hand-edited metadata.Reproducible without a server, object storage or a fuzzer:
The second invocation aborts before this change and succeeds after it. A directory written by an unpatched binary loads correctly with a patched one, because the classification is recomputed when the metadata is parsed again, so existing broken views recover on upgrade without manual repair. The metadata format is unchanged: a parameterized view simply stores no column list, exactly as the already-working flat spelling does.
One behaviour change is worth calling out. A view written with explicit parentheses, such as
SELECT 1 AS x UNION DISTINCT (SELECT {n:UInt64} AS x UNION ALL SELECT 3), is nested by the parser rather than by a rewrite, so its parameter was invisible atCREATEtime too. It never wrote unreadable metadata: with the parameter unset theCREATEfailed withUNKNOWN_QUERY_PARAMETER, and with it set the parameter was substituted and an ordinary view was stored. The same accessor governs that shape, so it is now preserved as a parameterized view, matching what the equivalent flat spelling already did. The regression test covers it.This does not claim to close the torn-read race that issue #111542 is titled after: the reporter's own failing tables do not look like parameterized views, so that instance may be a different mechanism. What it fixes is the deterministic carrier of the same fatal message, reproduced above and seen aborting the same table across six consecutive restarts in a CI artifact on that issue. #110906 is disjoint: it only degrades a future variant of this failure from a server abort to an exception, and is not the fix for these views.