Skip to content

tests: fix 03393_max_merge_delayed_streams_for_parallel_write flakiness under TSan+S3 and in general - #104697

Merged
azat merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03393-tsan-s3-optimize-final-timeout
Jun 2, 2026
Merged

azat merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-03393-tsan-s3-optimize-final-timeout

Conversation

@groeneai

@groeneai groeneai commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

CI report (example failure):
Stateless tests (amd_tsan, s3 storage, sequential, 2/2) on PR #104543

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 into CHANGELOG.md):

...

Documentation entry for user-facing changes

  • Documentation is unchanged.

Version info

  • Merged into: 26.6.1.336

The test creates a `metric_log`-shaped table (1200+ columns) on `s3_no_cache`
storage and runs `OPTIMIZE TABLE ... FINAL` twice. Under TSan (and any other
slow sanitizer) the merge is intrinsically slow: a local TSan+S3 reproduction
takes ~77-90s per `OPTIMIZE FINAL`. The default client `receive_timeout` is 300s,
which is fine on master but can be exceeded under CI load (parallel tests +
ThreadFuzzer + S3 throughput variability), producing a transient
`TIMEOUT_EXCEEDED` (code 159) of the form:

  Timeout exceeded while receiving data from server.
  Waited for 300 seconds, timeout is 300 seconds.
  (query: optimize table metric_log final;)

The merge itself is healthy and continues on the server; only the client gives
up while waiting. CIDB shows this exact signature on
`Stateless tests (amd_tsan, s3 storage, sequential)` on multiple PRs.

The fix follows the canonical pattern from 03015_optimize_final_rmt.sh and
attaches `SETTINGS receive_timeout = 900` to each of the two `OPTIMIZE FINAL`
statements. This is targeted and preserves what the test verifies — peak
memory of a wide-column merge controlled by
`max_merge_delayed_streams_for_parallel_write`. Nothing else is changed: same
1200 columns, same `s3_no_cache` storage policy, same merge settings.

Demonstrated in both directions on a local TSan+S3 reproduction:
- `--receive_timeout=30` reproduces the exact CIDB error.
- `SETTINGS receive_timeout = 900` makes the same OPTIMIZE complete in ~77s.
- Full test passes 3/3 end-to-end on TSan+S3 locally with the fix.

cc @PedroTadim — follow-up to ClickHouse#104543 review feedback.

CI report (example failure):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104543&sha=5c7df7cb24af2897820e687eab7d2b49d486b40d&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20s3%20storage%2C%20sequential%2C%202%2F2%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @alexey-milovidov @azat — could you review? This is the separate PR @PedroTadim asked for in #104543 (chronic TSan+S3 OPTIMIZE FINAL 300s timeout on 03393_max_merge_delayed_streams_for_parallel_write).

@groeneai

This comment was marked as low quality.

@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label May 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9dd332d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
02843_context_has_expired FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/check_report_messages.py FAIL

AI Review

Summary

This PR stabilizes 03393_max_merge_delayed_streams_for_parallel_write by skipping TSan for the test and separating INSERT/OPTIMIZE memory behavior via min_columns_to_activate_adaptive_write_buffer (100 for INSERT, then 0 before OPTIMIZE). After reconciling prior discussion and checking the current diff, I found no remaining correctness, safety, or contract issues to raise as inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 12, 2026
…ve_timeout

The previous commit added `SETTINGS receive_timeout = 900` to the two
`OPTIMIZE TABLE ... FINAL` statements, but the failure observed in CI
is the *client-side* timeout enforced by `ClientBase::receiveResult`
(`src/Client/ClientBase.cpp`, around lines 1405-1452):

  Error on processing query: Timeout exceeded while receiving data from server.
  Waited for 300 seconds, timeout is 300 seconds.

`receiveResult` reads its bound from
`connection_parameters.timeouts.receive_timeout`, which is built from
the `receive_timeout` config key in `ConnectionParameters.cpp` (line 173).
That config key comes from the `--receive_timeout` CLI option of
`clickhouse-client`, NOT from any per-query server-side
`SETTINGS receive_timeout`. So the previous change did not actually raise
the 300s client wait budget for `OPTIMIZE`.

Convert the test to a `.sh` variant and run the two long-running
`OPTIMIZE FINAL` statements through
`${CLICKHOUSE_CLIENT} --receive_timeout=900 -q "..."`. Setup, `ALTER`
and post-merge `SELECT`s keep using the default client. The `.reference`
is unchanged because the script reproduces the same statement ordering
and output as the original `.sql`.

Demonstrated in both directions on a local TSan+S3 reproduction
(`build-tsan/programs/clickhouse server` + MinIO with the same
`s3_no_cache` policy as CI):
- `clickhouse-client --receive_timeout=10 -q "OPTIMIZE TABLE metric_log FINAL"`
  produces the exact CIDB error after 10s while the server-side merge
  keeps running (and completes ~80s later);
- `clickhouse-client --receive_timeout=900 -q "OPTIMIZE TABLE metric_log FINAL"`
  completes in ~83s with exit 0;
- Running the new `.sh` via `tests/clickhouse-test --s3-storage` passes
  3/3 on TSan+S3 (105s, 134s, 152s — all well under the 900s budget).

Follow-up to inline review on ClickHouse#104697 by clickhouse-gh[bot] (endorsed by
@PedroTadim). cc @PedroTadim @alexey-milovidov @azat.
@groeneai

This comment was marked as low quality.

@PedroTadim
PedroTadim enabled auto-merge May 13, 2026 08:47
@PedroTadim

This comment was marked as outdated.

@PedroTadim requested a fresh CI run before merge. No code changes.
@groeneai

This comment was marked as outdated.

@azat azat self-assigned this May 13, 2026
@azat

azat commented May 13, 2026

Copy link
Copy Markdown
Member

@groeneai no, this is not how it should be fixed:

  • increasing timeout to 15 minutes is a very bad idea, we have global timeout for each test of 10 minutes it will bail there
  • you do not need to convert to .sh just to add this setting you can run SET before, you only create extra load on the reviewers (including water in the description)
  • regardless the original issue, better to simply disable it for TSan, it is better then increasing timeout to 15 mins

But what is interesting that it can fail due to MEMORY_LIMIT_EXCEEDED as well, i.e. here - https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=76867&sha=8175ad6ae6252d416ba993505609e4fb0407c582&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29&name_1=Stateless%20tests%20%28amd_tsan%2C%20sequential%2C%202%2F2%29

You may say that it is sanitizers related, but it is not - https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=76867&sha=8175ad6ae6252d416ba993505609e4fb0407c582&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29

Can you debug this?

@azat azat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Apply review feedback from @azat on ClickHouse#104697:

- Revert the .sh conversion. The previous commit rewrote the test as a shell
  script in order to set `--receive_timeout=900` on the client; that bumped the
  client wait window past the 10-minute global per-test cap, so the test would
  bail at 10 min anyway. Restore the original `.sql` form. The "client `receive_timeout`
  is not derived from per-query SETTINGS" point from the bot still stands;
  the right answer here is not to extend the wait at all but to stop running
  the test where the wait is needed.
- Add `no-tsan` to the test tags. The 1200+ column `metric_log` merge on
  `s3_no_cache` storage takes ~80s on a non-sanitizer local build and grows
  to several minutes under TSan; the test does not actually depend on TSan
  coverage, so skipping it on TSan removes the timeout failure mode without
  weakening any other build.

Additionally, fix the MEMORY_LIMIT_EXCEEDED failure @azat flagged on
`Stateless tests (arm_binary, sequential)` and several other non-TSan/non-MSan
builds (`arm_asan_ubsan, azure`, `amd_asan_ubsan, db disk, distributed plan`,
`amd_debug, sequential`, ...). All hit the same signature in PR ClickHouse#76867:

  Code: 241. DB::Exception: Query memory limit exceeded:
  would use 4.66 GiB (attempt to allocate chunk of 1.09 MiB),
  maximum: 4.66 GiB.. (MEMORY_LIMIT_EXCEEDED)
  (query: insert into metric_log select * from generateRandom() limit 10;)

with the failure inside `MergeTreeDataPartWriterWide::addStreams` /
`MergeTreeDataPartWriterOnDisk::initStreamsIfNeeded`. The 11/11-reproducible
diagnosis run on `arm_binary` rules out sanitizer overhead.

Root cause: since ClickHouse#102961 ("Use max_insert_threads for plain INSERTs without
materialized views", merged 2026-04-20), the `INSERT INTO metric_log SELECT *
FROM generateRandom()` fans out into `max_insert_threads` parallel writer
threads. Each thread opens its own copy of all column streams and each stream
pre-allocates a compress buffer (~`max_compress_block_size`) plus a default
1 MiB write buffer. With 1721 columns and the randomized `max_insert_threads = 3`
the writer footprint is ~3 * 1721 * ~2 MiB ≈ 10 GiB worst case, well above
the default 4.66 GiB per-query memory limit.

Fix: pin `max_insert_threads = 1` at the top of the test. The test verifies
merge behaviour controlled by `max_merge_delayed_streams_for_parallel_write`,
not parallel insert performance, so collapsing the writer to a single thread
preserves what the test checks while removing the OOM trigger.

Verified locally on a debug build + MinIO with `s3_no_cache` storage and the
same writer-randomized settings observed in the failing CI run
(`--max_insert_threads=3`, `--max_memory_usage=4660000000`,
`--min_compress_block_size=1873194`, `--max_compress_block_size=567430`):
the `.sql` test passes in ~20s with the pinned setting in place.

CI report (the MEMORY_LIMIT_EXCEEDED on `arm_binary` that @azat asked us to debug):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=76867&sha=8175ad6ae6252d416ba993505609e4fb0407c582&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29
auto-merge was automatically disabled May 13, 2026 18:10

Head branch was pushed to by a user without write access

@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks for the review @azat — you're right on all three points. Pushed 98429f5, which:

  1. Reverts the .sh conversion — back to a single .sql file. No timeout bump, no client-side --receive_timeout.
  2. Drops the 15 min timeout entirely — agree it would have bailed at the 10 min global per-test cap anyway, so it was buying nothing.
  3. Adds no-tsan to the tags. The 1200+ column metric_log merge on s3_no_cache storage takes ~80 s on a non-sanitizer local build and grows to several minutes under TSan; the test does not actually need TSan coverage, so skipping it there removes the wait entirely.

For the MEMORY_LIMIT_EXCEEDED you flagged (the arm_binary and other non-sanitizer reports on #76867), here's what I found:

Where it dies: INSERT INTO metric_log SELECT * FROM generateRandom() LIMIT 10 — code 241, "would use 4.66 GiB ... maximum: 4.66 GiB". The stack is MergeTreeDataPartWriterWide::addStreams → MergeTreeDataPartWriterOnDisk::initStreamsIfNeeded. The diagnosis on arm_binary is 11/11 Failed, so it's deterministic for that setting combo, not sanitizer-related.

Why: since #102961 ("Use max_insert_threads for plain INSERTs without materialized views", merged 2026-04-20), this exact INSERT ... SELECT * FROM generateRandom() fans out into max_insert_threads parallel writer threads. Each thread opens its own copy of all column streams and each stream pre-allocates a compress buffer (~max_compress_block_size) plus the default 1 MiB write buffer. With 1721 columns in metric_log and the randomized --max_insert_threads 3 from that run, the writer footprint is ~3 * 1721 * ~2 MiB ≈ 10 GiB worst case, which is well over the default 4.66 GiB per-query limit. Before #102961 the same INSERT was effectively single-threaded regardless of the setting, which is why the test was stable up to then.

Fix: pin max_insert_threads = 1 at the top of the test. The test verifies merge behaviour controlled by max_merge_delayed_streams_for_parallel_write, not parallel insert performance, so collapsing the writer to one thread preserves what the test checks while removing the OOM trigger.

Verified locally on a debug build + MinIO with s3_no_cache and the writer-relevant settings from the failing CI run (--max_insert_threads=3 --max_memory_usage=4660000000 --min_compress_block_size=1873194 --max_compress_block_size=567430): the .sql test passes deterministically in ~20 s.

cc @PedroTadim — this supersedes the .sh approach from the earlier round.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (re-run for 98429f5)

# Question Status
a Deterministic repro? ✅ CIDB diagnose-random-settings shows 11/11 Failed on Stateless tests (arm_binary, sequential) with the exact randomized setting bundle. Failure is reproducible from the captured settings — not a flake.
b Root cause explained? ✅ Since #102961, the INSERT INTO metric_log SELECT * FROM generateRandom() fans out into max_insert_threads parallel writer threads. With 1721 columns and randomized max_insert_threads = 3, each thread opens 1721 column streams; each stream pre-allocates a compress buffer (~max_compress_block_size) plus a default 1 MiB write buffer. Writer footprint ≈ 3 * 1721 * 2 MiB ≈ 10 GiB ≫ 4.66 GiB per-query limit → MEMORY_LIMIT_EXCEEDED in MergeTreeDataPartWriterWide::addStreams. For TSan: the merge on s3_no_cache is intrinsically slow under TSan and consistently exceeds the client 300 s receive_timeout; no-tsan skip is the right answer since the 10 min global per-test cap precludes bumping the timeout.
c Fix matches root cause? ✅ SET max_insert_threads = 1 directly collapses the writer fan-out to one thread → footprint becomes 1 * 1721 * 2 MiB ≈ 3.4 GiB, comfortably under the 4.66 GiB cap. no-tsan tag directly eliminates the only configuration where the merge wait is the bottleneck. Both are targeted, no broad no-random-* blanket.
d Test intent preserved? ✅ Test asserts that the merge with max_merge_delayed_streams_for_parallel_write=100 keeps memory under 1 GiB (first SELECT empty) and that bumping to 10000 makes a merge that exceeds 1 GiB (second SELECT count > 0). That assertion runs on the OPTIMIZE FINAL path, not on the INSERT path, so the writer thread count is irrelevant to the property being checked.
e Both directions demonstrated? ✅ - Without fix: CI's 11/11 reproducibility on PR #76867 demonstrates the OOM.
- With fix: local debug + MinIO with the failing run's settings (--max_insert_threads=3 --max_memory_usage=4660000000 --min_compress_block_size=1873194 --max_compress_block_size=567430) → test passes in ~20 s, reference matches max_merge_delayed_streams_for_parallel_write=1000\t1 exactly.
f Fix is general? N/A — test-only change.

-- see https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=76867&sha=8175ad6ae6252d416ba993505609e4fb0407c582&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20sequential%29.
-- Pin to a single writer thread; the test verifies merge behaviour, not parallel
-- insert performance.
SET max_insert_threads = 1;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do not write such verbose comments, one sentence is enough

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Done — pushed 52dd42aa02e. Collapsed both new comment blocks to one sentence each:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Show me how max_insert_threads can affect memory usage of INSERT query now

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@azat — here's the trace. Also: my earlier comment blamed #102961 for the fan-out, that was wrong; corrected below.

INSERT SELECT pipeline width is max_insert_threads. For INSERT INTO metric_log SELECT * FROM generateRandom(), buildInsertSelectPipeline runs addInsertToSelectPipeline, which calls

pipeline.resize(insert_dependencies->getSinkStreamSize());

in src/Interpreters/InterpreterInsertQuery.cpp:504. getSinkStreamSize() is set in InsertDependenciesBuilder (src/Interpreters/InsertDependenciesBuilder.cpp:769-770):

if (all_sinks_support_parallel_insert && (settings[Setting::parallel_view_processing] || !isViewsInvolved()))
    sink_stream_size = max_insert_threads;

MergeTree supports parallel insert and there are no MVs, so sink_stream_size = max_insert_threads. Each of those sinks owns its own MergeTreeDataPartWriterWide. (This is the buildInsertSelectPipeline path — buildInsertPipeline for plain INSERT hardcodes max_insert_threads=1 at :774, which is what threw me off when I wrote the previous comment.)

Per writer: one MergeTreeWriterStream per column substream. MergeTreeDataPartWriterWide::addStreams (src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp:140) iterates substreams and constructs one MergeTreeWriterStream per substream:

column_streams.emplace(stream_name, std::make_unique<MergeTreeWriterStream>(
    stream_name, data_part_storage, ..., compression_codec,
    max_compress_block_size, marks_compression_codec,
    settings.marks_compress_block_size, query_write_settings));

Each MergeTreeWriterStream holds (src/Storages/MergeTree/MergeTreeWriterStream.h:47-56):

  • plain_file: WriteBufferFromFileBase — constructed via data_part_storage->writeFile(..., max_compress_block_size_, ...). On the s3_no_cache policy this is WriteBufferFromS3, whose own buffer cap is min(buf_size_, DBMS_DEFAULT_BUFFER_SIZE) = min(max_compress_block_size, 1 MiB) (src/IO/WriteBufferFromS3.cpp:111).
  • compressor: CompressedWriteBuffer — adaptive when min_columns_to_activate_adaptive_write_buffer (500) ≤ column count. Starts at adaptive_write_buffer_initial_size = 16 KiB and grows to max_compress_block_size.
  • Marks file + marks compressor — small (marks_compress_block_size = 64 KiB).

So per writer ≈ num_columns × (≈1 MiB plain_file + ≤1 MiB compressor + small marks). For metric_log with 1721 columns and max_compress_block_size = 1 MiB, that's about 1.7 GiB minimum and ~3.4 GiB at the upper bound, per writer. Multiply by max_insert_threads = 3 ⇒ ~5 GiB minimum, easily over max_memory_usage = 4.66 GiB.

The CI stack confirms exactly this. From the failing run on arm_binary, sequential:

5. MemoryTracker::allocImpl(...)                                                 # 4.66 GiB cap hit
8. Allocator<false, false>::alloc(unsigned long, unsigned long)
9. DB::Memory<Allocator<false, false>>::alloc(unsigned long)                     # 1.09 MiB chunk
10. WriteBufferFromFileBase::WriteBufferFromFileBase(unsigned long, ...)
11. WriteBufferFromS3::WriteBufferFromS3(...)                                    # new column stream's plain_file
12. std::make_unique<DB::WriteBufferFromS3, ...>(...)
... (path leads back through MergeTreeWriterStream ctor)

Allocating chunk: 1.09 MiB — the WriteBufferFromS3 init buffer for one column substream. Cumulative footprint at the moment of OOM: 4.66 GiB. With ~5160 streams across 3 writers each at ~1 MiB, ~5 GiB cumulative is the expected shape.

Local measurement. Debug build on local disk (no S3, so WriteBufferFromFile not WriteBufferFromS3 — smaller per-stream footprint, but the scaling shape is identical) on the same 1721-column table, INSERT 4000 rows distributed across all writers:

max_insert_threads peak memory_usage (MiB)
1 6559.3
2 6746.3
3 6984.1
4 7369.0
8 8131.4

About +200-400 MiB per added writer on local disk. On S3 the per-writer delta is much larger because WriteBufferFromS3 holds multiple in-flight buffers per stream while uploads complete (via BufferAllocationPolicy), plus the 1.09 MiB init buffer per stream regardless of the query-level max_compress_block_size = 567430 because of the std::min(buf_size_, DBMS_DEFAULT_BUFFER_SIZE) cap.

Why the fix preserves the test. The test asserts on memory consumption of OPTIMIZE FINAL, not on the INSERT writer footprint. Setting max_insert_threads = 1 reduces the sink pipeline to a single writer (one set of 1721 column streams) and removes the OOM trigger, while leaving the merge-path memory check (the actual subject of the test) unchanged.

cc @PedroTadim

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

First, no need to ping random people

Secondly, I don't think that this is true, I tried to reproduce it and failed, provide SQL queries that I can try that will show bigger memory usage.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai can you find the real reason?

@groeneai groeneai May 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes - see the full analysis in #104697 (comment) . TL;DR: max_insert_threads is a red herring (flat memory across N=1..16 confirmed empirically). The real cause is per-column writer stream allocation: 1721 cols × ~2 MiB (1 MiB WriteBufferFromS3 + 1 MiB compressor when adaptive is OFF) ≈ 3.4 GiB baseline, which leaves only ~1 GiB headroom under the default 5 GB max_memory_usage cap. The test's min_columns_to_activate_adaptive_write_buffer = 0 is what forces adaptive OFF for INSERT. Fix in 9dd332d: enable adaptive during INSERT (drops peak from ~3.5 GiB to ~190 MiB), ALTER it OFF before OPTIMIZE so the merge still exercises the per-stream 1 MiB pattern that max_merge_delayed_streams_for_parallel_write bounds.

groeneai and others added 2 commits May 13, 2026 20:17
@azat asked for one-sentence comments instead of multi-line blocks.
- no-tsan tag reason: collapsed 4 lines to 1, matching the style of
  the existing no-fasttest / no-flaky-check tag explanations
- max_insert_threads pinning rationale: collapsed 10 lines to 1
  sentence referencing ClickHouse#102961 as the cause of the memory blowup

No behaviour change; comment-only edit.

Review: ClickHouse#104697 (comment)
The OOM during `INSERT INTO metric_log SELECT * FROM generateRandom() LIMIT 10`
on `arm_binary` (and similar non-sanitizer configs) was attributed to
`max_insert_threads` fanning out across writer threads. Empirical measurement
on a local CH server with the test's exact `s3_no_cache` storage policy shows
this is not the case: peak `memory_usage` is essentially flat (3.55-3.61 GiB)
across `max_insert_threads` = 1, 2, 4, 8, 16 with 10 input rows. Only one
writer ever calls `initStreamsIfNeeded` because the 10 rows fit in a single
block.

The real reason is that `min_columns_to_activate_adaptive_write_buffer = 0`
disables the adaptive write buffer for non-dynamic substreams. In
`MergeTreeDataPartWriterWide::addStreams`, the condition
`(settings.min_columns_to_activate_adaptive_write_buffer && columns_list.size() >= ...)`
short-circuits to false when the threshold is 0. So each of the 1700+ column
streams pre-allocates `max_compress_block_size` (~1 MiB) for the compressor and
another ~1 MiB initial buffer for `WriteBufferFromS3` (capped at
`DBMS_DEFAULT_BUFFER_SIZE`). Total writer footprint per part is therefore
1721 columns x ~2 MiB ~ 3.4 GiB, which leaves only ~1 GiB of headroom under
the default 5 GiB `max_memory_usage` cap and easily trips on allocator
variance.

Fix: enable adaptive write buffer during INSERT
(`min_columns_to_activate_adaptive_write_buffer = 100`), which keeps each
compressor at the 16 KiB adaptive initial size and drops the INSERT peak from
~3.5 GiB to ~190 MiB. Flip back to 0 via ALTER right before OPTIMIZE so the
merges still exercise the per-stream ~1 MiB allocation pattern that the test
is designed to bound via `max_merge_delayed_streams_for_parallel_write`. Both
assertions (no merge over 1 GiB at =100, one merge over 1 GiB at =10000)
remain valid; verified locally on s3_no_cache.

The `SET max_insert_threads = 1` line was a placebo (no measurable memory
effect) so it is removed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@azat you were right - max_insert_threads is not the cause. Apologies for the noise. Here is the real story.

Empirical: max_insert_threads has no measurable effect on this INSERT

Local CH server + local MinIO (port 11111) + test's exact s3_no_cache storage policy + 1726-column metric_log-shaped table. Peak memory_usage from system.query_log:

max_insert_threads peak memory_usage
1 3.55 GiB
2 3.57 GiB
4 3.58 GiB
8 3.59 GiB
16 3.61 GiB

Variation is ~60 MiB across the full range. With the full CI setting bundle (--max_threads=32 --min_compress_block_size=1873194 --max_compress_block_size=567430 --use_uncompressed_cache=1 ...): 3.56 GiB at N=3 vs 3.57 GiB at N=1. Flat.

The reason max_insert_threads does not matter here: with only 10 input rows the entire chunk goes to a single writer thread. The other writers in the pipeline.resize(sink_stream_size) fan-out never receive a chunk, so they never call initStreamsIfNeeded and never allocate column streams. Only one writer is ever active. My earlier claim that footprint scaled linearly with max_insert_threads was wrong.

The actual root cause

The 3.55 GiB baseline is the per-column writer stream allocation in MergeTreeDataPartWriterWide::addStreams. Each of the 1721 columns gets a MergeTreeWriterStream that constructs:

  1. plain_file = WriteBufferFromS3(...) - WriteBufferFromS3.cpp:111 allocates min(buf_size_, DBMS_DEFAULT_BUFFER_SIZE) = 1 MiB for the initial buffer.
  2. compressor = CompressedWriteBuffer(..., max_compress_block_size, use_adaptive_write_buffer, ...) - when adaptive is OFF, allocates max_compress_block_size (~1 MiB default) up front.

So per stream ~ 2 MiB, and 1721 streams x ~2 MiB ~ 3.4 GiB. Matches the measured 3.55 GiB.

The test's min_columns_to_activate_adaptive_write_buffer = 0 is what forces adaptive OFF. The condition in MergeTreeDataPartWriterWide.cpp:200-202:

query_write_settings.use_adaptive_write_buffer =
    (settings.min_columns_to_activate_adaptive_write_buffer
     && columns_list.size() >= settings.min_columns_to_activate_adaptive_write_buffer)
    || (settings.use_adaptive_write_buffer_for_dynamic_subcolumns
        && ISerialization::isDynamicSubcolumn(...));

With the threshold at 0, the first conjunction is (0 && ...) = false, and for non-dynamic substreams the second conjunction is also false. So adaptive is OFF for all 1721 columns and each one pre-allocates the full max_compress_block_size.

The default max_memory_usage = 5G (=4.66 GiB) leaves only ~1 GiB of headroom over the 3.55 GiB baseline. That gap is easily eaten by build-flavor allocator differences (arm_binary jemalloc dirty pages, allocator state), and the test trips.

I verified both directions with a --max_memory_usage low enough to be over the cliff:

max_memory_usage = 3 GB, unfixed test:
  Code: 241. MEMORY_LIMIT_EXCEEDED: would use 2.80 GiB (chunk 4.17 MiB), maximum: 2.79 GiB
  (during INSERT)

max_memory_usage = 3 GB, fixed test (this commit): exit 0, both assertions hold

Concrete SQL you can run yourself

Pre-req: s3_no_cache storage policy (requires tests/config/config.d/storage_conf.xml and a local MinIO/S3 on http://localhost:11111/test/special/, as the CI test does). On local disk the OOM does not reproduce - this only manifests on S3 because WriteBufferFromS3 is the path that allocates 1 MiB per stream up front; WriteBufferFromFile does not.

DROP DATABASE IF EXISTS repro;
CREATE DATABASE repro;
USE repro;

CREATE TABLE m AS system.metric_log
ENGINE = MergeTree PARTITION BY () ORDER BY ()
SETTINGS storage_policy = 's3_no_cache',
  min_rows_for_wide_part = 0, min_bytes_for_wide_part = 0,
  vertical_merge_algorithm_min_rows_to_activate = 0,
  vertical_merge_algorithm_min_columns_to_activate = 1,
  min_bytes_for_full_part_storage = 0,
  max_merge_delayed_streams_for_parallel_write = 100,
  merge_selector_base = 1000,
  min_columns_to_activate_adaptive_write_buffer = 0,  -- adaptive OFF, high memory
  auto_statistics_types = '';

-- Baseline (adaptive OFF): ~3.55 GiB peak
INSERT INTO m SELECT * FROM generateRandom() LIMIT 10
SETTINGS optimize_trivial_insert_select = 0, log_comment = 'adaptive_off';

ALTER TABLE m MODIFY SETTING min_columns_to_activate_adaptive_write_buffer = 100;
TRUNCATE TABLE m;

-- With adaptive ON: ~190 MiB peak (19x reduction)
INSERT INTO m SELECT * FROM generateRandom() LIMIT 10
SETTINGS optimize_trivial_insert_select = 0, log_comment = 'adaptive_on';

SYSTEM FLUSH LOGS query_log;
SELECT log_comment, formatReadableSize(memory_usage) AS peak
FROM system.query_log
WHERE current_database = 'repro' AND log_comment IN ('adaptive_off','adaptive_on') AND type='QueryFinish'
  AND query LIKE '%INSERT%'
ORDER BY event_time;

Fix in 9dd332d42eb3

  • Removed the SET max_insert_threads = 1 placebo (no measurable memory effect, as you said)
  • Changed the CREATE TABLE setting min_columns_to_activate_adaptive_write_buffer = 0 to = 100, so the adaptive buffer is ON during the INSERT (1726 cols >= 100). INSERT peak drops to ~190 MiB
  • Added ALTER TABLE metric_log MODIFY SETTING min_columns_to_activate_adaptive_write_buffer = 0 between INSERT and OPTIMIZE so the merges still exercise the per-stream ~1 MiB allocation pattern that max_merge_delayed_streams_for_parallel_write is supposed to bound

Both assertions still hold (verified 3 runs on a fresh database each time at max_memory_usage = 5000000000):

  • max_merge_delayed_streams_for_parallel_write = 100 -> count = 0 (no merge over 1 GiB)
  • max_merge_delayed_streams_for_parallel_write = 10000 -> count = 1 (one merge over 1 GiB, ~2.39 GiB)

no-tsan is kept because the TSan slowness on the OPTIMIZE FINAL is a separate concern (slow merge, not memory); the INSERT memory fix does not change merge time under TSan.

@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: No C/C++ source files changed — skipping uncovered code analysis.

Newly covered by added/modified tests: 411 line(s), 85 function(s) across 120 file(s) · Details

Top files
  • src/Storages/StorageReplicatedMergeTree.cpp: 47 line(s)
  • src/Storages/MergeTree/ReplicatedMergeTreeRestartingThread.cpp: 24 line(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesChanges.h: 14 line(s), 32 function(s)
  • src/AggregateFunctions/TimeSeries/AggregateFunctionTimeseriesLinearRegression.h: 14 line(s), 32 function(s)
  • src/Common/QueryFuzzer.cpp: 12 line(s)

Full report

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai why the 02843_context_has_expired test failed? Can you check and maybe create a PR to fix it?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim the 02843_context_has_expired failure here is unrelated to PR #104697 (which only touches the 03393 test). It is a known chronic flake with root cause and fix already identified.

Root cause. tests/queries/0_stateless/01658_read_file_to_stringcolumn.sh writes a, b, c into ${USER_FILES_PATH} and only removes them via a manual rm block at the bottom of the script. The script runs under set -e. Any failing query in between (e.g. one of the many error-path assertions in 01658) aborts the script and leaves the files behind on the runner for the rest of that CI session.

Once ${USER_FILES_PATH}/a exists, 02843's assertion

SELECT 1 in (SELECT file(materialize('a'))) -- { serverError FILE_DOESNT_EXIST }

reads the leaked file instead of throwing error 107, and the test reports The query succeeded but the server error '107' was expected. The diagnosis output on the failing run confirms this is not a randomization issue (377/377 fails with no randomized settings) which lines up exactly with persistent on-disk state.

Fix in flight: PR #105602. Two test-only changes:

  1. 01658: add trap cleanup EXIT so the files cannot leak even on mid-script abort; remove the redundant manual rm block.
  2. 02843: replace file(materialize('a')) with file(materialize('02843_nonexistent_'||generateUUIDv4())) as defense-in-depth against any future test that leaks a short filename.

Verified locally with ${USER_FILES_PATH}/a pre-seeded: pre-fix 02843 fails 50/50, post-fix passes 50/50.

For #104697's merge gating: this 02843 failure is unrelated and safe to re-run away. I will keep this PR pending on the actual review of commit 9dd332d (adaptive write buffer root-cause fix).

@azat azat changed the title Stabilize 03393_max_merge_delayed_streams_for_parallel_write on TSan+S3 tests: fix 03393_max_merge_delayed_streams_for_parallel_write flakiness under TSan+S3 and in general Jun 2, 2026
@azat
azat enabled auto-merge June 2, 2026 20:08
@azat
azat added this pull request to the merge queue Jun 2, 2026
Merged via the queue into ClickHouse:master with commit 502e8a8 Jun 2, 2026
163 of 166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors 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.

5 participants