Repository navigation
Add min_unreserved_disk_space_for_merge MergeTree setting - #115723
alexey-milovidov merged 34 commits into
Conversation
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
|
Workflow [PR], commit [89d3e58] Summary: ✅
AI ReviewSummaryThis PR adds Findings❌ Blockers
Tests
Final VerdictRequest changes. The new setting is still inconsistent on plain LLVM Coverage ReportMeasured on commit 89d3e58.
Changed lines: Changed C/C++ lines covered: 139/139 (100.00%) · Uncovered code |
Build profile diff (arm_release)Commit See the job log for details. |
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.
…space-merge-80006
master moved the current version to 26.9, so the setting needs its own block there.
…space-merge-80006
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.
|
Update on the review threads: Ordinary background |
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
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
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).
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
👷🏻 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.
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]>
Closes: #80006
Changelog category (leave one):
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. Unlikekeep_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) inCompactionStatistics::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 plainOPTIMIZEgo through the capped path.StorageReplicatedMergeTree: the merge-selecting task uses the capped value when assigning merges, and so does plainOPTIMIZE, which therefore refuses at selection time instead of enqueueing a log entry.ReplicatedMergeTreeQueue::shouldExecuteLogEntryre-applies the cap on the executing replica, except forOPTIMIZE FINAL/PARTITIONentries, which carrybypass_min_unreserved_space, and for TTL drops under a rows-only TTL, which master already runs regardless of size.OPTIMIZE ... FINAL/OPTIMIZE ... PARTITIONbypass selection-time size caps by design, same asmax_bytes_to_merge_at_max_space_in_pool: both engines route them throughselectAllPartsToMergeWithinPartition, which only looks at the raw free space. This is documented in the setting description.Mutations keep their existing behavior (
getMaxSourcePartBytesForMutationis 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
OPTIMIZErefuses withoptimize_throw_if_noop = 1, then lowers the setting viaALTER TABLE ... MODIFY SETTINGand checks that the merge proceeds. It also checks thatOPTIMIZE ... FINALandOPTIMIZE ... PARTITIONstill merge while the threshold is in force, on bothMergeTreeandReplicatedMergeTree.Forward compatibility: log entries carrying
bypass_min_unreserved_spacecannot be parsed by replicas older than this change — the same posture as thecleanup/apply_patchesfields when they were introduced. OnlyOPTIMIZE FINAL/OPTIMIZE PARTITIONentries carry the bit, and only while the setting is non-zero.Workflow [PR]
Sync PR [sync-upstream/pr/115723]
Version info
26.10.1.868-master(included in26.10and later)