Repository navigation
Fix ReplicatedMergeTree replica staying readonly forever after a failed attach-path startup - #113733
Conversation
…h startup A ReplicatedMergeTree table whose startup goes through ReplicatedMergeTreeAttachThread could stay in readonly mode indefinitely, rejecting every write with TABLE_IS_READ_ONLY. Recovery then depended on an unrelated ZooKeeper session loss, a SYSTEM RESTART REPLICA, or a server restart, rather than on the table's own retry. BackgroundSchedulePoolTaskInfo::schedule and ::scheduleAfter both refuse a deactivated task and return false, and ReplicatedMergeTreeRestartingThread ignores that return value, so a rejected re-arm is silent. When a startup attempt on the attach path throws after startBeingLeader, startupImpl's catch calls restarting_thread.shutdown(false), which deactivates the restarting task. ReplicatedMergeTreeAttachThread::run sees a hardware error and retries, and the next attempt gets past startBeingLeader and enters the from_attach_thread branch with the task still deactivated. The inline restarting_thread.run() there therefore cannot re-arm itself on either outcome, neither scheduleAfter(check_period_ms) on success nor scheduleAfter(next_failure_retry_ms) on failure, and the following restarting_thread.start(false) only cleared the deactivated flag without enqueuing anything. The task was left activated but neither scheduled nor delayed, that is, owned by no pool collection, so nothing retried the activation and nothing armed the zookeeper_session_expiration_check_period timer. A replica that did activate through this path silently lost its periodic session-expiration check. The ZSESSIONEXPIRED callback installed later in startupImpl does call start(true), so an unrelated session loss can rescue the table, but only if one happens to occur after this table subscribed. In the reported failure the only session-expiry notify in the affected server process fired 91 ms before that subscription, and belonged to a sibling table. The wedged table's restarting task then logged nothing at all for the remaining 417 seconds of the run, while the sibling's task logged its periodic scheduling line seven times at exact 60 second intervals. Call start(true), that is activateAndSchedule(), which clears the flag and enqueues under a single schedule_mutex hold. It runs strictly after the inline run() returns, so the ordering introduced in ClickHouse#68513 to keep a pool thread from entering run() concurrently is preserved. On a healthy first attempt the extra scheduled run takes runImpl's early-return fast path and re-arms the periodic check, measured on both a patched and an unpatched binary. Two failpoints make the two-attempt sequence deterministic in test_restarting_task_rearmed_after_failed_attach_startup, which asserts that the task is owned by the pool while the replica is still readonly and that the replica recovers once the injected failure is disabled. With the re-arm reverted to start(false) it fails on that ownership assertion; with the fix it passed every countable repetition, 60 of 60. test_startup_with_small_bg_pool_partitioned, which reported this failure, is unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
test_restarting_task_rearmed_after_failed_attach_startup enables rmt_startup_fail_after_being_leader, which is declared ONCE and therefore process-global: it fires for whichever startupImpl reaches it first. Its injection site sits above the `if (from_attach_thread)` branch, so any ReplicatedMergeTree's startup can consume it, not just the table under test. start_clean_clickhouse() restarts the server whenever the preceding test left fault_injection.xml behind, and a restart re-attaches every ReplicatedMergeTree with an attach thread that reaches the same injection site. Two such tables survive into this test and it dropped neither, so it raced them for the failpoint. Table loading also lags the harness's readiness gate: in a captured run the first table only began loading 5 ms after `Ready for connections`, and the two attach-path startups arrived 4.4 s and 6.1 s after it, so a wait on `select 20` returns before the competitors have started. The ordering is load-dependent rather than guaranteed. Losing that race made the test fail identically on a patched and an unpatched binary, so its verdict stopped distinguishing a regression from a misdirected failpoint. Drop both tables SYNC first. DROP resolves the table through DatabaseCatalog, which waits for its startup job in the foreground pool, so it quiesces the instance instead of racing it, and the following assertion on system.replicas proves the window is closed rather than assuming it. Test-only change; no server code is modified.
test_restarting_task_rearmed_after_failed_attach_startup enables both failpoints, and rmt_restarting_thread_fail_startup is REGULAR, so every inline restarting_thread.run() on the attach path fails. It is disabled only after start(true) has already cleared the deactivated flag, so the run that eventually succeeds is a pool run whose scheduleAfter is accepted with or without the fix. Nothing observed an inline run that succeeds while the task is still deactivated, which is the case the periodic session check depends on. Add a second test that enables only rmt_startup_fail_after_being_leader. The first attempt throws after startBeingLeader and its cleanup deactivates the task; the failpoint is ONCE, so the attach thread's retry finds it consumed, reaches the from_attach_thread branch with the task still deactivated, and its inline run() succeeds. That run's own scheduleAfter is refused, so the periodic timer exists only because the following start(true) re-arms the task. The replica activates in this shape, so is_readonly is 0 on both a patched and an unpatched binary and cannot be the oracle; it is asserted as a positive control that the inline run really did succeed. The oracle is the scheduler state: the task must be owned by the pool on every sample, and delayed must be observed, which is what distinguishes an armed periodic timer from a single enqueue. The table sets zookeeper_session_expiration_check_period to 2 seconds so the timer is observable across the sampling window; a per-table setting beats runner injection and leaves the shared module config alone.
Internal second-model review (click to expand)This change went through six review rounds before publication. Each round was a cold code review that
Carriers were enumerated independently each round before reading the plan, with no divergence: On the healthy path the extra scheduled run is a no-op: it takes Both new tests were verified failing on a reverted binary against the shipping test file, not argued |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-11:20260806-214400 |
|
cc @alesapin @tavplubix, could you review this? A ReplicatedMergeTree replica whose startup goes through the attach thread can be left with its restarting task activated but enqueued in no pool collection, after which nothing retries the activation and nothing arms the periodic ZooKeeper session check, so the replica can stay readonly indefinitely. The cause is that a previous attempt's cleanup deactivated the task, so both the inline run()'s own scheduleAfter and the following start(false) were silently refused. |
|
Workflow [PR], commit [2aba0b7] Summary: ✅
AI ReviewSummaryThis PR fixes the attach-thread startup path for Final VerdictStatus: ✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 27/28 (96.43%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units59 translation units recompiled, 486 s compile time in total, 44 of them have a recent master baseline. |
The previous commit made the attach-path call `restarting_thread.start(true)`, that is `BackgroundSchedulePoolTaskInfo::activateAndSchedule`. That helper only tests `scheduled`, so when the inline `run()` had already armed a delay it went on to `scheduleImpl`, which cancels the pending delayed entry and enqueues the task for immediate execution instead. Recovering the deactivated task does not need that. When the task is deactivated, `run()`'s own `scheduleAfter` is refused and nothing is armed, so there is no delay to keep. When it is not deactivated, `run()` has already chosen the interval: `zookeeper_session_expiration_check_period` after a successful attempt, or `min(10000, 100 * (n + 1) * (n + 2) / 2)` ms after a failed one. Cancelling it retried `tryStartup()` immediately on every attach-path startup, not only in the window the previous commit fixes. Replace the call with `ensureArmed`, which activates the task and then arms a retry through `scheduleAfter(0, /*overwrite=*/false)`. With `overwrite` unset that call returns false while a delay is already armed, so an interval `run()` chose is kept and only a refused re-arm is replaced. `DistributedAsyncInsertDirectoryQueue` and `BackgroundJobsAssignee` already use the same argument for the same reason. The call still happens after the inline `run()` returns, so the ordering from ClickHouse#68513 is unchanged. Measured on a failing attach-path startup whose task was never deactivated, with `zookeeper_session_expiration_check_period` left at its default: the interval between the inline attempt and the next one is 22.5 to 114.4 ms over five runs with the previous commit, against 121.6 to 149.4 ms over five runs with this one, which is the 100 ms first-failure backoff `run()` selected. The subsequent intervals are 300, 600, 1000 and 1500 ms in both arms. Both integration tests added by the previous commits still pass, and still fail when the fix is reverted.
The two tests added earlier both enable the failpoint that makes a startup attempt's cleanup deactivate the restarting task, so the retry's inline `run()` can never arm a delay before the re-arm. Neither test could therefore tell `ensureArmed` apart from an unconditional `activateAndSchedule`: with `scheduleAfter`'s `overwrite` argument flipped to true, both still passed. Add a test for the other state. It enables only the failpoint inside `tryStartup`, so nothing deactivates the task and the inline `run()` arms its own first-failure backoff. It then reads the `Trying to start replica up` timestamps and asserts that no attempt follows the previous one immediately, which is what cancelling an armed delay would produce. Measured on the same binary with `overwrite` flipped to true, the gap after the inline attempt is 21.0 to 28.7 ms; with it left false it is 121.6 to 149.4 ms, the 100 ms delay `run()` selected. Also wait for the attach thread's `Table is initialized` line in the first test before sampling the task's pool state, as the second test already does. `Trying to startup table from right now` is logged just before the inline `run()` and the re-arm, and the readonly assertion that follows it holds throughout startup, so on its own it does not order the sampling after the code under test.
The delay test read every `Trying to start replica up` line for its table, including the one logged by the `CREATE TABLE` that precedes the `DETACH`. The gap between that attempt and the first one after `ATTACH` is user-driven rather than an interval `run()` chose, so a slow step between the two statements could fail the assertion on correct code. Take the attach-path trace's own timestamp first and keep only the attempts at or after it. `grep_in_log` passes its argument to `zgrep` as a basic regular expression, so this reads the two markers with separate calls instead of one alternation.
Assert the gap after the inline attempt specifically rather than the smallest gap in the run, since that is the one whose delay the re-arm can cancel, and note in the comment what makes the threshold meaningful: the later gaps have known nominal values, so they measure the pool's pickup latency directly, and it stayed under 16 ms across every arm measured here against a 100 ms delay. Also name `ensureArmed` in the comment of the preceding test, which still said `start`.
CI finish ledger - 9aa0821Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260807-113000 |
|
@tavplubix I am not sure if this fix is right. If something failed on a replica, could it make sense to stay read-only? |
|
@PedroTadim Staying read-only after a failed startup is right, and the fix keeps that. What it changes is that the replica also stops retrying.
What breaks is the scheduling of the next attempt. Nothing the table owns recovers from that. The attach thread reschedules only when Retrying indefinitely with backoff is also what every non-attach startup already does: The first new test asserts exactly that pair: |
|
@groeneai look at the CI failures |
…arting-task-rearm
|
@PedroTadim Both reds on the old head were one event, and neither came from this PR's diff. I have merged master and pushed, so CI is running again on What failed on
The merge is content-preserving for my part: the If the same |
CI finish ledger - 2aba0b7CI is fully finished on this head and there are no failing checks.
One note so the CIDB rows are not misread: Session id: cron:our-pr-ci-monitor:20260809-013000 |
Related: #68513
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a
ReplicatedMergeTreetable staying in readonly mode indefinitely when its startup goes through the attach thread (used when ZooKeeper is unavailable at load) and an earlier attempt has failed: the restarting task's retry was silently rejected because the earlier attempt's cleanup had deactivated it, so the table kept rejecting writes withTABLE_IS_READ_ONLYand scheduled neither its own retry nor its periodic ZooKeeper session check.Description
BackgroundSchedulePool'sscheduleandscheduleAfterrefuse a deactivated task and returnfalse;ReplicatedMergeTreeRestartingThreadignores that return, so a rejected re-arm is silent.When a startup attempt on the attach path throws after
startBeingLeader,startupImpl's catchcalls
restarting_thread.shutdown(false), deactivating the task. The next attempt reaches thefrom_attach_threadbranch with the task still deactivated, so the inlinerestarting_thread.run()cannot re-arm itself and the following
restarting_thread.start(false)only cleared the flagwithout enqueuing anything. The task ended up activated but neither scheduled nor delayed, so
nothing retried the activation and nothing armed the
zookeeper_session_expiration_check_periodtimer, leaving the table readonly until an unrelated session expiry re-armed the task.
The change replaces that call with
ensureArmed, which activates the task and arms a retry throughscheduleAfter(0, /*overwrite=*/false). Withoverwriteunset that call returns false while adelay is already armed, so an interval
run()chose is kept and only a refused re-arm is replaced;activateAndSchedulewould instead cancel that delay and rerun at once on every attach-pathstartup. The call still runs after the inline
run(), so #68513's ordering is preserved.Three new integration tests drive these sequences with failpoints: one keeps the retry failing and
asserts the task is pool-owned while the replica is readonly, then that it recovers once the
injected failure is disabled; one lets the retry's inline run succeed and asserts the periodic check
is armed anyway, with
is_readonlyas a positive control; one leaves the task active sorun()arms its own backoff, and asserts no retry follows the previous one immediately. The first two fail
with the whole change reverted; the third is green there, since
start(false)also left an armeddelay alone, and fails when the re-arm is made unconditional.
test_startup_with_small_bg_pool_partitioned, which reported this, is unchanged.Version info
26.8.1.1018(included in26.8and later)