Skip to content

Pin the part format in 02228_merge_tree_insert_memory_usage - #111929

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:pin-02228-compact-part-format
Jul 27, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:pin-02228-compact-part-format

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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):

...

Description

02228_merge_tree_insert_memory_usage asserts that two INSERTs with
max_insert_delayed_streams_for_parallel_write=1000000 FAIL with MEMORY_LIMIT_EXCEEDED
under max_memory_usage='30Mi'. Under some randomized MergeTree settings both INSERTs
succeed instead, so the negative assertion never fires:

The query succeeded but the server error '241' was expected (query: insert into data_02228 ...)
The query succeeded but the server error '241' was expected (query: insert into data_rep_02228 ...)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109408&sha=44dfafb3dcee3c3528e7b5c4f0ca00c04e4aebd8&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

CIDB, 30 days: 5 hits on 5 unrelated pull requests, 0 on master (~48.7k OK runs), on
arm_binary parallel, amd_debug parallel, amd_tsan parallel and
amd_asan_ubsan distributed plan. The runner's --diagnose-random-settings minimized the
culprit to the same three MergeTree settings in every fully-minimized sample, for example
--min_bytes_for_wide_part 0 --min_bytes_for_full_part_storage 509915446 --min_columns_to_activate_adaptive_write_buffer 2.

Root cause: the assertion is a memory-footprint assertion. With no early flush, the write
buffers of all 100 partitions are held at once and must exceed the 30 MiB budget. Compact
parts, the format these ~1.3 KB parts get by default, keep a ~1 MiB compressor per delayed
part, so the budget is always exceeded. The runner sets min_bytes_for_wide_part to 0 with
probability 0.3, which flips the parts to Wide, where the buffer sizes become
setting-dependent: min_columns_to_activate_adaptive_write_buffer at or below the table's 3
columns starts each stream at 16 KiB, and a large min_bytes_for_full_part_storage selects
Packed storage whose underlying file buffer allocates nothing. The footprint collapses well
under 30 MiB, the INSERT succeeds and the expectation fails. This is not a product bug: the
lower memory use is the intended effect of b243331. The test simply never pinned the
part format its assertion is calibrated for.

Fix: pin min_bytes_for_wide_part = 10485760, the non-cloud default, at CREATE TABLE level
on both tables. MergeTreeData::choosePartFormat selects Compact when any one of the bytes,
rows or level terms is satisfied, so this single setting guarantees Compact and makes the whole
Wide-only mechanism unreachable. Table-level SETTINGS win over the randomizer, which only
injects a setting when it is absent. The assertion, the memory budget and the delayed-stream
settings are unchanged.

Coverage note: the test no longer exercises the Wide adaptive-write-buffer path under
randomization. That path has dedicated tests
(03770_min_columns_to_activate_adaptive_write_buffer.sql.j2,
03393_max_merge_delayed_streams_for_parallel_write.sql, 03261_delayed_streams_memory.sql),
and Compact is the regime this test was written for in 3a5a39a.

Verification, debug build:

  • Without the pin, with each of the three fully-minimized culprit sets: FAIL, showing exactly
    the two inverse-assertion lines. With the pin: OK. Both directions, all three sets.
  • Mechanism: with the pin present and --min_bytes_for_wide_part 0 injected, system.parts
    shows Compact; without the pin, same injection, it shows Wide.
  • 150 runs with full randomization: 150/150 OK.
  • Seven adversarial MergeTree combinations aimed at shrinking Compact buffers
    (max_compress_block_size 1, compact_parts_max_bytes_to_buffer 1024,
    compact_parts_max_granules_to_buffer 1, min_bytes_for_full_part_storage 536870912,
    compress_per_column_in_compact_parts 1, ratio_of_defaults_for_sparse_serialization 0.0,
    min_columns_to_activate_adaptive_write_buffer 0): all OK.

The test asserts that two INSERTs with
max_insert_delayed_streams_for_parallel_write=1000000 fail with
MEMORY_LIMIT_EXCEEDED under max_memory_usage='30Mi'. Under some randomized
MergeTree settings both INSERTs succeed instead, so the negative assertion
never fires. CIDB shows 5 hits on 5 unrelated pull requests and 0 on master
in 30 days, and the runner's ddmin minimization names the same three settings
every time, always including min_bytes_for_wide_part=0.

The assertion is a memory-footprint assertion: with no early flush the write
buffers of all 100 partitions are held at once and must exceed the budget.
Compact parts, the format these ~1.3 KB parts get by default, keep a ~1 MiB
compressor per delayed part, so the budget is always exceeded. Setting
min_bytes_for_wide_part to 0 flips the parts to Wide, where buffer sizes
become setting-dependent: min_columns_to_activate_adaptive_write_buffer at or
below the table's 3 columns starts each stream at 16 KiB, and a large
min_bytes_for_full_part_storage selects Packed storage whose underlying file
buffer allocates nothing. The footprint collapses below 30 MiB and the INSERT
succeeds. The lower memory use is correct and intended (b243331); the
test simply never pinned the part format its assertion is calibrated for.

Pin min_bytes_for_wide_part to the non-cloud default at CREATE TABLE level on
both tables. MergeTreeData::choosePartFormat ORs the bytes, rows and level terms, so
this single setting guarantees Compact and makes the Wide-only mechanism
unreachable. Table-level SETTINGS win over the randomizer, which only injects
a setting when it is absent. The assertion, the memory budget and the
delayed-stream settings are unchanged.

Verified on a debug build: fails without the pin and passes with it on all
three fully-minimized culprit sets, 150/150 under full randomization, and
across seven adversarial combinations aimed at shrinking Compact buffers.
system.parts confirms Compact with the pin and Wide without it under the same
injected settings.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus an
independent cold code review by the reviewing session (6 nits, no blockers or majors).

# Sev Finding Verdict Evidence / action
1 💡 min_bytes_for_wide_part = 0 probability stated as 0.3 AGREE threshold_generator(0.3, 0.3, 0, 1GiB) returns min_val when random() <= 0.3 (tests/clickhouse-test:1297-1309, 1697). Claim exact, no change
2 💡 Description named a non-existent symbol choosePartTypeAndStorage AGREE — fixed The selector is MergeTreeData::choosePartFormat (MergeTreeData.cpp:5710); the description now names it
3 💡 One ddmin culprit set lacks min_columns_to_activate_adaptive_write_buffer, is it covered? AGREE Yes. That setting has exactly one reader in the tree, MergeTreeDataPartWriterWide.cpp:207; pinning Compact makes the whole Wide path unreachable, so all 5 samples are covered
4 💡 Test liveness: would this still fail if the pin were reverted? AGREE Yes, by ClientBase::addMergeTreeSettings (ClientBase.cpp:3458-3465, injects only when absent) plus the satisfies() OR at MergeTreeData.cpp:5720-5727. Assertion, 30 MiB budget and both delayed-stream values are byte-identical in the diff
5 💡 Two invariant carriers not in the plan's table AGREE Both non-actionable: canUsePolymorphicParts cannot fire (index_granularity_bytes is drawn from randint(1024, 30MiB), never 0), and tests/config/config.d/polymorphic_parts.xml is beaten by table-level SETTINGS — the pin also immunizes the test under --wide-parts
6 💡 Packed storage does reduce the Compact footprint, contrary to the plan's reasoning AGREE Measured 322.71 MiB (Full) vs 119.61 MiB (Packed) at a 3 GiB budget. Conclusion unchanged: 119.61 MiB is still ~4x the 30 MiB budget, and the adversarial matrix exercises Packed and Full directly

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260726-014400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? YES. clickhouse-test --no-random-settings --merge-tree-settings "--min_bytes_for_wide_part 0 --min_bytes_for_full_part_storage 509915446 --min_columns_to_activate_adaptive_write_buffer 2" 02228_merge_tree_insert_memory_usage fails 100% of the time, printing exactly the two "The query succeeded but the server error '241' was expected" lines seen in CI.
b Root cause explained? YES. Compact parts keep a CompressedWriteBuffer at the default 1 MiB per delayed part, so 100 unflushed partitions always exceed max_memory_usage='30Mi'. The runner sets min_bytes_for_wide_part = 0 with p=0.3, flipping these ~1.3 KB parts to Wide, where min_columns_to_activate_adaptive_write_buffer at or below the table's 3 columns starts each stream at 16 KiB and a large min_bytes_for_full_part_storage selects Packed storage with a 0-byte file buffer. The footprint drops under the budget, the INSERT succeeds, and the negative assertion fails.
c Fix matches root cause? YES. Pinning min_bytes_for_wide_part = 10485760 (the non-cloud default) restores the Compact regime the assertion is calibrated for. No widened bound, no relaxed or removed serverError expectation, no blanket no-random-merge-tree-settings, no data-size reduction, no product change.
d Test intent preserved / new tests added? YES. The assertion, the 30 MiB budget, the partition count, the row count and both max_insert_delayed_streams_for_parallel_write values are untouched, so the test still catches the deferred-final-part-flush regression it was added for in 3a5a39a. Test-only change, so no new regression test is owed.
e Both directions demonstrated? YES, on all three fully-minimized ddmin culprit sets from CIDB: FAIL without the pin, OK with it. The no-randomization master-config baseline passes in both cases. 150/150 OK under full randomization.
f Fix is general across code paths? YES. Both tables get the identical pin: data_02228 (CollapsingMergeTree, MergeTreeSink) and data_rep_02228 (ReplicatedCollapsingMergeTree, ReplicatedMergeTreeSink), the symmetric sink path. CIDB shows both INSERTs failing together in every sample and the local repro reproduces both lines.
g Fix generalizes across inputs (params/datatypes/wrappers)? YES. Seven adversarial MergeTree combinations aimed at shrinking the Compact footprint all pass: min_columns_to_activate_adaptive_write_buffer 0/1, max_compress_block_size 1, min_compress_block_size 1, compact_parts_max_bytes_to_buffer 1024, compact_parts_max_granules_to_buffer 1, min_bytes_for_full_part_storage 0 and max, compress_per_column_in_compact_parts 1, ratio_of_defaults_for_sparse_serialization 0.0. min_rows_for_wide_part and min_level_for_wide_part need no pin because MergeTreeData::choosePartFormat ORs the three terms, so the bytes term alone yields Compact.
h Backward compatible? (maintainer-approved exception only) N/A. Test-only change: no setting default changed, so no SettingsChangesHistory.cpp entry; no serialization or format change; no new setting.
i Invariants and contracts preserved? YES. No source is touched, so no function contract, data-structure invariant or concurrency contract is affected. The test-level invariant, that 100 unflushed Compact parts exceed 30 MiB, is now explicit instead of accidental.

Session id: cron:clickhouse-impl-slot-7:20260726-011000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze — could you review this? Test-only: the negative MEMORY_LIMIT_EXCEEDED assertion in 02228 silently stops firing when the settings randomizer sets min_bytes_for_wide_part = 0 and flips the parts from Compact to Wide, so the pin restores the part format the 30 MiB assertion is calibrated for.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c3877f3]

Summary: ✅


AI Review

Summary

This PR makes 02228_merge_tree_insert_memory_usage deterministic under randomized MergeTree settings by pinning min_bytes_for_wide_part on both test tables, so the MEMORY_LIMIT_EXCEEDED assertion stays in the Compact-part regime it relies on. I reviewed the changed test together with the current addMergeTreeSettings injection path and MergeTreeData::choosePartFormat, and I do not see a remaining correctness or coverage gap in the fix.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 26, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jul 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 53c4f14

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) wide-typed key comparison inserts a CAST into the monotonic chain, so matchesExactContinuousRange() promises exact continuity it cannot deliver #109023 (ours, open)
Mergeable Check / PR rollup of the above resolved via the owner above

Server log, which is what pins the owner:

Inconsistent KeyCondition behavior: matchesExactContinuousRange() reported an exact continuous
range, but the mark range [124, 150) (exact subrange [125, 149)) of part all_3_3_0 is not exactly
continuous. Participating conditions: (_CAST(column 0) in ['5', '5']), (column 1 in [995, 995])
query: SELECT count() RESPECT NULLS FROM t_big WHERE (g = 5) AND (r = 995)
       SETTINGS use_lightweight_primary_key_index_analysis = 1

_CAST on the leading key column means the monotonic function chain is non-empty, which is exactly
the case #109023 stops treating as Constraint::POINT.

Not caused by this PR: the diff pins part format and memory-related settings in
02228_merge_tree_insert_memory_usage; it touches no engine code and this abort is in
primary-key mark-range analysis on an unrelated fuzzer table.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111929&sha=53c4f1463ada78c851931fd04a67a463cff633fc&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Session id: cron:our-pr-ci-monitor:20260726-083000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c3877f3

No failures to own on this head. All 174 check-runs are complete, Finish Workflow,
Config Workflow, Mergeable Check and CH Inc sync are green, and the PR rollup is green.
CIDB reports zero FAIL or ERROR test rows for this commit.

This head is a plain merge of master into the branch, so it carries no source change of mine. The
previous ledger's Stress test KeyCondition line (STID 5182-2f27, owner #109023) did not recur
here.

Session id: cron:our-pr-ci-monitor:20260727-073000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit e596609 Jul 27, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 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.

3 participants