Skip to content

Fix TTL merge slot leak when a selected merge is dropped before execution - #111925

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-ttl-merge-slot-leak
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:fix-ttl-merge-slot-leak

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

Related: #96130

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

Fixes background TTL merges stopping server-wide when a selected TTL merge is dropped before it starts executing (for example, when its table is dropped or detached while the merge is still queued in the background pool). Each such merge leaked a slot booked against max_number_of_merges_with_ttl_in_pool; once the counter reached the limit, no further TTL merges were scheduled until the server was restarted.

Description

A non-replicated TTL merge books a slot in the global counter for max_number_of_merges_with_ttl_in_pool at merge selection time (to close the assign-vs-execute race), and the booking is handed over to the MergeList entry only when the merge starts executing. If the selected merge is abandoned before that handover, the slot was leaked. Two abandonment paths were compensated; several were not, most notably the pending-queue removal that DROP/DETACH TABLE performs on a merge still waiting in the background pool. Each leak permanently decrements the number of TTL merges the server can run; once it reaches the per-table limit (default 2), merge_with_ttl_allowed is false for every default-limit table and background TTL merges stop server-wide until restart, while regular merges keep running.

The fix makes the booking a scope guard owned by the selected-merge entry, released automatically on any path that abandons the merge before its MergeList entry exists, and disarmed once that entry takes over the accounting. This replaces the two ad-hoc per-path compensations with a single mechanism covering every abandonment path. The same book-to-insert gap in the replicated path (MergeFromLogEntryTask) is guarded symmetrically. A debug/sanitizer assertion guards the counter against underflow.

The flaky test 04321_table_readonly_background_merges surfaced this: its writable control table relies on a background TTL merge, which never ran once the global counter had leaked to the limit earlier in the run (test 02293_part_log_has_merge_reason, the only test setting the limit to 100, was unaffected, which pinpointed the counter). Report where it was observed: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=0aa6569f3e6563c982227857effd5d2d19c97527&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29

Regression test 04641_ttl_merge_slot_leak_unscheduled reproduces the leak deterministically via the mt_skip_scheduling_merge_once failpoint (which drops a selected merge exactly once, the same accounting gap the table-drop hits) with the limit set to 1, and verifies that a later background TTL merge still runs after the dropped selection, and that a second TTL merge cycle runs afterwards (either a leaked or an over-released slot makes the second cycle time out, so the test discriminates both accounting errors in all build types).

…tion

A non-replicated TTL merge books a slot in the global counter for
`max_number_of_merges_with_ttl_in_pool` at selection time (to close the
assign-vs-execute race), and hands the booking over to the `MergeList` entry only
when the merge starts executing. If the selected merge is abandoned before that
handover, the slot was leaked. Only two abandonment paths were compensated;
others were not, most notably the pending-queue removal that `DROP`/`DETACH TABLE`
performs on a merge still waiting in the background pool, and a `STOP MERGES`
landing between selection and scheduling. Each leak permanently reduces the
number of TTL merges the server can run; once the counter reaches the per-table
limit (default 2), `merge_with_ttl_allowed` is false for every default-limit table
and background TTL merges stop server-wide until restart, while regular merges
keep running.

Make the booking a `scope_guard` owned by the selected-merge entry, released on
any path that abandons the merge before its `MergeList` entry exists and disarmed
once that entry takes over the accounting. The guard is armed before the slot is
booked, so the booking is the last statement of the block and cannot be stranded.
This replaces the two ad-hoc per-path compensations with a single mechanism
covering every abandonment path. Guard the same book-to-insert gap in the
replicated path (`MergeFromLogEntryTask`) symmetrically, and add a
debug/sanitizer assertion against counter underflow.

This surfaced as the flaky test `04321_table_readonly_background_merges`, whose
writable control table relies on a background TTL merge that never ran once the
global counter had leaked to the limit earlier in the run.

Add a regression test that reproduces the leak deterministically via the
`mt_skip_scheduling_merge_once` failpoint with the limit set to 1. A second TTL
merge cycle on a fresh table, run after `DROP`ping the first so its whole
background task and the slot accounting it carries are destroyed, also catches
the opposite accounting error (an over-released slot), so the test discriminates
both directions in all build types.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=0aa6569f3e6563c982227857effd5d2d19c97527&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29
PR where it was observed: ClickHouse#96130

Co-Authored-By: Claude Opus 4.8 <[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; 5 review rounds, 11 findings; the final round returned 0 findings, and the independent cold reviews found 0 blockers in every round).

# Sev Finding Verdict Evidence / action
1 ⚠️ Regression test would still pass if the guard handover to the selected entry were removed (over-release mutant), so it did not prove the handover mechanism (04641_ttl_merge_slot_leak_unscheduled.sh) AGREE — fixed @ 1bdcf06 Added an initial part-count assertion and a second TTL merge cycle: an over-released slot wraps the counter when the first merge's MergeList entry is destroyed, so the second cycle times out; a leaked slot fails the first cycle.
2 ⚠️ Replicated book-to-insert exception window (MergeFromLogEntryTask::prepare) lacks a focused injected-exception regression test DISAGREE The guarded window contains only getStorageID, Context::createCopy, makeQueryContextForMerge, setCurrentQueryId, and insert - allocation-only failure modes with no data-dependent throw path. Guard-on-unwind is a language guarantee; the identical arm/release pattern is regression-tested end-to-end on the plain path by 04641, and 01921_concurrent_ttl_and_normal_merges_zookeeper_long passed on the fixed debug build with the underflow assertion active (an erroneous post-insert release would abort there). Injecting an exception into that window would require a new production failpoint solely for the test - disproportionate for a strictly-protective 4-line guard.
3 💡 chassert(counter > 0) followed by a separate --counter is not atomic; two concurrent erroneous decrements at count 1 could both pass the assert and wrap AGREE — fixed @ 1bdcf06 Replaced with fetch_sub(1) and an assertion on the returned previous value at both decrement sites (kept as two statements: chassert compiles to an unevaluated operand in release builds, so the decrement must not live inside it).
4 💡 Changelog entry used past tense ("Fixed ...") where the guidelines require present tense AGREE — fixed Entry now opens with "Fixes background TTL merges stopping server-wide ...".
5 💡 Commit message omitted the CI report URL and the corresponding PR URL AGREE — fixed Amended into the (unpushed) commit message: the S3 report URL and the #96130 PR URL.
6 ⚠️ (round 2) Second test cycle could still pass with the handover removed in RELEASE builds: cycle 1's count() == 1 becomes visible at the merge commit, before the executor destroys the MergeList entry (where the erroneous counter wrap lands), so cycle 2's selection could sneak into that window and be admitted AGREE — fixed @ 1bdcf06 Real race: MergePlainMergeTreeTask::finish commits before task teardown, and ThreadFuzzer::maybeInjectSleep right after the commit widens the window. First fixed with a system.merges teardown barrier; round 3 showed that barrier is itself insufficient (see #8) and it was replaced by a DROP TABLE barrier. Also added a build-safe assertion that the ONCE failpoint was actually consumed by cycle 1 (it auto-disables on fire), so the test cannot silently rot into never exercising the dropped-selection path.
7 💡 (round 2) Added comments and commit message use bare literal names where repo guidelines require inline code AGREE — fixed @ 1bdcf06 Wrapped literal setting/class/method names (max_number_of_merges_with_ttl_in_pool, MergeList, MergePlainMergeTreeTask::prepare, onEntryDestroy, ...) in backticks across the four added comment sites, the test comment block, and the commit message.
8 ⚠️ (round 3) The system.merges barrier orders cycle 2 only after the MergeList entry's destruction, but in an over-release mutant the erroneous wrap fires later, at the selected-entry guard inside the same task's destruction (merge_mutate_entry is declared before merge_list_entry, so it is destroyed after), leaving a release-build window where cycle 2 is admitted before the wrap lands AGREE — fixed @ 1bdcf06 Verified against the member declaration order and the executor teardown path. Replaced the barrier: cycle 1's table is now DROPped between the cycles - DROP TABLE waits (removeTasksCorrespondingToStorage) until the task object is fully destroyed, including the guard, before returning - and cycle 2 runs on a second table against the same global counter. The counter has settled before cycle 2 begins, in every build type.
9 ⚠️ (round 3) Both booking sites increment the TTL counter before installing the cancellation guard; if constructing the guard's std::function threw, the slot would leak AGREE (hardening) — fixed @ 1bdcf06 The concrete leak is unreachable with the bundled libc++ (the one-reference-capture lambda takes the small-buffer placement-new branch, which cannot throw), but the order was swapped anyway at both sites - arm the guard first, then book (an atomic increment that cannot throw) - so the exception safety is locally provable without small-buffer-optimization reasoning.
10 💡 (round 3) Remaining bare SQL statement names (DROP/DETACH TABLE, STOP MERGES) in the test comment and commit message AGREE — fixed @ 1bdcf06 Backticked per repo guidelines.
11 💡 (round 4) Still more bare literal names in the test comments (MergeTree, session_timezone, today, count(), system.fail_points, removeTasksCorrespondingToStorage) AGREE — fixed @ 1bdcf06 Third raising of this class (rounds 2 and 3 each closed it only partially), so the whole class was swept rather than just the reported lines: also the literal setting value Manual, the failpoint type ONCE, and scope_guard in the commit message. Comment text only - no logic, no reference, and the binary's build id is unchanged.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260725-231900

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04641_ttl_merge_slot_leak_unscheduled fails 3/3 on the pristine build (~77s each, the poll times out because the leak is permanent). It drops one selected TTL merge via the mt_skip_scheduling_merge_once failpoint with max_number_of_merges_with_ttl_in_pool = 1.
b Root cause explained? Yes. A TTL merge books a global slot at selection time; the booking is handed to the MergeList entry only when the merge starts executing. Paths that abandon the merge before that handover (pending-queue removal on DROP/DETACH, STOP MERGES, exceptions, the failpoint) leaked the slot. Once the counter hit the per-table limit, merge_with_ttl_allowed stayed false and background TTL merges stopped server-wide.
c Fix matches root cause? Yes. The booking becomes a scope guard released on every pre-handover abandonment path and disarmed at handover, replacing two ad-hoc per-path compensations. Not a test-side budget bump (the starvation is permanent, so no budget helps) and not a symptom guard.
d Test intent preserved / new tests added? Yes. New regression test added; it checks two TTL merge cycles so it discriminates both accounting errors (a leak times the cycle out; an over-released slot wraps the global counter when the first cycle's background task is destroyed and admits no later TTL merge). Between the cycles it (1) asserts the ONCE failpoint was consumed by cycle 1 and (2) drops the first table, which waits for that task to be destroyed in full before cycle 2 starts on a fresh table, so cycle 2's selection reads the settled counter in every build type. The flaky test 04321_table_readonly_background_merges is not touched (separate PR off master).
e Both directions demonstrated? Yes. Leak direction (Build ID 23951c95...): FAIL 3/3. Over-release direction (deleting the handover line entry->ttl_merge_booking = std::move(ttl_merge_booking), Build ID 28e069f1...): the test fails on both cycle assertions and the debug server aborts on the underflow assertion (prev > 0 in MergeList::onEntryDestroy, reached from TaskRuntimeData::resetTask) when cycle 1's task is destroyed. The DROP TABLE barrier waits for exactly that destruction, so the kill is deterministic in all build types (in a release build the counter has already wrapped when cycle 2 is selected, so it times out). Fixed (Build ID 8fe5d589...): OK on single runs, OK 50/50 with the long tag temporarily removed, and OK 10/10 in one session.
f Fix is general across code paths? Yes. One RAII mechanism covers all abandonment paths; the replicated sibling (MergeFromLogEntryTask::prepare) is guarded symmetrically. Mutation entries never book a TTL slot and leave the guard disarmed. Neighbor tests (04321, 02293, 04207, 04492, 01070, 04009, 00933, 01921) all pass; no assertion or counter underflow in the server log.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for datatypes/type wrappers (this is merge-scheduling accounting, type-agnostic). The relevant matrix is the abandonment path (covered in f) and the pool-limit value; the test uses limit 1 so a single leak is decisive, and the bug affects any limit once the counter reaches it.
h Backward compatible? Yes. Internal accounting only. No settings, no SettingsChangesHistory.cpp, no serialization/protocol change, no behavior change for successfully executed merges.
i Invariants and contracts preserved? Yes. Invariant: every bookMergeWithTTL() is balanced by exactly one decrement, via the guard if the merge dies before its MergeList entry exists, otherwise via onEntryDestroy. The guard is armed before the slot is booked, so the booking is the last statement of the block and cannot be stranded even if the guard's own construction throws. Handover is exactly-once: the guard is disarmed (released without invoking) on the statement immediately after a successful insert. A chassert guards the counter against underflow. The guard captures the global MergeList (which outlives all tasks), and the member is declared last so it is destroyed first.

Session id: cron:clickhouse-review-slot-9:20260725-231900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @alesapin - could you review this? A TTL merge books a slot against max_number_of_merges_with_ttl_in_pool at selection time and only hands the booking to the MergeList entry when it starts executing, so every path that abandons the merge in between (notably the pending-queue removal on DROP/DETACH TABLE) leaked the slot permanently and eventually stopped background TTL merges server-wide; this replaces the two ad-hoc per-path compensations with a scope_guard owned by the selected-merge entry, and guards the same gap in MergeFromLogEntryTask.

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

clickhouse-gh Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1bdcf06]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug) FAIL
Logical error: Too large size (A) passed to allocator. It indicates an error. (STID: 1367-1ab3) FAIL cidb

AI Review

Summary

This PR fixes the TTL-merge slot accounting gap between merge selection and MergeList insertion for both plain and replicated MergeTree execution paths, and the new stateless regression test checks both the original leak and the opposite double-release failure mode. I did not find a remaining correctness issue in the current head.

Missing context / blind spots
  • ⚠️ The full CI matrix was still pending at review time; the initial PR report and available checks were green, but the remaining build configurations had not finished yet.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 35/37 (94.59%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1bdcf06

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
AST fuzzer (amd_debug) / Logical error: Too large size (A) passed to allocator (STID 1367-1ab3) fuzzer-mutated index_granularity near 2^63 with index_granularity_bytes=0 makes the non-adaptive per-mark row count the allocation limit in the debug-only validateColumnOfFixedSize read-back; 8 distinct PRs / 9 hits in 30d, 0 master #108650 (ours, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Not PR-caused: this PR changes TTL merge-slot bookkeeping (MergeList/MergeMutateSelectedEntry/StorageMergeTree) plus one new stateless test. The abort is in the MergeTree wide-part write-back validator reached from a fuzzed index_granularity, an independent path with a root cause already isolated and fixed in #108650.

Session id: cron:our-pr-ci-monitor:20260726-063000

alexey-milovidov added a commit that referenced this pull request Aug 7, 2026
Two more eligibility restrictions for `reattach_tables_before_query_execution`:

1. Skip `MergeTree` tables whose metadata carries any TTL. The internal
   `DETACH TABLE ... SYNC` cancels selected-but-not-started background TTL
   merges, and `MergePlainMergeTreeTask::cancel` does not return the
   `max_number_of_merges_with_ttl_in_pool` slot booked at selection time, so
   every such cancellation leaks a slot until server restart; two leaks disable
   TTL merges server-wide. This is the AI review blocker, and the cause of the
   recurring `04321_table_readonly_background_merges` and
   `04267_ttl_drop_merge_no_data_read` failures in this PR's CI. The skip
   stays until the underlying leak is fixed (see
   #111925).

2. Skip tables that have an Outdated part not covered by any Active part. The
   `DETACH`/`ATTACH` cycle reloads the parts from disk and resurrects such a
   part as Active — e.g. the empty covering part left by `ALTER TABLE ...
   DETACH PART` until the asynchronous cleanup deletes it. The same
   resurrection happens on a server restart in that window, so it is
   pre-existing behavior, but the hook must not turn it into a deterministic
   side effect of an unrelated query. This caused the
   `04653_mutation_rewrite_stale_part_column_type` failure (confirmed by the
   CI diagnosis as caused by the randomization): the resurrected empty part
   received the pending mutation, and the following `OPTIMIZE TABLE ... FINAL`
   became a silent no-op because the empty part lacks the projections of its
   neighbors ("Parts have different projection sets").

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=021fa9deea22167db809efe3dadc5af26126a327&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%202%2F3%29
PR: #96130

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov, your #121236 fixes the same leak as this PR and covers every path it guards (a queued merge discarded on DROP/DETACH TABLE, the early returns before scheduling, and the MergeFromLogEntryTask gap), with a cleaner design: the slot is owned by the selected merge, and bookMergeWithTTL/cancelMergeWithTTL are gone. This PR now conflicts with master. Should I close it in favor of #121236, or resolve the conflicts here?

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

#121236 is merged, and it fixes this leak on master (the TTL slot is now owned by the selected merge, and bookMergeWithTTL is gone), so this PR is superseded. I am not going to resolve the conflicts here; it can be closed.

This branch has not been deployed

No deployments
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-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants