Skip to content

Disable regular merges in 03518_alter_logical_race so the ALTER's mutation is not starved - #114028

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-03518-alter-mutation-starved-by-merges
Aug 10, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-03518-alter-mutation-starved-by-merges

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026

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

03518_alter_logical_race fails on Stateless tests (amd_debug, parallel) with
TIMEOUT: ALTER TABLE alter_table DROP COLUMN h plus NO ALTER PROGRESS: completed zero full ALTER ADD/MODIFY/DROP cycles, its own progress guard firing
(CI report).

Root cause: DROP/MODIFY COLUMN on a physical column needs a data mutation, which advances
only when the merge-selecting task creates a MUTATE_PART entry per part. try_assign_merge
tries a regular merge first and returns EntryCreated before reaching mutation selection, then
reschedules immediately. This test's concurrent INSERTs keep mergeable ranges permanently
available, so every pass goes to a merge and the mutation starves: 2471 MERGE_PARTS against 44
MUTATE_PART. Strict alter-version ordering then blocks the second worker at metadata too, so
zero cycles complete. #108060 went one layer too shallow, unpinning count throttles the
mutation never reaches.

Fix: disable regular merges for the table (max_bytes_to_merge_at_max_space_in_pool = 0) so the
selector reaches mutation selection. Mutations are unaffected, reading
getMaxSourcePartBytesForMutation instead. With merges off parts accumulate, so
parts_to_delay_insert / parts_to_throw_insert are raised. Same approach as
04652_mutate_part_ahead_of_table_metadata_version.sh. SYSTEM STOP MERGES would not work even
table-scoped: it takes the merges_blocker lock, which
ReplicatedMergeTreeQueue::shouldExecuteLogEntry applies to MUTATE_PART too.

No assertion is weakened and the guard is untouched, so this makes the promised race happen
rather than tolerating its absence. Mutation-side column resolution is exercised 5.7x more
(MUTATE_PART 4,958 -> 28,249); the merge-side path under concurrent ADD/DROP COLUMN stays
covered by 01079_parallel_alter_add_drop_column_zookeeper and 03144_..._on_steroids, which
keep merges on and force them with OPTIMIZE FINAL. Raising the timeout was rejected: the
starved mutation decelerated with no bound.

Validation, same box and load, only the test file differing: master fails 5/50 with the
signature above; with the fix 50/50 on debug and 50/50 on ASAN. p95 drops 77.5s to
32.7s, nothing reaches the 180s hard deadline, the settings verifiably applied
(0 MERGE_PARTS), no Too many parts.

The test fails on Stateless tests (amd_debug, parallel) with

  TIMEOUT: ALTER TABLE alter_table DROP COLUMN h
  NO ALTER PROGRESS: completed zero full ALTER ADD/MODIFY/DROP cycles

i.e. its own progress guard firing because no ALTER worker completed a cycle.

DROP COLUMN and MODIFY COLUMN on a physical column require a data mutation
(AlterCommands.cpp isRequireMutationStage), and StorageReplicatedMergeTree::alter
waits for it. A replicated mutation only advances when the merge-selecting task
creates a MUTATE_PART entry per part, but try_assign_merge attempts a regular
merge FIRST and returns AttemptStatus::EntryCreated at
StorageReplicatedMergeTree.cpp:4505, before control reaches the mutation
selection block at :4531-4560, then reschedules immediately at :4590-4591.

This test's concurrent INSERT stream keeps mergeable ranges permanently
available, so every selector pass is spent on a merge and the mutation is
starved. In the failing run 2471 MERGE_PARTS entries were created against 44
MUTATE_PART, with the mutation rate decaying from 41 to 0 entries per minute as
the part population grew. Strict alter-version ordering
(ReplicatedMergeTreeAltersSequence::canExecuteMetaAlter) then prevented the
second worker from applying even its DROP's metadata, which is why zero cycles
completed rather than one.

PR ClickHouse#108060 chased this one layer too shallow: it unpinned the mutation count
throttles (max_replicated_mutations_in_queue,
number_of_free_entries_in_pool_to_execute_mutation), but a mutation that never
reaches the selection block never consults them. Neither limit fired in this run.

Disable regular merges for the table instead. max_bytes_to_merge_at_max_space_in_pool = 0
short-circuits getMaxSourcePartsBytesForMerge, so can_assign_merge is false and
control falls through to mutation selection on every pass. Mutations are
unaffected: that path reads getMaxSourcePartBytesForMutation, a different
function. With merges off parts accumulate unmerged, so parts_to_delay_insert and
parts_to_throw_insert are raised above the per-partition defaults (1000/3000) to
keep the test's INSERT side from being delayed or rejected, which would break the
INSERT progress guard. max_parts_in_total (100000, whole-table) is left alone.

04652_mutate_part_ahead_of_table_metadata_version.sh uses the same setting on
ReplicatedMergeTree for the same purpose. SYSTEM STOP MERGES is table-scoped and
would not need no-parallel, but it is still not usable here: it takes the
merges_blocker action lock, and ReplicatedMergeTreeQueue::shouldExecuteLogEntry
applies that lock to MUTATE_PART as well as MERGE_PARTS, so it would block the
mutation this needs to let through.

No assertion is weakened: the test asserts ALTER cycle progress, INSERT progress
and an empty reference, and nothing reads system.parts, part counts or merge
state. The trade is narrower than "no coverage lost": with merges off this test
no longer exercises the merge-side column resolution path (MERGE_PARTS 33152 to 0
over the two 50x arms), while the mutation-side path is exercised 5.7x more
(MUTATE_PART 4958 to 28249). The merge arm under concurrent ADD/DROP COLUMN stays
covered by 01079_parallel_alter_add_drop_column_zookeeper.sh and
03144_parallel_alter_add_drop_column_zookeeper_on_steroids.sh, which keep merges
enabled and additionally force them with OPTIMIZE TABLE ... FINAL. The ALTERs
still carry no IF [NOT] EXISTS, so NOT_FOUND_COLUMN_IN_BLOCK or DUPLICATE_COLUMN
would still fail the run, and the progress guard keeps full strength. Raising
MAX_TIMEOUT was rejected: the starved mutation was decelerating with no bound,
and the healthy amd_debug p50 is 11.7s against this run's 182s.

Validated on one box under identical load, with only the test file differing:
pristine master fails 5/50 under tests/clickhouse-test --test-runs 50, carrying
the exact signature above; with this change 50/50 pass on debug and 50/50 on
ASAN. p95 drops from 77.5s to 32.7s and no run reaches the 180s hard deadline.
Confirmed the settings took effect rather than being silently ignored (0
MERGE_PARTS and 28249 MUTATE_PART entries across the 50 debug runs, 0 and 23359
on ASAN) and that no Too many parts or insert delay line appeared in either.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111534&sha=b8c37b85647510a9b374b77fadaeeddd8ab957f5&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, no blockers)

An independent model reviewed this change cold against the source; I adjudicated its findings.
Both rounds converged on one question: does the test still prove the mechanism it claims?

⚠️ Can the test pass without ever executing a MUTATE_PART? (raised twice) — disagreed, but it
corrected my own earlier reasoning.

My first-round answer was that a completed ALTER cycle already implies a data mutation. That is
wrong, and I am retracting it: EphemeralLocksInAllPartitions creates no locks when
/block_numbers has no partitions, so a mutation against a table with zero parts finalizes with
empty parts_to_do and no MUTATE_PART entry.

The finding still does not hold, for a different reason. It needs every completed cycle to run
against an empty table, and within_budget prevents that: below the 10s soft deadline it returns
"keep going" unconditionally, and past it stops only once both progress markers exist. So an
ALTER worker cannot stop after one empty cycle - it keeps cycling for at least 10s while INSERTs
land at 94.7 parts/sec (matching the CI failing run within 0.2%), so the table is non-empty for
effectively all of that window. Both early exits are closed too: the shutdown path waives the
progress guard outright, and the other is reachable only after the window has elapsed.

Measured across all 101 validation runs (51 debug + 50 ASAN, counted per runner database), the
MUTATE_PART floor is 280 per run (p50 562 debug, 500 ASAN). No run came near zero.

The proposed system.part_log oracle was declined on its own merits as well: it would make a
concurrency verdict depend on an async flush, and it pins how merges are suppressed rather than
the contract that the race was exercised, so a later legitimate change there would redden a green
test.

💡 p95 precision. The quoted 77.5s -> 32.7s uses a rank convention one step low. Applied to
both arms it understates the improvement (2.37x quoted, 2.56x actual); left as the conservative
number.

Round 1 also corrected two commit-message claims that were right in conclusion but wrong in
reasoning: SYSTEM STOP MERGES is table-scoped (the real reason it is unusable is that it takes
the merges_blocker lock, which shouldExecuteLogEntry applies to MUTATE_PART too), and the
coverage trade is now stated explicitly instead of as "no coverage lost".

Session id: cron:clickhouse-review-slot-48:20260809-103700

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. tests/clickhouse-test 03518_alter_logical_race --test-runs 50 on pristine master fails 5/50 with the verbatim CI signature (TIMEOUT: ALTER TABLE alter_table DROP COLUMN h + NO ALTER PROGRESS), every failure sitting at the test's 180s HARD_DEADLINE.
b Root cause explained? Yes. DROP/MODIFY COLUMN on a physical column needs a data mutation; a replicated mutation advances only when the merge-selecting task creates a MUTATE_PART entry per part. try_assign_merge tries a regular merge first and returns EntryCreated (StorageReplicatedMergeTree.cpp:4505) before reaching the mutation block (:4531-4560), then reschedules immediately (:4590-4591). The concurrent INSERT stream keeps mergeable ranges permanently available, so every pass is spent on a merge: measured 2471 MERGE_PARTS entries against 44 MUTATE_PART. Strict alter-version ordering (ReplicatedMergeTreeAltersSequence.cpp:82-88) then blocks the second worker at metadata, so zero cycles complete.
c Fix matches root cause? Yes. It removes exactly the preempting work that was measured to consume the selector passes. Not a widened bound, not a no-random-* tag, not a data reduction, not a relaxed guard. = 0 short-circuits getMaxSourcePartsBytesForMerge, making can_assign_merge false at :4434 so control falls through to mutation selection; mutations read a different function (getMaxSourcePartBytesForMutation) and are unaffected.
d Test intent preserved / new tests added? Yes, preserved; tests-only change with no assertion touched. Reading all 294 lines confirms the test asserts ALTER-cycle progress, INSERT progress and an empty reference, and reads nothing about system.parts, part counts or merge state. Coverage is not unchanged, though: with merges off this test no longer exercises the merge-side column resolution path (MERGE_PARTS 33,152 to 0 across the two 50x arms), while the mutation side is exercised 5.7x more (MUTATE_PART 4,958 to 28,249); the merge arm stays covered by 01079_parallel_alter_add_drop_column_zookeeper.sh and 03144_parallel_alter_add_drop_column_zookeeper_on_steroids.sh, which keep merges on and force OPTIMIZE ... FINAL. ALTERs still carry no IF [NOT] EXISTS, so NOT_FOUND_COLUMN_IN_BLOCK / DUPLICATE_COLUMN would still fail the run. The progress guard keeps full strength: this makes the race happen rather than tolerating its absence.
e Both directions demonstrated? Yes, same box, same load, same runner, only the test file differing: pristine master 45 passed / 5 FAILED; with the fix 50/50 passed on debug and 50/50 on ASAN. p95 77.5s to 32.7s, max 102.9s to 45.9s, and the 180s hard-deadline runs disappear entirely. Since the diff touches only a .sh file the binary is byte-identical by design (Build-ID 6c5283187e5b8c2a504e1d0d0fdd6fd2f696f543 before and after), which is the correct A/B shape here.
f Fix is general across code paths? N/A for the server (no src/ diff). Within the test the single CREATE TABLE is the only carrier, and all three ALTER statement types (ADD, MODIFY, DROP) use that table and that selector, so one change covers them all.
g Fix generalizes across inputs? N/A (test settings fix, no type or parameter surface introduced). The relevant axis is INSERT pressure: at the CI rate (measured 5693 parts/min locally vs CI's 5682) the fix is green 100/100. At 3x that rate, deliberately induced locally, the test can still exceed its budget because mutation throughput itself binds, which is a different, pre-existing regime that CI does not exhibit and this change does not claim to address.
h Backward compatible? Yes, vacuously: per-table settings inside one test file. No default changed, so no SettingsChangesHistory.cpp entry; no new setting, no experimental gate, no serialization or format change, no deletion logging.
i Invariants and contracts preserved? Yes. alter_sync stays default so the ALTER still waits for its mutation, which is what makes starvation observable. no-random-settings / no-random-merge-tree-settings are kept. max_parts_in_total (100000, whole-table) is untouched and never approached: Too many parts, TOO_MANY_PARTS and Delaying inserting are all 0 across both 50x windows, and the settings verifiably applied (0 MERGE_PARTS, 28,249 MUTATE_PART over the 50 debug runs; 0 and 23,359 on ASAN), so the pass is not vacuous. Also 0 Logical error, NOT_FOUND_COLUMN, DUPLICATE_COLUMN, Segmentation and no sanitizer report.

Session id: cron:clickhouse-impl-slot-7:20260809-044400

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun, could you review this? The test's concurrent INSERTs keep mergeable ranges always available, so the merge-selecting task returns EntryCreated on a regular merge before ever reaching mutation selection, and the ALTER's mutation starves (2471 MERGE_PARTS against 44 MUTATE_PART); disabling regular merges for the test table lets it through.

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

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78c1a6e]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel) FAIL
04722_count_substrings_cancellation FAIL cidb IGNORED

AI Review

Summary

This PR updates 03518_alter_logical_race.sh to disable regular background merges and raise the insert part-count thresholds so the MODIFY COLUMN mutation is no longer starved behind merge selection. I reviewed the current diff, the surrounding test logic, the related sibling tests the PR relies on for merge-path coverage, the prior PR discussion, and the live CI results; I did not find an actionable correctness, coverage, or metadata issue in the current change.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 9, 2026
@PedroTadim PedroTadim self-assigned this Aug 9, 2026
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 78c1a6e

Every failure below has an owner: a fixing PR (mine 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
Stateless tests (amd_tsan, parallel) / 04722_count_substrings_cancellation flaky, not caused by this PR: the diff is one line in 03518_alter_logical_race.sh and touches nothing this test exercises. The runner's own diagnosis rerun passed 2/2 with the same randomized settings. The failing line is constant_vector: cancelled before the pipeline started, i.e. the 1-second max_execution_time expired during parsing/analysis on a loaded runner, which the test deliberately reports as inconclusive rather than as a pass #114061 (external, open) — removes this test and the rest of the recently added cancellation family

Mergeable Check and the PR rollup are red only because they aggregate the row above.

Session id: cron:our-pr-ci-monitor:20260809-210000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 10, 2026
Merged via the queue into ClickHouse:master with commit d65909c Aug 10, 2026
179 of 181 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
bdeitte pushed a commit to bdeitte/ClickHouse that referenced this pull request Oct 23, 2026
…erges

`PARTITION BY b % 10` with a per-row `rand(2)` made every 1000-row INSERT
write 10 parts. ClickHouse#114028 disabled regular merges for this table so that
merges stop starving the ALTER's mutation, which removed the only bound on
the part count: each later ALTER mutation then has to rewrite every part
inserted before it, at one MUTATE_PART entry per merge-selecting pass, and
the last one of the chain can exceed the 120 s client timeout
(`TIMEOUT: ALTER TABLE alter_table DROP COLUMN i` on arm_binary, with 2419
and 1178 parts to rewrite in the two failing runs).

Both failure modes come from the 10-parts-per-INSERT rate, so cut it at the
source: `randConstant(2)` puts every INSERT into one partition (one part per
INSERT) while successive INSERTs still spread over all 10 partitions, and
regular merges are re-enabled by dropping max_bytes_to_merge_at_max_space_in_pool,
parts_to_delay_insert and parts_to_throw_insert. The ClickHouse#108060 throttle
overrides stay, as do the deadlines and the progress guards.

Local server with the CI test config, master file vs this change: 10.0 vs
1.0 parts per INSERT; slowest ALTER p95 66.5 s vs 5.6 s at -j4; on the
release build at -j10, 1/100 TIMEOUT vs 0/100 and 107 s vs 6.6 s. The
pre-ClickHouse#114028 file fails 14/50 at -j24 with NO ALTER PROGRESS; this change
passes 50/50 there and 50/50 on ASAN.

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

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

4 participants