Skip to content

Fix INSERT ... SELECT FROM url()/s3() with parallel replicas inserting the data once per replica - #120488

Merged
devcrafter merged 10 commits into
masterfrom
fix-insert-select-auto-cluster-parallel-replicas
Sep 21, 2026
Merged

devcrafter merged 10 commits into
masterfrom
fix-insert-select-auto-cluster-parallel-replicas

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 16, 2026 •

Copy link
Copy Markdown
Member

Closes: #120485
Related: #100146
Related: ClickHouse/ClickBench#2046

With parallel replicas enabled, parallel_replicas_for_cluster_engines converts a plain url / s3 / ... table function into a cluster storage on the initiator, so INSERT INTO <replicated table> SELECT * FROM url(...) takes the distributed parallel_distributed_insert_select path and forwards the query to every replica of the cluster. The forwarded query text still named the plain function, and a replica 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 replicas inserted the data N times. This is what broke the ClickBench load for 2- and 3-replica services after 26.6.

IStorageCluster::read already rewrites the source for a plain SELECT via updateQueryToSendIfNeeded (the function becomes its *Cluster variant with the cluster name argument, and the structure and format arguments are added). This PR applies the same rewrite to the forwarded query in InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage, and makes updateQueryToSendIfNeeded public for that.

url with a non-HTTP scheme (url('s3://...'), url('az://...'), url('hdfs://...')) is delegated to another table function while the query text keeps the surface name url, so the same rewrite produced urlCluster('s3://...') - a shape urlCluster rejects, and with the argument grammar of the delegate rather than of url. That was already the behaviour of a plain SELECT. Scheme dispatch is now resolved on the node that received the query: the delegate runs with parallel_replicas_for_cluster_engines turned off and builds its plain storage. tests/integration/test_s3_style_link::test_url_s3_scheme_with_parallel_replicas covers it.

The scope here is the source cluster storage of the forwarded query. The sibling Distributed-destination path, StorageDistributed::distributedWriteFromClusterStorage, needs the same rewrite and is fixed separately in #121070.

The new test 05218_insert_select_auto_cluster_function_parallel_replicas inserts three files of 10, 20 and 30 rows through url and through s3 with test_cluster_one_shard_three_replicas_localhost as the parallel replicas cluster, and checks the row count, that every replica ran the forwarded INSERT, that the forwarded query names the *Cluster function, and that the replicas together read every file exactly once. On an unfixed binary it reports 180 rows instead of 60, 0 cluster-function queries and 180 rows read by the replicas.

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 <replicated table> SELECT ... FROM url(...) (and s3, azureBlobStorage, ... ) with parallel replicas enabled inserting the data once per replica: the query forwarded to the replicas now names the *Cluster table function, so every replica reads only its share of the files. Closes #120485.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.326-master (included in 26.10 and later)
  • Backported to: 26.9.1.1624, 26.8.11.31, 26.7.14.28

…nction inserting the data once per replica

With parallel replicas enabled, `parallel_replicas_for_cluster_engines` converts a plain
`url` / `s3` / ... table function into a cluster storage on the initiator, so
`INSERT INTO <replicated table> SELECT * FROM url(...)` takes the distributed
`parallel_distributed_insert_select` path and forwards the query to every replica of the
cluster. The forwarded query text still named the plain function, and a replica 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 replicas
inserted the data N times.

`IStorageCluster::read` already rewrites the source for a plain `SELECT` via
`updateQueryToSendIfNeeded` (the function becomes its `*Cluster` variant with the cluster
name argument). Apply the same rewrite to the forwarded query in
`InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage`.

Closes: #120485

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b98fbce]

Summary: ✅


AI Review

Summary

This PR fixes the forwarded-query rewrite for INSERT ... SELECT from auto-converted cluster table functions and disables cluster fan-out for scheme-dispatched url delegates such as url('s3://...'). The core code changes look coherent, but one important proof gap remains: the delegated url('s3://...') regression still does not exercise the distributed INSERT ... SELECT shape that the PR claims to fix.

Findings

⚠️ Majors

  • [tests/integration/test_s3_style_link/test.py:182] The new delegated-url regression creates a plain MergeTree, so parallel_distributed_insert_select = 2 never reaches InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage. The test therefore proves only the local fallback after TableFunctionURL::executeImpl disables parallel_replicas_for_cluster_engines, not the distributed INSERT ... SELECT contract described in the PR. Suggested fix: add a regression with a replicated/DataLake destination, or extend an existing stateless test, so url('s3://...') is covered on the distributed insert path as well.
Final Verdict

Request changes until the delegated url('s3://...') distributed INSERT ... SELECT path is covered by a regression test.

LLVM Coverage Report

Measured on commit b98fbce.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.80% 80.80% +0.00%

Changed lines: Changed C/C++ lines covered: 35/36 (97.22%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). labels Sep 16, 2026
@devcrafter devcrafter self-assigned this Sep 17, 2026
@devcrafter
devcrafter requested a balanced review from Copilot September 18, 2026 12:43

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.

Pull request overview

Fixes parallel-replicas INSERT ... SELECT FROM url()/s3() duplicating reads/inserts across replicas by rewriting the forwarded query to use *Cluster table functions (matching the existing SELECT rewrite path), and adds a stateless regression test to validate correct distribution and reads.

Changes:

  • Make IStorageCluster::updateQueryToSendIfNeeded publicly callable so InterpreterInsertQuery can reuse the existing rewrite logic.
  • Rewrite the forwarded INSERT ... SELECT query text to use the *Cluster table function and include explicit structure/format args where needed.
  • Add a stateless test that validates row counts, forwarded query shape, and per-replica read distribution for url() and s3().

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
tests/queries/0_stateless/05218_insert_select_auto_cluster_function_parallel_replicas.sh Adds regression test covering url()/s3() distributed insert behavior with parallel replicas.
tests/queries/0_stateless/05218_insert_select_auto_cluster_function_parallel_replicas.reference Adds expected output for the new regression test.
src/Storages/IStorageCluster.h Exposes updateQueryToSendIfNeeded publicly to reuse rewrite logic outside read().
src/Interpreters/InterpreterInsertQuery.cpp Applies the cluster-function rewrite to the forwarded distributed INSERT ... SELECT query.

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

alexey-milovidov and others added 2 commits September 20, 2026 08:24
…ent run

The test used `query_id`s that only varied with the database name and then looked
the secondary queries up in `system.query_log` with an `event_date >= yesterday()`
window. A re-run against the same server within that window could pick up the
secondary `INSERT` rows of an earlier run, inflating `replicas`,
`cluster_function_queries` and `rows_read_by_replicas`.

The `query_id`s now carry a per-run unique suffix and both log lookups are bounded
by `event_time >= now() - INTERVAL 10 MINUTE`.

The forwarded-query assertion also matched a loose, case-sensitive `%Cluster(%`.
It now checks the exact expected function of each section - `urlCluster` and
`s3Cluster` - case-insensitively.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed: merged master (the branch was 540 commits behind, clean merge) and addressed the remaining AI-review action item.

AI review, major 1 — StorageDistributed::distributedWriteFromClusterStorage. Confirmed and fixed in a separate pull request: #121070. It applies the same updateExternalDynamicMetadataIfExists + getStorageSnapshot + updateQueryToSendIfNeeded rewrite on the Distributed destination path, naming the cluster of the Distributed table. Out of scope here; this pull request fixes the source-cluster forwarding path only.

AI review, major 2 — query log isolation. Addressed in ac81f765: the query_ids of 05218_insert_select_auto_cluster_function_parallel_replicas.sh now carry a per-run unique suffix, and both system.query_log lookups are additionally bounded by event_time >= now() - INTERVAL 10 MINUTE, so a re-run against the same server cannot pick up the secondary queries of an earlier run. The forwarded-query assertion also no longer uses the loose case-sensitive %Cluster(% pattern: it now checks the exact expected function of each section, urlCluster and s3Cluster, case-insensitively.

CI failures on 3ac0adba — all unrelated to this change (it only touches the distributed INSERT ... SELECT forwarding path):

@groeneai, investigate the performance failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=120488&sha=3ac0adba968efdf04b768ba39c687690be44e86c&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%206%2F6%29 and provide a fix in a separate pull request. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Performance Comparison (arm_release, master_head, 6/6) at 3ac0adba968e

The gate that reds the shard is #120927's dashboard verdict, and its two blocking rows are timeseries_to_grid_aggregation_functions #1 (0.0639 -> 0.1083 s, +69.4%) and #21 (0.2138 -> 0.2555 s, +19.4%).

Both sides of that run read the identical physical layout (SelectedParts 4, SelectedMarks 489, SelectedRows 4000000), ran identical thread counts (LocalThreadPoolJobs 16, ConcurrencyControlSlotsAcquired 11) and spent identical system time (209 ms vs 206 ms). The only thing that differs is user CPU, and it differs as a constant rather than a ratio: of the ten queries this shard sampled, eight pay between +361 ms and +545 ms of extra user CPU on the candidate side regardless of what they cost to begin with (#1 186 -> 732 ms, #24 540 -> 901 ms), and two pay nothing (#29 +3 ms, and #31, the most expensive of the file at 3560 ms, -21 ms). In wall clock that constant is +29 to +44 ms per query, which reads as +69% on the 64 ms query and +15% on the 280 ms one.

Which of the two servers pays it is decided per run, not by the build:

  • On MasterCI, where neither side is this branch, 74 of the 604 arm_release runs of this test in the last 14 days have the candidate side at least 25 ms slower on the file's median query, and 71 have the baseline side at least 25 ms slower.
  • The same pair of binaries flips sign between runs. 0bd48741e3 -> ff2f597d43 measured +24.9 ms on one runner and -34.7 ms on another; 6b8954cd0f -> 750c61fdb6 measured -47.8 ms and then +0.7 ms.

So this is neither your change nor a timeSeries*ToGrid regression: the same binary measures both fast and slow. Within a single run, though, each side's samples are tight, so both judges agree, and #121090 (which requires the dashboard's query to also be slower in the shard's own report) leaves this shard red. I am investigating the measurement itself at full effort and will post the pull request here.

One correction to the triage above: the 5/6 red is a different failure, with no timeseries query involved. Its "10 errors" is a single Python traceback counted line by line, from iceberg_suite_tpch.query4.run0 hitting the harness max_query_seconds at elapsed 15167.068 ms, maximum: 15000.000 ms (Code 159), the same shape as #119215. A fix task owns that one and its pull request link will follow here too.

@groeneai

Copy link
Copy Markdown
Collaborator

Correction to my last paragraph: the 5/6 red already has a merged fixing PR, and nothing is owed on it.

iceberg_suite_tpch.query4 is a 351 ms query on that shard (14-day p50; p95 360 ms, max 409 ms over 662 samples, zero runs above 15 s) that started exceeding 15 s on 2026-09-17 23:00Z. The Code: 159 is the messenger for the planner regression reverted by #120923, not a fixture that outgrew the cap. Its merge commit 0b3b89d0 is not an ancestor of 3ac0adba (diverged, 3 behind), so that run measured the regression, but it is an ancestor of your current ac81f765 (542 ahead, 0 behind), so the master merge you pushed already picks it up and the 5/6 red should not reproduce. If #121075 re-lands it, the red returns with it: that branch reproduces the same 10 errors on 5/6 at 01:36Z.

Only the 6/6 measurement is still open on my side.

@clickhouse-gh

clickhouse-gh Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b98fbceda with master e0b84a678 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 18580d454; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator

The pull request for the 6/6 measurement: #121189.

The cause sits upstream of both judges I described. Select historical data fetches the learned per-query thresholds from play.clickhouse.com with a hardcoded 10 s read timeout, and that query takes 8 to 10 s in CI. On a timeout the step writes an empty historical-thresholds.tsv and reports success; compare.sh LEFT JOINs that file with join_use_nulls=0, so a join miss is 0 and greatest(0.15, 0, 0) is 0.15. An absent history therefore reads exactly like a rock-steady query, and the whole shard is judged on the bare 0.15/0.25 floors. 18 of 40 sampled master runs of arm_release master_head 6/6 were judged that way, and the only trace was one WARNING line in an 80 MB job log.

That accounts for the entire report red at 3ac0adba: replaying compare.sh's rule over the shard's 574 client_time rows gives 4 blocking rows with the shipped thresholds, exactly the four reported errors, and 0 once the learned thresholds are restored. Query #1 measured 0.694 against a learned bar of 1.20.

So the constant user-CPU offset I measured earlier is unchanged and still not your change; the learned thresholds are what used to absorb it. #121189 moves the timeout to the constant praktika's own CIDB reader already uses and makes both fail-open branches say so on the report instead of only in the log. #121090 is still needed for the dashboard half of the gate.

alexey-milovidov and others added 2 commits September 20, 2026 16:56
`url('s3://...')`, `url('az://...')` and `url('hdfs://...')` are delegated to
the matching object-storage table function, but the query AST still carries the
surface name `url`. When `parallel_replicas_for_cluster_engines` made the
delegate build its `*Cluster` storage,
`StorageObjectStorageCluster::updateQueryToSendIfNeeded` derived the forwarded
function name from that surface name and sent
`urlCluster('parallel_replicas', 's3://...', ...)` to the replicas - a shape
`TableFunctionURL::parseArgumentsImpl` rejects for every non-HTTP scheme, and
carrying the argument grammar of the delegate rather than of `url`.

Reproduced on a local server with `url_scheme_mappers` pointing `s3://` at
MinIO: both `SELECT count() FROM url('s3://test/x.csv', 'CSV', 'a UInt32')` and
`INSERT INTO t SELECT * FROM url('s3://test/x.csv', ...)` failed with
`BAD_ARGUMENTS: The urlCluster table function does not support the 'S3' scheme`.

Scheme dispatch is now resolved on the node that received the query: the
delegate is executed with `parallel_replicas_for_cluster_engines` turned off, so
it builds its plain storage. A plain `http(s)` `url` is untouched and still
forwards `urlCluster(...)` to the replicas.

Adds `test_url_s3_scheme_with_parallel_replicas` to
`tests/integration/test_s3_style_link`, covering both the `SELECT` and the
distributed `INSERT ... SELECT` shapes, and documents the limitation next to the
existing `urlCluster` note.

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

mintlify Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 21, 2026, 2:04 AM

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 21, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 21, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 21, 2026
Backport #120488 to 26.9: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you — that closes out the 1/6 red exactly the way it closed out 6/6, and nothing is owed on my side for it. The all-query-metrics.tsv evidence is the decisive part: one (0.15, 0.25) pair across all 185121 rows of the shard, and the same on the other five arm shards of 21b1698e86a1, so the run was judged on the bare floors rather than on the learned bars of 0.56 / 0.44 / 0.65. Measured against their own bars none of the three queries is a change, which matches the reasoning I gave when I flagged them: none of optimize_time_filter_with_preimage, serialization_pool_lookup or order_by_read_in_order has this PR's code on its path.

The serialization_pool_lookup #0 detail is a fair correction — it is shard 2/6's row and 2/6 is green, so only the two rows the dashboard confirmed were ever gating. Noted for the triage.

#121189 and #121090 are noted, including that neither clears 1/6 on its own.

For the record on this PR: it merged as 295f03a. The one review thread that was still open at merge — the MergeTree destination in test_s3_style_link::test_url_s3_scheme_with_parallel_replicas not reaching distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage — was a valid observation and is fixed in the follow-up #121369, which makes that destination a ReplicatedMergeTree (4/4 PASS locally).

PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #120488 to 26.8: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #120488 to 26.7: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
PedroTadim added a commit that referenced this pull request Sep 23, 2026
Cherry pick #120488 to 26.3: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
…ith parallel replicas inserting the data once per replica
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
…ith parallel replicas inserting the data once per replica
robot-clickhouse added a commit that referenced this pull request Sep 23, 2026
…ith parallel replicas inserting the data once per replica
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 23, 2026
PedroTadim added a commit that referenced this pull request Sep 24, 2026
Backport #120488 to 26.7: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
PedroTadim added a commit that referenced this pull request Sep 24, 2026
Backport #120488 to 26.8: Fix `INSERT ... SELECT FROM url()`/`s3()` with parallel replicas inserting the data once per replica
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
…`/`s3()` with parallel replicas inserting the data once per replica
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 3, 2026
… a replicated destination

Follow-up to ClickHouse#120488.

`test_url_s3_scheme_with_parallel_replicas` created its `INSERT ... SELECT`
destination as a plain `MergeTree`.
`InterpreterInsertQuery::distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage`
returns early unless the destination supports replication, so the
`parallel_distributed_insert_select = 2` half of the test never got as far as
looking at the source storage: it only exercised the local fallback and would
have passed just the same before the fix.

Create the destination as a `ReplicatedMergeTree` (and give the instance a
ZooKeeper) so the distributed path is entered for real. It then declines the
query solely because `TableFunctionURL::executeImpl` runs the delegate with
`parallel_replicas_for_cluster_engines` turned off and the delegated
`url('s3://...')` therefore resolves to a plain storage rather than to an
`IStorageCluster` - which is the property under test. Should the delegate ever
fan out again, the forwarded query would name `urlCluster('s3://...')` and every
replica would read the whole file, and the row count now catches that.

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

This branch was successfully deployed

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

Labels

comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

INSERT ... SELECT FROM url()/s3() with parallel replicas inserts the data once per replica (since 26.6)

7 participants