Skip to content

Reject REPLACE/MOVE/DETACH PARTITION with pending lightweight-update patches in plain MergeTree - #107386

Merged
Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-tree-replace-partition-drops-patch-parts
Jun 23, 2026
Merged

Avogar merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-merge-tree-replace-partition-drops-patch-parts

Conversation

@groeneai

@groeneai groeneai commented Jun 13, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fix silent data loss on plain (non-replicated) MergeTree when REPLACE PARTITION, MOVE PARTITION, DETACH PARTITION, or DETACH PART is run on a partition that still has unapplied lightweight UPDATE patches. These operations now reject the command (as ReplicatedMergeTree already does), pointing to ALTER TABLE ... APPLY PATCHES, instead of silently reverting the committed update.

Description

A lightweight UPDATE records, per row, the source part's data version in a
separate patch part. Plain StorageMergeTree partition operations clone or keep
only the base data parts and renumber them to new, higher block numbers, while
the pending patch part is left behind. On the next read the renamed base part's
version is above the patch's recorded version, so the patch is dropped and the
committed update is silently reverted (data loss).

Minimal reproducer (returns [5,1] instead of [11,15] before this change):

SET enable_lightweight_update = 1;
CREATE TABLE t (c0 Int) ENGINE = MergeTree ORDER BY tuple()
  SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
INSERT INTO t VALUES (1);
INSERT INTO t VALUES (5);
UPDATE t SET c0 = c0 + 10 WHERE TRUE;        -- [11,15]
ALTER TABLE t REPLACE PARTITION ID 'all' FROM t;
SELECT groupArray(c0) FROM t;                -- was [5,1], now rejected

The same silent revert happened for REPLACE/ATTACH PARTITION FROM another
table whose source partition has pending patches, MOVE PARTITION TO TABLE,
DETACH PARTITION, and DETACH PART.

StorageReplicatedMergeTree already guards exactly these operations with
getPatchPartsVectorForPartition + assertNoPatchesForParts, rejecting them
with an actionable SUPPORT_IS_DISABLED message that points at APPLY PATCHES.
This brings plain StorageMergeTree to the same behavior. DROP PARTITION
stays allowed, matching the Replicated engine (it destroys data by design).

No existing GitHub issue found.

Tested locally on a debug build: new test 03100_lwu_51_replace_partition_pending_patch
fails on master HEAD (the operations silently succeed and the data reverts) and
passes with this change; the existing 03100_lwu_* patch-parts suite (including
03100_lwu_22_detach_attach_patches) and the 00626/00975/01818/02271/02731
partition-op tests are unaffected.

Version info

  • Merged into: 26.6.1.1157

…n MergeTree

A lightweight UPDATE records, per row, the source part's data version in a
separate patch part. Plain StorageMergeTree partition operations clone or keep
only the base data parts and renumber them to new, higher block numbers, while
the pending patch part is left behind. On the next read the renamed base part's
version is above the patch's recorded version, so the patch is dropped and the
committed update is silently reverted (data loss).

Reproducer (returns [5,1] instead of [11,15] before this change):

    SET enable_lightweight_update = 1;
    CREATE TABLE t (c0 Int) ENGINE = MergeTree ORDER BY tuple()
      SETTINGS enable_block_number_column = 1, enable_block_offset_column = 1;
    INSERT INTO t VALUES (1);
    INSERT INTO t VALUES (5);
    UPDATE t SET c0 = c0 + 10 WHERE TRUE;
    ALTER TABLE t REPLACE PARTITION ID 'all' FROM t;
    SELECT groupArray(c0) FROM t;

The same silent revert happens for REPLACE/ATTACH PARTITION FROM another table
whose source partition has pending patches, MOVE PARTITION TO TABLE, DETACH
PARTITION, and DETACH PART.

StorageReplicatedMergeTree already guards exactly these operations with
getPatchPartsVectorForPartition + assertNoPatchesForParts, rejecting them with
an actionable SUPPORT_IS_DISABLED message that points at APPLY PATCHES. This
brings plain StorageMergeTree to the same behavior. DROP PARTITION stays
allowed, matching the Replicated engine (DROP destroys data by design).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. On a debug build, the exact SQL in the PR description returns [5,1] instead of [11,15] 100% of the time on master HEAD (verified via clickhouse local and via the new test against a master-HEAD server). The same revert reproduces deterministically for REPLACE-from-other-table, MOVE PARTITION, DETACH PARTITION, and DETACH PART.
b Root cause explained? Yes. A lightweight UPDATE writes a patch part keyed to each base part's data version. Plain StorageMergeTree replacePartitionFrom/movePartitionToTable/dropPart(detach)/dropPartition(detach) clone or keep only the BASE parts and renumber them to new higher block numbers via insert_increment.get(); the pending patch part is not carried. On read, SourcePartsSetForPatch::getPatchParts does upper_bound(renamed_base.getDataVersion()) over the patch versions; the renamed base version is now ABOVE the patch's recorded version so upper_bound returns end() and the patch is dropped, yielding the pre-update values.
c Fix matches root cause? Yes. The fix rejects the operation at the source when the target partition has unapplied patches, instead of cloning base parts and orphaning the patch. It is the exact guard StorageReplicatedMergeTree already uses for these same four operations (getPatchPartsVectorForPartition + assertNoPatchesForParts), so plain MergeTree reaches parity rather than introducing new behavior. DROP PARTITION is intentionally left allowed (matches Replicated; DROP destroys data by design).
d Test intent preserved / new tests added? New test added: 03100_lwu_51_replace_partition_pending_patch. It asserts each of REPLACE-self / REPLACE-other / MOVE / DETACH PARTITION / DETACH PART is rejected with SUPPORT_IS_DISABLED and the data is preserved, then that APPLY PATCHES followed by REPLACE carries the patched data. No existing test was weakened.
e Both directions demonstrated? Yes. The new test FAILS on master HEAD (the guarded ops silently succeed; clickhouse-test reports "The query succeeded but the server error '344' was expected", and the data reverts to [1,5]/[]) and PASSES with this change (20/20 runs with randomization).
f Fix is general, not a narrow patch? Yes. The CI symptom was REPLACE-from-self only, but I verified the identical orphaned-patch revert in the sibling code paths and widened the fix to all four operations the Replicated engine guards (REPLACE/ATTACH FROM, MOVE, DETACH PARTITION, DETACH PART). DROP is deliberately excluded for parity. This is not a defensive symptom guard: it rejects the unsafe operation at its source with an actionable APPLY-PATCHES message, identical to the established Replicated behavior.

Session id: cron:clickhouse-worker-slot-5:20260613-101000

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CurtizJ @alesapin — could you review this? Plain (non-replicated) MergeTree silently reverts a committed lightweight UPDATE when REPLACE/MOVE/DETACH PARTITION (or DETACH PART) runs on a partition with pending patch parts: the base parts are cloned/renumbered and the orphaned patch is dropped on the next read. This adds the same getPatchPartsVectorForPartition + assertNoPatchesForParts guard that StorageReplicatedMergeTree already applies to these four operations (DROP stays allowed), turning the silent data loss into an actionable APPLY-PATCHES rejection.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e7d2a45]

Summary: ✅


AI Review

Summary
  • The PR makes plain MergeTree reject REPLACE/ATTACH PARTITION FROM, MOVE PARTITION, DETACH PARTITION, and DETACH PART when the source/base parts still have unapplied lightweight UPDATE patch parts, matching the existing StorageReplicatedMergeTree guard and preventing silent loss of already-committed patch data. The previous race finding is fixed in the current code by reading source base parts and source patch parts under one parts-lock snapshot, and I resolved that obsolete thread.
Missing context / blind spots
  • ⚠️ The direct Praktika PR report for e7d2a458fbeb843373ba112200bb470a1b0c2bf7 currently contains 0 test rows, so I could not validate a CI pass from that report. A populated CI report would close this gap.
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 13, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
…ES race

In replacePartitionFrom and movePartitionToTable the base parts to clone
and the patch parts were read under two separate parts-lock acquisitions.
A concurrent source-side APPLY PATCHES could materialize and remove the
patch between the two reads, so assertNoPatchesForParts would pass while
the code went on to clone the already-captured pre-patch base parts,
reopening the silent revert the guard is meant to prevent.

Take both the visible source parts and the patch parts under a single
source-side parts lock before deciding whether to reject, matching
StorageReplicatedMergeTree::replacePartitionFromImpl. APPLY PATCHES swaps
parts under the exclusive parts lock, so holding it (exclusive for
replacePartitionFrom, shared for movePartitionToTable) across both reads
makes the two snapshots consistent.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (re-validation after the lock-snapshot fix)

# Question Answer
a Deterministic repro? Yes for the non-concurrent guard (test 03100_lwu_51_replace_partition_pending_patch: REPLACE-self, REPLACE-other, MOVE, DETACH PARTITION, DETACH PART all rejected; data preserved). The concurrent race flagged by the review is a TOCTOU between two lock acquisitions and cannot be triggered on demand without injecting a sleep into the old code; it is closed structurally rather than by a timing test.
b Root cause explained? replacePartitionFrom/movePartitionToTable read the base parts to clone under one parts-lock and then re-read the patch parts under a second parts-lock. A source-side APPLY PATCHES interleaving between the two materializes and removes the patch, so assertNoPatchesForParts sees no patch and passes, while the code clones the already-captured pre-patch base parts. That reopens the silent revert the guard exists to prevent.
c Fix matches root cause? Yes. Both the visible source parts and the patch parts are now read under a single source-side parts lock before deciding whether to reject, mirroring StorageReplicatedMergeTree::replacePartitionFromImpl (SRMT.cpp:9035-9040). APPLY PATCHES swaps parts under the exclusive parts lock, so holding that lock (exclusive in replacePartitionFrom because the PARTITION ALL path needs getVisibleDataPartsVectorUnlocked; shared in movePartitionToTable, as SRMT's MOVE does) across both reads makes the two snapshots consistent and the interleaving impossible.
d Test intent preserved / new tests added? Preserved. 03100_lwu_51 is unchanged and still passes; it asserts both rejection (serverError SUPPORT_IS_DISABLED) and that the committed update survives. No assertion was weakened. The race is a concurrency property of the lock discipline, verified by code inspection against the established SRMT pattern rather than a flaky timing test.
e Both directions demonstrated? The guard direction is demonstrated by the test (fails-before on unfixed master, passes-after with the guard, shown in the prior tick). This commit does not change observable single-threaded behavior; it only narrows the lock window, so 03100_lwu_51 continues to pass: 10/10 no-random, 30/30 with full randomization (--no-parallel-replicas to avoid the single-node parallel_replicas cluster artifact).
f Fix is general, not a narrow patch? Yes. Both clone paths that capture parts and then clone them (replacePartitionFrom, movePartitionToTable) are converted to a single-snapshot read. dropPart/dropPartition are not affected by this race: dropPart re-grabs the active part inside the same merge-blocked critical section and does not clone a stale pre-read pointer (matching SRMT's two-step DETACH PART), and dropPartition already reads its parts and patches under one lockParts() snapshot.

Build ID c2e22ddad2ab12eea9538efd3f193f94722d3154 (changed from ff412c710c3a..., confirmed in the running test server).

Session id: cron:clickhouse-worker-slot-2:20260613-165300

@clickhouse-gh

clickhouse-gh Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.70% 84.70% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 66/67 (98.51%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI fully finished and clean on HEAD e7d2a458fbeb (Finish Workflow SUCCESS, 149 passed / 17 skipped, 0 failures). This is the commit that took a single src_data lock snapshot for both visible source parts and patch parts (addressing the TOCTOU change request). No PR-caused failures. Ready for review.

@Avogar
Avogar added this pull request to the merge queue Jun 23, 2026
Merged via the queue into ClickHouse:master with commit 1b07609 Jun 23, 2026
166 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 23, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.1, 26.2, 26.3, 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

@groeneai

Copy link
Copy Markdown
Collaborator Author

Confirmed pre-existing, not a recent regression: we independently reproduced this silent data loss on a clean master HEAD (commit 40f84e47315) before the fix, so it predates 26.1 through 26.5 as you found. The backport decision is the maintainers' call via pr-must-backport.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 26, 2026
…rtition adoption

Cross-table partition adoption (REPLACE/ATTACH/MOVE PARTITION FROM, CLONE AS,
cross-shard/foreign FETCH) hardlink-clones parts and keeps their content
unchanged, including the persisted _block_number/_block_offset columns that a
source table with enable_block_number_column/enable_block_offset_column
materializes at merge time. Those pairs are the unique row identity Join-mode
patch application depends on (PatchPartInfo.h). Every table numbers blocks from
1, so imported identities collide with the destination's own. A later merge
gathers the duplicates into one part; applying a lightweight-update patch in
Join mode then hits the sorted/unique assertion in applyPatchJoin
(applyPatches.cpp:578, an abort under debug/sanitizer builds) or silently
patches the wrong rows in a release build.

Add MergeTreeData::assertNoPersistedBlockIdentityInAdoptedParts, which throws
SUPPORT_IS_DISABLED when a part being adopted physically stores _block_number
or _block_offset, and call it at every cross-table adoption door in both the
MergeTree and ReplicatedMergeTree engines (replacePartitionFrom,
movePartitionToTable, the to_detached path of fetchPart, movePartitionToShard).
CLONE AS is covered via its lowering to ATTACH PARTITION ALL FROM. The check is
content-based, not settings-based, because destination settings are mutable and
a part without the persisted files serves only name-derived virtuals. Self
REPLACE is exempt because it removes the originals it clones; self ATTACH is not.

This is the same layer and policy as PR ClickHouse#107386, which rejected the sibling
patch-orphaning case. The allocator-vs-content class (RESTORE, detach/restart/
attach, non-empty restore) is a distinct bug left for a follow-up.

Also make a failing FETCH PARTITION clean up after itself. fetchPartition
fetches the parts of a partition concurrently and rethrows only after every
worker has finished, so for a partition holding both a merged identity-bearing
part and a later level-0 part the level-0 worker renames its part into detached
before the merged one is rejected. The statement then failed while leaving that
part behind, which made it attachable and made a retry fail earlier and
differently, on checkIfDetachedPartitionExists with PARTITION_ALREADY_EXISTS.
Record the parts this query itself renamed into detached and, unless the whole
partition was fetched, remove exactly those on the way out. With to_detached a
true result from fetchPart means that call performed the rename under that exact
name, which is what establishes ownership: the entry check is explicitly racy, so
a name alone would not, and a part detached concurrently would have taken a _tryN
name instead. Each part is renamed out of the way and removed on its own,
as DROP DETACHED PARTITION does, so failing on one part neither rolls back nor
skips the others, and a failure after the rename leaves at worst an inert
directory. The staging name carries a unique suffix so a leftover from an earlier
attempt can never collide with, and thereby block, a later one.
This non-atomicity predates the new guard, which is simply the first common way
to reach it.

Adds 03100_lwu_54_attach_foreign_block_ids, covering the REPLACE/ATTACH/MOVE
and FETCH rejections, both single-column sources (_block_offset only and
_block_number only, so each half of the check is exercised on its own), the
allowed column-less and self-REPLACE cases on both engines, the absence of any
surviving part after a rejection (no active part in the rejected CLONE AS
target, no detached part after the rejected FETCH, which pins the ordering the
fetchPart guard relies on), the mixed-partition FETCH leaving behind only a part
that was detached before it ran and staying retryable with the same error, and a
lightweight-update correctness postlude. Pins the two settings off in five existing tests whose
merged sources newly hit the guard under randomization:
00975_move_partition_merge_tree, 02998_projection_after_attach_partition,
03008_s3_plain_rewritable, 03008_s3_plain_rewritable_alter_partition and
03008_azure_plain_rewritable_alter_partition.

Found by the Stress test (arm_tsan) job on PR ClickHouse#108715:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=870fe2bdb1cfda4dbd20fd6fff4f788e074f0736&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#108715

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 26, 2026
…rtition adoption

Cross-table partition adoption (REPLACE/ATTACH/MOVE PARTITION FROM, CLONE AS,
cross-shard/foreign FETCH) hardlink-clones parts and keeps their content
unchanged, including the persisted _block_number/_block_offset columns that a
source table with enable_block_number_column/enable_block_offset_column
materializes at merge time. Those pairs are the unique row identity Join-mode
patch application depends on (PatchPartInfo.h). Every table numbers blocks from
1, so imported identities collide with the destination's own. A later merge
gathers the duplicates into one part; applying a lightweight-update patch in
Join mode then hits the sorted/unique assertion in applyPatchJoin
(applyPatches.cpp:578, an abort under debug/sanitizer builds) or silently
patches the wrong rows in a release build.

Add MergeTreeData::assertNoPersistedBlockIdentityInAdoptedParts, which throws
SUPPORT_IS_DISABLED when a part being adopted physically stores _block_number
or _block_offset, and call it at every cross-table adoption door in both the
MergeTree and ReplicatedMergeTree engines (replacePartitionFrom,
movePartitionToTable, the to_detached path of fetchPart, movePartitionToShard).
CLONE AS is covered via its lowering to ATTACH PARTITION ALL FROM. The check is
content-based, not settings-based, because destination settings are mutable and
a part without the persisted files serves only name-derived virtuals. Self
REPLACE is exempt because it removes the originals it clones; self ATTACH is not.

This is the same layer and policy as PR ClickHouse#107386, which rejected the sibling
patch-orphaning case. The allocator-vs-content class (RESTORE, detach/restart/
attach, non-empty restore) is a distinct bug left for a follow-up.

Also make a failing FETCH PARTITION clean up after itself. fetchPartition
fetches the parts of a partition concurrently and rethrows only after every
worker has finished, so for a partition holding both a merged identity-bearing
part and a later level-0 part the level-0 worker renames its part into detached
before the merged one is rejected. The statement then failed while leaving that
part behind, which made it attachable and made a retry fail earlier and
differently, on checkIfDetachedPartitionExists with PARTITION_ALREADY_EXISTS.
Record the parts this query itself renamed into detached and, unless the whole
partition was fetched, remove exactly those on the way out. With to_detached a
true result from fetchPart means that call performed the rename under that exact
name, which is what establishes ownership: the entry check is explicitly racy, so
a name alone would not, and a part detached concurrently would have taken a _tryN
name instead. Each part is renamed out of the way and removed on its own,
as DROP DETACHED PARTITION does, so failing on one part neither rolls back nor
skips the others, and a failure after the rename leaves at worst an inert
directory. The staging name carries a unique suffix so a leftover from an earlier
attempt can never collide with, and thereby block, a later one.
This non-atomicity predates the new guard, which is simply the first common way
to reach it.

Adds 03100_lwu_54_attach_foreign_block_ids and its ReplicatedMergeTree half
03100_lwu_55_attach_foreign_block_ids_replicated, covering the REPLACE/ATTACH/MOVE
and FETCH rejections, both single-column sources (_block_offset only and
_block_number only, so each half of the check is exercised on its own), the
allowed column-less and self-REPLACE cases on both engines, the absence of any
surviving part after a rejection (no active part in the rejected CLONE AS
target, no detached part after the rejected FETCH, which pins the ordering the
fetchPart guard relies on), the mixed-partition FETCH leaving behind only a part
that was detached before it ran and staying retryable with the same error, and a
lightweight-update correctness postlude. Pins the two settings off in five existing tests whose
merged sources newly hit the guard under randomization:
00975_move_partition_merge_tree, 02998_projection_after_attach_partition,
03008_s3_plain_rewritable, 03008_s3_plain_rewritable_alter_partition and
03008_azure_plain_rewritable_alter_partition.

The new coverage is split across two files, and four of the five pinned tests
carry no-flaky-check, because the flaky check runs each changed test 50 times
with the thread fuzzer enabled and fails any single run over 180s. The fuzzer
adds a per-statement cost that dominates these tests: the combined adoption test
measured 0.4s without it and 130s with it, on a 93-statement file whose queries
are individually trivial, and the four object-storage and 10M-row tests were
already 14-21s each without it. Neither the assertions nor the fixtures change:
the split preserves all 68 non-boilerplate statements, all 12 expected-error
markers and all 14 reference lines in order, and the two halves measure 60s and
62s under the fuzzer. no-flaky-check is used rather than the long tag because it
narrows only the flaky check, leaving the Fast test and coverage jobs untouched.

Found by the Stress test (arm_tsan) job on PR ClickHouse#108715:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=870fe2bdb1cfda4dbd20fd6fff4f788e074f0736&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#108715

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-tree-replace-partition-drops-patch-parts

Reject REPLACE/MOVE/DETACH PARTITION with pending lightweight-update patches in plain MergeTree
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 pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants