Skip to content

Unthrottle mutations in 02899_restore_parts_replicated_merge_tree - #112090

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-02899-unthrottle-mutation
Aug 7, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-flaky-02899-unthrottle-mutation

Conversation

@groeneai

@groeneai groeneai commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #110935

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

02899_restore_parts_replicated_merge_tree intermittently fails on Fast test and
Fast test (arm_darwin). The runner kills the test at its per-test budget while one of the
mutations_sync=2 ALTERs is still in flight:

[ 2086 / 12705] 02899_restore_parts_replicated_merge_tree:   [ FAIL ] 60.16 sec.
Reason: Timeout! Killing process group 64263
...
64584 clickhouse-client ... --query ALTER TABLE table_with_unsuccessful_commits DELETE WHERE value = 'hello' SETTINGS mutations_sync=2

The process list at kill time names the blocking statement in both failing runs. On the
server side that ALTER is then terminated by the shutdown that follows the kill:

Code: 341. DB::Exception: Mutation is not finished because table shutdown was called.
It will be done after table restart. (UNFINISHED) (version 26.8.1.1)
... TCPHandler: Processed in 59.129 sec.

The 60 s that expires is clickhouse-test --timeout 60, which only the Fast test jobs pass
(ci/jobs/fast_test.py:378 is the sole --timeout 60 in all of ci/); it is enforced by
proc.wait(args.timeout) at tests/clickhouse-test:3516 and the process-group kill at
:695. Every other stateless job leaves the 600 s default, which is why only these two
jobs can turn a ~60 s stall into a failure. (Note in passing that
tests/config/users.d/limits_fast.yaml, which would pin a server-side
max_execution_time: 60, is in fact never installed: tests/config/install.sh:273-275
gates its symlink on [[ $(is_fast_build) == 1 ]], but is_fast_build only returns an
exit code and prints nothing, so the substitution is always empty. That is a separate
issue and not addressed here.)

This is a blocking wait, not a slow run. The measured quantity is the runner's per-test
wall clock (test_duration_ms): over 30 days the maximum passing test duration is 7.51 s
on Fast test and 13.59 s on Fast test (arm_darwin) against the 60 s per-test cap, the
12-59 s band is essentially empty, and both failures sit exactly at the cap.

Root cause

StorageReplicatedMergeTree::mutate creates the mutation znode, schedules
mergeSelectingTask and waits. That task asks
CompactionStatistics::getMaxSourcePartBytesForMutation, whose pool guard is

// Compaction/CompactionStatistics.cpp:155
if (occupied <= 1 || max_tasks_count - occupied >= number_of_free_entries_in_pool_to_execute_mutation)

occupied is the server-global CurrentMetrics::BackgroundMergesAndMutationsPoolTask
gauge, so it is driven by whatever else the server happens to be doing — in CI, the other
tests running in parallel, not this test. When the inequality fails the function returns
0 and StorageReplicatedMergeTree.cpp:4527 returns AttemptStatus::Limited, so no
MUTATE_PART log entry is created and waitMutationToFinishOnReplicas just spins its
one-second recheck loop. The failing job's own server log shows the refusal:

max_tasks_count (32) - occupied (25) < number_of_free_entries_in_pool_to_execute_mutation (8)

What turns a transient refusal into a 60 s stall is that nothing re-attempts the
assignment promptly. The reschedule block at the end of mergeSelectingTask is

// StorageReplicatedMergeTree.cpp:4579-4584 (settings accessors elided for readability)
Float32 new_sleep_ms = static_cast<Float32>(merge_selecting_sleep_ms);
if (result == AttemptStatus::EntryCreated || result == AttemptStatus::NeedRetry)
    new_sleep_ms /= merge_selecting_sleep_slowdown_factor;
else if (result == AttemptStatus::CannotSelect)
    new_sleep_ms *= merge_selecting_sleep_slowdown_factor;
new_sleep_ms *= std::uniform_real_distribution<Float32>(1.f, 1.1f)(thread_local_rng);

so the next attempt is scheduleAfter(merge_selecting_sleep_ms) (:4594), and the
interval is only ever shortened by an attempt that succeeded. In the failing job the
interval was already at its max_merge_selecting_sleep_ms ceiling of 60000 ms when the
mutation was created, driven there by the OPTIMIZE ... FINAL loop's CannotSelect
returns, and the refusals simply re-armed it:

00:32:08.944182 Scheduling next merge selecting task after 60000ms, current attempt status: CannotSelect
00:32:09.005420 Created mutation with ID 0000000000 (data versions: all = 2; )
00:32:09.005701 ... there are not enough free threads for mutations (max_tasks_count (32) - occupied (25) < ...(8))
00:32:09.005712 Scheduling next merge selecting task after 60000ms, current attempt status: Limited

After that line the table's merge-selecting task does not run again at all: for the
following 58 s the only log lines for this table are Failed to wait for mutation '0000000000', will recheck (58 of them, roughly one per second), until the runner's kill
triggers shutdown at 00:33:07. Note the asymmetry that makes this self-inflicted rather
than merely unlucky: Limited matches neither branch above, so a refusal never shortens
the interval, yet the unconditional jitter multiply on the last line means a run of
refusals can only lengthen it — measured on the reproduction, starting from the
merge_selecting_sleep_ms floor rather than the ceiling, 20 consecutive Limited
attempts went 5052 -> 15389 ms (mean ratio 1.0607, 3.05x overall). So the same stall is
reachable with or without the OPTIMIZE ... FINAL loop.

Nor does anything wake the assigner when pool slots free up again. Tree-wide there are
eight merge_selecting_task->schedule() sites — StorageReplicatedMergeTree.cpp:4590,
:5691, :7154, :8493, MergeFromLogEntryTask.cpp:493,
MutateFromLogEntryTask.cpp:346, ReplicatedMergeTreeQueue.cpp:1276 and
ReplicatedMergeTreeSink.cpp:1220 — and none of them fires for this table in this
situation. :8493 is the one in mutate and has already fired; the two
finish_callbacks in MergeFromLogEntryTask / MutateFromLogEntryTask are per-table
(they run when this table's own merge or mutation completes, not when some other table
releases a slot, which is what occupied is counting); :5691 and
ReplicatedMergeTreeSink.cpp:1220 need a local commit or INSERT that the blocked test is
not doing; :7154 is the metadata-ALTER path; and ReplicatedMergeTreeQueue.cpp:1276
only runs when updateMutations actually loads new entries. So the blocker clears in
milliseconds, the assigner stays asleep for a full minute, and the runner's 60 s per-test
budget expires first.

The fix

Set number_of_free_entries_in_pool_to_execute_mutation = 0 on this test's table.

With the threshold at 0, max_tasks_count - occupied >= 0 is always true, so
getMaxSourcePartBytesForMutation can never return 0 for pool reasons and the Limited
return at :4527 becomes unreachable for this table. The mutation is assigned on the
first merge-selecting attempt, with no dependence on how long the backoff sleeps. = 0
is always a legal value — MergeTreeSettings.cpp:2489 rejects only values greater than
background_pool_size * background_merges_mutations_concurrency_ratio.

This is the remedy a maintainer already applied to the same starvation in
03518_alter_logical_race.sh ("Disable the throttles that defer MODIFY COLUMN's data
mutation behind merges: under this test's concurrent INSERT load they can starve the first
mutation"), and 12 further stateless tests set this setting to 0 for the same purpose.

I deliberately did not pin the sleep ceiling instead: that bounds the symptom and makes
the table poll ZooKeeper more often for its whole lifetime, whereas removing the refusal
changes no interval at all. The reproduction confirms the distinction — with the fix the
backoff still reaches its 60 s ceiling (six after 60000ms, current attempt status: CannotSelect) and the ALTER completes in 0 s, so a saturated sleep on its own is
harmless; only the Limited refusal blocks assignment. This also means the fix is
indifferent to which of the two routes to a long interval a given run took.

I also did not add a no-random-* tag: none of the five relevant settings appears among
the 61 keys of MergeTreeSettingsRandomizer, so the runner cannot move them.

Verification

Note that CI does not run at the shipped default of this setting:
tests/config/config.d/merge_tree.xml:4 overrides
number_of_free_entries_in_pool_to_execute_mutation to 8 server-wide, which is the
value in the failing job's log line quoted above. The reproduction below deliberately uses
the stricter shipped default of 20 instead, by shrinking the pool.

Reproduced with a server whose merges/mutations pool is 26 while
number_of_free_entries_in_pool_to_execute_mutation stays at its shipped default of 20,
with 7 pool slots held by unrelated tables (the test's own table has no projections, so
its work never contributes), giving 26 - 7 = 19 < 20:

there are not enough free threads for mutations
(max_tasks_count (26) - occupied (7) < number_of_free_entries_in_pool_to_execute_mutation (20)),
so won't select new parts to merge or mutate.

A/B on the same binary, same fixture, differing only in that setting:

ALTER result elapsed
without the setting Code: 159 TIMEOUT_EXCEEDED 61 s
with the setting success 0 s

Through clickhouse-test with its normal randomized settings, on the same server: the
current version of the test fails (Having 1 errors!, the 60 s timeout on the
mutations_sync=2 ALTER, reported via stderr since the shell does not check exit codes),
the fixed version passes in 6.6 s.

Mechanism check, per-arm, scoped to each arm's own table: there are not enough free threads for mutations 20 -> 0, current attempt status: Limited 20 -> 0, and the
waitMutationToFinishOnReplicas recheck spins 60 -> 0. With the fix the MUTATE_PART
entry appears 5 ms after the mutation znode is created.

--test-runs 50 with default randomization, under the same sustained pool pressure:
50/50 passed, 5.79-6.24 s per run.

I swept the other stateless tests for the same shape (ReplicatedMergeTree, a synchronous
mutation, an OPTIMIZE ... FINAL, and neither of the two protections). An earlier revision
of this description named 04144_skip_index_after_alter_modify_column_replicated as the
same class and promised a follow-up. That was wrong and there is no follow-up:
StorageReplicatedMergeTree::optimize never reads mutations_sync (its only two readers
in src/ are StorageMergeTree.cpp:1126 and StorageReplicatedMergeTree.cpp:8509), so
that test cannot reach this mechanism. Its two Timeout! hits are one pull request at one
commit, built with enable_block_number_column and enable_block_offset_column defaulted
to true; the same pull request reverted that before merging, and the test has 0
timeout-shaped failures in about 155000 runs since.

No related open issue found for this test.

Version info

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

groeneai added 2 commits July 27, 2026 09:29
…utations

The test intermittently timed out on Fast test and Fast test (arm_darwin) with
the client hitting its 60s budget on one of the mutations_sync=2 ALTERs:

  Code: 159. DB::Exception: Timeout exceeded: elapsed 60052.163029 ms,
  maximum: 60000 ms. (TIMEOUT_EXCEEDED)

Those are the two jobs whose tests/config/users.d/limits_fast.yaml pins
max_execution_time: 60, and both run on every PR.

It is a blocking wait rather than a slow run: over 30 days the maximum passing
duration is 7.51s on Fast test and 13.59s on arm_darwin against a 60s cap, the
12-59s band is empty, and both failures sit exactly at the cap.

Root cause. StorageReplicatedMergeTree::mutate creates the mutation znode,
schedules mergeSelectingTask and waits. That task asks
CompactionStatistics::getMaxSourcePartBytesForMutation, whose pool guard at
CompactionStatistics.cpp:155 reads the server-global
BackgroundMergesAndMutationsPoolTask gauge, so it is driven by the other tests
running in parallel rather than by this test. On refusal
StorageReplicatedMergeTree.cpp:4525 returns AttemptStatus::Limited, no
MUTATE_PART entry is created, and waitMutationToFinishOnReplicas just spins.

What turns a transient refusal into a 60s stall is the reschedule block at
:4576-4585. Limited matches neither the divide branch (EntryCreated/NeedRetry)
nor the multiply branch (CannotSelect), but the jitter multiply
new_sleep_ms *= uniform_real_distribution<Float32>(1.f, 1.1f) is unconditional,
so every refusal ratchets the sleep upward. Measured over 20 consecutive
Limited attempts: 5052 -> 15389 ms, mean ratio 1.0607, 3.05x overall, starting
from the merge_selecting_sleep_ms floor rather than the ceiling. And there is
no wake-up for "pool slots freed" - the only merge_selecting_task->schedule()
sites are :4588, :5689, :7152 and :8491, and :8491 (from mutate) has already
fired. So the blocker clears in milliseconds while the assigner sleeps ever
longer, and the client's 60s budget expires first.

Fix: set number_of_free_entries_in_pool_to_execute_mutation = 0 on this test's
table. At 0 the condition max_tasks_count - occupied >= 0 is always true, so
getMaxSourcePartBytesForMutation can never return 0 for pool reasons and the
Limited return becomes unreachable for this table - the mutation is assigned on
the first attempt, with no dependence on how long the backoff sleeps. 0 is
always legal: MergeTreeSettings.cpp:2489 rejects only values greater than
background_pool_size * background_merges_mutations_concurrency_ratio.

This is the same remedy already applied to the same starvation in
03518_alter_logical_race.sh, and 18 other stateless tests set this setting for
the same purpose. I did not pin the sleep ceiling instead: that bounds the
symptom and permanently increases ZooKeeper polling for the table, whereas
removing the refusal changes no interval. The reproduction confirms the
distinction - with the fix the backoff still reaches its 60s ceiling and the
ALTER completes in 0s, so a saturated sleep alone is harmless.

No no-random-* tag is needed: none of the five relevant settings appears among
the 61 MergeTreeSettingsRandomizer keys, so the runner cannot move them.

Verified with a server whose pool is 26 while the setting stays at its default
of 20 and 7 slots are held by unrelated tables, so 26 - 7 = 19 < 20 and the
real guard fires. A/B on one binary, same fixture: without the setting
Code: 159 at 61s, with it success at 0s. Through clickhouse-test with normal
randomization the current version fails and the fixed version passes in 6.6s.
Per-arm log counts scoped to each arm's table: "there are not enough free
threads for mutations" 20 -> 0, "current attempt status: Limited" 20 -> 0,
recheck spins 60 -> 0. --test-runs 50 under sustained pool pressure: 50/50.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110935&sha=bbc9355f428946983e9f5687ed8c6b25e5d14adf&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
Related: ClickHouse#110935
…e_tree

Follow-up to the previous commit on this branch. The one-line test fix
(`number_of_free_entries_in_pool_to_execute_mutation = 0`) is unchanged and
still correct; this commit only fixes how the failure was described, plus the
in-tree comment that carried one of the wrong claims.

Three corrections.

1. The previous commit message quoted a client-side `TIMEOUT_EXCEEDED` exception
as the CI failure. That text is in no artifact of either failing job: it was a
fragment of a truncated `play.clickhouse.com` reply that leaked into a scratch
file during the failure harvest, and the version string embedded in it is the
one that query server reports, not the 26.6.1.1 and 26.8.1.1 of the failing
jobs. What the artifacts do contain is the runner verdict

  [ 2086 / 12705] 02899_restore_parts_replicated_merge_tree:   [ FAIL ] 60.16 sec.
  Reason: Timeout! Killing process group 64263

with the blocking `mutations_sync=2` ALTER named in the process list, and then
server-side, after the kill

  Code: 341. DB::Exception: Mutation is not finished because table shutdown was
  called. It will be done after table restart. (UNFINISHED) (version 26.8.1.1)
  ... TCPHandler: Processed in 59.129 sec.

2. The expiring 60 s budget is not a server-side `max_execution_time`. It is
`clickhouse-test --timeout 60`, the only `--timeout 60` in `ci/`
(`ci/jobs/fast_test.py:378`), enforced by `proc.wait(args.timeout)` at
`tests/clickhouse-test:3516` and the process-group kill at `:695`. That is also
the simpler explanation of why only the two Fast test jobs manifest this: every
other stateless job leaves the 600 s default. `tests/config/users.d/limits_fast.yaml`,
which would pin `max_execution_time: 60`, is never installed at all -
`tests/config/install.sh:273-275` gates its symlink on
`[[ $(is_fast_build) == 1 ]]`, but `is_fast_build` only returns an exit code and
prints nothing, so the substitution is always empty. The failing job's own trace
shows `++ return 1` / `+ [[ '' == 1 ]]`, and `limits_fast` appears nowhere in it.
That substitution bug is a separate concern and is not touched here.

Consistently, the durations compared in the previous message are the runner's
per-test wall clock (`test_duration_ms`), not query durations.

3. The in-tree comment repeated the same `max_execution_time` claim on its last
line, so it was a source-visible defect rather than only a description one. It
is now three lines carrying just the durable reason - isolation from global
merges/mutations pool contention - with literal names in inline code blocks;
the incident-level detail lives in the commit messages and the PR description.

Also corrected: 12 further stateless tests set this setting to 0 for the same
purpose (18 files mention it, but 3 are reference fixtures and 2 of the
remaining tests set an illegal value expecting `BAD_ARGUMENTS`); and CI does not
run at the shipped default of 20 - `tests/config/config.d/merge_tree.xml:4`
overrides it to 8 server-wide, which is the value in the failing job's
`max_tasks_count (32) - occupied (25) < ... (8)` line. The reproduction uses the
stricter default of 20 by shrinking the pool instead.

No behaviour change: the only non-comment edit in the previous commit is
untouched, and the comment-stripped test file is byte-identical to it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110935&sha=bbc9355f428946983e9f5687ed8c6b25e5d14adf&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
Related: ClickHouse#110935
@groeneai

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

Before opening this PR I ran an independent cold review of the resulting code plus a
second-model review pass, and adjudicated every finding. Two rounds were needed: the first
round bounced this change back for rework, and the second round's automated pass returned
no findings.

Round 1 (previous head) — 2 blockers + 3 nits, all agreed and fixed. Both blockers were
about the failure narrative, not the fix:

Finding Verdict
❌ The description's headline exception quote (a client-side TIMEOUT_EXCEEDED) appears in no artifact of either failing job. It was a fragment of a truncated play.clickhouse.com reply that leaked into a scratch file during the failure harvest; the version string embedded in it is the one that query server reports, not the 26.6.1.1 / 26.8.1.1 of the failing jobs. agreed, rewritten from the real artifacts
❌ The stated 60 s budget was attributed to a server-side max_execution_time from tests/config/users.d/limits_fast.yaml. That file is never installed: tests/config/install.sh:273-275 gates its symlink on [[ $(is_fast_build) == 1 ]], but is_fast_build only returns an exit code and prints nothing, so the substitution is always empty (the failing job's own trace shows ++ return 1 / + [[ '' == 1 ]]). The clock that actually expires is clickhouse-test --timeout 60. The same wrong claim was on the in-tree comment, so it was source-visible. agreed, re-attributed and the comment corrected
⚠️ The in-tree comment was five lines of incident-level detail (including the falsified claim) with literals unformatted. agreed, now three lines, literals in backticks
💡 Two countable claims (18 other stateless tests; the throttle's value in CI) were wrong. agreed, re-derived: 12 other tests, and CI overrides the setting to 8 server-wide via tests/config/config.d/merge_tree.xml:4

Round 2 (this head) — 1 major + 3 nits from my own cold review; the automated pass
returned 0 findings.
All description-level; the one-line test change is unchanged.

Finding Verdict
⚠️ The description claimed the only merge_selecting_task->schedule() sites are the four in StorageReplicatedMergeTree.cpp, and rested the "nothing wakes the assigner" argument on that. Tree-wide there are eight — the other four are MergeFromLogEntryTask.cpp:493, MutateFromLogEntryTask.cpp:346, ReplicatedMergeTreeQueue.cpp:1276 and ReplicatedMergeTreeSink.cpp:1220, and the first two are precisely "a merge/mutation finished, so a slot was released" callbacks. One git grep refutes the sentence as written. agreed; the conclusion holds (those callbacks are per-table, so slots freed by other tables never wake this one), and the description now lists all eight with a per-site reason plus the direct log evidence: after the Limited refusal the table logs no merge-selecting line for 58 s, only its once-per-second mutation recheck, until the kill
💡 The sleep-ratchet ladder was presented as the mechanism while the OPTIMIZE ... FINAL loop was called "not required". In the failing job the interval was already at its 60000 ms ceiling from that loop's CannotSelect returns before the mutation existed; the ladder was measured on the local reproduction, starting from the floor. agreed; both routes are now described, each labelled with where it was observed. The fix is indifferent to which route a run took
💡 PR title was 77 characters. agreed, shortened to 65
💡 Re-derived the "12 further stateless tests" count independently rather than trusting the previous round's note (18 files − 3 reference/fixture files − one setting 100 and expecting BAD_ARGUMENTS − one setting 15). correct as written, no change

Disagreed, with reasons. The previous commit's message still contains the retracted
quote; .claude/CLAUDE.md forbids amend and rebase on a branch, so it stays and the
current commit carries an explicit retraction instead — the PR description, which is what
gets reviewed, is fully corrected. A build-identity check prescribed in the fix plan was
unsatisfiable because the build tree had been reclaimed between rounds; it was replaced
with a stronger proof (the change touches one file, and that file's comment-stripped hash
is byte-identical across the two commits with master's copy as a differing control).

Independently verified for this round, on master: the throttle has exactly one
runtime consumer (Compaction/CompactionStatistics.cpp:154) so nothing else is perturbed,
and the merge path reads a different setting; occupied can never exceed
max_tasks_count because MergeTreeBackgroundExecutor::trySchedule refuses at >=, which
is what makes the Limited return unreachable at 0; = 0 cannot trip validation;
fault_probability_before_part_commit is set after all three ALTERs, so unthrottling
them cannot weaken the restore-parts coverage; none of the five relevant settings appears
among the 61 MergeTreeSettingsRandomizer keys; ci/jobs/fast_test.py:378 is the only
--timeout 60 in ci/ and the macOS job reaches it through fast_test_darwin.sh, which
is why only the two Fast test jobs manifest this. Every string now quoted in the
description was checked against the job's own job.log and clickhouse-server.log.zst.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, and not "~1%". With the merges/mutations pool at 26 and 7 slots held by unrelated tables (so 26 - 7 = 19 < 20, the shipped default of number_of_free_entries_in_pool_to_execute_mutation), the current version of the test fails on every run: 3/3 mutations_sync=2 ALTERs hit Code: 159 TIMEOUT_EXCEEDED (60824 / 60903 / 60915 ms) in a direct bash -x run, and 1/1 clickhouse-test run reported Having 1 errors!. The server log carries the guard verbatim: max_tasks_count (26) - occupied (7) < number_of_free_entries_in_pool_to_execute_mutation (20).
b Root cause explained? Yes. mutate creates the mutation znode and waits; mergeSelectingTask asks CompactionStatistics::getMaxSourcePartBytesForMutation, whose pool guard (Compaction/CompactionStatistics.cpp:155) reads the server-global BackgroundMergesAndMutationsPoolTask gauge, so parallel tests decide it. On refusal StorageReplicatedMergeTree.cpp:4527 returns AttemptStatus::Limited and no MUTATE_PART entry is created. The next attempt is then scheduleAfter(merge_selecting_sleep_ms) (:4594), and only a successful attempt shortens that interval: Limited matches neither branch of the backoff update (:4579-4583) while the jitter multiply at :4584 is unconditional, so a run of refusals can only lengthen it (measured from the floor, 20 consecutive Limited attempts: 5052 -> 15389 ms, mean ratio 1.0607, 3.05x). In the failing CI job the interval was already at the 60000 ms ceiling from the OPTIMIZE FINAL loop's CannotSelect returns before the mutation existed, so both routes reach the same stall. Nor does anything wake the assigner when slots free up: tree-wide there are eight merge_selecting_task->schedule() sites (StorageReplicatedMergeTree.cpp:4590, :5691, :7154, :8493, MergeFromLogEntryTask.cpp:493, MutateFromLogEntryTask.cpp:346, ReplicatedMergeTreeQueue.cpp:1276, ReplicatedMergeTreeSink.cpp:1220) and none fires here — :8493 (from mutate) already fired, the two finish_callbacks are per-table (they run on this table's own completions, not when another table releases a slot), :5691/Sink:1220 need a local commit or INSERT, :7154 is the metadata-ALTER path, and Queue:1276 requires updateMutations to load new entries. Confirmed in the failing job: after 00:32:09.005712 Scheduling next merge selecting task after 60000ms, current attempt status: Limited the table logs no further merge-selecting line for 58 s, only Failed to wait for mutation '0000000000', will recheck (58 occurrences), until the kill triggers shutdown at 00:33:07. So the blocker clears in milliseconds while the assigner stays asleep, and the runner's 60 s per-test budget expires first. That budget is clickhouse-test --timeout 60, passed only by the Fast test jobs (ci/jobs/fast_test.py:378) and enforced at tests/clickhouse-test:3516 -> :695; every other stateless job leaves the 600 s default, which is why only those two jobs manifest it.
c Fix matches root cause? Yes. At number_of_free_entries_in_pool_to_execute_mutation = 0, max_tasks_count - occupied >= 0 is always true, so the function can never return 0 for pool reasons and the Limited return at :4527 is unreachable for this table — the mutation is assigned on the first attempt with no dependence on sleep length. This removes the refusal rather than bounding the sleep that follows it. Not a widened bound, not a no-random-* tag, not a data reduction. The fixed arm's own backoff still saturates (six after 60000ms, current attempt status: CannotSelect) while the ALTER completes in 0 s — direct evidence that the refusal, not the sleep, was the blocker.
d Test intent preserved / new tests added? Preserved. The parts_after_detach_attach comparison, the 11-iteration OPTIMIZE FINAL loop and the fault_probability_before_part_commit sequence are untouched; the .reference (Ok) is unchanged. fault_probability_before_part_commit=1 is set after all three ALTERs, so those ALTERs are pure fixture setup and the restore-parts coverage does not depend on mutation throttling — the test needs the mutations to COMPLETE. No new test: this fixes an existing test's fixture, not a source bug.
e Both directions demonstrated? Yes, on one binary. A/B with the identical fixture differing only in this setting: without it Code: 159 TIMEOUT_EXCEEDED at 61 s, with it success at 0 s. Through clickhouse-test with normal randomization on the same server: current version fails (Having 1 errors!, 238 s), fixed version passes in 6.61 s. Per-arm log oracle, scoped to each arm's own table: there are not enough free threads for mutations 20 -> 0, current attempt status: Limited 20 -> 0, waitMutationToFinishOnReplicas recheck spins 60 -> 0. --test-runs 50 under the same sustained pool pressure: 50/50 passed.
f Fix is general across code paths? Yes for the scope of this test. The setting lives on the TABLE, so one line covers all three mutations_sync=2 ALTERs. The later OPTIMIZE ... SETTINGS alter_sync=0 is async by construction and has its own 300-iteration poll. StorageMergeTree is not a carrier (no mergeSelectingTask); SharedMergeTree is excluded by the file's # Tags: no-shared-merge-tree. I swept every 0_stateless blob on master for the same shape (ReplicatedMergeTree + a synchronous mutation + an OPTIMIZE ... FINAL + neither protection): 6 other candidates, of which 04144_skip_index_after_alter_modify_column_replicated shows the same signature (2 Timeout! Killing process group hits, both on Fast test). Left out of this PR so it stays one root cause; following up separately.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (flaky test fixture-setting fix, not a code bug — there is no type/parameter matrix). The equivalent axis is the runner's setting randomization, and it is closed by measurement: parsing all 61 MergeTreeSettingsRandomizer keys shows number_of_free_entries_in_pool_to_execute_mutation, merge_selecting_sleep_ms, max_merge_selecting_sleep_ms, merge_selecting_sleep_slowdown_factor and max_replicated_mutations_in_queue are all absent, so the runner cannot move them and no no-random-* tag is needed. The 50/50 run used full randomization.
h Backward compatible? (maintainer-approved exception only) N/A / yes — test-only change. No setting default changed, no SettingsChangesHistory.cpp entry needed, no serialization or format change, no user-visible behaviour.
i Invariants and contracts preserved? Yes. = 0 can never trip validation: MergeTreeSettings.cpp:2489 rejects only values greater than background_pool_size * background_merges_mutations_concurrency_ratio. The throttle's documented purpose is to "leave free threads for merges" (Compaction/CompactionStatistics.cpp:153); this test runs 3 tiny mutations over a 30-row table, so the effect on co-running tests is negligible — which is why 12 further stateless tests already set it to 0, and why a maintainer applied the same remedy to the same starvation in 03518_alter_logical_race.sh. No interval is changed, so ZooKeeper polling behaviour is untouched. Wall clock is unchanged or better (5.79-6.24 s per run vs the 30-day CI maximum passing durations of 7.51 s on Fast test and 13.59 s on Fast test (arm_darwin)).

Session id: cron:clickhouse-review-slot-53:20260727-111800 (authored by cron:clickhouse-impl-slot-46:20260727-104000)

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @scanhex12 — could you review this? It sets number_of_free_entries_in_pool_to_execute_mutation = 0 on the test's table so its mutations_sync=2 ALTERs are not refused assignment by the server-global merges/mutations pool guard (CompactionStatistics::getMaxSourcePartBytesForMutation), which parallel tests drive; on refusal nothing re-attempts promptly and the runner's 60 s per-test budget expires. Same remedy as 03518_alter_logical_race.sh.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [650c47c]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
04493_correlated_subquery_join_runtime_filter_dup_column FAIL cidb IGNORED

AI Review

Summary

This PR makes 02899_restore_parts_replicated_merge_tree set number_of_free_entries_in_pool_to_execute_mutation = 0 so its synchronous replicated mutations are not blocked by unrelated global merges/mutations pool occupancy. I traced the setting through CompactionStatistics::getMaxSourcePartBytesForMutation, the ReplicatedMergeTree mutation-assignment path, and the test flow after the change, and I do not see a correctness or coverage regression in the current diff.

Final Verdict

✅ No findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 650c47c

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
Stateless tests (amd_asan_ubsan, distributed plan, parallel) / 04493_correlated_subquery_join_runtime_filter_dup_column flaky via randomized settings, not caused by this PR: the run drew --join_runtime_filter_min_probe_rows 2837 (and --query_plan_optimize_join_order_randomize 1), so no runtime filter is built and exactly one reference line moves 1 -> 0. The runner's own diagnosis on the same run reports Runs: 28, Failed: 0, Passed: 28 — the failure is not reproducible. This PR changes only tests/queries/0_stateless/02899_restore_parts_replicated_merge_tree.sh. #111691 (external, open) — it pins join_runtime_filter_min_probe_rows = 0 in this exact test file

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

@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 7, 2026
Merged via the queue into ClickHouse:master with commit 82be63e Aug 7, 2026
177 of 179 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 Aug 7, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Sep 15, 2026
… merges/mutations pool contention

04068_lwd_minmax_projection_recovery_rmt stops making progress and is killed by
the Fast test 60 second per-test cap: 3 failures in 190,994 runs over 45 days,
none of them on master, and in the job that surfaced it (#120099) it was the sole
red of 15,103 rows. It is a stall rather than a slow test (the OK maximum is
7.0 s over 25,331 Fast test runs and 14.5 s over 10,219 arm_darwin runs, while
the failures sit at 60.05 and 60.10 s), and the non-replicated sibling of this
test has 0 failures in 190,985 runs.

The twelve single-row INSERTs each schedule the merge-selecting task, so twelve
iterations run back to back, find nothing mergeable and return
AttemptStatus::CannotSelect, which multiplies merge_selecting_sleep_ms up to
max_merge_selecting_sleep_ms (60 s). DELETE FROM then creates the mutation, and
the single iteration that sees it is refused by the pool-headroom guard in
CompactionStatistics::getMaxSourcePartBytesForMutation:

  max_tasks_count (32) - occupied (25) <
  number_of_free_entries_in_pool_to_execute_mutation (8)

so max_source_part_bytes_for_mutation is 0 and mergeSelectingTask returns
AttemptStatus::Limited. Limited matches neither arm of the backoff epilogue, so
the saturated 60 second interval is reused verbatim, no MUTATE_PART entry is
created, and lightweight_deletes_sync = 2 blocks until max_execution_time fires.
With the threshold at 0 the guard's comparison is unconditionally true for this
table, so the mutation is assigned on the first iteration that sees it, whatever
unrelated parallel tests are doing to the server-global pool. The non-replicated
sibling is immune because StorageMergeTree::mutate() calls
background_operations_assignee.trigger(), which shrinks its backoff instead of
leaving it saturated.

Reproduced as a 2x2 over pool occupancy and this diff, on one server and one
binary: the pristine file with an occupied pool fails with code 159 after
60.64 s; this diff under the same occupancy passes in 2.69 s with byte-for-byte
reference output; both files pass on an idle pool, which places the failure on
occupancy rather than on the test. 100 of 100 randomized runs of this test and
its plain sibling pass, as do 10 runs each of 02440_mutations_finalization and
03716_mutations_parts_postpone_reasons_rmt.

The engine-level starvation, where Limited reuses a saturated interval for every
Replicated table, is tracked upstream in #61902 and is deliberately not touched
here; this is the same test-side remedy already merged in #118435 and #112090
for the identical log signature.

Related: #120099

Co-Authored-By: Claude Opus 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 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