Skip to content

Pause the statistics refresh while replica metadata restore and RENAME TABLE rewrite part paths - #125927

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-statistics-refresh-part-path-race
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-statistics-refresh-part-path-race

Conversation

@groeneai

@groeneai groeneai commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Description

TSan data races in CI, both with the background statistics refresh (MergeTreeData::refreshStatistics) reading a part's root_path/part_dir while another thread rewrites it:

  • Integration tests (amd_tsan, 1/8), test_modify_engine_on_restart/test_lazy_load_tables.py: the convert-to-replicated startup job runs restoreMetadataInZooKeeper, which renames every part to detached/ in place (report).
  • Stateless tests (amd_tsan, flaky check), STID 4967-4b32: RENAME TABLE of a non-Atomic table (MergeTreeData::rename -> changeRootPath) (report).

The refresh holds no table lock, and since #124420 no parts lock either. Instead of locking the reader, both writers now pause the refresh task (new MergeTreeData::pauseStatisticsCache, a guard that waits for a running pass and re-arms the task afterwards), which also works for lazy_load_tables stand-ins. So does the cleanup of parts with a failed quorum, which renames single parts the same way. The runtime SYSTEM RESTORE REPLICA additionally takes the exclusive lock of the table (for a lazily loaded table, also the lock of its nested storage, which system.parts takes) while it moves the parts, because queries read the same paths (TSan also reported a heap-use-after-free there). So it now waits for running queries, up to lock_acquire_timeout.

Validated on TSan builds of this branch and its base with the CI test's flow (convert-to-replicated in a lazy database, restart) and with loops of SYSTEM RESTORE REPLICA and RENAME TABLE while the refresh and queries run: about 100 reports on base, none with the fix. Related stateless tests show no new failures. Only TSan observes the race; a new test checks that the refresh task is armed again after RENAME TABLE. A non-Atomic RENAME with a refresh in flight waits for one part's statistics load (1.4 s on a disk throttled to 2 GET/s).

If #120758 removes the background refresh first, only the SYSTEM RESTORE REPLICA lock remains needed.


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

groeneai and others added 4 commits October 15, 2026 00:37
The background statistics refresh (`MergeTreeData::refreshStatistics`) reads
the storage path of every part without any table lock, and since ClickHouse#124420
without the parts lock. Two writers rewrite those paths for every part:
`restoreMetadataInZooKeeper`, which renames all parts to `detached/` in place
(`forcefullyMovePartToDetachedAndRemoveFromMemory`, documented as unsafe for
parts others hold), and `MergeTreeData::rename` (`changeRootPath`, under the
exclusive lock of the catalog object only). TSan reported both in CI: the
convert-to-replicated startup job in
test_modify_engine_on_restart/test_lazy_load_tables.py and RENAME TABLE of a
non-Atomic table (STID 4967-4b32).

Add `MergeTreeData::pauseStatisticsCache`, a guard that cancels and
deactivates the refresh task (waiting for a running pass, which stops at its
next part), keeps it disarmed while any guard lives, and re-arms it at the end
if it was armed or `startStatisticsCache` was called meanwhile. Shutdown wins.
Pausing through the task works for `lazy_load_tables` stand-ins too, whose
table locks belong to the proxy, not to the nested storage running the task.

Both writers take the guard around their rename loops. `MergeTreeData::rename`
releases it after `renameInMemory`, so the re-armed task gets the new storage
id. The runtime `SYSTEM RESTORE REPLICA` additionally takes the exclusive lock
of the catalog object (the one queries lock) around the snapshot and the move
loop, because queries read the same paths (TSan reported a race and a
heap-use-after-free on the marks loader there). It is passed as a callback;
the attach thread and the convert-to-replicated job cannot take it (they run
inside the table's startup) and need not (queries wait for the startup job).

Cost: a non-Atomic RENAME with a refresh pass in flight waits for one part's
statistics load (1.4 s on a disk throttled to 2 GET/s, 0.1 s before), and the
runtime restore waits for running queries up to `lock_acquire_timeout`
(then DEADLOCK_AVOIDED, which the client may retry).

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

Three follow-ups to the statistics refresh pause:

- `ReplicatedMergeTreeRestartingThread::removeFailedQuorumParts` moves parts
  with a failed quorum to `detached/` with
  `forcefullyMovePartToDetachedAndRemoveFromMemory`, which renames them in
  place, and it runs on every restarting-thread startup while the refresh is
  armed. It now pauses the refresh around its loop when there is anything to
  move.
- For a `lazy_load_tables` stand-in, the runtime `SYSTEM RESTORE REPLICA`
  locked only the stand-in, while `system.parts` locks the nested storage and
  reads part paths. The `lock_out_readers` callback now returns a vector of
  locks, and `restoreReplica` takes the stand-in's lock and then the nested
  storage's lock when it is a different object.
- A test checks that the refresh task is armed again after `RENAME TABLE` of
  a table in an Ordinary database, under the new table name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`deactivate` cancels only a delayed task: a task still waiting in the pool
queue, or one that is executing, stays in `system.background_schedule_pool`
with `deactivated = 1` until a worker is done with it. The first refresh pass
of the table is queued at CREATE TABLE and can wait there when the per-type
cap is saturated by other tables' refresh passes, so the query after RENAME
could list the old task next to the new one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the three call-site comments on why the statistics refresh is paused, keep that once on pauseStatisticsCache, shorten the lock_out_readers doc, and leave the refresh_stats_task_mutex comment as on master.

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

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

Pre-publication review by an independent model (engine: codex) plus my own review, three rounds.

# Sev Finding Verdict Evidence / action
1 ⚠️ The failed-quorum cleanup (removeFailedQuorumParts) also renames an Active part in place while the refresh may read it AGREE, fixed @ 3d7a792 pause guard around its loop
2 ⚠️ For a lazily loaded table, system.parts locks the nested storage, not the stand-in the restore locks AGREE, fixed @ 3d7a792 the restore locks both, stand-in first
3 ❌ mergeTreeIndex and sibling table functions read source parts with no lock on the source table DISAGREE they take no table lock at all, so they race with every in-place part writer on master, e.g. RENAME TABLE in an Ordinary database; not changed or widened here
4 ⚠️ No test fails if the refresh is never re-armed AGREE, fixed @ 3d7a792 new test: the task is armed again after RENAME TABLE; a timing test of the restore lock is not added
5 ❌ Queries that load statistics still race with the failed-quorum cleanup DISAGREE the same query reads that part's data and marks through the same paths with no lock on every release (TSan on base: 19 query-reader reports against the same rename), as MergeTreeData.h documents for forcefullyMovePartToDetachedAndRemoveFromMemory on active parts; pre-existing, not widened here
6 ⚠️ The new test can list the old, deactivated task while it is still queued AGREE, fixed @ c964f72 filter deactivated = 0

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. The final round found nothing new.

Session id: cron:clickhouse-review-slot-8:20261015-024400

@clickhouse-gh

clickhouse-gh Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3b17102]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_asan_ubsan, azure, parallel) FAIL
05258_query_condition_cache_prewhere_attribution FAIL cidb

AI Review

Summary

Reviewed commit 3b171021904781b0dcc4b16a98acbfd8a371ffe9. The PR pauses MergeTreeData::refreshStatistics while part paths are rewritten and excludes table readers during runtime SYSTEM RESTORE REPLICA, including lazy-table wrappers. No actionable new findings. The regression test 05401_statistics_refresh_task_rearmed_after_rename passes in Fast test. The PR also reports before/after TSan stress validation, which was not independently rerun during this review.

Final Verdict

Status: ✅ Approve.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tiandiwonder @alesapin, could you review this? The background statistics refresh reads part paths without any lock since #124420, so restoreMetadataInZooKeeper, the failed-quorum cleanup and a non-Atomic RENAME TABLE now pause it while they rename parts in place, and the runtime SYSTEM RESTORE REPLICA also takes the exclusive table lock.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Oct 15, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Oct 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3b17102

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
Stateless tests (arm_asan_ubsan, azure, parallel) / 05258_query_condition_cache_prewhere_attribution flaky, not from this PR (it only changes the statistics refresh and restore locking): the second query of a pair (qcc_no_rf_2) found no query condition cache entry (0 0), 0 of 3 reruns failed. The tested merge commit predates the fix, which runs the test no-parallel because other tests clear that server-wide cache #125702 (mine, merged)
PR praktika rollup of the row above #125702 (mine, merged)

The only other FAIL rows on this head are the Config Workflow pre-hook of the two attempts before the can be tested label was added; the job passed after that.

Session id: cron:our-pr-ci-monitor:20261015-190014

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim this label will not produce a 26.10 backport: the robot only picks merged PRs, and this PR cannot merge on master because #120758 (merged 2026-10-16) removed refreshStatistics and startStatisticsCache, the code it patches. That is also why master is clean since then: 0 failures in 3952 test_modify_engine_on_restart results on 104 master commits in amd_tsan, against 14 on the 26.10 branch and its backport PRs.

26.10 has #124420 without #120758, so the fix has to land on the branch itself, and I don't open PRs against release branches. Two options (same question I left on #126352):

  • cherry-pick this PR onto 26.10: its diff applies without conflicts (checked against 26.10 at 9e331a83);
  • or put back the readLockParts() above loadStatistics in refreshStatistics that remove readLockParts above loadStatistics #124420 removed (26.6 to 26.9 still have it).

The open cherry-picks of #124420 to 26.7, 26.8 and 26.9 (#125184, #125185, #125186) would bring the same race to those branches if merged.

@hanfei1991

Copy link
Copy Markdown
Member

close it because #120758 is merged

@hanfei1991 hanfei1991 closed this Oct 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed for master: 0 test_modify_engine_on_restart failures in amd_tsan on 160 master commits since #120758 merged.

26.10 still has the race: 19 failures with this TSan report (DataPartStorageOnDiskBase::rename vs loadStatistics) on the branch and its backport PRs since 2026-10-16, the latest today at 09:54 UTC. It has #124420 but not #120758, and the v26.10-must-backport label on this closed PR will not fire. The cherry-picks of #124420 to 26.7, 26.8 and 26.9 were auto-closed today, so 26.10 is the only affected branch.

Could you put back auto parts_lock = readLockParts(); above loadStatistics in refreshStatistics on 26.10 (a revert of #124420 there), or should #120758 get v26.10-must-backport instead? I don't open PRs against release branches.

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. pr-not-for-changelog This PR should not be mentioned in the changelog v26.10-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants