Skip to content

Fix logical error on a non-transactional DROP PARTITION over an uncommitted part - #105116

Merged
alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
tuanpach:fix-truncate-tx-insert-race
Sep 12, 2026
Merged

alexey-milovidov merged 25 commits into
ClickHouse:masterfrom
tuanpach:fix-truncate-tx-insert-race

Conversation

@tuanpach

@tuanpach tuanpach commented May 16, 2026 •

Copy link
Copy Markdown
Member

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 sets removal_csn = Tx::NonTransactionalCSN, producing the on-disk shape creation_csn = 0, removal_csn = 1 that VersionMetadata::validateInfo rejects as unrecoverable — a logical error, and a server abort in debug / sanitizer builds:

Logical error: 'Object ...|all_12_25_7, creation_csn is not set while removal_csn is set to 1'.

TRUNCATE was fixed for this in #109598 by skipping uncommitted parts, but the other non-transactional removers were not: ALTER TABLE ... DROP PARTITION, DETACH PARTITION and DROP PART still take the whole active part set. This change refuses the bad write one layer lower, in VersionMetadata::setAndStoreRemovalTID, with SERIALIZATION_ERROR, so the caller can retry once the in-flight creation finalizes. The guard inspects only the on-disk VersionInfo and 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 whose creation_csn has 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. NonTransactionalRemovalLocks now 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 FROM and MOVE PARTITION TO TABLE commit 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. MOVE uses 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::replacePartitionFromImpl has the same ordering but is not reachable — IInterpreter::checkStorageSupportsTransactionsIfNeeded rejects any transaction touching a storage that supports replication, so a replicated table never holds a part with an uncommitted transactional creator.

A non-transactional DETACH has to both copy the parts to detached/ 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 _tryN directory 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 under detached/, so a later ATTACH PARTITION restores just that prefix. renameAndCommitEmptyParts now does the whole thing under the one parts lock it precommits the empty parts with: it checks removability, copies the covered parts, and calls MergeTreeData::Transaction::commit with 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. StorageReplicatedMergeTree clones inside the removal's own parts lock for the same reason. Holding the lock across the copy is cheap here: for a plain MergeTree the copy is a hardlink-based freeze, since copy_instead_of_hardlink in makeCloneInDetached is gated on supportsReplication.

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

  • 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 (a server abort in debug builds) when a non-transactional DROP PARTITION, DETACH PARTITION, DROP PART, REPLACE PARTITION FROM or MOVE PARTITION TO TABLE covered a part whose creating transaction had not committed yet, leaving that part with creation_csn = 0 and removal_csn = 1. Such an operation now fails with SERIALIZATION_ERROR and 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

  • Documentation is written (mandatory for new features)

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

Version info

  • Merged into: 26.9.1.1299 (included in 26.9 and later)

@clickhouse-gh

clickhouse-gh Bot commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ae6d4c]

Summary: ✅


AI Review

Summary

This PR hardens non-transactional MergeTree removals against uncommitted creators, batch-partial stamping, and stale DETACH clone targets. The remaining blocker is that the new non-transactional DETACH flow commits the removal before writing the detached/ copy, so an ordinary clone I/O exception now turns a failed DETACH into a destructive operation. There is also still a narrower false-positive window in the TransactionLog::getCSN fallback that contradicts the PR description. I would not merge it as-is.

Findings

❌ Blockers

  • [src/Storages/StorageMergeTree.cpp:2915-2940,3056-3059,3171-3174] DETACH is now committed before clonePartsToDetached starts copying the removed parts. makeCloneInDetached still does real filesystem I/O and can throw, so a mid-loop failure leaves the empty covering parts active, the source parts already Outdated, and only a prefix of the partition present under detached/. The statement fails, but ATTACH PARTITION can no longer restore the full partition.
    Suggested fix: stage the detached copy before publishing the removal, or add a rollback path that re-activates the removed parts if any post-commit clone fails.

⚠️ Majors

  • [src/Interpreters/MergeTreeTransaction/VersionMetadata.cpp:137-158] [dismissed by author -- https://github.com/Fix logical error on a non-transactional DROP PARTITION over an uncommitted part #105116#discussion_r3982014090] isCreatedByUncommittedTransaction / isCreationCommitted still call TransactionLog::getCSN(creation_tid) without a strict fallback, so a creator can already be committed globally and still look "uncommitted" until tid_to_csn catches up. That means non-transactional DROP / DETACH / REPLACE / MOVE can still throw a spurious SERIALIZATION_ERROR in exactly the "committed but creation_csn not written yet" window that the PR body says is handled.
    Suggested fix: either narrow the PR claim and coverage to the smaller guarantee it actually provides, or make these helpers observe the commit-point CSN synchronously instead of relying on the async tid_to_csn map alone.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 5ae6d4c.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 131/148 (88.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 16, 2026
@antonio2368 antonio2368 self-assigned this Jun 2, 2026

@antonio2368 antonio2368 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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:

  1. Covered part A is already committed, so setAndStoreNonTransactionalRemovalTID succeeds and persists removal_tid = Tx::NonTransactionalTID / removal_csn = Tx::NonTransactionalCSN.
  2. Covered part B was created by an in-flight transaction whose creation_csn has not been published yet, so the new guard throws SERIALIZATION_ERROR.
  3. MergeTreeData::Transaction::commit exits before the later NOEXCEPT_SCOPE that activates the new empty covering part and moves covered parts to Outdated.
  4. 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Wouldn't this catch LOGICAL_ERROR also which is wrong?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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.

tuanpach added a commit to tuanpach/ClickHouse that referenced this pull request Jun 3, 2026
`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.
tuanpach added a commit to tuanpach/ClickHouse that referenced this pull request Jun 3, 2026
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.

@tuanpach tuanpach left a comment •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

(removed)

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1052 1110 +5.5% <0.0001 This PR only touches non-transactional part-removal batching (DROP/DETACH/REPLACE/MOVE PARTITION); ClickBench Q28 is a read-only SELECT that never exercises that path, and CPU time is flat (15503 vs 15507 ms), so the +5.5% is run-to-run variance.

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
  • StressHouse run: 394f582a-5739-4099-8701-d55fba5f3daa
  • MIRAI run: 9859bb76-b08e-4517-aead-542b38da0723
  • PR check IDs:
    • clickbench_186282_1789227617
    • clickbench_186288_1789227617
    • clickbench_186294_1789227617
    • tpch_adapted_1_official_186305_1789227617
    • tpch_adapted_1_official_186318_1789227617
    • tpch_adapted_1_official_186328_1789227617

/// 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should we do TransactionLog::getCSN(current_info.creation_tid)? same question for above

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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.

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why no-encrypted-storage?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Removed it.

wait "$insert_pid"

# Both committed rows must still be visible.
$CLICKHOUSE_CLIENT -q "SELECT count() FROM t_truncate_non_tx_partial_removal"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

should this be inside a transaction to verify it works?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

No need to put it inside a transaction. The above INSERT is already committed.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 04242 is gone in 9f39b6a (the TRUNCATE case it covered is already fixed in master by #109598). Its replacement 05162 keeps the same shape — a committed part plus a part whose creating transaction is still open — but drives it with DROP PARTITION, which #109598 did not change.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

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.

@tuanpach

tuanpach commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

Sorry, I will work on it.

tuanpach added 5 commits July 9, 2026 00:48
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.
@tuanpach
tuanpach force-pushed the fix-truncate-tx-insert-race branch from ccad250 to f8f46fb Compare July 9, 2026 02:59
Left behind when the per-call preflight was hoisted out to
`Transaction::commit`. Fixes the Style check on ClickHouse#105116.
@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.70% 85.80% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.80% 77.90% +0.10%

Changed lines: Changed C/C++ lines covered: 49/56 (87.50%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

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.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 On the two blockers in the latest AI review — one is implemented (d5a853d), the other I believe is misdiagnosed.

Blocker 2 (REPLACE / MOVE precheck does not reserve removal_tid) — implemented, with a correction to the reasoning.

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. MergeTreeData::Transaction::commit and removePartsFromWorkingSet are the only places that lock an Active part for removal, and both flip it to Outdated in the same parts-lock critical section — so a concurrent transactional remover cannot leave an Active part locked for another observer to find. I tried to build the suggested regression (BEGIN TRANSACTION; TRUNCATE, then a non-transactional REPLACE PARTITION FROM from another session) and it produced no SERIALIZATION_ERROR at all, because the transactional TRUNCATE had already moved the part out of the active set.

What is reachable is MergeTreeTransaction::rollback: it calls restoreAndActivatePart first and clears removal_tid / unlockRemovalTID afterwards, outside the parts lock, so a part is briefly Active and still locked. Reaching that window from a test needs fault injection, and this pull request deliberately removed its last failpoint, so the check ships without a dedicated test rather than with one that does not reach the branch. 05175 covers the creator-state branch.

Blocker 1 (getCSN false-positive window) — pre-existing, and strictly narrowed by this pull request.

The window is real and the description of the ordering is right: the CSN znode is created, afterCommit then stamps creation_csn on each part, and runUpdatingThread populates tid_to_csn later still.

But this is not something the pull request introduces. Before it, 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. Adding the TransactionLog::getCSN fallback strictly shrinks the window; the review itself calls it "the existing … window". For comparison, the behaviour being replaced in that same 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, as the review suggests. That is a change to the transaction-log commit protocol affecting every reader of tid_to_csn, not to the removal guard, and it does not belong in a bug fix for the abort. VersionMetadata has no atomic creation_csn to pass as getCSNAndAssert's 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 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`.
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 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. dropPartition / dropPart hold lockOperationsWithParts(), which only the partition commands themselves take (StorageMergeTree.cpp:2948, 3015, 3128 and the REPLACE / MOVE pair) — INSERT does not. stopMergesAndWait() blocks merges, not inserts. So between the precheck and MergeTreeData::Transaction::commit, a transactional INSERT can land a new part in the partition; getActivePartsToReplace recomputes the covered set at commit time, picks it up, and NonTransactionalRemovalLocks::lock then throws — after makeCloneInDetached has run.

But that outcome is not introduced here. In exactly that sequence, before this pull request, setAndStoreRemovalTID wrote creation_csn = 0 + removal_csn = 1 and validateInfo threw LOGICAL_ERROR from the same place in renameAndCommitEmptyParts — leaving the same orphan detached/ clone in a release build — and aborted the server in debug and sanitizer builds. The reachability of the orphan clone is unchanged; what changed is that the error is now a retryable SERIALIZATION_ERROR instead of a logical error or a crash. The window this pull request did newly open (a refused removal for a part selected at the start) is closed by 4a83a2d, and 05161 asserts it with a control run.

What the required action actually costs. Making the precheck a reservation means holding one DataPartsLock across select → check → lock → makeCloneInDetached → renameAndCommitEmptyParts, i.e. cloning part data to detached/ (disk I/O, potentially large) while holding the lock that every insert and every read of the part set needs. The alternative the review offers — move the clone after the removal can no longer throw — is the better shape and is already how the transactional path works (dropPartsImpl clones after outdatePart), but it reorders the partition-command path for all engines and all callers.

Either way it is a behavioural restructure of ALTER TABLE … DROP/DETACH PARTITION, not a narrowing of the abort fix, and it changes lock-hold characteristics on a hot path. I would rather not fold it into a bug fix that is green and whose regression is covered, and instead do it as a follow-up where it can be reviewed and perf-checked on its own. Happy to open that follow-up now, or to fold it in here if you would rather have it in one change — just say which.

alexey-milovidov and others added 2 commits September 12, 2026 05:13
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]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
alexey-milovidov and others added 2 commits September 12, 2026 10:34
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass of 2026-09-12: the AI Review blocker is adopted, and the one red is unrelated and now fixed on master.

Blocker — renameAndCommitEmptyParts returned the precommit selection. Adopted in a9d06b606129.

The finding is right. covered_parts is accumulated by renameTempPartAndReplaceUnlocked under a parts lock that is released before MergeTreeData::Transaction::commit reacquires it and recomputes the covered set with getActivePartsToReplace. When a covering part appears in that window, commit marks the empty part obsolete and removes nothing at all, yet the old code still undelayed the stale selection with remove_time = 0, dropped it from the deduplication log, and — through the value handed to dropPart / dropPartition — cloned it into detached/ while it was still active.

commit already returns total_covered_parts, so the fix is exactly the suggested one: take that vector and use it for all three. The LOG_INFO now prints both counts, so a divergence is visible in the log. All three call sites run with txn == nullptr, so commit does not fold covered_outdated_parts into the returned vector — it is exactly the set this statement removed.

Tests note. 05176 pins the invariant positively (DETACH PARTITION and DETACH PART clone exactly what was removed, re-ATTACH restores every row, DROP clones nothing), and 05161 pins the negative half. The divergence itself is not reachable from a test without fault injection: lockOperationsWithParts serialises the partition commands, an INSERT lands above the empty part's block range so it is never covered, and merges are held off by stopMergesAndWait — the only producer of a covering part in that window is a merge rolled back after stopMergesAndWait returned, which is why the code logs that case explicitly. Adding a failpoint in the merge commit path to reach it is a larger change than the fix; I would rather not grow this bug fix by it.

Upgrade check (amd_release) — Logical error: Virtual row has different type for A. Expected B, got C.

Not caused by this pull request, and already fixed on master:

  • the abort is in setVirtualRow / MergingSortedAlgorithm::initialize over a sorting key of CAST(json.b, 'String') — read-in-order virtual rows, nothing to do with transactions or part removal;
  • it is fleet-wide: 66 failures over 2026-09-10..2026-09-12 across 64 different pull requests, including master itself (pull_request_number = 0, first seen 2026-09-10 16:22 on ad8622edd0f);
  • the fix is Fix wrong results when a sorting key expression's type depends on a session setting #119385 ("Fix wrong results when a sorting key expression's type depends on a session setting"), merged into master on 2026-09-12 10:39.

master is merged in (5ae6d4c121f6, clean, no conflicts), so the next run picks the fix up.

Verification. ninja clickhouse-bundle then ninja clickhouse, 0 errors; check_cpp.sh clean. Against a local server: 05161, 05162, 05175, 05176, 04057–04060, 01173, 03812 and the detach_part / drop_part / detach_partition / drop_partition families all pass (the only non-pass is 04622_detach_partition_fsync_part_directory, which needs system.part_log that a minimal server does not have).

The CH Inc sync red was on the old head; the private mirror is MERGEABLE again after the master merge.

Comment thread src/Storages/StorageMergeTree.cpp Outdated
/// 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();

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.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 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 _tryN buildup on retries (05161 asserts this, and it still passes);
  • a clone that fails on I/O fails the statement with the parts still Active — the Transaction destructor 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).

alexey-milovidov and others added 2 commits September 12, 2026 16:36
`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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pass of 2026-09-12 (third): the new AI Review blocker is adopted, master is merged in, and the tree is green locally.

Blocker — post-commit clone made DETACH exception-unsafe. Adopted in 1afe40dbb74d.

The previous round moved the detached/ copy after the removal; this round points out that this made an ordinary makeCloneInDetached I/O failure destructive — empty covering parts active, sources Outdated with remove_time = 0, only a prefix of the partition under detached/. Both findings are real and they point in opposite directions, so rather than pick an order, the copy and the removal now happen under the same lock.

renameAndCommitEmptyParts takes a clone_to_detached flag and, while still holding the parts lock it precommitted the empty parts under, checks removability, clones the covered parts, and calls MergeTreeData::Transaction::commit(part_lock) with that lock instead of letting commit reacquire it. The covered set cannot change in between, so the copy is of exactly the parts that are removed; a refused removal is refused before anything is copied (no orphan, no _tryN buildup — 05161's assertion still holds); and a failed copy fails the statement with the parts still active, the Transaction destructor rolling the empty parts back.

I had argued on 2026-09-12 00:41 that this shape costs too much because it holds DataPartsLock across a data copy. That was wrong for this path: copy_instead_of_hardlink in makeCloneInDetached is gated on supportsReplication(), so for a plain MergeTree the copy is a hardlink-based freeze. StorageReplicatedMergeTree clones inside the removal's own parts lock already, so all three engines now do the same thing.

The remaining Major (the TransactionLog::getCSN window) is [dismissed by author] in the verdict itself — it is pre-existing and strictly narrowed here, as adjudicated at #105116 (comment).

CI. No failures on 5ae6d4c1 — the Upgrade check red of the previous pass is gone (it was fleet-wide and fixed by #119385). The only non-green check is CH Inc sync, which is pending; master is merged in again (b35849825ea3, clean, no conflicts) so it re-bases on a current head.

Verification. ninja clickhouse-bundle then ninja clickhouse, 0 errors; check_cpp.sh clean. Against a local server after the master merge: 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, 04057–04060 — 26 of 26 pass.

Merged via the queue into ClickHouse:master with commit 68afe27 Sep 12, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 15, 2026
…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.
@ClickHouse ClickHouse deleted a comment from clickgapai Sep 21, 2026
@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

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 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.

Received signal 6 (internal) (STID: 3563-49ac)

7 participants