Skip to content

Add min_partition_age_to_force_merge_seconds to compact partitions that no longer receive inserts - #115547

Merged
Michicosun merged 31 commits into
ClickHouse:masterfrom
valerypetrov:feature/optimize-merge-smallparts
Sep 11, 2026
Merged

Michicosun merged 31 commits into
ClickHouse:masterfrom
valerypetrov:feature/optimize-merge-smallparts

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #79697.

This adds an opt-in MergeTree setting, 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 Simple and StochasticSimple merge selectors waive the size-ratio requirement in allow() that otherwise refuses "unbalanced" merges of a large part together with small ones.

Forcing is the same early return min_age_to_force_merge_seconds takes, so it also waives the min_parts_to_merge_at_once floor: 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_size still bounds which parts are examined.
  • merge_selector_enable_heuristic_to_remove_small_parts_at_right still 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 in sanityCheck. That pair routes a stale partition to the whole-partition merge, which is the only merge marked final — and a final merge is what enables ReplacingMergeTree CLEANUP. Since selectPartsToMerge returns 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. Unlike min_age_to_force_merge_seconds with min_age_to_force_merge_on_partition_only, the partition does not have to fit into a single merge, and unlike plain min_age_to_force_merge_seconds, actively written partitions are unaffected. The default is 0 (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):

  • Improvement

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

Added the min_partition_age_to_force_merge_seconds MergeTree setting: when every part in a partition is at least this old, the Simple and StochasticSimple merge selectors compact that partition's parts within the max_bytes_to_merge_at_max_space_in_pool limit.

Documentation entry:

  • Documentation is generated from the setting description in MergeTreeSettings.cpp.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.9.1.1222 (included in 26.9 and later)

valerypetrov and others added 3 commits August 19, 2026 21:54
…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 Michicosun self-assigned this Aug 20, 2026

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

Optimize is not a command that should be used to reduce the number of parts in the table. This is an invalid approach.

@Michicosun Michicosun added the close in a month if not active This will be closed in case of no information label Aug 20, 2026
valerypetrov and others added 2 commits August 20, 2026 09:40
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
@valerypetrov valerypetrov changed the title Add OPTIMIZE TABLE ... PARTITION p MERGE SMALLPARTS [LIMIT n] Add min_partition_age_to_force_merge_seconds to compact partitions that no longer receive inserts Aug 20, 2026
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@Michicosun , makes sense. I've redone the initial approach. Please verify.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@Michicosun The OPTIMIZE ... MERGE SMALLPARTS approach is reverted and replaced with an opt-in MergeTree setting, min_partition_age_to_force_merge_seconds, that works inside the background merge selector: when every part in a partition is at least that old, the Simple/StochasticSimple selectors consider all its ranges for merging and skip the right-tail small-parts heuristic there, while each merge still respects max_bytes_to_merge_at_max_space_in_pool (so a partition larger than the limit converges to a few max-size parts, unlike min_age_to_force_merge_on_partition_only). Could you take another look and re-add can be tested so CI runs on the new approach?

@Michicosun Michicosun added can be tested Allows running workflows for external contributors and removed close in a month if not active This will be closed in case of no information labels Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1408e2e]

Summary: ✅


AI Review

Summary

This PR adds the min_partition_age_to_force_merge_seconds MergeTree setting, wires it into the Simple and StochasticSimple merge selectors, documents the youngest-part / cooldown semantics, scopes the cleanup-related incompatibility check to the selector algorithms that actually consume the setting, and adds focused selector plus functional coverage. I did not find any remaining blocker or major issue in the current head.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 1408e2e.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 143/156 (91.67%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 21, 2026
valerypetrov and others added 2 commits August 21, 2026 08:53
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
valerypetrov and others added 2 commits August 21, 2026 10:39
…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
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1408e2e98 with master c108e273b (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

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

Job report

valerypetrov and others added 2 commits August 21, 2026 14:11
…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]>
@valerypetrov

Copy link
Copy Markdown
Contributor Author

@Michicosun — I've fully reworked the PR per your feedback: the OPTIMIZE-based approach is gone, replaced by the min_partition_age_to_force_merge_seconds MergeTree setting that works inside the background merge selector. Your CHANGES_REQUESTED review predates that redesign, and the feedback from your follow-up comments is addressed at head e00ff95 — could you re-review it when you have time? Thank you!

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

everything else lgtm

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Thank you for the review!

@clickhouse-gh clickhouse-gh Bot added the comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. label Sep 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 548 603 +10.1% <0.0001 This PR only adds a new merge-selector setting (min_partition_age_to_force_merge_seconds), inert unless explicitly set; it cannot touch Q16's read path. The +10.1% is run-to-run variance on a query flagged noisy.
⚠️ 18 not_sure 872 1019 +16.9% <0.0001 The diff adds a dormant force-merge setting with no default behavior change, so it cannot affect Q18's execution. The +16.9% is noise on an intrinsically flaky query.
⚠️ 28 not_sure 1052 1181 +12.3% <0.0001 Already not_sure from disagreeing tests. The merge-selector setting added here is inert by default and unrelated to this SELECT; treat the delta as variance on a noisy query.
⚠️ 32 not_sure 722 806 +11.6% <0.0001 Within master's current variance band and left non-directional. The dormant merge setting cannot touch this read path, so the delta is not attributable to the PR.
⚠️ 33 not_sure 1143 1272 +11.3% <0.0001 Within master's current variance band. The PR only adds an off-by-default force-merge setting, so this delta is variance, not a PR effect.
⚠️ 34 not_sure 1153 1276 +10.6% <0.0001 Within master's current variance band. The added merge-selector setting is inert unless enabled and cannot affect this query; delta is run-to-run variance.

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: b3602ed5-f2f7-4c12-a4cb-0b069692d34d
  • MIRAI run: 5de9b2dc-6516-4bc4-98f3-26ae2bb84c76
  • PR check IDs:
    • clickbench_2056_1789120607
    • clickbench_2062_1789120606
    • clickbench_2068_1789120607
    • tpch_adapted_1_official_2079_1789120607
    • tpch_adapted_1_official_2090_1789120607
    • tpch_adapted_1_official_2128_1789120607

…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
@valerypetrov
valerypetrov force-pushed the feature/optimize-merge-smallparts branch from bbf56ce to fb8fc8a Compare September 10, 2026 07:21
… 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
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. labels Sep 10, 2026
…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
@Michicosun
Michicosun added this pull request to the merge queue Sep 11, 2026
Merged via the queue into ClickHouse:master with commit 9742676 Sep 11, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 11, 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-improvement Pull request with some product improvements 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.

Command for targeted merging of small parts in a partition

4 participants