Repository navigation
Avoid pure-virtual abort during MergeTree destruction race (STID 3631-4165) - #104561
hanfei1991 merged 5 commits into
Conversation
…-4165) A `BackgroundJobsAssignee` task on a pool thread can race with `~StorageMergeTree` / `~StorageReplicatedMergeTree` and dispatch `data.scheduleDataProcessingJob(*this)` through a vtable that has already demoted to `MergeTreeData`. `scheduleDataProcessingJob` is pure virtual at the `MergeTreeData` level (only the leaf storages override it), so the dispatch lands on `__cxa_pure_virtual` and aborts the server. This is reachable in practice when `shutdown` throws partway through the cleanup. `StorageReplicatedMergeTree::~StorageReplicatedMergeTree` wraps the `shutdown` call in a try/catch and swallows the exception, so member destruction proceeds with the background scheduler still alive. `~BackgroundJobsAssignee::finish()` then calls `deactivate()`, which blocks on `exec_mutex` waiting for the in-flight `threadFunc` to finish — but `threadFunc`'s next call is the pure-virtual dispatch above. The fix is a defensive `false`-returning override of `scheduleDataProcessingJob` on `MergeTreeData`. In normal operation, the derived overrides win the virtual dispatch and this default is dead code. During the destruction race, the default takes the dispatch: `threadFunc` reads `false` as "no work scheduled" and falls through to `postpone()`, which is a no-op once `finish()` has moved the holder out. The pool thread completes `execute()` normally, the destructor's `deactivate()` returns, and destruction proceeds safely. Affected runs (all identical stack traces, all unrelated PRs): - PR ClickHouse#102343 (Paimon) — Stress test (arm_asan_ubsan) - PR ClickHouse#101027 (obfuscateQuery revert) — Stress test (arm_asan_ubsan, s3) - PR ClickHouse#100272 (h3 → h3o) — Stress test (arm_asan_ubsan, s3) - PR ClickHouse#104472 (count_distinct_optimization) — Stress test (arm_debug) CI report (latest): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104472&sha=ad31d65c8cb512098dc41a848bfa9e42650e123e&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Pre-PR validation gate (TASK.md §Phase 4 step 9) Session:
On the "fix root cause vs guard against symptom" question: shutdown() throwing partway through is a legitimate failure mode in a complex distributed system (e.g., ZooKeeper drops, exception during |
|
cc @alesapin @CurtizJ @alexey-milovidov — could you review this? It fixes a chronic |
|
Workflow [PR], commit [242806a] Summary: ✅
AI ReviewSummaryThis PR hardens Final VerdictStatus: ✅ Approve |
…lure path The base-class `MergeTreeData::scheduleDataProcessingJob` fallback only covers the late window where the vtable has already demoted to `MergeTreeData`. `background_operations_assignee` is a `MergeTreeData` member, so if `StorageReplicatedMergeTree::shutdown` throws before `partialShutdown` reaches `background_operations_assignee.finish`, the destructor's try/catch swallows the exception and the assignees are still active while the derived `StorageReplicatedMergeTree` members are being destroyed. In that earlier window a pool thread can still dispatch into `StorageReplicatedMergeTree::scheduleDataProcessingJob` and touch `queue`, `cleanup_thread`, or capture `this` while those members are in teardown. Stop all three assignees at the end of the destructor, after the try/catch and before derived member destruction begins. `finish` is idempotent (it moves the holder out under the lock), so this is a no-op on the normal path where `shutdown` already stopped them. `~StorageMergeTree` is not affected: its destructor does not catch, so a throwing `shutdown` reaches `std::terminate` from the noexcept destructor and never enters the live-assignee member-destruction window. The base-class `false`-returning fallback is kept as a last-resort guard for the demoted-vtable window. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Follow-up commit 8d91a4b addresses the review on the earlier (pre-demotion) window. Pre-PR validation gate:
Session: cron:clickhouse-ci-task-worker:20260603-205209 |
…h window The previous fix stopped the assignees only in ~StorageReplicatedMergeTree. The same demoted-vtable abort exists for plain StorageMergeTree via the streaming path: StorageMergeTree::shutdown calls flushAndPrepareForShutdown, which early-returns when flush_called is already set. If a prior flushAndPrepareForShutdown set flush_called (via flush_called.exchange(true)) but threw before reaching background_streaming_assignee.finish (e.g. a merges/moves blocker cancelForever throws, or cleanup_thread.stop throws), the destructor's shutdown(false) no-ops and the streaming assignee is left active while the derived members destruct. A pool thread can then dispatch BackgroundJobsAssignee::threadFunc -> MergeTreeData::scheduleStreamingJob (a MergeTreeData-level override that is reachable once the vtable demotes), which calls buildPromoters(), still pure virtual at the MergeTreeData level, landing in __cxa_pure_virtual and SIGABRT. Stop all three assignees at the end of ~StorageMergeTree, after shutdown(false) and before derived member destruction, mirroring the replicated destructor. finish is idempotent (moves the holder out under the lock), so it is a no-op on the normal path where shutdown already stopped them. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
CI summary — HEAD CI has fully finished on this commit: 143 success, 20 skipped, 0 pending/in-progress. Two stateless test failures, both unrelated to this PR's diff (MergeTree destructor lifetime fix):
No PR-caused failures. Ready for re-review. |
|
|
||
| bool MergeTreeData::scheduleDataProcessingJob(BackgroundJobsAssignee & /*assignee*/) | ||
| { | ||
| /// Safety net for STID 3631-4165 (pure-virtual call abort in |
There was a problem hiding this comment.
The comments here is too long. Please keep it as short as possible or remove them.
There was a problem hiding this comment.
Shortened in 242806a:
MergeTreeData::scheduleDataProcessingJob(cpp): 41-line block → 2 lines.MergeTreeData::scheduleDataProcessingJob(h): 12-line block → 2 lines.~StorageMergeTree/~StorageReplicatedMergeTreeassignee-stop comments: also tightened for consistency.
Net: -62 / +9 comment lines, no behavior change. Full rationale stays in the commit messages of 870737c / 8d91a4b / 4c2a4a6 and the PR description.
Built ASan locally, smoke-tested MergeTree create/insert/optimize/drop — clean.
Session id: cron:clickhouse-ci-task-worker:20260605-160700
Replace the long block comments in `MergeTreeData::scheduleDataProcessingJob` (definition and declaration) and the destructor assignee-stop calls in `~StorageMergeTree` / `~StorageReplicatedMergeTree` with one-to-two-line non-obvious-only comments. Full rationale (destruction race timeline, flushAndPrepareForShutdown early-return path, why finish is idempotent) remains in the commit messages of 870737c / 8d91a4b / 4c2a4a6 and the PR description. Net diff: -62 lines comments, +9 lines comments. No behavior change.
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes background-job scheduling lifecycle: a last-resort scheduleDataProcessingJob guard plus stopping background assignees in the StorageMergeTree/StorageReplicatedMergeTree destructors. None of that code runs on the SELECT query path, so the four flagged ClickBench improvements (Q4 -10%, Q15 -20%, Q28 -5%, Q34 -6%) cannot plausibly be caused by this change. They are run-to-run variance — note the base used 30 runs versus 6 on the source side — so all four are downgraded to not-sure rather than reported as real gains. clickbenchFlagged queries (4 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 8/10 (80.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 27 line(s) · Uncovered code |
CI Ledger — covered HEAD: `242806ac8dfc` (hanfei1991 comment-shortening fix-up)Pulled the failure set after CI fully completed (last check 20:45:45Z, >20min CIDB ingestion buffer met).
Zero test FAIL/ERROR rows in CIDB on this HEAD. The only red is `CH Inc sync` which is the CH Inc internal sync aggregator job, not a code result. All 143 builds + integration + stateless + stress + AST/BuzzHouse fuzzer + perf jobs pass on this HEAD. `Finish Workflow` and `Mergeable Check` both SUCCESS. Verified the StorageMergeTree streaming-assignee sibling-path fix (`4c2a4a6593f`) and the ReplicatedMergeTree fix (`8d91a4bfa50`) survived the comment-shortening rebase clean. Per the @hanfei1991 directive on 2026-06-05T14:28:05Z, the verbose explanatory comments in `MergeTreeData.cpp` (`scheduleDataProcessingJob` body, 41→2 lines), `MergeTreeData.h` (decl, 12→2 lines), and the destructor assignee-stop blocks (`StorageReplicatedMergeTree.cpp` 6→2, `StorageMergeTree.cpp` 3→3) have been shortened. Full rationale remains in the commit messages of `870737c1381` / `8d91a4bfa50` / `4c2a4a6593f` and the PR description. Awaiting reviewer ack. Session: cron:our-pr-ci-monitor:20260605-210000 |
…utdown noise The upgrade-check post-restart `<Error>` scrub catches a transient lock-timeout emitted by `SystemLog<MetricLogElement>::flushImpl` when the background `MetricLog` flush loop races with shutdown work on `system.metric_log` during the upgrade restart sequence: ``` <Error> void DB::SystemLog<DB::MetricLogElement>::flushImpl(...) [LogElement = DB::MetricLogElement]: Failed to flush system log system.metric_log with N entries up to offset M: Code: 473. DB::Exception: WRITE locking attempt on "system.metric_log" has timed out! (60000ms) Possible deadlock avoided. Client should retry. Owner query ids: . (DEADLOCK_AVOIDED), Stack trace ... ``` Another worker (DROP/RENAME/DETACH on `system.metric_log`, or a parallel mutation/merge) holds the table-level write lock, the flush blocks for the 60s timeout, and then aborts with code 473 (`DEADLOCK_AVOIDED`). The 473 code is the engine's own "gave up to avoid a deadlock, not a crash" signal — losing a few `MetricLogElement` samples during shutdown is harmless; the upgrade-check stage is not asserting on metric continuity. CIDB confirms this is chronic CI noise, not a code regression: 4 hits across 4 distinct PRs in the last 30 days, 0 master, 100% on `Upgrade check (amd_release)`. Reported by @ alexey-milovidov on PR ClickHouse#102017 (cited ClickHouse#106425, ClickHouse#104561, ClickHouse#106202). The added regex requires BOTH the `SystemLog` flush wrapper for `metric_log` AND the `DEADLOCK_AVOIDED` error code together, mirroring the narrowing approach of the existing `rdk:FAIL.*Connect to.*failed: Connection refused` and `StorageKafka2.*Broker transport failure` filters. Real `metric_log` regressions (other flush errors) and unrelated `DEADLOCK_AVOIDED` hits on other system_log tables (`query_log`, `text_log`, etc.) still surface. Related: ClickHouse#102017 Related: ClickHouse#106563 Related: ClickHouse#101576 Co-Authored-By: Claude Opus 4.8 <[email protected]>
STID 3631-4165 recurred on release branch 26.3 - this fix is not on 26.3, 26.5 or 25.8The
Master is clean (0 hits since this merged; the only other hit in 120 days is a pre-fix
On 26.3 and 26.5 the dtors are byte-identical to pre-fix master, the assignees are members The backport label is necessary but not sufficientSimulating what
But the clean merges do not compile. This PR's dtor hunks call three assignees, and Two references to an undeclared member. What I am asking forCould you apply Two things will need a hand afterwards:
I did not open release-branch PRs myself because I do not hand-write backports. @hanfei1991 you approved this one, so tagging you rather than opening a new thread. |
Avoid
__cxa_pure_virtualabort during MergeTree destruction race (STID 3631-4165). ABackgroundJobsAssigneetask on a pool thread can race with~StorageMergeTree/~StorageReplicatedMergeTreeand dispatchdata.scheduleDataProcessingJob(*this)through a vtable that has already demoted toMergeTreeData. SincescheduleDataProcessingJobis pure virtual at theMergeTreeDatalevel (it is overridden only by the leaf storages), the dispatch lands on__cxa_pure_virtualand the server aborts. Provide a defensivefalse-returning override onMergeTreeDataso the call stays well-defined; the backgroundthreadFuncthen exits via its normalpostpone()path which is a no-op oncefinish()has moved the holder out.Why this happens
IBackgroundOperation(the polymorphic interface used byBackgroundJobsAssignee::threadFunc) declares two pure virtuals:MergeTreeData : public IBackgroundOperationimplementsscheduleDataMovingJob, but notscheduleDataProcessingJob— that one is overridden only by the leaf storages (StorageMergeTree,StorageReplicatedMergeTree).In normal operation, dispatching
data.scheduleDataProcessingJob(*this)from insideBackgroundJobsAssignee::threadFuncalways lands on the leaf override, because the dynamic type of*thisis the leaf storage throughout the table's lifetime.The problem is the destruction race:
~StorageReplicatedMergeTree(or~StorageMergeTree) body runs with vtable = the leaf class.shutdown(false), which is supposed to callbackground_operations_assignee.finish()and stop pool threads.finish()deactivates theBackgroundSchedulePoolTaskHolder, which waits onexec_mutexuntil the in-flightfunction()returns.*thisdemotes toMergeTreeData.MergeTreeDatamember destructors run, including~BackgroundJobsAssigneefor both assignees. Their destructors callfinish()again — a no-op in the normal case becauseholderwas already moved out at step 2.If anything between step 2 and the actual
finish()call goes wrong —shutdown()throwing partway, aflushAndPrepareForShutdown/partialShutdownexception, an earlier externalshutdown()that returned early without reaching the assignee cleanup — the holder can still be non-null when we reach step 4. The destructor ofBackgroundJobsAssigneethen callsfinish()for the first time. Insidefinish(),deactivate()blocks onexec_mutex, waiting for the currently-runningfunction() = [this]{ threadFunc(); }to finish. ThatthreadFuncis about to issuedata.scheduleDataProcessingJob(*this)through the now-demotedMergeTreeDatavtable — where the method was pure virtual — and the call lands on__cxa_pure_virtual, aborting the process.StorageReplicatedMergeTree::~StorageReplicatedMergeTreewrapsshutdown(false)in atry/catch(logs and swallows), making it the primary scenario where this race is reachable.StorageMergeTree::~StorageMergeTreeletsshutdownthrow →std::terminate, which is a different crash class than the one tracked here.The fix
Provide a defensive
false-returning override ofscheduleDataProcessingJobonMergeTreeData:threadFuncinterpretsfalseas "no work was scheduled" and falls through topostpone().postpone()re-acquiresholder_mutexand sees thatfinish()has already movedholderout, so it returns immediately. The pool thread completesexecute()normally, releasesexec_mutex, and the destructor'sdeactivate()returns. Destruction proceeds safely.Reproducibility
This is a rare destruction-time race — it has hit 4 unrelated PRs across 30 days (PR #102343, #101027, #100272, #104472), with identical stack signatures, none of which touch the
BackgroundJobsAssignee/BackgroundSchedulePool/MergeTreeDatashutdown paths. CIDB cross-check below.The race is not deterministically reproducible in a regression test without intrusive instrumentation: it requires
shutdown()to throw partway through the cleanup AND a background task to be in flight at that exact moment. The fix is a defensive non-pure default at theMergeTreeDatalevel; verifying its correctness is a code review exercise rather than a test exercise, because the only observable effect in the normal path is "the default is never taken". CI stress tests will continue to surface this STID family if regressions are introduced.Local smoke test: built ClickHouse with the fix, started the server, created/inserted/optimized/dropped a
MergeTreetable over multiple parts — all worked correctly.Stack trace (representative — all 5 hits look identical)
CIDB cross-check (30 days)
obfuscateQuery.cpp, parsersCountDistinctPass.cpp, settingsNone of these PRs touch
src/Storages/MergeTree/BackgroundJobsAssignee.cpp,src/Core/BackgroundSchedulePool.cpp, or theMergeTreeData::shutdownpaths. The stack signature is identical across all 4 PRs — single root cause, chronic trunk bug.CI reports:
Related history
PR #99366 (merged 2026-03-16) fixed a different race in
BackgroundJobsAssignee::finish()(concurrentstart()/finish()mutatingholderwithout the lock). That fix is good but does not cover the vtable-demotion scenario described here, sinceholdermutex synchronization does nothing to prevent the leaf vtable from going away while a pool thread is mid-virtual-dispatch throughdata. STID 3631-4165 remained chronic after that merge.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Fix a rare server abort during
MergeTreefamily table destruction. The abort could occur whenshutdownraised an exception before the background-job scheduler was fully stopped: a background task firing in that narrow window would dispatch a virtual call through a partially-destroyed storage object and hit__cxa_pure_virtual.Documentation entry for user-facing changes
Version info
26.6.1.462