Skip to content

Support max_insert_threads for plain INSERTs - #109000

Merged
alexey-milovidov merged 53 commits into
masterfrom
max-insert-threads-for-direct-inserts
Aug 1, 2026
Merged

alexey-milovidov merged 53 commits into
masterfrom
max-insert-threads-for-direct-inserts

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Closes: #108997

max_insert_threads previously parallelized only the SELECT side of INSERT SELECT. For a plain INSERT (data sent from clickhouse-client or 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 of max_insert_threads.

This makes max_insert_threads apply to plain INSERTs 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 a ResizeProcessor (1 → N) fans out to max_insert_threads parallel sink chains (apply squashing → write). This mirrors the existing INSERT SELECT path in addInsertToSelectPipeline.

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 by InsertDependenciesBuilder: 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 (unless parallel_view_processing is enabled and the dependent view chains are free of deduplication hazards), or is a Buffer or Distributed target (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):

  • Performance Improvement

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

max_insert_threads can now parallelize the writing side of a plain INSERT (data sent from clickhouse-client or over the HTTP interface) when the destination write path can safely fan out, not only INSERT SELECT.

Documentation entry for user-facing changes

  • Documentation is written (the max_insert_threads setting description is updated)

Version info

  • Merged into: 26.8.1.616 (included in 26.8 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [156b630]

Summary: ✅


AI Review

Summary

This PR parallelizes the write side of a plain synchronous INSERT and adds a substantial set of safety gates for deduplication, forwarding storages, hidden materialized views, and quorum inserts. The remaining blocker is that the final simplification dropped the earlier single-stream guard for capped Memory tables, so the current head can change which rows survive a plain client/HTTP INSERT into a circular-buffer Memory table.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterInsertQuery.cpp:887-904, src/Storages/StorageMemory.cpp:127-153, docs/en/engines/table-engines/special/memory.md:28-40] [dismissed by author -- https://github.com/Support max_insert_threads for plain INSERTs #109000#discussion_r3669854647] The current head again lets a plain INSERT fan out into several MemorySinks for a Memory table with max_rows_to_keep or max_bytes_to_keep. MemorySink::onFinish applies the circular-buffer eviction when each sink commits its own batch, so a multi-block insert now keeps whichever branch finishes last, not the tail of the original input. That violates the documented Memory contract that the oldest rows are deleted on each insertion, and it is a real regression for existing plain inserts because this PR is exactly what starts applying max_insert_threads to that path. Restoring the capped-Memory single-stream guard (or reestablishing input-order retention before eviction) is still necessary.
Final Verdict

❌ Request changes.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 30, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 query_duration_ms from system.query_log (best of 3 runs), so it excludes the client/curl transfer. Compared the pre-PR master binary against this PR's binary, both built from the same tree.

Before (master) — max_insert_threads has no effect on a plain INSERT:

format mit=1 mit=4 mit=8 mit=16
Native 4872 ms 4854 ms 4889 ms 4793 ms
TSV 4764 ms 4776 ms 4743 ms 4745 ms
CSV 4787 ms 4766 ms 4842 ms 4717 ms
JSONEachRow 4908 ms 4903 ms 5127 ms 5358 ms

After (this PR) — the writing side scales with max_insert_threads:

format mit=1 mit=4 mit=8 mit=16 speedup @16 vs master
Native 5666 ms 1529 ms 876 ms 667 ms 7.3×
TSV 5621 ms 1506 ms 1035 ms 1044 ms 4.6×
CSV 4843 ms 1993 ms 1901 ms 1704 ms 2.8×
JSONEachRow 5013 ms 3191 ms 3195 ms 3201 ms 1.5×

(That's ~4 → 30 M rows/s for Native.)

Takeaways:

  • The gain is largest for formats that are cheap to parse (Native), where the write side dominates and now runs across N streams.
  • Parse-heavy formats (JSONEachRow) benefit less, because the input is still read/parsed as a single stream — so parsing becomes the bottleneck once the write side is parallelized. This matches the updated setting docs.
  • max_insert_threads=1 is byte-for-byte the old pipeline (no Resize), so the default behavior is unchanged.

Verified via EXPLAIN PIPELINE INSERT ...: master produces 1 MergeTreeSink regardless of max_insert_threads, while this PR produces N.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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: tests/performance/insert_direct_parallel.xml.

It uses the shell-script perf-query support (<query type="shell">) and is fully self-contained via clickhouse-local — CREATE + direct INSERT, no server table to clean up (the temporary directory is discarded on exit):

  • data is generated as Native and piped into a CREATE + INSERT ... FORMAT Native, so the direct-insert write side is what's measured, not format parsing;
  • a compound sort key + ZSTD(3) codecs make the write side expensive enough for the sink parallelism to show;
  • max_insert_threads = 8, with the memory-based thread clamp disabled so it engages deterministically.

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 max_insert_threads) against this branch, so it should report the speedup; after merge the same test guards against regressions.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 209 180 -13.9% <0.0001 ClickBench Q4 is a read-only SELECT, but this PR only touches the INSERT write-side pipeline (max_insert_threads fan-out and dedup-hazard gating). It cannot affect query execution, so the -13.9% is run-to-run variance.
⚠️ 15 not_sure 218 190 -13.0% <0.0001 Q15 is a SELECT and the PR changes only INSERT pipeline construction, not the read path. The -13.0% is not a plausible PR effect and reads as measurement noise.

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_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 1076 1132 +5.2% <0.0001 Correctly held within the master variance band. The +5.2% is on a SELECT, which this INSERT-only PR cannot touch, so the small delta is noise.

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
  • StressHouse run: 326415e3-a128-4dba-a7d3-f38ba02e9f19
  • MIRAI run: 955ac9c7-bdd5-43f5-ac06-28310df85445
  • PR check IDs:
    • clickbench_1183683_1785544128
    • clickbench_1183694_1785544128
    • clickbench_1183706_1785544128
    • tpch_adapted_1_official_1183714_1785544128
    • tpch_adapted_1_official_1184090_1785544157
    • tpch_adapted_1_official_1184218_1785544174

alexey-milovidov and others added 2 commits July 1, 2026 06:25
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed two follow-up commits (c2aed715eeb..df5c8f0eb13) after triaging the CI report [PR report]:

1. Dedup collision with strict block limits (AI-review Major) — fixed in 54dbb33a08a

Confirmed the finding is real. In the strict path the source block number is stamped by a per-stream AddDeduplicationInfoTransform after the ResizeProcessor fan-out, so each branch restarts numbering at 0. With a non-empty insert_deduplication_token the dedup id is token + block number (content-independent), so branches collide and MergeTreeSink drops rows. The fix keeps use_strict_insert_block_limits + tokenized inserts single-stream (insert_threads = 1), exactly the pre-PR behavior for that combination. The token-less strict path is unaffected because ids are redefined from the data hash (RedefineDeduplicationInfoWithDataHashTransform) and stay unique across branches, so parallelism is preserved there. Compiled clean (-Werror); this is a conservative, fail-close guard rather than a shared-counter rework — happy to switch to sharing one counter across branches if you prefer to keep parallelism for that (non-default) combo.

2. 02481_parquet_int_list_multiple_chunks flake — fixed in df5c8f0eb13

This is a genuine consequence of the PR, not infra: the test does a plain INSERT of a Parquet file into a Memory table (supportsParallelInsert() == true) and checks the md5 of SELECT *. With a randomized max_insert_threads > 1 the writing side now fans out across parallel streams and the Memory table receives the blocks in a non-deterministic order, so the md5 differs (count stays 70000 — reordering, not data loss). Pinned max_insert_threads = 1 on that INSERT since the test exercises the Parquet reader, not insert parallelism.

Heads-up (not a blocker): parallelizing the write side of a plain INSERT makes its row order non-deterministic for max_insert_threads > 1, the same as INSERT SELECT already is. Other stateless tests that do a plain INSERT and then check exact unordered output may surface the same flake under settings randomization and would need the same max_insert_threads = 1 pin (or an ORDER BY).

Remaining CI failures — pre-existing, not caused by this PR

  • 00732_quorum_insert_have_data_before_quorum_zookeeper_long (arm_binary): Code: 286 ... UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE on a single-row INSERT — the classic timing flake of non-parallel quorum tests. CIDB shows it also failed on unrelated PRs Read vectors from part when loading usearch index #101843 (06-09) and More settings to randomize #106734 (06-08). Only one branch is engaged for a one-row insert, so the fan-out isn't involved.
  • BuzzHouse (amd_tsan) Cannot fill arrow array A with B data (STID 4565-4839): a LOGICAL_ERROR thrown in CHColumnToArrowColumn.cpp:883 — Arrow output conversion, a separate subsystem from the INSERT-pipeline change here. It appears exactly once in 120 days of CIDB (this run only), consistent with a rare latent Arrow-output bug the fuzzer happened to hit, not a regression from this PR.

No re-merge with master: the branch is ~150 commits behind but the merge-base is <1 day old and master has not touched InterpreterInsertQuery.cpp / Settings.cpp / InsertDependenciesBuilder.cpp since then (no conflicts).

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 0f9facdb9c0:

Addressed the AI review "Request changes" (regression test for the strict tokenized fallback).
Added 04493_max_insert_threads_strict_tokenized_dedup, the missing coverage for the single-stream fallback introduced in 54dbb33a08a. It asserts that:

  • with use_strict_insert_block_limits = 1 and a non-empty insert_deduplication_token a plain INSERT falls back to one MergeTreeSink (via EXPLAIN PIPELINE), while the same strict INSERT without a token still fans out to four sinks;
  • all rows of a many-block streamed INSERT arrive under the strict tokenized combination.
    Deduplication is enabled on the table (non_replicated_deduplication_window), so removing the fallback would collide per-stream source block numbers and drop rows, failing the test. The corresponding review thread is resolved.

The Stateless tests (amd_debug, parallel) failure is a pre-existing flake, not caused by this PR.
00732_quorum_insert_have_data_before_quorum_zookeeper_long fails with UNSATISFIED_QUORUM_FOR_PREVIOUS_WRITE - a replica-synchronization timing flake on this _long quorum test. It has flaked on unrelated master-based runs before this PR existed (#101843 on 2026-06-09, #106734 on 2026-06-08). The test only does single-row INSERT ... VALUES under quorum: with max_insert_threads > 1 the single input chunk is routed to one sink chain; the other (empty) sink chains write no part and perform no quorum bookkeeping (quorum handling only runs when a part is actually written), so the write side of the parallelization cannot affect quorum confirmation. The new head re-runs this job.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 old_separate_hashes, not for the default new_unified_hash.

Root cause. In the strict path the per-branch AddDeduplicationInfoTransform restarts its source_block_number from 0 in every parallel branch. The final block id is then built differently by the two hash functions in InsertDeduplication.cpp:

  • getBlockHash (old path, old_separate_hashes): for a tokenless block at SOURCE level it sets by_part_writer to the data hash and returns early, so source_block_number is not part of the id → safe.
  • getBlockUnifiedHash (default new_unified_hash, and compatible_double_hashes): it sets extension to the data hash and then appends every extra_token. The SOURCE_NUMBER extra is skipped only in the if (is_async_insert && ... SOURCE_NUMBER) branch. For a sync insert it falls through and appends the real value, so the id is effectively hash(data_hash : source_block_number) → the source number participates.

Because the default insert_deduplication_version is new_unified_hash, two identical squashed blocks in one streamed INSERT that land on different branches both get source_block_number = 0 and the same data hash → identical block id → the sink treats the second as a duplicate and drops it. In the single-stream case those two blocks get source numbers 0 and 1, so both are kept — hence this is a regression introduced by the fan-out, exactly as the AI describes.

Scope. Only the strict path (use_strict_insert_block_limits = 1) is affected; the non-strict path stamps source_block_number in the single-stream head before the ResizeProcessor, so the main max_insert_threads win is unaffected. Trigger: use_strict_insert_block_limits = 1, max_insert_threads > 1, empty insert_deduplication_token, active deduplication (ReplicatedMergeTree, or non-replicated with non_replicated_deduplication_window > 0), default new_unified_hash, and ≥2 identical blocks in one INSERT.

Fix direction. The strict_tokenized_insert single-stream fallback should also cover the tokenless case whenever the id can fold in source_block_number — i.e. for new_unified_hash/compatible_double_hashes (equivalently: keep strict inserts single-stream unless insert_deduplication_version == old_separate_hashes). Sharing one atomic counter across the branch-local transforms is not a correct alternative: retry-based deduplication relies on deterministic global source numbering, which a race-ordered shared counter would not reproduce.

Suggested regression test: strict, tokenless, max_insert_threads > 1, default new_unified_hash, ReplicatedMergeTree (or a dedup window), a streamed INSERT containing repeated identical blocks, asserting that all rows arrive.

…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 26c419a3c4c to address the AI-review Request changes finding (strict token-less dedup collision), implementing the fix direction from my analysis above.

Fix

InterpreterInsertQuery::buildInsertPipeline now keeps a strict INSERT single-stream whenever the deduplication id can fold in the per-branch source block number, not only for a non-empty token:

strict && (insert_deduplication_token non-empty
           || insert_deduplication_version != old_separate_hashes)

Rationale (default new_unified_hash): in the strict path the per-branch AddDeduplicationInfoTransform restarts its source block number from 0, and a synchronous token-less id is hash(data_hash : source_block_number), so two identical squashed blocks on different branches collide and MergeTreeSink/ReplicatedMergeTreeSink skip one — silently dropping rows. Only old_separate_hashes derives a token-less id from the data hash alone (source number dropped) and can safely fan out. 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 untouched. As before, sharing one counter across branches is intentionally not used — retry-based dedup relies on deterministic global source numbering, which a race-ordered shared counter would not reproduce.

Tests

  • New 04494_max_insert_threads_strict_tokenless_dedup: asserts the strict token-less INSERT falls back to a single sink under the default new_unified_hash (via EXPLAIN PIPELINE), that a non-strict token-less INSERT still fans out to four sinks, and that all rows arrive for a many-block streamed INSERT of ten identical 1000-row blocks under an active dedup window (would drop rows if the fan-out restarted numbering per branch).
  • 04493_max_insert_threads_strict_tokenized_dedup: its former "token-less still fans out" assertion is now invalidated by the fix, so it instead exercises the gating on use_strict_insert_block_limits (a non-strict tokenized INSERT still fans out).

The inline thread on InterpreterInsertQuery.cpp is resolved.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The AST fuzzer (amd_debug) failure (Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa)) is a pre-existing, unrelated flake, not caused by this PR.

Known flake; it will pass on re-run once the current workflow finishes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stateless tests (amd_tsan, s3 storage, parallel, 1/2) failure (03100_lwu_07_merge_patches) is a pre-existing flake, not caused by this PR.

What failed. The diff is a single patch-part name, not a data difference:

-patch-3e1a7650697c132eb044cc6f1d82bc92-all_3_11_1_10	13
+patch-3e1a7650697c132eb044cc6f1d82bc92-all_3_11_2_10	13

Only the merge level differs (..._3_11_1_10 vs ..._3_11_2_10): the patch partition went through one extra background merge before the system.parts snapshot. The row counts and all SELECT results are identical. This is a background-merge-timing race in the lightweight-update patch part naming, with no relation to the insert pipeline.

Not reproducible. The CI harness re-ran the test 22 times with the same randomized settings and all 22 passed:

--- Randomized settings diagnosis ---
Step 1: Re-running with the same randomized settings (budget: 60s)...
  Runs: 22, Failed: 0, Passed: 22, Other: 0
Result: All reruns passed. The failure is not reproducible (likely a transient issue).

History. The test has flaked on master itself (pull_request_number = 0) on 2026-06-11 and 2026-06-07, and on unrelated PRs (#99654, #107409, #103112, #106802, #105480, #77210) over the last 30 days.

Why the PR cannot cause it. The test's only insert is INSERT INTO t_lightweight SELECT number, number FROM numbers(20) — a 20-row single-block INSERT ... SELECT, which goes through buildInsertSelectPipeline (already parallelizable before this PR), not the plain-INSERT buildInsertPipeline path this PR changes. The write-side fan-out cannot change patch-part merge levels.

Re-running the failed jobs to clear the transient reds. The only remaining public reds are this and the chronic AST fuzzer (amd_debug) flake (STID 1941-1bfa, #108372), triaged above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Proven:

Screenshot_20260702_050602

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Cloud Performance Report

This is false.

alexey-milovidov and others added 2 commits July 2, 2026 03:33
`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]>
@alexey-milovidov
alexey-milovidov requested a review from Fgrtue July 2, 2026 03:47
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 9, 2026
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]>
alexey-milovidov added a commit to ClickHouse/ClickBench that referenced this pull request Aug 27, 2026
…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]>
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
…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.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
… 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.
alexey-milovidov added a commit that referenced this pull request Aug 28, 2026
…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.
nihalzp pushed a commit to nihalzp/ClickHouse that referenced this pull request Nov 16, 2026
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]>
eoger-ant pushed a commit to eoger-ant/ClickHouse that referenced this pull request Nov 16, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements 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.

max_insert_threads can work for usual INSERTs

3 participants