Skip to content

Fix INSERT INTO <Distributed table> SELECT FROM url()/s3() with parallel replicas: duplicated data and bypassed sharding key - #121070

Merged
devcrafter merged 12 commits into
masterfrom
fix-insert-select-distributed-auto-cluster-function
Oct 3, 2026
Merged

devcrafter merged 12 commits into
masterfrom
fix-insert-select-distributed-auto-cluster-function

Conversation

@devcrafter

@devcrafter devcrafter commented Sep 19, 2026 •

Copy link
Copy Markdown
Member

Related: #120488
Related: #120485
Related: #100788

INSERT INTO <Distributed table> SELECT ... FROM url(...) (or s3(...), azureBlobStorage(...), ...) with parallel replicas enabled goes through StorageDistributed::distributedWriteFromClusterStorage, which forwards the query text to every shard of the Distributed table's cluster and hands the shards their read tasks through a task iterator. Two things are wrong on that path.

1. The data is inserted once per shard. parallel_replicas_for_cluster_engines converts the plain table function into a cluster storage on the initiator, but the forwarded query text still named the plain function. A shard running it as a secondary query does not convert it again — the conversion is deliberately skipped for SECONDARY_QUERY, and the plain table function hardcodes distributed_processing = false — so it ignored the task iterator, expanded the globs itself and inserted the whole dataset. This is the same defect #120488 fixes for the ReplicatedMergeTree and data lake destinations, and it is fixed the same way: IStorageCluster::updateQueryToSendIfNeeded rewrites the source into its *Cluster variant before the query is serialized.

The cluster named in the rewritten function is the Distributed table's own cluster, because its shards are the ones that run the forwarded query and consume the read tasks; the source's cluster_for_parallel_replicas plays no part in this fan-out and need not even exist on those shards. The target cluster name is therefore passed to updateQueryToSendIfNeeded instead of always being the source storage's own cluster. A remote() / cluster() destination owns an ad-hoc cluster that is absent from remote_servers, so there is no name a shard could resolve: such a query is not forwarded at all, rather than forwarded in a shape that every shard would answer with the whole source.

2. The sharding key was bypassed. With parallel_distributed_insert_select = 2 (the default since 25.7) the forwarded INSERT is retargeted at each shard's own local table, bypassing DistributedSink and therefore the sharding key. For a Distributed source that is sound — the rows a shard reads from its local table are already the rows placed there — but a cluster table function hands out files by rendezvous hashing over their paths, which has nothing to do with the destination's sharding key. The rows end up on arbitrary shards, and optimize_skip_unused_shards then prunes shards that do hold matching rows, so queries silently return partial results.

The distributed execution is now used only when the destination's sharding key is not deterministic. A non-deterministic key (rand(), ...) cannot describe where a row belongs — shard pruning is already disabled for it — so arbitrary placement is fine and the fast path stays. A deterministic key does describe it and a cluster table function can never satisfy it, so the query falls back to the ordinary INSERT ... SELECT, which places the rows through DistributedSink while the SELECT still reads the source cluster in parallel. This follows the existing contract of these paths: an inapplicable optimization falls back rather than throwing, and the reason is logged.

With parallel_distributed_insert_select = 1 nothing changes: the forwarded INSERT still targets the Distributed table, so every shard re-shards its own rows through the sink and the execution stays distributed.

Note that this also changes an explicitly written s3Cluster(...) / urlCluster(...) source inserting into a Distributed table that has a deterministic sharding key: it stops inserting into the shards' local tables. That is intentional — the data it produced violated the table's declared sharding key.

The new test 05219_insert_select_auto_cluster_function_distributed covers four cases against a two-shard Distributed destination: url and s3 sources with a rand() sharding key (row counts, and that every shard ran a forwarded *Cluster INSERT naming the destination cluster and that the shards together read every file exactly once), and a deterministic sharding key with parallel_distributed_insert_select set to 2 (no forwarded cluster-function query) and to 1 (the execution stays distributed). On an unfixed binary the row counts double and no forwarded query names a *Cluster function.

04492_parallel_distributed_insert_select_strips_initiator_only_settings shards its destination by rand() now: its fileCluster case exists to check that initiator-only settings are stripped from the forwarded query, which requires the forwarded query to exist.

This is built on top of #120488, whose commit the branch contains, because the rewrite hook it introduces is extended here. Once #120488 is merged into master the diff of this pull request reduces to the changes described above.

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

Fix INSERT INTO <Distributed table> SELECT ... FROM url(...) (and s3, azureBlobStorage, ...) with parallel replicas enabled inserting the data once per shard of the destination cluster: the query forwarded to the shards now names the *Cluster table function with the cluster of the Distributed table, so every shard reads only its share of the files. Such an INSERT also no longer writes into the shards' local tables when the destination has a deterministic sharding key, because the rows a cluster table function hands to a shard cannot satisfy that key and the resulting placement made optimize_skip_unused_shards return partial results; it falls back to the ordinary INSERT ... SELECT instead, which places the rows through the Distributed sink.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1391-master (included in 26.10 and later)

devcrafter and others added 4 commits September 18, 2026 18:24
…le function inserting the data once per shard

`parallel_replicas_for_cluster_engines` converts a plain `url` / `s3` / ... table function into a cluster
storage on the initiator, so `INSERT INTO <Distributed table> SELECT * FROM url(...)` takes the
`parallel_distributed_insert_select` path in `StorageDistributed::distributedWriteFromClusterStorage` and
forwards the query to every shard of the `Distributed` table's cluster. The forwarded query text still named
the plain function, and a shard running it as a secondary query created a plain storage that expanded the
globs and read every file on its own instead of taking its share of the read tasks from the initiator, so N
shards inserted the data N times.

This is the same defect that was fixed for the `ReplicatedMergeTree` and data lake destinations in
#120488; apply the same
`IStorageCluster::updateQueryToSendIfNeeded` rewrite here.

The cluster to name in the rewritten `*Cluster` function is the `Distributed` table's own cluster, because
its shards are the ones that run the forwarded query and consume the read tasks; the source's
`cluster_for_parallel_replicas` plays no part in this fan-out and need not exist on those shards. Thread the
target cluster name through `updateQueryToSendIfNeeded` instead of always injecting the source storage's own
cluster. A `remote()` / `cluster()` destination owns an ad-hoc cluster that is absent from `remote_servers`,
so there is no name a shard could resolve: skip the distributed execution and fall back to the ordinary
`INSERT ... SELECT` pipeline rather than forward a query that every shard would answer with the whole source.

Also drop the unused `dst_cluster` local and hoist the source metadata that the rewrite and the task iterator
both need.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…CT from a cluster table function

With `parallel_distributed_insert_select = 2` (the default since 25.7)
`StorageDistributed::distributedWriteFromClusterStorage` retargets the forwarded INSERT at each shard's own
local table, bypassing `DistributedSink` and therefore the sharding key. For a `Distributed` source that is
sound - the rows a shard reads from its local table are already the rows placed there - but a cluster table
function hands out files by rendezvous hashing over their paths, which has nothing to do with the
destination's sharding key. The rows then sit on arbitrary shards, and `optimize_skip_unused_shards` later
prunes shards that do hold matching rows, so the query silently returns partial results.

Take the distributed execution only when the destination's sharding key is not deterministic. A
non-deterministic key (`rand()`, ...) cannot describe where a row belongs - shard pruning is already
disabled for it - so arbitrary placement is fine and the fast path stays. A deterministic key does describe
it and a cluster table function can never satisfy it, so fall back to the ordinary `INSERT ... SELECT`,
which places the rows through `DistributedSink` while the `SELECT` still reads the source cluster in
parallel. This follows the existing contract of these paths: an inapplicable optimization falls back, it
does not throw, and the reason is logged the same way the cluster-address mismatch in
`distributedWriteBetweenDistributedTables` logs it.

`05219_insert_select_auto_cluster_function_distributed` gains two cases over a destination sharded by `x`:
with `parallel_distributed_insert_select = 2` no `*Cluster` query is forwarded at all, and with `= 1` the
execution stays distributed because the forwarded INSERT still targets the `Distributed` table and every
shard re-shards its own rows through the sink.

`04492_parallel_distributed_insert_select_strips_initiator_only_settings` shards its destination by `rand()`
now: its `fileCluster` case exists to check that initiator-only settings are stripped from the forwarded
query, which requires the forwarded query to exist.

Related: #100788

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Falling back to the ordinary `INSERT ... SELECT` because the destination's sharding key is deterministic is
a normal execution decision rather than something the user has to act on, so it does not warrant a warning.
The stateless tests run the client with `send_logs_level=warning`, so this also keeps the message off the
client's stderr and lets `05219_insert_select_auto_cluster_function_distributed` drop the
`send_logs_level = 'fatal'` it needed to silence it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [93e5fbf]

Summary: ✅


AI Review

Summary

This PR fixes the Distributed-table side of INSERT ... SELECT from url/s3-style cluster-function sources by rewriting forwarded queries to *Cluster(...) and by disabling the parallel_distributed_insert_select = 2 fast path when the destination sharding key actually constrains row placement. The new Distributed-destination coverage looks solid, but the same rewrite still keys off the raw StorageDistributed::cluster_name member, so named cluster(...) / clusterAllReplicas(...) destinations still do not pass their actual destination cluster name into the forwarded query.

Findings

⚠️ Majors

  • [src/Storages/StorageDistributed.cpp:1350] TableFunctionRemote::executeImpl still creates cluster(...) / clusterAllReplicas(...) destinations with cluster_name = '' and keeps the real destination only in owned_cluster (src/TableFunctions/TableFunctionRemote.cpp:69). distributedWriteFromClusterStorage still uses that empty member for both the bailout and updateQueryToSendIfNeeded, so INSERT INTO FUNCTION cluster('dest_cluster', db, tbl) SELECT * FROM s3Cluster('source_cluster', ...) still forwards s3Cluster('source_cluster', ...) instead of rewriting it to dest_cluster, and it will still throw CLUSTER_DOESNT_EXIST as soon as source_cluster is not configured on the workers. Plain url() / s3() sources on the same destination also needlessly fall back even though getCluster()->getName() is available there. Derive target_cluster_name from the actual destination cluster (getCluster()->getName() when the storage owns a named cluster) and only fall back once that derived name is still empty (remote('host1,host2', ...) / Remote). Please also extend 05219_insert_select_auto_cluster_function_distributed with a named cluster(...) destination case that asserts the forwarded query names the destination cluster.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Use the actual destination cluster name for named cluster(...) / clusterAllReplicas(...) destinations in distributedWriteFromClusterStorage.
    • Add a focused regression case for INSERT INTO FUNCTION cluster(...) SELECT FROM s3Cluster(...) that checks the forwarded query uses the destination cluster name.

LLVM Coverage Report

Measured on commit 93e5fbf.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 81/88 (92.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
/// altogether rather than forward a query that every shard would answer with the whole source.
const auto * source_table_function = extractTableFunctionFromSelectQuery(source_to_send);
const bool needs_cluster_function = source_table_function && !endsWith(source_table_function->name, "Cluster");
if (needs_cluster_function && cluster_name.empty())

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 bailout only handles the plain url / s3 spellings that still need rewriting. If the user writes urlCluster / s3Cluster / fileCluster explicitly, updateQueryToSendIfNeeded keeps the original first argument, but every worker still runs ITableFunctionCluster::parseArgumentsImpl before it can consume the task iterator. That means INSERT INTO <Distributed/remote/cluster> SELECT ... FROM s3Cluster('source_cluster', ...) still fails with CLUSTER_DOESNT_EXIST whenever source_cluster is not configured on the destination shards, even though that cluster name is irrelevant on this destination-driven path. This path needs the same treatment as the auto-converted case: either rewrite the first argument to the destination cluster or fall back to the ordinary INSERT ... SELECT.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ac4d4c1, by rewriting the argument as you suggest rather than by requiring the clusters to match.

Worth noting this is not a regression: before this PR the forwarded text was the user's query verbatim, so it already named the source cluster and a destination shard without it already threw. The rewrite now names the cluster the query is really sent to, in all three *Cluster implementations; it is a no-op for IStorageCluster::read and the replicated INSERT ... SELECT, where that cluster is the source storage's own.

Requiring a match would be the wrong rule here. distributedWriteBetweenDistributedTables compares cluster addresses because each shard reads its own local table — a data-locality requirement. A cluster table function has no locality: any node can read any file, and which nodes read is already decided by the destination cluster, since the task iterator is built from it. 01099_parallel_distributed_insert_select:124-139 and 03850_nested_cluster_table_function_task_iterator both deliberately pair a mismatched source cluster with a Distributed destination and assert the shortcut still happens — 01099 even stops distributed sends first and asserts the rows are visible anyway, which a fallback would break.

The new test covers an explicit s3Cluster naming a cluster other than the destination's: the forwarded queries name the destination cluster, and with the fix reverted they name the source one.

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.

TableFunctionRemote::executeImpl still builds every cluster(...) / remote(...) destination StorageDistributed with cluster_name = String{} and keeps the actual destination cluster only in owned_cluster (src/TableFunctions/TableFunctionRemote.cpp:69-85, src/Storages/StorageDistributed.h:239-243). distributedWriteFromClusterStorage still uses that raw cluster_name for both the bailout and the rewrite target (src/Storages/StorageDistributed.cpp:1348-1354), so the original issue is still present on those destinations.

For a named cluster(...) destination that means plain url() / s3() sources still bail out even though getCluster()->getName() is resolvable there, and explicit s3Cluster / urlCluster / fileCluster sources are still rewritten to *Cluster('', ...), which still reaches ITableFunctionCluster::parseArgumentsImpl as an empty name and throws CLUSTER_DOESNT_EXIST on the worker. This still needs to derive the target from getCluster()->getName() when the destination owns a named cluster, and only fall back once that derived name is still empty (remote('host1,host2', ...) / Remote).

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 93e5fbf23 with master a24f0fdd8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 320e50402; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

13 object files changed (-930.83 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/FrequencyHolder.cpp.o 1.12 MiB 207.93 KiB -943.97 KiB (-81.95%)

720 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

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

Job report

…plicitly written *Cluster source

Two gaps found in review of the distributed INSERT SELECT path from a cluster table function.

The sharding-key guard tested `isDeterministic`, which is too strict. A `dictGet` sharding key is not
deterministic across queries - the dictionary can be reloaded - but it is fixed within one and does state
where a row belongs, and `allow_nondeterministic_optimize_skip_unused_shards` exists precisely so that
reads can prune by it (see `01527_dist_sharding_key_dictGet_reload`). Such a key was therefore treated as
"describes no placement" and the shard-local fast path was taken, scattering rows against it. Test on
`isDeterministicInScopeOfQuery` instead: it still lets `rand()` through, which is not fixed even within one
query and so describes nothing, and now catches `dictGet`.

An explicitly written `s3Cluster(...)` / `urlCluster(...)` / `fileCluster(...)` source kept its own cluster
name in the forwarded query. On the destination-driven path the shards that run that query are those of the
`Distributed` table, and they reject a cluster name their own `remote_servers` does not define
(`ITableFunctionCluster::parseArgumentsImpl`) even though they never dispatch by it - they take their share
of the work from the initiator's task iterator. Replace the argument with the cluster the query is actually
sent to, the same one the auto-converted case already names. On `IStorageCluster::read` and the replicated
`INSERT ... SELECT` path this is a no-op, because there that cluster is the source storage's own.

Note that requiring the two clusters to match instead would be wrong here: unlike
`distributedWriteBetweenDistributedTables`, which compares cluster addresses because each shard reads its
own local table, a cluster table function has no such locality - any node can read any file, and which
nodes read is already decided by the destination cluster. `01099_parallel_distributed_insert_select` and
`03850_nested_cluster_table_function_task_iterator` both pair a deliberately mismatched source cluster with
a `Distributed` destination and assert the shortcut is taken.

`05219_insert_select_auto_cluster_function_distributed` covers both: a `dictGet` sharding key, where no
`*Cluster` query is forwarded, and an explicit `s3Cluster` naming a different cluster, where the forwarded
queries name the destination's cluster and not the source's.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
src_storage_cluster.updateExternalDynamicMetadataIfExists(local_context);
const auto storage_metadata = src_storage_cluster.getInMemoryMetadataPtr(local_context, false);
const auto src_snapshot = src_storage_cluster.getStorageSnapshot(storage_metadata, local_context);
src_storage_cluster.updateQueryToSendIfNeeded(source_to_send, src_snapshot, local_context, cluster_name);

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.

cluster_name.empty() is too narrow here. TableFunctionRemote::executeImpl builds every remote() / cluster() destination StorageDistributed with cluster_name_ = '', and the Remote / RemoteSecure engine does the same for its owned-cluster instances, so an explicit urlCluster / s3Cluster / fileCluster source skips this bailout and line 1508 rewrites its first argument to the empty string. The worker then reaches ITableFunctionCluster::parseArgumentsImpl and throws CLUSTER_DOESNT_EXIST before it can consume the task iterator, so queries like INSERT INTO TABLE FUNCTION cluster('test_cluster_two_shards_localhost', currentDatabase(), 't') SELECT * FROM s3Cluster('test_cluster_one_shard_three_replicas_localhost', ...) SETTINGS parallel_distributed_insert_select = 2 regress even though the destination cluster is named. I think this needs to derive the target name from the actual destination cluster (for cluster(...) that is getCluster()->getName()), and if that name is still empty (remote(...) / address-based Remote(...)) fall back for all cluster-table-function sources, not just the plain spellings. A stateless case for INSERT INTO TABLE FUNCTION cluster(...) SELECT * FROM s3Cluster(...) would lock this down.

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.

src/TableFunctions/TableFunctionRemote.cpp:69-85 still constructs every remote() / cluster() destination StorageDistributed with cluster_name_ = String{} and keeps the real destination cluster only in owned_cluster. In the current distributedWriteFromClusterStorage code, src/Storages/StorageDistributed.cpp:1341-1347 only falls back when the source is the plain url / s3 spelling, then unconditionally passes cluster_name into updateQueryToSendIfNeeded.

That means INSERT INTO FUNCTION cluster(...) SELECT * FROM s3Cluster(...) still rewrites the source to s3Cluster('', ...), and the worker will still hit CLUSTER_DOESNT_EXIST in ITableFunctionCluster::parseArgumentsImpl before it can consume the task iterator. This still needs to derive the target name from the actual destination cluster (getCluster()->getName()) when one exists, and otherwise fall back for all *Cluster sources, not only the plain spellings.

devcrafter and others added 2 commits September 21, 2026 12:21
Match the hardening `05218_insert_select_auto_cluster_function_parallel_replicas` received: give every query
a unique id rather than one derived only from the database name, and bound the `system.query_log` lookups by
`event_time` as well as `event_date`. Re-running the test against the same server no longer risks counting
the secondary queries of an earlier run. The section labels are now carried next to the query id instead of
being parsed back out of it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@devcrafter
devcrafter requested a review from azat September 21, 2026 12:50
@azat azat self-assigned this Sep 23, 2026
@devcrafter
devcrafter requested a balanced review from Copilot September 27, 2026 22:14

Copilot AI left a comment

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.

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

Review effort: Lite
Findings: 1 High severity · 2 Medium severity

Open (3)
What changed in this PR

Fixes incorrect behavior for INSERT INTO <Distributed table> SELECT ... FROM url()/s3()/... under parallel replicas by ensuring forwarded queries use the correct *Cluster functions and by disabling an unsafe optimization when the destination sharding key requires placement preservation.

Changes:

  • Rewrite forwarded distributed INSERT-SELECT source table functions to *Cluster(...) using the destination cluster name, preventing per-shard full rereads/duplication.
  • Skip the parallel_distributed_insert_select = 2 “insert into local tables” fast path when the destination sharding key is deterministic-in-scope-of-query (incl. dictGet), to avoid breaking shard pruning correctness.
  • Add/adjust stateless tests covering url/s3 sources, deterministic vs non-deterministic sharding keys, and explicit *Cluster sources.
File Description
tests/​queries/​0_stateless/​05219_insert_select_auto_cluster_function_distributed.sh New test validating forwarded query rewriting and correctness across sharding-key modes.
tests/​queries/​0_stateless/​05219_insert_select_auto_cluster_function_distributed.reference Expected output for the new 05219 test.
tests/​queries/​0_stateless/​04492_parallel_distributed_insert_select_strips_initiator_only_settings.sh Adjust test destination sharding to keep the forwarded-query assertions meaningful.
src/​Storages/​StorageURLCluster.h Extend rewrite hook API to accept a target cluster name.
src/​Storages/​StorageURLCluster.cpp Rewrite/retarget urlCluster (and friends) to the destination cluster name in forwarded queries.
src/​Storages/​StorageFileCluster.h Extend rewrite hook API to accept a target cluster name.
src/​Storages/​StorageFileCluster.cpp Retarget fileCluster cluster-name argument to the destination cluster name in forwarded queries.
src/​Storages/​StorageDistributed.h Track “deterministic in scope of query” sharding key property; allow mutating src cluster during rewrite.
src/​Storages/​StorageDistributed.cpp Implement deterministic-in-scope check + guard; rewrite source table functions to *Cluster with destination cluster name.
src/​Storages/​ObjectStorage/​StorageObjectStorageCluster.h Extend rewrite hook API to accept a target cluster name.
src/​Storages/​ObjectStorage/​StorageObjectStorageCluster.cpp Retarget already-*Cluster object storage functions to the destination cluster name in forwarded queries.
src/​Storages/​IStorageCluster.h Update rewrite hook contract to include target_cluster_name and document semantics.
src/​Storages/​IStorageCluster.cpp Pass the storage’s own cluster name when rewriting during distributed reads.
src/​Interpreters/​InterpreterInsertQuery.cpp Pass the source storage cluster name when rewriting forwarded insert-select queries into replicated destinations.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +1339 to +1347
const auto * source_table_function = extractTableFunctionFromSelectQuery(source_to_send);
const bool needs_cluster_function = source_table_function && !endsWith(source_table_function->name, "Cluster");
if (needs_cluster_function && cluster_name.empty())
return {};

src_storage_cluster.updateExternalDynamicMetadataIfExists(local_context);
const auto storage_metadata = src_storage_cluster.getInMemoryMetadataPtr(local_context, false);
const auto src_snapshot = src_storage_cluster.getStorageSnapshot(storage_metadata, local_context);
src_storage_cluster.updateQueryToSendIfNeeded(source_to_send, src_snapshot, local_context, cluster_name);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, and it reproduced: 0 rows inserted, the shards rejecting s3Cluster('') with CLUSTER_DOESNT_EXIST. Fixed in 437ac97 by your second alternative — the *Cluster storages now keep the name the user wrote when target_cluster_name is empty.

Also tried the first alternative (widening the guard to both source shapes) and backed it out: the local path then goes through DistributedSink, which refuses a multi-shard remote() with no sharding key, so this query turned into STORAGE_REQUIRES_PARAMETER where it previously inserted every row once. Regression case added to 05219.

Comment on lines 371 to 381
else
{
ASTPtr cluster_name_arg = args.front();
/// The function is already the `*Cluster` variant, so it carries a cluster name the user wrote. Replace
/// it with the cluster whose nodes will actually run the query: the two differ when the destination
/// drives the fan-out (`INSERT INTO <Distributed table> SELECT`), and the nodes reject a name their
/// own `remote_servers` does not define (`ITableFunctionCluster::parseArgumentsImpl`) even though they
/// never dispatch by it - they take their share of the work from the initiator's task iterator.
args.erase(args.begin());
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);
args.insert(args.begin(), cluster_name_arg);
args.insert(args.begin(), make_intrusive<ASTLiteral>(target_cluster_name));
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already handled — args.empty() is checked earlier in this same function, before the settings extraction and this erase:

if (args.empty())
    throw Exception(ErrorCodes::LOGICAL_ERROR,
        "Unexpected empty list of arguments for {}Cluster table function", configuration->getEngineName());

That predates this PR (399414b), so no change needed here. The equivalent check was missing in StorageURLCluster and was added in 93e5fbf.

Comment thread src/Storages/StorageURLCluster.cpp Resolved
args.erase(args.begin());
configuration->addStructureAndFormatToArgsIfNeeded(args, structure, configuration->format, context, /*with_structure=*/true);
args.insert(args.begin(), cluster_name_arg);
args.insert(args.begin(), make_intrusive<ASTLiteral>(target_cluster_name));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This cluster won't be used anywhere right? Maybe we should not pretend that it will in the source code otherwise it create confusion for reader. And i.e. just replace with empty string here, and remove this check for SECONDARY_QUERY

if (!context->tryGetCluster(cluster_name))
throw Exception(ErrorCodes::CLUSTER_DOESNT_EXIST, "Requested cluster '{}' not found", cluster_name);

And we can remove additional args and so on

Copy link
Copy Markdown
Member 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 receiving node never uses it: on a secondary query every *Cluster table function builds the plain storage with distributed_processing = true (TableFunctionObjectStorageCluster.cpp, TableFunctionURLCluster.cpp, TableFunctionFileCluster.cpp) and takes its share from the initiator's task iterator, so the name is only validated and then discarded there.

I tried the empty string and backed it out: the forwarded query then reads s3Cluster('', ...) in each shard's query_log, which loses the one thing that tells you which cluster the function belongs to when reading logs. Passing the destination's cluster keeps the forwarded query self-describing.

Dropping the existence check for secondary queries would make the empty name workable, but that check is older than this path and is entangled with remote('host', xxxCluster('host_only_cluster', ...)), where the cluster legitimately exists only on the remote host - a separate problem with its own fix. I would rather not change shared table-function validation from here.

The comments are shortened, and they now say plainly that the nodes resolve the name but do not dispatch by it.

@azat azat Oct 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping the existence check for secondary queries would make the empty name workable, but that check is older than this path and is entangled with remote('host', xxxCluster('host_only_cluster', ...)),

We can allow it only for secondary_query, but anyway up to you.

but that check is older than this path and is entangled with

I don't understand what this means

Comment thread src/Storages/StorageDistributed.cpp Outdated
Comment on lines +1293 to +1307
/// With `parallel_distributed_insert_select = 2` the forwarded INSERT was retargeted at the shard's own
/// local table just above, so a row stays on whichever shard happened to read it. For a `Distributed`
/// source that is sound — the rows a shard reads are already the rows placed there — but a cluster table
/// function hands out files by rendezvous hashing over their paths, which has nothing to do with the
/// destination's sharding key. A sharding key that is fixed within a query states where a row must live,
/// and `optimize_skip_unused_shards` later prunes shards by it, so scattering rows against it would
/// silently produce wrong results. Skip the distributed execution and let the ordinary
/// `INSERT ... SELECT` place the rows through `DistributedSink`; the `SELECT` still reads the source
/// cluster in parallel.
///
/// The check is `isDeterministicInScopeOfQuery` rather than `isDeterministic` on purpose: a `dictGet`
/// sharding key is not deterministic across queries, yet it does state where a row belongs and
/// `allow_nondeterministic_optimize_skip_unused_shards` lets reads prune by it. Only a key that is not
/// even fixed within one query (`rand()`) describes no placement at all, and for those the fast path
/// stays.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is too much, I think it is enough to tell that it is for *Cluster

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut to three lines, keeping only the *Cluster-specific reason. The isDeterministicInScopeOfQuery rationale is dropped - the variable name and the LOG_INFO below already say it.

getStorageID().getNameForLogs(),
src_storage_cluster.getName(),
sharding_key_column_name);
return {};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option is to fallback to INSERT INTO dist_table, i.e spawn on each node this query instead of INSERT INTO local_table, that will be correct, but yes, it will increase amount of queries/parts, so probably does not make sense at least w/o separate setting, and not in scope of this PR

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is what parallel_distributed_insert_select = 1 already does. The guard only trips for = 2, which retargets the forwarded INSERT at the shard's own local table; with = 1 the forwarded INSERT still targets the Distributed table, so each shard re-shards its own rows and the fan-out is kept. 05219 asserts both.

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

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still find some comments too verbose, but it is up to you to decide does it make sense to trim

Comment thread src/Storages/IStorageCluster.h Outdated
Comment on lines +65 to +66
/// An empty `target_cluster_name` means the caller has no name to give (an ad-hoc `remote()` / `cluster()`
/// destination). A function the user already wrote as `*Cluster` then keeps the name it carries, which is

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better to explain what 'ad-hoc' means, 'INSERT INTO function cluster(x)' over 'INSERT INTO dist' (personally I was strugle to understand)

@devcrafter devcrafter Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ad-hoc here means not a defined cluster aka 127.0.0.{1,2}. I'll try to make the comment clear

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced "ad-hoc" with the query shape it stands for: a destination written as INSERT INTO FUNCTION remote('127.0.0.{1,2}', db, tbl) SELECT ... rather than INSERT INTO <Distributed table> SELECT ..., whose cluster is built from the address expression and has no name anywhere. Also moved the general meaning of target_cluster_name ahead of the empty-name case.

@devcrafter
devcrafter enabled auto-merge October 2, 2026 22:45
@devcrafter
devcrafter added this pull request to the merge queue Oct 3, 2026
Merged via the queue into master with commit f86ca42 Oct 3, 2026
149 checks passed
@devcrafter
devcrafter deleted the fix-insert-select-distributed-auto-cluster-function branch October 3, 2026 05:04
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 3, 2026
devcrafter added a commit that referenced this pull request Oct 24, 2026
…`INSERT ... SELECT`

Passing `'auto'` through the structure and format helper still rewrote the
arguments: it overwrote an explicit `structure = '...'` key-value argument
with `'auto'`, so a node could infer a different type than the query gave.
Skip the helper on the `INSERT ... SELECT` paths instead: only the rename to
the `*Cluster` variant and the cluster name argument are applied, and the
other arguments reach the nodes as written, as before #120488.

Add type-sensitive test cases for an explicit structure, positional and as a
key-value argument.

Related: #120488
Related: #121070

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Oct 26, 2026
…er functions

The forwarded `INSERT ... SELECT` used to carry the names-and-types structure
of the source storage instead of `'auto'`, so the nodes did not take the
structure from the insertion table and filled fields missing in the files
with the default values of their types instead of the `DEFAULT` expressions
of the destination table.

Related: ClickHouse#120488
Related: ClickHouse#121070

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
devcrafter added a commit that referenced this pull request Oct 26, 2026
Resolve conflicts for 26.9, which lacks
#121070: keep the
`updateQueryToSendIfNeeded` signature without `target_cluster_name` and add
only the `add_structure_and_format` argument. Drop the change to
`StorageDistributed::distributedWriteFromClusterStorage`, which does not
rewrite the source on 26.9.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
devcrafter added a commit that referenced this pull request Oct 26, 2026
`INSERT INTO <Distributed table> SELECT FROM s3(...)` with parallel replicas
inserts the data once per shard on 26.9, which lacks
#121070.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Oct 29, 2026
`INSERT INTO FUNCTION remote(...) SELECT * FROM url(...)` with
`parallel_replicas_for_cluster_engines` used to insert the rows once per
destination shard. It was fixed by
ClickHouse#121070, but its test does
not cover a plain source into a `remote(...)` destination.

Closes: ClickHouse#121347

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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-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.

5 participants