Skip to content

Fix ReplicatedMergeTree replica staying readonly forever after a failed attach-path startup - #113733

Merged
PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-rmt-attach-restarting-task-rearm
Aug 9, 2026
Merged

PedroTadim merged 8 commits into
ClickHouse:masterfrom
groeneai:fix-rmt-attach-restarting-task-rearm

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #68513

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixes a ReplicatedMergeTree table 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 with TABLE_IS_READ_ONLY and scheduled neither its own retry nor its periodic ZooKeeper session check.

Description

BackgroundSchedulePool's schedule and scheduleAfter refuse a deactivated task and return
false; ReplicatedMergeTreeRestartingThread ignores that return, 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), deactivating the task. The next attempt reaches the
from_attach_thread branch with the task still deactivated, so the inline restarting_thread.run()
cannot re-arm itself and the following restarting_thread.start(false) only cleared the flag
without 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_period
timer, 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 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;
activateAndSchedule would instead cancel that delay and rerun at once on every attach-path
startup. 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_readonly as a positive control; one leaves the task active so run()
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 armed
delay alone, and fails when the re-arm is made unconditional.
test_startup_with_small_bg_pool_partitioned, which reported this, is unchanged.

Version info

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

groeneai and others added 3 commits August 6, 2026 21:28
…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.
@groeneai

groeneai commented Aug 6, 2026

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

This change went through six review rounds before publication. Each round was a cold code review that
did not read the author's own evidence first, plus a separate second-model gate. The gate returned
0 findings on the final head, and its --delta focus diffstat was empty, confirming that the last
two rounds changed only commit-message text. No round found anything wrong with the code: the src/
diff has been byte-identical since the second round, and every bounced item was a false or unmeasured
claim in maintainer-facing prose.

# Finding Verdict
⚠️ 1 The changelog said the table stays readonly "until the server was restarted". Too strong: SYSTEM RESTART REPLICA rebuilds the storage object (InterpreterSystemQuery.cpp:1477 table.reset(), :1520 re-get, :1589 startup()) and is not readonly-gated (doRestartReplica has 0 assertNotReadonly, against 5 elsewhere in src/); and the ZSESSIONEXPIRED handler is installed in the wedged state with restarting_thread.start(true) as its body (StorageReplicatedMergeTree.cpp:5946-5950), reached because run()'s catch (...) never rethrows. In the reported failure it did not help for a timing reason only. Fixed. All three places now name the three real recovery routes. The point is sharper, not weaker: recovery stops being the table's own business, because nothing arms its zookeeper_session_expiration_check_period timer any more.
⚠️ 2 Three separate rounds found a countable in the PR body, a commit message or the validation comment that reproduced under no predicate: a "50 out of 50" measured on a file that is not what ships, "the only session-expiry notify in the whole run" (the retained bundle holds three, across three server processes), "both of its call sites" for a return value that is ignored at four, and in this round a claim that the reporting test "passes 20 out of 20 on the merits". Each fixed against a re-measurement. The last one is replaced by the measured split: the reporting test reached a verdict 31 times on a patched binary, 8 passed and the other 23 stopped on an environmental error before the body ran. It never failed on its own merits: its assertion text appears in none of the 81 retained logs.
❌ 3 The gate argued the new start(true) lets a pool run of the restarting task overlap startupImpl's tail. Disagreed, refuted on three independent legs. Its necessary step is false at master: run() calls scheduleAfter on all three exits and deactivated defaults false, so on every attach startup except the two-attempt sequence fixed here the inline run() already arms the task before start() is reached (first-failure backoff 100 ms); the else branch has always paired start(true) with the identical tail, so the overlap is the pre-existing shape for every non-attach startup; and the tail's five actions are disjoint from runImpl's startup set, with flush_and_shutdown_mutex appearing 0 times in ReplicatedMergeTreeRestartingThread.cpp. Its remedy would reverse #68513's ordering and re-open the race that fix closed.
💡 4 After this change ReplicatedMergeTreeRestartingThread::start(false) has no callers left, so the else task->activate(); arm and the bool schedule parameter are dead. Noted, deliberately not changed. Deleting the parameter would turn a one-line behavioural fix into an API change; better as a separate cleanup if wanted.

Carriers were enumerated independently each round before reading the plan, with no divergence:
.start(false) now appears nowhere in src/ (control: .start(true) = 3); of the three
startupImpl call sites only ReplicatedMergeTreeAttachThread.cpp:210 passes from_attach_thread = true; from_attach_thread is confined to three files and restarting_thread has one declaration;
activateAndSchedule() already has 14 uses in src/Storages/MergeTree, so this moves the single
outlier onto the existing convention. SharedMergeTree has no implementation here, so there is no
symmetric storage to mirror. restarting_thread.wakeup() has exactly one caller
(StorageReplicatedMergeTree.cpp:4155) and EventNotifier::notify iterates only the subscribers
present when it fires, with ZooKeeperImpl.cpp:1432 its only non-test emitter, so no other route
could re-arm the task.

On the healthy path the extra scheduled run is a no-op: it takes runImpl's early return
(if (!storage.is_readonly && !storage.getZooKeeper()->expired())), a local atomic plus a local
expiry check with no Keeper round trip, and then re-arms the periodic check. activateAndSchedule()
clears the flag and enqueues under a single schedule_mutex hold, so there is no window that a
separate activate() + schedule() pair would have opened.

Both new tests were verified failing on a reverted binary against the shipping test file, not argued
from reading. Each has a positive control that prevents a vacuous green: the failing-retry test
asserts is_readonly = 1 before sampling the scheduler, and the succeeding-retry test asserts
is_readonly = 0, so neither can pass by the replica having stayed readonly. The failpoints throw a
Coordination::Exception constructed in place, so they never enter ZooKeeperImpl::finalize and
cannot emit the session-expiry notify that would otherwise re-arm the task and green the test on an
unpatched binary.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Failpoints reproduce the two-attempt sequence exactly, with no probability tuning: one pytest command per test fails on an unpatched binary and passes on a patched one, 60 of 60 and 85 of 85 countable runs. All 127 excluded runs were attributed to an external cause, in two classes: 77 to a concurrent unrelated test session tearing down all four of this module's containers, and 50 to docker-network churn that failed cluster.start() before any test body ran. Across the 81 retained logs, six runs failed on a test's own assertion and all six are the intended unpatched arm: three pairs on the pool-ownership oracle, two pairs for the failing-retry test and one for the succeeding-retry one. No ClickHouse crash and no OOM in any of them. Not a low-rate shape.
b Root cause explained? Yes. BackgroundSchedulePool's schedule and scheduleAfter refuse a deactivated task and return false, and the restarting thread ignores that return. A startup attempt that throws after startBeingLeader deactivates the task in startupImpl's catch, so the next attempt enters the from_attach_thread branch with the task deactivated: the inline run() cannot re-arm itself on either outcome, and start(false) only cleared the flag without enqueuing, leaving the task owned by no pool collection.
c Fix matches root cause? Yes. It restores the invariant at the site that broke it, using an existing mechanism with an existing caller on the non-attach path. No widened bound, no no-random-* tag, and deliberately not a timeout increase: the wait is unbounded because no timer exists, so no budget would fix it.
d Test intent preserved / new tests added? Yes. test_startup_with_small_bg_pool_partitioned is untouched in budget, tags and assertions, and it never failed on the merits: its own assertion text appears in none of the 81 retained logs. It reached a verdict 31 times on a patched binary, 8 passed and the other 23 stopped on an environmental error rather than on an assertion: 18 on Cannot start ClickHouse, 2 on a container-start bad hostname, and one each on a docker HTTP 500, a docker exec, and a client connection error. That is the shared-box class the other arms document. Two new integration tests cover the failing retry and the succeeding one.
e Both directions demonstrated? Yes. On an unpatched binary both tests fail on the scheduler-state assertion; on a patched one both pass every countable repetition, 60 of 60 and 85 of 85. The logs separate the two failure modes: for the failing-retry test the restarting task logs its injected failure and then nothing more, while for the succeeding-retry test it logs a complete activation and then falls silent, in both cases ending on Starting the restarting thread, schedule: false with none of the recurring pool scheduling that the patched arm shows. Each arm asserted the server's own logged build id against the binary's, because --binary selects only the client.
f Fix is general across code paths? Yes. Of the three startupImpl call sites only the attach-thread one passes true; the only activate-then-inline-run call site in src/ is this one; from_attach_thread is confined to three files and restarting_thread is a member of StorageReplicatedMergeTree only, so there is no sibling storage to mirror. The fix is at the caller that opened the window, not a guard at the symptom. Both the success and the failure path of the inline run are covered by the same unconditional call.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not applicable to datatypes: no data path or column types are involved. The relevant axes were measured instead: both run() outcomes are fixed by the same unconditional call, and the defect and the fix are independent of background_schedule_pool_size, verified with the default value as well as the value the reporting test uses.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialization, protocol or metadata format change, so no SettingsChangesHistory.cpp entry. The only externally visible change is that a replica which previously hung readonly now retries.
i Invariants and contracts preserved? Yes. The invariant is that after startupImpl returns the restarting task is owned by the schedule pool, and the fix establishes it on the one path that violated it. The ordering from #68513 is preserved verbatim: the task becomes pool-schedulable strictly after the inline run() returns, so no pool thread can enter run() concurrently. The pool's documented invariant that a deactivated task is never scheduled, delayed or executing is untouched, because the refusal is not weakened; the caller simply stops calling in while deactivated. Shutdown races stay safe: startupImpl re-checks the shutdown flags under flush_and_shutdown_mutex immediately after, run() returns at once on need_stop, and deactivate() cancels a pending schedule.

Session id: cron:clickhouse-review-slot-11:20260806-214400

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 7, 2026
@PedroTadim PedroTadim self-assigned this Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2aba0b7]

Summary: ✅


AI Review

Summary

This PR fixes the attach-thread startup path for ReplicatedMergeTree so the restarting task is re-armed when an earlier failed attempt left it deactivated, which otherwise could leave the replica stuck in readonly mode indefinitely. The current head narrows the re-arm to the previously-unarmed case, keeps delays that run() already selected, and adds focused integration coverage for the failing-retry, successful-retry, and delay-preservation paths. I did not find a remaining correctness or safety issue in the current code.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.90% 78.80% -0.10%

Changed lines: Changed C/C++ lines covered: 27/28 (96.43%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2aba0b7e4 with master d53179b03 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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 units

59 translation units recompiled, 486 s compile time in total, 44 of them have a recent master baseline.

Job report

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`.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9aa0821

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
Fast test / 02280_add_query_level_settings trunk regression, not caused by this branch: Code: 252 ... Too many parts (1 with average size of 505.00 B) on the FIRST INSERT into an empty table. Breadth over 30 days: 12 rows across 12 distinct unrelated PRs, 0 master, 10 of them carrying TOO_MANY_PARTS. The test builds a plain MergeTree with parts_to_throw_insert = 1, while this branch only changes ReplicatedMergeTree restart and attach code, and that test file is not in its diff #113045 (external, open)
Finish Workflow / Post Hooks same event as the row above, not a second defect: Fast test failed at 11:11:06Z and every Bugfix validation job was skipped one second later at 11:11:07Z, so the new-tests check found that no per-arch job had reached a verdict and reported it. It resolves when the Fast test red above clears #113045 (external, open), same owner as the row above

Fast test failing this early gates the rest of the matrix, so this commit shows only 4 job
successes and 169 skips rather than a broad red. Nothing here is caused by the change itself,
and no separate fix task is owed because both rows resolve with the single fixing PR above.

Session id: cron:our-pr-ci-monitor:20260807-113000

@PedroTadim

Copy link
Copy Markdown
Member

@tavplubix I am not sure if this fix is right. If something failed on a replica, could it make sense to stay read-only?

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

@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.

is_readonly is cleared in exactly one place, setNotReadonly at ReplicatedMergeTreeRestartingThread.cpp:171, reached only after tryStartup() has actually succeeded. This change adds 25 lines to src/ and none of them mentions readonly, so a replica whose startup keeps failing stays read-only for as long as it keeps failing: every failing retry returns before that line, and writes keep being rejected with TABLE_IS_READ_ONLY.

What breaks is the scheduling of the next attempt. schedule and scheduleAfter return false and do nothing on a deactivated task (BackgroundSchedulePool.cpp:71 and :81), and the restarting thread ignores that return. On the attach path, a first attempt that throws after startBeingLeader has its cleanup call restarting_thread.shutdown(false), which deactivates the task. The next attempt reaches StorageReplicatedMergeTree.cpp:5910 with it still deactivated, so all three scheduleAfter calls in the inline run() (:95, :100, :106) are refused, and start(false) at :5915 only clears the flag without enqueuing anything. The task ends up in no pool collection, so neither the failure backoff nor zookeeper_session_expiration_check_period is armed.

Nothing the table owns recovers from that. The attach thread reschedules only when startupImpl itself throws (ReplicatedMergeTreeAttachThread.cpp:111-114), and here it returned successfully because the inline run() swallowed the failure. restarting_thread.wakeup() at :4154 is driven by queue_updating_task, which is activated only after a successful startup. What remains is an unrelated ZooKeeper session expiry on the shared session, an explicit SYSTEM RESTART REPLICA, or a server restart.

Retrying indefinitely with backoff is also what every non-attach startup already does: :5919 passes start(true), so run() stays scheduled and retries at min(10000, 100 * (n + 1) * (n + 2) / 2) ms. The attach path was the only one that could stop. The deliberate latch is still there and untouched: when the attach thread's error is not a hardware error it logs "table will remain readonly", sets initialization_done and does not retry.

The first new test asserts exactly that pair: is_readonly is 1 while the task is pool-owned and the injected failure keeps firing, then 0 once the failure is disabled.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai look at the CI failures

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

@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 2aba0b7.

What failed on 9aa0821: Fast test / 02280_add_query_level_settings, which fails on the first INSERT into an empty table with Code: 252, Too many parts (1 with average size of 505.00 B). That test builds a plain MergeTree with parts_to_throw_insert = 1; my diff is 5 files, all ReplicatedMergeTree attach/restart plus its own integration test, and contains no occurrence of 02280, TOO_MANY_PARTS or parts_to_throw. Scoped to that signature, CIDB gives 9 rows over 30 days across 9 distinct unrelated PRs and 0 on master. It is the known trunk regression, fixed by #113045 (open). The wider family carriers are 02458_relax_too_many_parts, 02015_async_inserts_5 and 00980_merge_alter_settings, which hit 9 more PRs today.

Finish Workflow was a cascade of that same red, not a second defect: Fast test failed at 11:11:06Z and all five Bugfix validation jobs went skipped at 11:11:07Z, one second later. new_tests_check.py then blocks because no per-arch Bugfix Validation validated the bug, since none of them ran. With 149 jobs dropped there was no other signal on that head at all, which is why a fresh run was the only way forward. I cannot re-run the workflow myself, so the merge was the available lever.

The merge is content-preserving for my part: the +/- payload of my contribution against the new base is byte-identical to the payload against the old one. On the merged tree the module is 5 passed / 0 failures in 210.73 s, and the overwrite=false semantics ensureArmed relies on are unchanged upstream (BackgroundSchedulePool.cpp:83-84 still returns false while a delay is armed).

If the same 02280 failure comes back on this head I will report it here rather than push again, since a second merge would not change anything.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2aba0b7

CI is fully finished on this head and there are no failing checks.

Check / test Reason Owner / fixing PR
(none) - -
CH Inc sync private sync (pending) CH Inc sync (private, not actionable by me)

One note so the CIDB rows are not misread: test_startup_with_small_bg_pool and
test_startup_with_small_bg_pool_partitioned are recorded FAIL under
Bugfix validation (integration tests, amd64) and (aarch64) for this head. Both of those jobs
report success, because that is what the job asserts - the test must fail on master HEAD without
the change for the bug to be validated. Those rows are the expected outcome, not a red, so they get
no owner row above.

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

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 9, 2026
Merged via the queue into ClickHouse:master with commit e2194b4 Aug 9, 2026
180 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 9, 2026
@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default 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