Skip to content

Fix StorageReplicatedMergeTree startup/shutdown races - #121672

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-replicated-merge-tree-startup-shutdown-race
Oct 7, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-replicated-merge-tree-startup-shutdown-race

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Several things could go wrong when a DETACH raced an in-flight async startup of a ReplicatedMergeTree table:

  • The periodic refresh tasks and the outdated-parts loading task stayed armed on a table that was already shut down. A repeated shutdown returned early, and startup did not re-check shutdown_called.
  • waitFirstTry could hang forever. ReplicatedMergeTreeAttachThread::shutdown could cancel the scheduled first attempt before it ran, so first_try_done was never set. A racing start could also re-arm the attach task after shutdown had deactivated it.
  • The interserver parts exchange endpoint could be torn down under a concurrent full shutdown that still needs it for waitForUniquePartsToBeFetchedByOtherReplicas.

What changes:

  • shutdown is now serialized by a mutex, taken before shutdown_called is read.
  • shutdown deactivates the refresh tasks on every call, and on a repeated call stops whatever a racing startup could have re-armed.
  • startup stops right away when it sees shutdown_called after arming.
  • ReplicatedMergeTreeAttachThread re-checks the flag after arming, always deactivates in shutdown, and always sets and notifies first_try_done.

Split out of #96130, where the random DETACH/ATTACH testing hook exposed these races.

Related: #96130

Changelog category (leave one):

  • Improvement

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

Make the asynchronous startup of a ReplicatedMergeTree table robust against a concurrent DETACH, which could previously hang the startup forever or leave background tasks running on a table that was already shut down.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.1753-master (included in 26.10 and later)

A `DETACH` racing an in-flight async `startup` of a `ReplicatedMergeTree`
table could:
- leave the periodic refresh tasks and the outdated-parts loading task armed
  on a shut-down table (the repeated `shutdown` returned early, and `startup`
  did not re-check `shutdown_called`);
- hang `waitFirstTry` forever, when `ReplicatedMergeTreeAttachThread::shutdown`
  cancelled the scheduled first attempt before it ran, so `first_try_done`
  was never set; or re-arm the attach task after `shutdown` deactivated it;
- tear the interserver parts exchange endpoint down under a concurrent full
  shutdown that still needs it for `waitForUniquePartsToBeFetchedByOtherReplicas`.

`shutdown` is now serialized by a mutex taken before consulting
`shutdown_called`, deactivates the refresh tasks on every call, and on a
repeated call stops whatever a racing `startup` could have re-armed.
`startup` stops right away when it observes `shutdown_called` after arming.
`ReplicatedMergeTreeAttachThread` re-checks the flag after arming, always
deactivates in `shutdown`, and always publishes `first_try_done`.

Split out of #96130

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0e4ef7f]

Summary: ✅


AI Review

Summary

This PR hardens StorageReplicatedMergeTree against async startup/shutdown races by making repeated shutdown calls tear down anything a racing startup re-armed, making ReplicatedMergeTreeAttachThread always publish first_try_done on cancellation, deferring data_parts_exchange_endpoint teardown to the outer shutdown, and serializing refresh_stats_task replacement against concurrent deactivation. After reading the current PR diff, the current head code, the prior review threads, and the current green CI report, I do not see an unresolved correctness, concurrency, or lifecycle issue in the patched paths.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 0e4ef7f.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 66/84 (78.57%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 23, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 0e4ef7f4f with master 54ff83b1b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 0ca8150d9; 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

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

Job report

alexey-milovidov and others added 2 commits October 3, 2026 08:29
When the attach thread's `startupImpl` fails because the table is already
being shut down, its cleanup removed the interserver parts exchange
endpoint, while the full `shutdown` still needs it to serve peer fetches in
`waitForUniquePartsToBeFetchedByOtherReplicas`. Leave the endpoint to the
full `shutdown` in that case, and make the attach thread stop retrying once
the storage is being shut down, so it never tries to register the endpoint
again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 5, 2026 01:53
…s_task`

`startStatisticsCache` re-assigns the `refresh_stats_task` holder (on `startup`
and on `ALTER` of `refresh_statistics_interval`), while a concurrent `shutdown`
reads and deactivates the same holder. Guard the holder with a dedicated mutex
and route every deactivation through the new `stopStatisticsCache`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: 05237_with_expression_alias_scope_descendant in https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121672&sha=8f6acff2228c21d13f30ae32011f32c7691f7698&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20parallel%2C%201%2F2%29 (the view row returned 10 instead of 100; not reproducible on rerun, unrelated to this PR) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Other failures from the previous run: the stress test server start failure (05315_mongodb_connection_options_secrets named collections) and 05218_timeseries_alp_codec are fixed on master and pulled in by the merge just pushed; 01660_join_or_any under parallel replicas is being fixed in #123683. new_tests_check is still open for a maintainer decision, see the review thread.

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator

The fix is in progress: #123790 (it includes the change from my #123774, closed in its favor). In its own run on 2a290a03b667, 05237_with_expression_alias_scope_descendant passes in the arm_binary DBReplicated job.

The failure on 8f6acff2228c has the same diff as on the other PRs (view 10, stored alias is bare 0): it is deterministic in that job, and the 71 reruns pass only because the diagnostics rerun runs without --replicated-database (my open #112247 fixes that). The new head 0a0c604056df includes #123789, so it will not run this job until #123790 brings it back with the fix.

…h-thread startup cleanup

The previous fix decided whether to keep `data_parts_exchange_endpoint` from plain loads of
`shutdown_prepared_called` / `shutdown_called`, which a concurrent full `shutdown` publishes
later, so the cleanup could still remove the endpoint that the full `shutdown` then needs in
`waitForUniquePartsToBeFetchedByOtherReplicas`. Taking `shutdown_mutex` there is not possible:
the full `shutdown` holds it while waiting for the attach thread.

Now the failure cleanup of `startupImpl` in the attach thread leaves the endpoint registered,
and its teardown belongs to `shutdown` only. A retry of the attach thread reuses the registered
endpoint. The endpoint is published in `data_parts_exchange_endpoint` only after `addEndpoint`
succeeds, so a retry never skips the registration, and a duplicate-endpoint failure no longer
removes the endpoint of another table with the same name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The Stateless tests (arm_asan_ubsan, azure, sequential) failure on 0a0c604 is the job-level 9000 s timeout. It hit at test 1153 of 1164 while tests were still passing at normal speed, so it is a capacity problem of that lane, not a hang. #123849 (splitting the lane into 2 batches) addresses it. Pushed 407a0ab for the remaining review thread about the endpoint teardown. new_tests_check is still left for a maintainer decision.

@alexey-milovidov alexey-milovidov removed the pr-bugfix Pull request with bugfix, not backported by default label Oct 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only failing check was the bug-fix gate in Finish Workflow (No new tests have been added). That gate needs a regression test that fails on master. These races only show up when a DETACH runs during the async table startup at server start. A regular ATTACH/DETACH from a query is serialized by DDLGuard, so a stateless test can't reproduce them deterministically. They were found by the random DETACH/ATTACH testing hook in #96130. I changed the changelog category to Improvement and merged master. A human should check whether Bug Fix (with backports) is preferred; that would need a reproducer, e.g. a failpoint-based one.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Oct 6, 2026
…tup`

During server or database shutdown, `flushAndPrepareForShutdown` runs for all
tables before `shutdown`. It sets `shutdown_prepared_called` and stops the attach
and restarting threads, but not `shutdown_called`. A late async `startup` must not
re-arm background work after that, so stop it on either flag.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found this good. Even verbosity is justified.

@alexey-milovidov alexey-milovidov self-assigned this Oct 7, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 7, 2026
Merged via the queue into master with commit 49ffde5 Oct 7, 2026
152 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-replicated-merge-tree-startup-shutdown-race branch October 7, 2026 14:57
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 7, 2026
alexey-milovidov added a commit that referenced this pull request Oct 8, 2026
Resolve conflicts with #121672 (the `StorageReplicatedMergeTree` half), which
already added `refresh_stats_task_mutex` and `stopStatisticsCache`: keep the
`refresh_stats_stopped` latch from this PR on top of it, and take master's
`StorageReplicatedMergeTree::shutdown`, which already stops the statistics task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 13, 2026
Resolve the cherry-pick of #125165 to 26.9.

The conflicts come from #121671 and #121672, which are not on 26.9: on
master the statistics refresh task is stopped through `stopStatisticsCache`
under `refresh_stats_task_mutex`, and the `refreshStatistics` loop no
longer takes the parts lock per part. On 26.9 the task is deactivated
directly in `startStatisticsCache`, `~MergeTreeData` and the `shutdown`
of `StorageMergeTree` and `StorageReplicatedMergeTree`, so
`refresh_stats_cancelled` is set before each of those four
`deactivate` calls, reset when `startStatisticsCache` arms a new task,
and checked before each part in `refreshStatistics`.

Neither the mutex nor `stopStatisticsCache` is ported, and the
`LoadedStatistics` profile event that master's loop also increments is
left out. The `05361_statistics_refresh_does_not_block_drop` test is
ported unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Oct 13, 2026
Resolve the cherry-pick of #125165 to 26.8.

The conflicts come from #121671 and #121672, which are not on 26.8: on
master the statistics refresh task is stopped through `stopStatisticsCache`
under `refresh_stats_task_mutex`, and the `refreshStatistics` loop no
longer takes the parts lock per part. On 26.8 the task is deactivated
directly in `startStatisticsCache`, `~MergeTreeData` and the `shutdown`
of `StorageMergeTree` and `StorageReplicatedMergeTree`, so
`refresh_stats_cancelled` is set before each of those four
`deactivate` calls, reset when `startStatisticsCache` arms a new task,
and checked before each part in `refreshStatistics`.

Neither the mutex nor `stopStatisticsCache` is ported, and the
`LoadedStatistics` profile event that master's loop also increments is
left out. The `05361_statistics_refresh_does_not_block_drop` test is
ported unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. pr-improvement Pull request with some product improvements 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