Skip to content

Refuse REPLACE/ATTACH PARTITION FROM a part whose creating transaction has not committed - #121308

Open
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:refuse-republish-uncommitted-partition-clone
Open

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:refuse-republish-uncommitted-partition-clone

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 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):

ALTER TABLE ... REPLACE PARTITION FROM and ALTER TABLE ... ATTACH PARTITION FROM (and CREATE TABLE ... CLONE AS, which is built on the latter) no longer publish source parts belonging to a transaction that has not committed: a later rollback of that transaction used to leave the destination table holding rows that were never committed. Such an operation is now refused with SERIALIZATION_ERROR and succeeds on retry once the source transaction finishes.

Description

Related: #110494 (reported there) and #105116 (fixed the removal side, left the source side open).

Needs allow_experimental_transactions, so not reachable by default.

With an uncommitted BEGIN TRANSACTION; INSERT INTO src VALUES (42) in flight, a non-transactional ALTER TABLE dst REPLACE PARTITION ID 'all' FROM src succeeded and published that row. A rollback then emptied src but left dst holding the row permanently. ATTACH PARTITION ... FROM and CREATE TABLE ... CLONE AS behaved the same, as did a plain MergeTree source with a ReplicatedMergeTree destination: that destination never holds transactional parts of its own, but the source it clones from can.

Root cause: without a transaction, getVisibleDataPartsVectorInPartition does no MVCC filtering and returns every active part, including one whose creating transaction is still running. replacePartitionFrom clones those with txn = nullptr, so each destination part is created with Tx::NonTransactionalTID: committed and durable on the spot, where the source rollback cannot reach it. movePartitionToTable already enforces this invariant through isCreationCommitted().

Change: a new MergeTreeData::checkPartsCanBeRepublishedNonTransactionally throws SERIALIZATION_ERROR when a part's creation is not committed. It is called on the source parts from StorageMergeTree::replacePartitionFrom and from StorageReplicatedMergeTree::replacePartitionFromImpl, and is not gated on replace (the pre-existing destination-side check is, which is why ATTACH ... FROM had no coverage). The existing Republish branch delegates to it, so the rule has one implementation. On a ReplicatedMergeTree destination, ATTACH PARTITION ALL FROM now validates every source partition before the first is cloned (raised in review), so it cannot publish a subset and then refuse.

Validation: new 05235 fails on the unfixed binary in both oracles and passes 50/50 under settings randomization. The 65 stateless tests covering these commands have an identical failure set before and after.


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

With an uncommitted `BEGIN TRANSACTION; INSERT INTO src ...` in flight, a
non-transactional `ALTER TABLE dst REPLACE PARTITION ... FROM src` succeeded and
published that row into `dst`. Rolling the source transaction back then emptied
`src` but left `dst` holding the row permanently, so a destination table durably
kept rows that were never committed anywhere. `ATTACH PARTITION ... FROM` and
`CREATE TABLE ... CLONE AS`, which are built on the same statement, behaved the
same way. Reachable only with `allow_experimental_transactions` enabled.

`getVisibleDataPartsVectorInPartition` applies `filterVisibleDataParts` only when
a transaction is present; with none it returns every active part, including one
whose creating transaction is still running. `replacePartitionFrom` then clones
those parts with `clone_params.txn = nullptr`, so each destination part is created
with `Tx::NonTransactionalTID` and is committed and durable on the spot, where the
source rollback cannot reach it.

Master already states the invariant this violates, on
`NonTransactionalRemovalKind::Republish` and on `isCreationCommitted()`: data whose
creation is not committed must not be republished somewhere a commit cannot be
taken back. `movePartitionToTable` enforces it. `replacePartitionFrom` checked only
the destination parts it discards, and only when `replace` was true, so the source
parts were never checked at all.

The new `MergeTreeData::checkPartsCanBeRepublishedNonTransactionally` throws
`SERIALIZATION_ERROR` when a part's creation is not committed. It is called on the
source parts from `StorageMergeTree::replacePartitionFrom` and from
`StorageReplicatedMergeTree::replacePartitionFromImpl`, and the existing
`Republish` branch of `checkPartsCanBeRemovedNonTransactionally` now delegates to
it, so the rule has one implementation.

Not gated on `replace`: the pre-existing destination-side check is, which is why
`ATTACH ... FROM` had no coverage, and both statements clone the source
identically. A plain `MergeTree` source with a `ReplicatedMergeTree` destination is
the documented migration direction and leaked the same way, so the replicated path
is fixed too; it needs no `!txn` guard because that destination does not support
transactions, so the query never runs in one.

Not reusing `checkPartsCanBeRemovedNonTransactionally(src_parts, Republish)`
directly, which would have been a one-line change: it also throws when another
transaction holds the part's removal lock. `REPLACE`/`ATTACH ... FROM` never remove
the source parts, so that leg would refuse a legal clone whenever a concurrent
transactional `DROP PARTITION` on the source held the lock, reporting a removal
that is not happening. The creation-committed half is the whole requirement here.

Self-`REPLACE`, where source and destination are the same table, gets no exemption:
republishing an uncommitted part's rows under a committed creation is unsafe even
within one table.

The background `executeReplaceRange` clone is left alone. The initiator runs the
guard before the log entry is created, so executors only ever see committed parts,
and throwing in a replication-queue executor would stall the queue.

One existing message changes, from "Cannot non-transactionally move object ..." to
"... republish ...", because the predicate now serves both callers. No test
asserted the old text.

Validated on a debug build: all four surfaces refused with `SERIALIZATION_ERROR`
and left the destination empty, while the same statements still succeed once the
source transaction commits. The new test fails on the unfixed binary in both of
its oracles. A 65-test sweep of every stateless test mentioning `REPLACE
PARTITION`, `ATTACH PARTITION ... FROM`, `MOVE PARTITION TO TABLE` or `CLONE AS`
has an identical failure set before and after the change, and the new test passes
50/50 with settings randomization.
Drop the sibling-predicate navigation note and the duplicate of the Republish invariant already stated on the enumerator; fold the replicated call site's note into one line.
@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 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two questions this is likely to raise, answered up front:

  • Why is StorageReplicatedMergeTree::replacePartitionFromImpl guarded without a !txn check?
    Because it cannot see a transaction: checkStorageSupportsTransactionsIfNeeded throws for a
    supportsReplication() storage on both of its branches (IInterpreter.cpp:44-60), i.e. with
    throw_on_unsupported_query_inside_transaction on or off, and CREATE TABLE ... CLONE AS routes
    through that same interpreter (InterpreterCreateQuery.cpp:3227-3229).
  • Why is a non-transactional INSERT INTO dst SELECT * FROM src still allowed to read the same
    uncommitted rows?
    Non-transactional reads sit outside MVCC by design, and that is row
    visibility, not part republication. This change is about durability: cloning a part stamps the
    copy Tx::NonTransactionalTID and commits it where the source rollback cannot reach it.
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus an independent
reviewer pass over the resulting code (4 nits, none blocking; bounded: 1 full pass + 1 fix round +
1 delta recheck). No fix round was needed.

# Sev Finding Verdict Evidence / action
1 💡 The new predicate's doc comment does not say why it may be evaluated outside the source parts lock, while the sibling it was extracted from tells the reader its callers hold that lock (MergeTreeData.h:993 vs :989) AGREE, not blocking Safety verified rather than assumed: the predicate reduces to creation_csn && creation_csn != RolledBackCSN (VersionMetadata.cpp:183-192) and a commit is monotonic, so a part that passes can never become uncommitted before the clone; the reverse race yields only a retryable refusal. The removal-lock leg, which does need the lock, deliberately stayed behind. assertNoPatchesForParts runs in the same lock-free position just below. Left as is
2 💡 05235 bundles four plain MergeTree cases with one ReplicatedMergeTree case, so the zookeeper and no-shared-merge-tree tags that case forces suppress all five in the legs skipping those tags AGREE, not blocking tests/clickhouse-test:3224 (--no-zookeeper, used by the ParallelReplicas leg), :3287, :3166. The main stateless legs default to --zookeeper, so primary coverage is intact; splitting the replicated case into its own file would recover the side legs
3 💡 Only t_republish_src is dropped up front; the five other tables the test creates are not, unlike 05161, 05162 and 05175 AGREE, not blocking All six are dropped at the end, so a clean run self-cleans and repeated runs of the flaky check are unaffected; the exposure is a cascade only after an iteration that already failed
4 💡 The extraction turned a catch-all else if into kind == NonTransactionalRemovalKind::Discard && ... (MergeTreeData.cpp:7323) DROPPED Equivalent for a two-value enum (MergeTreeData.h:973-981), and naming the kind explicitly is the better style for a closed dispatch: a future third kind is forced to decide rather than inherit a default

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-10:20260921-091100

@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% per run, not probabilistic. Session A holds BEGIN TRANSACTION; INSERT INTO src VALUES (42); a non-transactional ALTER TABLE dst REPLACE PARTITION ID 'all' FROM src then publishes the row, and after A's ROLLBACK src is empty while dst keeps count() = 1. New test 05235 fails deterministically on the unfixed binary.
b Root cause explained? Without a transaction getVisibleDataPartsVectorInPartition does no MVCC filtering and returns every active part, including one whose creating transaction is still running. replacePartitionFrom clones those with txn = nullptr, so each destination part gets Tx::NonTransactionalTID and is committed and durable immediately, beyond the reach of the source rollback.
c Fix matches root cause? Yes, at the source: the clone is refused before anything is published, with the retryable SERIALIZATION_ERROR the in-tree Republish doctrine already prescribes for this class. Not a widened bound, a tag, or a guard at a symptom site. Silently filtering the uncommitted parts out of src_parts was rejected: it would copy a partial partition, and REPLACE would drop the destination partition while writing less than the source.
d Test intent preserved / new tests added? New 05235 with five cases: REPLACE, ATTACH, a ReplicatedMergeTree destination, CREATE TABLE ... CLONE AS, and a mandatory in-range control (committed source still succeeds). No existing test weakened or retagged; 05161, 05162 and 05175 stay green on both binaries.
e Both directions demonstrated? Yes, at the ad-hoc and runner level, each arm asserting the server's startup build id. Pristine [ FAIL ], fixed [ OK ], and on the unfixed binary both oracles move: the four SERIALIZATION_ERROR lines are absent AND each destination count is 1 instead of 0, while the control line is byte-identical in both arms.
f Fix is general across code paths? All five cross-table clone/move carriers have a disposition. Fixed: both replacePartitionFrom implementations (so CLONE AS, which lowers to one, is covered and tested as its own surface). Already guarded and now sharing one implementation: StorageMergeTree::movePartitionToTable. Safe by construction: StorageReplicatedMergeTree::movePartitionToTable (source is *this, both ends replicated). Deliberately not guarded: the background executeReplaceRange clone, since the initiator checks before the log entry exists and throwing in a replication-queue executor would stall the queue. Out of scope: ATTACH/FETCH from detached/.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: the predicate reads part version metadata, never column types. The dimensions that exist are covered: replace true and false, is_all true and false, plain and replicated destination, empty src_parts (a no-op). Both sides of the value dimension are exercised: uncommitted creation refused, committed creation succeeds. A rolled-back creation is also refused, matching MOVE PARTITION TO TABLE.
h Backward compatible? (maintainer-approved exception only) No setting, no SettingsChangesHistory.cpp entry, no format or metadata change, no new error code. Four commands can now fail with a retryable SERIALIZATION_ERROR where they previously published uncommitted data, and succeed on retry once the source transaction finishes. One pre-existing shape is newly refused: a part whose version metadata was left as a .tmp file loads as DummyTID/RolledBackCSN, so its creation is not committed; refusing to clone it is correct and is what MOVE already does.
i Invariants and contracts preserved? The check is read-only, takes no lock and holds none: in StorageMergeTree it runs after the src_parts_lock block is released, like the assertNoPatchesForParts check just below it, so no lock ordering changes. It runs before anything is cloned or published, so a refusal leaves both tables untouched rather than half replaced. The Discard and removal-lock behaviour of checkPartsCanBeRemovedNonTransactionally is preserved exactly; only the reporting order within a Republish batch can change, and both messages are SERIALIZATION_ERROR. Nothing new is persisted, so there is no restart re-entry path.

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [313cc30]

Summary: ✅


AI Review

Summary

This PR adds a source-side creation_tid check before REPLACE / ATTACH PARTITION FROM and CREATE TABLE ... CLONE AS can republish parts into a non-transactional destination, and it fixes the earlier ATTACH PARTITION ALL FROM partial-apply bug on ReplicatedMergeTree. I still do not think it is merge-ready because the sibling SharedMergeTree path appears to remain unguarded: the only new regression test explicitly opts out of --replace-replicated-with-shared because that engine's partition commands do not hit these checks.

Findings
⚠️ Majors
  • [src/Storages/StorageReplicatedMergeTree.cpp:9429] The new invariant is only wired into StorageMergeTree / StorageReplicatedMergeTree, while the new regression test says --replace-replicated-with-shared rewrites the statement to an engine “whose partition commands this check does not reach” (tests/queries/0_stateless/05235_replace_attach_partition_from_uncommitted_source.sh:6-7). That means the SharedMergeTree variant can still non-transactionally republish rows from an uncommitted source part, so the PR's promise that REPLACE / ATTACH / CLONE AS now refuse this leak is still false for that supported mode.
    Suggested fix: land the equivalent checkPartsCanBeRepublishedNonTransactionally call in the SharedMergeTree partition-copy path (or land the private counterpart in lockstep and mention that here), then drop the no-shared-merge-tree exclusion so the regression is covered in those jobs too.
Final Verdict
  • Status: ⚠️ Request changes
  • Wire the same source-part guard into the SharedMergeTree partition-copy implementation, and cover that path instead of skipping it with no-shared-merge-tree.

LLVM Coverage Report

Measured on commit 313cc30.

Metric Baseline Current Δ
Lines 88.00% 88.00% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · 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 21, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 21, 2026
`StorageReplicatedMergeTree::replacePartitionFrom` expands `ATTACH PARTITION ALL
FROM` into an unordered set of partition ids and calls `replacePartitionFromImpl`
once per id. Each of those calls commits its own destination parts and creates its
`REPLACE_RANGE` log entry before the next id is looked at, so the republish check
this branch added inside `replacePartitionFromImpl` could only refuse the partition
it was called for: with one committed and one uncommitted partition in the same
source, the statement published whichever committed partitions it reached first and
only then threw `SERIALIZATION_ERROR`. Measured on a ten-partition source, the
destination was left holding partitions 5, 6, 7 and 9; the subset varies, because
the id set is unordered.

Check every source partition in `replacePartitionFrom` before the loop starts, so a
refusal cannot leave part of the statement applied.

The check inside `replacePartitionFromImpl` stays, and is the authoritative one: the
pre-pass releases the source parts lock before the loop re-reads each partition, so
without it a transaction inserting into the source in between would still be cloned.
The pre-pass is what makes the ordinary case, where the uncommitted part is already
there when the statement starts, refuse without publishing anything. Closing the
remaining window would require the whole multi-partition statement to be atomic,
which it has never been: `assertNoPatchesForParts`, the empty-source check and
`CANNOT_ASSIGN_ALTER` can all throw from the same loop today.

One ordering change is visible to users: when one source partition holds an
uncommitted part and another has unapplied patches, the error is now
`SERIALIZATION_ERROR` instead of whichever condition the first visited partition hit.

`StorageMergeTree::replacePartitionFrom` needs no equivalent change. It already
collects every source part for `ATTACH PARTITION ALL FROM` into one vector and checks
them in a single call before it clones anything.

Reported by the AI review on ClickHouse#121308.
@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 313cc309f with master 69ee3e445 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 9449c3a89; 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

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

Job report

src_parts_to_republish.insert(src_parts_to_republish.end(), partition_parts.begin(), partition_parts.end());
}
}
src_data.checkPartsCanBeRepublishedNonTransactionally(src_parts_to_republish);

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.

This only fixes the plain/ReplicatedMergeTree entrypoints. The new regression test immediately opts out of --replace-replicated-with-shared because that rewrite lands on an engine “whose partition commands this check does not reach” (tests/queries/0_stateless/05235_replace_attach_partition_from_uncommitted_source.sh). That means the SharedMergeTree variant can still non-transactionally republish rows from an uncommitted source part, so the PR's REPLACE / ATTACH / CLONE AS contract is still false in that supported mode. Please wire the same checkPartsCanBeRepublishedNonTransactionally guard into the SharedMergeTree partition-copy path (or land the private counterpart in lockstep) and drop the no-shared-merge-tree exclusion so the regression is covered there too.

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.

Verified, and the call you ask for cannot be added from this repository. Measured on this tree at 313cc309:

  • MergeTreeData::replacePartitionFrom is pure virtual (MergeTreeData.h:2004) and has exactly two overrides here: StorageMergeTree.h:324 and StorageReplicatedMergeTree.h:924. Both now run the guard, the replicated one over every source partition before the first clone.
  • StorageSharedMergeTree has no definition in this repository: no file matches StorageSharedMergeTree*, the header <Storages/StorageSharedMergeTree.h> is not present, and every reference to the class sits behind #if CLICKHOUSE_CLOUD (src/Interpreters/MergeTreeTransaction.cpp:16-18, src/Storages/System/StorageSystemReplicas.h:14-15). Its override of that pure virtual is in the closed-source tree, so I can neither add the call nor test whether it already refuses, and I will not assert either way about its current behavior.
  • The predicate was written for that reuse: checkPartsCanBeRepublishedNonTransactionally is a public MergeTreeData member (MergeTreeData.h:995), not a private helper of either storage, so the counterpart there is one call on the source parts before the clone. I am putting the gap on the record here for whoever owns that engine.

On dropping no-shared-merge-tree: it is honored in two places, --cloud mode (tests/clickhouse-test:3164-3169) and --replace-replicated-with-shared (:3285-3291), and neither flag is passed by any workflow in this repository (zero hits under ci/ and .github/). In --cloud mode this test is already skipped by its zookeeper tag two lines below, so the tag only decides anything under the engine rewrite, which maps ReplicatedMergeTree to SharedMergeTree (:293). Dropping it adds no coverage here, and unless that closed-source override already refuses it turns the replicated-destination cases red there. I would rather the exclusion be dropped by the change that adds the call than ship a knowingly red test; 260 stateless tests carry the tag for the same reason.

I did consider splitting the file so the four plain MergeTree cases keep running under the rewrite, which does not touch them. That adds a second file for paths this repository's CI already runs, including the s3-storage job, so I left it as one file.

@tuanpach tuanpach self-assigned this Sep 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Dear @tuanpach, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@clickhouse-gh clickhouse-gh Bot added comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

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-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... 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.

2 participants