Skip to content

Drop empty MergeTree parts in one batch instead of rescanning outdated parts per part - #129845

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/batch-empty-parts-drop
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/batch-empty-parts-drop

Conversation

@groeneai

@groeneai groeneai commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118193

Changelog category (leave one):

  • Performance Improvement

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

Improve the performance of TRUNCATE and of the removal of empty parts in MergeTree tables with many partitions: the outdated parts are now scanned once per batch of dropped empty parts instead of once per part, so the cost grows linearly with the number of partitions instead of quadratically.

Description

MergeTreeData::clearEmptyParts called dropPartNoWaitNoThrow once per empty part, and StorageMergeTree ran a full clearOldPartsFromFilesystem after each one. Every such call walks all outdated parts under the parts lock in grabOldParts (with a getCoveredOutdatedParts lookup for each empty one), and none of the empty parts outdated by the previous iterations is due yet (old_parts_lifetime). A TRUNCATE of a table with E partitions leaves E empty parts, so it made E scans over a growing set of outdated parts.

This is what kept the server from stopping in La Casa Del Dolor (amd_msan) on #118193 (report): DDLWorker::shutdown waited for an ON CLUSTER TRUNCATE of a table partitioned by moduloOrZero(Float64, 250) that was still inside clearEmptyParts. The same loop was caught on master in La Casa Del Dolor (amd_debug).

The virtual becomes dropPartsNoWaitNoThrow(const Strings &). StorageMergeTree outdates each part as before and runs one cleanup for the batch. StorageReplicatedMergeTree keeps its per-part body (one DROP_PART log entry each, no local scan). clearUnusedPatchParts uses the same call.

Validation (debug build, clickhouse local, TRUNCATE of N one-row partitions, N = 1000/2000/4000/8000/16000): 0.8/2.2/6.4/23.7/40.9 s before, 0.7/1.2/2.3/4.6/9.9 s after. A second TRUNCATE of 1000 partitions next to the N outdated empty parts went from 1.2-10.4 s to a flat 0.6 s. The new test checks the PartsLocks count of a 50-partition TRUNCATE (104 before, 55 after) and that the TRUNCATE still runs the cleanup over the parts it dropped; it fails on master and passed 50/50 with randomized settings.


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

groeneai and others added 3 commits November 6, 2026 20:53
…d parts

`MergeTreeData::clearEmptyParts` called `dropPartNoWaitNoThrow` once per
empty part, and `StorageMergeTree::dropPartNoWaitNoThrow` ran a full
`clearOldPartsFromFilesystem` after outdating each part. Each of those calls
walks every outdated part under the parts lock in `grabOldParts` (with a
`getCoveredOutdatedParts` lookup for each empty one). The empty parts
outdated by the previous iterations are not due for removal
(`old_parts_lifetime`), so dropping E empty parts revisits them E times:
the work is quadratic in the number of empty parts, plus E times the
outdated parts left by earlier operations.

TRUNCATE of a table with one partition per value creates one empty part per
partition, so it hit this directly: `La Casa Del Dolor (amd_msan)` on ClickHouse#118193
was force-killed at shutdown while `DDLWorker::shutdown` waited for an ON
CLUSTER TRUNCATE inside `clearEmptyParts`, and the same loop was seen on
master in `La Casa Del Dolor (amd_debug)`.

Replace the virtual with `dropPartsNoWaitNoThrow(const Strings &)`:
`StorageMergeTree` outdates each part exactly as before and runs one cleanup
for the batch; `StorageReplicatedMergeTree` keeps its per-part body (one
DROP_PART log entry per part, no local scan). `clearUnusedPatchParts` uses
the same call.

Debug build, `clickhouse local`, TRUNCATE of a table with N one-row
partitions (N = 1000/2000/4000/8000/16000): before 0.8/2.2/6.4/23.7/40.9 s,
after 0.7/1.2/2.3/4.6/9.9 s. A following TRUNCATE of 1000 new partitions
next to those N outdated empty parts took 1.2 s to 10.4 s before (linear in
N) and a flat 0.6 s after. The parts lock is taken N + 5 times instead of
2N + 4.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed parts

The `PartsLocks` bound alone stays green if the single cleanup after the
batch drop is removed. With the table's background cleanup stopped, only that
cleanup can mark the outdated empty parts, so require that none of them is
still in the `NOT_ATTEMPTED` removal state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`SYSTEM STOP CLEANUP` is checked only when a cleanup iteration starts, so the
iteration scheduled at table startup can still run its parts pass after the
TRUNCATE and mark the outdated empty parts itself. Pin
`merge_tree_clear_old_parts_interval_seconds` so that such an iteration skips
the parts pass, and only the TRUNCATE's own cleanup can mark them.

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

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)
# Finding Verdict
⚠️ 1 The PartsLocks < 750 bound does not show that the single batch cleanup still runs Agreed: the test now stops the background cleanup and checks that every part the TRUNCATE outdated was seen by its cleanup (removal_state). An exact lock count was not used: a concurrent scan skips one lockParts.
⚠️ 2 SYSTEM STOP CLEANUP does not stop a cleanup iteration already in flight, which could mark the parts itself Agreed: the test pins merge_tree_clear_old_parts_interval_seconds, as 04057_transaction_version_metadata_lifecycle does.
💡 3 Renaming the pure virtual changes the signature for out-of-tree overriders Noted: kept the single batch virtual.

@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local, debug, TRUNCATE of 8000 one-row partitions: 23.7 s before, 4.6 s after; the parts lock is taken 16004 vs 8005 times. Same-commit A/B binaries.
b Root cause explained? clearEmptyParts dropped each empty part with its own clearOldPartsFromFilesystem, and each one walks all outdated parts in grabOldParts. The previously outdated empty parts are not due yet, so E empty parts cost E scans over a growing set.
c Fix matches root cause? Yes. The parts are outdated one by one as before and the cleanup runs once per batch. No timeout or cancellation workaround.
d Test intent preserved / new tests added? New 05498_clear_empty_parts_many_partitions: PartsLocks of a 500-partition TRUNCATE is 1004 before and 505 after, threshold 750; with the background cleanup stopped, no dropped part may still be unseen by a cleanup (removal_state), so deleting the batch cleanup fails it (500 unseen); the cleanup interval is pinned so that an in-flight background iteration cannot mark the parts either. No existing test changed.
e Both directions demonstrated? Yes. The test fails 8/8 on master (PartsLocks line), fails 5/5 with the batch cleanup removed (removal_state line), and passes 50/50 with randomized settings plus 10/10 without.
f Fix is general across code paths? Both callers (clearEmptyParts, clearUnusedPatchParts) and both overriders changed, so every StorageMergeTree caller (TRUNCATE, DROP PART/PARTITION, ALTER, startup, cleanup thread) gets it. ReplicatedMergeTree has no local scan per part and keeps its per-part DROP_PART entries.
g Fix generalizes across inputs (params/datatypes/wrappers)? 0, 1 and many parts; parts removed concurrently are skipped as before; old_parts_lifetime 0 and 480 give the same end state as before (measured).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change.
i Invariants and contracts preserved? Per-part outdate and deduplication log update are unchanged; each part pointer is released before the cleanup; the covered-parts-first rule lives in grabOldParts, untouched. An exception from part k still propagates after k-1 parts.

Session id: cron:clickhouse-impl-slot-41:20261106-202100

@clickhouse-gh

clickhouse-gh Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1d13e05]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) FAIL
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05829_autopr_skip_index_on_read_in_subquery FAIL cidb
05043_autopr_set_source_leaf_steps FAIL cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
04353_text_index_explicit_tokenizer_argument NOT_FAILED cidb
05034_lazy_materialization_column_function_set_capture NOT_FAILED cidb
01710_projection_with_mixed_pipeline NOT_FAILED cidb
05399_autopr_plan_without_parallel_replicas NOT_FAILED cidb

AI Review

Summary

The PR batches empty-part and unused-patch-part drops so StorageMergeTree scans outdated parts once per batch, preserving per-part removal, deduplication updates, and replicated DROP_PART entries. No actionable findings. The supplied before/after measurements support the performance improvement. The focused regression test checks both the reduced PartsLocks count and that cleanup still runs; it passes at the current PR head in Fast test and passed all 50 debug flaky-check runs on the preceding revision.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 6, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim @CurtizJ, could you review this and add the can be tested label so CI runs? clearEmptyParts ran a full outdated-parts cleanup after every dropped empty part, so a TRUNCATE of a table with many partitions was quadratic and kept DDLWorker::shutdown waiting in La Casa Del Dolor (amd_msan); StorageMergeTree now outdates the whole batch and runs one cleanup.

@clickhouse-gh clickhouse-gh Bot added can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 6, 2026
@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 70e53b6

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
Fast test / 05457_dictionary_remote_clickhouse_invalidate_query not from this PR (it changes only how MergeTreeData::clearEmptyParts drops empty parts, plus test 05498): the test was added to master by #129336 a few hours earlier and hit the 60 s Fast test timeout; 2 of its first 31 Fast test runs timed out the same way, the other one on an unrelated PR. This failure dropped the remaining 95 jobs, so this head has no functional test results a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the row above a fix task is created (the same one as above)
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20261107-000004

@groeneai

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05457_dictionary_remote_clickhouse_invalidate_query (Fast test timeout) created: #129879

…y-parts-drop

Resolve the conflict in StorageMergeTree.cpp: master added
detachPartAfterFailedFsync right above dropPartNoWaitNoThrow, which this
branch replaces with dropPartsNoWaitNoThrow. Both are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1d13e05ec with master 93ad15c64 (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

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

Job report

The flaky check runs the test under the thread fuzzer, whose mutex hooks are
compiled in on the debug and release builds. There every part write and every
part drop costs about half a second, so with 500 partitions the INSERT and the
TRUNCATE took about 250 s each in `Stateless tests (amd_binary, flaky check)`
and `Stateless tests (amd_debug, flaky check)`, over the 180 s limit.

The parts lock oracle does not need 500 parts: TRUNCATE takes it 2N + 4 times
before the fix and N + 5 times after it, so 50 partitions with a threshold of
75 keep the same separation (104 against 55).

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

Copy link
Copy Markdown
Member

cc @alexey-milovidov nice to review

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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants