Repository navigation
Fix logical error on a non-transactional DROP PARTITION over an uncommitted part - #105116
Conversation
|
Workflow [PR], commit [5ae6d4c] Summary: ✅
AI ReviewSummaryThis PR hardens non-transactional Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 5ae6d4c.
Changed lines: Changed C/C++ lines covered: 131/148 (88.51%) · Uncovered code |
antonio2368
left a comment
There was a problem hiding this comment.
One AI finding:
I think this still has a blocker in the multi-part replacement path.
The new guard in VersionMetadata::setAndStoreRemovalTID is locally correct: for Tx::NonTransactionalTID, it throws SERIALIZATION_ERROR before setting removal_tid/removal_csn when the covered part still has an uncommitted transactional creation_tid.
The problem is the caller contract. In MergeTreeTransaction::addNewPartAndRemoveCovered, the non-transactional branch stamps covered parts one by one:
for (const auto & covered : covered_parts)
{
transaction_context.part_name = covered->name;
covered->version->setAndStoreNonTransactionalRemovalTID(transaction_context);
}For a non-transactional TRUNCATE, DROP PARTITION, or DETACH PARTITION that covers multiple parts, this can leave partial persistent side effects:
- Covered part
Ais already committed, sosetAndStoreNonTransactionalRemovalTIDsucceeds and persistsremoval_tid = Tx::NonTransactionalTID/removal_csn = Tx::NonTransactionalCSN. - Covered part
Bwas created by an in-flight transaction whosecreation_csnhas not been published yet, so the new guard throwsSERIALIZATION_ERROR. MergeTreeData::Transaction::commitexits before the laterNOEXCEPT_SCOPEthat activates the new empty covering part and moves covered parts toOutdated.- Rollback only handles the precommitted new part. It does not clear the removal metadata already persisted on
A.
After that failed user operation, A can already be invisible: VersionInfo::isVisible returns false immediately for removal_tid.isNonTransactional. So a retryable SERIALIZATION_ERROR can still leave committed data logically removed even though the operation failed.
The locked_parts_to_cleanup vector in MergeTreeData::Transaction::commit looks intended for this, but it is only appended after addNewPartAndRemoveCovered returns and I do not see any consumer for it. It also would not cover the intra-call case where one covered part is stamped and a later covered part throws before the helper returns.
I think the fix should either preflight all covered parts for this new uncommitted-creator condition before persisting any non-transactional removal metadata, or make the stamping phase rollback-safe by recording each successfully stamped part immediately and clearing both removal_tid and removal_csn if any later part fails.
| # Without the fix this crashes the server on a LOGICAL_ERROR. | ||
| # With the fix it must fail with `SERIALIZATION_ERROR`. | ||
| $CLICKHOUSE_CLIENT -q "TRUNCATE TABLE t_truncate_non_tx_vs_insert_tx" 2>&1 \ | ||
| | grep -oE "SERIALIZATION_ERROR|LOGICAL_ERROR" | head -1 |
There was a problem hiding this comment.
Wouldn't this catch LOGICAL_ERROR also which is wrong?
There was a problem hiding this comment.
Fair point, tightened in 4fc8079 -- grep -o "SERIALIZATION_ERROR" | head -1. A LOGICAL_ERROR regression would now produce a clearer empty-vs-SERIALIZATION_ERROR diff against the reference.
There was a problem hiding this comment.
🕵 The test file is gone in 9f39b6a: the TRUNCATE case it covered is already fixed in master by #109598, so it no longer reproduced anything and was failing Fast test. Its replacement 05161 matches on SERIALIZATION_ERROR only — a regression back to a logical error prints nothing at all, which is an unambiguous diff.
`MergeTreeTransaction::addNewPartAndRemoveCovered` stamps each covered part with `removal_tid = NonTransactionalTID` in a per-part loop. With the `SERIALIZATION_ERROR` guard added in the previous commit, a throw on the Nth covered part leaves parts 1..N-1 already stamped on disk -- silently invisible (`isVisible` returns false for any non-tx removal) and not undone by the transaction destructor. A retryable failure of the user operation thus silently makes committed data invisible. Preflight all covered parts before any stamping. If any has an in-flight transactional creator, throw upfront -- no part gets stamped, the operation is cleanly retryable. A new regression test `04242_truncate_non_tx_partial_removal` covers two parts where only the second has a pending creator and asserts both rows remain visible after the failed TRUNCATE. Addresses review feedback on ClickHouse#105116.
Per review on ClickHouse#105116: - 04241's grep now matches only `SERIALIZATION_ERROR`. The previous `SERIALIZATION_ERROR|LOGICAL_ERROR` alternation would print `LOGICAL_ERROR` on a regression and produce a less-clear test failure than a plain reference mismatch. - Trim the comments in `setAndStoreRemovalTID`, the `transaction_before_csn_publish` failpoint site, and the test header to state the invariant rather than narrate the cause and effect.
|
📊 Cloud Performance Report ✅ AI verdict: The only flagged query is ClickBench Q28, showing a +5.5% median shift (1052.5 -> 1110.5 ms) with mixed signals from the two tests. This PR changes only the non-transactional part-removal path for DROP/DETACH/REPLACE/MOVE PARTITION (adding all-or-nothing removal locking and pre-checks against uncommitted creators); none of that code runs during a read-only ClickBench SELECT. CPU time is essentially unchanged (15503 vs 15507 ms) and the query has no history to lean on, so the delta is measurement noise rather than a PR effect, and it has been downgraded to not_sure. No cross-query patterns were observed. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
| /// the resulting `creation_csn = 0 + removal_csn = 1` shape would be rejected | ||
| /// by `validateInfo` and is unrecoverable on restart. | ||
| if (tid.isNonTransactional() | ||
| && !info.creation_csn |
There was a problem hiding this comment.
should we do TransactionLog::getCSN(current_info.creation_tid)? same question for above
There was a problem hiding this comment.
TransactionLog::getCSN(info.creation_tid) would eliminate spurious SERIALIZATION_ERRORs in the window where the creator has committed globally but this replica's on-disk creation_csn hasn't caught up yet.
Leaving it out of this PR — the guard is still correct without it, just more conservative than necessary.
There was a problem hiding this comment.
🕵 Done in 65e4e2b. VersionMetadata::isCreatedByUncommittedTransaction now falls back to TransactionLog::getCSN(creation_tid) when creation_csn is unset, the same way isVisible and canBeRemoved already do, so a creator that is committed globally but not yet stamped on this replica no longer produces a spurious SERIALIZATION_ERROR (a rolled back creator answers Tx::RolledBackCSN, which is also not refused).
The lookup happens before updateInfoWithRefreshDataThenStoreAndSetMetadata so it is not done under the metadata update lock; the update function still re-checks the refreshed VersionInfo before throwing.
There was a problem hiding this comment.
🕵 The blocker on this line is addressed in 319e693.
REPLACE PARTITION FROM and MOVE PARTITION TO TABLE now check the parts they are about to remove before committing their own new ones, under the same parts lock they commit with, so a refused removal leaves the partition untouched instead of half replaced or half moved.
MOVE uses a stricter predicate, VersionMetadata::isCreationCommitted: it republishes the rows in another table where a commit cannot be taken back, so the creating transaction must be committed rather than merely no longer running — otherwise a creation that later rolls back would resurrect rows that never existed.
StorageReplicatedMergeTree::replacePartitionFromImpl has the same ordering but is not reachable: IInterpreter::checkStorageSupportsTransactionsIfNeeded throws NOT_IMPLEMENTED for any storage that supportsReplication(), regardless of throw_on_unsupported_query_inside_transaction, so a replicated table never holds a part with an uncommitted transactional creator. A check there would only add a throw after the Keeper commit, which is strictly worse.
The new 05175_replace_move_partition_non_tx_uncommitted covers both statements. I verified it discriminates: with the two checks reverted and everything else unchanged, it fails — the retried MOVE trips over PART_IS_TEMPORARILY_LOCKED: Part all_1_1_1 (state Outdated) already exists on the half-moved destination.
There was a problem hiding this comment.
TransactionLog::getCSN here is still too weak to close the false-positive window that Antonio called out.
At the current head, isCreatedByUncommittedTransaction/isCreationCommitted only do TransactionLog::getCSN(current_info.creation_tid) (VersionMetadata.cpp:147, :156). But getCSNImpl only consults the asynchronously loaded tid_to_csn map unless the caller passes an explicit fallback atomic (TransactionLog.cpp:615-633). These helpers do not pass one.
So a same-server creator can already be committed globally and still look "uncommitted" here: the CSN znode is created before finalizeCommittedTransaction calls afterCommit, and afterCommit only writes creation_csn to the part afterwards (TransactionLog.cpp:490-508, MergeTreeTransaction.cpp:337-352). A non-transactional DROP PARTITION / DETACH PARTITION / MOVE that races in that window still gets a spurious SERIALIZATION_ERROR even though the creator has already committed.
So the "creator that is committed globally but not yet stamped on this replica no longer produces a spurious SERIALIZATION_ERROR" part is not actually true yet. This still needs a path that can observe the just-committed local transaction instead of the async tid_to_csn cache alone.
There was a problem hiding this comment.
🕵 Answered at pull-request level so it did not land in this thread — linking it here: #105116 (comment)
Short version: the getCSN window is real and described correctly, but it is not introduced here. Before this change the guard was !info.creation_csn alone, which is false-positive for that window and for the much longer period where a transaction committed long ago but this particular part was never stamped; the TransactionLog::getCSN fallback strictly shrinks it. And the behaviour being replaced in that window is not success — it is the creation_csn is not set while removal_csn is set to 1 logical error, i.e. a server abort in debug and sanitizer builds.
Closing the remainder needs the CSN published synchronously at commit point, which is a change to the transaction-log commit protocol affecting every reader of tid_to_csn, not to the removal guard. VersionMetadata has no atomic creation_csn to hand getCSNAndAssert as a fallback either — getInfo() already reads the mutex-protected struct, so it is as fresh as the data gets; the value simply does not exist yet in that window. Happy to split that into its own pull request if you want it tracked.
| @@ -0,0 +1,50 @@ | |||
| #!/usr/bin/env bash | |||
| # Tags: no-ordinary-database, no-encrypted-storage, no-parallel | |||
| wait "$insert_pid" | ||
|
|
||
| # Both committed rows must still be visible. | ||
| $CLICKHOUSE_CLIENT -q "SELECT count() FROM t_truncate_non_tx_partial_removal" |
There was a problem hiding this comment.
should this be inside a transaction to verify it works?
There was a problem hiding this comment.
No need to put it inside a transaction. The above INSERT is already committed.
There was a problem hiding this comment.
|
Dear @antonio2368, 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. |
|
Sorry, I will work on it. |
A transactional INSERT's storage commit flips the new part to `Active` before `TransactionLog::commitTransaction` creates the CSN znode in Keeper. A concurrent non-transactional remover (e.g. TRUNCATE) running in that window sees the part as `Active` with `creation_csn == 0` and stamps `removal_csn = NonTransactionalCSN`. `validateInfo` rejects the resulting shape (removed part with no committed creation point) and the server aborts on a `LOGICAL_ERROR`. The new `transaction_before_csn_publish` failpoint pauses precisely in that window. The new test 04241 deterministically reproduces the abort under debug builds.
`setAndStoreRemovalTID` now throws `SERIALIZATION_ERROR` when asked to write `removal_tid = Tx::NonTransactionalTID` on a part whose `creation_csn` is still unset and whose `creation_tid` is transactional. Without this guard the resulting on-disk shape (`creation_csn == 0, removal_csn == NonTransactionalCSN`) is caught by `validateInfo` and the server aborts on `LOGICAL_ERROR` (in debug or sanitizer builds) — a crash that is otherwise reproducible by 04241 added in the previous commit. The guard inspects only `info`, so it is correct regardless of which replica the creating transaction is running on. Callers must be retry-friendly under contention; `DDLWorker`'s normal exception handling already records the failure for the originating client.
`MergeTreeTransaction::addNewPartAndRemoveCovered` stamps each covered part with `removal_tid = NonTransactionalTID` in a per-part loop. With the `SERIALIZATION_ERROR` guard added in the previous commit, a throw on the Nth covered part leaves parts 1..N-1 already stamped on disk -- silently invisible (`isVisible` returns false for any non-tx removal) and not undone by the transaction destructor. A retryable failure of the user operation thus silently makes committed data invisible. Preflight all covered parts before any stamping. If any has an in-flight transactional creator, throw upfront -- no part gets stamped, the operation is cleanly retryable. A new regression test `04242_truncate_non_tx_partial_removal` covers two parts where only the second has a pending creator and asserts both rows remain visible after the failed TRUNCATE. Addresses review feedback on ClickHouse#105116.
Per review on ClickHouse#105116: - 04241's grep now matches only `SERIALIZATION_ERROR`. The previous `SERIALIZATION_ERROR|LOGICAL_ERROR` alternation would print `LOGICAL_ERROR` on a regression and produce a less-clear test failure than a plain reference mismatch. - Trim the comments in `setAndStoreRemovalTID`, the `transaction_before_csn_publish` failpoint site, and the test header to state the invariant rather than narrate the cause and effect.
Two code paths iterate parts and stamp `removal_tid = NonTransactionalTID` one at a time -- if the innermost guard in `setAndStoreRemovalTID` throws on iteration N, iterations 1..N-1 are already persisted with no rollback, silently making committed data invisible after a "retryable" failure. - `MergeTreeData::Transaction::commit` calls `addNewPartAndRemoveCovered` once per precommitted part. The per-call preflight added earlier only vouches for a single call's covered set. Hoist it to a batch preflight in the outer loop and drop the now-redundant per-call check. - `MergeTreeData::removePartsFromWorkingSet` (non-tx branch) loops over `remove` calling `removeOldPart` per part. Add the same upfront preflight. The innermost guard in `setAndStoreRemovalTID` stays as defense-in-depth. Also drop the `no-encrypted-storage` tag from 04241 and 04242 -- it was copied from 04141 without checking; the tests pass under `--encrypted-storage` randomization. Addresses review feedback on ClickHouse#105116.
ccad250 to
f8f46fb
Compare
Left behind when the per-call preflight was hoisted out to `Transaction::commit`. Fixes the Style check on ClickHouse#105116.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 49/56 (87.50%) · Uncovered code |
|
Dear @antonio2368, 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. |
`05163` was taken by `05163_bloom_filter_array_date_literal`, added to master while this branch was in review.
`lockRemovalTID` is the other way the removal behind `REPLACE PARTITION FROM` and `MOVE PARTITION TO TABLE` can be refused, so the up-front check now covers it too: a part that another transaction already holds the removal lock on is rejected before either statement publishes its own parts. An already *removed* part is not an error -- the removal skips it. The window this closes is narrow. A removal lock and the move to `Outdated` are taken together under the table's parts lock (`MergeTreeData::Transaction::commit` and `removePartsFromWorkingSet` are the only places that lock an `Active` part for removal, and both flip the state in the same critical section), so a concurrent remover cannot leave an `Active` part locked. What can is `MergeTreeTransaction::rollback`: it calls `restoreAndActivatePart` first and clears `removal_tid` afterwards, outside the parts lock, so a part is briefly `Active` and still locked. That window is not reachable from a test without fault injection, and this pull request removed its last failpoint on purpose, so the check ships without a dedicated test rather than with one that does not actually reach it. `05175` covers the creator-state branch.
|
🕵 On the two blockers in the latest AI review — one is implemented (d5a853d), the other I believe is misdiagnosed. Blocker 2 ( The check now also rejects a part that another transaction holds the removal lock on, so both ways the later removal can be refused are caught before either statement publishes anything. The stated mechanism is not the one that makes it reachable, though. What is reachable is Blocker 1 ( The window is real and the description of the ordering is right: the CSN znode is created, But this is not something the pull request introduces. Before it, the guard was Closing the remainder needs the CSN published synchronously at commit point, as the review suggests. That is a change to the transaction-log commit protocol affecting every reader of Happy to be overruled and split the commit-point change into its own pull request if you want it tracked. |
`dropPart` and `dropPartition` call `makeCloneInDetached` before `renameAndCommitEmptyParts`, so a `DETACH` refused by the removal guard used to leave the clone behind, and every retry added another `_tryN` directory next to it. Both now check the parts they are about to remove before the clone is made -- which also avoids building the empty covering parts for an operation that cannot go ahead. `05161` asserts it: the refused `DETACH PARTITION` adds no row to `system.detached_parts`. With the two checks reverted the test fails, reporting 1 detached part instead of 0. Addresses the AI review finding on `StorageMergeTree.cpp:3021-3038,3137-3158`.
|
🕵 The premise of this round is correct, but I do not think the required action belongs in this pull request. Laying out the facts so it is an informed call. The gap is real. The precheck is not a reservation. But that outcome is not introduced here. In exactly that sequence, before this pull request, What the required action actually costs. Making the precheck a reservation means holding one Either way it is a behavioural restructure of |
The precheck added in 4a83a2d samples the state, it does not reserve it: `checkPartsCanBeRemovedNonTransactionally` runs in `dropPart` / `dropPartition` before `makeCloneInDetached`, but the removal itself happens later, in `MergeTreeData::Transaction::commit` under a parts lock this path does not hold across the two points. `getActivePartsToReplace` recomputes the covered set there, so `NonTransactionalRemovalLocks::lock` can still refuse a part that the precheck did not see -- after the clone has already been written, which is exactly the orphan `detached/` copy and the `_tryN` buildup the precheck was meant to remove. Make the ordering carry the guarantee instead of the precheck. The non-transactional `DETACH` path now copies to `detached/` after `renameAndCommitEmptyParts` has committed, out of the parts it reports as covered, the same way the transactional path clones after `outdatePart`. A refused removal therefore cannot leave anything behind, whichever of the two checks refuses it, and a `DETACH` that goes through copies exactly the parts it removed rather than the ones selected earlier. The precheck is kept as a fast path: it still fails the common case before any empty part is built. `05176_detach_partition_clone_after_removal` covers the other half of the contract -- that the copies are still made, for both `DETACH PARTITION` and `DETACH PART`, and that re-attaching them brings every row back. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…lection `renameAndCommitEmptyParts` accumulated `covered_parts` from `renameTempPartAndReplaceUnlocked`, released the parts lock, and only then called `MergeTreeData::Transaction::commit`, which reacquires the lock and recomputes the covered set with `getActivePartsToReplace`. The two can diverge: when a covering part appears in that window, `commit` marks the empty part obsolete and removes nothing, yet the old code still undelayed those parts with `remove_time = 0`, dropped them from the deduplication log, and - through the value returned to `dropPart` / `dropPartition` - cloned them into `detached/` although they were still active. `ATTACH` could then restore an older version of a part than the `DETACH` had removed. `commit` already returns `total_covered_parts`, the authoritative answer. Use it for all three, and return it to the callers. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Pass of 2026-09-12: the AI Review blocker is adopted, and the one red is unrelated and now fixed on Blocker — The finding is right.
Tests note.
Not caused by this pull request, and already fixed on
Verification. The |
| /// Everything below -- and the clone to `detached/` made by the callers -- must use that answer, | ||
| /// otherwise a concurrently appearing covering part makes us report, undelay and detach a part | ||
| /// that is still active. | ||
| DataPartsVector removed_parts = transaction.commit(); |
There was a problem hiding this comment.
renameAndCommitEmptyParts now returns only after the non-transactional removal is already committed, and both dropPart / dropPartition call clonePartsToDetached afterwards. That makes DETACH exception-unsafe: getTemporaryPartDirectoryHolder / makeCloneInDetached still do ordinary filesystem work and can throw. If the second clone of a multi-part partition fails (for example ENOSPC), the statement returns an exception with the empty covering parts already active, the source parts already Outdated, and only a prefix of the partition present under detached/. A later ATTACH PARTITION restores only that prefix.
The previous ordering failed before touching the working set. We need a staged clone/publish scheme here, or a rollback that re-activates the removed parts when the post-commit clone fails, otherwise DETACH can lose data on an ordinary I/O error.
There was a problem hiding this comment.
🕵 Adopted in 1afe40dbb74d. The finding is right, and it is the mirror image of the previous round's: copying after the removal makes an ordinary I/O error destructive, copying before it leaves an orphan in detached/ whenever the removal is then refused. Neither order is safe on its own, so the fix is to stop choosing between them.
renameAndCommitEmptyParts now takes clone_to_detached and does the whole thing under the one parts lock it already precommits the empty parts with: it checks removability, clones the covered parts, and calls MergeTreeData::Transaction::commit(part_lock) with that same lock instead of letting commit reacquire it. Because the lock is held across all three:
- the covered set cannot change between the check, the clone and the commit, so the copy is of exactly the parts that are removed — which is also what the previous round's finding was about;
- a removal that has to be refused is refused before anything is copied, so no orphan copy and no
_tryNbuildup on retries (05161asserts this, and it still passes); - a clone that fails on I/O fails the statement with the parts still
Active— theTransactiondestructor rolls the empty parts back — so nothing is lost.
This is the "reservation" shape I argued against on 2026-09-12 00:41 on cost grounds, and that argument does not hold up: for a plain MergeTree the copy is a hardlink-based freeze, because copy_instead_of_hardlink in makeCloneInDetached is gated on supportsReplication(), which is false here. StorageReplicatedMergeTree already clones inside the removal's own parts lock (removePartsInRangeFromWorkingSetAndGetPartsToRemoveFromZooKeeper, clone_to_detached), so this aligns the two engines rather than inventing a new locking pattern.
One detail worth flagging: the PART_IS_TEMPORARILY_LOCKED retry loop now covers only the precommit renames — a batch_precommitted flag rethrows anything raised by the clone or the commit, since retrying those after a partial precommit would be wrong.
Verified: ninja clickhouse-bundle and ninja clickhouse, 0 errors; check_cpp.sh clean. Against a local server, 05161, 05162, 05175, 05176, 01451_detach_drop_part, 01451_replicated_detach_drop_part_long, 01710_projection_detach_part, 00516_deduplication_after_drop_partition_zookeeper, 03285_materialize_ttl_only_drop_parts, 01173_transaction_control_queries and the 04057–04060 transaction tests all pass (26/26 after merging master).
`renameAndCommitEmptyParts` committed the non-transactional removal and only then did `dropPart` / `dropPartition` call `clonePartsToDetached`. That made `DETACH` exception-unsafe: `makeCloneInDetached` does ordinary filesystem work and can throw, so a failure on the second part of a multi-part partition left the empty covering parts active, the source parts `Outdated` with `remove_time = 0`, and only a prefix of the partition under `detached/` -- a later `ATTACH PARTITION` would restore just that prefix. The earlier ordering (clone first) was not safe either: the precheck only sampled the part set, so a removal refused at commit time left an orphan copy in `detached/` and a `_tryN` directory on every retry. Both go away by doing the whole thing under one parts lock, which is what `StorageReplicatedMergeTree` already does (the clone in `removePartsInRangeFromWorkingSetAndGetPartsToRemoveFromZooKeeper` is made inside the removal's own lock). `renameAndCommitEmptyParts` now takes `clone_to_detached` and, while still holding the lock it precommitted the empty parts under, checks removability, clones the covered parts, and calls `Transaction::commit` with that same lock. So: - the covered set cannot change between the check, the clone and the commit, so the copy is made of exactly the parts that are removed; - a removal that has to be refused is refused before anything is copied, so no orphan is left in `detached/`; - a clone that fails on I/O fails the statement with the parts still active -- the transaction rolls the empty parts back and no data is lost. Holding the lock across the copy is what the previous round was trying to avoid, but for a plain `MergeTree` the copy is a hardlink-based freeze: `copy_instead_of_hardlink` in `makeCloneInDetached` is gated on `supportsReplication`, which is false here. `05161` already asserts that a refused `DETACH` leaves `detached/` empty; its comment is updated to the new reason. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🕵 Pass of 2026-09-12 (third): the new AI Review blocker is adopted, Blocker — post-commit clone made The previous round moved the
I had argued on 2026-09-12 00:41 that this shape costs too much because it holds The remaining Major (the CI. No failures on Verification. |
…d-part-removal-on-load ClickHouse#105116 replaced the per-part removal in Transaction::commit with a batch that locks every covered part first and stores the removal TIDs afterwards, so the commit failpoint moved out of the per-part loop to the point before that batch runs. It still pauses after the covering parts are durable and before any covered part is stamped, which is the window loadOutdatedDataParts has to recover from. setAndStoreNonTransactionalRemovalTID kept its single-argument form on master, so completeRemovalOfCoveredPart is unchanged by the merge.
A non-transactional part remover sees every active part, including one whose creating transaction has not committed yet. Covering such a part writes
removal_tid = Tx::NonTransactionalTID, which immediately setsremoval_csn = Tx::NonTransactionalCSN, producing the on-disk shapecreation_csn = 0, removal_csn = 1thatVersionMetadata::validateInforejects as unrecoverable — a logical error, and a server abort in debug / sanitizer builds:TRUNCATEwas fixed for this in #109598 by skipping uncommitted parts, but the other non-transactional removers were not:ALTER TABLE ... DROP PARTITION,DETACH PARTITIONandDROP PARTstill take the whole active part set. This change refuses the bad write one layer lower, inVersionMetadata::setAndStoreRemovalTID, withSERIALIZATION_ERROR, so the caller can retry once the in-flight creation finalizes. The guard inspects only the on-diskVersionInfoand the transaction log, so it is correct regardless of which replica the creating transaction runs on, and it does not fire for a creator that is already committed but whosecreation_csnhas not been written to this part yet.A non-transactional removal is also not undoable — nothing ever clears
removal_csn— so a batch that fails halfway would leave the already-stamped parts invisible for good even though the statement failed with a supposedly retryable error.NonTransactionalRemovalLocksnow takes the removal lock of every part of a batch before any of them is written, so a conflict (an in-flight creator, or another transaction already removing one of the parts) is reported before anything is persisted and the statement leaves the table untouched.REPLACE PARTITION FROMandMOVE PARTITION TO TABLEcommit their own new parts before removing the old ones, so refusing the removal at that point would leave the partition half replaced or half moved. Both now check the parts they are about to remove first, under the same parts lock they commit with.MOVEuses the stricter check of the two: it republishes the rows in another table where a commit cannot be taken back, so the creating transaction must be committed rather than merely no longer running.StorageReplicatedMergeTree::replacePartitionFromImplhas the same ordering but is not reachable —IInterpreter::checkStorageSupportsTransactionsIfNeededrejects any transaction touching a storage that supports replication, so a replicated table never holds a part with an uncommitted transactional creator.A non-transactional
DETACHhas to both copy the parts todetached/and remove them, and neither order is safe on its own: copying first leaves an orphan copy behind whenever the removal is then refused (and a_tryNdirectory on every retry), while copying afterwards makes an ordinary I/O error destructive — the parts are already gone and only a prefix of the partition is underdetached/, so a laterATTACH PARTITIONrestores just that prefix.renameAndCommitEmptyPartsnow does the whole thing under the one parts lock it precommits the empty parts with: it checks removability, copies the covered parts, and callsMergeTreeData::Transaction::commitwith that same lock. The covered set therefore cannot change in between — the copy is of exactly the parts that are removed, a refusal happens before anything is copied, and a failed copy fails the statement with the parts still active.StorageReplicatedMergeTreeclones inside the removal's own parts lock for the same reason. Holding the lock across the copy is cheap here: for a plainMergeTreethe copy is a hardlink-based freeze, sincecopy_instead_of_hardlinkinmakeCloneInDetachedis gated onsupportsReplication.Originally surfaced by
Stress test (amd_tsan, meta in keeper): https://github.com/ClickHouse/clickhouse-private/actions/runs/25947990737 (on https://github.com/ClickHouse/clickhouse-private/pull/57844).Closes: #109698
Related: #109598
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix a logical error (a server abort in debug builds) when a non-transactional
DROP PARTITION,DETACH PARTITION,DROP PART,REPLACE PARTITION FROMorMOVE PARTITION TO TABLEcovered a part whose creating transaction had not committed yet, leaving that part withcreation_csn = 0andremoval_csn = 1. Such an operation now fails withSERIALIZATION_ERRORand can be retried once the creating transaction finishes; it no longer removes or replaces any part of the affected batch.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/105116]
Version info
26.9.1.1299(included in26.9and later)