Skip to content

Allow creating a Distributed table over a table function - #110073

Closed
alexey-milovidov wants to merge 147 commits into
masterfrom
distributed-over-table-function
Closed

alexey-milovidov wants to merge 147 commits into
masterfrom
distributed-over-table-function

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 11, 2026 •

Copy link
Copy Markdown
Member

Related: #106189

Allow creating a Distributed table over a table function, in the same way the remote/cluster table functions already accept an arbitrary table expression.

Previously CREATE TABLE ... ENGINE = Distributed(...) only accepted Distributed(cluster, database, table[, sharding_key[, policy_name]]), where database and table had to be string literals or identifiers. StorageDistributed itself already supported being backed by a table function (remote_table_function_ptr), but that capability was only reachable through the remote/cluster/clusterAllReplicas table functions.

This change lets the engine take a table function directly:

CREATE TABLE t ENGINE = Distributed(cluster, table_function()[, sharding_key[, policy_name]]);
-- e.g.
CREATE TABLE distributed_numbers ENGINE = Distributed(test_cluster_two_shards, numbers(100));

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 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. As a side effect, INSERT INTO FUNCTION cluster('cluster', table_function()) now fails with this clear error instead of silently building a broken INSERT INTO <empty> query for the shards.

Relationship to #106189

This is complementary to #106189 (Remote/RemoteSecure storage engines): that PR adds address-based engines over an ad-hoc cluster, while this one lets the configured-cluster Distributed engine take a table function. The table-function INSERT guard in StorageDistributed::write is aligned with #106189 (identical exception message, guard placed only in write). The read path here additionally handles the case where the remote database/table names are empty (a table-function-backed Distributed stores empty names rather than the system.one placeholder that #106189's engines inherit from the remote table function); this also makes the shared read path robust for #106189's engines.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Allow creating a Distributed table over a table function, e.g. CREATE TABLE t ENGINE = Distributed(cluster, numbers(100)), in the same way as the cluster/remote table functions accept a table function.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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]>
@mintlify

mintlify Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 11, 2026, 2:00 AM

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [72f2a61]

Summary: ❌

job_name test_name status info comment
Style check FAIL
cpp FAIL cidb
Code Review DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 11, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 3 commits July 11, 2026 03:49
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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
`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.
Comment thread src/Storages/StorageDistributed.cpp Resolved
… 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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
…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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
…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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 4 commits July 11, 2026 11:52
… 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]>
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 2 commits July 11, 2026 20:58
… 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The two stress-test failures on f75f6b4 are unrelated to this PR:

@groeneai, investigate the second failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110073&sha=f75f6b4383cd713bb07ad345f879953ae276e50e&name_0=PR&name_1=Stress%20test%20%28arm_msan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. There is no open issue for STID 4348-2010 yet.

Comment thread src/Storages/StorageDistributed.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

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 SuspendCallback holding Impl & impl. A crash there means the sink context / FiberStack was moved-from or destroyed while a suspend was in flight, i.e. an interaction between AsyncTaskExecutor resume/cancel/restart/destroyFiber and the in-flight suspend_callback. This is arm_msan-only and I could not reproduce it locally without an arm MSAN build, so I have no deterministic repro yet. I will keep investigating on #110124 and open a separate fix PR once I can back it with a repro; I will not push a speculative change. Nothing needed on this PR.

…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`.
Comment thread src/Storages/StorageDistributed.cpp Resolved
…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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the two infrastructure failures on 1255a744754f, unrelated to this PR, and provide a fix in a separate PR if applicable (if a fix is already in progress, link it here):

  • Fast test (arm_darwin) — the macOS runner hit No space left on device while installing the test configs, so the binary could not even run (Permission denied follow-up); looks like runner disk hygiene.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) — the shard hit the 7200 s session timeout at 98% (940/955 passed, last test test_keeper_https_control_standalone_cluster); no individual test failed.

I merged current master into the branch (df1a98b347b8) so the fresh CI run re-runs both jobs.

@groeneai

Copy link
Copy Markdown
Collaborator

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 df -h, 33 s before the failure, already showed the root volume at 98% used with 2.4 GiB free (/dev/disk5s2s1). So the host was over the line before this job started rather than filled by it, and ci/tmp sits on that volume.

On master a macOS runner never checks free space anywhere: _check_conditions has no disk check, and check_post_run returns early for Environment.MACOS before reaching its df. A host that boots full therefore stays in the pool.

#113605 extracts the check as Runner.check_free_disk_space and calls it from _check_conditions, deliberately above the macOS early return, so it runs in the runner loop before config() and run_job(), i.e. strictly before the config-install step. At the thresholds already in that file (3,000,000 1-KiB blocks and 5% free) this host fails both at 2.4 GiB / 2%: the runner raises, run() deregisters it, and the job goes to a healthy host.

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 Fast test (arm_darwin) failures with this signature across 18 distinct pull requests between 2026-08-01 and 2026-08-25.

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 ci/jobs/scripts/integration_tests_configs.py ends HAVING dur > 60000, so only 302 of 1085 discovered test files carry a weight. The rest land in unknown_groups and are placed by unweighted whole-prefix round-robin, leaving the LPT pass balancing about a quarter of the suite.

#115963 lowers that floor to > 1000 and regenerates the table with it: 302 -> 1079 entries, 99.3% of discovered files covered, and 7 prefix groups left on the round-robin path instead of 620. Held-out simulation (trained on days 8-21, scored on the last 7, so the windows are disjoint): parallel peak 6087 s -> 5568 s, spread 20.2% -> 2.2%. Over 30 days this signature has 54 Timeout rows across 49 distinct pull requests and 5 of the 6 old-analyzer shards, 5 of them on master itself; 3/6 is joint-worst at 17.

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.

Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
Comment thread src/Storages/StorageDistributed.cpp Resolved
alexey-milovidov and others added 2 commits August 30, 2026 02:58
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CI status on df1a98b347b8 and what was done about it.

Four reds, all previously-known and none related to this PR; three of them already have a fix on master, so I merged master (clean, b5b3a8d87030) to pull them in:

@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: TableFunctionFactory::get moved inside the tolerant block of the local-replica probe (with the requested timeSeriesMetrics regression test in 04621_distributed_over_table_function_2), and the stale database = ... escape-hatch advice removed from the exception message, the surrounding comment and the source-registered engine documentation.

@groeneai

Copy link
Copy Markdown
Collaborator

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 (getReadyFileDescriptor during RemoteQueryExecutor::finish) is the early-finish path that PR addresses: the three paths that stop the hedged replica factory never cleared the per-offset pending-replacement flag, so once the last replica's receiver timed out the designed SOCKET_TIMEOUT was suppressed and the loop reached Epoll::getManyReady with nothing registered. CI is green on 8c3d5fe312f412 and the branch is mergeable, with no human review on it yet.

alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 30, 2026
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure on b5b3a8d8 was BuzzHouse (amd_tsan): an out-of-bounds std::vector<String>::operator[] in ReplicatedMergeTreeCleanupThread::clearOldLogs (fatal.log). It is unrelated to this pull request - no Distributed or table-function code is involved - and it already has a fix in flight: #117147 ("Fix out-of-bounds read in the ReplicatedMergeTree cleanup thread when `max_replicated_logs_to_keep = 0`"), which is not merged yet, so merging master cannot clear it here.

Master was merged anyway (05fc26319f01); that merge also required updating the reference of 04538_distributed_over_time_series_table_function, because master commit 4134b2fe62d2 changed the default TimeSeries id type to Tuple(UInt64, LowCardinality(UUID)). All 29 stateless tests of this pull request pass locally against a build of the new head.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

I don't like it.

This branch was successfully deployed

1 active deployment
staging - docs — 72f2a61e Deployed Sep 1, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants