Repository navigation
Unthrottle mutations in 02899_restore_parts_replicated_merge_tree - #112090
PedroTadim merged 2 commits into
Conversation
…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
Internal second-model review (click to expand)Before opening this PR I ran an independent cold review of the resulting code plus a Round 1 (previous head) — 2 blockers + 3 nits, all agreed and fixed. Both blockers were
Round 2 (this head) — 1 major + 3 nits from my own cold review; the automated pass
Disagreed, with reasons. The previous commit's message still contains the retracted Independently verified for this round, on |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-53:20260727-111800 (authored by cron:clickhouse-impl-slot-46:20260727-104000) |
|
cc @scanhex12 — could you review this? It sets |
|
Workflow [PR], commit [650c47c] Summary: ❌
AI ReviewSummaryThis PR makes Final Verdict✅ No findings. |
CI finish ledger — 650c47cEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260727-180000 |
82be63e
… 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]>
Related: #110935
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
02899_restore_parts_replicated_merge_treeintermittently fails onFast testandFast test (arm_darwin). The runner kills the test at its per-test budget while one of themutations_sync=2ALTERs is still in flight: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:
The 60 s that expires is
clickhouse-test --timeout 60, which only the Fast test jobs pass(
ci/jobs/fast_test.py:378is the sole--timeout 60in all ofci/); it is enforced byproc.wait(args.timeout)attests/clickhouse-test:3516and the process-group kill at:695. Every other stateless job leaves the 600 s default, which is why only these twojobs 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-sidemax_execution_time: 60, is in fact never installed:tests/config/install.sh:273-275gates its symlink on
[[ $(is_fast_build) == 1 ]], butis_fast_buildonlyreturns anexit 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 son
Fast testand 13.59 s onFast test (arm_darwin)against the 60 s per-test cap, the12-59 s band is essentially empty, and both failures sit exactly at the cap.
Root cause
StorageReplicatedMergeTree::mutatecreates the mutation znode, schedulesmergeSelectingTaskand waits. That task asksCompactionStatistics::getMaxSourcePartBytesForMutation, whose pool guard isoccupiedis the server-globalCurrentMetrics::BackgroundMergesAndMutationsPoolTaskgauge, 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:4527returnsAttemptStatus::Limited, so noMUTATE_PARTlog entry is created andwaitMutationToFinishOnReplicasjust spins itsone-second recheck loop. The failing job's own server log shows the refusal:
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
mergeSelectingTaskisso the next attempt is
scheduleAfter(merge_selecting_sleep_ms)(:4594), and theinterval is only ever shortened by an attempt that succeeded. In the failing job the
interval was already at its
max_merge_selecting_sleep_msceiling of 60000 ms when themutation was created, driven there by the
OPTIMIZE ... FINALloop'sCannotSelectreturns, and the refusals simply re-armed it:
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 killtriggers shutdown at
00:33:07. Note the asymmetry that makes this self-inflicted ratherthan merely unlucky:
Limitedmatches neither branch above, so a refusal never shortensthe 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_msfloor rather than the ceiling, 20 consecutiveLimitedattempts went
5052 -> 15389 ms(mean ratio 1.0607, 3.05x overall). So the same stall isreachable with or without the
OPTIMIZE ... FINALloop.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:1276andReplicatedMergeTreeSink.cpp:1220— and none of them fires for this table in thissituation.
:8493is the one inmutateand has already fired; the twofinish_callbacks inMergeFromLogEntryTask/MutateFromLogEntryTaskare per-table(they run when this table's own merge or mutation completes, not when some other table
releases a slot, which is what
occupiedis counting);:5691andReplicatedMergeTreeSink.cpp:1220need a local commit or INSERT that the blocked test isnot doing;
:7154is the metadata-ALTER path; andReplicatedMergeTreeQueue.cpp:1276only runs when
updateMutationsactually loads new entries. So the blocker clears inmilliseconds, 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 = 0on this test's table.With the threshold at 0,
max_tasks_count - occupied >= 0is always true, sogetMaxSourcePartBytesForMutationcan never return 0 for pool reasons and theLimitedreturn at
:4527becomes unreachable for this table. The mutation is assigned on thefirst merge-selecting attempt, with no dependence on how long the backoff sleeps.
= 0is always a legal value —
MergeTreeSettings.cpp:2489rejects only values greater thanbackground_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 deferMODIFY COLUMN's datamutation 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 isharmless; only the
Limitedrefusal blocks assignment. This also means the fix isindifferent 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 amongthe 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:4overridesnumber_of_free_entries_in_pool_to_execute_mutationto 8 server-wide, which is thevalue 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_mutationstays 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:A/B on the same binary, same fixture, differing only in that setting:
Code: 159 TIMEOUT_EXCEEDEDThrough
clickhouse-testwith its normal randomized settings, on the same server: thecurrent version of the test fails (
Having 1 errors!, the 60 s timeout on themutations_sync=2ALTER, 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 mutations20 -> 0,current attempt status: Limited20 -> 0, and thewaitMutationToFinishOnReplicasrecheck spins 60 -> 0. With the fix theMUTATE_PARTentry appears 5 ms after the mutation znode is created.
--test-runs 50with 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 revisionof this description named
04144_skip_index_after_alter_modify_column_replicatedas thesame class and promised a follow-up. That was wrong and there is no follow-up:
StorageReplicatedMergeTree::optimizenever readsmutations_sync(its only two readersin
src/areStorageMergeTree.cpp:1126andStorageReplicatedMergeTree.cpp:8509), sothat test cannot reach this mechanism. Its two
Timeout!hits are one pull request at onecommit, built with
enable_block_number_columnandenable_block_offset_columndefaultedto
true; the same pull request reverted that before merging, and the test has 0timeout-shaped failures in about 155000 runs since.
No related open issue found for this test.
Version info
26.8.1.980(included in26.8and later)