Repository navigation
Add min_partition_age_to_force_merge_seconds to compact partitions that no longer receive inserts - #115547
Conversation
…ommand Implements GitHub issue ClickHouse#79697: a new OPTIMIZE TABLE variant that merges the smallest contiguous run of parts in a partition instead of all parts. ## Syntax OPTIMIZE TABLE t PARTITION p MERGE SMALLPARTS [LIMIT n] ## Semantics - Selects the minimum-size contiguous window of adjacent parts in the partition that fits within max_bytes_to_merge_at_max_space_in_pool. - If LIMIT n is given, the window has at most n parts; otherwise it considers all window sizes from 2 up to the total number of parts. - Skips the SimpleMergeSelector heuristic (which deprioritises small parts) by selecting the window directly. - Requires PARTITION to be specified; MERGE SMALLPARTS without PARTITION is rejected with BAD_ARGUMENTS at the interpreter level. - Incompatible with FINAL, DEDUPLICATE, CLEANUP, DRY RUN, and MANIFEST. - Works for all MergeTree-family tables (plain and replicated). ## Algorithm Uses a sliding-window scan over the parts sorted by sort-key position: for each window length len in [2, min(limit, n)]: compute sum of parts[0..len), then slide across the partition: slide: subtract the outgoing part, add the incoming part track the window [start, start+len) with minimum total size that is <= max_bytes_to_merge_at_max_space_in_pool After finding the best window, canMergeAllParts() is called to verify concurrent-merge constraints, and disk space is validated before the merge task is created. ## Files changed - src/Parsers/CommonParsers.h: add MERGE_SMALLPARTS multi-word keyword - src/Parsers/ASTOptimizeQuery.h: add merge_smallparts / merge_smallparts_limit fields; update getID() - src/Parsers/ASTOptimizeQuery.cpp: format, writeJSON, readJSON support - src/Parsers/ParserOptimizeQuery.cpp: parse MERGE SMALLPARTS [LIMIT n] - src/Storages/MergeTree/MergeTreeDataMergerMutator.h: declare selectSmallPartsToMergeWithinPartition() - src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp: implement selectSmallPartsToMergeWithinPartition() with sliding-window algorithm - src/Storages/StorageMergeTree.h: add merge_smallparts params to merge() and selectPartsToMerge() - src/Storages/StorageMergeTree.cpp: wire MERGE SMALLPARTS through selectPartsToMerge() dispatch and optimize() - src/Interpreters/InterpreterOptimizeQuery.cpp: validate MERGE SMALLPARTS constraints
…support The sliding-window search picked the globally smallest-byte window across all lengths, which a positive-size sum always minimizes at length 2 — LIMIT n was accepted but never honored beyond requiring n >= 2. Search descending from the max window length instead, so the largest window that fits under max_bytes_to_merge_at_max_space_in_pool wins. Also wire MERGE SMALLPARTS into StorageReplicatedMergeTree::optimize(), which has its own merge-selection path separate from StorageMergeTree and was previously left unhandled, silently falling back to a plain merge. Co-Authored-By: Claude Fable 5 <[email protected]>
Covers plain MergeTree (LIMIT enforcement, no-LIMIT full consolidation, PARTITION/FINAL/DEDUPLICATE/CLEANUP validation, single-part no-op error) and ReplicatedMergeTree (LIMIT enforcement replicates correctly). Co-Authored-By: Claude Fable 5 <[email protected]>
Michicosun
left a comment
There was a problem hiding this comment.
Optimize is not a command that should be used to reduce the number of parts in the table. This is an invalid approach.
Per review, OPTIMIZE is not the right vehicle for reducing the number of parts in a table. Replaced by a merge-selector setting in the next commit. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
When every part in a partition is at least this many seconds old (the partition no longer receives inserts), the Simple and StochasticSimple merge selectors consider all ranges in it for merging and skip the right-tail small-parts heuristic for them. Unlike min_age_to_force_merge_on_partition_only, the partition does not have to fit into a single merge: each merge respects max_bytes_to_merge_at_max_space_in_pool. Closes ClickHouse#79697 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
|
@Michicosun , makes sense. I've redone the initial approach. Please verify. |
|
@Michicosun The |
|
Workflow [PR], commit [1408e2e] Summary: ✅
AI ReviewSummaryThis PR adds the Final Verdict✅ No new findings. LLVM Coverage ReportMeasured on commit 1408e2e.
Changed lines: Changed C/C++ lines covered: 143/156 (91.67%) · Uncovered code |
The test declared its own MiB in an anonymous namespace, which made every use ambiguous against the MiB from base/unit.h that arrives transitively. Include that header explicitly and drop the local constant. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Per review: the setting silently turned enable_heuristic_to_remove_small_parts_at_right off for aged partitions. Leave that heuristic alone; merging the tail in is now opted into by turning it off explicitly, and the setting's description says so. The forced path also still inherited the window_size cutoff, so an idle partition with more parts than the window never had its prefix examined and could stay uncompactable however old it got. Consider all of its ranges, with a regression test at window_size + 1 parts. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Per review: ForceMergeByPartitionAgeLeavesRightTailHeuristicAlone asserted a range length of 2, which also matches merging the tail as [10 MiB, 1024] - the regression the test exists to catch. Compare part names instead. The window test had the same gap: any adjacent pair out of 1001 parts satisfied a length of 2, while the claim is specifically that the two leading parts get picked. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
…ion path Per review: forcing regular merges by partition age pre-empted min_age_to_force_merge_on_partition_only. selectPartsToMerge returns as soon as chooseMergesFrom finds a regular merge, so getBestPartitionToOptimizeEntire was never reached for that partition - and that is the only path marking a merge final, which is what StorageMergeTree and StorageReplicatedMergeTree require to run a ReplacingMergeTree CLEANUP. A stale partition fitting under max_bytes_to_merge_at_max_space_in_pool would merge without cleanup and, left as one part, could never be cleaned up afterwards. MergeSelectorApplier already withholds min_age_to_force_merge from the regular selector for exactly this reason; this setting was plumbed in unconditionally. Reject the combination in sanityCheck rather than silently disabling one of the two, and say so in the setting description. Regression in 03357. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
The unit test asserted the trailing small part is trimmed, and the tightened
assertion showed it is not: the selector picks {all_1_1_0, all_2_2_0}. The trim
in Estimator::consider only applies to a range of three parts or more, and
force_merge_by_partition_age returns from allow() before the
min_parts_to_merge_at_once floor, so the cheapest candidate is the two-part range
ending at the tail, which the trim never touches.
That is the behavior this setting wants - compacting the small tail is the point
of ClickHouse#79697 - but the test and the setting description both described it wrongly.
Assert what the selector actually does, and say why, instead of a property that
cannot hold. The code still leaves enable_heuristic_to_remove_small_parts_at_right
alone, which was the review request; it just is not observable through a forced
two-part merge.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units12 translation units recompiled, 31 s compile time in total, 12 of them have a recent master baseline. |
…stic Per review: the setting must not disable other heuristics as a side effect. It still silently skipped the window_size / stochastic-sliding cutoff for aged partitions, which is the same cross-heuristic relation in another place. Forcing by partition age now only makes a range eligible in `allow()`, exactly as min_age_to_force_merge already does; window_size keeps bounding which parts are examined. Drops the gtest that asserted the bypass and updates the setting description. Co-Authored-By: Claude Opus 5 <[email protected]>
The forced path returned from allow() before the min_parts_to_merge_at_once guard, so setting min_partition_age_to_force_merge_seconds silently lifted that floor as well. Forcing now waives only the size-ratio requirement it exists for; every other knob is left to be turned off explicitly through its own setting. min_age_to_force_merge keeps its existing position and behaviour. The floor defaults to 0, so this changes nothing unless it was set deliberately. Co-Authored-By: Claude Opus 5 <[email protected]>
|
@Michicosun — I've fully reworked the PR per your feedback: the OPTIMIZE-based approach is gone, replaced by the |
Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
…ant setting check Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PcH1uX3QLcLes3XfidQqsC
Co-authored-by: Mikhail Artemenko <[email protected]>
|
Thank you for the review! |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a single new merge-tree setting, min_partition_age_to_force_merge_seconds, that changes background merge selection only when a user explicitly enables it (default 0). It touches no query-execution or read path, so it cannot plausibly cause a per-query change on ClickBench SELECTs. The two flagged regressions (Q16 +10.1%, Q18 +16.9%) both sit on queries with intrinsically noisy history and are downgraded to not_sure as run-to-run variance; Q28/Q32/Q33/Q34 were already non-directional (test disagreement or within master's current variance band) and are consistent with that read. No real PR-attributable performance signal here. clickbenchFlagged queries (6 of 43)
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
|
…merge-smallparts The only non-infra red check on the branch, "Docs examples", failed on Function/timeSeriesPrometheusValueToString, a file this PR does not contain and does not touch. Master fixed the misaligned table in that function's documented example in 9bed853 ("Fix width of `timeSeriesPrometheusValueToString` doc example table"), which landed after this branch last merged master, so picking master up clears it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
bbf56ce to
fb8fc8a
Compare
… age The description said only that every part must be older than the value, which left out what the comparison actually uses and when forcing stops. State that the gate reads the youngest part's age and that any new part, including the merged part a forced merge produces, resets it, so a large partition is compacted over rounds spaced by this interval. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
…use it min_partition_age_to_force_merge_seconds is read by fillSimpleSettings alone, i.e. only the Simple and StochasticSimple merge selectors act on it. With Trivial or Manual it is inert, so there is no regular-merge pre-emption of the whole-partition final merge and nothing for the sanity check to protect. Gate the rejection on those two selectors so CREATE/ALTER no longer fail for the others, say so in the setting description and the error, and cover both the accepted case under 'Trivial' and the rejection that returns when the table is switched back to Simple or StochasticSimple. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Summary
Closes #79697.
This adds an opt-in
MergeTreesetting,min_partition_age_to_force_merge_seconds, addressing the issue's use case in the background merge selector itself (similar in spirit to #105454).When set to a non-zero value and every part in a partition is at least that many seconds old — i.e. the partition no longer receives inserts — the
SimpleandStochasticSimplemerge selectors waive the size-ratio requirement inallow()that otherwise refuses "unbalanced" merges of a large part together with small ones.Forcing is the same early return
min_age_to_force_merge_secondstakes, so it also waives themin_parts_to_merge_at_oncefloor: a forced merge can cover fewer parts than that floor asks for. No other knob is affected — each keeps its own meaning and its own default, and a workload that needs one of them off must turn it off explicitly through its own setting.merge_selector_window_sizestill bounds which parts are examined.merge_selector_enable_heuristic_to_remove_small_parts_at_rightstill trims a trailing small part from a selected range of three parts or more.Compacting a trailing small part is the point of #79697, and it happens out of the box: that trim only applies to ranges of three parts or more, so the cheapest candidate in an idle partition is the two-part range ending at the small tail.
This setting cannot be combined with
min_age_to_force_merge_seconds+min_age_to_force_merge_on_partition_only, and the combination is rejected insanityCheck. That pair routes a stale partition to the whole-partition merge, which is the only merge markedfinal— and a final merge is what enablesReplacingMergeTreeCLEANUP. SinceselectPartsToMergereturns as soon as a regular merge is found, forcing regular merges by partition age would pre-empt that path and silently stop cleanup from running. The two mechanisms are complementary: use the pair for partitions that fit into a single merge, and this setting for the ones that do not.Each merge still respects
max_bytes_to_merge_at_max_space_in_pool, so a partition larger than that limit converges to a few max-size parts. Unlikemin_age_to_force_merge_secondswithmin_age_to_force_merge_on_partition_only, the partition does not have to fit into a single merge, and unlike plainmin_age_to_force_merge_seconds, actively written partitions are unaffected. The default is0(disabled), preserving existing behavior. Merged parts start with age 0, which re-arms the threshold, so compaction of an idle partition proceeds in naturally throttled rounds.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the
min_partition_age_to_force_merge_secondsMergeTreesetting: when every part in a partition is at least this old, theSimpleandStochasticSimplemerge selectors compact that partition's parts within themax_bytes_to_merge_at_max_space_in_poollimit.Documentation entry:
MergeTreeSettings.cpp.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/115547]
Version info
26.9.1.1222(included in26.9and later)