Skip to content

Deactivate the background tasks in the MergeTreeData destructor - #113722

Merged
alexey-milovidov merged 5 commits into
masterfrom
fix/statistics-refresh-task-destruction-race
Aug 10, 2026
Merged

alexey-milovidov merged 5 commits into
masterfrom
fix/statistics-refresh-task-destruction-race

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

ThreadSanitizer caught a data race between MergeTreeData::refreshStatistics running in the background schedule pool and MergeTreeData::~MergeTreeData: the task captures this and writes cached_estimator under stats_mutex, but both members are declared after refresh_stats_task, so they are destroyed before the holder's destructor deactivates the task. shutdown deactivates the task too, but a task activated after the shutdown (a table startup or an ALTER of refresh_statistics_interval racing with a drop) can still be running when the storage is destroyed. refresh_parts_task has the same hazard with refresh_parts_mutex, and outdated_data_parts_loading_task / unexpected_data_parts_loading_task have it with outdated_unloaded_data_parts / unexpected_data_parts (startup can re-activate them after shutdown already deactivated them). Deactivate all four tasks explicitly in the destructor before any member is destroyed; for the part-loading tasks this goes through stopOutdatedAndUnexpectedDataPartsLoadingTask, which sets the cancellation flags first so a running load exits early.

Caught by Stress test (arm_tsan) on an unrelated pull request: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109453&sha=f2faebe867fbdc127a107ee44f3c369cca2ce04d&name_0=PR&name_1=Stress%20test%20(arm_tsan)

The race is inherently non-deterministic (a stress-test interleaving of a table drop with the background statistics refresh), so no deterministic regression test is added; the CI report above is the reproduction.

Related: #89544
Related: #109453

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):

Fixed a data race between the background tasks of a MergeTree table (statistics refresh, parts refresh, outdated/unexpected parts loading) and the destruction of the table.

alexey-milovidov and others added 2 commits August 6, 2026 20:08
ThreadSanitizer caught a data race between `MergeTreeData::refreshStatistics`
running in the background schedule pool and `MergeTreeData::~MergeTreeData`:
the task captures `this` and writes `cached_estimator` under `stats_mutex`,
but both members are declared after `refresh_stats_task`, so they are
destroyed before the holder's destructor deactivates the task. `shutdown`
deactivates the task too, but a task activated after the shutdown (a table
startup or an ALTER of `refresh_statistics_interval` racing with a drop) can
still be running when the storage is destroyed. `refresh_parts_task` has the
same hazard with `refresh_parts_mutex`.

Deactivate both tasks explicitly in the destructor before any member is
destroyed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109453&sha=f2faebe867fbdc127a107ee44f3c369cca2ce04d&name_0=PR&name_1=Stress%20test%20(arm_tsan)
PR: #109453

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d9169d4]

Summary: ✅


AI Review

Summary

This PR changes MergeTreeData::~MergeTreeData to explicitly deactivate the four BackgroundSchedulePool task holders that can outlive shutdown() and otherwise rely on member-destruction order for cleanup. In the current code, deactivate() is a synchronizing stop, the destructor now stops both refresh tasks and both outdated/unexpected-part loading tasks before any dependent members are destroyed, and the previously reported startup/ALTER-vs-drop reactivation gap is closed. I did not find a remaining contract violation in the touched lifecycle paths.

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.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 8/10 (80.00%) · 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
…structor

`outdated_data_parts_loading_task` and `unexpected_data_parts_loading_task` have the
same declaration-order hazard as the refresh tasks: their holders are declared before
`outdated_unloaded_data_parts` / `unexpected_data_parts`, and `startup` can re-activate
them after `shutdown` already deactivated them. Call
`stopOutdatedAndUnexpectedDataPartsLoadingTask` in `~MergeTreeData` so the cancellation
flags are set before the join and a running load exits early.

Addresses the AI review blocker.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The three stress-test failures on ceedb772 are unrelated to this change (a destructor-only fix; none of the failing stacks involve ~MergeTreeData or the background tasks):

@alexey-milovidov alexey-milovidov changed the title Deactivate the refresh tasks in the MergeTreeData destructor Deactivate the background tasks in the MergeTreeData destructor Aug 8, 2026
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator

The Stress test (arm_asan_ubsan, s3) hung check on ceedb772 is fixed by your own #113909, which you opened six minutes after this comment, so there is nothing separate for me to send. I verified it covers this failure rather than assuming it:

  • The hung row is the query you quoted: elapsed 251.996213, is_cancelled = 1, read_rows 0, stack ending StorageSystemPartsColumns::processNextStorage <- StorageSystemPartsBase.cpp:337 (initializePipeline) <- ISourceStep::updatePipeline. The whole result is built inside initializePipeline, before any executor exists, and PipelineExecutor is the only caller of addPipelineExecutor (PipelineExecutor.cpp:143). That is why cancelQuery had no executor to cancel and the row stayed for 252 s.
  • Check the query cancellation while filling system.parts and its siblings #113909 guards both the per-storage loop (StorageSystemPartsBase.cpp:335) and the per-part loop in each of the four processNextStorage implementations, following the system.zookeeper (StorageSystemZooKeeper.cpp:677) and system.remote_data_paths (StorageSystemRemoteDataPaths.cpp:354) pattern.
  • checkTimeLimit covers both channels here, not only the timeout. It calls throwProperExceptionIfNeeded first (ProcessList.cpp:672), which throws on is_killed irrespective of elapsed time, and timeout_overflow_mode defaults to THROW so the max_execution_time = 10 on that row fires too. That setting is not randomized by clickhouse-test.

One residual I am noting rather than raising: the guard is per part, while the observed frame was inside the per-column body (the enumerateStreams callback at StorageSystemPartsColumns.cpp:366). A single part with very many columns and substreams is still uninterruptible. The interval is bounded by one part and I have no case where that alone exceeds the window, so per-part looks like the right granularity.

Your other two bullets need nothing from me: the assertTypeEquality failures are the master-wide STID 2508-2e0c family you already link #113534 for.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single red on 9e401fcf — 04661_refreshable_mv_cancel_during_planning on Stateless tests (amd_tsan, s3 storage, parallel, 3/3) — is a timing flake of that test, unrelated to this change: the harness re-ran it 8/8 green with the same randomized settings, and the test races a 10-second client timeout against the drop of a refreshable materialized view on a loaded sanitizer runner. This PR only reorders destructor-time task deactivation in MergeTreeData (the joins happened anyway during member destruction), and the inner table destruction runs in the background drop thread, not in the DROP query the test times.

Opened #113960 to widen the test's timing margins. Also merged the latest master into this branch for a fresh CI run.

@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d9169d421 with master e493bf79b (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 2b2987cc1; 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.67 MiB 687.65 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

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single red on 0f21815e — test_keeper_dynamic_log_level/test.py::test_adjust_log_level on Integration tests (amd_msan, 4/8) — is a master-wide flake unrelated to this change: CIDB shows it failing on dozens of pull requests and on master itself since 2026-08-05 (18 failures on 08-08 alone), while this PR only reorders destructor-time task deactivation in MergeTreeData and touches no Keeper code. Fixes are already open: #113571 and #113938 (the test asserts the log level immediately after SET LOG LEVEL instead of polling for the change).

pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 9, 2026
The test distinguishes "the drop cancelled the blocked refresh planning"
from "the drop waited for the planning to finish" by racing a 10-second
client timeout against a ~30-second `sleepEachRow` chain inside the
refresh's planning stage. On a loaded sanitizer runner 10 seconds is not
enough for a legitimately cancelled drop: the test failed once with
"drop did not finish" on `Stateless tests (amd_tsan, s3 storage)` and
then passed 8/8 reruns with the same randomized settings.

Widen both sides of the margin: the planning block now lasts ~120 seconds
and the drop gets 60 seconds, keeping the discrimination (a drop that
waits for planning cannot fit in the timeout) while tolerating scheduling
delays.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113722&sha=9e401fcfde10f841ae373a205bc2b1630dd5a48e&name_0=PR
Related PR: ClickHouse#113722

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red on 0f21815e7e8 was the master-wide test_keeper_dynamic_log_level flake on Integration tests (amd_msan, 4/8); its fix #113938 has now merged into master, so I merged master into this branch (clean merge, new head d9169d421fb4) to pull the fix in and clear the red on the next CI run. MergeTreeData.cpp rebuilds clean after the merge. No unresolved review threads; AI review remains ✅.

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

Okay.

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit 2b9eafe Aug 10, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/statistics-refresh-task-destruction-race branch August 10, 2026 17:33
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 10, 2026
PedroTadim pushed a commit to JiaQiTang98/ClickHouse that referenced this pull request Sep 18, 2026
The tables based on `StorageSystemPartsBase` (`system.parts`, `system.parts_columns`,
`system.projection_parts`, `system.projection_parts_columns`) build the whole result
eagerly in `initializePipeline`, so a cancelled or timed out query kept building rows
over every storage and part until the very end. In a stress test with ThreadFuzzer this
took minutes and tripped the hung check: a `SELECT` over `system.parts_columns` stayed
in the process list for 252 seconds with `is_cancelled = 1` and `max_execution_time = 10`.
Check the query status per storage and per part.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113722&sha=ceedb772f6aa36e221d25ce48f9af71f032a7b08&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%2C%20s3%29
PR: ClickHouse#113722

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

Labels

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