Skip to content

Qualify table function arguments sent to parallel replicas - #128194

Draft
nickitat wants to merge 16 commits into
masterfrom
pr-table-function-qualify-args
Draft

nickitat wants to merge 16 commits into
masterfrom
pr-table-function-qualify-args

Conversation

@nickitat

@nickitat nickitat commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Stacked on #119350: the base branch is that pull request's, so the diff here is this change alone.

A table function's arguments are sent to parallel replicas as written, so a replica resolved an unqualified table name in them against its own current database, not the initiator's: timeSeriesSamples(ts) in a non-default database failed there with UNKNOWN_TABLE. Plain tables do not have this problem, because the QueryTree -> AST conversion already qualifies a table name with its database.

ITableFunction::getTableArgument lets a table function say which leading arguments name a table and that it also accepts that table as 'database', 'table'. Before the query is sent, the initiator rewrites such a call to the qualified form (qualifyTableFunctionArguments), so timeSeriesSamples(ts) is sent as timeSeriesSamples('db', 'ts'). It is implemented by the TimeSeries target functions, timeSeriesSelector and prometheusQuery / prometheusQueryRange. The rewrite runs on every path that sends a query to the replicas: the task-based read, the custom-key fan-out and INSERT SELECT with parallel_distributed_insert_select = 2.

The rewrite never enters the arguments of another table function: remote and cluster evaluate theirs on the servers they name, so a call nested there is left as written, as without parallel replicas. The database setting stays stripped, so a qualified read never requires the initiator's current database to exist on the replicas.

This lands after #119350: without it, the replicas that now resolve such a call would each read the whole table.

Closes: #118130

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 UNKNOWN_TABLE with parallel replicas when a table function such as timeSeriesSamples named a table without its database and the current database was not the default one.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/128194]

A replica resolves an unqualified table name in a table function's arguments against its own current
database, not the initiator's, so `timeSeriesSamples(ts)` in a non-default database failed there with
`UNKNOWN_TABLE`. `ITableFunction::getTableArgument` reports which leading arguments name a table, and
before the query is sent the initiator rewrites them to `'database', 'table'`
(`qualifyTableFunctionArguments`): in the task-based read, the custom-key fan-out and `INSERT SELECT`
with `parallel_distributed_insert_select = 2`. The rewrite never enters the arguments of another table
function, since `remote` and `cluster` evaluate theirs on the servers they name.

Stacked on #119350, whose last commit moved this out of it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nickitat nickitat added pr-bugfix Pull request with bugfix, not backported by default comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Oct 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e0f5d3]

Summary: ✅


AI Review

Summary

This PR preserves the initiator's database when forwarding table-function calls to parallel replicas, including local view wrappers and INSERT INTO FUNCTION destinations. The latest changes address all earlier findings, including preserving scalar subqueries and the permission-dependent branch of viewIfPermitted. No unresolved actionable findings remain at 4e0f5d3a1f4992a177213d716122b70d40647982.

Final Verdict

Status: ✅ Approve.

@nickitat
nickitat changed the base branch from master to pr-table-function-anchor October 29, 2026 22:40
@nickitat
nickitat added this pull request to stack #128195 October 29, 2026 22:40
@nickitat
nickitat marked this pull request as draft October 29, 2026 22:41
@clickhouse-gh

clickhouse-gh Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 4e0f5d3a1 with master 3c82fa8cc (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

227 object files changed (+246.93 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Analyzer/TableFunctionNode.cpp.o 130.26 KiB 168.70 KiB +38.44 KiB (+29.51%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorageCluster.cpp.o 934.61 KiB 960.36 KiB +25.75 KiB (+2.75%)
src/CMakeFiles/dbms.dir/Planner/findParallelReplicasQuery.cpp.o 171.57 KiB 194.59 KiB +23.02 KiB (+13.42%)
src/CMakeFiles/dbms.dir/Interpreters/ClusterProxy/executeQuery.cpp.o 558.38 KiB 578.00 KiB +19.61 KiB (+3.51%)
src/TableFunctions/CMakeFiles/clickhouse_table_functions.dir/TableFunctionObjectStorage.cpp.o 2.66 MiB 2.67 MiB +18.48 KiB (+0.68%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

667 translation units recompiled, 5662 s compile time in total, 667 of them have a recent master baseline.

Job report

nickitat and others added 4 commits October 30, 2026 10:49
…plicas

Only the source `SELECT` was qualified. For
`INSERT INTO FUNCTION timeSeriesSamples(dst) SELECT * FROM timeSeriesSamples(src)` with a replicated
destination, the insert passes the parallel-replicas admission, but the forwarded
`ASTInsertQuery::table_function` still named `dst` without its database. The replicas resolved it in their
default database and failed with `UNKNOWN_TABLE`, or wrote into a same-named table there. The destination
is now rewritten to `'database', 'table'` with `ITableFunction::getTableArgument`, like the table function
calls in the `SELECT`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The qualification skipped the arguments of every table function, and the analyzer leaves the query of
`view` unresolved anyway, so it was sent as written. With `parallel_replicas_prefer_local_join = 1`, a join
against `view(SELECT value FROM timeSeriesSamples(ts))` or `view(SELECT value FROM t)` made the replicas
resolve `ts` and `t` in their default database: `UNKNOWN_TABLE`, or wrong results from a same-named table.

The query of `view` is now replaced with what a resolved copy prints, which names its tables qualified and
has its table function arguments qualified. It stays an unresolved argument, so that the initiator plans the
query it sends as before. Only the arguments of `remote`, `remoteSecure`, `cluster` and
`clusterAllReplicas` are left alone, since the servers they name evaluate them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…y-args

# Conflicts:
#	tests/queries/0_stateless/05175_time_series_table_functions_parallel_replicas.sql
… `TimeSeries` version 11

A row of the samples table now holds the samples of one series within one time bucket in the column
`samples`, and the table is an `AggregatingMergeTree`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nickitat and others added 3 commits October 30, 2026 15:10
…lel replicas

The query of `view` is qualified by printing a copy resolved with type-only analysis, which does not execute
scalar subqueries: it replaces each with a constant holding a placeholder value (the type's default), or with
`__getScalar` for some types, and the copy printed these. A join with
`view(SELECT (SELECT max(value) FROM source) AS value)` matched 0 instead of the real maximum on the replicas.

Constants made of or folded from a subquery are now replaced with the expressions they were made of before
printing, and the analysis runs with `enable_scalar_subquery_optimization` disabled so that no `__getScalar`
is left. The tables and table functions in those subqueries are qualified as well.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`viewIfPermitted` leaves its query unresolved as `view` does, but only `view` had its query qualified, so a
join with `viewIfPermitted(SELECT ... FROM t ELSE ...)` read `default.t` on the replicas.

Its query is now qualified the same way. Qualifying resolves the query, which checks access to its tables;
when the user may not run it, as `TableFunctionViewIfPermitted` decides, the call is sent as its `ELSE` table
function, which the initiator reads too. Sent as written instead, a replica would decide again on the query
resolved in its own default database, and could read a table there the user is allowed to read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nickitat and others added 3 commits October 31, 2026 20:55
…reads

The previous change decided the branch by resolving the query of `viewIfPermitted`, which checks less than
`TableFunctionViewIfPermitted` does: a user who may see the columns of a table but not read it got its query sent
to the replicas, which, running as a user who may read it, returned its rows. When the call was allowed, it was
still sent as `viewIfPermitted`, so a replica running as another user could choose `ELSE`. And a `view` sent as the
`ELSE` table function kept its query unqualified.

The branch is now taken from the storage `TableFunctionViewIfPermitted` made: a view of its query, or the storage of
its `ELSE` table function. The call is sent as `view` of the qualified query, or as the `ELSE` table function, which
is handled in turn when it is `view` or `viewIfPermitted`. The replicas get no `viewIfPermitted` to decide again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMTxKfRgb4QVVVCfsmAbFo
…query of `view`

With `enable_function_early_short_circuit`, the analysis that qualifies the query of `view` folds
`1 OR (SELECT count() FROM t) > 0` to a constant whose source expression is an unresolved copy, which
`RestoreScalarSubqueriesVisitor` restored because it has a subquery. The replicas got `t` unqualified and failed
with `UNKNOWN_TABLE` in their own default database. The analysis now runs without early short-circuit, so the
source expression of such a constant is resolved and its tables are qualified.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMTxKfRgb4QVVVCfsmAbFo
…uery of `view`

The analysis that qualifies the query of `view` disabled `enable_scalar_subquery_optimization` and
`enable_function_early_short_circuit` in the context it built the query with, but `buildQueryTree` applies the
`SETTINGS` of each query and union to its own context, so `SETTINGS enable_function_early_short_circuit = 1` there
enabled the early fold again, and the replicas got the unqualified table of the folded subquery and failed with
`UNKNOWN_TABLE`. The settings are now set on the context of every query and union after the tree is built. The
query sent keeps the user's `SETTINGS`, which are printed from the nodes rather than their contexts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMTxKfRgb4QVVVCfsmAbFo
Base automatically changed from pr-table-function-anchor to master November 1, 2026 00:23
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 16, 2026
A table function that reads the current database, through a name without
a database (`loop(t)`, `dictionary('d')`, `timeSeriesSamples(ts)`) or
through '' (`mergeTreeIndex('', t)`), kept that argument as written in the
query tree. That tree is what remote(), Distributed, *Cluster and
parallel replicas send to other servers, and each of them resolved the
name in its own default database: an IN or JOIN subquery of a
distributed query read other rows or failed with UNKNOWN_TABLE.

As asked in
ClickHouse#131589 (comment),
the knowledge of which arguments name the database moves to the table
function, which computes it in parseArguments: the new virtual
ITableFunction::getQualifiedArguments returns the leading arguments with
that database written out, and QueryAnalyzer::resolveTableFunction
substitutes them in one place. This replaces the `merge` binder of ClickHouse#122985
and ClickHouse#131528 and the `loop` / `dictionary` binder of the first version of
this PR; StorageMerge::getSourceDatabaseNameOrRegexp, which only the
`merge` binder used, is removed. Calls already written that way keep
their nodes. The exclusions are unchanged: the table of remote() or
cluster(), a query printed from a resolved tree (serialize_query_plan
shard plans) and a secondary query.

Implemented by merge, loop, dictionary (a database name containing a dot
stays unqualified), mergeTreeIndex, mergeTreeAnalyzeIndexes,
mergeTreeCodecBlockCounts, mergeTreeTextIndex, mergeTreeProjection,
timeSeriesSamples / Tags / TimeRanges / MetricFamilies (and their
aliases), timeSeriesSelector, prometheusQuery and prometheusQueryRange.
The TimeSeries functions use the `num_table_arguments` names of ClickHouse#128194.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TimeSeries table functions are broken with parallel replicas: UNKNOWN_TABLE on the replicas and duplicated rows

1 participant