Skip to content

Respect free disk space in TTL drop merges that keep rows - #122391

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:row-retaining-ttl-drop-needs-space
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:row-retaining-ttl-drop-needs-space

Conversation

@groeneai

@groeneai groeneai commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122280
Related: #119983
Related: #122481
Related: #123068

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 TTL merges of fully expired parts that keep rows (a GROUP BY, WHERE or column TTL) ignoring free disk space. Such a merge was started with a 1 MiB reservation even when the rows it writes back did not fit, failed with No space left on device and was retried about once per second, so the TTL was never applied and other writes to that disk could fail. These merges now obey the same size limits and space reservation as other merges. Closes #122280.

Description

On 26.8.10.6 and 26.9.1.1629, a MergeTree table with TTL ... GROUP BY whose fully expired parts exceed their disk's free space starts a TTLDropMerge with a 1 MiB reservation, fails with errno: 28 and restarts it about once per second, also with default settings, so the TTL is never applied. Other inserts to that disk can fail (5 of 150 on master).

Such a part is merged as a whole-part drop, and two safeguards assume it writes nothing: the drop selector ignores the merge size limits (half the unreserved space, pool pressure, max_bytes_to_merge_at_max_space_in_pool) and estimateNeededDiskSpace skips fully expired parts. But only a DELETE TTL expired for every row empties a part; a GROUP BY, WHERE or column TTL writes the rows back.

Now only parts whose DELETE TTL has expired for every row skip the size limits and the reservation. Every other fully expired part (GROUP BY, WHERE or column TTL, a DELETE TTL without a value, or one that ALTER removed) obeys these size limits and is counted by the reservation, also for OPTIMIZE ... DRY RUN. The replicated queue check (#119983, #123068) applies the same rule only to tables with no other TTL, so a full replica still postpones a large DELETE + move drop. Mutations of parts whose DELETE TTL expired for every row reserve only 1 MiB; #122481 fixes that.

Tests (test_ttl_drop_not_postponed_by_size): new cases C (plain table, full disk, also with a value-less DELETE TTL: no merge starts, a dry run is refused, with room it reserves the part size), D (a DELETE TTL next to another TTL still drops on a full disk) and E (a dry run after REMOVE TTL is refused); B and the mixed case of #123068 check the replicated reservation. B, C, E and the mixed case fail on master.

🤖 Generated with Claude Code


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

groeneai and others added 3 commits September 25, 2026 23:27
A part whose GROUP BY, WHERE or column TTL has expired is selected as a
whole-part TTL drop. The drop selector gave such merges unlimited size
constraints, and estimateNeededDiskSpace skipped fully expired parts, both
assuming that the merge writes nothing. That holds only with an
unconditional rows TTL, through which TTLTransform drops all data;
otherwise the rows are aggregated or filtered and written back. On a disk
with less free space than the part, the merge started with a 1 MiB
reservation, failed with ENOSPC and was selected again about once per
second, so the TTL was never applied and concurrent writes to the disk
could fail.

Use hasRowsTTL() at both safeguards: without an unconditional rows TTL the
drop gets the regular merge constraints, and the plain and replicated merge
reservations count the expired parts. hasOnlyRowsTTL() would be too narrow:
a DELETE TTL next to a move, recompression, column, GROUP BY or WHERE TTL
also empties the part, and such drops keep ignoring free space.

Extend test_ttl_drop_not_postponed_by_size. Case B now queues the drop
while it fits, fills the disk, checks that the queue still postpones it and
that the executed merge reserves room for its rows. New case C covers a
non-replicated table on a full disk, new case D a DELETE TTL next to a
recompression TTL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit let a TTL drop of a completely expired part skip the
size limits and the space reservation whenever the table has an
unconditional rows TTL. The table having one does not make the part
empty: `TTLTransform` drops all rows only when the part's own rows TTL
maximum has expired, and a row whose `DELETE` TTL is 0 records no value.
A part whose every row has such a value, or that was written before the
`DELETE` TTL was added with `materialize_ttl_after_modify = 0`, is still
a drop candidate through its `GROUP BY`, `WHERE` or column TTL; it got
unlimited constraints and 1 MiB, and its rows were written back into a
full disk, the same ENOSPC loop.

Check the part instead. `PartProperties::GeneralTTLInfo` gets
`rows_ttl_expired`: the table has a rows TTL and the part's rows TTL
maximum is set and expired, the condition under which `TTLTransform`
empties it. The drop selector first looks, with unlimited constraints,
only at such parts, then at every other completely expired part with
the regular merge constraints. `estimateNeededDiskSpace` skips a
completely expired part only if it has a rows TTL value, so the merge
reservations, `OPTIMIZE ... DRY RUN` included, count the rows such a
merge writes; the mutation reservations count such parts too. This
replaces the caller parameter of the previous commit.

Run case C of `test_ttl_drop_not_postponed_by_size` also with a
`DELETE` TTL that has no value for any row, and check that a dry run
of the part is refused with `NOT_ENOUGH_SPACE` while the disk is full.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`estimateNeededDiskSpace` skipped a completely expired part whose rows
TTL values had expired, trusting only what the part records. The merge
empties such a part only if the metadata it runs with has a rows TTL.
`ALTER ... REMOVE TTL` is metadata-only, and so is a `MODIFY TTL` that
drops the `DELETE` with `materialize_ttl_after_modify = 0`, so the part
keeps its expired values while the merge writes every row back.
`OPTIMIZE ... DRY RUN` has no other size check: it reserved nothing and
failed with a write error on a full disk instead of `NOT_ENOUGH_SPACE`.
Background merges and mutations are size-limited at selection, so they
only lost the reservation margin.

Pass the metadata snapshot of the merge or mutation to the estimate and
skip a part only if that snapshot has a rows TTL. With a rows TTL the
estimate is unchanged; without one it counts every part.

Add case E to `test_ttl_drop_not_postponed_by_size`: after `REMOVE TTL`,
a dry run of an expired part on a full disk must be refused with
`NOT_ENOUGH_SPACE`.

Co-Authored-By: Claude Opus 5.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 26, 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 in each of three rounds, plus an
independent-model gate (engine: codex; 2 findings in round 1, 1 in round 2, 1 in round 3).

# Sev Finding Verdict Evidence / action
1 ❌ A DELETE TTL in the table does not prove a fully expired part ends up empty: a part whose DELETE TTL has no value (every row 0, or added by ALTER without materialization) was still dropped with no size limit and a 1 MiB reservation, and its rows were kept AGREE, fixed @ 5e88d50 the unlimited pass and the skipped bytes require the part's own DELETE TTL to have expired; test C also runs with such a TTL
2 ❌ OPTIMIZE ... DRY RUN reserved nothing for expired parts that keep rows AGREE, fixed @ 5e88d50 the rule lives in the shared estimate; test C checks the refusal
3 ❌ Mutation reservations keep the old rule DISAGREE a mutation cannot start unless the part fits the free space (plain selection and the replicated queue), and whether it writes anything depends on its commands; since 5e88d50 the mutation reservations use the same shared rule anyway
4 ❌ After REMOVE TTL a part keeps its expired DELETE TTL values, the estimate still skipped it, and a dry run then wrote every row into a full disk AGREE, fixed @ c0bed3b the estimate also requires a rows TTL in the metadata the merge runs with; new test E
5 ❌ A replicated entry runs its TTL at the entry's create_time while the estimate uses the wall clock, so an entry assigned before its parts' DELETE TTL expired can reserve less than it writes DISAGREE mechanism agreed, but pre-existing and unchanged: the wall clock in estimateNeededDiskSpace is master's line, this PR only removes parts from master's skip set, and a TTLDrop is assigned only for parts already expired at create_time, so the drops changed here are consistent. A separate root cause, not reproduced; not changed in this PR
6 💡 The replicated queue gate from #119983 still exempts only a DELETE-only TTL (its comment still says only such a table empties a drop) noted unchanged and conservative; offered in the description
7 💡 Row-retaining drops now obey max_bytes_to_merge_at_max_space_in_pool and pool pressure noted deliberate, the same limits as the other TTL merges; stated in the description
8 💡 Case B's row count after the postponement cannot see an execution (distinct ids survive the rollup), and two test comments still describe the old two-insert layout noted the postponement is asserted by the queue state

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding. Also noticed, not raised: the drop selector ignores prefer_not_to_merge volumes (merge
avoidance, not free space), and a drop selected just before SYSTEM STOP TTL MERGES runs without TTL
on its small reservation, both unchanged by this PR.

Session id: cron:clickhouse-review-slot-8:20260926-051000

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_ttl_drop_not_postponed_by_size on master fails case C (both parameters) at step 2 every run (TTLDropMerge started, then errno: 28, No space left on device), case B at step 7 (reserved 1048576 B for 18660912 B of rows) and case E (OPTIMIZE ... DRY RUN writes into the full disk, errno: 28 in tmp_merge_dr_*/s.bin, instead of NOT_ENOUGH_SPACE). The reporter's SQL reproduces on official 26.8.10.6 and 26.9.1.1629: about 61 failing attempts per 60 s.
b Root cause explained? A part whose GROUP BY, WHERE or column TTL expired is a whole-part drop candidate. The drop selector ignored the merge size limits and the reservation skipped fully expired parts, both assuming an empty result, which holds only when the metadata the merge runs with has a DELETE TTL and the part's DELETE TTL has expired for every row. The merge wrote the rows into a disk without room for them, failed, and was re-selected at once.
c Fix matches root cause? Yes. Both safeguards now use the exact condition under which the TTL merge empties the part: checked per part, and in the reservation against the metadata snapshot of the merge or mutation it sizes. No bound widened, no setting added.
d Test intent preserved / new tests added? Case A unchanged. Case B keeps its postpone assertion and adds the replicated reservation check. New case C (the reported bug, also next to a DELETE TTL without a value, plus a DRY RUN refusal), case D (a DELETE TTL next to another TTL still drops on a full disk) and case E (a dry run of an expired part after REMOVE TTL is refused for lack of space).
e Both directions demonstrated? Yes: master fails B, both C parameters and E; the previous head of this branch fails E only; the fix passes 6/6 in 10 fresh clusters and 12/12 with --count 2 in one cluster. Seven mutants each fail a named case (unlimited second pass, per-part flag ignored, hasOnlyRowsTTL for the flag, master's estimate, estimate never skipping, estimate without the part's rows-TTL value check, queue-gate conjunct dropped).
f Fix is general across code paths? Yes: the shared selector covers both engines, and the rule lives in the shared estimate, whose five callers (plain and replicated merges, OPTIMIZE ... DRY RUN, both mutation reservations) each pass the snapshot of the operation they size.
g Fix generalizes across inputs (params/datatypes/wrappers)? GROUP BY TTL (B, C), DELETE TTL without a value next to GROUP BY (C), DELETE + recompression (D), DELETE only (A), DELETE removed by ALTER (E); WHERE and column TTLs take the same path. Affected stateless TTL and dry-run tests pass 140/140 randomized. Default and non-default ttl_only_drop_parts both reproduce and are fixed. Type wrappers: N/A.
h Backward compatible? (maintainer-approved exception only) Yes: no setting or format change. Parts that the merge empties are handled as before at every site; any other fully expired part's drop now obeys the regular merge limits and reserves its size, like other merges.
i Invariants and contracts preserved? A merge that writes rows is admitted within the free-space and pool limits and reserves room for them; only a merge with an empty result skips both. The unlimited pass admits only parts that satisfy the empty-result condition, also for a multi-part range, and the estimate skips only parts the merge's own metadata empties. The replicated queue gate's hasOnlyRowsTTL exemption is unchanged.

Session id: cron:clickhouse-impl-slot-41:20260926-035500

@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [40cffe1]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel) FAIL
05055_format_schema_source_query_background_access FAIL cidb

AI Review

Summary

The PR makes row-retaining TTLDrop merges respect merge-size limits and reserve disk space, including OPTIMIZE ... DRY RUN. The merge fix is sound; one pre-existing mutation-reservation issue remains as an explicitly deferred follow-up. The previous stale-expression reservation finding is withdrawn: MergeTask and TTLTransform also use the stored rows-TTL bound to discard all rows, so that finding's claimed rewrite does not follow.

Missing context / blind spots
  • ⚠️ Integration and integration bugfix-validation jobs are pending for head 40cffe1511166a417c1f70cd8d09e8acfae11347; their green status has not been established. The author reports repeated passing regression runs on earlier revisions. Completed results for test_ttl_drop_not_postponed_by_size would close this gap. Current CI report.
Findings

⚠️ Majors

  • CompactionStatistics.cpp:56: An expired source part still receives a zero-byte estimate for mutations that rewrite its rows. [dismissed by author -- https://github.com/Respect free disk space in TTL drop merges that keep rows #122391#discussion_r4110461441] The source-size gate measures the roomiest disk in the policy, whereas both mutation paths reserve on the source part's disk, so that gate does not protect a full source disk. A regular ALTER TABLE ... UPDATE of a column unrelated to TTL does not execute TTL; even the ttl_only_drop_parts decorator finishes the rewrite before replacing its result with an empty part. Such mutations can therefore still start with the 1 MiB minimum reservation, exhaust the disk and fail repeatedly, affecting concurrent writes. This is pre-existing and not worsened by this diff, which narrows the original estimator's skip condition. The author's decision to handle it separately in Reserve disk space for the mutation of a part whose TTL has expired #122481 is accepted; that PR remains open and is absent from this head. The follow-up should use a mutation-specific estimate that counts the source bytes.
Final Verdict

✅ Approve the scoped merge fix. The mutation issue above is retained for visibility as a pre-existing, separately tracked limitation. No new inline findings were posted; the existing mutation thread remains open, and the unsupported stale-expression thread was resolved. Current-head integration validation is still pending.

/// Exclude expired parts
time_t part_max_ttl = part->ttl_infos.part_max_ttl;
if (part_max_ttl && part_max_ttl <= current_time)
if (metadata_snapshot.hasRowsTTL() && part->ttl_infos.table_ttl.max && part_max_ttl && part_max_ttl <= current_time)

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.

estimateNeededDiskSpace is now shared by the mutation reservations too, but this continue is only safe for operations that are known to delete the rows. Both mutation callers (MutateFromLogEntryTask::prepare and StorageMergeTree::selectPartsToMutate) now route through this helper, while MutateTask only reapplies TTL when shouldExecuteTTL sees TTL dependencies, and the "drop the whole expired part" shortcut is limited to hasOnlyRowsTTL(). That leaves a real gap for tables like TTL ts + INTERVAL 1 DAY DELETE, ts + INTERVAL 10 YEAR RECOMPRESS ...: a regular ALTER ... UPDATE / MATERIALIZE COLUMN on a fully expired part still rewrites the rows, but this branch reserves 0 bytes because table_ttl.max and part_max_ttl are expired. On a full disk that mutation can still fail with NOT_ENOUGH_SPACE and retry forever.

Please keep the "skip expired source parts" rule scoped to operations that are guaranteed to remove those rows (TTLDrop / MATERIALIZE TTL / the hasOnlyRowsTTL() mutation optimization), and make generic mutation reservations count the part size.

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 still looks unresolved in the current tree. estimateNeededDiskSpace still skips any fully expired rows-TTL part for both mutation callers (src/Storages/StorageMergeTree.cpp:2434 and src/Storages/MergeTree/MutateFromLogEntryTask.cpp:139), but the actual mutation path only drops the result automatically on the much narrower hasOnlyRowsTTL() && ttl_only_drop_parts && !materialize_ttl_recalculate_only optimization (src/Storages/MergeTree/MutateTask.cpp:4129, src/Storages/MergeTree/MutateTask.cpp:4267, src/Storages/MergeTree/MutateTask.cpp:4346).

So a generic mutation on a fully expired part in a table like TTL ts + INTERVAL 1 DAY DELETE, ts + INTERVAL 10 YEAR RECOMPRESS still rewrites the rows while reserving 0 bytes. The local size gate does not prove safety either: it is based on the maximum free space across all disks (src/Storages/MergeTree/Compaction/CompactionStatistics.cpp:149), while the mutation later reserves on the source part's own disk (src/Storages/StorageMergeTree.cpp:1014), and the replicated path has no such gate before reserveSpace(estimated_space_for_result, source_part->getDataPartStorage()) (src/Storages/MergeTree/MutateFromLogEntryTask.cpp:191).

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

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 40cffe1511166a417c1f70cd8d09e8acfae11347 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "String" }, { "name…).

See the job log for details.

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only background merge code: how fully expired parts are chosen for TTL drop merges and how disk space is estimated for merges and mutations, plus integration tests. None of the ClickBench or TPC-H SELECT queries run that code. Q20's -42.0% improvement comes with a matching CPU drop, but the diff cannot explain it, so it is downgraded to not_sure and does not count as a PR effect. The automatic suppression of Q16 (+12.4%), Q33 (+6.7%) and Q34 (+5.3%) is consistent with the diff: each stays inside master's normal range, and all three queries have a noisy history.

clickbench

⚠️ 4 inconclusive

Flagged queries (4 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 530 596 +12.4% <0.0001 The +12.4% stays inside master's normal range for this query, and the query's history is noisy. This PR only changes TTL merge selection and disk-space estimates, which this SELECT never runs.
⚠️ 20 not_sure 220 128 -42.0% <0.0001 CPU time dropped too, so something did change, but this PR only touches TTL merge selection and merge disk-space estimates. A read-only SELECT on a table without TTL never runs that code.
⚠️ 33 not_sure 1049 1119 +6.7% 0.0009 The +6.7% stays inside master's normal range for this query, and the query's history is noisy. The changed TTL merge code is not on this query's execution path.
⚠️ 34 not_sure 1046 1102 +5.3% 0.0009 The +5.3% stays inside master's normal range for this query, and the query's history is noisy. The changed TTL merge code is not on this query's execution path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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: cd0303bb-b900-4cd6-b564-9e1e92b31d41
  • MIRAI run: a945c305-d274-4ec1-b427-e58ea35fe1a8
  • PR check IDs:
    • clickbench_89483_1791939782
    • clickbench_89975_1791939861
    • clickbench_90085_1791939870
    • tpch_adapted_1_official_90278_1791939931
    • tpch_adapted_1_official_90409_1791939944
    • tpch_adapted_1_official_90431_1791939945

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 59423c4

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
Performance Comparison (arm_release, master_head, 5/6) / order_by_read_in_order #1 dashboard confirmed_regression, client_time 0.021 -> 0.034 s (+62.8%), which the shard's own report calls only unstable. The query reads the last granule of hits_100m_single in reverse order, and the two servers rebuilt that table with different granule boundaries: this run selected 12322 vs 12381 marks and read 6515 vs 16404 rows. The table has no TTL, so the TTL merge selection and disk-space estimate this PR changes behave the same for it. In the last 7 days on arm the same query was reported slower on 139 other pull requests and 18 true-master runs #122459 (mine, open): it rebuilds the hits datasets with constant granularity, so both servers read the same layout
Mergeable Check, PR rollups, red only because of the shard above #122459 (mine, open)

All 146 check runs completed (102 passed, 43 not selected, 1 red) and CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20260928-063113

…rop-needs-space

# Conflicts:
#	src/Storages/MergeTree/Compaction/CompactionStatistics.cpp
#	src/Storages/MergeTree/Compaction/CompactionStatistics.h
#	src/Storages/MergeTree/MergeFromLogEntryTask.cpp
#	src/Storages/StorageMergeTree.cpp
#	tests/integration/test_ttl_drop_not_postponed_by_size/configs/storage_configuration.xml
#	tests/integration/test_ttl_drop_not_postponed_by_size/test.py
The mixed case of test_ttl_drop_not_postponed_by_size now asserts that
the merge writing back the rows of the attached part reserves at least
what that part holds. The attached part is made larger than the 1 MiB
minimum reservation so that the check can fail: on master the mixed
range reserves 1 MiB for about 2 MB of rows it writes back.

The orphan case now queues its drop while the part still fits and fills
the disk afterwards, as the GROUP BY case does: with the selector change of
this branch, a drop that keeps rows is no longer assigned when the disk
cannot hold them, so the drop would otherwise never reach the queue check.

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.

A row-retaining TTLDrop merge (GROUP BY TTL) on plain MergeTree bypasses both free-space safeguards and loops forever on ENOSPC

2 participants