Skip to content

Do not count an insert's own parts in the "too many parts" check - #114016

Merged
alexey-milovidov merged 2 commits into
masterfrom
fix/parallel-insert-sink-self-too-many-parts
Aug 9, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
fix/parallel-insert-sink-self-too-many-parts

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • CI Fix or improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Fix a spurious TOO_MANY_PARTS rejection of a parallel INSERT that counted the parts committed by the insert's own sibling sinks.

Since max_insert_threads started to apply to plain INSERTs (#109000), an insert fans out to multiple parallel MergeTreeSinks (the default max_insert_threads = 0 resolves to the number of cores, so even a single-row INSERT VALUES creates one sink per core). Each sink ran the "too many parts" throw check in onStart, and nothing guarantees that all onStarts complete before a sibling sink commits its part: a sink whose onStart ran late — e.g. its worker thread was preempted on a loaded machine — counted the parts committed by its sibling sinks and spuriously rejected the very insert that wrote them. This made 02458_relax_too_many_parts flaky fleet-wide (~5–11 failures/day across unrelated PRs since 2026-08-01), and it is a correctness regression for any workload inserting near parts_to_throw_insert.

The fix moves the throw check to StorageMergeTree::write / StorageReplicatedMergeTree::write, which run on the query thread while the insert pipeline is being built — before any sink of the query executes — so the check never sees the query's own parts. The sinks' onStart keeps the delay-under-pressure behavior (allow_throw = false), where the parallel streams sleep concurrently rather than one after another on the query thread (hence the new allow_delay = false mode of delayInsertOrThrowIfNeeded for the query-thread check).

Verification: a random 0–3 ms sleep at the top of the sinks' onStart (now behind the new merge_tree_sink_on_start_random_sleep failpoint) makes the race deterministic — the first section of 02458_relax_too_many_parts failed 40/40 before the fix with the exact fleet error signature (Too many parts (3 with average size of 435.00 B)) and passes 40/40 with it. The new test 04826_parallel_insert_sinks_too_many_parts_self_race uses that failpoint: it fails 5/5 with the pre-fix behavior and passes 5/5 with the fix, and the legitimate TOO_MANY_PARTS of the over-threshold insert still throws. Related tests (02458_relax_too_many_parts, 00940_max_parts_in_total, 01603_insert_select_too_many_parts, 01709/01809 inactive-parts tests, 02280_add_query_level_settings, 04202_move_partition_to_table_too_many_parts, 04492_max_insert_threads_auto_default) pass locally.

CI failure example: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113984&sha=ea086a58d6d2f255bbbde02f94e35ab84c4a64c7&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29

Closes: #114015
Related: #109000

Since `max_insert_threads` started to apply to plain `INSERT`s (#109000),
an insert fans out to multiple parallel `MergeTreeSink`s (the default
`max_insert_threads = 0` resolves to the number of cores). Each sink ran
the "too many parts" throw check in `onStart`, and nothing guarantees all
`onStart`s complete before a sibling sink commits its part: a sink whose
`onStart` ran late (e.g. its worker thread was preempted on a loaded
machine) counted the parts committed by its sibling sinks and spuriously
rejected with `TOO_MANY_PARTS` the very insert that wrote them. This made
`02458_relax_too_many_parts` flaky fleet-wide (~5-11 failures/day since
2026-08-01), e.g.:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113984&sha=ea086a58d6d2f255bbbde02f94e35ab84c4a64c7&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
on #113984

Move the throw check to `StorageMergeTree::write` / `StorageReplicatedMergeTree::write`,
which run on the query thread while the insert pipeline is being built, so
the check never sees the query's own parts. The sinks' `onStart` keeps the
delay-under-pressure behavior (`allow_throw = false`), where the parallel
streams sleep concurrently; the new `allow_delay = false` mode of
`delayInsertOrThrowIfNeeded` avoids sleeping once per sink stream on the
query thread.

Add the `merge_tree_sink_on_start_random_sleep` failpoint, which skews the
sinks' start times, making the race deterministic: with the failpoint, the
new test `04826_parallel_insert_sinks_too_many_parts_self_race` fails 5/5
with the pre-fix behavior and passes 5/5 with the fix.

Closes: #114015

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

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab57d28]

Summary: ✅


AI Review

Summary

This PR fixes the parallel-insert self-race where a late-starting MergeTreeSink / ReplicatedMergeTreeSink could count parts already committed by its sibling sinks and spuriously throw TOO_MANY_PARTS. The race fix itself looks right, but the constructor-side check is still effectful and now overcounts rejected inserts for parallel fan-out, so I would not approve the PR in its current form.

PR Metadata
  • Changelog category is not correct for the actual change. This is a user-visible correctness fix, not a CI-only improvement.
  • Replace the category with Bug Fix.
  • Under Bug Fix, a Changelog entry is required; the current entry is specific and can stay as-is.
Findings
⚠️ Majors
  • [src/Storages/MergeTree/MergeTreeSink.cpp:97] delayInsertOrThrowIfNeeded increments ProfileEvents::RejectedInserts before throwing. Running it in every sink constructor means one rejected plain INSERT with max_insert_threads = auto(N) now records N rejected inserts in system.events / query_metric_log, even though only one input block was rejected. ReplicatedMergeTreeSink mirrors the same bug. Suggested fix: evaluate the throw result once per table write and fan that cached result out to sibling sinks, or make the constructor path side-effect-free and increment the metric only where a single sink actually rethrows.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: stop overcounting ProfileEvents::RejectedInserts for parallel inserts, and change the Changelog category to Bug Fix.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.90% +0.00%

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

Full report · Diff report

Moving the "too many parts" check from the sink's onStart to
StorageMergeTree::write / StorageReplicatedMergeTree::write changed where
the error surfaces: at insert chain construction instead of during
execution. That broke two tests in the Fast test CI job:

- 00633_materialized_view_and_too_many_parts_zookeeper: with
  materialized_views_ignore_errors = 1, a TOO_MANY_PARTS error from a
  materialized view must be swallowed and logged in system.query_views_log,
  but only errors thrown by an executing sink are handled that way - an
  error thrown while building the pushing-to-views chain failed the whole
  INSERT with return code 252.
- 02456_async_inserts_logs: a failed async insert flush logged 0 rows in
  system.asynchronous_insert_log instead of the actual row count, because
  the flush pipeline failed before execution started.

Keep the evaluation of the check on the query thread, at sink construction
(all sinks of an insert are constructed before the pipeline executes, so
the check still never sees the query's own parts), but capture the
exception and rethrow it in onStart, so it surfaces during execution
exactly where it did before.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114016&sha=8ccd24f820675bc704e2f9997dc53212f7e64f68&name_0=PR&name_1=Fast%20test
PR: #114016

Co-Authored-By: Claude Fable 5 <[email protected]>
/// thrown by an executing sink, not errors thrown while the insert chain is being built).
try
{
storage.delayInsertOrThrowIfNeeded(nullptr, context, /*allow_throw=*/ true, /*allow_delay=*/ false);

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.

delayInsertOrThrowIfNeeded is not a pure predicate: it increments ProfileEvent::RejectedInserts before it throws. Calling it in every sink constructor means one rejected plain INSERT with max_insert_threads = auto(N) now records N rejected inserts in system.events / query_metric_log, even though there is still only one rejected input block and N - 1 branches may stay empty. The same effect is mirrored in ReplicatedMergeTreeSink.

Can we evaluate the throw condition once per table write and fan that cached result out to sibling sinks, or at least move the metric bump to the single place that actually rethrows?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Good catch, confirmed and fixed in #114107 (this PR had already merged).

Measured it: a rejected INSERT with max_insert_threads = 16 recorded 16 RejectedInserts. The four throw paths of delayInsertOrThrowIfNeeded now go through MergeTreeData::countRejectedInsert, which bumps the event at most once per query (memoized on query_id + the address of the query's QueryStatus, so a retry reusing the same query_id is still counted). The new test 04836_rejected_inserts_counted_once_per_insert reads the rejected query's profile events from the query log and prints 16 without the change, 1 with it.

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ab57d28b8 with master 9b6a2d734 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 5bf49d370; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.65 MiB 687.63 MiB -3.02 MiB (-0.44%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

238 translation units recompiled, 2228 s compile time in total, 230 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/hive-metastore-cmake/__/hive-metastore/ThriftHiveMetastore.cpp: 11.0 s

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok, convinced.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
Merged via the queue into master with commit 650387c Aug 9, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/parallel-insert-sink-self-too-many-parts branch August 9, 2026 23:20
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
alexey-milovidov added a commit that referenced this pull request Aug 10, 2026
…-parts-check-once

Conflict resolution: master merged #114016, which fixes the same spurious
`TOO_MANY_PARTS` rejection by evaluating the check on the query thread in the
`MergeTreeSink` / `ReplicatedMergeTreeSink` constructor and rethrowing it from
`onStart`. This branch fixes it with the more general shared-gate mechanism:
the check runs in `onStart` under a per-query, per-destination-table gate
(`InsertStartGates`), so it runs exactly once no matter when a sink is created.

The gate subsumes the constructor placement - 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 `INSERT`s of `Alias`, `Distributed` (local writes), `Buffer`
(direct / threshold flushes), `WindowView` and `TimeSeries`. Therefore the
constructor check and the `too_many_parts_exception` member are dropped in
favour of `runOnceBeforeFirstWrite`.

Everything else from #114016 is kept: the `allow_delay` parameter of
`delayInsertOrThrowIfNeeded` (both sides added it identically), 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. The `parts_to_delay_insert` backpressure stays per block in
`consume`, as it was on this branch.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test 02458_relax_too_many_parts: a parallel INSERT can spuriously throw TOO_MANY_PARTS due to its own parts

2 participants