Skip to content

Reject non-transactional removal of parts created by uncommitted transactions - #110494

Closed
tiandiwonder wants to merge 3 commits into
masterfrom
fix-nontx-drop-over-uncommitted-part
Closed

tiandiwonder wants to merge 3 commits into
masterfrom
fix-nontx-drop-over-uncommitted-part

Conversation

@tiandiwonder

@tiandiwonder tiandiwonder commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes: https://github.com/ClickHouse/clickhouse-private/issues/64528

Problem

A non-transactional ALTER TABLE ... DROP PARTITION that covers a part inserted by a not-yet-committed transaction fails with a logical error creation_csn is not set while removal_csn is set to 1, which aborts the server in debug and sanitizer builds. Deterministic reproducer: session A runs BEGIN TRANSACTION; INSERT INTO t VALUES (1); and stays open; session B runs ALTER TABLE t DROP PARTITION ID 'all'. This also fires in stress runs of 01169_old_alter_partition_isolation_stress.sh when the query fuzzer moves the DROP PARTITION out of its transaction.

Root cause

The VersionMetadata refactor (d6350c1) made setAndStoreRemovalTID write removal_tid and removal_csn = Tx::NonTransactionalCSN in a single update. A non-transactional removal selects covered parts ignoring MVCC visibility, so it can cover a part whose creation_csn is still unresolved (the creating transaction is running). Persisting removal_csn first violates the write-order invariant that creation_csn is persisted before removal_csn (the pre-refactor isVisible chasserted !had_removal_csn || had_creation_csn), and validateInfo raises the logical error. Only the non-transactional path can reach this state: a transactional remover picks covered parts from its MVCC snapshot and never sees uncommitted parts of other transactions.

Solution

Fail close: reject the non-transactional removal instead of removing data whose fate is not decided yet (removing it would make the creator's COMMIT succeed while its rows are silently gone).

  1. New VersionMetadata::checkNonTransactionalRemovalIsPossible throws SERIALIZATION_ERROR when the part's creation_csn is unresolved and tryGetCSN(creation_tid) shows the creating transaction is still running. Committed (CSN just not written back yet) and rolled-back creators proceed as before. setAndStoreRemovalTID calls it for non-transactional tids — the single choke point of every non-transactional removal.
  2. MergeTreeData::Transaction::commit pre-checks all covered parts before locking any of them for non-transactional operations. A non-transactional removal mark cannot be undone once persisted, and the existing locked_parts_to_cleanup was dead code (populated, never consumed) — without the pre-pass, a multi-part DROP PARTITION failing on the Nth part left parts 1..N-1 permanently marked as removed while still Active, making them invisible to transactional readers (verified empirically). The dead code is removed.

The client sees Code: 650. SERIALIZATION_ERROR: Cannot remove data object ...: it was created by transaction ... which is not committed yet. Wait for the transaction to commit or roll back, and retry — the standard retryable conflict signal of the transactions MVCC model. After the creating transaction finishes, the same DROP PARTITION succeeds.

  1. The same hazard existed in non-transactional REPLACE PARTITION FROM and MOVE PARTITION TO TABLE, which remove the old parts via removePartsInRangeFromWorkingSet after committing the cloned/moved parts (a rejected REPLACE used to leave a half-replaced destination). Now removePartsFromWorkingSet checks all parts before mutating any (every non-transactional multi-part removal is all-or-nothing), replacePartitionFrom checks the active parts inside the drop range before renaming and committing the clones, and movePartitionToTable checks the moved source parts before publishing anything in the destination.
  2. Since MOVE publishes the moved data in another table, it uses the stricter checkCreationIsCommitted: the creating transaction must be committed — a rollback marks creation_csn = RolledBackCSN before removing the part from the working set, so rejecting only still-running creators would leave a window where rolled-back rows get committed into the destination. A commit is irreversible, so once this check passes under the parts lock the moved data cannot retroactively become rolled back.

Adjacent paths verified: background merges never meet uncommitted parts (once transactions are used, merges begin their own transaction and filter invisible parts); non-transactional OPTIMIZE on such tables is already rejected upstream with ABORTED before touching version metadata.

The new test covers: rejection with both a committed and an uncommitted part in the partition (and that the committed part is not left locked — a retried DROP after COMMIT removes everything), the ROLLBACK variant, the committed-parts control, and the REPLACE PARTITION FROM / MOVE PARTITION TO TABLE rejection with byte-identical destinations. The transactional isolation tests (01168*, 01169*, 01170, 01171) pass locally with the fix.

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 a logical error (creation_csn is not set while removal_csn is set) when a non-transactional ALTER TABLE ... DROP PARTITION removes a part inserted by a transaction that has not committed yet. Such an operation is now rejected with SERIALIZATION_ERROR and can be retried after the transaction commits or rolls back.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

…art removal

A non-transactional `ALTER TABLE ... DROP PARTITION` covers all active parts,
including parts created by transactions that have not committed yet (it selects
covered parts ignoring MVCC visibility). Since d6350c1,
`VersionMetadata::setAndStoreRemovalTID` wrote `removal_csn = Tx::NonTransactionalCSN`
together with `removal_tid` in a single update, so for such parts the version
metadata ended up with `removal_csn` set while `creation_csn` was still
unresolved, and `validateInfo` raised a logical error `creation_csn is not set
while removal_csn is set` (aborting debug and sanitizer builds).

Restore the pre-refactor write order (`creation_csn` is always persisted before
`removal_csn`): defer the `removal_csn` fill in `setAndStoreRemovalTID` and
`updateCSNIfNeeded` until `creation_csn` is resolved, and teach `validateInfo`
that a bare non-transactional `removal_tid` over an unresolved creation is a
valid deferred state. Once the creating transaction commits, the next metadata
update fills `removal_csn` (`creation_csn > removal_csn` is already exempted
for `Tx::NonTransactionalCSN`).

Closes: ClickHouse/clickhouse-private#64528

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [072ca1a]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, distributed plan, parallel) FAIL
00543_null_and_prewhere FAIL cidb
02932_apply_deleted_mask FAIL cidb
01661_extract_all_groups_throw_fast FAIL cidb
02477_single_value_data_string_regression FAIL cidb
04033_tpc_ds_q31 FAIL cidb
02240_protobuflist_format_persons FAIL cidb
02900_limit_by_query_stage FAIL cidb
04040_tpc_h_q03 FAIL cidb
02122_parallel_formatting_JSONCompactStringsEachRowWithNames FAIL cidb
01304_direct_io_long FAIL cidb
10 more test cases not shown
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This PR changes plain MergeTree non-transactional partition removal to fail with SERIALIZATION_ERROR instead of persisting removal_csn ahead of an unresolved creation_csn, and it extends that guard to REPLACE / MOVE. The original logical-error path is addressed, but the current head still leaves one MVCC leak on the source side of REPLACE / ATTACH PARTITION FROM and two places where the new "all-or-nothing" removal contract can still fail after some parts have already been marked removed.

Findings

❌ Blockers

  • [src/Storages/StorageMergeTree.cpp:2988, 3113-3136] REPLACE PARTITION FROM / ATTACH PARTITION FROM still clone source parts selected from getVisibleDataPartsVectorInPartition in the non-transactional case, which returns every active part, including one whose creating transaction is still running. Because the clone is created with Tx::NonTransactionalTID, the destination can publish another transaction's uncommitted rows even if the source later rolls back. Suggested fix: require every src_part to pass checkCreationIsCommitted() before any clone is published, including the ALL path.
  • [src/Storages/MergeTree/MergeTreeData.cpp:9295-9340] The new pre-pass in MergeTreeData::Transaction::commit checks only creator state; it does not reserve the real removal locks. A concurrent transactional remover can already hold removal_tid on one later covered part, so earlier covered parts can be marked removed by setAndStoreNonTransactionalRemovalTID() and the Nth part then throws from lockRemovalTID(), leaving a failed non-transactional replace-style commit partially applied. Suggested fix: acquire / validate all removal locks (or another equivalent no-fail reservation) for the full covered set before storing any non-transactional removal metadata.
  • [src/Storages/MergeTree/MergeTreeData.cpp:5851-5862] The same gap exists in removePartsFromWorkingSet: prechecking checkNonTransactionalRemovalIsPossible() does not prevent a later part from failing in setAndStoreNonTransactionalRemovalTID() because it is already locked for removal by another transaction. That still lets a multi-part non-transactional DROP PARTITION / REPLACE path remove parts[0..N-1] and then fail on parts[N], violating the advertised all-or-nothing behavior. Suggested fix: use the same up-front lock reservation strategy here as in the commit path, or otherwise make the second phase infallible before the first removal mark is persisted.
Final Verdict

Request changes. The logical-error exception is fixed, but the current head still allows publishing uncommitted source data via REPLACE / ATTACH PARTITION FROM and still has two partial-application windows in the new non-transactional multi-part removal paths.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
…sactions

A non-transactional `ALTER TABLE ... DROP PARTITION` covers all active parts
ignoring MVCC visibility, so it can cover a part whose creating transaction has
not committed yet. Since d6350c1, `VersionMetadata::setAndStoreRemovalTID`
persisted `removal_csn = Tx::NonTransactionalCSN` together with `removal_tid`,
so for such parts `removal_csn` was persisted while `creation_csn` was still
unresolved, and `validateInfo` raised a logical error `creation_csn is not set
while removal_csn is set` (aborting debug and sanitizer builds).

Fail close instead (supersedes the previous commit, which deferred the
`removal_csn` write and let the removal silently discard the uncommitted data):
`setAndStoreRemovalTID` now rejects a non-transactional removal with
`SERIALIZATION_ERROR` while the creating transaction is still running, and
`MergeTreeData::Transaction::commit` checks all covered parts before locking
any of them - a non-transactional removal mark cannot be undone once persisted,
and the previously collected `locked_parts_to_cleanup` was dead code (populated,
never consumed), so a multi-part DROP failing on the Nth part left the earlier
parts permanently marked as removed while still Active. The dead code is
removed.

Closes: ClickHouse/clickhouse-private#64528

Co-Authored-By: Claude Fable 5 <[email protected]>
@tiandiwonder tiandiwonder changed the title Do not persist removal_csn before creation_csn on non-transactional part removal Reject non-transactional removal of parts created by uncommitted transactions Jul 15, 2026
if (covering_part)
continue;
for (const auto & covered : covered_parts)
covered->version->checkNonTransactionalRemovalIsPossible();

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 pre-pass only checks the creator transaction; it does not reserve the covered parts themselves. The second pass can still fail on the Nth part for a different SERIALIZATION_ERROR, for example if that part is already removal_tid-locked by a concurrent transactional DROP PART / DROP PARTITION. By then parts 1..N-1 have already gone through setAndStoreNonTransactionalRemovalTID, so they become invisible and eligible for cleanup even though the outer non-transactional DROP PARTITION failed. To actually fail close, this first phase needs to acquire/validate the real removal locks (or otherwise guarantee that the later write phase cannot still fail on one part only) before any removal_tid is stored.

… removal

Non-transactional `REPLACE PARTITION FROM` and `MOVE PARTITION TO TABLE` remove
the old parts via `removePartsInRangeFromWorkingSet` after committing the
cloned/moved parts, bypassing the pre-check in `MergeTreeData::Transaction::commit`.
A rejected `REPLACE` left a half-replaced destination: the old committed part
already removed, the cloned part already published, and the uncommitted part kept.

Check earlier instead:
- `removePartsFromWorkingSet` checks all parts before mutating any of them, so
  every non-transactional multi-part removal path is all-or-nothing;
- `replacePartitionFrom` checks the active parts inside `drop_range` right after
  taking the parts lock, before renaming and committing the clones;
- `movePartitionToTable` checks the moved source parts after taking both parts
  locks, before publishing anything in the destination table.

Since MOVE publishes the moved data in the destination table, it uses a stricter
predicate (`checkCreationIsCommitted`): the creating transaction must be
committed, so a rollback happening between source part selection and the final
check cannot leak rolled-back rows into the destination (a rollback marks
`creation_csn = RolledBackCSN` before removing the part from the working set,
and a commit is irreversible once the check passes under the parts lock).

The parts lock serializes these checks against concurrent part publish, so they
are race-free. Test cases for REPLACE and MOVE added.

Related: ClickHouse/clickhouse-private#64528

Co-Authored-By: Claude Fable 5 <[email protected]>
/// replaced range contains a part of a still-running transaction (see
/// checkNonTransactionalRemovalIsPossible), and at that point the cloned parts would
/// already be committed and could not be undone.
if (replace && !local_context->getCurrentTransaction())

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 pre-checks the destination parts that REPLACE is about to remove. The source side is still unguarded: src_parts above are collected with getVisibleDataPartsVectorInPartition, and in the non-transactional case that returns every active part, including one whose creation_tid is still running. cloneAndLoadDataPart then stamps the clone with Tx::NonTransactionalTID, so ALTER TABLE ... REPLACE PARTITION ... FROM can publish another transaction's uncommitted rows into the destination even if the source transaction later rolls back.

Can we require every src_part to pass checkCreationIsCommitted() before publishing the clones here (same guard as MOVE PARTITION TO TABLE)? ATTACH PARTITION FROM goes through the same helper, so it needs the same protection if we want to preserve MVCC on the source side too.

Comment on lines +5851 to +5854
/// A non-transactional removal mark cannot be undone once persisted, so check all parts
/// before mutating anything (see checkNonTransactionalRemovalIsPossible).
for (const DataPartPtr & part : remove)
part->version->checkNonTransactionalRemovalIsPossible();

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.

checkNonTransactionalRemovalIsPossible() only proves that the creator transaction is no longer running; it does not reserve the part itself. If remove = [p1, p2] and p2 was already removal_tid-locked by a concurrent transactional DROP PART / DROP PARTITION before we entered here, the loop below will still successfully call setAndStoreNonTransactionalRemovalTID() for p1 and then throw from lockRemovalTID() on p2. That leaves p1 invisible / outdated even though the outer non-transactional removal failed, so the new "check all parts before mutating anything" contract is still violated for direct multi-part removals.

Can we acquire / validate the actual removal locks for the full remove set up front (or otherwise guarantee the write phase cannot still fail on one part) before persisting any non-transactional removal mark?

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Cross-linking: #105116 fixes the same defect (creation_csn = 0 + removal_csn = 1 from a non-transactional remover) with the same SERIALIZATION_ERROR strategy, the same getCSN refinement and the same removal of the dead locked_parts_to_cleanup. It does not cover REPLACE PARTITION FROM / MOVE PARTITION TO TABLE, which this pull request does.

It does close the review finding still open here about the pre-pass not reserving the covered parts: instead of checking and then stamping, NonTransactionalRemovalLocks takes lockRemovalTID on every part of the batch and holds it across the stamping phase, so a part that is removal_tid-locked by a concurrent transactional DROP PART cannot be acquired between the check and the write.

The two should probably be reconciled into one change rather than merged independently.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

@groeneai could you pick up the one part of this that is still broken? Verified on current master, so it survives #105116: with session A holding BEGIN TRANSACTION; INSERT INTO src VALUES (42) uncommitted, a non-transactional ALTER TABLE dst REPLACE PARTITION ID 'all' FROM src succeeds and publishes that row into dst, and after A rolls back src is empty while dst keeps the row permanently — ATTACH PARTITION FROM behaves identically. The source parts come from getVisibleDataPartsVectorInPartition, which returns every active part when there is no current transaction, so the missing guard is checkCreationIsCommitted() on each src_part in StorageMergeTree::replacePartitionFrom, the same one movePartitionToTable already applies — and it has to run regardless of the replace flag so that ATTACH ... FROM is covered too.

@tiandiwonder

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #105116, which fixed the same defect on 2026-09-12 with a stronger design: it reserves the removal locks for the whole batch (NonTransactionalRemovalLocks), which also answers the review's objection that the pre-passes here validate the creator transaction without reserving the parts, so a concurrent transactional DROP PART can still make the write phase fail on the Nth part. Verified on a master build that DROP PARTITION, REPLACE PARTITION FROM and MOVE PARTITION TO TABLE over a part of an uncommitted transaction are all already rejected with SERIALIZATION_ERROR and leave the data untouched — the behaviour this branch's test asserts. The one thing neither change fixes is the source side of REPLACE / ATTACH PARTITION FROM, raised separately above.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the source side of REPLACE / ATTACH PARTITION FROM over a part whose creating transaction is still running, and I will follow up here with a PR or with my findings.

@groeneai

Copy link
Copy Markdown
Collaborator

Opened #121308 for the source side.

Your case reproduces on current master: with BEGIN TRANSACTION; INSERT INTO src VALUES (42) left uncommitted, a non-transactional ALTER TABLE dst REPLACE PARTITION ID 'all' FROM src publishes that row, and after the rollback src is empty while dst keeps it. ATTACH PARTITION FROM and CREATE TABLE ... CLONE AS behave the same, and so does a plain MergeTree source with a ReplicatedMergeTree destination, so #121308 guards StorageReplicatedMergeTree::replacePartitionFromImpl as well.

Two corrections to the mechanism, neither of which changes your conclusion:

  1. checkCreationIsCommitted() does not exist in master; it is a symbol from your branch. The guard movePartitionToTable applies is checkPartsCanBeRemovedNonTransactionally(src_parts, NonTransactionalRemovalKind::Republish) at StorageMergeTree.cpp:3663, whose Republish branch calls VersionMetadata::isCreationCommitted().
  2. I did not reuse that function on src_parts directly, because it also throws when another transaction holds a part's removal lock. REPLACE / ATTACH ... FROM only clone, they never remove the source parts, so that leg would refuse a legal clone whenever a concurrent transactional DROP PARTITION on the source holds the lock, reporting a removal that is not happening. Refuse REPLACE/ATTACH PARTITION FROM a part whose creating transaction has not committed #121308 extracts the creation check into checkPartsCanBeRepublishedNonTransactionally, calls it on the source parts, and has the Republish branch delegate to it so the rule keeps one implementation.

The rest of your analysis holds, including that the check must not be gated on the replace flag: the pre-existing destination-side check is, which is why ATTACH ... FROM had no coverage at all.

@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 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-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants