Repository navigation
Perform the Too many parts check once per INSERT query - #113045
alexey-milovidov wants to merge 149 commits into
Conversation
`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
|
Workflow [PR], commit [187dbba] Summary: ❌
AI ReviewSummaryThe PR shares pre-write Findings
Tests
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 VerdictStatus: Honor shard selection, preregister cascading isolated checks, and preserve matching pending isolated outcomes during borrowed flush decisions, with focused regression coverage. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes60 object files changed (+458.53 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units356 translation units recompiled, 2937 s compile time in total, 356 of them have a recent master baseline. |
…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]>
…-parts-check-once
…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]>
# 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]>
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]>
…`05617` Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…-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]>
…-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]>
|
🕵 Merged
One point needs a human decision. Locally, on a build of the merged tree: the tests of this PR, the four originally flaky tests, |
…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) |
There was a problem hiding this comment.
[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()) |
There was a problem hiding this comment.
[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.
Related: #109000
MergeTreeSink::onStartandReplicatedMergeTreeSink::onStartperform theparts_to_throw_insert/parts_to_delay_insertcheck, andonStartis the only place where anINSERTmay be rejected withTOO_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
INSERTwrites through up tomax_insert_threadssinks running in parallel, and every one of them runsonStart(ExceptionKeepingTransform::preparereturnsReadyfor theStartstage of every sink, whether or not it ever receives a chunk). TheonStartcalls 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. TheINSERTfails withTOO_MANY_PARTSeven 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_threadsinInsertDependenciesBuilder) has been in place for theINSERT SELECTpath since031a9d5a528, and the default ofmax_insert_threadschanged from1to0(auto, the number of CPU cores) in 26.8 - so anINSERT SELECTinto a MergeTree table could already be rejected by a stream that counted a part the query had written itself. Before #109000 the plain-INSERTpipeline passed a hardcoded/*max_insert_threads*/ 1to the builder and always had a single sink, which is why the flaky tests below - all of them plainINSERT ... VALUES- only started failing when that changed.The check is now shared by all the sinks of one query: the first sink to reach
onStartruns 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: theparts_to_delay_insertbackpressure is applied by every sink before each of its blocks, including the first one, so a parallelINSERTkeeps 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.InsertDependenciesBuildercreates the registry and takes each sink's gate from it next tosetRuntimeData/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. AnAliasdestination forwards the write through a nestedINSERTper parallel branch and the real check runs inside those nested inserts, soAliasSinkreceives the registry and threads it into the nestedInterpreterInsertQuery, whose builder inherits it instead of creating its own.DistributedandBufferdestinations are always kept single-stream by #109000, so their own pre-write checks are unaffected - but their in-query nestedINSERTs into the underlying tables are not. The local writes of aDistributeddestination run through nestedINSERTs into the underlying table: one per incoming block on thewriteToLocalpath (the direct local write of a background-send insert withprefer_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-blockINSERTcounted the part the first block had already committed on the local target and failed the query mid-way;DistributedSinkalso receives the registry and threads it into both nestedINSERTpaths (the new test04826_insert_distributed_local_too_many_parts_gatecovers a two-block insert into a local target withparts_to_throw_insert = 1on both paths). Theparallel_distributed_insert_selectrewrite of anINSERT ... SELECTbetween twoDistributedtables writes the local shards the same way - one nestedInterpreterInsertQueryper destination shard this server belongs to - and a server can be local for several destination shards of one cluster, so those sibling nestedINSERTs write into the same underlying table and now share one registry as well (the new test04847_insert_parallel_distributed_insert_select_local_shardscovers a two-local-shard cluster withparts_to_throw_insert = 1on the target, plus the non-parallel quorum variant of the same topology). The gates can only be shared by nestedINSERTs running in this process. Withprefer_localhost_replica = 0a local shard is deliberately routed back to this server throughRemoteQueryExecutor(or a remote writing job of the foreground fan-out), and each such write is an independent TCPINSERTwith 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 (aDistributedtable spanning two local shards could start failing withACCESS_DENIEDfor 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 aBufferdestination run through nestedINSERTs 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-blockINSERTused to count the part an earlier one had committed on the destination;BufferSinkalso receives the registry and threads it throughflushBuffer/writeBlockToDestinationinto those nestedINSERTs, while the background flush keeps creating fresh gates per flush as before (the new test04827_insert_buffer_direct_write_too_many_parts_gatecovers both paths withparts_to_throw_insert = 1on 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 nestedINSERTruns with a group registry whose gates are shared with all of them, so a query whose buffered rows were flushed by someone else'sINSERTdoes not re-run the check later and count the part holding its own rows (the new test05054_insert_buffer_mixed_queries_flush_gatecovers 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 test05223_insert_buffer_failed_flush_retry_gatecovers 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 aBufferare 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 test05055_insert_buffer_concurrent_shard_flush_gatepins that topology: the rows of one INSERT are spread over two shards whose parallel flushes write a part each into a destination withparts_to_throw_insert = 1). The participants of a group write are not necessarily the registries of the queries themselves: when the destination of aBufferis anotherBuffer, 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 test05153_insert_chained_buffer_flush_gatecovers a two-buffer chain in front of a destination withparts_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 test05023_insert_buffer_preexisting_rows_too_many_parts_gatecovers a query arriving at a buffer that already holds a row of an earlier one). ATimeSeriesdestination forwards the write through nestedINSERTs into its inner target tables, soTimeSeriesSinkalso receives the registry and threads it into them, sharing the check across sibling branches converging on the sameTimeSeriestable. Those nested pipelines are now created inonStartrather than in the sink's constructor: the registry reaches the sink only afterStorageTimeSeries::writehas 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 forWindowView(PushingToWindowViewSinkthreading the registry intoStorageWindowView::writeIntoWindowView), but theWINDOW VIEWfeature has been removed onmasterin 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 >= 2or'auto', withinsert_quorum_parallel = 0) permits a single in-flight quorum part per table, which is why itsmax_insert_threadsfan-out is kept single-stream. But the single sink stream is still duplicated into one branch per dependent materialized view, and withparallel_view_processing = 1those branches ran concurrently - two views converging on oneReplicatedMergeTreetarget raced two in-flight quorum parts of oneINSERTagainst each other, so a sibling branch could fail withUNSATISFIED_QUORUM_FOR_PREVIOUS_WRITEor conflict on the/quorum/statusnode. The serialization such an insert needs is derived from the collected sink graph, not from the settings alone (InsertDependenciesBuilder::computeQuorumStreamRequirements): only writes reaching aReplicatedMergeTreetable are quorum writes, and only two of them racing on the same table conflict. TheINSERT SELECTfan-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 reachableReplicatedMergeTreetarget, or a forwarding storage (anAlias, aDistributed, aBuffer, aTimeSeries) that hides its physical destination, in which case the probe fails closed. An insert whose write graph never reaches a replicated table keeps itsmax_insert_threadsfan-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 byignore_materialized_views_with_dropped_target_table- never creates a sink, so it does not force the serialization (the new test04825_insert_quorum_ignored_broken_view_fanoutcovers a broken ignored view attached to a plainMergeTreedestination). The dependent views of such an insert are pushed sequentially only when two branches converge on the same replicated table (a sequential branch blocks incommitPartuntil 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/statusnode. AnAliasdestination hides its target's views behind the nestedINSERTits sink runs, and that nestedINSERTobserves the same settings and derives the same requirements. The new test04828_insert_timeseries_too_many_parts_gateexercises non-parallel quorum inserts through two views converging on oneTimeSeriestable whose data table is replicated - the shape that racedUNSATISFIED_QUORUM_FOR_PREVIOUS_WRITEbeforeTimeSerieswas included in the hidden-target probes. The new test04817_insert_quorum_sequential_dependent_viewscovers theINSERT SELECTfan-out deterministically viaEXPLAIN PIPELINEand exercises quorum inserts through two materialized views converging on one replicated target withparallel_view_processing = 1; the new test04823_insert_quorum_graph_derived_serializationcovers the fan-out kept for a plainMergeTreedestination, 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 foregroundDistributedinsert are nestedINSERTs that can each commit a quorum part into the same local target through different shards, soDistributedSinkcompletes them one-by-one for a non-parallel quorum insert (the new test04907_insert_distributed_local_quorum_sequentialcovers 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 plainMergeTreetarget.parallel_view_processing = 0gets the same treatment on theINSERT SELECTpath:buildInsertPipelinealready kept a plainINSERTsingle-stream when the destination is a forwarding storage that hides its target's dependent-view graph behind the nestedINSERTits sinks run (serial_hidden_views), butaddInsertToSelectPipelinestill passed the rawmax_insert_threadsto the builder - which sees no views for such a destination - so anINSERT SELECTinto anAliasfanned out into severalAliasSinks whose hidden materialized views ran concurrently across sibling branches despite the setting. The guard is now mirrored there; anAliasin front of a target with dependent views is the only topology whose fan-out survived to that point, sinceDistributed,BufferandTimeSeriesdestinations are already collapsed to one stream by the builder'ssupportsParallelInsertcheck. The new test04869_insert_select_alias_hidden_views_serialcovers the single stream with a hidden dependent view, and the fan-out kept both without dependent views and withparallel_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 pruningcollectAllDependenciesapplies to the executable graph - so a stale dependency does not force anINSERTinto anAliassingle-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
masteron 2026-08-01, right after #109000 was merged, each of them rejecting anINSERTthat counts the part it has written itself:02458_relax_too_many_partsINSERT INTO test VALUES (6, 'a')parts_to_throw_insert = 302280_add_query_level_settingsINSERT INTO table_for_alter VALUES (1, '1')into an empty tableparts_to_throw_insert = 100980_merge_alter_settingsINSERT INTO table_for_alter VALUES (1, '1')into an empty tableparts_to_throw_insert = 102015_async_inserts_5INSERT INTO async_inserts VALUESparts_to_throw_insert = 1The server log of the
02458_relax_too_many_partsfailure below shows the mechanism directly: 26 sinks are created for the query, its partall_5_5_0is renamed into place at01:46:59.792095, and the query is rejected withToo many parts (3 ...)at01: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_querycovers both halves: anINSERTwith a largemax_insert_threadsthat brings a table from one part up toparts_to_throw_insert = 2has to be accepted, andProfileEvents['DelayedInserts']of a single-rowINSERThas 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 anAlias.TimeSeriesis also classified as a forwarding storage in the deduplication-safety probes (storageDeduplicatesBlocksOnInsert,storageRebuildsDeduplicationIdsOnInsert,forwardedInsertReachesDependentView,forwardedInsertHidesDependentView,forwardedInsertHidesDependentViewForwardingToSeparateContext), sinceTimeSeriesSinkforwards a plain block into its nestedINSERTs and drops the outer chunk'sDeduplicationInfo. This is fail-close classification only, not a reachable fix:StorageTimeSeriesdoes not overrideIStorage::supportsParallelInsert, so an insert whose graph reaches aTimeSeriestable is already single-stream and the probes cannot change the outcome - and writes arriving throughTimeSeriesSinkturn out not to deduplicate on the inner tables at all, so no rows are lost when two views converge on oneTimeSeriestable. The clauses keep the classification correct ifStorageTimeSeriesever starts supporting parallel inserts. The new test04846_insert_mv_timeseries_dedup_parallel_viewspins the no-row-loss half end to end: two identical materialized views converging on oneTimeSeriestable with a deduplicating data table (non_replicated_deduplication_window) underparallel_view_processing = 1land 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
INSERTinto that table (into any of its columns): the check runs before the nestedINSERTchecks the access rights, and a user who may only insert into the forwarding table must getACCESS_DENIEDrather than aTOO_MANY_PARTSthat describes the parts of the protected target (the new test05454_insert_too_many_parts_gate_hidden_target_access). Second, undermaterialized_views_ignore_errorsthe 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 anOPTIMIZEor background flush of aBufferthat holds the query's rows decides anew with the buffer's own limits (both covered by the new test05453_insert_too_many_parts_gate_buffer_optimize_and_ignored_views).Relation to #114016
While this pull request was open, #114016 landed on
masterwith a narrower fix for the same root cause: it evaluates the check on the query thread in theMergeTreeSink/ReplicatedMergeTreeSinkconstructor and rethrows it fromonStart. Mergingmasterresolves that in favour of the shared gate, which subsumes it - a sink whoseonStartruns 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 nestedINSERTs ofAlias,Distributed,BufferandTimeSeries. Everything else from #114016 is kept, including themerge_tree_sink_on_start_random_sleepfailpoint and its test04826_parallel_insert_sinks_too_many_parts_self_race, which the shared gate also makes pass.Related: #114016
Relation to #128833
#128833 landed on
masterwhile this pull request was open and added a probe for serial destinations hidden behind anAlias(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 underignore_materialized_views_with_dropped_target_table/materialized_views_ignore_errorslike the other hidden-graph probes here, so04825_insert_quorum_ignored_broken_view_fanoutkeeps its fan-out through anAlias. And its test05837_distributed_insert_select_preserves_orderexpected fourDistributedSinks for anINSERT SELECTfrom a multi-stream source: since this pull request applies the single-stream guards of a plainINSERT(insertDeduplicationNeedsSingleStream,serial_hidden_views) toINSERT SELECTtoo, and aDistributeddestination 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 thatDistributeddestinations are already collapsed to one stream by thesupportsParallelInsertcheck is not accurate forINSERT SELECT: it is these guards that collapse them.)Related: #128833
A
MaterializedViewthat 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 anINSERTforwarded into such a view through anAliasor aBufferbehaves like the direct one (the new test05839_insert_too_many_parts_gate_view_reading_from_view).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a spurious
TOO_MANY_PARTSerror for anINSERTexecuted withmax_insert_threadsgreater than one. TheToo many partscheck 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]