Skip to content

Add min_unreserved_disk_space_for_merge MergeTree setting - #115723

Merged
alexey-milovidov merged 34 commits into
ClickHouse:masterfrom
valerypetrov:fix/min-unreserved-space-merge-80006
Sep 28, 2026
Merged

alexey-milovidov merged 34 commits into
ClickHouse:masterfrom
valerypetrov:fix/min-unreserved-space-merge-80006

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #80006

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

New MergeTree setting min_unreserved_disk_space_for_merge: background merge selection subtracts the specified amount from the unreserved disk space, so large merges stop being selected before they can take the last free space and starve inserts. Unlike keep_free_space_bytes, the protected space remains usable by ClickHouse itself.

Documentation entry for user-facing changes

Merge selection already bounds the maximum total size of source parts by max_unreserved_free_space / 2 (DISK_USAGE_COEFFICIENT_TO_SELECT) in CompactionStatistics::getMaxSourcePartsBytesForMerge. This change subtracts the new setting from the unreserved space before that bound is applied, in the overload both engines' selection paths go through. As the disk fills up, the maximum selectable merge shrinks, and once only the protected headroom remains, merges stop being selected while inserts continue to work.

Coverage notes:

  • StorageMergeTree: background selection and plain OPTIMIZE go through the capped path.
  • StorageReplicatedMergeTree: the merge-selecting task uses the capped value when assigning merges, and so does plain OPTIMIZE, which therefore refuses at selection time instead of enqueueing a log entry. ReplicatedMergeTreeQueue::shouldExecuteLogEntry re-applies the cap on the executing replica, except for OPTIMIZE FINAL/PARTITION entries, which carry bypass_min_unreserved_space, and for TTL drops under a rows-only TTL, which master already runs regardless of size.
  • Explicit OPTIMIZE ... FINAL / OPTIMIZE ... PARTITION bypass selection-time size caps by design, same as max_bytes_to_merge_at_max_space_in_pool: both engines route them through selectAllPartsToMergeWithinPartition, which only looks at the raw free space. This is documented in the setting description.
  • On disks with unlimited space (object storage) unreserved space is reported as unlimited, so the setting has no effect there.

Mutations keep their existing behavior (getMaxSourcePartBytesForMutation is untouched); extending the protection to mutations could be a follow-up if desired.

The stateless test uses a 1 PiB threshold to make merge selection impossible, checks that plain OPTIMIZE refuses with optimize_throw_if_noop = 1, then lowers the setting via ALTER TABLE ... MODIFY SETTING and checks that the merge proceeds. It also checks that OPTIMIZE ... FINAL and OPTIMIZE ... PARTITION still merge while the threshold is in force, on both MergeTree and ReplicatedMergeTree.

Forward compatibility: log entries carrying bypass_min_unreserved_space cannot be parsed by replicas older than this change — the same posture as the cleanup/apply_patches fields when they were introduced. Only OPTIMIZE FINAL/OPTIMIZE PARTITION entries carry the bit, and only while the setting is non-zero.


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

Version info

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

Background merges could book all remaining disk space, starving inserts.
The new setting subtracts a configurable headroom from the unreserved
space used to size merge selection, so merges shrink dynamically as the
disk fills and stop once only the protected headroom remains, while the
space stays usable for inserts (unlike keep_free_space_bytes).

Closes ClickHouse#80006

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
@rienath rienath added the can be tested Allows running workflows for external contributors label Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [89d3e58]

Summary: ✅


AI Review

Summary

This PR adds min_unreserved_disk_space_for_merge and wires it through the replicated OPTIMIZE path, the replication queue, and replicated TTL-time-based space reservation. Those replicated-path fixes look coherent, but the plain MergeTree background path still leaves one real hole: row-retaining whole-part TTLDrop merges can reserve only the 1 MiB floor and then write into the protected headroom, so the new setting does not yet uphold its core invariant for that merge class.

Findings

❌ Blockers

  • [src/Storages/MergeTree/Compaction/CompactionStatistics.cpp:42-62; src/Storages/StorageMergeTree.cpp:1931-1934] estimateNeededDiskSpace still treats every fully expired part as a zero-byte merge, but MergeType::TTLDrop is not equivalent to “writes nothing”. MergeSelectorApplier can select whole-part GROUP BY, WHERE, and column-TTL drops as TTLDrop, and MergeTask only takes the empty-part short-circuit when hasOnlyRowsTTL() is true. On plain MergeTree, the background path still feeds that zero estimate into CurrentlyMergingPartsTagger, so with min_unreserved_disk_space_for_merge barely above zero it can reserve only the 1 MiB floor and then rewrite a source-sized result into the space this setting is supposed to keep out of merges’ reach. Suggested fix: make the local reservation path distinguish row-deleting vs row-retaining TTLDrop merges (the same hasOnlyRowsTTL() split the replicated queue already uses), or add a local headroom gate before treating TTLDrop as size-free.
Tests
  • ⚠️ The new stateless coverage only exercises synchronous OPTIMIZE paths and the explicit FINAL / PARTITION bypass. It does not cover the plain MergeTree background TTLDrop case above, so the current regression suite would not catch this hole.
Final Verdict

Request changes. The new setting is still inconsistent on plain MergeTree for row-retaining whole-part TTLDrop merges, which means it can still recreate the insert-starvation path it is intended to prevent.

LLVM Coverage Report

Measured on commit 89d3e58.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 79.50% 79.60% +0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 89d3e58c58bd85e451c2f3982277316fb5bdf5b2 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

valerypetrov and others added 5 commits August 24, 2026 08:35
The replicated path seeded the selector from the raw max_bytes_to_merge_at_max_space_in_pool,
so OPTIMIZE enqueued an entry that shouldExecuteLogEntry then postponed forever; it now derives
the same cap and refuses at selection time. Test covers the replicated case instead of skipping it.
master moved the current version to 26.9, so the setting needs its own block there.
The master merge dropped master's new merge_tree 26.9 entry below this block's
closing `});` instead of inside it, leaving an orphaned initializer and a
stray brace that did not compile.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Its only use in this file was replaced by
CompactionStatistics::getMaxSourcePartsBytesForMerge(*this), which reads
the setting internally, leaving the extern declaration with no reference
left in StorageReplicatedMergeTree.cpp.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ueue

The setting is a selection-time limit, but ReplicatedMergeTreeQueue::shouldExecuteLogEntry
re-derived it for every MERGE_PARTS entry. Explicit OPTIMIZE ... PARTITION and OPTIMIZE ...
FINAL bypass the cap when selecting parts (they go through selectAllPartsToMergeWithinPartition),
so on a replicated table they enqueued a log entry that the queue then postponed forever:
the entry's source parts exceeded the clamped limit, and the ignore_max_size carve-out that
normally lets explicitly ordered merges through only triggers when the limit equals
max_bytes_to_merge_at_max_space_in_pool. With alter_sync = 1 the OPTIMIZE query waited on that
entry indefinitely.

The queue now computes the limit without the headroom, so it keeps enforcing the pre-existing
free-space bound while explicitly ordered merges run as before. Background merges are still
capped where they are assigned. The setting description now also mentions OPTIMIZE ... PARTITION,
which bypasses the cap for the same reason FINAL does, and the test covers both engines.

Co-Authored-By: Claude Opus 5 <[email protected]>
…or all merges

Dropping min_unreserved_disk_space_for_merge in shouldExecuteLogEntry removed
the setting's protection from every background MERGE_PARTS entry on the
executing replica, not just from user-forced ones: a 50 GiB source merge
assigned by a replica with 300 GiB free would still run on a replica with
105 GiB free, reserve ~55 GiB and leave the inserts the headroom was meant
to protect with nothing (ClickHouse#80006 is exactly that starvation, from the other
side).

The queue now re-derives the limit with the headroom again, and only entries
whose parts were selected without it - OPTIMIZE ... FINAL / OPTIMIZE ...
PARTITION, which go through selectAllPartsToMergeWithinPartition - bypass
it, via a new serialized bypass_min_unreserved_space bit on the log entry.
Plain OPTIMIZE keeps respecting the headroom end to end (its selector is
seeded with the headroom-respecting limit), and background entries keep
respecting it both at assignment and at execution. Setting the bit on the
entry before it is serialized matters: the ZooKeeper node is written inside
createLogEntryToMergeParts, so the flag is a parameter there rather than a
post-hoc mutation of the returned copy.

An old replica reading an entry that carries the bit fails to parse it the
same way it would one carrying cleanup or apply_patches - the established
posture for new optional MERGE_PARTS fields.
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Update on the review threads:

Ordinary background MERGE_PARTS entries respect min_unreserved_disk_space_for_merge on the executing replica again; only user-forced OPTIMIZE FINAL/OPTIMIZE PARTITION entries bypass the headroom. The bypass is carried by an explicitly serialized bypass_min_unreserved_space bit in ReplicatedMergeTreeLogEntryData (the same optional-field pattern as cleanup; it is set only in createLogEntryToMergeParts from the optimize path, before the ZK node is serialized) — d6e3e97. Test 05025 is extended: a background merge is blocked under a 1 PiB headroom, while OPTIMIZE PARTITION still merges.

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
The 26.9 entry claimed `enable_adaptive_codec_selection` was renamed from
`allow_experimental_adaptive_codec_selection`. That old name does not
exist anywhere under src/, and the setting already has its real
introduction record under 26.8 just below. The entry came in with this
branch, not from master.

system.documentation reconstructs rename and alias history from these
free-form reason strings, so leaving it in makes the server report a
rename that never occurred.
The bypass marker is written into the replication log entry only when the
setting is non-zero, so an entry queued while it was 0 runs under the
headroom even if the setting is raised first. That is the narrower of the
two options left once the log-entry format cannot carry the field to older
replicas, so state it in the setting's description rather than leaving it
implicit.
The description explained when the bypass field is written but not what it
costs. A replica that does not know the field fails on the whole log entry
rather than skipping it, so enabling this mid-upgrade stalls the queue on
every not-yet-upgraded replica. That belongs in the setting's own
description, not only in the PR body, since the description is the lasting
user-facing contract.
MergeFromLogEntryTask sized its reservation with
estimateNeededDiskSpace(parts, true), which drops expired source parts
using the *executing* replica's clock, while the merge itself evaluates
TTL at entry.create_time (the assigning replica's clock, passed as
time_of_merge to mergePartsToTemporaryPart).

The two disagree whenever clocks do. A follower whose clock lags sized a
TTL drop as a full 1.1x source-size reservation even though the merge
writes an empty part, so the queue-side TTLDrop exemption added here
could let an entry past min_unreserved_disk_space_for_merge and then hit
NOT_ENOUGH_SPACE. The opposite skew was worse: a part expiring after
entry.create_time but before execution made the estimate skip it, so the
replica reserved nothing for a merge that does write a full-size result.

Pass entry.create_time through to estimateNeededDiskSpace so the
reservation is derived from the same moment the merge is, on every
replica. This keeps the zero-reservation contract of a TTLDrop entry
without trusting entry.merge_type: an entry mislabelled TTLDrop by a
buggy or older leader still gets a full-size reservation, because the
estimate looks at the parts' own ttl_infos rather than at the label.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
valerypetrov and others added 3 commits September 11, 2026 05:53
The queue exempted TTLDrop entries from the size check outright on the
grounds that they "reserve nothing". They do not: MergeFromLogEntryTask
estimates 0 bytes for them (every source part is expired at
entry.create_time), but balancedReservation and
reserveSpacePreferringTTLRules clamp every estimate up to
RESERVATION_MIN_ESTIMATION_SIZE, so a drop still takes 1 MiB, and with an
unconditional exemption it took it out of the space that
min_unreserved_disk_space_for_merge protects, or failed with
NOT_ENOUGH_SPACE on a full replica.

Keep the reservation as it is - the floor guards every reservation
against under-estimation and a drop still writes a (small) part - and make
the queue-side check honour it instead: treat the entry's source size as
that floor, so it is admitted exactly when the headroom-respecting limit
leaves room for what the merge actually reserves, with the same safety
factor every other merge gets. The constant moves from a file-private
namespace to MergeTreeData so the queue can name it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
estimateNeededDiskSpace was already sized at entry.create_time, but the
TTL-aware destination choice in balancedReservation and the
reserveSpacePreferringTTLRules fallback still evaluated the move TTL
rules at the local clock, so a replica whose clock lags the assigning
one could pick a different volume than the merge itself (which runs at
entry.create_time) implies, or fail with NOT_ENOUGH_SPACE there.

Thread entry.create_time through both for the log-entry path.
balancedReservation gains a trailing `time_of_move` parameter that
defaults to 0, meaning the local clock, so fetches and the local
StorageMergeTree merge path keep their behaviour.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Since the queue sizes a replicated TTL drop entry at the 1 MiB reservation
floor and postpones it while the headroom-respecting limit is below that,
the min_unreserved_disk_space_for_merge description could no longer list
expired-part drops among the merges that ignore the setting. Say what
happens instead: they are not limited by their source size, are selected
whenever the limit is above zero, and the executing replica's queue checks
them as a 1 MiB merge. The OPTIMIZE FINAL / PARTITION exemption is
unchanged and stays as it was.

Also trim the comment above the TTLDrop branch in shouldExecuteLogEntry
to two lines.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
…d-space-merge-80006

Resolved conflict in src/Core/SettingsChangesHistory.cpp (kept both new 26.9 MergeTree entries).
valerypetrov and others added 3 commits September 24, 2026 19:33
A TTL drop merge estimates 0 bytes, but its reservation is raised to
`RESERVATION_MIN_ESTIMATION_SIZE`. Taking the smaller of that floor and
the source size under-sized the check when the expired sources were
below 1 MiB, so the merge could still eat into the protected space.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…space-merge-80006

Bring the branch up to date with master. It merges without conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master is now 26.10, and a new setting has to be recorded in the history
block of the current version.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The override replaced the source size of every TTLDrop entry with the
1 MiB reservation floor. Since master's hasOnlyRowsTTL exemption, drops
that delete every row already skip the size check, so the override only
changed drops that keep rows (GROUP BY, WHERE or column TTL). Those
rewrite what their source parts hold, and sizing them at 1 MiB let them
past the limit that master postpones them on. This broke
test_ttl_drop_not_postponed_by_size::test_row_retaining_drop_is_still_postponed_by_source_size.

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

UInt64 estimateNeededDiskSpace(const MergeTreeDataPartsVector & source_parts, const bool & account_for_deleted)
UInt64 estimateNeededDiskSpace(

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 still treats every fully expired part as a zero-byte merge, but MergeType::TTLDrop is not synonymous with "writes nothing". A whole-part GROUP BY / column / WHERE TTL is also selected as TTLDrop (MergeSelectorApplier.cpp:76-84), yet MergeTask only takes the empty-part short-circuit when hasOnlyRowsTTL() is true (MergeTask.cpp:874-875); otherwise it rewrites the surviving rows. On non-replicated StorageMergeTree that estimate still feeds straight into CurrentlyMergingPartsTagger (StorageMergeTree.cpp:1996-1997), so with min_unreserved_disk_space_for_merge barely above zero such a merge can reserve only the 1 MiB floor and still start rewriting a source-sized result into the protected headroom. The replicated queue got the hasOnlyRowsTTL() split, but the local path still relies on this zero-byte estimate for every TTLDrop. I think this estimate needs the same metadata-based distinction, or the local background path needs its own headroom gate before treating TTLDrop as size-free.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👷🏻 The size-free selection (MergeSelectorApplier.cpp:79-84) and this zero-byte estimate are master's code, and bounding row-keeping drops at selection breaks master's test_row_retaining_drop_is_still_postponed_by_source_size, which expects such a drop to be queued and then postponed. a07def1 states it in the setting description instead: plain MergeTree does not size-limit a whole-part drop under a GROUP BY, WHERE or column TTL. Measured on master with a 1 MiB merge limit: a TTL ... DELETE WHERE table merged 10381677 bytes of expired parts into a 5180551-byte part, while a table without TTL was not merged.

valerypetrov and others added 2 commits September 26, 2026 09:00
21e92cf stopped the replicated queue from sizing TTL drop entries as
a 1 MiB merge, so the setting description no longer matches the code: the
queue skips the size check for drops under a rows-only TTL and sizes the
others by their source parts. Remove that clause.

The same commit left RESERVATION_MIN_ESTIMATION_SIZE public in
MergeTreeData.h with no user outside MergeTreeData.cpp, so move it back
to master's anonymous namespace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
…space-merge-80006

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

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

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Sep 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 28, 2026
Merged via the queue into ClickHouse:master with commit e2ddefa Sep 28, 2026
172 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 28, 2026
@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 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-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... pr-feature Pull request with new product feature 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.

Merges Reserve Whole Disk and Stops Inserts

4 participants