Skip to content

Do not leave parts on disk when TRUNCATE, DROP PARTITION or MOVE PARTITION fails to commit - #121708

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-truncate-rollback-leaves-empty-part-120910
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-truncate-rollback-leaves-empty-part-120910

Conversation

@groeneai

@groeneai groeneai commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120910

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a MergeTree table failing to load with Logical error: Part ... intersects previous part ... after a TRUNCATE TABLE, DROP PARTITION, DROP PART or MOVE PARTITION TO TABLE that failed while committing. Such a statement left its empty covering part on disk under its permanent name, and a later merge then produced a same level part over a wider block range, which the part loader rejects. A MOVE PARTITION TO TABLE whose destination commit failed also left the moved parts there, so reloading that table brought back rows the statement had not moved.

Description

On 26.9, a TRUNCATE TABLE on a MergeTree table that fails while committing leaves its empty covering part on disk under its final name, and the table then fails to attach with Logical error: Part all_1_8_1 intersects previous part all_1_1_1, so the server does not start. MOVE PARTITION TO TABLE leaks the same way: in the destination if its commit fails, in the source if a later one does.

Root cause: StorageMergeTree covers the parts it removes with empty parts one level above them, renamed to their final names before committing. MergeTreeData::Transaction::commit() is not atomic across parts and can throw; rollback() moved the parts out of the working set but never renamed them back, leaving no rollback marker on disk. A later merge then produces a same level part over a wider block range, which PartLoadingTree::add rejects.

The change records each part's directory before the rename and, in rollback(), renames the part out of its permanent name into a free tmp_rollback_ directory, which the loader skips. It does not rename back to the recorded directory, which another statement may own by then. On object storage, a part whose storage transaction is not committed has no directory yet; that transaction is undone instead, removing its uploaded blobs. The undo is opt-in per caller (setUndoRenamesOnRollback), because a rename may only be undone while the parts are still private to the transaction. On the replicated INSERT path the part is published in Keeper before commit() runs, which can still throw, so there the permanent directory is what a restart recovers from. Replicated callers, merges and mutations are therefore unchanged and keep that leak, as does the non-atomicity noted in StorageMergeTree.cpp since 2020: a source-side failure leaves the destination committed.

Reported by @ alexey-milovidov in #120910 (comment), failing job https://github.com/ClickHouse/ClickHouse/actions/runs/35705130932/job/106713077937. Issue: #122212.


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

groeneai and others added 2 commits September 23, 2026 05:37
…ITION fails to commit

StorageMergeTree covers the parts a TRUNCATE, DROP/DETACH PART, DROP/DETACH
PARTITION or MOVE PARTITION TO TABLE removes with empty parts one level above
them. renameAndCommitEmptyParts renames those parts to their final names before
committing the transaction, because renaming is IO bound and must not hold the
parts lock.

MergeTreeData::Transaction::commit() is not atomic across parts: it commits each
part's storage transaction in a loop, and that loop, getActivePartsToReplace,
addNewPartAndRemoveCovered and removal_locks.store() can all throw. rollback()
then moved the parts out of the working set but never renamed them back, so a
commit that failed left a part that was never committed on disk under a
permanent name, with no txn_version.txt marker (the tid is non-transactional, so
the RolledBackCSN store is deferred and never reaches the disk).

A later merge of the still active level 0 parts produces a part of the same
level over a wider block range. MergeTreePartInfo::contains requires a strictly
greater level when the block ranges differ, so the two parts neither contain one
another nor are disjoint, and the next part load throws

  Part all_1_8_1 intersects previous part all_1_1_1

out of PartLoadingTree::add. The table cannot be loaded and the server aborts on
startup.

Record the directory each part had before renameParts() moved it, and rename
those parts out of it in rollback(). The record and the undo are opt-in per
caller (setUndoRenamesOnRollback), because a caller is only allowed to undo a
rename while its parts are still private to the transaction. On the replicated
INSERT path the part is published in Keeper before Transaction::commit() runs and
commit() can still throw after that, so there the permanent directory is the
recovery path a restart needs: renaming it back would leave Keeper referencing a
part this replica no longer has. Every replicated caller, every merge and every
INSERT therefore keeps today's behaviour byte for byte and allocates nothing new.

By the time ~Transaction runs the undo, the callers have already released the
temporary directory holder and the operation mutex: all three callers of
renameAndCommitEmptyParts declare the transaction before they take the operation
mutex and before they bind the holders, and reverse order destruction frees both
of those first. A statement that was waiting on the operation mutex can cover
the same parts, derive the same block range and level, and legitimately own the
recorded tmp_empty_<name> directory. The undo therefore does not target the
recorded name at all: it renames the part to a free tmp_rollback_ directory,
which nothing else in the tree creates or claims. Reordering the declarations is
not an alternative, because the comment above each of them forbids it:
rollback() takes the parts lock itself and could deadlock in a destructor. The
invariant the fix needs is only that the part does not keep a permanent name:
loadDataParts skips any directory whose name starts with tmp, and
clearOldTemporaryDirectories reaps it. remove_new_dir_if_exists stays false, so
the undo can never delete a directory another statement owns, and a failure of
any kind falls through to the per-part log and continue.

The same leak exists on the merge, mutation and replicated-commit paths and is
not addressed here.

Co-Authored-By: Claude Opus 5 <[email protected]>
Condense the failpoint and setUndoRenamesOnRollback() declaration docs, drop the design rationale above the tmp_rollback rename (it is in the commit message) and the self-evident member comment.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Before opening this PR I ran an independent cold review of the resulting code plus a second-model
adversarial pass, and adjudicated every finding against the measured evidence. Findings and verdicts:

# Finding Verdict
❌ The reverse rename in Transaction::rollback() ran after the statement had already released its temporary-directory claim, so a concurrent TRUNCATE/DROP PARTITION covering the same part could take the deterministic tmp_empty_<name> first, and the permanently named part survived. Agreed, fixed. Raised twice, and correctly: handling the collision still left a race between the existence check and the move. The undo therefore no longer targets the recorded name at all, it renames the part to a fresh tmp_rollback_* name, a prefix nothing else in the tree ever creates or claims, so no competing creator is left to race. remove_new_dir_if_exists stays false.
❌ The PR title and changelog entry named only TRUNCATE/DROP PARTITION/DROP PART, although the change also covers MOVE PARTITION TO TABLE, whose consequence is different: reloading the destination brought back rows the failed statement had not moved. Agreed, fixed. Title and entry now name it, and the second block of the new test asserts it.
❌ A Related: line for the reported failure was left inside the template's HTML comment, so the provenance was invisible. Agreed, fixed.
❌ The doc comment for the new setUndoRenamesOnRollback() still promised that rollback renames the parts back to where renameParts() found them, which stopped being true once the undo switched to a fresh temporary directory. Agreed, fixed. Raised independently by the cold pass and by the second model; the commit message and PR body had already been corrected, the header had not.
⚠️ DataPartStorageOnDiskBase::rename assigns part_dir only after the directory sync guards, so with fsync_part_directory=1 a post-move failure leaves the storage object naming a directory that is no longer there, both guards in the new undo decline to act, and the part is orphaned. Mechanism confirmed step by step, disagreed as this PR's to fix: its first step throws inside renameParts(), one statement before commit(), so the invariant this PR states is not the one broken, and the outcome in that sub-case is identical to master. Recording it rather than acting on it, since I could not reproduce it.
⚠️ A source-side commit failure in MOVE PARTITION TO TABLE leaves the destination parts committed, so the rows can exist in both tables. Disagreed for this PR: the destination commit ran to completion there, so it cleared its own rename record and the new code cannot participate. The dest-before-src ordering is untouched here and reachable identically without this change.
⚠️ The new test cannot exercise the source-side opt-in of MOVE PARTITION TO TABLE, and could therefore not detect a broken source rollback. Disagreed in part. The gap is real and deliberate: the destination commit always precedes the source one, so an armed failpoint can never reach the source commit from a functional test, and the framework has no ordinal mode. But there is no separate source rollback to break, rollback()'s undo is one loop with no per-table branch, so the only source-specific element is the one-line opt-in.
💡 setUndoRenamesOnRollback() silently records nothing if called after renameParts(). Agreed as a nit, documented in the doc comment. A renameParts(bool) parameter was rejected as touching every caller in the tree for a footgun one sentence closes.
💡 The undo remains best effort: a genuine IO error on the rename is logged and the statement's original error is preserved. By design. remove_new_dir_if_exists is false, so the undo can never delete a directory another statement owns, and every disk touch sits in a per-part try.
💡 The helper that picks the temporary name gives up after ten candidates and returns the tenth even when it exists, so ten accumulated leftovers for one part name would defeat the undo. Left as is. The rename then fails and is logged, which is exactly the behaviour before this change, and each leftover is already eligible for removal the moment it is created.
💡 A crash between the rename and the undo still leaves a permanently named part, which on restart covers its level 0 source and silently applies part of the failed statement. Unchanged from before this PR, in both the window and the outcome, and not closable without a write-ahead record of the rename. Nothing here claims crash atomicity.
💡 The opt-in's doc comment states that no caller may pass a part from detached/, because the undo runs before rollback() classifies detached parts by their current directory, but nothing asserts it. Agreed as a nit, left as documentation. The property holds for all three call sites and is structural rather than incidental. Named here so that a fourth opt-in is added with the constraint in view.
💡 The same leak shape exists on two sibling paths that are not covered: the merged part of a background merge, and REPLACE/ATTACH PARTITION FROM, which renames each part as it is added rather than in one deferred pass. Out of scope, deliberately, and named rather than left implicit. The merge, mutation and replicated-commit residual is stated in the PR description. REPLACE PARTITION cannot be reached by this mechanism at all: it renames inside renameTempPartAndReplace with need_rename = false. Neither is a regression here, the flag defaults to off. No follow-up promised, because I measured neither of them.
💡 The undo asks the part storage for the temporary name through the storage-level helper rather than the part-level wrapper used elsewhere, and a second-model pass separately proposed dropping the call parentheses from the method names in the new doc comment. Both noted and not applied. The two name helpers differ only by a guard for projection parts, which cannot apply here. On the comment style, this header already writes 'if commit() is called' and 'Reverts the changes made by grabOldParts()', and the same spelling appears in about a hundred comments under src/Storages/MergeTree.

Both directions were measured on Build-ID-distinct binaries rather than argued: with the opt-ins intact
and only the undo removed, the TRUNCATE block reproduces the reported Part all_1_3_1 intersects previous part all_1_1_1 and the server then cannot be restarted at all, and the MOVE PARTITION block
returns 3 rows from the destination after a reload instead of 0. Replacing the exists() durability
probe with hasActiveTransaction() leaks 2 of 3 parts, which is why the probe measures the disk. 50 of
50 randomized runs of the new test pass.

@clickhouse-gh clickhouse-gh Bot closed this Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, on demand, no randomization and no restart needed: 3 level 0 parts, SYSTEM ENABLE FAILPOINT merge_tree_transaction_fail_after_empty_part_rename, TRUNCATE (rejected with FAULT_INJECTED), OPTIMIZE FINAL, DETACH + ATTACH. 50/50 runs green with randomized settings on.
b Root cause explained? Yes. The empty covering parts are renamed to their final names before Transaction::commit(), that commit is not atomic across parts and can throw in four places, and rollback() left them under those names with no txn_version.txt marker on disk. A later merge makes a same level part over a wider block range, which PartLoadingTree::add rejects because MergeTreePartInfo::contains needs a strictly greater level when the ranges differ.
c Fix matches root cause? Yes. The leak is "renamed to a permanent name, never committed, never moved back out of it", and the fix renames exactly those parts out of that name on the rollback path, into a fresh tmp_-prefixed directory the part loader skips. No relaxed invariant in MergeTreePartInfo::contains, no guard at the consumer, no widened bound.
d Test intent preserved / new tests added? New test 05238_rollback_renames_empty_parts_back, no existing test weakened. Two blocks with different failure tokens: TRUNCATE reddens on Part ... intersects previous part ..., MOVE PARTITION TO TABLE on a wrong row count. It asserts row counts rather than directory names, so it is not coupled to which temporary name the undo picks.
e Both directions demonstrated? Yes, nine Build-ID-distinct binaries across three rounds. Removing only the undo block reproduces Part all_1_3_1 intersects previous part all_1_1_1, aborts the server and then prevents it from restarting at all; removing either opt-in reddens only its own block, proving the two arms independent; with the fix the permanently named level 1 leftover count is 0 instead of 3, and the rejected durability predicate leaks 2 of 3 parts.
f Fix is general across code paths? Yes, by closed census rather than sampling: the three opt-in calls cover all four statements that build empty covering parts (TRUNCATE, DROP/DETACH PART, DROP/DETACH PARTITION, MOVE PARTITION TO TABLE), and the undo is one shared loop, observed reached from both producers. The other renameParts() callers are deliberately left alone: on the replicated INSERT path the part is published in Keeper before commit() runs and commit() can still throw after that, so there the permanent directory is the recovery path a restart needs.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers are not applicable, the change moves directories and reads no columns. The dimensions that do exist are covered: both producers, both disk regimes (on a local disk all three recorded renames are durable and all three leak without the fix; on object storage only the committed one is durable and exactly one leaks, still enough for the intersection), and both consumer message variants.
h Backward compatible? (maintainer-approved exception only) Yes, nothing to be compatible with: no setting added or changed, so no SettingsChangesHistory.cpp entry, and no on-disk format, part name format, version gate or experimental flag. The directory the undo leaves behind matches the loader's tmp skip and both temporary-directory cleanup prefix sets, and every caller that does not opt in is byte for byte unchanged.
i Invariants and contracts preserved? The invariant added is that an empty covering part occupies a permanent directory only if its transaction committed. The undo runs before rollback() takes the parts lock, preserving the no-IO-under-the-parts-lock contract stated on renameParts(); every disk touch is inside a per-part try, including the existence probe, because DiskLocal rethrows EACCES/EIO/ESTALE; remove_new_dir_if_exists is false, so the undo can never delete a directory anything else owns; and no lock or transaction declaration was moved or reordered.

Session id: cron:clickhouse-impl-slot-4:20260923-041200

@clickhouse-gh clickhouse-gh Bot reopened this Sep 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0ec39fb]

Summary: ❌

job_name test_name status info comment
Code Review DROPPED

LLVM Coverage Report

Measured on commit 0ec39fb.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.80% 79.70% -0.10%

Changed lines: Changed C/C++ lines covered: 47/51 (92.16%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 23, 2026
@groeneai
groeneai requested review from CurtizJ and azat September 23, 2026 06:38
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 74fb1f1

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
Performance Comparison (arm_release, master_head, 4/6) dashboard-verdict gate: job summary 3 too long; 1 confirmed regression(s) on the performance dashboard, while the shard's own report calls no query slower #121090 (mine, open), with #121189 (mine, open)
Mergeable Check praktika rollup of the row above #121090 (mine, open)
PR praktika rollup of the row above #121090 (mine, open)

Shards 1/6, 2/6, 3/6, 5/6 and 6/6 all passed on this head, so this is a single-shard
dashboard verdict, not a measured regression from this diff.

Session id: cron:our-pr-ci-monitor:20260923-190314

groeneai and others added 3 commits October 7, 2026 12:25
…ck-leaves-empty-part-120910

# Conflicts:
#	src/Common/FailPoint.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp
The test arms a failpoint, which the failpoint_tests_are_isolated style
check now requires to be tagged no-parallel and no-fasttest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
At that point the part is under its permanent name, not under the
directory renameParts() recorded, so the message no longer names the
recorded directory.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
/// A part storage transaction that has not been committed still holds its `moveDirectory`,
/// so on an object storage disk the new directory is not there; on a local disk the move
/// already ran.
if (!part->getDataPartStorage().exists())

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.

On object-storage disks, exists()==false here is the normal "rename is still buffered in the part-storage transaction" case, not proof that rollback has nothing left to clean up. rollback() then drops the part from the working set without ever calling undoTransaction(), even though the empty-part path already documents at src/Storages/MergeTree/MergeTreeData.cpp:7926 that skipping undoTransaction() strands uploaded blobs when the final directory never materializes.

That means a multi-part TRUNCATE / DROP PARTITION / source half of MOVE PARTITION TO TABLE can still leak the later empty parts on object storage once the first commitTransaction() succeeds and a later one throws. I think rollback needs to undoTransaction() for parts whose storage is still active, and reserve the tmp_rollback_* rename path for parts whose storage transaction has already committed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 0ec39fb: a rolled back part with no directory yet now has its storage transaction undone (keyed on the directory, since a local disk's transaction stays active after the move), and 05238_rollback_removes_uncommitted_part_blobs checks through system.blob_storage_log that no uploaded blob is left behind.

…k yet

On an object storage disk a part's directory and metadata only appear when
its storage transaction commits, while its blobs are uploaded as the files
are written. When `Transaction::commit()` fails after committing the storage
of some parts, the remaining parts were dropped from the working set with
their storage transactions neither committed nor undone, so the blobs they
had already uploaded stayed in the object storage with no metadata pointing
at them.

`rollback()` now undoes the storage transaction of such a part (only for the
callers that opted into undoing renames, whose parts are still private to the
transaction). Measured with a `local_blob_storage` disk, a 3-part TRUNCATE
and the failpoint firing after the first commit: before, 14 non-empty blobs
(two empty compact parts) remained after `DROP TABLE SYNC`; after, none.

The new test checks this through `system.blob_storage_log`: every non-empty
uploaded blob of its own disk must get a successful delete event. With the `undoTransaction()`
call removed it reports 2 leaked blobs (packed parts) in 3 of 3 runs.

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

groeneai commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0ec39fb

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
Code Review infra, not from this PR: GitHub abandoned the job (Job did not finish, GitHub reported [abandoned]). Its check run is still queued with no runner inside a run that has already completed, so it never ran, and the automatic infrastructure retry skips a failed run whose listed jobs did not fail #124479 (mine, open): retries a PR run whose failing jobs GitHub never ran
Mergeable Check, PR rollups, red only because of the row above (Failed: 0, Dropped: 1) #124479 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

The other 148 check runs completed, Finish Workflow is green, and CIDB has no FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261007-230450

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. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant