Skip to content

Release the tasks left in a MergeTree background executor's queue on shutdown - #113653

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-executor-shutdown-drains-pending-tasks
Sep 22, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-executor-shutdown-drains-pending-tasks

Conversation

@groeneai

@groeneai groeneai commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

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 shutdown stall where a background merge or mutation left in a MergeTree background executor's queue kept holding its table lock, so any table lock taken later during shutdown waited for the full lock_acquire_timeout (120 s by default) and then failed with DEADLOCK_AVOIDED. Observed as system.session_log losing a batch of rows when its schema is rotated on upgrade.

Description

MergeTreeBackgroundExecutor::wait() flipped the executor into shutdown mode and waited for the running jobs, but never touched the pending queue. threadFunction breaks out of its loop before popping once shutdown is set, so a task that routine had re-pushed for another step (MergePlainMergeTreeTask is multi-step) was neither resumed nor cancelled. Such a task keeps its TableLockHolder, a table share lock taken with NO_QUERY, for as long as the task object lives, i.e. until the storage's own shutdown reaches removeTasksCorrespondingToStorage.

Any exclusive table lock taken between those two points therefore waits the full timeout. On the upgrade path this hits system.session_log: written only on login/logout, its first flush of the run lands after Shutting down storages, so its obsolete-structure RENAME runs inside the window. prepareTable then fails, and flushImpl still confirms the batch, so the rows are dropped. In the reference occurrence the lock was released 2 s after the rename had timed out.

The fix drains pending in wait(), cancelling and destroying each remaining task. The drain runs after pool->wait(), which is the point from which no worker can push to pending any more (--scheduled_jobs happens only after a job function returns, and each threadFunction loop is one job), and via SCOPE_EXIT so a rethrown worker exception cannot skip it. No task that would otherwise have completed is cancelled, because the workers had already stopped popping. All four executors and every storage using them are covered, not just system logs.

Validated with a new gtest in the existing gtest_executor.cpp: it fails on unmodified wait() and passes with the fix. Four mutants each redden only that test: removing the drain, draining without cancelling, draining only before pool->wait(), and draining a single task instead of the whole queue.

Related: #112951


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

Version info

  • Merged into: 26.10.1.464-master (included in 26.10 and later)

…shutdown

`MergeTreeBackgroundExecutor::wait()` set `shutdown = true` and waited for the
running jobs, but never touched the `pending` queue. `threadFunction` breaks out
of its loop before popping once `shutdown` is set, so a task that `routine` had
re-pushed for another step was neither resumed nor cancelled.

`MergePlainMergeTreeTask` is multi-step, and it holds a `TableLockHolder` (a
table share lock taken with `NO_QUERY`) for as long as the task object lives.
An abandoned task therefore keeps that lock until the storage's own shutdown
reaches `removeTasksCorrespondingToStorage`, and any exclusive table lock taken
in between waits the full `lock_acquire_timeout` and then fails with
`DEADLOCK_AVOIDED`.

On the upgrade path this is what breaks the rotation of `system.session_log`.
Because that log is written only on login and logout, its first flush of the run
lands after `Shutting down storages`, so its obsolete-structure `RENAME` runs
inside the window: `prepareTable` then fails once the lock acquisition times out
(60 s in the Upgrade check, which installs `tests/config/users.d/limits.yaml`;
the default is 120 s), and `flushImpl` still confirms the batch, so the rows are
dropped. It became reachable for every
upgrade from a released build when `ArrowFlight` was added to the `interface`
enumeration. In the occurrence this was diagnosed from, the lock was released
2 s after the rename had already timed out.

Drain `pending` in `wait()`, cancelling and destroying each remaining task.
The drain runs after `pool->wait()`, which is the point from which no worker can
push to `pending` any more: `--scheduled_jobs` happens only after a job function
returns, and each `threadFunction` loop is one pool job. Draining only before
`pool->wait()` is measurably insufficient, because a worker still mid-step
re-pushes afterwards. It is invoked through `SCOPE_EXIT` so that a worker
exception rethrown by `ThreadPool::wait()` cannot skip it.

No task that would otherwise have completed is cancelled, since the workers had
already stopped popping. This covers all four executors and every storage that
uses them, not only system logs.

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

groeneai commented Aug 6, 2026

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

Two review rounds by a model that did not write the change, each followed by an independent
second-model pass over the resulting code. Round 1 bounced three items back for implementation;
this round found no defect in the code and one false claim in the PR description, which I corrected.
Verdicts below, including the ones I disagreed with and why.

Finding Verdict
⚠️ The description credited the mutation test with settling the drain's placement, and quoted a stale count. The parenthetical read "that last one 20/20, which is what settles the placement". 20/20 was measured on round 1's fixture; the shipped fixture measures 30/30. More importantly, the mutant corroborates the placement, it does not establish it — that follows from ThreadPool: --scheduled_jobs happens only after a job function returns, ThreadPool::wait() waits for scheduled_jobs == 0, and each threadFunction loop is one job, so after pool->wait() no worker can push to pending. AGREE — parenthetical deleted rather than renumbered. The description already carries the source argument.
❌ "The regression test still does not deterministically prove that draining occurs after pool->wait()", on the grounds that the main thread may reach wait() "before the worker pushes back to pending", letting a drain-before-pool->wait() mutant pass. DISAGREE — the necessary step is inverted. In that exact interleaving pending is empty when the pre-drain runs, so it cancels nothing; the worker then re-pushes (restart_task is unconditional — it consults only is_currently_deleting, never shutdown), breaks out of its loop, and the mutant, having no post-wait() drain, leaves the task in pending alive and uncancelled: both assertions fail. For the mutant to survive, the push must land strictly between shutdown = true and the pre-drain — the opposite of the premise, and a window of one mutex handoff against a 1 ms step cycle. Measured 90/90 across three configurations, including the same mutant on the previous fixture under two pinned CPUs against 16 spinning hogs, which is the descheduling the argument requires.
💡 The drain runs through plain SCOPE_EXIT, so it also executes while unwinding a pool->wait() rethrow, and it allocates. Noted, not blocking. Reaching it needs compound OOM (an escaping worker exception and an allocation failure inside the drain), the process is already exiting, and src/ convention is 251 plain SCOPE_EXIT against 30 SCOPE_EXIT_SAFE. Recorded as distinct from round 1's noexcept-based objection, which concerned cancel() and does not cover this.

Residual, stated rather than papered over: the arm that exercises the drain's placement is
empirical (90/90), not a proof. A deterministic version is not constructible from a test: only
wait() sets shutdown, and it then blocks until every worker's job has returned, so a worker held
until shutdown would wait on a thread waiting on it. The placement rests on the ThreadPool
argument above; the description no longer claims the mutant settles it.

Round 1's findings, for completeness: the description quoted the Upgrade check's 60 s
lock_acquire_timeout as the default (it is 120 s; the 60 comes from
tests/config/users.d/limits.yaml) — corrected in both the source comment and the description; the
mutation arm above was put into a fix plan and implemented exactly, and its prescribed fixture change
measured behaviourally neutral with a negative control, which is reported as such. Two nits were
disagreed with evidence.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter=Executor.ShutdownReleasesPendingTasks fails in a few milliseconds on unmodified wait(), in 100% of runs. Not a low-rate flake.
b Root cause explained? wait() set shutdown = true (MergeTreeBackgroundExecutor.cpp:105) and awaited running jobs, never touching pending. threadFunction breaks on shutdown before popping (:440), so a task routine re-pushed for another step is neither resumed nor cancelled, and keeps its TableLockHolder (MergePlainMergeTreeTask.h:76, taken with NO_QUERY at StorageMergeTree.cpp:1750) until the storage's own shutdown reaches removeTasksCorrespondingToStorage. For system that is delayed past the log flush (Context.cpp:1008 vs DatabaseCatalog.cpp:345), so the session_log rotation's lockExclusively (DatabaseOnDisk.cpp:481 -> IStorage.cpp:117) waits the full timeout and throws DEADLOCK_AVOIDED.
c Fix matches root cause? Yes: it releases the leaked tasks at the site that leaks them. Not a band-aid. The four alternatives (allowlist the log line in upgrade_runner.sh, rotate the log at startup, a test-only config, reorder Context::shutdown) all leave the leak in place, and the last would trade the stall for the SIGBUS that ordering exists to prevent.
d Test intent preserved / new tests added? No existing test weakened: all five pre-existing Executor tests are untouched and green. One new focused gtest added to the existing gtest_executor.cpp (no CMake change needed), sized to the fix, with no no-random-* tag.
e Both directions demonstrated? Yes, same command on two Build-ID-verified binaries. Pre-fix b644da47fcd72fb3 (pristine wait(), new test kept) FAILS on both assertions; post-fix 3f93f686bcce3508 PASSES, 50/50.
f Fix is general across code paths? Fixed in wait(), so all three queue policies (RoundRobinRuntimeQueue, PriorityRuntimeQueue, DynamicRuntimeQueue, all three explicitly instantiated at the bottom of the same file), all four executors (Context.cpp:1008-1011) and the destructor are covered by construction. git grep "shutdown = true" over src/Storages/MergeTree/ returns exactly 1 hit, the site fixed, so no sibling executor has the same leak. StorageReplicatedMergeTree uses the same executors.
g Fix generalizes across inputs (params/datatypes/wrappers)? Not a data-typed change; the input is "a task in pending at shutdown". Shapes covered: empty queue (five pre-existing tests call wait() on an empty or drained queue), one queued multi-step task (new test), many tasks with concurrent removers (RemoveTasks, RemoveTasksStress, 30 repeats). pending.empty()/pop() are the queues' own primitives, so an empty queue is a no-op loop.
h Backward compatible? (maintainer-approved exception only) Yes, trivially: no setting, no format, no protocol, no serialization change, so no SettingsChangesHistory.cpp entry. The behaviour change is strictly "release resources that were being leaked": no task that would otherwise have completed is cancelled, because the workers had already stopped popping before the drain can observe anything.
i Invariants and contracts preserved? The queue invariant (a task is in exactly one of pending/active) holds: the drain pops only from pending, after every worker has exited, so it cannot race active. pending is touched only under mutex; cancel() and destruction run outside it, matching the two-phase shape removeTasksCorrespondingToStorage already uses. No double-cancel: TaskRuntimeData::cancel() and resetTask() both guard on if (task), and after wait() a later removeTasksCorrespondingToStorage finds both queues empty. is_done is untouched by the drain. The error path is covered by SCOPE_EXIT, since ThreadPool::wait() can rethrow a worker exception.

Session id: cron:clickhouse-impl-slot-45:20260806-092200

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @azat, could you review this? MergeTreeBackgroundExecutor::wait() never drained its pending queue, so a multi-step merge re-pushed by routine was neither resumed nor cancelled and kept its TableLockHolder until the storage's own shutdown, making any exclusive table lock taken in between wait the full lock_acquire_timeout and fail with DEADLOCK_AVOIDED.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2120202]

Summary: ✅


AI Review

Summary

This PR changes MergeTreeBackgroundExecutor::wait() so that, after worker jobs have fully exited, it drains and cancels any tasks still left in pending instead of letting them survive until executor destruction. I checked the current branch-tip code, the touched tests, the shutdown call sites, and the relevant ThreadPool behavior; I did not find an unresolved correctness, compatibility, or evidence gap that warrants changes.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 2120202.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 51/53 (96.23%) · 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 6, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2a033ad

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
Build (arm_release) / Post Hooks non-gating build-profile telemetry upload rejected by the shared CI logs cluster; all 8 retries exhausted (WARNING: LogCluster query failed with code 500 x8, then ERROR: Failed to query LogCluster). The Build (arm_release) check-run itself is green, and this PR touches no build-profile or telemetry code a fix task owns this (investigating at full effort - fixing-PR link to follow on this PR); root cause posted at #113408

Merged PR #113409, which added that retry, is deliberately not linked as the owner: the eight
warning lines prove its retry loop is present on this build and was exhausted anyway, so it does not
fix this failure. The remaining variable measured out to be server-side on the writer endpoint rather
than in the repo, and that write-up is on #113408.

Session id: cron:our-pr-ci-monitor:20260806-213000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
groeneai and others added 2 commits August 30, 2026 11:49
Master factored `requestShutdown` out of `wait` in 3e1b29b, which touched
the same lines as this branch. `wait` now calls it and the `pending` drain still
runs from a `SCOPE_EXIT` around `pool->wait()`, the point past which no worker
can push there any more. `requestShutdown` alone does not release the pending
tasks, so the leak this branch fixes is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
The test scheduled a single task, so replacing the drain's loop with one pop
would have left tasks alive and still passed. Schedule three cycling tasks and
assert that each of them is cancelled and destroyed.

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

clickhouse-gh Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 013e209

Every failure below has an owner: a fixing PR (ours 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
Upgrade check (amd_release) / Cannot start clickhouse-server not PR-caused, CI-harness defect on master: tests/config/install.sh symlinks silk.xml with no version gate, so the previous-release server rejects enable_silk_runtime with Code: 137 ... UNKNOWN_ELEMENT_IN_CONFIG and never starts. Onset is a cliff at 2026-08-30 13:48:57Z (65 rows / 64 distinct PRs in 7 days, 0 true-master rows, still firing at 19:06Z) #117172 (ours, open)
Upgrade check (amd_release) / Check failed the same job's second abort row (Check failed with exit code 1), same task_url, same event as the line above #117172 (ours, open)

No other check failed at this head, and none of the failures is PR-caused: the diff here touches
the MergeTree background executor and its gtest, not tests/config/.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113653&sha=013e20960579d88a1ec700aeff97d888aafb361d&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29

Session id: cron:our-pr-ci-monitor:20260830-190000

@clickhouse-gh clickhouse-gh Bot added the comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. label Sep 4, 2026

@alexey-milovidov alexey-milovidov left a comment

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 changes are good, except the unit test. We prefer not to use unit tests. But still acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Sep 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 22, 2026
Merged via the queue into ClickHouse:master with commit d59f7af Sep 22, 2026
175 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 Sep 22, 2026
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-background-ops Background pools/scheduling for merges, cleanup, maintenance. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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