Skip to content

Create the ReplicatedMergeTree restarting thread's task deactivated - #119264

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:restarting-thread-task-created-deactivated
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:restarting-thread-task-created-deactivated

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117293

Changelog category (leave one):

  • Improvement

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

Fixed a race during ReplicatedMergeTree startup on the attach path: a ZooKeeper session expiring during replica activation could run ReplicatedMergeTreeRestartingThread::run on a background pool thread concurrently with the inline activation. The observed effect is an assertion abort (Logical error: 'storage.is_readonly') in debug and sanitizer builds; a release build instead re-runs setZooKeeper and tryStartup mid-activation.

Description

ReplicatedMergeTreeRestartingThread::run has two independent executors and must not run on both at once: its own BackgroundSchedulePool task, serialized by exec_mutex, and the inline restarting_thread.run the attach path takes (StorageReplicatedMergeTree.cpp:5979), which bypasses both.

BackgroundSchedulePoolTaskInfo::deactivated defaults to false, so the task is schedulable from construction and the inline activation can be overtaken by its own side effects: runImpl arms queue_updating_task, the session expires, queueUpdatingTask catches ZSESSIONEXPIRED and calls restarting_thread.wakeup, and a pool thread enters run while the inline executor is still between setNotReadonly and first_time = false. It reads first_time == true with is_readonly == false and trips chassert(storage.is_readonly).

Creating the task deactivated is the convention the storage constructor already states at StorageReplicatedMergeTree.cpp:481: the four tasks created there are all deactivated there, and ReplicatedMergeTreePartCheckThread does the same in its own constructor. It makes the wakeup in that window a no-op, and the attach path's following start(/*schedule=*/true) activates and schedules, so it is coalesced, not lost.

Requested by @ alexey-milovidov in #117293 (comment).

A new integration test parks the inline activation at a failpoint and expires the session with SYSTEM RECONNECT ZOOKEEPER, forcing the interleaving. While parked it polls system.background_schedule_pool, where a deactivated task has no row, so the refused schedule is observed rather than inferred; the same query must return the row again after recovery. Without the one-line change it aborts the server in 5 of 5 runs with the stack from the CI report; with it, 20 of 20 pass, and in the 10 runs whose server log I counted the refused wakeup is coalesced into a normal session-replacement restart in all 10. test_replicated_table_attach still passes 6 of 6, so no wakeup is dropped.

Neighbouring races left untouched, and CIDB breadth for this signature

Three neighbouring races are untouched, none reachable for this assertion, none with a CIDB occurrence: session_expired_callback_handler outliving a failed attach attempt, is_readonly_metric_set written from both threads, and shutdown not waiting for an inline execution.

Exactly one occurrence in 90 days, and no open issue or pull request matches the signature, so this is not verifiable post-merge by a drop in failure frequency; the evidence is the reddening negative arm plus the call-site enumeration.

SELECT check_start_time, check_name, pull_request_number, commit_sha, head_ref
FROM default.checks
WHERE position(test_context_raw, 'storage.is_readonly') > 0
  AND check_start_time >= now() - INTERVAL 90 DAY
2026-09-04 01:08:01    Stress test (arm_debug)    117293    1209779bd81c5de44849dc0908019d0bda7b670a    fix-chain-to-in-fixed-string-padding

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117293&sha=1209779bd81c5de44849dc0908019d0bda7b670a&name_0=PR&name_1=Stress%20test%20%28arm_debug%29


Workflow [PR]
Sync PR [sync-upstream/pr/119264]

`ReplicatedMergeTreeRestartingThread::run` must not run on two threads at once, but it
has two independent executors: its own `BackgroundSchedulePool` task, whose executions are
serialized by `BackgroundSchedulePoolTaskInfo::exec_mutex`, and the direct inline
`restarting_thread.run` the attach path takes at
`StorageReplicatedMergeTree.cpp:5979`, which bypasses the task and therefore that
mutex.

`BackgroundSchedulePoolTaskInfo::deactivated` defaults to `false`, so the task is
schedulable from the moment it is created. That lets the inline activation be overtaken
by its own side effects: `runImpl` arms `queue_updating_task`, the ZooKeeper session
then expires, `queueUpdatingTask` catches `ZSESSIONEXPIRED` and calls
`restarting_thread.wakeup`, and a pool thread enters `run` while the inline executor
is still between `setNotReadonly` and `first_time = false`. It observes
`first_time == true` with `is_readonly == false`, which is the state
`chassert(storage.is_readonly)` rules out.

Creating it deactivated is the convention the storage constructor already states at
`StorageReplicatedMergeTree.cpp:481`, "We create and deactivate all tasks for
consistency. They all will be scheduled and activated by the restarting thread.": the
four tasks created there are all deactivated there, `ReplicatedMergeTreePartCheckThread`
does the same in its own constructor, and a dozen further tasks across `src/`
are created that way. So this restores an existing convention rather than adding a second
lock to tolerate its absence. Three of the storage's other tasks are created active
(`cleanup_thread` and `deduplication_hashes_cache`, both started by the restarting thread,
and `part_moves_between_shards_orchestrator`, started by `startupImpl`); none of them is
ever run inline, so none has a second executor to overlap, and none is touched here.

The refused wakeup is not lost. Immediately after the inline call the attach path runs
`restarting_thread.start(/*schedule=*/ true)`, which activates and schedules, so the
pool re-enters `run` with `first_time` already cleared and takes the
`getZooKeeper()->expired()` branch, performing a proper `partialShutdown` and restart.
That ordering is what `8ff11ef56512d` established; on a branch where the attach path
still calls `start(/*schedule=*/ false)` this change would turn the coalesced retry into
a dropped one, so the two belong together.

Reported as `Logical error: 'storage.is_readonly'` in `Stress test (arm_debug)` on
ClickHouse#117293. The CI report for that run is
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117293&sha=1209779bd81c5de44849dc0908019d0bda7b670a&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

The assertion is debug and sanitizer only; a release build continues with both executors
inside `setZooKeeper` and `tryStartup` on the same table.

The regression test parks the inline activation on a new `PAUSEABLE_ONCE` failpoint and
expires the session with `SYSTEM RECONNECT ZOOKEEPER`, so the interleaving is forced
rather than waited for. While the activation is parked it also polls
`system.background_schedule_pool`, where a deactivated task has no row, so the refused
schedule is observed rather than inferred, and once the table has recovered the same
query is required to return a row, so the poll cannot pass by matching nothing. It aborts
the server in 5 of 5 runs without the one-line change and passes 20 of 20 with it. It
needs the default `background_schedule_pool_size`, so it cannot live in
`test_replicated_table_attach`, which pins that to 1.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 10, 2026
@groeneai

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

Four rounds of an independent cold review plus a second-model gate (engine: codex), on cbb79aad4add5,
5a53c2ca0afd1, 6791de80b4f2e and 6749d9a659012. The gate returned zero findings on the final tree.
Everything agreed is fixed before this branch is published, so the diff above already reflects it.

  • ❌ A commit-message claim that the restarting thread's task was the only one of this storage's tasks created
    active. It is not: cleanup_thread, deduplication_hashes_cache and
    part_moves_between_shards_orchestrator are also created active (none of them is ever run inline, so none
    has a second executor to overlap). Reworded to the convention that does hold, and those three are now named
    as untouched.
  • ❌ The regression test inferred the refused schedule from the absence of an abort. While the inline
    activation is parked it now also requires system.background_schedule_pool to show no row for the
    restarting thread's task, and after recovery it requires the same query to return the row again, so a zero
    cannot mean "matches nothing". The parked window runs to its deadline and reports a window that observed
    nothing.
  • ❌ A stale run count in this description: it read 30 of 30 passing runs, which was the count for the
    previous revision of the test file. The final file measured 20 of 20 positive and 5 of 5 negative, and that
    is what the text above now says.
  • 💡 AGENTS.md style applied to the new comments, commit message and test: function and method names written
    as f rather than f(), and literal SQL, class and function names wrapped in inline code.
  • 💡 Wording: run "must not run on two threads at once" rather than "is not reentrant"; a corrected task
    count in the commit message; the CI report URL added to it.
  • ⚠️ Dismissed, with the reason: a request for Bug Fix (user-visible misbehavior in an official stable release). chassert is compiled out in release builds, and the only observed consequence is the
    arm_debug abort, so I did not want to claim a stable-release user-visible misbehaviour I cannot show. The
    changelog entry states the release-build effect explicitly. Happy to relabel on request.
  • ⚠️ Dismissed, with the measurement: a request for a durable post-wakeup observable, on the theory that the
    awaited session-expiry log line precedes wakeup, so the parked window could be measured before the second
    executor is armed. In the negative arm that whole chain, from the awaited line through wakeup, the pool
    enqueue and the dispatch into runImpl, measures 64 microseconds (...342737 to ...342801), against a 30 s window
    sampled 49 times. A refused schedule also leaves no trace to observe: schedule returns false before
    touching any pool collection, so the fixed behaviour is the absence of an effect, and observing it would
    mean adding instrumentation to a hot pool path for a test. The discriminating oracle is the abort itself,
    which reddens 5 of 5 with the fix line removed, with a stack matching the CI report frame for frame.
  • ⚠️ Raised and then dropped by the round-4 review after checking it against the code, and recorded because
    the description mentions the residual: the session_expired_callback_handler subscribed at
    StorageReplicatedMergeTree.cpp:6003 can outlive a failed attach attempt, but it cannot reach this
    assertion. To subscribe at all, startupImpl must already have returned from the inline
    restarting_thread.run, and run clears first_time before it returns, so a later overlap can no longer
    enter the first_time branch that holds the chassert.

Session id: cron:clickhouse-review-slot-48:20260910-150700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SYSTEM ENABLE FAILPOINT rmt_restarting_thread_pause_after_activation parks the attach path's inline activation inside the window, then SYSTEM RECONNECT ZOOKEEPER expires the latched session. No timeouts and no sleeps: the parked thread cannot advance, so first_time stays set and is_readonly stays 0 for as long as the pause is held. python3 -m ci.praktika run "integration" --test "test_replicated_restarting_thread_race" aborts the server in 5 of 5 runs without the fix, on 5 independent clusters.
b Root cause explained? Yes. ReplicatedMergeTreeRestartingThread::run must not run on two threads at once but has two executors: its pool task (serialized by exec_mutex) and the inline restarting_thread.run at StorageReplicatedMergeTree.cpp:5979, which bypasses the task. BackgroundSchedulePoolTaskInfo::deactivated defaults to false, so the task is schedulable from construction; runImpl arms queue_updating_task, the session expires, queueUpdatingTask catches ZSESSIONEXPIRED and calls wakeup, and a pool thread enters run while the inline executor is still between setNotReadonly and first_time = false. It reads first_time == true with is_readonly == false and trips chassert(storage.is_readonly).
c Fix matches root cause? Yes. The defect is a mis-initialised task, so the fix initialises it, in the constructor, exactly as the four sibling tasks of the same storage already are. It is not a widened bound, a no-random-* tag, a data reduction, or a defensive check, and the assertion itself is untouched.
d Test intent preserved / new tests added? Yes. No existing test is modified, and chassert(storage.is_readonly) is kept, since it is the only signal for this bug class. One new integration test is added, it reddens 5 of 5 without the one-line change, and while the activation is parked it also asserts the positive half of the mechanism: the task has no row in system.background_schedule_pool, so the refused schedule is observed rather than inferred from the absence of an abort.
e Both directions demonstrated? Yes. Without the fix: 5 of 5 fail on the test's own assertion, with a stack identical to the CI report (same abortOnFailedAssertion, runImpl, run, BackgroundSchedulePoolTaskInfo::execute, threadFunction frames, the aborting one reached through execute, i.e. the pool executor). With the fix: 20 of 20 pass, on three independent clusters (5, 5 and 10 iterations), 0 aborts. Both arms ran the byte-identical committed test file, on two binaries differing by exactly that one line. Every iteration is shown to have entered the race window: in the 10-iteration leg the server log carries 10 of 10 inline activations, 10 of 10 refused-wakeup attempts and 10 of 10 session-replacement restarts. The pool-table oracle has three controls: while parked the row must be absent (about 49 samples per iteration, 500 executions of that query across the leg, none non-zero), after recovery the same query is required to return it, and each control is shown to be able to fail: corrupting the query's predicate fails the recovery half, and pointing the poll at a non-existent table fails the parked half on its own "no sample" assertion.
f Fix is general across code paths? Yes. Every path that can schedule this task before the first start was enumerated (grep -rn "restarting_thread" src/ gives exactly 8 sites) and each is either impossible in that window or coalesced by start(/*schedule=*/true) at StorageReplicatedMergeTree.cpp:5981. Fixed at the source rather than guarded at the abort site. The sibling ReplicatedMergeTreeAttachThread task is created active too, but its only three uses are activateAndSchedule, deactivate and a scheduleAfter inside its own run, so nothing outside can schedule it and changing it would be a provable no-op.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A by shape: no value flows through this change, so there is no type wrapper, argument or boundary value to vary. The one input dimension that does exist is background pool size, and both sides are covered: the default (this test, where two executors are possible) and background_schedule_pool_size=1 (test_replicated_table_attach, 6 of 6).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no on-disk or wire format, no versioned behaviour, so nothing is required in SettingsChangesHistory.cpp. The only behavioural dependency is on 8ff11ef56512d, present on master, which is what makes the refused wakeup coalesce instead of being lost.
i Invariants and contracts preserved? Yes. No new lock, so no new lock-ordering, deadlock or starvation surface; deactivate takes exec_mutex then schedule_mutex, the same order execute uses. deactivate is idempotent, so shutdown is unaffected. The invariant's other half, that no schedule request made before the first start is lost, is shown empirically rather than argued: in the 10-iteration leg the log carries 10 refused-wakeup attempts and 10 normal session-replacement restarts, and the test polls system.background_schedule_pool for the full 30 s while the activation is parked, observing no row for the task in any sample, and then requires the same query to return the row once the task is activated again. State here is RAM-only, so there is no crash or restart durability path to walk.

Session id: cron:clickhouse-impl-slot-5:20260910-141400

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6749d9a]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[s3] FAIL cidb
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[local] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[s3] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[azure] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[local] FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED
Build (riscv64) DROPPED

AI Review

Summary

This PR makes the ReplicatedMergeTreeRestartingThread schedule-pool task start deactivated and adds a focused integration test that parks the attach-path activation, forces a ZooKeeper session expiration, and verifies the wakeup is coalesced instead of overlapping the inline run. I traced the attach/startup/restart flow, the BackgroundSchedulePool activation and scheduling semantics, the failpoint handshake, and the new test's oracle. I did not find unresolved correctness, concurrency, or metadata issues in the current tree.

Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @alesapin, could you review this? ReplicatedMergeTreeRestartingThread's pool task is created schedulable, so on the attach path a ZSESSIONEXPIRED wakeup from queueUpdatingTask can start a second executor of run while the inline activation is still between setNotReadonly and first_time = false, which trips chassert(storage.is_readonly); this creates the task deactivated, as the sibling tasks of the same storage already are.

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6749d9a65 with master 6d69b30d8 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

9 translation units recompiled, 25 s compile time in total, 9 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6749d9a

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
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[local, s3] server abort on the Iceberg pruning path from merged #118606, first seen fleet-wide 2026-09-10 14:34Z #119298 (external, merged 17:26:35Z) reverted the cause on master, and it is NOT an ancestor of this head (ledger rule 3c, not 3d); forward fix #119292 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_bucket_partition_pruning.py::test_bucket_partition_pruning[local, s3, azure] collateral of the same abort: Code: 210. DB::NetException: Connection refused (NETWORK_ERROR) once the server is gone #119298 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

This job started 17:16:55Z, about 10 minutes before #119298 merged, so the build predates the
revert; a run on a head that contains it will not show these two failures. Mergeable Check and
PR are the praktika rollups of that single integration job, not separate failures.

Not caused by this PR: the diff is ReplicatedMergeTreeRestartingThread, one failpoint and one
new integration test, none of them on the Iceberg pruning path. The same abort collapsed the
test_storage_iceberg_with_spark module on 51 other pull requests and on true master today.

Session id: cron:our-pr-ci-monitor:20260910-200115

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author

One more CI hit of this race, this time in a release build and with a worse symptom: Stress test (arm_release) on an unrelated PR aborted with Logical error: 'Can't find queue-0000000014 in the memory queue. It is a bug.' from ReplicatedMergeTreeQueue::removeProcessedEntry (STID 4920-41c7): report.

The server log shows the same interleaving on the attach path (container time):

  • 16.124 a mutation all_1_1_0_4 -> all_1_1_0_5 starts, scheduled by the inline activation
  • 16.153 the inline run logs Table started successfully
  • 16.157 queueUpdatingTask gets ZSESSIONEXPIRED and calls restarting_thread.wakeup
  • 16.160 the pool task enters run on another thread and logs Activating replica., the first_time branch, so no partialShutdown
  • 16.170 the inline path calls restarting_thread.start
  • 16.443 the pool task runs queue.initialize and load, replacing the queue entries with new objects for the same znodes
  • 17.443 the mutation commits all_1_1_0_5, then removeProcessedEntry does not find its original entry and the server aborts

So in a release build the second tryStartup clears the in-memory queue under a running mutation. With the task created deactivated, the wakeup at 16.157 is a no-op, and the session replacement goes through start and then partialShutdown, which removes and waits for the table's running merge and mutation tasks before the queue is reinitialized.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes. Master still has the race this fixes: the restarting thread's task is still created schedulable, the attach path still activates the replica inline with restarting_thread.run, and queueUpdatingTask still calls restarting_thread.wakeup on ZSESSIONEXPIRED, so a pool thread can start a second activation inside that window. #121672 reworked startup/shutdown but did not touch this.

CI hit it twice so far: Stress test (arm_debug) with Logical error: 'storage.is_readonly', and Stress test (arm_release) with Can't find queue-... in the memory queue, where the second activation reinitializes the queue under a running mutation.

The PR still merges cleanly. Its CI is from 2026-09-10, so I can merge master to rerun it if you want.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

A third CI hit, the first on master: Stress test (azure, amd_tsan) at a903fa731b1f reports a data race on first_time between the attach path's inline restarting_thread.run (ReplicatedMergeTreeRestartingThread.cpp:114) and the pool task (:122), and it aborted the server on two consecutive starts (STID 4283-6081).

The trigger is different from the session expiry, and more common: only a failed inline activation is needed. For test_1.rmt1, tryStartup threw ALL_REPLICAS_LOST, so the catch in run called task->scheduleAfter(next_failure_retry_ms) (100 ms on the first failure) on the task that is schedulable from construction but not started yet. The pool then entered run while the inline call was still in partialShutdown and tryLogCurrentException. The server log shows this on all three starts of that phase: the pool task logs Activating replica. 100 ms after the inline call's Waiting for threads to finish (03:21:37.160 -> 37.260, 03:22:08.134 -> 08.234, 03:22:39.342 -> 39.443), with no Starting the restarting thread line before it.

With the task created deactivated, that scheduleAfter returns without scheduling, and the following start(/*schedule=*/true) schedules the retry only after the inline run has returned.

This branch has not been deployed

No deployments
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 comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants