Skip to content

Only distribute an INSERT SELECT across replicas when the target table replicates - #120775

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-pr-insert-select-non-replicated-target
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-pr-insert-select-non-replicated-target

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #120714
Closes: #121169

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

Fixed INSERT ... SELECT with parallel replicas running once per replica when the target table is neither a replicated MergeTree nor a remote Iceberg table, so each replica wrote its own share to the same destination. A plain S3, Azure or HDFS target silently kept only the last replica's share; a Delta Lake target failed with commit conflict (DELTA_KERNEL_ERROR) and lost the whole insert. The write is now also kept on the initiator when the target has a dependent materialized view, whose rows would otherwise be split across replicas, and for a MergeTree target with insert_deduplication_token or insert_quorum without insert_quorum_parallel, where the replicas' writes dropped or failed each other. The same applies when the SELECT reads a cluster table function such as s3Cluster. A remote Iceberg table keeps the distributed write, since its sink retries a conflicting commit. Reading still uses parallel replicas. Closes #120714. Closes #121169.

Description

With parallel replicas, INSERT INTO <non-replicated target> SELECT ... ran on every replica. Delta Lake (#120714): the per-replica commits race for one log version. Plain object storage (#121169): the last PutObject to the shared key wins, so rows go missing silently.

Root cause: the only target test in buildInsertSelectPipelineParallelReplicas, storage->isMergeTree() && !storage->supportsReplication(), rejected only StorageMergeTree. This flips it into an allowlist shared with the cluster-table-function fan-out: a concrete replicated MergeTree or remote Iceberg target with no dependent view keeps the distributed write; everything else writes once on the initiator. Each node numbers its blocks from zero, so with a deduplication token their blocks collide (three nodes: up to 2/3 of rows dropped, no error), and a sequential quorum fails with code 286 after partial commits. The cluster-source path no longer admits Delta Lake.

Blast radius: Distributed, Buffer, materialized view, Delta Lake and local or catalog-backed Iceberg targets, replicated ones with a dependent view or behind an Alias, and the two settings above keep correct results but lose the write-side fan-out.

Validation: 05230, 05238_dependent_view, 05239 and test_insert_select_colliding_write_settings, red before the fix; 05238_lazy_target, 03394_pr_insert_select and the IcebergS3 arm of 05230 assert the kept fan-out. Master's 05406, 05433 and test_insert_select_time_series_independent_uuids now use a replicated target instead of Memory/Null.


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

…icates

buildInsertSelectPipelineParallelReplicas ships the whole INSERT ... SELECT to
every replica, and each replica then runs a full INSERT over the rows its own
coordinated read produced. That adds up to one logical INSERT only when the
per-replica writes converge into one table, which replication does for a
MergeTree.

Its only target-storage test was a denylist of exactly one storage:

    if (auto storage = getTable(query); storage->isMergeTree() && !storage->supportsReplication())
        return {};

Being a conjunction on isMergeTree(), it rejected only StorageMergeTree: every
storage whose isMergeTree() is false was admitted, and supportsReplication() was
never consulted. A Delta Lake target therefore got one WriteTransaction per
replica, each with its read version pinned at sink construction, all committing
the same log version. The object-store CAS rejects the losers, delta-kernel-rs
has no retry anywhere in the Delta write path, and the losing sink deletes its
own data files before rethrowing, so the client saw

    Code: 742. DB::Exception: Received DeltaLake kernel error GenericError:
    Generic delta kernel error: commit conflict at version 1 (in commit).

while the table kept a spurious extra commit and either all of the rows or none
of them, depending on which replica lost. Measured deterministically, 3/3 runs
per shape. A File target hit the same fan-out as Code: 159 Lock timeout
exceeded; Memory, Log and plain object storage keep the rows on whichever
replica wrote them.

Flip that denylist into the allowlist the invariant demands, and use the
already-resolved table parameter instead of a second getTable(query), which
re-executes the table function for INSERT INTO FUNCTION. Excluded targets fall
through to buildInsertSelectPipeline, which keeps parallel replicas for reading
and runs the sink once on the initiator. Every pre-existing test that asserts
this path's row or execution counts uses a ReplicatedMergeTree target, and
03394_pr_insert_select still asserts its four INSERT executions;
02981_insert_select_resize_to_max_insert_threads case 3 reaches it with a
Distributed target and its sink count is unchanged, measured on both binaries.
So this restores the feature's own scope rather than inventing one.

The setting's own documentation described a source requirement only, so it
gains one clause for the target.

The regression test asserts both halves of the contract: one commit and one
INSERT execution for one INSERT, and ParallelReplicasUsedCount > 0 on the
initiator, so that disabling parallel replicas outright cannot pass it.

The structurally identical fan-out for a *Cluster source in
distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage admits data
lakes deliberately and is left unchanged; the disposition is put to its owners
in the pull request.

Closes: ClickHouse#120714

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 gate finding in the full pass,
0 in the delta recheck, plus my own cold review of the resulting code; bounded: 1 full pass +
1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test passes even when the read silently falls back to one replica, so it did not prove the half of the contract that says reading stays distributed; on about a quarter of CI runs automatic_parallel_replicas_mode = 2 is drawn and turns enable_parallel_replicas off (tests/clickhouse-test:1852, InterpreterSelectQueryAnalyzer.cpp:145-159). Raised independently by the gate and by my own review. AGREE, fixed @ aaf0a91 The test pins automatic_parallel_replicas_mode = 0 at query level and asserts ParallelReplicasUsedCount > 0 on the initiator's row. Proven live rather than argued: with parallel replicas switched off the four earlier oracles still print their reference values and only the new one reddens; with the p=0.25 draw injected the test passes, and with the pin deleted it reddens.
2 ⚠️ One pre-existing test does assert this path's shape with a non-replicated target, so the claim that none did was false and that shape had not been run: 02981_insert_select_resize_to_max_insert_threads case 3 runs EXPLAIN PIPELINE INSERT INTO t3_dist SELECT * FROM t4_pr with three parallel replicas and asserts a sink count, and t3_dist is Distributed. AGREE, fixed @ aaf0a91 Ran it on both binaries: 8 / 8 / 8, [ OK ] on each, because both pipelines build max_insert_threads sinks. Neither that test nor its .reference was touched, and the claim is now the measured statement. The behaviour change for such targets is stated in the description.
3 💡 parallel_distributed_insert_select's own documentation stated a source requirement only, while this change makes the target requirement stricter. AGREE, fixed @ aaf0a91 One clause appended to that sentence. No SettingsChangesHistory entry is owed: no default value changes.
4 💡 In this file, "replication merges those independent writes" reads as MergeTree merges. AGREE, fixed @ aaf0a91 Second line reworded to state the property as visibility. The comment stays: it justifies a non-obvious domain property rather than describing the fix.
5 💡 The allowlist tests the direct target only, so an admitted replicated target whose dependent materialized view inner table is not replicated still fans out; buildInsertPipeline's own comment gives dependent views as the reason parallel replicas are disabled for plain INSERTs. AGREE, not fixed here Pre-existing, and not observable on a rig where all replicas are one process, so I have no measurement to offer. Walking dependent views before admitting a target is a design call for the path owners, so it is noted here rather than guessed at in this change.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260918-092900

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. INSERT INTO <DeltaLakeLocal> SELECT from a 3-part MergeTree with enable_parallel_replicas=1, max_parallel_replicas=3, cluster_for_parallel_replicas='test_cluster_one_shard_three_replicas_localhost', parallel_distributed_insert_select=2 fails 3/3 runs per shape on 01b8f1c9fb2e1: Code: 742 ... commit conflict at version N (in commit). No timing dependence.
b Root cause explained? The only target-storage test in buildInsertSelectPipelineParallelReplicas was a denylist of one storage, storage->isMergeTree() && !storage->supportsReplication(). As a conjunction on isMergeTree() it rejects only StorageMergeTree, so every storage with isMergeTree() == false is admitted and supportsReplication() is never consulted. Each replica then opens its own Delta transaction with the read version pinned at sink construction, all commit the same log version, delta-kernel-rs has no retry, and the losing sink deletes its own data files.
c Fix matches root cause? Yes: the admission test itself is flipped into the allowlist its invariant requires, at the decision that caused the fan-out. Not a Delta special case, not a sink-side distributed_depth guard, not a widened bound. It answers the in-tree // NOTE: should we limit it more here? on the replaced line.
d Test intent preserved / new tests added? New 05230_parallel_replicas_insert_select_deltalake_single_commit.{sh,reference} with five printed oracles (commit count before/after, INSERT status, row count, INSERT executions, and a ParallelReplicasUsedCount > 0 control proving the read stayed distributed). No existing test weakened or rebaselined; no no-random-settings / no-parallel / no-parallel-replicas tag, no widened bound, no shrunk dataset. 03394_pr_insert_select still asserts 4 INSERT executions for its ReplicatedMergeTree target and passes, which is the guard that the kept case is untouched; 02981_insert_select_resize_to_max_insert_threads (a Distributed target on this path) prints an identical 8 / 8 / 8 on both binaries.
e Both directions demonstrated? Yes, with the same runner command on both binaries (base 77b45bf5..., fix cc626896...). Base: [ FAIL ], insert executions 3 at parallel_replicas_local_plan=1 (rows left behind plus a spurious empty commit) and 4 at =0 (all 30000 rows lost). Fix: [ OK ], 1 execution, 1 commit, 30000 rows, in both shapes and with parallel_replicas_insert_select_local_pipeline=0. The mutation arm was re-measured after every test edit, so the oracles are proven still live; the new control was additionally proven live by a negative arm (parallel replicas off: the other four oracles print their reference values and only the control reddens).
f Fix is general across code paths? Censused every site combining the two predicates over src/. Only two are admission tests for a distributed INSERT: this one, and the *Cluster-source sibling at InterpreterInsertQuery.cpp:1088, which admits data lakes deliberately (#86783) and is left alone with the question put to its owners in the PR body (measured still broken). Others (InterpreterSelectQuery.cpp:743,869, SystemLog.cpp:949, Planner/*) are SELECT-side or unrelated. The fix uses the two virtuals rather than a getName() check, so SharedMergeTree keeps the fan-out.
g Fix generalizes across inputs (params/datatypes/wrappers)? The predicate is on the storage, so the input axis is target storage, not data types. Measured base vs fix on three other admitted sinks: Memory and Log go 3 executions to 1, and File(TSV) goes from Code: 159 ... Lock timeout exceeded to a clean single-execution INSERT of all 30000 rows. Stated limit: all replicas are one process here, so the per-node row split is not observable in this rig, only the fan-out.
h Backward compatible? Yes. No setting added, renamed or re-defaulted, so no SettingsChangesHistory.cpp entry is owed (parallel_distributed_insert_select's docstring gained one clause naming the target requirement; a docstring is not a value change); no on-disk or wire format touched. Targets outside {replicated MergeTree} lose the write-side fan-out and keep the read-side one, which is already reachable today via SET parallel_distributed_insert_select = 0. The one pre-existing test that asserts this path's shape with a non-replicated (Distributed) target, 02981_insert_select_resize_to_max_insert_threads case 3, was measured on both binaries and is unchanged.
i Invariants and contracts preserved? The new return {} is the same early return, at the same position, that the replaced test used: before the AST check and before the plan-building probe, with no lock or resource held (the context copy is function-local). supportsReplication() is left untouched because DatabaseReplicated and findParallelReplicasQuery also read it. StorageProxy does not forward isMergeTree(), so the allowlist fails closed for proxied tables. No durability or crash-recovery surface.

Session id: cron:clickhouse-impl-slot-6:20260918-085500

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9f438eb]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR shares a target admission check between the parallel-replica and cluster-source INSERT SELECT paths, keeping unsafe writes on the initiator while preserving distributed reads. The earlier target-classification findings are addressed or deliberately scoped out, but the token fallback still permits silent row loss through multiple local sinks. Reviewed head: 9f438eb4dc59ee6cc8c5780087b744bb29562504.

Findings

❌ Blockers

  • src/Interpreters/InterpreterInsertQuery.cpp:885: The token fallback does not preserve all rows with strict block limits. With use_strict_insert_block_limits = 1, max_insert_threads = 3, and several output blocks in one partition, addInsertToSelectPipeline still creates multiple local sinks and puts one AddDeduplicationInfoTransform after the resize on each stream. Their counters independently start at zero, producing identical token-based IDs for distinct blocks; the replicated destination silently deduplicates them. The new test fixes max_insert_threads = 1, hiding the remaining path. Apply the source-deduplication safety restriction used by buildInsertPipeline, or maintain global block numbering across the sinks.
  • src/Interpreters/InterpreterInsertQuery.cpp:886: [dismissed by author -- https://github.com/Only distribute an INSERT SELECT across replicas when the target table replicates #120775#issuecomment-6612143983] The sequential-quorum fallback retains the same table-wide conflict when max_insert_threads > 1: addInsertToSelectPipeline passes that count unchanged, allowing sibling ReplicatedMergeTreeSink instances to contend for the single quorum status node and fail after partial writes. The author explicitly leaves local fan-out unchanged; that decision does not eliminate this reachable failure. Fix it or link a tracking issue and qualify the quorum-fix claim. No new inline comment was posted for this deliberately deferred case.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available for runtime reproduction. The source trace was checked against the exact PR head. Its Praktika workflow is still running: Fast test and Style check have passed, while the relevant functional and integration jobs remain pending.
Tests
  • ⚠️ Exercise the token fallback with strict block limits, several blocks in one partition, and max_insert_threads > 1; verify full row count and uniqueness. Also cover the sequential-quorum fallback with multiple requested insert streams. The current regression pins one stream for both settings.
Final Verdict

Status: ❌ Block

Make the strict-token fallback preserve every row and add focused regression coverage. Fix or explicitly track the deferred sequential-quorum failure.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). label Sep 18, 2026
@devcrafter devcrafter self-assigned this Sep 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9f438eb4d with master 43d95b07f (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - aaf0a91

CI is fully finished at this commit. One job failed, it has an owner, and it is not caused by this diff.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 5/6) / iceberg_suite_tpch Trunk join-reordering regression. The report's Run Errors table is entirely iceberg_suite_tpch, with the frames tests/performance/scripts/perf.py:1067 and :473: TPC-H Q5 exceeds the harness max_execution_time=15 because computeJoinCost costs a relation without a row estimate as a single row, so the greedy solver joins the unmeasured Iceberg relations first and defers the one that has measured statistics. Latent until #120176 merged on 2026-09-17, whose FK to PK branch turned that fabricated 1 into an active preference #120762 (mine, open)
Mergeable Check / PR Aggregators reporting the single performance job above, no separate failure #120762 (mine, open)

Not caused by this diff, measured rather than argued: this diff touches src/Core/Settings.cpp, src/Interpreters/InterpreterInsertQuery.cpp and the new 05230_parallel_replicas_insert_select_deltalake_single_commit.{sh,reference}, and adds no performance test. Re-measured just now, this shard failed 114 of 237 runs on 2026-09-18, spread over 100 distinct pull requests and 8 true-master commits, against 6 of 347 on 2026-09-17. The two unstable query verdicts in the same job summary are timing noise on group_by_multiple_strings, not failures to own.

Session id: cron:our-pr-ci-monitor:20260918-200532

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4c6403f

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 measurement verdict, not a regression of this diff: job info 3 too long, 1 faster, 1 slower, 4 unstable; 1 confirmed regression(s) on the performance dashboard, client_time 0.0141 to 0.0167 s (+18.6%). The dashboard-verdict gate added by #120927 reds a master_head shard on a confirmed_regression; that query is called slower on 226 distinct pull requests and on 47 distinct true-master heads (96 master rows) in the last 7 days, so the verdict tracks the benchmark rather than this branch #121090 (mine, open)
Build profile diff job-level RuntimeError: CI logs cluster query failed, raised in query at ci/jobs/build_profile_diff_job.py:234 and reached from compare_opt_functions via run_comparison (:1556), so a non-ok CI logs cluster response aborts the job with a traceback instead of degrading to "no baseline". Not reachable from this diff: the job's only work is reading build_time_trace on the logs cluster, and it neither builds nor runs the server. Measured over the last 24 hours: 203 error rows across 203 distinct heads and 202 distinct pull requests, latest at 05:13:45Z, and 0 rows on master, since the job runs on pull requests only #118708 (mine, open)
Mergeable Check, PR praktika rollups of the two rows above (Failed: Build profile diff, Performance Comparison (arm_release, master_head, 1/6)) #121090 (mine, open) and #118708 (mine, open)

Session id: cron:our-pr-ci-monitor:20260920-053046

alexey-milovidov and others added 2 commits September 23, 2026 02:21
…hout views

Two review findings on the write-side allowlist this branch added, plus what
fixing the second one exposed.

`StorageProxy`, the stand-in a `lazy_load_tables` database keeps in the catalog
until a table is first accessed, forwards `supportsReplication()` but not
`isMergeTree()`, so the allowlist read `false` for a lazily attached
`ReplicatedMergeTree` target and refused the distributed write for it: the
branch took the fan-out away from those targets, measured as 3 INSERT
executions before and 1 after. The classification now resolves the stand-in
first, with the same file-local helper `src/Analyzer/ValidationUtils.cpp`
already uses for its `isRemote` call sites. Resolving costs nothing here: this
is the table the INSERT is about to write into, so the nested storage is
materialized moments later anyway. Once the in-flight proxy-transparency work
(ClickHouse#113389, ClickHouse#117972) lands, `table` arrives already resolved and the helper
becomes a no-op rather than a conflict.

The direct target replicating is also not enough. Every replica pushes its own
slice of the coordinated read through the target's dependent materialized
views, so a view target that does not replicate keeps a different subset of the
rows on each replica: measured on three nodes, a `ReplicatedMergeTree` target
feeding a plain `MergeTree` view left the view with 0/100000/200000 of 300000
rows per node, and a read of the view from the node that issued the INSERT
returned none of them. The write fan-out inside a single INSERT already fails
closed on this, on the presence of a dependent view rather than on a proof that
the reachable view graph converges, and this reuses that predicate
(`InsertDependenciesBuilder::forwardedInsertReachesDependentView`) so a
replicated view graph, which does converge, is refused too. Proving convergence
recursively would restore the distributed write for that shape; it belongs
behind that predicate, not here.

That predicate resolves a forwarding chain to its end, which leaves `Alias`:
besides `MergeTreeData` it is the only storage answering `isMergeTree()` true,
it answers it from the table it points at, and inserting into it pushes the
views attached to the alias itself as well (03636_storage_alias_basic asserts
that), which the probe skips at every hop it follows. An alias target was
therefore still admitted with a non-replicated view hanging off the alias,
measured as 3 INSERT executions. Rather than enumerate a chain whose middle
hops are not reachable from here, the allowlist now requires a concrete table,
so `Alias` is refused whether or not a view is attached.

All four cases are pinned by stateless tests whose oracle is the INSERT
execution count from `system.query_log`, with a no-view arm as the control that
the rig distributes the write at all.
@groeneai

Copy link
Copy Markdown
Collaborator Author

be889cb narrows the write-side allowlist further, after the two review comments on it. The distributed write is now admitted only for a concrete replicated MergeTree target with no reachable dependent view:

  • a replicated target of a lazy_load_tables database keeps the fan-out, which this branch had taken away from it (the catalog stand-in does not forward isMergeTree());
  • a target with a dependent materialized view falls back to the initiator, because each replica pushes only its own coordinated share through the view;
  • an Alias target falls back as well: it reports the target's capabilities and owns views of its own, which the dependent-view probe skips at every hop it follows.

Measured on three replicas, 30000 rows per arm, only this predicate differing between the two binaries:

target INSERT executions before after
replicated, no view (control) 3 3
replicated, lazily attached 1 3
replicated + non-replicated view 3 1
replicated + replicated view 3 1
Alias over replicated, view on the alias 3 1

Row counts and the check that reading still used parallel replicas are identical in both binaries for every arm, so the fallback keeps the rows and the distributed read. New tests: 05238_parallel_replicas_insert_select_dependent_view and 05238_parallel_replicas_insert_select_lazy_target, plus 20 repeats each under randomized settings and the 6 03636_storage_alias tests.

One case stays admitted: a dependent view that exists only on a follower, which the initiator's catalog cannot see. It was admitted before this branch too; closing it needs a per-replica dependency lookup at planning time or suppressing the followers' view push.

Moved here out of the description to keep that within budget: the *Cluster-source sibling, distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage, admits data lakes deliberately (#86783), and I measured it still losing a whole INSERT into a Delta table. I left it alone, since #120488 is editing that function. Should it be narrowed to Iceberg, which does retry the CAS?

Comment thread src/Core/Settings.cpp Resolved
Two review findings on the write-side allowlist this branch added.

The setting reaches two write fan-outs and only one of them was narrowed. When
the source of the SELECT is an `IStorageCluster`, the whole INSERT is forwarded
to every node of that cluster by
`distributedWriteIntoReplicatedMergeTreeOrDataLakeFromClusterStorage`, which kept
the older `(isMergeTree() || isDataLake()) && supportsReplication()` gate.
Measured on three nodes with a `fileCluster` source: a `ReplicatedMergeTree`
target feeding a plain `MergeTree` materialized view was still forwarded to all
three, each of them running the INSERT over its own slice of the read (three
forwarded executions, 20000 of the 60000 source rows each), so the view keeps a
different subset of the rows on every node. An `Alias` target was forwarded the
same way, with the views attached to the alias itself receiving one partial write
per node. Those are the two shapes the other path now refuses, so the
concrete-target and dependent-view requirements move into a helper that both
call. The engine predicates stay per path: only the cluster-source one admits a
data lake, and only the other one has to resolve the `lazy_load_tables` stand-in
before asking `isMergeTree()`.

The description of `parallel_distributed_insert_select` promised the distributed
write for any replicated MergeTree target, which this branch stopped making true,
so it now names the two shapes that fall back to the initiator.

The new stateless test asserts the fan-out is gone for both shapes with the
INSERT execution count from `system.query_log`, keeps a no-view arm as the control
that the rig forwards at all, and asserts that a fallback still reads the source on
every node and that every row arrives: on the unfixed binary exactly the admission
and read lines flip and no row count moves.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pushed d80f5d5: the target-shape guard is now shared with the cluster-table-function write path, and the description of parallel_distributed_insert_select matches the narrowed contract. Both review comments of this round are answered in their threads with the numbers; this note records what my own second-pass review raised and what I did with it.

Not acted on, with the reason.

  • Hoisting the guard above table->distributedWrite. An Alias over a Distributed target does bypass the alias-level views, but the proposed remedy is unsound here: the dependent-view predicate fails closed on StorageDistributed (InsertDependenciesBuilder::forwardedInsertReachesDependentView returns true for it unconditionally, since the write is forwarded through a separate INSERT), so applying it before distributedWrite would refuse the distributed write for every Distributed target, view or not, and that is the primary documented use of this setting. The path is also untouched by this branch.
  • A dependent view existing only on a follower. Terminal, same as the previous round: DatabaseCatalog::getDependentViews reads the local catalog, so such a view is invisible to the initiator. It was equally admitted before this branch, which had no view check at all, and every remedy is a cross-node behaviour change rather than something this predicate can reach.
  • Raising the changelog category to Critical Bug Fix. I do not select that category on my own; it is for a maintainer to ask for. Bug Fix is accurate: a released version returns wrong results on a documented setting combination.

Open question, in the sibling-path thread. The cluster-source path also admits a data lake target and forwards the whole INSERT to every node, where each Delta sink commits its own transaction; that is issue #120714's shape through the other door, and the data lake half of the contract has no test. I have not measured it and did not change it, because the remedy is a design choice rather than a guard.

The cluster-source write fan-out admits any target answering `isDataLake()`, and
`StorageObjectStorage` answers both `isDataLake()` and `supportsReplication()` with
`configuration->isDataLakeConfiguration()`. So `INSERT INTO <data lake> SELECT ...
FROM s3Cluster(...)` is forwarded to every node of the source cluster, and each node
opens and commits a transaction of its own.

The Delta sink does not retry a conflicting commit, so those commits race for one log
version. Measured on master 95a6488, three-replica localhost cluster,
`DeltaLakeLocal` target, `fileCluster` source over 6 files and 60000 rows: the INSERT
fails with `Code: 742 ... commit conflict at version 1 (DELTA_KERNEL_ERROR)`, the table
is left with 0 rows plus a spurious commit in `_delta_log`, and the query log shows 4
INSERT executions. That is issue ClickHouse#120714 through a second admission site.

The Iceberg sink does retry, up to `MAX_TRANSACTION_RETRIES` (`IcebergWrites.cpp`), so
its per-node commits converge: on the same master an `IcebergLocal` target keeps the
fan-out and all 60000 rows land. The admission is therefore narrowed to the engine that
cannot absorb concurrent commits rather than to data lakes as a class, and `05239` gains
that Iceberg arm as the boundary control.

Neither lake was covered as a target before: `tests/integration/test_s3_cluster_insert_select`
only inserts into `ReplicatedMergeTree`, and `test_s3_cluster`'s Iceberg case uses a lake
as the source with a `MergeTree` target.

`05238` gains the target shape issue ClickHouse#121169 reported, a sink that does not replicate at all:
on master 95a6488 the three replicas contend for the same `File` table and the INSERT
dies with `Code: 159 ... Lock timeout exceeded`; a remote object store has no such lock, so
there the last writer simply wins.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Wave 5 on d3fb678: the cluster-source data-lake admission

One commit, 8 files, +128/-3. The two inline threads carry the measurements; both were taken on master
95a6488aec323, so they describe released behaviour rather than this branch.

  • INSERT INTO <Delta Lake> SELECT ... FROM fileCluster(...) lost all 60000 rows with commit conflict at version 1. The cluster-source gate now admits a data lake only when its sink retries a conflicting
    commit, which Iceberg does and Delta does not, so Iceberg's fan-out is unchanged and has a boundary arm
    in 05239.
  • 05238 gained the target shape Parallel replicas INSERT SELECT into an S3 table: every replica uploads its share to the same key, silent loss of most rows #121169 reported, a sink that does not replicate at all: on master the
    three replicas contend for the same File table and the INSERT dies with Lock timeout exceeded. A
    remote object store has no such lock, which is why there the last writer wins silently instead.

Four things stayed out, each stated before and unchanged:

  • A dependent view that exists only on a follower is invisible to the initiator, which reads the local
    catalog. That was equally admitted before this branch, and every remedy is a cross-node behaviour change
    rather than something this predicate can reach.
  • Hoisting the target guard above StorageDistributed::distributedWrite would refuse the distributed write
    for every Distributed target, view or not, because the view predicate fails closed there. That is the
    setting's primary documented use, and the path is untouched here.
  • The parallel-replicas gate still does not admit Iceberg. It never admitted a data lake deliberately: the
    isDataLake() admission was added to the cluster-source gate alone (Distributed insert-select for data lakes #86783), while the parallel-replicas
    denylist carried an open NOTE asking whether it should be limited further. Admitting Iceberg there would be a new
    optimization rather than a restoration, so it is not in a bug fix.
  • A test that provokes the Iceberg retry cannot be a stateless test today: every lost CAS is logged at
    Error level with a stack trace (PreconditionFailed for If-None-Match), which the runner counts as a
    failure. Measured 4 failures in 10 runs with a six-file source, so the 05239 arm pins the admission
    rather than the retry. An integration test can cover the concurrency if that is wanted.

The PR body now names the Delta Lake fallback and the Iceberg exception in the changelog entry and the
blast radius.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d3fb678

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 2/6) dashboard-verdict gate: job summary 2 too long; 1 confirmed regression(s) on the performance dashboard, while the shard's own report calls no query slower and has no per-query verdict at all #121090 (mine, open), with #121189 (mine, open)
Mergeable Check praktika rollup of the row above #121090 (mine, open)
PR praktika rollup of the row above #121090 (mine, open)

Shards 1/6 and 3/6 to 6/6 all passed on this head, and no test-level failure was ingested for
this commit in any other job.

Session id: cron:our-pr-ci-monitor:20260923-190314

groeneai and others added 2 commits October 7, 2026 12:51
…t-non-replicated-target

Master now declares an inline `unwrapStorageProxy` in `StorageProxy.h` and
resolves the `lazy_load_tables` stand-in in `InterpreterInsertQuery::getTable`
and in the cluster-source write path, so the file-local helper of the same name
is dropped (it no longer compiles next to the header's) and the gate classifies
the already-resolved `table` directly. The remaining `StorageProxy` subclasses
(`StorageTableFunctionProxy`, `StorageURLSchemeDispatch`, `StorageURLDatabaseTable`)
never wrap a MergeTree-family table or an `Alias`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master's `storage_casts` style check rejects a raw `dynamic_cast` to a
deferrable engine on a catalog pointer. `dst_storage` is already resolved by
`resolveStorageProxyLoading`, so `DeferredTable::Load` loads nothing here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…el-replicas path too

The parallel-replicas INSERT SELECT path admitted only a replicated MergeTree target, while the
cluster-source path also admits Iceberg, whose sink re-reads the metadata and retries a conflicting
commit. On master both paths fan out an Iceberg INSERT, so the narrower check on the
parallel-replicas path turned off a working write-side fan-out for `INSERT INTO <Iceberg> SELECT
... FROM <MergeTree>`.

Move the engine check into `targetAbsorbsDistributedWrite`, so both paths admit the same targets: a
replicated MergeTree or an Iceberg table on remote object storage, not reached through an `Alias`
and with no dependent view. `IcebergLocal` is not admitted: its files live under each server's own
`user_files`, so on a real multi-node cluster every node would commit its slice into a separate
table. On a loopback cluster that only costs the write-side fan-out.

Measured on a 3-replica localhost cluster with MinIO, 3M rows from a MergeTree source:
- `IcebergS3`: master and this commit run 3 INSERT executions (4 with
  `parallel_replicas_local_plan = 0`) and land every row exactly once, with lost CAS attempts
  logged as `PreconditionFailed` errors and retried; the previous head ran 1.
- `IcebergLocal`: 1 execution on both paths, all rows.

05230 gains an `IcebergS3` arm (fan-out kept, `send_logs_level = 'fatal'` for the retried
conflicts), and the 05239 Iceberg arm becomes the local-Iceberg fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@devcrafter, one design choice for you on this PR, raised by the latest bot comment.

On master, INSERT INTO <materialized view> SELECT and INSERT INTO <Buffer> SELECT with parallel replicas run once per replica whatever table they write into. Measured on a 3-node cluster, 300000 source rows, parallel_distributed_insert_select = 2, parallel_replicas_local_plan = 0: with a plain MergeTree behind them the INSERT succeeded and the nodes ended with 100000/100000/100000 rows (materialized view) and 100000/0/200000 (Buffer); with a ReplicatedMergeTree behind them every node converged to 300000.

This PR writes both shapes once on the initiator, so the rows are always correct, but a replicated table behind the wrapper loses the write-side fan-out, as a Distributed target already does here.

Should I (a) keep that, or (b) classify a materialized view or Buffer target by the table it writes into, keeping the fan-out when that table qualifies and no view depends on the wrapper itself? I would keep (a) in this PR; (b) is a small change if you prefer it.

Since 26.8 `max_insert_threads` defaults to the number of cores, so the
INSERT into the local Iceberg table runs several sinks, and each of them
commits its own snapshot. When two of them race for the same metadata
version, the loser's conditional publish of `v<N>.metadata.json` fails
inside `writeMetadataFileAndVersionHint`, which logs the exception at
Error level and returns false so the sink retries. The rows are correct,
but the `<Error>` line reaches the client through `send_logs_level` and
the test fails with "having stderror" (1 of 50 runs in
`Stateless tests (arm_asan_ubsan, targeted)` on 11bfc02).

The race is between sinks of the same INSERT on the initiator, not a
second node: the failing run still reports one INSERT execution
(`local iceberg: distributed write 0`) and 30000 rows. Measured on the
CI amd_asan_ubsan binary of 11bfc02 with 32 insert threads: 2 of
40 iterations print `Code: 504 ... v2.metadata.json already exists`,
every INSERT makes two commits; with `max_insert_threads = 1` in the
query, 0 of 40, every INSERT makes one commit.

The setting is pinned on that one query rather than through a
random-settings limit, because the race also happens at the default
value, which the runner does not always override.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@devcrafter devcrafter self-assigned this Oct 19, 2026
groeneai and others added 3 commits November 3, 2026 14:13
…t-non-replicated-target

# Conflicts:
#	src/Core/Settings.cpp
05406 and 05433 (added on master while this PR was open) assert the
distributed INSERT SELECT through an `ENGINE = Memory` target. This PR
writes a non-replicated target once on the initiator, so the fan-out
those tests check is no longer taken: 05406 counts 1 INSERT instead of
4, and 05433's second insert runs as an ordinary INSERT SELECT, where
the mixed `parallel_replicas_plan_based` subquery is rejected
(INCORRECT_QUERY). Both now use a `ReplicatedMergeTree` target, the
idiom of 03394_pr_insert_select and 05213, so they keep exercising the
distributed path; both pass on master and with this change.

test_insert_select_time_series_independent_uuids (integration, also new
on master) inserted into a `Null` table feeding a per-node `MergeTree`
view and asserted the INSERT ran on every replica; it now inserts into a
`ReplicatedMergeTree` table, so the distributed INSERT is still the one
under test.

05239 creates its local Iceberg table with `Int64`: master now rejects
`UInt64` columns on CREATE of an Iceberg table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… token or a sequential quorum

Both write fan-outs (parallel replicas, and a cluster table function
source) run one INSERT per node. Each node numbers its blocks from zero,
and with `insert_deduplication_token` the block id is the token plus that
number, so blocks written by different nodes get the same ids and the
later ones are dropped as duplicates. With `insert_quorum >= 2` and
`insert_quorum_parallel = 0` only one quorum part may be in flight per
table, so the nodes' inserts fail each other with "Another quorum insert
has been already started" after some of them have committed. These are
the hazards the intra-query write fan-out already keeps single-stream
for; the same check now makes `targetAbsorbsDistributedWrite` refuse the
cross-node one. Only MergeTree targets are affected: an Iceberg target
ignores both settings and keeps its fan-out.

Measured on a three-node cluster, 300000 rows, master and this branch
alike before the change: with a token 100000-200000 rows are kept and the
INSERT reports success; with a sequential quorum the INSERT fails with
code 286 and leaves 3000 rows. With the change all 300000 rows are
written once, by one INSERT, and the read stays distributed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (the only conflict was the parallel_distributed_insert_select description) and pushed a40180f.

  • Three tests added on master while this PR was open reached the distributed INSERT SELECT through a non-replicated target, which this PR writes once on the initiator: 05406, 05433 (Memory) and test_insert_select_time_series_independent_uuids (Null feeding a per-node view). They now use a ReplicatedMergeTree target, so they still exercise the distributed path, and pass on master as well. 05239 creates its Iceberg table with Int64, since master now rejects UInt64 there.
  • New: a replicated MergeTree target also stays on the initiator with insert_deduplication_token, or with insert_quorum but without insert_quorum_parallel. Each node numbers its blocks from zero, so on a three-node cluster (300000 rows, master behaves the same) a token kept 100000-200000 rows with no error, and a sequential quorum failed with code 286 after 3000 rows were committed. test_insert_select_colliding_write_settings covers both settings for both source paths; it failed all 8 runs before the change.
  • Not covered by the new check: deduplicate_insert_select = 'enable_even_for_bad_queries' without a token. The initiator's own max_insert_threads fan-out of an ordinary INSERT SELECT is unchanged; master keeps a sequential-quorum insert single-stream only for INSERT ... VALUES (04652).

…t-non-replicated-target

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// Each node numbers its blocks from zero, so a deduplication token gives blocks of different nodes the same
/// identifiers, and a non-parallel quorum insert allows only one part in flight per table.
if (table->isMergeTree()
&& (!settings[Setting::insert_deduplication_token].value.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.

[Blocker] The token fallback still silently drops rows with use_strict_insert_block_limits = 1 and multiple local insert streams. For example, run the new token regression with max_insert_threads = 3, max_threads = 3, strict limits enabled, and max_insert_block_size = 1000. Returning false here sends it to addInsertToSelectPipeline, which passes the unchanged thread count to InsertDependenciesBuilder and installs a separate AddDeduplicationInfoTransform after resizing to those streams (InterpreterInsertQuery.cpp:549–552,670–690). Each transform starts at source block zero, so different blocks in the same partition receive identical token-based IDs and ReplicatedMergeTreeSink discards some as duplicates. The new regression's max_insert_threads = 1 masks this case.

Please keep this fallback single-stream when strict limits and source deduplication are enabled, as buildInsertPipeline already does, or preserve globally unique block numbering across its sinks. Add a focused regression with multiple insert streams and assert that every source row survives.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Not specific to this PR: on master with parallel replicas off, a local INSERT ... SELECT of 300000 rows into a MergeTree with a deduplication window, with insert_deduplication_token, use_strict_insert_block_limits = 1, max_insert_threads = 3 and max_insert_block_size = 1000, keeps 121000 rows without an error (300000 with max_insert_threads = 1). The per-stream numbering is in addInsertToSelectPipeline, which this PR does not change and which every local INSERT ... SELECT goes through, so I will fix it in a separate PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Correction to my reply above: #113045 (open) already covers this. It moves the single-stream decision of buildInsertPipeline into insertDeduplicationNeedsSingleStream and also applies it in addInsertToSelectPipeline before InsertDependenciesBuilder::create, so a strict-limits INSERT ... SELECT into a deduplicating table keeps one insert stream (its test 04904_04870_insert_select_deduplication_single_stream). I will track #113045 instead of opening a separate PR.

@clickhouse-gh

clickhouse-gh Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Dear @devcrafter, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@devcrafter devcrafter self-assigned this Nov 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-parallel-replicas Parallel reading from replicas for query speed (not data replication consistency). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

3 participants