Skip to content

Do not postpone a fully expired TTL drop because of source parts size - #119983

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:ttl-drop-not-postponed-by-source-size
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:ttl-drop-not-postponed-by-source-size

Conversation

@groeneai

@groeneai groeneai commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #119775
Related: #115723
Related: #112454

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 ReplicatedMergeTree TTL processing stalling indefinitely when a TTL merge that drops fully expired parts was larger than half the free disk space. Such a merge deletes every row and therefore needs no room for its source parts, but it was postponed on their size, and the postponed entry kept occupying the only max_replicated_merges_with_ttl_in_queue slot, so no TTL merge ran and no space was ever freed. It is now admitted when the table's only TTL is an unconditional rows TTL. Closes #119775.

Description

On ReplicatedMergeTree a TTL merge that drops fully expired parts is selected with no size limit, then refused by the source-parts-size check in shouldExecuteLogEntry, whose threshold is min(max_bytes_to_merge_at_max_space_in_pool, unreserved_free_space / 2). The refusal is self-sustaining: the postponed entry still counts towards max_replicated_merges_with_ttl_in_queue (default 1), so no further TTL merge is assigned, no space is freed, and the threshold never rises. The report has a 92.66 GiB expired part against a 65.31 GiB maximum, stuck three days.

Such a merge deletes every row, so its result is empty and its source bytes are not a space requirement: estimateNeededDiskSpace already values a fully expired range at 0, but it runs only after the queue has admitted the entry. This exempts the entry from the size check inside the existing TTL branch, leaving every other refusal there in force.

The exemption also requires the table's only TTL to be an unconditional rows TTL. MergeType::TTLDrop alone is not enough: a part expired by a GROUP BY, WHERE or column TTL is tagged TTLDrop too, and that merge rewrites the rows it keeps. On a build carrying only the type check, such a merge was admitted and merged 36000 rows while holding a 1 MiB reservation. hasOnlyRowsTTL() is the same predicate MergeTask uses for its own empty-result short-circuit.

New integration test test_ttl_drop_not_postponed_by_size measures the threshold before asserting. Case A fails on master with the reported postpone reason; Case B is a row-retaining TTLDrop that must stay postponed, and it fails on a build carrying only the type check.

TTLDrop exists in released 26.3 through 26.8, and not in 25.8.

#115723 touches this block with a different spelling while adding a MergeTree setting. This is a standalone bug fix for released branches; if that approach is preferred, close this one.


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

Version info

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

A whole-part TTL drop is selected with no size limit (tryChooseTTLMerge replaces the
caller's constraints with numeric_limits<size_t>::max() and tags the choice
MergeType::TTLDrop), but shouldExecuteLogEntry then refuses it whenever the source parts
exceed min(max_bytes_to_merge_at_max_space_in_pool, unreserved_free_space / 2).

For a merge that deletes every row, that comparison measures the wrong quantity: the
result part is empty, and estimateNeededDiskSpace already values a fully expired range at
0 bytes. It only runs after the queue has admitted the entry, so it never gets the chance.

The refusal is self-sustaining rather than a delay. countMergesAndPartMutations() counts
queue entries without filtering postponed ones, and isTTLMergeType covers TTLDrop, so the
refused entry consumes the whole max_replicated_merges_with_ttl_in_queue budget
(default 1). merge_with_ttl_allowed goes false, no further TTL merge is assigned, no space
is freed, and the threshold the entry is refused against never rises. The report has a
92.66 GiB expired part against a 65.31 GiB maximum, stuck three days until a manual
DROP PARTITION.

Exempt exactly that class from the size check, inside the existing TTL branch so that
every other refusal there keeps its force.

The exemption is not keyed on the merge type alone. part_max_ttl is the maximum over a
part's non-finished columns_ttl, table_ttl, group_by_ttl and rows_where_ttl, so a part
expired by a GROUP BY, WHERE or column TTL is selected and tagged TTLDrop as well, while
its merge retains rows and rewrites them. Measured with the type check alone, such a merge
was admitted and merged 36000 rows while holding the 1 MiB reservation floor that the
expired-part skip leaves behind. hasOnlyRowsTTL() is the predicate MergeTask uses to
decide its own empty-result short-circuit, so admission and execution now ask the same
question of the same metadata.

merge_type already travels in the log entry, so no format change is needed, and an entry
written by a leader older than TTLDrop carries TTLDelete and is correctly not exempted.

Closes ClickHouse#119775.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 14, 2026
@groeneai

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

Pre-publication review: my own cold pass over the resulting code, plus an independent-model gate
(engine: codex; 2 findings). No fix round was required. 6 findings adjudicated, 4 shown below;
the 2 omitted are a debug-build-only metadata copy cost that an adjacent pre-existing call in the
same function already pays, and a duplicate of row 1.

# Sev Finding Verdict Evidence / action
1 ❌ TTLDrop plus current hasOnlyRowsTTL() does not prove an empty result: a stale part_max_ttl left by ALTER ... MODIFY TTL ... SETTINGS materialize_ttl_after_modify = 0 still selects TTLDrop, and MergeTask then writes an empty part although the current TTL keeps the rows DISAGREE The defect is real, but this hunk is not what makes it reachable. I reproduced exactly this row loss on plain MergeTree, with no replication and no disk constraint, so the changed code path was never involved: two arms differing only in hasOnlyRowsTTL(), identical data and identical current TTL, gave 0 rows on the short-circuit arm against 200 on the general path (both should be 200). Plain MergeTree has no execution-time source-size gate at all (MergePlainMergeTreeTask carries no size logic; of the three getMaxSourcePartsBytesForMerge call sites two are selection and ReplicatedMergeTreeQueue.cpp:1841 is the only execution one), and on ReplicatedMergeTree the gate is already bypassed at :1852 on a roomy disk. The proposed guard would also not work: re-checking part_max_ttl at admission re-reads the same stale persisted value, and the loss happens in MergeTask after admission either way. See the note below
2 ❌ merge_type is persisted, so a whole-part drop queued by a pre-TTLDrop leader stays TTLDelete, remains size-gated, and still occupies the TTL queue slot DISAGREE Conceded as a fact, refuted as a blocker on two counts. The only way to cover such entries is to exempt TTLDelete, which would also exempt genuine row-delete merges that rewrite survivors and do need the headroom; that is what @ PedroTadim ruled out on the issue, and case B of the new test is the standing proof. The caveat is also narrower than stated: once any 26.3+ leader assigns a TTL drop it is tagged MergeType::TTLDrop (MergeSelectorApplier.cpp:84), so upgrading does unstick newly assigned entries, and only an entry created by a pre-26.3 leader stays stuck. I have stated that caveat on the issue rather than dropping it
3 💡 Nothing reddens if only the entry.merge_type == MergeType::TTLDrop conjunct is dropped, so that arm of the diff is uncovered DISAGREE Correct, and not constructible here. The conjunct's only real job is excluding TTLDelete (TTLRecompress requires a recompression TTL, which contradicts hasOnlyRowsTTL()). TTLRowDeleteMergeSelector selects under the caller's bounded constraints (MergeSelectorApplier.cpp:88), unlike the drop selector's unbounded ones, against the same min(pool, unreserved/2) used at execution, so producing an over-threshold TTLDelete entry needs free space to shrink between assignment and execution. That is reachable only by fabricating parts, which functional tests must not do, or by a contrived mid-test disk shrink
4 💡 The PR body claimed admission and execution ask the same question "of the same metadata"; they use the same predicate but read it twice, and a concurrent ALTER MODIFY TTL can land in between AGREE, corrected Reworded before publication to claim only what holds: hasOnlyRowsTTL() is the same predicate MergeTask uses. The in-diff comment never made the broader claim

One thing I want a maintainer to settle rather than decide myself, since row 1 is a real p0-severity
defect I am declining to fix here: the underlying problem is that estimateNeededDiskSpace values any
part with an expired part_max_ttl at zero, so a TTLDrop-tagged merge that retains rows is
under-reserved regardless of admission. I believe that belongs in the reservation and
TTL-re-evaluation layer, tracked as issue #117990, not in queue admission, and I have not treated
that in-flight work as discharging it. If you would rather this PR carried a guard, say so and I
will add one.

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

Session id: cron:clickhouse-review-slot-11:20260914-131900

@clickhouse-gh clickhouse-gh Bot closed this Sep 14, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bfda1f2]

Summary: ✅


AI Review

Summary

This PR exempts a subset of replicated TTLDrop merges from the execution-time source-size gate and adds an integration test for the stuck-queue case it is targeting. I do not think it is safe to merge as written: the new exemption assumes hasOnlyRowsTTL() proves the queued merge still drops all rows, but that is false for pre-ALTER parts with stale TTL metadata, so the patch can turn a previously postponed entry into data loss.

Findings

❌ Blockers

  • [src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp:1876] The new ignore_max_size exemption keys only off the current table metadata, but TTLDrop is selected from stored part_max_ttl. After ALTER TABLE ... MODIFY TTL ... SETTINGS materialize_ttl_after_modify = 0, pre-ALTER parts can keep stale part_max_ttl and a queued TTLDrop even though the current rows TTL no longer expires them. This patch now admits that entry on a tight disk, and MergeTask later uses the same hasOnlyRowsTTL() check to short-circuit it to an empty part, so the change widens an existing data-loss path instead of only unsticking safe merges.
    Suggested fix: revalidate that all source parts are still empty under the current TTL before bypassing the size gate, or at minimum refuse the exemption when any source part's metadata version predates the current table metadata and cover that path with a regression test.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit bfda1f2.

Metric Baseline Current Δ
Lines 89.10% 89.00% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code

Full report · Diff report

/// merge rewrites them, so it does need room for what its source parts hold.
if (entry.merge_type == MergeType::TTLDrop)
{
const auto metadata_snapshot = storage.getInMemoryMetadataPtr(storage.getContext(), false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This relaxes the source-size gate based only on the current table metadata, but that is not enough to prove a queued TTLDrop still deletes every row. After ALTER TABLE ... MODIFY TTL ... SETTINGS materialize_ttl_after_modify = 0, pre-ALTER parts can keep their old ttl_infos.part_max_ttl, so the selector can leave a TTLDrop entry for parts whose rows are no longer expired under the new rows TTL. With this change that entry is now admitted on a tight disk, and MergeTask later hits the same hasOnlyRowsTTL() check in src/Storages/MergeTree/MergeTask.cpp and short-circuits to an empty part.

Before this patch the size gate was the only thing preventing that execution in the low-space case, so this widens an existing data-loss path rather than only unsticking safe merges. Can we revalidate emptiness against the current TTL before setting ignore_max_size here, or at least refuse the exemption when any source part predates the current table metadata version (similar to the MUTATE_PART guard below)?

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.

This is a data-loss claim, so I measured it on master instead of arguing it.

Conceded, narrowly: inside the low-space window this patch admits an entry that master postpones.

Refuted as a reason to gate the exemption: the size gate is not what prevents the empty part. Two binaries from one tree, differing only in this hunk, single-node ReplicatedMergeTree, default disk with 3.26 TiB free, so the refusal at :1889 is unreachable whatever ignore_max_size holds:

CREATE TABLE stale_ttl (id UInt64, event_time DateTime)
ENGINE = ReplicatedMergeTree('/clickhouse/tables/stale_ttl', 'r1') ORDER BY id
TTL event_time + INTERVAL 1 DAY SETTINGS merge_with_ttl_timeout = 0;
SYSTEM STOP TTL MERGES stale_ttl;
INSERT INTO stale_ttl SELECT number, now() - INTERVAL 10 DAY FROM numbers(100);
INSERT INTO stale_ttl SELECT number + 100, now() - INTERVAL 10 DAY FROM numbers(100);
ALTER TABLE stale_ttl MODIFY TTL event_time + INTERVAL 1000 DAY
    SETTINGS materialize_ttl_after_modify = 0;
SYSTEM START TTL MERGES stale_ttl;

Identical on base eac62b32 (this file reverted to origin/master) and on patched 1c970486:

delete_ttl_info_max                   2026-09-05 (stale)   current TTL: event_time + toIntervalDay(1000)
server log                            TTLDrop merge: skipping data pipeline, all 2 source parts are fully expired
                                      Merge sorted 0 rows
"because source parts size" refusals  0
rows after the merge                  0        (200 expected under the current TTL)

Unpatched master admits and executes that entry in the default configuration and loses the rows: ignore_max_size is already true at :1852 whenever the pool is roomy, and 4 KiB of source parts is under any maximum regardless. A user OPTIMIZE TABLE ... FINAL loses them too, on a merge that read all 200 rows and so never touched the drop short-circuit. No queue-side condition is in that path at all.

Hence neither suggested guard prevents it. On the second one, :1950 is not that analogy: it refuses when the part is ahead of the table (part_metadata_version > table_metadata_version, an ALTER_METADATA this replica has not applied yet). The reverse direction is a proxy for emptiness rather than a check of it, and in the run above both parts sit at metadata_version 0 against the replica's 1 after a single MODIFY TTL, so keying the exemption on it would drop the fix for any table that has ever been altered while the rows still go. Revalidating emptiness at admission is not constructible either: the only bound available without opening the parts is part_max_ttl, which is the stale value.

The sink is one level below both this gate and the short-circuit, in TTLTransform, which decides from the persisted bound before evaluating the current expression:

/// Skip all data if table ttl is expired for part
if (algorithm->isMaxTTLExpired() && !rows_ttl.where_expression_ast)
    all_data_dropped = true;

src/Processors/Transforms/TTLTransform.cpp:76, with isMaxTTLExpired() reading data_part->ttl_infos. Fixing it there closes the roomy-disk case as well. It is the same trust-the-persisted-ttl_infos defect as #117990, and I am not treating that issue as discharging it.

For a maintainer reading this, the trade-off is the whole of it, and I will take the call either way: I would rather not add a refusal that narrows nothing on a roomy disk and costs the reported fix on any altered table. If you would rather this PR closed the low-space window regardless, say so and I will add the metadata-version refusal here.

@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Sep 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bfda1f297 with master 111e9f09f (stripped binary size, per-symbol sizes and ThinLTO time; 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

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

Job report

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

Perfect.

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

Perfect.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 652b650 Sep 19, 2026
176 of 348 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 Sep 19, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Sep 26, 2026
Every reservation is clamped up to 1 MiB, so any merge started with less than that above min_unreserved_disk_space_for_merge takes part of it, and the replicated queue runs rows-only TTL drops at a zero limit (master's ClickHouse#119983). Gating drops on the floor would postpone the merge that frees the space and hold the TTL queue slot. Also stop claiming that rewriting TTL merges are postponed: plain MergeTree selects a whole-part drop under a GROUP BY, WHERE or column TTL regardless of size.

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

Copy link
Copy Markdown
Contributor

@alexey-milovidov, could you please consider adding the pr-must-backport label to this PR?

alexey-milovidov pushed a commit to zeev1079/ClickHouse that referenced this pull request Oct 11, 2026
A part attached from a table with a different TTL, or written before
`MODIFY COLUMN ... REMOVE TTL` + `MODIFY TTL ... SETTINGS
materialize_ttl_after_modify = 0`, keeps an expired `ttl.txt` entry of a TTL
family the table no longer has (column, DELETE WHERE, GROUP BY) and has no
rows TTL info at all (`table_ttl = {0, 0}`). `TTLPartDropMergeSelector` tags
merges from `part_max_ttl`, the max over every family, so such parts get a
`TTLDrop` merge, and the short-circuit added in ClickHouse#105859 read `TTLDrop &&
hasOnlyRowsTTL()` as proof that every row expired and wrote an empty part
without reading anything.

The short-circuit now also requires every source part to have a calculated
rows TTL (`table_ttl.min != 0`, the rule of `checkAllTTLCalculated`) that has
expired at the time of the merge, which is exactly when the pipeline itself
would drop all rows. The `ReplicatedMergeTreeQueue` exemption from the source
parts size check (ClickHouse#119983) uses the same helper at `entry.create_time`, the
time the merge runs with, so a TTLDrop entry that rewrites rows keeps the
size check.

A part without rows TTL info also added nothing to the aggregated rows TTL
bound that `TTLTransform` and `TTLDeleteFilterTransform` use to decide "all
rows expired", so merging it with a fully expired part (the same routes, or
any OPTIMIZE FINAL) dropped its rows as well. The merge already forces the
TTL calculation for such a part; the aggregated bound is now reset so that the
per-row evaluation decides.

Closes ClickHouse#121124

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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.

ReplicatedMergeTree: fully expired TTL drop still postponed by source size after #86439, occupying the only TTL queue slot

4 participants