Repository navigation
Fix INSERT INTO <Distributed table> SELECT FROM url()/s3() with parallel replicas: duplicated data and bypassed sharding key - #121070
Conversation
…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]>
…istributed-auto-cluster-function
|
Workflow [PR], commit [93e5fbf] Summary: ✅
AI ReviewSummaryThis PR fixes the Findings
Final Verdict
LLVM Coverage ReportMeasured on commit 93e5fbf.
Changed lines: Changed C/C++ lines covered: 81/88 (92.05%) · Uncovered code |
| /// 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()) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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.
…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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…istributed-auto-cluster-function
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]>
There was a problem hiding this comment.
Note
Copilot was unable to run its full agentic suite in this review.
Copilot review overview
Review effort: Lite
Findings: 1
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
*Clustersources.
| 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.
| 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); |
There was a problem hiding this comment.
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.
| 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)); | ||
| } |
There was a problem hiding this comment.
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.
| 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)); |
There was a problem hiding this comment.
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
ClickHouse/src/TableFunctions/ITableFunctionCluster.h
Lines 74 to 75 in b588744
And we can remove additional args and so on
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| /// 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. |
There was a problem hiding this comment.
This comment is too much, I think it is enough to tell that it is for *Cluster
There was a problem hiding this comment.
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 {}; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
azat
left a comment
There was a problem hiding this comment.
I still find some comments too verbose, but it is up to you to decide does it make sense to trim
| /// 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 |
There was a problem hiding this comment.
Better to explain what 'ad-hoc' means, 'INSERT INTO function cluster(x)' over 'INSERT INTO dist' (personally I was strugle to understand)
There was a problem hiding this comment.
ad-hoc here means not a defined cluster aka 127.0.0.{1,2}. I'll try to make the comment clear
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…`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]>
…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]>
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]>
`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]>
`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]>


Related: #120488
Related: #120485
Related: #100788
INSERT INTO <Distributed table> SELECT ... FROM url(...)(ors3(...),azureBlobStorage(...), ...) with parallel replicas enabled goes throughStorageDistributed::distributedWriteFromClusterStorage, which forwards the query text to every shard of theDistributedtable'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_enginesconverts 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 forSECONDARY_QUERY, and the plain table function hardcodesdistributed_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 theReplicatedMergeTreeand data lake destinations, and it is fixed the same way:IStorageCluster::updateQueryToSendIfNeededrewrites the source into its*Clustervariant before the query is serialized.The cluster named in the rewritten function is the
Distributedtable's own cluster, because its shards are the ones that run the forwarded query and consume the read tasks; the source'scluster_for_parallel_replicasplays no part in this fan-out and need not even exist on those shards. The target cluster name is therefore passed toupdateQueryToSendIfNeededinstead of always being the source storage's own cluster. Aremote()/cluster()destination owns an ad-hoc cluster that is absent fromremote_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, bypassingDistributedSinkand therefore the sharding key. For aDistributedsource 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, andoptimize_skip_unused_shardsthen 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 ordinaryINSERT ... SELECT, which places the rows throughDistributedSinkwhile theSELECTstill 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 = 1nothing changes: the forwarded INSERT still targets theDistributedtable, 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 aDistributedtable 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_distributedcovers four cases against a two-shardDistributeddestination:urlands3sources with arand()sharding key (row counts, and that every shard ran a forwarded*ClusterINSERT naming the destination cluster and that the shards together read every file exactly once), and a deterministic sharding key withparallel_distributed_insert_selectset to2(no forwarded cluster-function query) and to1(the execution stays distributed). On an unfixed binary the row counts double and no forwarded query names a*Clusterfunction.04492_parallel_distributed_insert_select_strips_initiator_only_settingsshards its destination byrand()now: itsfileClustercase 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
masterthe diff of this pull request reduces to the changes described above.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
INSERT INTO <Distributed table> SELECT ... FROM url(...)(ands3,azureBlobStorage, ...) with parallel replicas enabled inserting the data once per shard of the destination cluster: the query forwarded to the shards now names the*Clustertable function with the cluster of theDistributedtable, so every shard reads only its share of the files. Such anINSERTalso 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 madeoptimize_skip_unused_shardsreturn partial results; it falls back to the ordinaryINSERT ... SELECTinstead, which places the rows through theDistributedsink.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121070]
Version info
26.10.1.1391-master(included in26.10and later)