Skip to content

Qualify a parameterized view's name when rendering it for another server - #113550

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-parameterized-view-database-lost-on-shard
Aug 6, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-parameterized-view-database-lost-on-shard

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #65318

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

Fixed a parameterized view losing its database when a query referencing it unqualified is sent to a shard, so the shard resolved the name against its own default database. Depending on what that database contained, the query either failed with UNKNOWN_FUNCTION or silently returned rows from a different view. Affects IN, JOIN and remote() through a Distributed table.

Description

TableFunctionNode::toASTImpl emitted the function name from table_function_name, the identifier as the user wrote it, and never consulted storage_id. An unqualified parameterized-view call therefore stayed unqualified all the way to the shard, which re-resolved it against its own default database.

Measured on a two-shard cluster with the session database set to the view's database and the call unqualified: IN, JOIN ... ON, JOIN ... USING and remote() all failed with Code: 46 ... Received from 127.0.0.2 ... Unknown table function pv, raised by the remote shard, which is direct evidence the name arrived unqualified. When that shard's default database held a same-named parameterized view, the query instead returned a wrong answer with nothing on stderr: 3 rows where 6 is correct. A qualified db.pv(...) call has always worked: the existing workaround.

Before #68978 a parameterized view became a TableNode, whose toASTIdentifier qualifies from storage_id; keeping it a resolved TableFunctionNode is what lost the database.

The initiator's database is the correct target. A parameterized view is expanded against the initiator's catalog, and its storage_id always has a database, since extractDatabaseAndTableNameForParameterizedView defaults it to the current one. The cross-replication case that TableNode::toASTIdentifier guards against is expressed by Cluster::maybeCrossReplication, which buildQueryTreeForShard consults to hand TableNode an empty database; no cluster or context reaches toASTImpl, so that signal cannot apply here.

Two conditions keep the change narrow. The parameterized-view discriminator is required: a regular table function also carries a storage id, whose database is the internal _table_function, so unconditional qualification renders numbers(3) as _table_function.numbers(3), and a test pins that. Qualification is also skipped unless the result is a two-part identifier, since that helper resolves only one or two parts, so a dotted database name is left as it is today.

The change is render-only: EXPLAIN QUERY TREE and EXPLAIN SYNTAX are byte-identical before and after.

Version info

  • Merged into: 26.8.1.902 (included in 26.8 and later)

A parameterized view referenced unqualified in a query that is shipped to a shard arrived at the
shard without its database, because TableFunctionNode::toASTImpl emitted table_function_name --
the identifier as the user wrote it -- and never consulted storage_id. The shard then re-resolved
the name against its own default database.

Measured on a two-shard cluster with the session database set to the view's database and the call
unqualified: non-GLOBAL IN through a Distributed table, JOIN ... ON, JOIN ... USING and remote()
all failed with UNKNOWN_FUNCTION raised by the remote shard. When the shard's default database
happened to hold a same-named parameterized view the query instead returned a silently wrong
answer -- 3 rows where 6 is correct, with the failing shard contributing none and nothing on
stderr. Before ClickHouse#68978 a parameterized view became a TableNode, whose toASTIdentifier qualifies
from storage_id, so this path is the one that lost the database.

The initiator's database is the correct target. A parameterized view is expanded against the
initiator's catalog and storage_id can never lack a database, since
extractDatabaseAndTableNameForParameterizedView defaults it to the current database. The
cross-replication case that TableNode::toASTIdentifier guards against is expressed by
Cluster::maybeCrossReplication, which buildQueryTreeForShard consults to hand TableNode a
deliberately empty database; no cluster or context reaches toASTImpl, so that signal cannot apply
here.

The parameterized-view discriminator is required rather than decorative: a regular table function
also carries a real storage id, so unconditional qualification would render numbers(3) as
system.numbers(3). Qualification is also skipped unless the result is a two-part identifier,
because extractDatabaseAndTableNameForParameterizedView resolves only one or two parts -- a
database whose name contains a dot has no resolvable qualified spelling and is left as it is
today.

The change is confined to rendering, so query-tree identity is untouched: EXPLAIN QUERY TREE and
EXPLAIN SYNTAX are byte-identical before and after, which is why the name is not rewritten at
resolve time.

Closes ClickHouse#65318
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

An independent cold code review plus a second-model review pass ran against this change before it
was published. Findings and their dispositions:

# Finding Verdict
⚠️ 1 The draft description justified the parameterized-view discriminator by saying unconditional qualification would render numbers(3) as system.numbers(3). It renders _table_function.numbers(3). A regular table function's storage id uses ITableFunction::getDatabaseName(), which is the literal _table_function; all 41 StorageID(getDatabaseName(...)) sites under src/TableFunctions/ use it and none uses another database. The system string traces to the TableFunctionNode constructor placeholder storage_id("system", "one"), which resolve overwrites, so it can never be a resolved node's rendered database. Fixed before publishing. The description now names _table_function. The discriminator itself is unaffected and is pinned by the regular-table-function control plus the mutant that reverts it, which reddens exactly that row with Unknown table function _table_function.numbers.
💡 2 The formatQuery control cannot detect a revert of this change: formatQuery parses and formats a raw AST and never builds a query tree, so TableFunctionNode::toASTImpl is unreachable from it. The second-model pass proposed removing the row or replacing it with a query-tree serialization assertion. Agreed on the fact, declined on the remedy. The row is labelled CONTROL and a control's job is to stay green on both arms, as four of the other five controls also do; it pins the parser and formatter path at no cost. The query-tree assertion the remedy asks for already exists in tree, in a stronger form: 01415_table_function_view asserts the rendering of a genuinely unresolved nested view(...) inside remote(...), and its committed reference prints that call unqualified, so it would fail if either the null-storage guard or the discriminator regressed. Adding a weaker in-test copy of an assertion master already makes would be churn. What was wrong was an internal note crediting this row with covering the unresolved-node carrier; that note now cites 01415.
💡 3 A fourth mutant listed in the internal plan (drop the storage != nullptr test) was never run and the omission was not recorded. Agreed, and deliberately not reinstated. Its stated acceptance criterion was unsatisfiable: storage is a StoragePtr, so storage->as<...>() without the test is a null-pointer dereference on the unresolved path rather than a clean build, and because typeid_cast checks its argument the result would be silent undefined behaviour rather than a crash. That is a reason the shipped null test is required, and the conclusion is established from the code without the arm. The unresolved-node path's coverage is 01415_table_function_view, as above.
💡 4 The description's closing sentence, that EXPLAIN QUERY TREE and EXPLAIN SYNTAX are byte-identical before and after, is a measurement rather than a structural guarantee: EXPLAIN QUERY TREE with dump_ast = 1 does render through toAST. No change. The sentence claims only what was measured, and it is accurate; EXPLAIN SYNTAX inlines a parameterized-view call into a subquery before rendering, so no such node survives to render, and EXPLAIN QUERY TREE does not call toAST in its default form. Recorded so the sentence is not later strengthened into a claim that would be false.

The dotted-database row relies on an error-message substring, which is brittler than a structural
oracle. That was reviewed and kept: every other candidate oracle for it (EXPLAIN SYNTAX,
EXPLAIN QUERY TREE, local resolution, and the error code alone) reads identically on the fix and
on the mutant that drops the two-part guards, so the message text is the only thing that
discriminates, and dropping the row would ship that guard unpinned.

Session id: cron:clickhouse-review-slot-48:20260805-163002

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on a local two-shard cluster with the session database set to the view's database and the call unqualified. Four shapes (IN through Distributed, JOIN ... ON, JOIN ... USING with joined_subquery_requires_alias = 0, remote()) each throw Code: 46 ... Received from 127.0.0.2 ... Unknown table function pv. The wrong-results variant, with a same-named view in the database the shard falls back to, returns 3 where 6 is correct, 3 of 3 runs, and writes 0 bytes to stderr. Both conditions are load-bearing: the same query against the local table, the GLOBAL IN spelling and any already-qualified db.pv(...) call all work.
b Root cause explained? TableFunctionNode::toASTImpl set the emitted name from table_function_name, the identifier as the user typed it, and never consulted storage_id, so an unqualified call stayed unqualified to the shard, which re-resolved it against its own default database. storage_id was populated all along: resolve takes it from storage->getStorageID(), and for a parameterized view Context::buildParameterizedViewStorage builds StorageID(database_name, table_name) where database_name comes from extractDatabaseAndTableNameForParameterizedView and defaults to the current database. TableNode::toASTIdentifier is the in-tree contrast; before #68978 a parameterized view took that qualifying path.
c Fix matches root cause? Yes. The defect is that render time discards storage_id, and the fix consults storage_id at render time, in the one function every affected spelling funnels through. No widened bound, no no-random-* tag, no guard bolted onto a crash site.
d Test intent preserved / new tests added? No existing test weakened or removed. One new stateless pair, 04678_parameterized_view_database_on_shard, with five witness rows (the four spellings plus the per-shard wrong-results breakdown in both the one-local-replica and all-replicas-remote spellings), five must-not-change controls (a regular table function, GLOBAL IN, an ordinary view, an already-qualified call, and formatQuery on an unresolved parse) and one fail-closed boundary row for a dotted database name.
e Both directions demonstrated? Yes, with the real runner, each arm on a restarted server whose SELECT lower(buildId()) was asserted against that binary's own readelf -n value before any verdict. Pristine master at the same base sha: FAIL, with rows 1 to 4 and every per-shard row empty and all controls green. With the fix: OK. Three mutants redden disjoint, named row sets: reverting the whole hunk reproduces the base failure; dropping the parameterized-view discriminator reddens only the regular-table-function control (Unknown table function _table_function.numbers); dropping the two-part guards reddens only the dotted-database row. After the mutants the source was restored and the Build ID confirmed back to exactly the shipped value.
f Fix is general across code paths? Yes. All four spellings reach the same function, measured failing identically before and passing identically after, so one change covers them. Carriers enumerated and dispositioned: TableNode::toASTIdentifier is already correct and unchanged, since buildQueryTreeForShard deliberately hands it an empty database for cross-replication; a regular table function must stay unqualified and is pinned by a control plus a mutant; an unresolved node (storage == nullptr) stays unqualified via the null guard, and getStorageID() is deliberately not called there because it throws LOGICAL_ERROR; QueryNode/UnionNode have no database of their own; ColumnNode::toASTImpl is the column-qualifier consumer and is untouched. Every rendering funnel (queryNodeToSelectQuery, queryNodeToDistributedSelectQuery, SelectStreamFactory, ClusterProxy::executeQuery, StorageDistributed, StorageMerge, findParallelReplicasQuery, PlannerJoinTree, getHeaderForProcessingStage) reaches the fixed function and needs no change of its own.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured through the distributed IN, all returning the correct 6: String, Nullable(UInt64), LowCardinality(String) and Array(UInt32) parameters, a view carrying its own SETTINGS clause, and the IN {…:Array(String)} form. The boundary case is a dotted database name, which is deliberately left unqualified because extractDatabaseAndTableNameForParameterizedView resolves only one or two identifier parts; that shape already fails today, identically before and after, and is pinned by the new row.
h Backward compatible? (maintainer-approved exception only) Yes. No new or changed setting, no default change and no serialization format change, so no SettingsChangesHistory.cpp entry is needed. The behaviour change is confined to a shape that previously either threw or returned wrong results.
i Invariants and contracts preserved? Yes, and proven rather than argued: for the same query on the same fixture, EXPLAIN QUERY TREE is md5-identical before and after, and so is EXPLAIN SYNTAX. table_function_name is left untouched, so dumpTreeImpl, isEqualImpl and updateTreeHashImpl, and therefore query-tree identity and cache keys, are unaffected. That is why the name is not rewritten at resolve time. 04105_explain_syntax_parameterized_view passes unchanged on both binaries, and a 145-test neighbour A/B over the parameterized-view, view, table-function, EXPLAIN-SYNTAX and distributed IN/JOIN families gives identical reason-bucketed failure sets on both arms, with nothing failing only with the fix.

Session id: cron:clickhouse-impl-slot-41:20260805-121400

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vdimir @devcrafter, could you review this? A parameterized view referenced unqualified lost its database when the query was rendered for a shard, because TableFunctionNode::toASTImpl emitted the name the user typed and never consulted storage_id, so the shard re-resolved it against its own default database and either failed with UNKNOWN_FUNCTION or silently read a same-named view.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [29fb308]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Received signal 6 (internal) (STID: 3782-4008) FAIL cidb IGNORED
Stress test (arm_tsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue ISSUE EXISTS
BuzzHouse (amd_msan) FAIL
Logical error: Sending a distributed query with unknown (zero) client version. The query context was not initialized as an initial query (STID: 4148-4291) FAIL cidb IGNORED

AI Review

Summary

This PR tries to keep an unqualified parameterized view bound to the initiator's database when a distributed query is rendered for another server. The current fix is not correct yet: it synthesizes database.table as plain ASTFunction::name text, but the remote execution path serializes that AST as a single identifier, so the shard still cannot re-resolve the parameterized view under the intended database.

Findings

❌ Blockers

  • [src/Analyzer/TableFunctionNode.cpp:164] The new qualification path drops the compound-name structure. Remote reads format shard queries through formattedAST (src/Processors/QueryPlan/ReadFromRemote.cpp:178-189), and ASTFunction::formatImplWithoutAlias prints name as one identifier (src/Parsers/ASTFunction.cpp:937-945). That turns the synthesized db.view into `db.view`(...), while Context::executeTableFunction only splits database and table when isCompoundName() is set (src/Interpreters/Context.cpp:2980-2989). In the affected distributed paths, the shard can therefore still resolve the call in its current database or report Unknown table function.
    Suggested fix: preserve the qualified name as a real compound table-function name through the AST/formatter path instead of concatenating database + "." + table into ASTFunction::name.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 8/8 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 5, 2026
{
const auto database_name = storage_id.getDatabaseName();
if (Identifier{database_name}.getPartsSize() == 1)
table_function_ast->name = database_name + "." + storage_id.getTableName();

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 builds a qualified parameterized-view name as plain text, but the shard path still serializes the query back to SQL through formattedAST (src/Processors/QueryPlan/ReadFromRemote.cpp:178-189). ASTFunction::formatImplWithoutAlias prints name as a single identifier via backQuoteIfNeed(name) (src/Parsers/ASTFunction.cpp:937-945), so the new value here is emitted as `db.view`(...) instead of db.view(...).

That is still resolved incorrectly on the remote side: Context::executeTableFunction only splits database and table when isCompoundName() is set (src/Interpreters/Context.cpp:2980-2989). Since TableFunctionNode only stores a String, this new path drops the compound-name structure entirely, so a distributed query can still hit the current database or throw Unknown table function.

The fix needs to preserve a real compound function name through the AST/formatter path, not just concatenate database + "." + table into ASTFunction::name.

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.

You are right that the name is emitted as a single backquoted token, and wrong that it then
resolves incorrectly. I measured both halves on this head.

The shard really does receive the backquoted form. This is the shard's own system.query_log row
(is_initial_query = 0) for the distributed query:

SELECT shardNum() AS `_shard_num`, count() FROM `probe15`.`local_data` AS `__table1`
WHERE `__table1`.`tenant_id` IN (
    SELECT ... FROM `probe15.pv`(`tenants` = _CAST(['t1'], 'Array(String)')) AS `__table1`)

It resolves anyway, because the analyzer does not use isCompoundName(). A parameterized view is
resolved at QueryAnalyzer.cpp:4512 through extractDatabaseAndTableNameForParameterizedView
(src/Analyzer/Utils.cpp:1194), which re-splits the name string itself:

Identifier table_identifier{table_function_name};   // Utils.cpp:1199, splits on '.'
if (getPartsSize() == 2) { database_name = table_identifier[0]; table_name = table_identifier[1]; }

So the backquoting is lossless here: `db.pv` parses back to the name db.pv with
is_compound_name = false, and the analyzer splits the string regardless.
Context::executeTableFunction, which you cite, is the old-analyzer path.

End to end on a two-shard cluster, with a same-named view in default so an incorrect resolution
shows up as a wrong answer rather than an error:

binary name the shard received per-shard rows total
master before this PR pv(...) 1 3 only 3, wrong
this PR `probe15.pv`(...) 1 3 and 2 3 6, correct

One asymmetry is real but not introduced here: with enable_analyzer = 0 the backquoted spelling
does fail with Code: 46, since that path is keyed on the parser flag. It is unreachable from the
initiator, because enable_analyzer is not shipped to the shard (I set it to 0 and to 1 on the
initiator and the secondary query's own Settings map carried no entry either time, so the shard
uses its own default). And with enable_analyzer = 0 there is no query tree, toASTImpl never
runs, the name is never qualified, and the per-shard result is 1 3 on both binaries, which is
the pre-existing bug this PR does not change.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 29fb308

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'in' (STID 0250-41a5) flaky trunk — a set built for an in is not ready at execution time a fix task is moved to pending (investigating at full effort — fixing-PR link to follow here)
BuzzHouse (amd_msan) / Logical error: Sending a distributed query with unknown (zero) client version. The query context was not initialized as an initial query (STID 4148-4291) trunk — an omitted Distributed structure is inferred under an uninitialized query context #113220 (ours, open)
Stress test (amd_tsan) / Received signal 6 (internal) (STID 3782-4008) chronic trunk — std::terminate on a retryable error while loading outdated data parts #107091 (ours, open)

CI is otherwise finished on this head: 175 check-runs, 0 incomplete, Config Workflow and
Finish Workflow both success, 155 success / 17 skipped.

None of the three is caused by this PR. Its diff is confined to
src/Analyzer/TableFunctionNode.cpp plus its own new stateless test: it touches no set/subquery
planning, no distributed client-version path, and no part-loading code. All three are broad
trunk families with master occurrences and carriers spread across many unrelated pull requests.

Build (arm_release) / Post Hooks is check-level success and is not a failure (Post Hooks
is a shared row name across many checks; the sibling rows on this sha are OK).

Session id: cron:our-pr-ci-monitor:20260806-020000

@PedroTadim PedroTadim self-assigned this Aug 6, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 6, 2026
Merged via the queue into ClickHouse:master with commit 203da0b Aug 6, 2026
177 of 181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 6, 2026
@groeneai groeneai added the groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work label Aug 19, 2026
amosbird pushed a commit to amosbird/ClickHouse that referenced this pull request Oct 10, 2026
…ch on shards

An `IN` set is named `__set_<tree hash of its subquery>`, and that name is
part of every column a shard returns whose expression contains the `IN`
(an aggregate argument, a `GROUP BY` key, a `SELECT` item); the initiator
matches those columns by name. `TableFunctionNode::updateTreeHashImpl`
hashed a parameterized view call as typed (`pv`), while `toASTImpl` sends
it qualified (`default.pv(...)`, ClickHouse#113550), so each shard hashed a different
name and the query failed with `NOT_FOUND_COLUMN_IN_BLOCK`, or
`THERE_IS_NO_COLUMN` with `serialize_query_plan = 1`.

A resolved parameterized view is now hashed by
`storage_id.getFullNameNotQuoted()`, the way `TableNode` hashes its
storage. For a call typed qualified the hash bytes are unchanged, so a
fixed initiator works with 26.9 and unfixed master shards and a 26.9
initiator behaves as before. Hashing only the storage id (without the
name bytes) also fixes a single-version cluster, but breaks the qualified
spelling against 26.9 and unfixed master shards in both directions
(measured), so the name bytes are kept.

`isEqualImpl`, `toASTImpl` and `dumpTreeImpl` are unchanged, so
`EXPLAIN QUERY TREE` and `EXPLAIN SYNTAX` output does not change.

Co-Authored-By: Claude Opus 5.5 <[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 groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

JOIN on parameterized view fails with UNKNOWN_IDENTIFIER

3 participants