Repository navigation
Support max_insert_threads for plain INSERTs - #109000
Conversation
Make `max_insert_threads` parallelize the writing side of a plain `INSERT` (data sent from `clickhouse-client` or over the HTTP interface), not only `INSERT SELECT`. The input is always read and parsed as a single stream, so previously the whole insert pipeline (squashing, writing to the destination table and dependent materialized views) ran in a single thread regardless of `max_insert_threads`. Now `buildInsertPipeline` builds `max_insert_threads` parallel sink chains and inserts a `ResizeProcessor` (1 -> N) after the single-stream head (counting, deduplication info, planning of squashing), mirroring the existing `INSERT SELECT` path in `addInsertToSelectPipeline`. For the default `max_insert_threads = 0` (-> 1) the pipeline is byte-for-byte unchanged. Parallelism is gated by `InsertDependenciesBuilder` (only when all destinations support parallel inserts) and disabled for asynchronous inserts, which have their own batching/flush mechanism. Closes: #108997 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [156b630] Summary: ✅
AI ReviewSummaryThis PR parallelizes the write side of a plain synchronous Findings❌ Blockers
Final Verdict❌ Request changes. |
Benchmark: is it actually faster?Yes. Setup: 96-core machine, 20M rows piped over HTTP into CREATE TABLE bench (id UInt64, val1 UInt32, val2 UInt32, name String, amount Float64, ts DateTime)
ENGINE = MergeTree ORDER BY (val1, val2, name) -- all columns CODEC(ZSTD(3))so the write side (sort + ZSTD + part write) is genuinely CPU-heavy. Metric is the server-side Before (master) —
After (this PR) — the writing side scales with
(That's ~4 → 30 M rows/s for Takeaways:
Verified via |
Add a shell-script performance test that measures the writing side of a plain INSERT (data streamed in, not INSERT SELECT) with `max_insert_threads > 1`. It is self-contained via `clickhouse-local`: data is generated as `Native` and piped into a `CREATE` + direct `INSERT` (the throwaway temporary directory of `clickhouse-local` removes the table on exit, so no explicit `DROP` is needed). A compound sort key plus `ZSTD` codecs make the write side expensive so the parallelization of the sinks is visible; the `Native` input keeps parsing cheap. Before this pull request `max_insert_threads` had no effect on such inserts, so the reference build runs the whole pipeline single-threaded; measured locally the patched build is ~3x faster (10M rows, `max_insert_threads = 8`). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Added an in-repo performance test so the improvement is measured automatically by the CI performance-comparison job, not just in the one-off benchmark above: It uses the shell-script perf-query support (
Measured locally with the reference (master) vs patched binary, 10M rows: ~2.8s → ~0.86s (~3.3×), stable across runs. The perf-comparison job on this PR compares master (no effect from |
|
📊 Cloud Performance Report ✅ AI verdict: This PR changes only the INSERT write-side pipeline: it parallelizes plain INSERTs under max_insert_threads and adds gating that keeps the write single-stream where a deduplication, dependent-materialized-view, quorum, or separate-context (Buffer/Distributed) hazard exists. It does not touch any SELECT execution path. All three flagged queries are read-only SELECTs (ClickBench Q4 -13.9% and Q15 -13.0% flagged as improvements, TPC-H Q4 +5.2% held within the variance band), so none of these deltas can be attributed to the change; the two improvements are downgraded to noise and the TPC-H suppression stands. No real per-query performance impact expected from this PR. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (1 of 22)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
With `use_strict_insert_block_limits`, the parallel plain-`INSERT` path added by this PR stamps the deduplication info (source block number) with a per-stream `AddDeduplicationInfoTransform` *after* the `ResizeProcessor` fan-out, so every parallel branch restarts its block numbering from zero. When a non-empty `insert_deduplication_token` is set, the dedup id is `token` + source block number and does not depend on the block contents, so different branches of a single `INSERT` produce identical ids. `MergeTreeSink` then treats those blocks as duplicates and skips them, silently dropping rows of a single parallel `INSERT`. Keep such inserts single-stream (as before the PR), so the source block numbering stays global. Without a token the ids are redefined from the data hash (`RedefineDeduplicationInfoWithDataHashTransform`), so they stay unique across branches and parallelism is preserved. Reported by the AI review on #109000 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This test inserts a Parquet file into a `Memory` table with a plain `INSERT` and checks the md5 of `SELECT *` (order-dependent). Since this PR parallelizes the writing side of a plain `INSERT`, with a randomized `max_insert_threads > 1` the `Memory` table receives blocks from several parallel streams in a non-deterministic order, changing the md5 and making the test flaky (result differs with reference). The test exercises the Parquet reader, not insert parallelism, so pin `max_insert_threads = 1` on the `INSERT` to keep the row order (and hence the reference md5) deterministic under settings randomization. #109000 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed two follow-up commits ( 1. Dedup collision with strict block limits (AI-review Major) — fixed in
|
The strict tokenized plain `INSERT` fallback added in the previous commit (keeping such inserts single-stream to avoid deduplication id collisions across parallel branches) had no dedicated coverage: the existing `04492_max_insert_threads_for_direct_insert` test only exercises plain `max_insert_threads` without `use_strict_insert_block_limits` or a non-empty `insert_deduplication_token`, so the guard could be removed while the current tests still pass, reintroducing silent row loss. Add `04493_max_insert_threads_strict_tokenized_dedup`, which asserts that with `use_strict_insert_block_limits = 1` and a non-empty `insert_deduplication_token` the writing side of a plain `INSERT` falls back to a single insert stream (one `MergeTreeSink`), while the same strict `INSERT` without a token still fans out to several streams, and that all rows of a many-block streamed `INSERT` arrive under the strict tokenized combination. Deduplication is enabled on the table via `non_replicated_deduplication_window` so that removing the fallback would collide per-stream source block numbers and drop rows, failing the test. Addresses the AI review request on #109000 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Addressed the AI review "Request changes" (regression test for the strict tokenized fallback).
The |
|
I checked the AI-review "Request changes" finding (strict tokenless dedup collision) against the current head, and it is a real, silent row-loss bug. The in-code comment's claim that "without a token the ids are redefined from the data hash, so they stay unique" holds only for Root cause. In the strict path the per-branch
Because the default Scope. Only the strict path ( Fix direction. The Suggested regression test: strict, tokenless, |
…isions The strict single-stream fallback added in `54dbb33a08a` only covered a non-empty `insert_deduplication_token`, but a token-less strict `INSERT` can also lose rows when the writing side fans out across `max_insert_threads`. In the strict path the per-branch `AddDeduplicationInfoTransform` restarts its source block number from zero in every parallel branch. Under the default `insert_deduplication_version = new_unified_hash` (and `compatible_double_hashes`) a synchronous token-less block id is `hash(data_hash : source_block_number)`, so two identical squashed blocks that land on different branches both get source number 0 and the same data hash - an identical id - which `MergeTreeSink` / `ReplicatedMergeTreeSink` treat as a duplicate and skip, silently dropping rows of a single `INSERT`. Only `old_separate_hashes` derives a token-less id from the data hash alone (dropping the source number) and can safely fan out. Extend the guard to keep a strict `INSERT` single-stream whenever the id can fold in the source block number, i.e. for any non-empty token or for `insert_deduplication_version != old_separate_hashes`. The non-strict path stamps the source block number in the single-stream head before the fan-out, so the main `max_insert_threads` win is unaffected. Add `04494_max_insert_threads_strict_tokenless_dedup` covering the token-less `new_unified_hash` case (single-stream fallback via `EXPLAIN PIPELINE` and all rows arriving for a many-block streamed `INSERT`), and adjust `04493_max_insert_threads_strict_tokenized_dedup` whose token-less assertion now exercises the gating on `use_strict_insert_block_limits`. This addresses the AI-review "Request changes" finding on `InterpreterInsertQuery.cpp`, confirmed as a real silent row-loss bug. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed Fix
Rationale (default Tests
The inline thread on |
|
The What failed. The diff is a single patch-part name, not a data difference: Only the merge level differs ( Not reproducible. The CI harness re-ran the test 22 times with the same randomized settings and all 22 passed: History. The test has flaked on Why the PR cannot cause it. The test's only insert is Re-running the failed jobs to clear the transient reds. The only remaining public reds are this and the chronic |
This is false. |
`max_insert_threads` parallelizes the writing side of a plain `INSERT` by resizing the pipeline to several sink streams. When `parallel_view_processing` is enabled this also fans out the dependent materialized-view chains, and each branch gets its own per-stream `UpdateDeduplicationInfoWithViewIDTransform` whose `view_block_number` restarts from zero. Under the legacy deduplication hash modes (`old_separate_hashes` / `compatible_double_hashes`) the VIEW-level block id is `hash(data_hash : view_id : view_block_number)` and drops the (global) source block number, so two identical source blocks landing on different branches produce the same materialized-view block id and one of them is skipped as a duplicate - silently dropping rows of a single parallel `INSERT`. Keep the dependent-MV deduplication path single-stream in that case (`InsertDependenciesBuilder` now keeps its sink stream size at 1 when views are involved, `deduplicate_blocks_in_dependent_materialized_views` is set, and the deduplication version is not `new_unified_hash`). Under `new_unified_hash` the VIEW id also folds in the global source block number, so identical blocks on different branches stay distinct and the fan-out is kept. Addresses review: #109000 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… INSERTs Integration test that exercises the single-stream fallback for the dependent materialized-view deduplication path under the legacy hash modes. Because `insert_deduplication_version` is a server setting, the test uses three nodes (`old_separate_hashes`, `compatible_double_hashes`, `new_unified_hash`). For each it: - asserts via `EXPLAIN PIPELINE` that a plain `INSERT` into a table with a dependent materialized view keeps a single `MergeTreeSink` pair (source + MV target) under the legacy modes, while `new_unified_hash` fans out to `max_insert_threads` streams; - asserts that a single plain `INSERT` of many identical blocks does not lose rows on the MV target (which it would under the legacy modes if the per-branch view block numbering collided across parallel streams). Addresses review: #109000 (comment) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Since `max_insert_threads` started to apply to plain `INSERT`s (ClickHouse#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 ClickHouse#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: ClickHouse#114015 Co-Authored-By: Claude Fable 5 <[email protected]>
…1622) Since ClickHouse 26.8, a plain INSERT runs with max_insert_threads = all cores (ClickHouse/ClickHouse#109000). The bulk Native load saturates the machine, so background merges barely progress during the load: the load itself finishes ~2x faster (ssb: 737s vs 1569s on 26.7.1.1315 -- exactly the 87 GB / 125 MB/s gp3 throughput floor), and the deferred merge work (~1.7x write amplification) lands in the query phase, where it competes with the queries for CPU, disk bandwidth and page cache on the c7a.4xlarge (16 vCPU, 32 GB). The 2026-08-26 master (26.9.1.170) results show the resulting timeline: mgbench (benchmarked first) is mildly elevated, ssb (second, and the largest single-INSERT dataset) degrades catastrophically with the telltale tapering within and across queries (Q1 hot 0.064s -> 8.4s, Q7 1.5s -> 32s with successive tries 40/45/39/35/32s, while Q8-Q13 are normal), and hits (third) is consistently *faster* on master -- the genuine engine speedups, visible once the merge storm has ended: https://benchmark.clickhouse.com/versions/#version=-&dataset=+sb&metric=hot&queries=- Wait for the server-wide system.merges to drain (up to MERGE_SETTLE_TIMEOUT, default 1 h) before the query phase, so every version is measured against the same, settled table state -- the state the old single-threaded loads reached implicitly within the load window. This also stabilizes the reported data_size (measured on settled parts). Co-authored-by: Claude Fable 5 <[email protected]>
…cord `Changelog-deleted-entry:` stored a flat pull request -> whole bullet snapshot, but a merge (skill section 7) puts several pull requests on one bullet — 74 of them in the current `CHANGELOG.md`. Two things went wrong with that: - When only one of a merged bullet's pull requests was reverted, the bullet stayed in the file carrying the others, and the recorded line was the whole merged one. The prompt asked for that line back, which duplicates the siblings, and `verify_edit` accepted it: `not_restored` only asks whether `/pull/109000)` appears somewhere. - When the whole merged bullet was deleted, every one of its pull requests was recorded against the same line, so the prompt listed the same bullet once per pull request. `group_restorations` now groups the entries to restore by the line they were recorded from — one bullet is restored once, however many pull requests it covers — and reports the `siblings` of that line which are still in the file. The prompt names them and asks for the missing link to be put back into the existing bullet instead of a copy of the recorded line. `duplicate_attributions` closes the verification gap: an edit that newly attributes a pull request twice in the in-progress section is rejected. Duplicates that predate the edit are left alone — the file has 20 of them across released sections, where the same pull request legitimately appears in a release and in a backport. `test_verify_edit_accepts_only_the_exact_merged_bullet_restoration` runs the whole path: leaving the reverted pull request out is rejected, pasting the recorded bullet next to the surviving one is rejected, merging the link back in passes. Without the duplicate check the paste is accepted, which is the reported defect.
… one bullet Both gaps are in the grouped-restoration path, and both come from a recorded merged bullet covering more pull requests than the restoration is about. **A sibling whose revert still stands.** `#109000` and `#109006` shared a bullet, both were reverted, and only `#109000` has been re-applied. The recorded line still attributes `#109006`, so replaying it advertises a change that is out of the release - the mirror image of the bug this whole pull request is about. `analyze_reverts` now reports `withheld`: the recorded entries whose deletion an uncancelled revert still licenses. The prompt asks for those attributions to be left off the restored bullet, and `verify_edit` rejects a section that attributes any of them, whether they were pasted back or simply never deleted. **A recorded bullet restored as two.** The re-apply check looked only at the bullet of a group's first pull request, so a merged bullet could come back as one bullet per pull request, undoing the merge of skill section 7 and letting each half lose the re-applying link on its own. One recorded bullet now has to come back as one bullet carrying all of its pull requests, and the re-apply link is checked on every one of them rather than on the first. Two tests added, both fail without their fix. The split one asserts that the one-bullet rule catches a split even when both halves carry the re-applying link, so it is not just the re-apply check under another name.
…survivor **`cancelling` was any-target, not every-target.** A revert that undoes something of this release *and* something that shipped earlier was exempt from strict retention on the strength of the first half alone, so its own entry could disappear with the entry it cancels - taking the user-visible half of it (skill section 2, case 5) out of the changelog. The exemption now needs every target to belong to this cycle; one target from an earlier release keeps the revert's entry protected. **The shared-bullet rule ignored the pull requests that never left.** The split check compared the bullets of the restored pull requests only, so with `#109000` and `#109006` off one bullet and only `#109000` restored, re-adding it as a second bullet with the same prose passed everything: no attribution repeats, the category matches, the re-apply link is there. The check now spans the group's `siblings` too, which is what "merge it back into the bullet that survived" means. The duplicate-attribution check moves ahead of the shared-bullet one: pasting the recorded merged bullet beside the survivor trips both, and "you wrote this entry twice" is the more specific diagnosis. Two tests added. Each fails without its fix, and the shared-bullet one asserts that no attribution repeats in its input, so it cannot pass as a restatement of the duplicate check.
Query 2 of polymorphic_parts_l.xml (INSERT through hits_buffer) takes 2.30 s on MasterCI amd and 4.22 s on arm. No existing query number or text changes: 1 query is disabled and 1 copy appended as 3, the same INSERT on numbers(20000), i.e. 20 parts of the same 1000 rows. Decision (deterministic, two repetitions on NUMA nodes 5 and 0, official amd release builds, both seat orders): - copy of query 2: per-part time 0.971 / 1.010 of the original's, per-part user time 1.005 / 1.026; on the MasterCI pair of ClickHouse#109000 (7a4e895 -> e523465) it keeps 1.002 / 1.097 of the original's client-time slowdown (original 1.217 / 1.214, copy 1.217 / 1.234). - query 0 (wide) is not replaced: on the ClickHouse#109454 pair (2485f14 -> 45cb837) its 20-part copy's per-part user time moved by 0.972 in one of four passes, and the rule asks for > 1 in every pass. hits_wide now receives 20 instead of 100 parts per run from the Buffer query, so a cost that grows with the parts already in the table, rather than per written part, is smaller in the copy. Saving: about 19 s of query time per master perf job on amd and 34 s on arm. Related: ClickHouse#129258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
No existing query number or text changes: 2 queries are disabled and 2 copies appended as 3 and 4. Queries 0 (wide) and 2 (Buffer) take 1.59 and 2.19 s on MasterCI amd (3.00 and 4.09 s on arm); each writes 100 parts of 100 rows. The copies are the same INSERTs on numbers(2000): 20 parts of the same 100 rows. The compact query (0.28 s) keeps its 100 parts. Local A/B with perf.py on official MasterCI builds, two repetitions on different NUMA nodes, both seat orders (decide.py VERDICT ok, GEN_ARGS 1 1): - per part, copy vs original: time 0.97-1.00x, user time 1.00-1.03x; file opens and buffer allocations per part equal, statistics step present exactly when in the original. - ClickHouse#109000 (7a4e895 -> e523465): the Buffer copy keeps 80-104% of query 2's client-time slowdown (CI: user time 1.38x amd, 1.70x arm). - ClickHouse#109454 (2485f14 -> 45cb837): the wide copy keeps 93-97% of query 0's per-part user time increase (CI: 1.07x amd, 1.06x arm). The ClickHouse#109454 passes ran perf.py with --min-runs 30 --cap 30: at CI's 5-7 runs per server a copy that keeps a 6% effect fully misses it in a third or more of passes. hits_wide receives 20 instead of 100 parts per run from each copy, so a cost that grows with the parts already in the table, rather than per written part, is smaller in the copies. Projected CI medians: 0.32 / 0.42-0.43 s on amd, 0.60 / 0.79-0.80 s on arm; about 31 s of query time per master perf job on amd and 57 s on arm. Related: ClickHouse#129258 Co-Authored-By: Claude Opus 5.5 <[email protected]>

Closes: #108997
max_insert_threadspreviously parallelized only theSELECTside ofINSERT SELECT. For a plainINSERT(data sent fromclickhouse-clientor over the HTTP interface) the whole pipeline — squashing the blocks and writing them to the destination table and to dependent materialized views — ran in a single thread regardless ofmax_insert_threads.This makes
max_insert_threadsapply to plainINSERTs as well. As suggested in the issue, the implementation resizes the pipeline after reading the input data: the input is read and parsed as a single stream through the head of the pipeline (counting, deduplication info, planning of squashing), and then aResizeProcessor(1 → N) fans out tomax_insert_threadsparallel sink chains (apply squashing → write). This mirrors the existingINSERT SELECTpath inaddInsertToSelectPipeline.For the default
max_insert_threads = 0(treated as 1) the pipeline is byte-for-byte unchanged. The parallelization of the writing side is gated byInsertDependenciesBuilder: it only happens when the write path can safely fan out, and it stays single-stream to preserve block deduplication when a destination deduplicates inserted blocks, has dependent materialized views (unlessparallel_view_processingis enabled and the dependent view chains are free of deduplication hazards), or is aBufferorDistributedtarget (both forward the write through a separate context — a background flush or a remote shard — that this query's deduplication settings do not govern, so they are always kept single-stream). It is also disabled for asynchronous inserts, which have their own batching/flush mechanism.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
max_insert_threadscan now parallelize the writing side of a plainINSERT(data sent fromclickhouse-clientor over the HTTP interface) when the destination write path can safely fan out, not onlyINSERT SELECT.Documentation entry for user-facing changes
max_insert_threadssetting description is updated)Version info
26.8.1.616(included in26.8and later)