Repository navigation
Allow creating a Distributed table over a table function - #110073
alexey-milovidov wants to merge 147 commits into
Conversation
The `Distributed` table engine can now take a table function as its
remote target, mirroring the `cluster('cluster_name', table_function())`
signature of the `cluster` table function:
CREATE TABLE t ENGINE = Distributed(cluster, table_function()[, sharding_key[, policy_name]])
The second engine argument is treated as a table function only when it
is a call to a registered table function (such as `numbers`, `remote`,
or `merge`); any other expression is still interpreted as a database
name, so the existing `Distributed(cluster, database, table, ...)` form
is unaffected. The structure is inferred from the table function when
the columns are omitted.
`INSERT` into a table-function-backed Distributed table is rejected with
`NOT_IMPLEMENTED`, since there is no concrete remote table to route rows
to (this also makes the pre-existing behavior of
`INSERT INTO FUNCTION cluster('cluster', table_function())` fail with a
clear error instead of silently building a broken query).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [72f2a61] Summary: ❌
|
Align the table-function INSERT guard in `StorageDistributed::write` with the one added by #106189 so the two changes converge: use the identical exception message ("Method write is not supported by storage {} with a table function target") and place the guard only in `write` (removing the extra guard in `distributedWrite`). A table-function target still fails closed on the `INSERT ... SELECT` optimization path: `remote_storage` is an empty `StorageID`, which the query builder rejects. The read path keeps the `remote_table_function_ptr ? StorageID::createEmpty()` form: the `Distributed` engine over a table function stores empty remote database/table names (self-consistent with the `remote_storage` member), rather than the `system.one` placeholder that #106189's `Remote`/`RemoteSecure` engines inherit from the `remote` table function. This also makes the shared `read` path robust for #106189's engines. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… table The `Distributed` engine's table-function branch only checked that the second argument is a registered table function name. That accepted `*Cluster` table functions (`urlCluster`, `s3Cluster`, `fileCluster`, ...), whose `ITableFunctionCluster::canBeUsedToCreateTable` is `false` and which `InterpreterCreateQuery` rejects for `CREATE TABLE ... AS table_function`. With explicit columns the unsupported combination was written to metadata without ever instantiating the function, so it was only discovered later at read time. Instantiate the candidate table function at create time and reject it with `BAD_ARGUMENTS` unless `canBeUsedToCreateTable` is true, mirroring `InterpreterCreateQuery`. The check is gated to `CREATE` so it does not run on `ATTACH`, where the table already exists and the backing cluster may be unavailable. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add regression tests for a `Distributed` table over a table function: - A `*Cluster` table function (`urlCluster`) is rejected at create time with `BAD_ARGUMENTS`, including when the columns are given explicitly. - A table function that resolves back to the `Distributed` table itself (e.g. `merge(currentDatabase(), '^dist_over_tf$')`) recurses at read time, but the recursion is bounded by `max_distributed_depth` and raises `TOO_LARGE_DISTRIBUTED_DEPTH` rather than hanging. This matches the behavior of two classic `Distributed` tables that reference each other; direct self-references are only detected at create time for the `Distributed(cluster, database, table)` form. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`DDLLoadingDependencyVisitor` extracts the loading dependency that a `dictGet`/`joinGet` expression in the sharding key introduces (so a `Distributed` table is loaded after the dictionary / `Join` table it references on restart). It hard-coded the sharding key as the 4th engine argument, matching the classic `Distributed(cluster, database, table, sharding_key, policy)` form. The table-function form `Distributed(cluster, table_function(), sharding_key, policy)` moves the sharding key to the 3rd argument, so the dependency was silently dropped: `Distributed(cluster, table_function(), dictGet(...))` could work before a reboot and then fail to load afterwards, exactly the case `test_dependent_dict_table_distr` guards for the classic form. Detect the table-function form the same way `registerStorageDistributed` does (a second argument that is a call to a registered table function) and read the sharding key from the shifted position. Regression test in `04508_distributed_over_table_function` asserts, via `system.tables.loading_dependencies_table`, that the dictionary dependency is registered for the table-function form.
… target
`updateSettingsAndClientInfoForCluster` always re-keyed the initiator's
`additional_table_filters` onto the source table via `main_table.getShortName()`.
When a `Distributed` table (or the `cluster`/`remote` table functions) targets a
table function, `main_table` is an empty `StorageID`, so `getShortName` threw a
confusing `UNKNOWN_TABLE` ("Both table name and UUID are empty") before the query
reached any shard.
The filter cannot be re-keyed onto a source table name for a table-function target:
the shard-side table-function expression is referenced only by an internally
generated `__tableN` alias (`createUniqueAliasesIfNecessary` overwrites any custom
alias), so there is no stable key the shards would match. Reject the combination
with a clear `NOT_IMPLEMENTED` instead. The classic named-table form is unaffected.
Reviewed at #110073
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…unction target
Two more paths assumed every `StorageDistributed` has a concrete remote
table id, which a table-function-backed `Distributed` table (e.g.
`Distributed(cluster, numbers(10))`) does not have, so they failed with a
confusing `UNKNOWN_TABLE` ("Both table name and UUID are empty") instead of
the advertised `NOT_IMPLEMENTED`.
- `INSERT ... SELECT` with `parallel_distributed_insert_select` enabled (the
default) reached `StorageDistributed::distributedWrite` before the guard in
`write`, and both distributed fast paths built
`StorageID(getRemoteDatabaseName(), getRemoteTableName())` out of empty
names. `distributedWrite` now returns early for a table-function target, so
the write falls back to `write`, which rejects it with `NOT_IMPLEMENTED`.
- `distributed_product_mode = 'local'` rewrites a nested `Distributed`
subquery to its concrete remote table. There is no such table for a
table-function target, so both rewrite sites -
`buildQueryTreeForShard` (analyzer) and `InJoinSubqueriesPreprocessor`
(old analyzer) - now reject it with a clear `NOT_IMPLEMENTED`.
Added a `StorageDistributed::isRemoteTableFunction` helper and regression
cases to `04508_distributed_over_table_function` covering both forms and both
analyzers; verified the classic named-table `local` rewrite still works.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ly CREATE The gate that rejects table functions that cannot back a `Distributed` table (`*Cluster` functions, `canBeUsedToCreateTable == false`) was conditioned on `args.mode <= LoadingStrictnessLevel::CREATE`, so only `CREATE` was covered. A user-issued `ATTACH TABLE ... (columns) ENGINE = Distributed(cluster, urlCluster(...))` runs with `LoadingStrictnessLevel::ATTACH`, which bypassed the check and re-opened the original bug through a different entrypoint: the unsupported combination was accepted into metadata with explicit columns and only failed later at read time. Gate the check on `!isLoadingFromExistingMetadata(args.mode)` instead, so every fresh user query (`CREATE`, `SECONDARY_CREATE`, `ATTACH`) is validated, while only genuine metadata loads (`FORCE_ATTACH` / `FORCE_RESTORE`, i.e. server startup / force-restore) skip it - matching how `InterpreterCreateQuery` validates `CREATE TABLE ... AS table_function`. Extend `04508_distributed_over_table_function` with a regression for the `ATTACH TABLE ... UUID '...' (columns) ENGINE = Distributed(..., urlCluster(...))` entrypoint (the `UUID` form is how an `Atomic` database accepts an `ATTACH` with an explicit definition). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… UUID
The `ATTACH TABLE ... UUID '04508000-...'` regression used a hardcoded UUID to
exercise the user-`ATTACH` (`LoadingStrictnessLevel::ATTACH`) gate on an `Atomic`
database. The UUID-to-table mapping is server-global and is registered before the
storage is constructed, so it leaks even when the `ATTACH` ultimately fails with
`BAD_ARGUMENTS`. The flaky check re-runs the changed test against the same server,
so the second run hit `Mapping for table with UUID=... already exists`
(`TABLE_ALREADY_EXISTS`) instead of the expected `BAD_ARGUMENTS`.
Use a `Memory` database instead: it accepts `ATTACH TABLE` with an explicit
definition without a UUID (unlike `Atomic`), still runs with mode `ATTACH`, and
leaves no global UUID mapping behind. The per-invocation-unique
`{CLICKHOUSE_DATABASE_1}` name plus `DROP DATABASE` guards make repeated runs safe.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… on the legacy read path The `clickhouse-gh` review found that a `Distributed(cluster, table_function())` read fails on the legacy `enable_analyzer = 0` path for qualified column references. That path rewrites the shard query with `ClusterProxy::rewriteSelectQuery`, which for a table-function target only swaps the `FROM` clause: it skips `RestoreQualifiedNamesVisitor` (there is no concrete remote `database.table` to restore onto) and `ASTSelectQuery::addTableFunction` dropped any existing alias. So `SELECT dist.number FROM dist SETTINGS enable_analyzer = 0` (or `SELECT d.number FROM dist AS d`) shipped `SELECT dist.number FROM numbers(10)` / `SELECT d.number FROM numbers(10)` and failed on the shard with an unknown-identifier error. Fix `ASTSelectQuery::addTableFunction` to preserve an explicit alias (the condition was inverted relative to `replaceDatabaseAndTable`), and in `rewriteSelectQuery` alias the shard-side table function with the qualifier the original query used for the Distributed table - its explicit alias, or otherwise its name - so qualified references keep resolving on the shard. This also fixes the same latent issue for the `cluster()`/`remote(..., table_function())` forms, which share this path. The analyzer path already resolves columns structurally and is unaffected. The regression is covered on both `enable_analyzer` settings in `04508_distributed_over_table_function`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…reserved
The Fast test flagged `02341_global_join_cte`: its first query expected
`ALIAS_REQUIRED` with `enable_analyzer = 0`, but now succeeds.
The old error was an artifact of the alias-dropping bug fixed in the previous
commit: `remote('127.{1,2}', view(...)) lhs` is a table-function-backed
distributed read, and `ClusterProxy::rewriteSelectQuery` used to drop the `lhs`
alias when replacing the `FROM` clause of the shard query. Since the shard
query has two tables (the `view(...)` and the external table shipped by
`GLOBAL JOIN`), `joined_subquery_requires_alias` rejected the now-unaliased
table function on the shard with `ALIAS_REQUIRED`, even though the user had
written an alias. With the alias preserved, the query succeeds on the shard
and returns the same result as on the analyzer path (and as the remaining
queries of the test).
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110073&sha=97c68a470628cce072e472e1229572e4ea14a61b&name_0=PR&name_1=Fast%20test
PR: #110073
Co-Authored-By: Claude Fable 5 <[email protected]>
… table-function-backed source The source-side fast path in `distributedWriteBetweenDistributedTables` replaced the whole `SELECT` with a bare `SELECT * FROM table_function()` (or, for a `view` source, with the inner query of the `view`), silently dropping the projection, the filter and the other clauses of the original query, so the rows written to the destination did not match the user's `SELECT`. Rebuild the shard query from the original `ASTSelectQuery` with only the table expression replaced, the same way the named-table branch does, and alias the table function with the qualifier the query used for the source table so that references qualified by it keep resolving on the shards. Addresses the review comment #110073 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
…alias on the legacy read path For a table-function-backed Distributed table, `ClusterProxy::rewriteSelectQuery` aliased the shard-side table function with the qualifier of the original table expression, which fixed `dist.x` and `d.x`, but skipped the `RestoreQualifiedNamesVisitor` pass, so a database-qualified reference like `db.dist.x` still shipped verbatim and could not bind to the aliased table function on the shard. Run the restore pass against a synthetic `remote_table.alias` equal to that qualifier, so `table.column`, `alias.column` and `database.table.column` references are all rewritten onto the alias the table function carries in the shipped query. Addresses the review comment #110073 (comment) Co-Authored-By: Claude Fable 5 <[email protected]>
|
Confirmed on the arm_msan failure (STID 4348-2010). It is the chronic async remote-read fiber SIGSEGV, unrelated to this PR:
I opened a tracking issue with the stack, signature, occurrences and root-cause direction: #110124. Root-cause direction: the unmapped address is the fiber's own stack, and the sink fiber is resumed via |
…ial dependencies of a persisted `remote()` target `DDLDependencyVisitor` decided the locality of a `remote()` / `remoteSecure()` address only for an IP literal and `localhost`, so the common host-name spelling - `remote(hostName(), currentDatabase(), 'src')`, which is also how a cluster definition usually spells a server - recorded no referential dependency on the local table the function reads, and `DROP` / `RENAME` of that table was allowed under `check_referential_table_dependencies = 1` even though the persisted table then fails at read time. The name this server reports for itself is known locally - `getFQDNOrHostName` determines it once and caches it, and the `hostName` function returns it - so recognizing that spelling needs no DNS lookup, which this analysis must avoid: it is re-run from metadata at server startup, where a slow or unavailable resolver would block loading the tables. Both the full name and its leading label are accepted, because a server named by a fully qualified domain name is commonly addressed by the short form as well. Any other host keeps the long-standing non-local assumption. Regression test `05029_remote_host_name_dependencies`.
…ble-function # Conflicts: # tests/queries/0_stateless/02341_global_join_cte.reference # tests/queries/0_stateless/02341_global_join_cte.sql
…et argument validation `validateTableFunctionTargetArguments` reparses the target with `TableFunctionFactory::get`, and the `timeSeries*` / `prometheusQuery*` family resolves its source table while parsing the arguments. A same-named local table with the wrong engine therefore threw `UNEXPECTED_TABLE_ENGINE` and rejected a remote-only explicit-columns definition based on irrelevant initiator-local catalog state, contradicting the deferred-resolution contract of this form. Defer this code exactly like `UNKNOWN_DATABASE` / `UNKNOWN_TABLE`: the paths that do require the target to resolve on the initiator (schema inference for an omitted column list, the access probe for a cluster with a local shard) re-resolve it afterwards under their own fatality rules, so nothing is lost. #110073
|
🕵 @groeneai, investigate the two infrastructure failures on
I merged current master into the branch ( |
|
Both are unrelated to this PR, and both already have an open fix PR of mine. Fast test (arm_darwin), disk exhaustion: #113605 The job's own On master a macOS runner never checks free space anywhere: #113605 extracts the check as Its limit, so I am not overselling it: a host that fills up mid-job is still only caught one job later, by the post-run check. This one was already full at pickup, so it is covered. 31 Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6), session timeout: #115963 7321 s of shard wall clock against the 7200 s budget. The cause is shard packing rather than any test: the regeneration query embedded above the duration table in #115963 lowers that floor to You have #116591 open on the same class. Mine predates it and overlaps it; which one lands is your call, I am not going to referee that. |
…local-replica probe; correct the unresolvable named collection contract Two unresolved `clickhouse-gh` review threads. 1. `SelectStreamFactory::createForShardImpl` built the target table function with `TableFunctionFactory::get` outside the tolerant block, so a target that resolves its backing object in `parseArguments` - `timeSeriesMetrics`, `timeSeriesSelector`, `prometheusQuery`, `prometheusQueryRange` - aborted the read instead of taking the skip/failover path that the named-table branch and the structure-resolving targets take. `get` now runs inside the same `try`. The static-structure functions this could otherwise misclassify are unaffected: `numbers` and `zeros` have no `parseArguments` and evaluate their arguments in `executeImpl`, outside the block. 2. The `remote`/`remoteSecure` named-collection binding rejected an unresolvable collection with a message - and a source-registered docs paragraph - advising an explicit `database = ...` / `db = ...` override as the escape hatch. It is not one: target-argument validation parses the target through `TableFunctionRemote`, which reports the absent collection as `NAMED_COLLECTION_DOESNT_EXIST` in those spellings too, as `04837_distributed_over_remote_unresolvable_named_collection` asserts. The message, the surrounding comment and the docs paragraph now say the collection must be defined on this server. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 CI status on Four reds, all previously-known and none related to this PR; three of them already have a fix on
@groeneai, could you take a look at the remaining one (#113981) and provide a fix in a separate PR? If a fix is already in progress, please link it there. The push also addresses the AI review: |
|
Already fixed in a separate PR: #114065, open since 2026-08-09. I have linked it in #113981 as you asked. The stack in that report ( |
…function The AI review found that `CREATE TABLE ... AS remote(..., viewIfPermitted(...))` persists the nested function too, and a later read on a local shard with `prefer_localhost_replica = 0` decides the guarded branch under the connection's credentials instead of the reader's grants, disclosing the guarded structure in the `BAD_ARGUMENTS` mismatch text or the guarded rows. Refuse a grant-dependent table function at any nesting depth in `InterpreterCreateQuery`, through a new `ITableFunction::dependsOnCurrentUserGrants` virtual that only `viewIfPermitted` overrides. An AST walk rather than a check inside `remote` argument parsing, because it also catches carriers such as `remote(..., loop(viewIfPermitted(...)))` and stays out of the files ClickHouse#110073 is rewriting; keyed on the new narrow predicate rather than `canBeUsedToCreateTable`, so `remote(..., clusterAllReplicas(...))` and other user-independent nested functions are not newly refused. The query form of the same disclosure, `SELECT ... FROM remote(..., viewIfPermitted(...))` with `prefer_localhost_replica = 0`, needs no table and is unchanged here; it is tracked separately.
|
@rschu1ze — tagging you on this one as JOIN-related, as requested. Review request sent too. |
…nction target The create-time analysis of a table-function target resolves the arguments of the stored AST in place, and that must stay in place: the same AST is formatted and sent to the other shards, so a session-dependent argument has to be resolved on the initiator. Resolving in place was losing something, though. `parseArguments` of `mysql`, `PostgreSQL` and `ytsaurus` consumes a function-local `SETTINGS` clause by erasing it from the argument list of the AST it is given, and for a `Distributed` / `Remote` / `RemoteSecure` target that list is the persisted definition, so a `CREATE` over such a target stored a definition without the settings the user wrote, and every later read used the defaults instead. The new `PreservedTableFunctionSettings` guard remembers every `SETTINGS` clause of the target - at any nesting depth, so `loop(mysql(..., SETTINGS ...))` is covered as well - and puts back the ones the analysis consumed, including when the analysis throws (a failed analysis is tolerated for a target with an explicit column list, and the definition is persisted anyway). It is applied to the local shard branch of `getStructureOfRemoteTableInShard` and to the create-time access probes of both the `Distributed` and the `Remote` / `RemoteSecure` branch. Test `05055_distributed_over_table_function_target_settings_preserved`: the `SETTINGS` clause of a `mysql` / `PostgreSQL` target survives `CREATE`, is visible in `system.tables.engine_full`, and survives a `DETACH` / `ATTACH` round trip through the metadata.
…today A table function written inside the argument list of a table engine - or inside the argument list of another function - is parsed as an ordinary expression, and only the table-function position of a query accepts a `SETTINGS` clause, so `Distributed(cluster, mysql(..., SETTINGS connect_timeout = 12))` is a syntax error, and so is the same clause nested in `remote(...)` or `view(...)`. The guard added in the previous commit therefore cannot be exercised from SQL: it is there so the persisted definition cannot start losing settings if that position ever accepts the clause. The test that tried to pin it is removed, and the reason is recorded in the guard's comment instead.
Master commit `4134b2fe62d2` ("TimeSeries: make `Tuple(UInt64, LowCardinality(UUID))`
the default id type") changed the default `id` column of the tags table, which this
test prints through `SHOW CREATE` of a `Distributed` table over `timeSeriesTags`.
The reference now carries the new type and its `toLowCardinality` default expression.
|
🕵 The only CI failure on Master was merged anyway ( |
|
I don't like it. |
Related: #106189
Allow creating a
Distributedtable over a table function, in the same way theremote/clustertable functions already accept an arbitrary table expression.Previously
CREATE TABLE ... ENGINE = Distributed(...)only acceptedDistributed(cluster, database, table[, sharding_key[, policy_name]]), wheredatabaseandtablehad to be string literals or identifiers.StorageDistributeditself already supported being backed by a table function (remote_table_function_ptr), but that capability was only reachable through theremote/cluster/clusterAllReplicastable functions.This change lets the engine take a table function directly:
mirroring the
cluster('cluster_name', table_function())signature. The second engine argument is treated as a table function only when it is a call to a registered table function; any other expression is still interpreted as a database name, so the existingDistributed(cluster, database, table, ...)form is unaffected. The structure is inferred from the table function when the columns are omitted.INSERTinto a table-function-backedDistributedtable is rejected withNOT_IMPLEMENTED, since there is no concrete remote table to route rows to. As a side effect,INSERT INTO FUNCTION cluster('cluster', table_function())now fails with this clear error instead of silently building a brokenINSERT INTO <empty>query for the shards.Relationship to #106189
This is complementary to #106189 (
Remote/RemoteSecurestorage engines): that PR adds address-based engines over an ad-hoc cluster, while this one lets the configured-clusterDistributedengine take a table function. The table-functionINSERTguard inStorageDistributed::writeis aligned with #106189 (identical exception message, guard placed only inwrite). Thereadpath here additionally handles the case where the remote database/table names are empty (a table-function-backedDistributedstores empty names rather than thesystem.oneplaceholder that #106189's engines inherit from theremotetable function); this also makes the sharedreadpath robust for #106189's engines.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Allow creating a
Distributedtable over a table function, e.g.CREATE TABLE t ENGINE = Distributed(cluster, numbers(100)), in the same way as thecluster/remotetable functions accept a table function.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/110073]