Skip to content

Perform the Too many parts check once per INSERT query - #113045

Open
alexey-milovidov wants to merge 149 commits into
masterfrom
fix-insert-too-many-parts-check-once
Open

alexey-milovidov wants to merge 149 commits into
masterfrom
fix-insert-too-many-parts-check-once

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

Related: #109000

MergeTreeSink::onStart and ReplicatedMergeTreeSink::onStart perform the parts_to_throw_insert / parts_to_delay_insert check, and onStart is the only place where an INSERT may be rejected with TOO_MANY_PARTS - rejecting a query that has already written a part is not acceptable, as the comment right above the call says.

Since #109000 a plain INSERT writes through up to max_insert_threads sinks running in parallel, and every one of them runs onStart (ExceptionKeepingTransform::prepare returns Ready for the Start stage of every sink, whether or not it ever receives a chunk). The onStart calls of the different sinks are not ordered with respect to each other's writes: a sink that the executor schedules late runs its check after another sink of the same query has already committed a part, counts that part, and rejects the query in the middle of it. The INSERT fails with TOO_MANY_PARTS even though the table was below the threshold when the query started - and even when the table was empty and the only part counted is the one the query wrote itself.

Note that #109000 exposed the flaw rather than introduced it. The parallel sink fan-out itself (sink_stream_size = max_insert_threads in InsertDependenciesBuilder) has been in place for the INSERT SELECT path since 031a9d5a528, and the default of max_insert_threads changed from 1 to 0 (auto, the number of CPU cores) in 26.8 - so an INSERT SELECT into a MergeTree table could already be rejected by a stream that counted a part the query had written itself. Before #109000 the plain-INSERT pipeline passed a hardcoded /*max_insert_threads*/ 1 to the builder and always had a single sink, which is why the flaky tests below - all of them plain INSERT ... VALUES - only started failing when that changed.

The check is now shared by all the sinks of one query: the first sink to reach onStart runs it and the others wait until it is finished, so it runs exactly once and strictly before any of the sinks writes anything. The shared decision includes a rejection: the gate remembers the outcome of the first run and rethrows the same exception to every other sink, instead of letting them re-enter a check that reads mutable state - the parts of the destination table - and could pass a moment later after a background merge or cleanup. This restores the behaviour that the single-sink pipeline had. Only the rejection is shared: the parts_to_delay_insert backpressure is applied by every sink before each of its blocks, including the first one, so a parallel INSERT keeps the same per-block throttling as a single-sink one (a sink that receives no data does not delay).

The gates live in a small per-query registry (InsertStartGates) keyed by the physical destination table id. InsertDependenciesBuilder creates the registry and takes each sink's gate from it next to setRuntimeData / setHasDependentMaterializedViews, so the sinks of all the streams that write into the same table share one gate - including the branches of different materialized views converging on the same target table. An Alias destination forwards the write through a nested INSERT per parallel branch and the real check runs inside those nested inserts, so AliasSink receives the registry and threads it into the nested InterpreterInsertQuery, whose builder inherits it instead of creating its own. Distributed and Buffer destinations are always kept single-stream by #109000, so their own pre-write checks are unaffected - but their in-query nested INSERTs into the underlying tables are not. The local writes of a Distributed destination run through nested INSERTs into the underlying table: one per incoming block on the writeToLocal path (the direct local write of a background-send insert with prefer_localhost_replica) and one per local replica job on the foreground path. Each of them used to create its own gates, so the second block of a multi-block INSERT counted the part the first block had already committed on the local target and failed the query mid-way; DistributedSink also receives the registry and threads it into both nested INSERT paths (the new test 04826_insert_distributed_local_too_many_parts_gate covers a two-block insert into a local target with parts_to_throw_insert = 1 on both paths). The parallel_distributed_insert_select rewrite of an INSERT ... SELECT between two Distributed tables writes the local shards the same way - one nested InterpreterInsertQuery per destination shard this server belongs to - and a server can be local for several destination shards of one cluster, so those sibling nested INSERTs write into the same underlying table and now share one registry as well (the new test 04847_insert_parallel_distributed_insert_select_local_shards covers a two-local-shard cluster with parts_to_throw_insert = 1 on the target, plus the non-parallel quorum variant of the same topology). The gates can only be shared by nested INSERTs running in this process. With prefer_localhost_replica = 0 a local shard is deliberately routed back to this server through RemoteQueryExecutor (or a remote writing job of the foreground fan-out), and each such write is an independent TCP INSERT with its own gates - the same situation as two shards of one query resolving to the same remote server, which no in-process registry can cover. That routing is left alone: it is not merely a scheduling hint but the only way to run the write through the connection pool under the credentials supplied to the engine instead of the initiator's, so overriding it for multi-local-shard topologies would be a backward-incompatible access-control change (a Distributed table spanning two local shards could start failing with ACCESS_DENIED for a user who only has rights on the distributed table). The sharing of the pre-write checks simply does not extend across the independent queries this setting asks for. The direct writes of a Buffer destination run through nested INSERTs into its destination table as well: one per block that bypasses the buffer by exceeding the max thresholds, and one per flush the buffer runs by threshold from within the query - so a later direct write of a multi-block INSERT used to count the part an earlier one had committed on the destination; BufferSink also receives the registry and threads it through flushBuffer / writeBlockToDestination into those nested INSERTs, while the background flush keeps creating fresh gates per flush as before (the new test 04827_insert_buffer_direct_write_too_many_parts_gate covers both paths with parts_to_throw_insert = 1 on the destination). A threshold flush writes out whatever the buffer holds at that moment - possibly the rows of several queries, not necessarily including the one that triggered it - so its single pre-write decision is shared with exactly the queries whose rows it writes: each buffer shard records the registries of the queries whose rows it currently holds, and the flush's nested INSERT runs with a group registry whose gates are shared with all of them, so a query whose buffered rows were flushed by someone else's INSERT does not re-run the check later and count the part holding its own rows (the new test 05054_insert_buffer_mixed_queries_flush_gate covers that interleaving). A participant that already holds a gate for the table lends it to the group, so a flush after an earlier write of the same query observes that decision instead of counting the parts of that earlier write. A gate that rejected a write is not lent, though: the rows of a rejected flush go back into the buffer to be written again later, and that later flush is a new write which decides anew - otherwise the cached rejection would keep the rows in the buffer for good after the limit was raised or the parts merged away, and reject a query whose rows are flushed together with them (the new test 05223_insert_buffer_failed_flush_retry_gate covers a later query flushing the rows of the rejected one, and the rows of two queries flushed in one block). The gate of a group write is looked up, created and stored in every participant with all the registries involved locked at once (in the order of their addresses, which is a global order, so a registry taking part in several group writes cannot deadlock against them): the shards of a Buffer are flushed in parallel, and two flushes carrying rows of one query - or a flush racing a direct write of that query - must not each conclude that the table has no gate yet and hand out different ones (the new test 05055_insert_buffer_concurrent_shard_flush_gate pins that topology: the rows of one INSERT are spread over two shards whose parallel flushes write a part each into a destination with parts_to_throw_insert = 1). The participants of a group write are not necessarily the registries of the queries themselves: when the destination of a Buffer is another Buffer, the flushed block is buffered again together with the group registry of the queries it was written for, and the second buffer lists that registry as a single participant of its own later flush. The queries behind such a wrapper own the rows just as the direct participants do, so the whole participant graph is walked when a gate is chosen and stored, not only its first level - otherwise a query whose rows reached the final destination through a chain of buffers never observed that write and could re-run the check afterwards and count the part its own rows created (the new test 05153_insert_chained_buffer_flush_gate covers a two-buffer chain in front of a destination with parts_to_throw_insert = 1). The query that triggered the flush participates only when its own rows are among the flushed ones: an eviction of data buffered by earlier queries makes no pre-write decision for it - otherwise it would spend the gate before the running query has written anything of its own and that query's first write would skip the check (the new test 05023_insert_buffer_preexisting_rows_too_many_parts_gate covers a query arriving at a buffer that already holds a row of an earlier one). A TimeSeries destination forwards the write through nested INSERTs into its inner target tables, so TimeSeriesSink also receives the registry and threads it into them, sharing the check across sibling branches converging on the same TimeSeries table. Those nested pipelines are now created in onStart rather than in the sink's constructor: the registry reaches the sink only after StorageTimeSeries::write has returned it, so building them in the constructor handed them an empty registry and the sharing held only by the accident of every sink of the query being constructed before any of them writes anything. An equivalent path existed for WindowView (PushingToWindowViewSink threading the registry into StorageWindowView::writeIntoWindowView), but the WINDOW VIEW feature has been removed on master in the meantime, so that part of the change is dropped - which also settles #113493, the reason this path could not be covered by a test.

A related single-in-flight-part contract exists one level up: a non-parallel quorum insert (insert_quorum >= 2 or 'auto', with insert_quorum_parallel = 0) permits a single in-flight quorum part per table, which is why its max_insert_threads fan-out is kept single-stream. But the single sink stream is still duplicated into one branch per dependent materialized view, and with parallel_view_processing = 1 those branches ran concurrently - two views converging on one ReplicatedMergeTree target raced two in-flight quorum parts of one INSERT against each other, so a sibling branch could fail with UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE or conflict on the /quorum/status node. The serialization such an insert needs is derived from the collected sink graph, not from the settings alone (InsertDependenciesBuilder::computeQuorumStreamRequirements): only writes reaching a ReplicatedMergeTree table are quorum writes, and only two of them racing on the same table conflict. The INSERT SELECT fan-out - which had no quorum guard at all - is kept single-stream only when a branch of the write may produce a quorum part: a reachable ReplicatedMergeTree target, or a forwarding storage (an Alias, a Distributed, a Buffer, a TimeSeries) that hides its physical destination, in which case the probe fails closed. An insert whose write graph never reaches a replicated table keeps its max_insert_threads fan-out even under a global quorum profile. Only the branches reachable in the executable graph are counted: a view branch pruned from the graph - e.g. a view whose dropped target table is ignored by ignore_materialized_views_with_dropped_target_table - never creates a sink, so it does not force the serialization (the new test 04825_insert_quorum_ignored_broken_view_fanout covers a broken ignored view attached to a plain MergeTree destination). The dependent views of such an insert are pushed sequentially only when two branches converge on the same replicated table (a sequential branch blocks in commitPart until the quorum of its part is satisfied, so the next branch starts with the quorum node already gone) or when a hidden write target makes such a convergence impossible to rule out - branches writing to distinct replicated tables keep running concurrently, since they do not share a /quorum/status node. An Alias destination hides its target's views behind the nested INSERT its sink runs, and that nested INSERT observes the same settings and derives the same requirements. The new test 04828_insert_timeseries_too_many_parts_gate exercises non-parallel quorum inserts through two views converging on one TimeSeries table whose data table is replicated - the shape that raced UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE before TimeSeries was included in the hidden-target probes. The new test 04817_insert_quorum_sequential_dependent_views covers the INSERT SELECT fan-out deterministically via EXPLAIN PIPELINE and exercises quorum inserts through two materialized views converging on one replicated target with parallel_view_processing = 1; the new test 04823_insert_quorum_graph_derived_serialization covers the fan-out kept for a plain MergeTree destination, the fan-out dropped when a dependent materialized view targets a replicated table, and quorum inserts through two views writing to two distinct replicated tables. The local jobs of a synchronous foreground Distributed insert are nested INSERTs that can each commit a quorum part into the same local target through different shards, so DistributedSink completes them one-by-one for a non-parallel quorum insert (the new test 04907_insert_distributed_local_quorum_sequential covers a two-block insert over a two-local-shard cluster writing one replicated target) - but only when the resolved local target may actually produce a quorum part, derived with the same graph probes, so a global quorum profile does not cost the local-shard parallelism of a foreground insert into a plain MergeTree target.

parallel_view_processing = 0 gets the same treatment on the INSERT SELECT path: buildInsertPipeline already kept a plain INSERT single-stream when the destination is a forwarding storage that hides its target's dependent-view graph behind the nested INSERT its sinks run (serial_hidden_views), but addInsertToSelectPipeline still passed the raw max_insert_threads to the builder - which sees no views for such a destination - so an INSERT SELECT into an Alias fanned out into several AliasSinks whose hidden materialized views ran concurrently across sibling branches despite the setting. The guard is now mirrored there; an Alias in front of a target with dependent views is the only topology whose fan-out survived to that point, since Distributed, Buffer and TimeSeries destinations are already collapsed to one stream by the builder's supportsParallelInsert check. The new test 04869_insert_select_alias_hidden_views_serial covers the single stream with a hidden dependent view, and the fan-out kept both without dependent views and with parallel_view_processing = 1. The hidden-view probes validate each catalog dependency under a share lock and skip a stale entry whose view no longer reads from the storage, matching the pruning collectAllDependencies applies to the executable graph - so a stale dependency does not force an INSERT into an Alias single-stream when the direct insert into its target keeps the fan-out.

This is the cause of a family of flaky tests that started failing on master on 2026-08-01, right after #109000 was merged, each of them rejecting an INSERT that counts the part it has written itself:

test failing query reported parts
02458_relax_too_many_parts INSERT INTO test VALUES (6, 'a') 3 with parts_to_throw_insert = 3
02280_add_query_level_settings INSERT INTO table_for_alter VALUES (1, '1') into an empty table 1 with parts_to_throw_insert = 1
00980_merge_alter_settings INSERT INTO table_for_alter VALUES (1, '1') into an empty table 1 with parts_to_throw_insert = 1
02015_async_inserts_5 INSERT INTO async_inserts VALUES 1 with parts_to_throw_insert = 1

The server log of the 02458_relax_too_many_parts failure below shows the mechanism directly: 26 sinks are created for the query, its part all_5_5_0 is renamed into place at 01:46:59.792095, and the query is rejected with Too many parts (3 ...) at 01:46:59.798713 - six milliseconds after it committed the part it is being counted for.

Report of that failure (MergeQueueCI, Fast test):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-112777-508dbed54a148ce6ae2dabe8ff91f4c7842bb1a0&sha=c71ec1f59e4b52ffe87c96e12743488cec72a7e0&name_0=MergeQueueCI&name_1=Fast%20test
Corresponding pull request: #112777

The new test 04692_insert_too_many_parts_check_once_per_query covers both halves: an INSERT with a large max_insert_threads that brings a table from one part up to parts_to_throw_insert = 2 has to be accepted, and ProfileEvents['DelayedInserts'] of a single-row INSERT has to match the number of blocks the query actually writes (one; two when the query writes through two materialized views converging on the same target table) rather than the number of streams it writes through - also when it writes through an Alias.

TimeSeries is also classified as a forwarding storage in the deduplication-safety probes (storageDeduplicatesBlocksOnInsert, storageRebuildsDeduplicationIdsOnInsert, forwardedInsertReachesDependentView, forwardedInsertHidesDependentView, forwardedInsertHidesDependentViewForwardingToSeparateContext), since TimeSeriesSink forwards a plain block into its nested INSERTs and drops the outer chunk's DeduplicationInfo. This is fail-close classification only, not a reachable fix: StorageTimeSeries does not override IStorage::supportsParallelInsert, so an insert whose graph reaches a TimeSeries table is already single-stream and the probes cannot change the outcome - and writes arriving through TimeSeriesSink turn out not to deduplicate on the inner tables at all, so no rows are lost when two views converge on one TimeSeries table. The clauses keep the classification correct if StorageTimeSeries ever starts supporting parallel inserts. The new test 04846_insert_mv_timeseries_dedup_parallel_views pins the no-row-loss half end to end: two identical materialized views converging on one TimeSeries table with a deduplicating data table (non_replicated_deduplication_window) under parallel_view_processing = 1 land both branches in full - nothing is deduplicated between the sibling branches of one query.

Three refinements of the shared decision. First, a deferred check of a table behind a forwarding sink is registered only if its context may INSERT into that table (into any of its columns): the check runs before the nested INSERT checks the access rights, and a user who may only insert into the forwarding table must get ACCESS_DENIED rather than a TOO_MANY_PARTS that describes the parts of the protected target (the new test 05454_insert_too_many_parts_gate_hidden_target_access). Second, under materialized_views_ignore_errors the check of a view branch is isolated: its failure is kept with that sink only, so the ignored rejection of one branch does not reject a sibling branch that writes into the same table with looser limits. Third, a gate whose decision failed for some of its checks is not lent to a group write, so an OPTIMIZE or background flush of a Buffer that holds the query's rows decides anew with the buffer's own limits (both covered by the new test 05453_insert_too_many_parts_gate_buffer_optimize_and_ignored_views).

Relation to #114016

While this pull request was open, #114016 landed on master with a narrower fix for the same root cause: it evaluates the check on the query thread in the MergeTreeSink / ReplicatedMergeTreeSink constructor and rethrows it from onStart. Merging master resolves that in favour of the shared gate, which subsumes it - a sink whose onStart runs late skips the check instead of re-running it - and additionally covers the sinks that are created during execution, which the constructor placement cannot: the nested INSERTs of Alias, Distributed, Buffer and TimeSeries. Everything else from #114016 is kept, including the merge_tree_sink_on_start_random_sleep failpoint and its test 04826_parallel_insert_sinks_too_many_parts_self_race, which the shared gate also makes pass.

Related: #114016

Relation to #128833

#128833 landed on master while this pull request was open and added a probe for serial destinations hidden behind an Alias (insertReachesSerialDestination). Two things were reconciled when merging it. The probe failed closed on a dependent view whose target table is dropped; it now prunes such a view under ignore_materialized_views_with_dropped_target_table / materialized_views_ignore_errors like the other hidden-graph probes here, so 04825_insert_quorum_ignored_broken_view_fanout keeps its fan-out through an Alias. And its test 05837_distributed_insert_select_preserves_order expected four DistributedSinks for an INSERT SELECT from a multi-stream source: since this pull request applies the single-stream guards of a plain INSERT (insertDeduplicationNeedsSingleStream, serial_hidden_views) to INSERT SELECT too, and a Distributed destination hides the dependent views and the deduplication of the tables on the shards, that case is single-stream here, and the reference of the test is updated accordingly. (So the earlier remark that Distributed destinations are already collapsed to one stream by the supportsParallelInsert check is not accurate for INSERT SELECT: it is these guards that collapse them.)

Related: #128833

A MaterializedView that is inserted into directly only passes the rows to its target: the views reading from the view itself are not run. The deferred pre-write checks no longer follow them, so an INSERT forwarded into such a view through an Alias or a Buffer behaves like the direct one (the new test 05839_insert_too_many_parts_gate_view_reading_from_view).

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 a spurious TOO_MANY_PARTS error for an INSERT executed with max_insert_threads greater than one. The Too many parts check was performed by every parallel writing stream, so a stream that started after another one had written a part counted that part and rejected the query, even when the table was below the threshold - or empty - when the query started.


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

`MergeTreeSink::onStart` and `ReplicatedMergeTreeSink::onStart` perform the
`parts_to_throw_insert` / `parts_to_delay_insert` check, and it is the only place
where an INSERT may be rejected with `TOO_MANY_PARTS`, because rejecting a query
that has already written a part is not acceptable.

Since #109000 a plain INSERT writes through up to `max_insert_threads` sinks
running in parallel, and every one of them runs `onStart`. The `onStart` calls of
the different sinks are not ordered with respect to each other's writes: a sink
that is scheduled late runs its check after another sink of the same query has
already committed a part, counts that part, and rejects the query in the middle
of it. The query fails with `TOO_MANY_PARTS` even though the table was below the
threshold when the query started, and even when the table was empty.

The check is now shared by all the sinks of the query: the first one to reach
`onStart` runs it and the others wait until it is finished, so it runs exactly
once and strictly before any of the sinks writes anything. This also stops the
insert delay from being applied by every stream separately.

This is the cause of the following flaky tests, all of which reject an INSERT
that counts the part it has written itself:
`02458_relax_too_many_parts`, `02280_add_query_level_settings`,
`00980_merge_alter_settings` and `02015_async_inserts_5`.

Report of one such failure:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=gh-readonly-queue/master/pr-112777-508dbed54a148ce6ae2dabe8ff91f4c7842bb1a0&sha=c71ec1f59e4b52ffe87c96e12743488cec72a7e0&name_0=MergeQueueCI&name_1=Fast%20test
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [187dbba]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, targeted) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Stateless tests (amd_tsan, flaky check) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_msan, flaky check) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Stateless tests (amd_tsan, s3 storage, targeted) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05054_insert_buffer_mixed_queries_flush_gate FAIL cidb
02046_low_cardinality_parallel_group_by NOT_FAILED cidb
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
Check Results FAIL

AI Review

Summary

The PR shares pre-write TOO_MANY_PARTS decisions across parallel and nested INSERT sinks while preserving per-block backpressure. Request changes: an unused local shard can reject a forwarded insert, and two ignored-view paths can write despite their effective rejection limits. Two new inline findings were posted together; the pending-outcome finding continues its existing thread.

Findings

⚠️ Majors

  • src/Interpreters/InsertDependenciesBuilder.cpp:774: Local checks ignore shard selection. With local shard 1 and remote shard 2, tryGetDistributedLocalTarget returns the local destination even when insert_shard_id = 2. An Alias over the Distributed table enforces that unused destination's check before creating the nested insert and can throw TOO_MANY_PARTS; the real writer creates only remote-shard jobs. Restrict the probe to the selected shards.

  • src/Interpreters/InsertDependenciesBuilder.cpp:919: Ignored hidden cascades omit downstream checks. Under materialized_views_ignore_errors = 1, the collector stops at a non-MergeTree target. In Alias -> definer view -> Null -> SQL SECURITY NONE view -> dst, the real nested builder still creates the final sink. If a loose direct sibling has already accepted the gate, the late isolated check has no preregistered outcome and is discarded, allowing the strict hidden branch to write. Collect isolated outcomes throughout the ordinary view cascade.

  • src/Interpreters/InsertStartGates.h:121: Borrowed acceptance hides a pending isolated rejection. A mixed-query Buffer flush can borrow query A's accepted decision while merging query B's pending isolated check for a hidden view. The flush's fresh matching view sink receives A's accepted outcome through lent_from; running the deciding gate records B's rejection only in B's original outcome. The flush consequently writes B's rows despite that failed check. Propagate the pending outcome to the matching view sink while preserving isolation from unrelated failures. The existing bot-authored thread was reopened with one follow-up.

  • src/Storages/StorageBuffer.cpp:1286: Parallel shard flushes still lack non-parallel quorum ordering. [dismissed by author -- https://github.com/Perform the Too many parts check once per INSERT query #113045#discussion_r4241721184] The author deliberately leaves this pre-existing behavior outside this PR. It remains real: flushAllBuffers schedules shards concurrently, and each replicated sink independently checks the shared quorum node after its parts gate, permitting quorum conflicts after partial progress. No thread reply or reopening was made for this dismissed point.

Tests
  • ⚠️ Add a forwarded Distributed insert selecting only a remote shard while an unselected local destination is at its part limit.
  • ⚠️ Extend 05812_insert_too_many_parts_gate_definer_ignore_errors_cascade with error ignoring enabled and assert that the strict hidden branch adds no rows.
  • ⚠️ Cover an accepted contributor plus a pending contributor in a buffer flush whose matching hidden view has an isolated rejection. Verify that the pending contributor's rejected view rows do not land.

The findings are source-traced. Available Praktika reports contain no failed tests, but these reproduction inputs were not executed locally; no ClickHouse binary is available in this job.

Final Verdict

Status: ⚠️ Request changes

Honor shard selection, preregister cascading isolated checks, and preserve matching pending isolated outcomes during borrowed flush decisions, with focused regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 187dbbaeb with master f455c7537 (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.

Object file sizes

60 object files changed (+458.53 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/InsertDependenciesBuilder.cpp.o 978.20 KiB 1.14 MiB +190.71 KiB (+19.50%)
src/CMakeFiles/dbms.dir/Processors/Sinks/SinkToStorage.cpp.o 38.26 KiB 84.07 KiB +45.80 KiB (+119.71%)
src/CMakeFiles/dbms.dir/Storages/StorageBuffer.cpp.o 1022.91 KiB 1.02 MiB +19.54 KiB (+1.91%)

716 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

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

Job report

…s` nested inserts

The AI review found two topologies where the start gate was not actually
shared by all the sinks of one query writing into the same table:

1. The gates were keyed by the view id, but different materialized views
   can converge on the same physical target table (`TO t`); with
   `parallel_view_processing = 1` the branches got separate gates, so a
   late branch could still count a part committed by a sibling branch and
   reject the query with a spurious `TOO_MANY_PARTS`.

2. An `Alias` destination forwards the write through a nested `INSERT`
   per parallel branch (`AliasSink::onStart`), and the real check runs in
   the `MergeTreeSink` / `ReplicatedMergeTreeSink` of those nested
   inserts. Each nested `InterpreterInsertQuery` built its own gates, so
   the check was performed once per branch, not once per query.

The gates now live in a small per-query registry (`InsertStartGates`)
keyed by the physical destination table id. `InsertDependenciesBuilder`
creates the registry (or inherits it) and takes each sink's gate from it,
so materialized-view branches converging on one table share one gate; a
forwarding sink (`AliasSink`) receives the registry and threads it into
the nested `INSERT` it runs, so the sinks created there - including the
target's own dependent-view sinks hidden behind the hop - keep sharing
the outer query's gates.

The test now also covers both topologies: `ProfileEvents['DelayedInserts']`
of a single `INSERT` has to be `1` when two materialized views write into
the same delayed table in parallel, and when the write goes through an
`Alias` with a large `max_insert_threads`.

Co-Authored-By: Claude Fable 5 <[email protected]>
…sert` backpressure per block

Sharing the whole `delayInsertOrThrowIfNeeded(..., true)` call across the parallel sinks
weakened `parts_to_delay_insert`: the first block of every sink except one skipped the delay.
Split the two concerns: the shared pre-write gate now performs only the throw checks (new
`allow_delay` parameter of `MergeTreeData::delayInsertOrThrowIfNeeded`), and every sink runs
the non-throwing delay check before each of its blocks, including the first one. A sink that
receives no data does not delay, so the counts in the test stay deterministic.

#113045

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 2 commits August 5, 2026 13:44
…dowView` inner table

`PushingToWindowViewSink` never used the gate it received: it forwards every chunk into
`StorageWindowView::writeIntoWindowView`, which creates a fresh sink of the inner table with
`inner_table->write` per chunk of every parallel branch of the query. Hand the per-query gate
registry over to `writeIntoWindowView` (the same way `AliasSink` threads it into its nested
INSERT), so those sinks share the query's gate of the inner table and the `Too many parts`
rejection runs once per query, strictly before any of them writes anything.

No regression test: a `WINDOW VIEW` currently cannot receive any inserted data at all - the
view dependency of its source table is never registered, so an INSERT into the source table
does not push to the window view, and a direct INSERT into the window view fails with
`std::out_of_range` in `InsertDependenciesBuilder::createPreSink`. Both failures predate this
change (they reproduce on 26.7), so the gate threading cannot be exercised end-to-end until
they are fixed.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 3 commits November 8, 2026 18:34
# Conflicts:
#	src/Storages/MergeTree/MergeTreeSink.cpp
…y parts` check

A `Buffer` may keep the check until a much later flush. Only the query-level
limits (`parts_to_throw_insert`, `dead_blobs_to_throw_insert`) are needed, so
freeze them into the callback instead of pinning the whole `ContextPtr`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… target that does not push to them

A nested `INSERT` (through `Alias`, `Buffer`, `Distributed`, `TimeSeries`) into a
storage whose `noPushingToViewsOnInserts` is true (`Kafka`, `NATS`, `RabbitMQ`,
`FileLog`) runs none of its dependent views, like `createChainWithDependencies`.
Align the graph-classification probes with that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/InsertStartGates.h Resolved
alexey-milovidov and others added 4 commits November 10, 2026 00:46
A group write borrowing the decision of a gate that has made it - possibly a lent gate of an earlier
flush itself - stored that gate as its `lent_from`, so flushes alternating between two `Buffer`
tables over one destination built an unbounded chain of gates: every historical gate stayed alive,
and every late check walked the whole chain while the buffer shard was locked.

A late check made on a lent gate is handed straight to its `lent_from`, and nothing else of
`lent_from` but its presence is consulted, so borrowing from the root of the chain makes the same
decision. `lent_from` now never points to a lent gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ets the write reaches

`TimeSeriesSink` creates the pipelines only of the target tables whose columns the `INSERT` lists,
but the hidden pre-write checks of a write reaching a `TimeSeries` table through a forwarding
storage were registered for every target. A `Distributed` table or a `Buffer` with only the metric
family columns writes only into the "metric families" table, yet its write was rejected by
`TOO_MANY_PARTS` of the "samples" or "tags" table.

The selection of the targets is moved to `StorageTimeSeries::getInsertTargets`, used by both
`TimeSeriesSink` and the hidden check collector, which now follows the columns a `Buffer` or a
`Distributed` table lists in its nested `INSERT`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 6 commits November 11, 2026 05:40
…erializedView` to its target

`StorageMaterializedView::write` passes the INSERT query, and so its column list, through to the
target table. The collector of the hidden pre-write checks dropped it at that hop, so a `Buffer`
writing only the metric family columns into a materialized view targeting a `TimeSeries` table
registered the checks of the "samples" and "tags" tables, which the write never touches, and could
be rejected with `TOO_MANY_PARTS` because of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ent instance of the table

A `Buffer` keeps the pending check of a query until it flushes the rows of that query. If the
destination table is detached and attached again in between, the instance the check was created
for is gone and the check was skipped, although the flush writes into the new instance with the
same `UUID`. Now the check resolves the table by its `StorageID` when the original instance has
expired, and is skipped only if the table does not exist anymore (the nested INSERT fails then).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…any parts` check

The table from `DatabaseCatalog` may be a `StorageTableProxy`, so a `dynamic_cast` to `MergeTreeData` would fail and skip the check. Fixes the `storage_casts` style check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 16, 2026 00:13
…-parts-check-once

Resolve the conflict in `StorageBuffer::writeBlockToDestination`: keep both the
`insert_start_gates` of this PR and the `query_context` added on master to share
the query's max-threads snapshot with the direct write.
…scading views

`registerHiddenDependentViewsPreWriteChecks` read `materialized_views_ignore_errors`
from the context of each recursive view, i.e. from the `SQL SECURITY` definer of a
view on the way, while the real `InsertDependenciesBuilder` of the nested `INSERT`
samples it once from its root context and applies it to the whole cascade. A
definer that ignores the errors of the views could therefore make the collector
register an isolated check for a sink whose real check is a regular one, and the
strict branch could write instead of rejecting the `INSERT`.

Carry the error policy of the nested `INSERT` along the writes the same `INSERT`
performs (dependent views, a `MaterializedView`, the nested storage of a proxy),
and sample it again only where a forwarding storage (`Alias`, `Buffer`,
`TimeSeries`, `Distributed`) starts a new nested `INSERT`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 21, 2026 03:04
…-parts-check-once

Conflicts in `InsertDependenciesBuilder` and `InterpreterInsertQuery`: both
sides added functions next to the constructor of `InsertDependenciesBuilder`
and a trailing argument to it. Both sets of functions are kept
(`forwardedInsertHidesSerialDestination` / `insertReachesSerialDestination`
from `master`, the quorum probes from this branch), and the constructor takes
both `insert_start_gates_` and `preserve_input_order`, in this order.
`addInsertToSelectPipeline` passes both, keeping the single-stream guards of
this branch (`dedup_single_stream`, `serial_hidden_views`).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`modernize-use-nodiscard` is enabled on `master` now, and the `arm_tidy` build
failed on `InsertStartGates::hasFailedDeferredCheckOf`,
`InsertStartGates::getFlushedBy` and `StorageTimeSeries::InsertTargets::contains`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113045&sha=fc7a8e8374076f40f5073fb1fbe4f77864fccb30&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29
#113045

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…master`

Two semantic conflicts with #128833
that the merge of `master` left behind:

`insertReachesSerialDestination` failed closed on a dependent view whose
target table is dropped. Such a view is pruned from the graph of the nested
`INSERT` under `ignore_materialized_views_with_dropped_target_table` or
`materialized_views_ignore_errors` and creates no sink there, so an `INSERT`
through an `Alias` lost its fan-out, which
`04825_insert_quorum_ignored_broken_view_fanout` pins. The probe now prunes
it the same way as `dependentViewMayWriteToReplicatedTable` does, resolving
the target through the context of the `INSERT`.

`05837_distributed_insert_select_preserves_order` expected four
`DistributedSink`s for an `INSERT SELECT` from a multi-stream source. This
branch intentionally applies the single-stream guards of a plain `INSERT`
(`insertDeduplicationNeedsSingleStream`, `serial_hidden_views`) to
`INSERT SELECT` as well, and a `Distributed` destination hides the dependent
views and the deduplication of the tables on the shards, so that case is
single-stream now. The reference and the comment of the test are updated;
the ordering half of the test is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ed view

A nested `INSERT` into a `MaterializedView` passes the rows to its target and
expands the dependent views of that target only: `collectAllDependencies`
does not run the views reading from the materialized view itself. The walk
registering the hidden pre-write checks followed them nevertheless, so an
`INSERT` forwarded into such a view through an `Alias` or a direct-writing
`Buffer` ran the `Too many parts` check of a table nothing is written into
and failed with `TOO_MANY_PARTS`, while the direct `INSERT` succeeded.

The new test `05839_insert_too_many_parts_gate_view_reading_from_view`
compares the direct and the forwarded inserts, and checks that the limit of a
view reading from the target is still enforced.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was conflicting) and pushed 4 commits:

  • 316fcba - the merge. InsertDependenciesBuilder got functions from both sides next to its constructor; both sets are kept, and the constructor takes insert_start_gates_ and then preserve_input_order from Preserve input order for order-sensitive insert destinations #128833.
  • 001ede8 - the arm_tidy builds failed only on modernize-use-nodiscard (enabled on master meanwhile) for three new const accessors; marked them [[nodiscard]].
  • 24740e3 - two semantic conflicts with Preserve input order for order-sensitive insert destinations #128833, found by running the tests on the merged tree. insertReachesSerialDestination now prunes a dependent view with a dropped target under ignore_materialized_views_with_dropped_target_table / materialized_views_ignore_errors, as the other hidden-graph probes of this PR do (04825_insert_quorum_ignored_broken_view_fanout).
  • 104d2e9 - the review finding about a directly inserted materialized view, with a new test.

One point needs a human decision. 05837_distributed_insert_select_preserves_order from #128833 pins four DistributedSinks for an INSERT SELECT from a multi-stream source into a Distributed table. This PR keeps such an insert single-stream: addInsertToSelectPipeline applies insertDeduplicationNeedsSingleStream (storageForwardsInsertToSeparateContext) and serial_hidden_views (forwardedInsertHidesDependentView, with the default parallel_view_processing = 0), and both fail closed for Distributed. I kept the behaviour of this PR and changed the reference of that test from 4 to 1, which gives up the write parallelism of a multi-threaded INSERT SELECT into a Distributed table. If that parallelism should stay, both guards need a carve-out for a directly targeted Distributed table instead.

Locally, on a build of the merged tree: the tests of this PR, the four originally flaky tests, 04826_parallel_insert_sinks_too_many_parts_self_race and the insert-related tests added on master since the previous merge - 102 tests, all passed. Tests needing S3/Azure were not run.

alexey-milovidov and others added 2 commits November 24, 2026 03:21
…aving deterministically

The test failed in the Fast test with "New test runs too long (> 15s)":
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=113045&sha=104d2e9f1bef348d8b0ce7e6052608ccd408af0a&name_0=PR&name_1=Fast%20test
#113045

Query B produced its two blocks from two branches of a `UNION ALL`. Under load
the query was granted a single thread, the sleeping branch ran first, and the
one-row block reached the `Buffer` table only together with the three-row one,
1.5 seconds later. The test then never observed that row in the buffer and
polled until its 15 second deadline before taking the fallback path.

Now query B reads the two blocks from the two parts of a source table in a
single stream, so the one-row block comes first regardless of the number of
threads, and the wait ends as soon as B finishes instead of running to the
deadline. Without the fix of this pull request the test now fails with
`Too many parts` on every run, and it takes about 3 seconds.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
StoragePtr tryGetDistributedLocalTarget(const StorageDistributed & distributed, const ContextPtr & context)
{
if (!context->getSettingsRef()[Setting::prefer_localhost_replica] || distributed.getRemoteTableName().empty()
|| distributed.getCluster()->getLocalShardCount() == 0)

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.

[Major] Honor insert_shard_id when collecting local checks

The cluster-wide local-shard count can be nonzero even when the selected shard is remote. For a cluster with local shard 1 and remote shard 2, wrap its Distributed table in an Alias, fill the local destination to parts_to_throw_insert, and insert through the alias with insert_shard_id = 2, prefer_localhost_replica = 1.

This helper still returns the local destination, so AliasSink::onStart enforces its deferred check and throws TOO_MANY_PARTS. The actual nested DistributedSink::writeSync restricts its jobs to shard 2 (DistributedSink.cpp:612–615), so it never writes locally; the equivalent direct insert into the Distributed table succeeds.

Please restrict this probe to the shards selected by insert_shard_id and cover remote-only routing through a forwarding sink. This is source-traced; I could not run a server reproduction here.

if (!target || !canInsertIntoAnyColumn(*target, view_context))
continue;

if (const auto * merge_tree = castStorage<MergeTreeData>(target, DeferredTable::Load).get())

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.

[Major] Collect isolated checks throughout an ignored view cascade

With ignore_errors = true, this branch stops at a target such as Null, although the actual nested builder also executes that target's dependent views. Their checks are consequently missing from the shared decision.

The existing 05812_insert_too_many_parts_gate_definer_ignore_errors_cascade topology demonstrates the gap if its outer insert uses materialized_views_ignore_errors = 1: a loose direct branch writes to dst, while another branch follows Alias(hidden) -> strict definer view -> Null -> SQL SECURITY NONE view -> dst. If the direct sink accepts the gate first, the final hidden sink registers its isolated check after the decision. No outcome was registered for that final view, so InsertStartGate::addCheck drops the callback and the hidden rows are written despite its parts_to_throw_insert = 1 limit.

Please walk ordinary dependent-view cascades under the same nested error policy and preregister each sink's isolated outcome. Extend 05812 to assert that the hidden rows stay absent with error ignoring enabled. This is a current-code trace, without a server reproduction.

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

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants