Skip to content

Fix StorageMergeTree startup/shutdown race - #121671

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

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

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

A DETACH racing an in-flight async startup of a MergeTree table could leave background work running on a table that was already shut down. A repeated shutdown returned early, and startup did not re-check shutdown_called after arming the refresh tasks, the outdated-parts loading task, the background assignees and the cleanup thread. flushAndPrepareForShutdown runs only once, so nothing would ever stop them, and an armed task could fire while ~MergeTreeData destroys the state it touches.

With this change, shutdown sets shutdown_called before deactivating the periodic tasks. On a repeated call (including the one from the destructor), it stops everything a racing startup could have re-armed. startup returns early if the flag is already set, and re-checks it after arming to undo what it armed if shutdown won in the middle. All the stops are idempotent.

stopStatisticsCache (added together with refresh_stats_task_mutex by #121672) now also sets a latch, so that a later startStatisticsCache (from startup or an ALTER of refresh_statistics_interval) does not arm the statistics task after shutdown.

The unit test gtest_merge_tree_startup_after_shutdown.cpp runs the losing interleaving deterministically (a complete shutdown, then startup, then the repeated shutdown) and checks that no task of the table stays live in the schedule pools. It fails without the fix. A second test runs startup and flushAndShutdown concurrently.

Scope: this PR covers StorageMergeTree. The StorageReplicatedMergeTree / ReplicatedMergeTreeAttachThread half of the same race was fixed in #121672. On current master, the known SQL paths do not run shutdown concurrently with startup: DETACH waits for the table's startup job, ATTACH runs startup under the DDL guard, and database shutdown runs stopLoading first. The race was reached through the random DETACH/ATTACH hook from #96130.

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

Related: #96130
Related: #121672

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

🤖 Generated with Claude Code


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

Version info

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

A `DETACH` racing an in-flight async `startup` could leave background work
armed on a logically shut-down table: `shutdown` returned early on a repeated
call, and `startup` did not re-check `shutdown_called` after arming the
refresh tasks, the outdated-parts loading task, the background assignees and
the cleanup thread. Since `flushAndPrepareForShutdown` runs only once, nothing
would ever stop them, and an armed task could fire while `~MergeTreeData`
destroys the state it touches.

`shutdown` now publishes `shutdown_called` before deactivating the periodic
tasks and, on a repeated call (including the destructor's), stops everything a
racing `startup` could have re-armed. `startup` re-checks the flag after
arming and unwinds. All stops are idempotent.

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 [8022d00]

Summary: ✅


AI Review

Summary

This PR hardens the non-replicated StorageMergeTree shutdown path against late async startup and related post-shutdown re-arm sites by publishing shutdown_called earlier, centralizing background-task teardown in stopAllBackgroundTasks, latching stopStatisticsCache, and covering the main interleavings with focused gtest cases. I reviewed the current diff together with all prior discussion and resolved bot threads, and I do not see a remaining correctness or lifecycle issue in the scoped StorageMergeTree changes.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 8022d00.

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

Changed lines: Changed C/C++ lines covered: 66/71 (92.96%) · 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
Comment thread src/Storages/StorageMergeTree.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 23, 2026
alexey-milovidov and others added 2 commits September 26, 2026 16:41
Address review: the fix had no regression coverage. The test runs the losing
interleaving deterministically: the complete first `shutdown` (as done by
`DETACH`), then the late `startup`, then the repeated `shutdown` (as done by
the destructor), and checks that no task of the table stays live in the
schedule pools. Without the fix, three tasks stay live in the common pool and
one in the streaming pool.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8022d00ea with master 828144718 (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

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

Job report

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

Looks clear.

alexey-milovidov and others added 2 commits September 27, 2026 03:48
`startStatisticsCache` move-assigns the `refresh_stats_task` holder, and it can run
concurrently with `shutdown` (a late async `startup`, or an `ALTER` of
`refresh_statistics_interval` racing with a `DETACH`/`DROP`), which reads and deactivates
the same holder. The holder is a plain `shared_ptr` wrapper, so this is a data race.

Guard the holder with `refresh_stats_task_mutex` and add `stopStatisticsCache`, which
deactivates the task and latches `refresh_stats_stopped`, so a `startStatisticsCache`
that runs after it does not arm the task at all. Use it in `StorageMergeTree::shutdown`,
the `startup` re-check, `StorageReplicatedMergeTree::shutdown` and `~MergeTreeData`.

Add a gtest that runs `startup` and `flushAndShutdown` concurrently and checks that no
task of the table stays live.

Addresses the AI review on #121671

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

Copy link
Copy Markdown
Member Author

🕵 Merged master (no conflicts); the PR's unit tests StorageMergeTree.StartupAfterShutdownArmsNoBackgroundTasks and StorageMergeTree.ConcurrentStartupAndShutdownArmNoBackgroundTasks pass locally. The only red check was Performance Comparison (arm_release, master_head, 1/6), flagging optimize_time_filter_with_preimage #4. This PR changes only MergeTree table startup/shutdown, which is not on that query's execution path, and the runner was also labeled disk-almost-full. Following the AI review, I changed the changelog category to Not for changelog: the description says there is no known SQL path that triggers this race on current master.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Oct 3, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits October 5, 2026 04:56
…down`

A late async `startup` on a table that was already shut down used to arm the
cleanup thread and the part-loading tasks, which run their first iteration
right away, and only then unwind them via the post-arm `shutdown_called`
re-check. Return before arming anything; the post-arm re-check stays for the
case where `shutdown` wins in the middle of `startup`.

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 Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) (the view returns 10 instead of 100, not reproducible on 58 reruns): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121671&sha=2b2ad922d5d49e3e5707f15401f5ffe160998ec3&name_0=PR and provide a fix in a separate PR. If the fix is already in progress, link it here.

Other failures: Build (amd_fuzzers) is fixed on master by #123738, 04316_reader_executor_basic by #123709 (master merged into this branch), and 05257_sql_security_view_sealed with parallel replicas looks covered by #123729.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
@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.

It is not flaky: on 2b2ad922d5d4 it has the same diff as on the other PRs (view 10, stored alias is bare 0), and it fails on every DBReplicated run. The 58 reruns pass because the diagnostic rerun runs without the Replicated database (#112247). The new head ef328fed81ca includes #123789, so this job will not run on it until #123790 brings it back with the fix.

The rollback of a failed writable-table settings `ALTER` calls
`wakeupBackgroundWorkers`, which re-arms the outdated/unexpected part loaders
via `startOutdatedAndUnexpectedDataPartsLoadingTask`. If `shutdown` has already
stopped them, they could fire on a shut-down table. Make
`wakeupBackgroundWorkers` a no-op once `shutdown_called` is set, which covers
every caller.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
`MergeTreeData::changeSettings` calls `startBackgroundMovesIfNeeded` on a
`storage_policy` change, which only checked `background_workers_enabled`, so
a settings `ALTER` racing after `shutdown` could re-arm
`background_moves_assignee` on a shut-down table. Skip it after `shutdown`,
re-check `shutdown_called` after `start` to close the race with a concurrent
`shutdown`, and make `scheduleDataMovingJob` return early after `shutdown`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 4 commits October 7, 2026 06:57
…ed` after arming in `ALTER`

`flushAndShutdown` runs `flushAndPrepareForShutdown` before `shutdown_called` is set, so a
concurrent `startup` could re-arm the assignees and the cleanup thread after they were stopped
without observing the flag, and `shutdown` never stopped them again (`flushAndPrepareForShutdown`
runs only once). This was caught by `StorageMergeTree.ConcurrentStartupAndShutdownArmNoBackgroundTasks`
in Unit tests (msan): https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121671&sha=latest&name_0=PR&name_1=Unit%20tests%20(msan)
PR: #121671

Now `shutdown` stops all background tasks unconditionally on every call, after publishing the flag.

Address review: the `table_readonly` 1 -> 0 `ALTER` re-checks `shutdown_called` after
`startBackgroundWorkers` and stops everything if a concurrent `shutdown` won, and the post-commit
disk cleanup is skipped on a shut-down table.

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

`wakeupBackgroundWorkers` checked `shutdown_called` only before the wake-up, so a `shutdown`
that published the flag right after that check could still see the cleanup task and the part
loaders re-armed on a shut-down table. Re-check the flag after the wake-up and stop all background
tasks if a concurrent `shutdown` won, the same pattern as in `startup` and the `table_readonly`
`ALTER`. Also skip `MergeTreeCleanupThread::iterate` once `shutdown_called` is set, so an iteration
scheduled in that window does nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 alexey-milovidov self-assigned this Oct 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 9, 2026
Merged via the queue into master with commit 448b879 Oct 9, 2026
152 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-merge-tree-startup-shutdown-race branch October 9, 2026 01:49
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 9, 2026
alexey-milovidov added a commit that referenced this pull request Oct 9, 2026
…r-part

Conflicts with #121671 resolved by
keeping its startup/shutdown race fix in `StorageMergeTree` while dropping the
statistics refresh task (`startStatisticsCache`, `stopStatisticsCache`,
`refresh_stats_task_mutex`), which this PR removes.

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-not-for-changelog This PR should not be mentioned in the changelog 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