Skip to content

Avoid pure-virtual abort during MergeTree destruction race (STID 3631-4165) - #104561

Merged
hanfei1991 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3631-4165-pure-virtual-bgjobs
Jun 6, 2026
Merged

hanfei1991 merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3631-4165-pure-virtual-bgjobs

Conversation

@groeneai

@groeneai groeneai commented May 11, 2026 •

Copy link
Copy Markdown
Collaborator

Avoid __cxa_pure_virtual abort during MergeTree destruction race (STID 3631-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. Since scheduleDataProcessingJob is pure virtual at the MergeTreeData level (it is overridden only by the leaf storages), the dispatch lands on __cxa_pure_virtual and the server aborts. Provide a defensive false-returning override on MergeTreeData so the call stays well-defined; the background threadFunc then exits via its normal postpone() path which is a no-op once finish() has moved the holder out.

Why this happens

IBackgroundOperation (the polymorphic interface used by BackgroundJobsAssignee::threadFunc) declares two pure virtuals:

virtual bool scheduleDataProcessingJob(BackgroundJobsAssignee & assignee) = 0;
virtual bool scheduleDataMovingJob(BackgroundJobsAssignee & assignee) = 0;

MergeTreeData : public IBackgroundOperation implements scheduleDataMovingJob, but not scheduleDataProcessingJob — that one is overridden only by the leaf storages (StorageMergeTree, StorageReplicatedMergeTree).

In normal operation, dispatching data.scheduleDataProcessingJob(*this) from inside BackgroundJobsAssignee::threadFunc always lands on the leaf override, because the dynamic type of *this is the leaf storage throughout the table's lifetime.

The problem is the destruction race:

  1. ~StorageReplicatedMergeTree (or ~StorageMergeTree) body runs with vtable = the leaf class.
  2. The body calls shutdown(false), which is supposed to call background_operations_assignee.finish() and stop pool threads. finish() deactivates the BackgroundSchedulePoolTaskHolder, which waits on exec_mutex until the in-flight function() returns.
  3. Body returns; the dynamic type of *this demotes to MergeTreeData.
  4. MergeTreeData member destructors run, including ~BackgroundJobsAssignee for both assignees. Their destructors call finish() again — a no-op in the normal case because holder was already moved out at step 2.

If anything between step 2 and the actual finish() call goes wrong — shutdown() throwing partway, a flushAndPrepareForShutdown / partialShutdown exception, an earlier external shutdown() that returned early without reaching the assignee cleanup — the holder can still be non-null when we reach step 4. The destructor of BackgroundJobsAssignee then calls finish() for the first time. Inside finish(), deactivate() blocks on exec_mutex, waiting for the currently-running function() = [this]{ threadFunc(); } to finish. That threadFunc is about to issue data.scheduleDataProcessingJob(*this) through the now-demoted MergeTreeData vtable — where the method was pure virtual — and the call lands on __cxa_pure_virtual, aborting the process.

StorageReplicatedMergeTree::~StorageReplicatedMergeTree wraps shutdown(false) in a try/catch (logs and swallows), making it the primary scenario where this race is reachable. StorageMergeTree::~StorageMergeTree lets shutdown throw → std::terminate, which is a different crash class than the one tracked here.

The fix

Provide a defensive false-returning override of scheduleDataProcessingJob on MergeTreeData:

bool MergeTreeData::scheduleDataProcessingJob(BackgroundJobsAssignee &)
{
    return false;
}
  • In normal operation, derived overrides always win the virtual dispatch — this default is dead code.
  • During the destruction race window, the now-defined default takes the dispatch. threadFunc interprets false as "no work was scheduled" and falls through to postpone().
  • postpone() re-acquires holder_mutex and sees that finish() has already moved holder out, so it returns immediately. The pool thread completes execute() normally, releases exec_mutex, and the destructor's deactivate() 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 / MergeTreeData shutdown 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 the MergeTreeData level; 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 MergeTree table over multiple parts — all worked correctly.

Stack trace (representative — all 5 hits look identical)

__pthread_kill_implementation
gsignal
__GI_abort
contrib/llvm-project/libcxxabi/src/abort_message.cpp:66
contrib/llvm-project/libcxxabi/src/cxa_virtual.cpp:16   ← __cxa_pure_virtual
src/Storages/MergeTree/BackgroundJobsAssignee.cpp:0: DB::BackgroundJobsAssignee::threadFunc()
src/Core/BackgroundSchedulePool.cpp:149: DB::BackgroundSchedulePoolTaskInfo::execute(...)
src/Core/BackgroundSchedulePool.cpp:492: DB::BackgroundSchedulePool::threadFunction()

CIDB cross-check (30 days)

PR Author Title Files in PR Date
#102343 Binnn-MX Re-add paimon storage engine Paimon docs/CI/integration 2026-04-28
#101027 alexey-milovidov Revert revert obfuscateQuery obfuscateQuery.cpp, parsers 2026-04-26
#104472 alexey-milovidov Enable count_distinct_optimization by default CountDistinctPass.cpp, settings 2026-05-11
#100272 alexey-milovidov h3 → h3o Rust rewrite rust_vendor, h3 cmake 2026-04-28

None of these PRs touch src/Storages/MergeTree/BackgroundJobsAssignee.cpp, src/Core/BackgroundSchedulePool.cpp, or the MergeTreeData::shutdown paths. 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() (concurrent start() / finish() mutating holder without the lock). That fix is good but does not cover the vtable-demotion scenario described here, since holder mutex synchronization does nothing to prevent the leaf vtable from going away while a pool thread is mid-virtual-dispatch through data. STID 3631-4165 remained chronic after that merge.

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 to CHANGELOG.md):

Fix a rare server abort during MergeTree family table destruction. The abort could occur when shutdown raised 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

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.462

…-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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (TASK.md §Phase 4 step 9)

Session: cron:clickhouse-ci-task-worker:20260511-031500

# Question Answer
a Deterministic repro? Partial. The bug is a destruction-time race: shutdown() must throw partway through cleanup AND a background task must be in flight at that exact moment. I cannot fire this on demand without intrusive fault injection. What IS isolated is the exact code path: ~StorageReplicatedMergeTree swallows a thrown shutdown(false) via try/catch, member destruction proceeds with holder still non-null, ~BackgroundJobsAssignee::finish() calls deactivate() which blocks on exec_mutex, and the in-flight threadFunc issues data.scheduleDataProcessingJob(*this) through the now-demoted MergeTreeData vtable where the method is pure virtual. CIDB confirms the same stack signature across 4 unrelated PRs in 30 days.
b Root cause explained? Yes. Pure-virtual call at MergeTreeData vtable level for scheduleDataProcessingJob, which is only overridden by the leaf storages (StorageMergeTree, StorageReplicatedMergeTree). Once the leaf destructor body returns, the dynamic type demotes to MergeTreeData, and any in-flight threadFunc calling that method via IBackgroundOperation & dispatches into __cxa_pure_virtual.
c Fix matches root cause? Yes. Adding a non-pure override MergeTreeData::scheduleDataProcessingJob returning false fills the missing slot in the MergeTreeData vtable. During the race window, the call now resolves to this safe default instead of __cxa_pure_virtual. threadFunc reads false → postpone() → no-op (holder moved out) → returns. Pool thread completes execute(), destructor's deactivate() unblocks, destruction proceeds.
d Test intent preserved / new tests added? N/A. No existing tests target this path. A deterministic regression test would require fault injection (forcing shutdown to throw at a specific point) which we don't have infrastructure for. CI stress tests have caught this STID 5 times in 30 days and will continue to surface regressions.
e Both directions demonstrated? Partial. I cannot demonstrate "fails without fix → passes with fix" on demand because the race is non-deterministic. What I did demonstrate: the fix compiles cleanly (full ninja clickhouse build), and basic MergeTree operations work end-to-end on a smoke test (create/insert/optimize/drop over multiple parts).
f Fix is general, not a narrow patch? Yes. The fix lives at the MergeTreeData level — the layer where the abstract IBackgroundOperation contract meets the concrete storage hierarchy. Any current or future class deriving from MergeTreeData benefits without needing to remember to call assignee.finish() defensively in its destructor. The companion scheduleDataMovingJob is already overridden by MergeTreeData (real implementation), so it does not need the same treatment for this bug.

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 flushAndPrepareForShutdown's cancellation calls, restarting thread shutdown timeouts). The current code already chose to handle it gracefully (swallow, log, proceed with destruction) rather than terminate. The defensive false override completes that graceful-degradation contract at the right architectural layer — it does not hide an upstream bug, it makes the existing graceful-degradation path actually safe. The alternative (force shutdown to never throw) would require eliminating exceptions from many independent subsystem teardowns, which is a much larger refactor and would itself need a defensive layer for new failure modes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @CurtizJ @alexey-milovidov — could you review this? It fixes a chronic __cxa_pure_virtual abort in BackgroundJobsAssignee::threadFunc during MergeTree destruction (STID 3631-4165, 4 unrelated PRs hit it in the last 30 days). Root cause: MergeTreeData doesn't override scheduleDataProcessingJob (only the leaf storages do), so when ~StorageReplicatedMergeTree swallows a thrown shutdown() via try/catch and member destruction proceeds with a background task still running, the vtable demotes to MergeTreeData mid-virtual-dispatch and the call lands on __cxa_pure_virtual. The fix is a defensive false-returning override at MergeTreeData level — dead code in normal operation, safe "no work to schedule" during the race. Related: PR #99366 fixed a different race in the same area; this one was not covered.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [242806a]

Summary: ✅


AI Review

Summary

This PR hardens MergeTree and ReplicatedMergeTree destruction against STID 3631-4165 by adding a concrete MergeTreeData::scheduleDataProcessingJob fallback and stopping all BackgroundJobsAssignee instances in the leaf destructors before derived member teardown. I did not find any unresolved correctness issues in the current diff; the prior bot findings about the replicated pre-demotion window and the plain StorageMergeTree streaming path are addressed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 17, 2026
…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]>
@groeneai

groeneai commented Jun 3, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 8d91a4b addresses the review on the earlier (pre-demotion) window. Pre-PR validation gate:

# Question Answer
a Deterministic repro? N/A for this hardening. The original abort (STID 3631-4165) was a destruction race observed across 4 unrelated Stress runs; it is not deterministically reproducible. This commit is a correctness fix requested in review, reasoned from the lifetime contract, not a new symptom.
b Root cause explained? Yes. background_*_assignee are MergeTreeData members. If StorageReplicatedMergeTree::shutdown throws before partialShutdown calls background_operations_assignee.finish, the destructor's try/catch swallows it and the assignees stay active while the derived RMT members (queue, cleanup_thread, ...) are destroyed. A pool thread can then dispatch into StorageReplicatedMergeTree::scheduleDataProcessingJob and touch members in teardown. The base-class fallback only covers the later demoted-vtable window.
c Fix matches root cause? Yes. The assignees are stopped at the end of ~StorageReplicatedMergeTree, after the try/catch and before derived member destruction begins, which is exactly the window identified.
d Test intent preserved? N/A. No test changed; the base-class fallback is retained as a last-resort guard. ~StorageMergeTree is unaffected (it does not catch, so a throwing shutdown reaches std::terminate from the noexcept destructor and never enters this window).
e Demonstrated in both directions? N/A for a non-deterministic race. Verified the ASan build links cleanly with the change.
f Fix is general, not a narrow patch? Yes. All three assignees (operations, moves, streaming) are stopped, not just the one in the reported stack. finish is idempotent so the normal path is unaffected. The symmetric leaf (StorageMergeTree) was checked and shown not to reach this window.

Session: cron:clickhouse-ci-task-worker:20260603-205209

Comment thread src/Storages/MergeTree/MergeTreeData.h Resolved
…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]>
@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI summary — HEAD 4c2a4a6593f4 (StorageMergeTree streaming-assignee sibling-path fix)

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

Failure Disposition
03444_distributed_hedged_requests_async_socket (Stateless tests (arm_asan_ubsan, azure, parallel)) Flaky azure test — 30d: PR #105249 (5), #105690 (3), this PR (1), 0 master. Tracked separately; not caused by this diff.
04033_tpc_ds_q01 (Stateless tests (arm_asan_ubsan, azure, parallel)) Flaky azure test — 30d: PR #104976 (1), this PR (1), 0 master. Unrelated to this diff.

CH Inc sync / PR aggregator FAILUREs are infra/meta, not code failures.

No PR-caused failures. Ready for re-review.


bool MergeTreeData::scheduleDataProcessingJob(BackgroundJobsAssignee & /*assignee*/)
{
/// Safety net for STID 3631-4165 (pure-virtual call abort in

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comments here is too long. Please keep it as short as possible or remove them.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shortened in 242806a:

  • MergeTreeData::scheduleDataProcessingJob (cpp): 41-line block → 2 lines.
  • MergeTreeData::scheduleDataProcessingJob (h): 12-line block → 2 lines.
  • ~StorageMergeTree / ~StorageReplicatedMergeTree assignee-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

@hanfei1991 hanfei1991 self-assigned this Jun 5, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

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.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline med (ms) PR med (ms) Change q-value Hint
⚠️ 4 not_sure 268 241 -10.1% <0.0001 PR only touches background-job scheduling and destructor cleanup; SELECT hot path untouched. -10% is variance.
⚠️ 15 not_sure 249 199 -20.1% <0.0001 Shutdown/assignee lifecycle change can't speed a read query; -20% unrelated to this PR.
⚠️ 28 not_sure 7038 6654 -5.5% <0.0001 Background merge-scheduling guard doesn't touch query execution; -5% is run-to-run variance.
⚠️ 34 not_sure 1519 1431 -5.8% <0.0001 Destructor cleanup ordering only; no effect on SELECT path. -6% is noise.

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
  • StressHouse run: 8da4e103-a9cf-4673-95a4-606b50d280b6
  • MIRAI run: 44d3e612-2011-43a7-84eb-ed862b05a9f7
  • PR check IDs:
    • clickbench_573667_1780750441
    • clickbench_573680_1780750441
    • clickbench_573686_1780750441
    • tpch_adapted_1_official_573691_1780750441
    • tpch_adapted_1_official_573699_1780750441
    • tpch_adapted_1_official_573706_1780750441

@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.00% 77.00% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

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

job test classification disposition
CH Inc sync (job-level) infra/aggregator meta-FAIL not code; same harness meta-fail observed across many other PRs today

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

pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Jun 6, 2026
…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]>
@hanfei1991
hanfei1991 enabled auto-merge June 6, 2026 22:50
@hanfei1991
hanfei1991 added this pull request to the merge queue Jun 6, 2026
Merged via the queue into ClickHouse:master with commit cc4a17e Jun 6, 2026
166 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 6, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

STID 3631-4165 recurred on release branch 26.3 - this fix is not on 26.3, 26.5 or 25.8

The __cxa_pure_virtual abort this PR fixed came back on 26.3 (Stress test (arm_asan),
commit 890331dfa56112c156e09e4f1dd7363749cdd2ea, version 26.3.17.64, 2026-07-22 16:41:29):
CI report.

clickhouse-server.err.log has a single Short fault info block, so this is the cause and
not fallout of an earlier fault:

(from thread 7060) Received signal 6 (internal)   Signal description: Aborted
(query_id: BgSchPool::be565c5d-2550-4d66-8ea2-d8a556874d7c) (query: )
7. contrib/llvm-project/libcxxabi/src/cxa_virtual.cpp:16:3
8. src/Storages/MergeTree/BackgroundJobsAssignee.cpp:0: DB::BackgroundJobsAssignee::threadFunc()
9. src/Core/BackgroundSchedulePool.cpp:149:12: DB::BackgroundSchedulePoolTaskInfo::execute(...)

Master is clean (0 hits since this merged; the only other hit in 120 days is a pre-fix
master run from 2026-05-14). The abort is still live on three active release branches,
by code state, not by CI presence:

branch cc4a17eaf4db ancestor MergeTreeData override leaf-dtor finish guard
master / 26.7 / 26.6 yes yes yes
26.5 no no no
26.3 no no no
25.8 no no (still pure at MergeTreeData.h:1248) no

On 26.3 and 26.5 the dtors are byte-identical to pre-fix master, the assignees are members
of the MergeTreeData base, and BackgroundJobsAssignee.h:39 still declares
scheduleDataProcessingJob pure, so the exact mechanism described in the PR body is
reachable there.

The backport label is necessary but not sufficient

Simulating what tests/ci/cherry_pick.py does
(git merge-tree --write-tree --merge-base=cc4a17eaf4db^1 origin/<branch> cc4a17eaf4db):

  • 26.3 and 26.5 merge cleanly (4 files, +24), so
    create_backport_from_resolved_tree would open the backport PRs directly.
  • 25.8 conflicts in src/Storages/MergeTree/MergeTreeData.h.
  • 26.6 and 26.7 produce an empty diff and are skipped automatically.

But the clean merges do not compile. This PR's dtor hunks call three assignees, and
background_streaming_assignee does not exist before 26.6 (it was wired on master
2026-05-14 by c41599a3fbe5, shipped in #105981). Materialising the simulated trees and
grepping them:

26.3 sim 8350ab0948747b: declarations of background_streaming_assignee: NONE
   uses: src/Storages/StorageMergeTree.cpp:316, src/Storages/StorageReplicatedMergeTree.cpp:5979
26.5 sim 3920818dd47982: declarations: NONE
   uses: src/Storages/StorageMergeTree.cpp:319, src/Storages/StorageReplicatedMergeTree.cpp:6051

Two references to an undeclared member. Type::Streaming is absent from 26.3/26.5
BackgroundJobsAssignee.{h,cpp} too, so the line has to be dropped rather than renamed.

What I am asking for

Could you apply v25.8-must-backport to this PR? Computed with the repo's own
select_backport_branches against the active releases, it expands to
[26.7, 26.6, 26.5, 26.3, 25.8], and 26.6/26.7 drop out as empty-diff, so it generates PRs
for exactly the three affected branches.

Two things will need a hand afterwards:

  1. the generated 26.3 and 26.5 backport PRs each need the one
    background_streaming_assignee.finish(); line removed from both leaf destructors before
    they build;
  2. 25.8 arrives as a cherry-pick PR needing manual resolution, and it needs a different
    patch anyway: there is no IBackgroundOperation there, the pure declaration sits on
    MergeTreeData itself (MergeTreeData.h:1248), and scheduleDataMovingJob carries no
    override.

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.

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

4 participants