Skip to content

Do not wait for a running statistics refresh when a MergeTree table is shut down - #125165

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/statistics-refresh-does-not-block-shutdown
Oct 12, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:groeneai/statistics-refresh-does-not-block-shutdown

Conversation

@groeneai

@groeneai groeneai commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

DROP TABLE, DETACH TABLE, server shutdown and ALTER TABLE ... MODIFY SETTING refresh_statistics_interval no longer wait until a running background refresh of the statistics cache of a MergeTree table has read the statistics of every part. On object storage with thousands of parts this wait could take minutes per table and delay a server restart. Closes #125136.

Description

MergeTreeData::refreshStatistics, the background task behind refresh_statistics_interval (300 s by default), reads the statistics of every active part, at least one read from the part's disk per part, with no stop check. Every place that stops the task (table shutdown, so DROP, DETACH and server shutdown; the destructor; ALTER ... MODIFY SETTING refresh_statistics_interval) calls deactivate, which waits for the running callback. On object storage with thousands of parts that is minutes per table, as in #125136, where a restart did not finish.

The task now has an atomic cancellation flag, set before each deactivate and reset only when a new task is armed. The walk checks it before each part and returns without publishing the partial estimator, so stopping the task waits for at most one part's statistics reads. refresh_stats_stopped could not be reused: it is guarded by the mutex the stopping thread holds while it waits, and the ALTER path must not set it.

Validation (debug build, local MinIO, disk throttled to 2 GET/s): DROP TABLE ... SYNC and the ALTER during a refresh take 58 to 70 s on master and at most 3.3 s with the change (over 300 randomized runs, more than half of them in parallel); a server with two tables of 120 parts mid-refresh shuts down in 121.9 s on master and 4.2 s with the change. The new test reproduces it through the disk-level s3_max_get_rps throttle, without failpoints; it fails on master and on each of four deletion mutants of the change.


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

Version info

  • Merged into: 26.10.1.2228-master (included in 26.10 and later)
  • Backported to: 26.9.18.13, 26.8.26.15

groeneai and others added 2 commits October 11, 2026 07:16
`refreshStatistics` walks every active part and reads its statistics, one or
more object storage reads per part, with no stop check. Every deactivation of
`refresh_stats_task` (table shutdown, `DROP`/`DETACH`, the destructor, and
`ALTER ... MODIFY SETTING refresh_statistics_interval`) joins the running walk
in `BackgroundSchedulePoolTaskInfo::deactivate`, so on object storage with
thousands of parts each of them waited minutes, and a server restart with many
such tables did not finish. `refresh_stats_stopped` cannot be used for this:
it is guarded by the mutex the deactivating thread holds while it waits, and
the `ALTER` path must not set it.

Add an atomic `refresh_stats_cancelled`, set before both `deactivate` calls and
reset only when `startStatisticsCache` arms a new task (under the same mutex,
after the old task has been joined). The walk checks it before each part and
returns without publishing the partial estimator, so a deactivation waits for
at most one part.

Closes ClickHouse#125136

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the refresh_stats_cancelled member comment to its one-line contract.

Co-Authored-By: Claude Opus 5.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 Oct 11, 2026
@groeneai

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

Two rounds: own cold review + Gate B (codex) on 5067fdae5970, then again on 7dfc5811b1b2 (Gate B: 0 findings).

Finding Verdict
⚠️ The test's wait for a running refresh accepted any executing sample, so a deleted flag reset could pass on a microsecond no-op run AGREE, fixed: the wait also requires elapsed_ms > 1000; that mutant now fails 10/10
💡 The test asserts DDL latency Kept: the master floor comes from the disk throttle (58 s or more), the fix max is 3.3 s over 156 randomized runs against a 20 s bound; no failpoint
💡 A stop still waits for one part's statistics reads, not one read By design; finer needs a cancellation parameter in the shared loadStatistics

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b3dc9e0]

Summary: ✅


AI Review

Summary

This PR adds a cancellation flag around MergeTreeData::refreshStatistics so ALTER TABLE ... MODIFY SETTING refresh_statistics_interval, DROP TABLE, DETACH TABLE, and shutdown stop waiting for a full statistics sweep across all parts. The core C++ task-lifecycle change looks consistent with the existing deactivate contract, but the new stateless test still has a false-positive path: if it never observes a running refresh, it prints a message and continues, so the regression test can pass without exercising the in-flight-refresh case it is meant to guard.

PR Metadata
  • Changelog category is mismatched: this is a real user-visible fix for a shutdown / DDL stall, so it should be Bug Fix, not Improvement.
  • Changelog entry is required for Bug Fix and the current text is specific enough.
  • Exact replacement for the category:
    • - Bug Fix
Findings
  • ⚠️ Majors
    • [tests/queries/0_stateless/05361_statistics_refresh_does_not_block_drop.sh:43, tests/clickhouse-test:4165] wait_for_refresh still returns success on timeout because its fallback path ends with echo, and .sh tests are launched through plain bash rather than bash -e. If the poll never catches executing, the script keeps going and can still produce the expected query_log booleans, so this regression test can pass without ever synchronizing with a real in-flight refreshStatistics.
    • Suggested fix: make the timeout path fail the test (echo ... >&2; exit 1), or enable set -e and return a non-zero status from wait_for_refresh.
Final Verdict

Changes required before merge: the production-side cancellation logic looks reasonable, but the new regression test still admits a success path that does not validate the contract it is supposed to protect.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b3dc9e00a with master ac85267b8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of dca38d441; 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

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

Job report

groeneai and others added 2 commits October 11, 2026 09:45
…e GET limit

The CI test profile (`tests/config/users.d/enable_blobs_check.xml`) enables
`s3_check_objects_after_upload`, which sends two HEAD requests per uploaded
part. They count against the disk's `s3_max_get_rps = 2`, so each 120-part
INSERT took about 120 s and every CI run 250 to 310 s (over the 180 s limit).
The disk access check at CREATE adds a few more HEAD/GET requests, and it runs
under `Context::getOrCreateDisk`'s server-wide `storage_policies_mutex`, which
in the flaky check serialized the parallel runs (CREATE up to 15 s) and
delayed their DROPs.

Disable `s3_check_objects_after_upload` for the inserts and skip the access
check of the ad hoc disks. With the CI user profile installed locally (debug
build): a run takes 8 to 11 s instead of 250 s, INSERTs make no throttled
requests, the 50 randomized runs (half at -j 8) pass with ALTER <= 0.9 s and
DROP <= 1.2 s, master still waits 58 s for both, and the four deletion mutants
still fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky checks on release and debug builds still ran the test for 150-200 s at 3e2d7fa:
with 8 copies in parallel, every one-row part cost about 650 ms of S3 uploads in CI, so each
120-part INSERT took 70-97 s, and one DROP of 120 parts waited 110 s in the shared parts
cleanup pool.

A statistics refresh reads every statistic of a part with its own GET request, so 24 parts with
5 statistics each keep the throttled walk at 120 requests or more, like 120 parts with one, while
the number of parts written and removed is 5 times smaller.

Local, debug build, CI user profile: master ALTER/DROP 57.8-69.9 s (5 runs), fix 83/83 OK with
ALTER max 2.5 s and DROP max 1.9 s (25 sequential, 25 at -j 8, 32 at -j 16, 9-15 s per run);
the four deletion mutants still fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 12, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into ClickHouse:master with commit b38b68c Oct 12, 2026
173 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 12, 2026
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
…r-part

Conflicts:
- `src/Storages/MergeTree/MergeTreeData.cpp`, `MergeTreeData.h`: master changed the old statistics
  refresh task (`startStatisticsCache` / `stopStatisticsCache` / `refreshStatistics`, #125165) so that
  shutdown does not wait for a running refresh. This PR removes that task entirely in favor of the
  per-part cache, so the removal is kept. Its test `05361_statistics_refresh_does_not_block_drop`
  exercises only the removed task and `refresh_statistics_interval` (now obsolete), so it is deleted.
- `src/Core/ServerSettings.cpp`: kept the `statistics_cache_*` settings and took master's new
  description of `iceberg_metadata_files_cache_policy`; the description of `statistics_cache_policy`
  now lists the possible values like the other cache policies after #123435.
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]>
robot-ch-test-poll3 added a commit that referenced this pull request Oct 13, 2026
Cherry pick #125165 to 26.8: Do not wait for a running statistics refresh when a MergeTree table is shut down
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Oct 13, 2026
Cherry pick #125165 to 26.9: Do not wait for a running statistics refresh when a MergeTree table is shut down
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 13, 2026
Backport #125165 to 26.9: Do not wait for a running statistics refresh when a MergeTree table is shut down
clickhouse-gh Bot added a commit that referenced this pull request Oct 13, 2026
Backport #125165 to 26.8: Do not wait for a running statistics refresh when a MergeTree table is shut down
@groeneai

Copy link
Copy Markdown
Collaborator Author

A question about the release branches. The test this PR added, 05361_statistics_refresh_does_not_block_drop, made the post-stress restart fail on 26.8: Stress test (amd_asan_ubsan), Cannot start clickhouse-server.

Under stress the test's INSERT INTO t_drop failed with an injected CANNOT_SCHEDULE_TASK, so wait_for_refresh t_drop kept polling until the stress run ended. The server was then restarted with t_alter (26 parts on its 2 GET/s disk) still in place, and loading it took 209 throttled GETs: Loaded data parts (26 items) took 104.001 seconds. The server was not ready within the 2 minute start budget. The stress client's ignore_drop_queries_probability=0.2 can leave t_alter behind the same way.

The test is still on 26.8, 26.9 and 26.10 (#120758 removed it from master), and I don't open PRs against release branches. It is rare so far: 1 of about 2,000 release-branch stress jobs since 2026-10-13, and none of 60 sampled green restarts had the table left over. A lighter variant would not remove the hazard: loading a part reads about 8 objects and a refresh reads 5, so the restart always costs more than the refresh the test needs.

Should 05361_statistics_refresh_does_not_block_drop.{sh,reference} be deleted on 26.8, 26.9 and 26.10, as on master (my recommendation), or kept as is?

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-improvement Pull request with some product improvements pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Server shutdown blocks indefinitely in ~MergeTreeData() waiting for refreshStatistics()

6 participants