Skip to content

Undo non-transactional removal marks when MergeTreeData::Transaction::commit fails - #115442

Closed
kirillshokhin wants to merge 3 commits into
masterfrom
fix-txn-commit-cleanup-on-exception
Closed

kirillshokhin wants to merge 3 commits into
masterfrom
fix-txn-commit-cleanup-on-exception

Conversation

@kirillshokhin

@kirillshokhin kirillshokhin commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

MergeTreeData::Transaction::commit marks covered parts as removed before the
NOEXCEPT_SCOPE that moves them to Outdated, because that marking can fail: a
concurrent transaction may hold the removal lock, and storing txn_version.txt can
fail on I/O. For a non-transactional commit nothing undid the marks that had already
been written (#97211 fixed only the dangling lock part, not the marks), so those parts stayed Active with removal_tid = Tx::NonTransactionalTID
and removal_csn = Tx::NonTransactionalCSN.
After #92141 the lock is released inline and that lock cleanup became obsolete, yet the vector #97211 introduced to collect the parts was still filled and never read.

Such a part is inconsistent in several ways:

  • it is invisible to every transactional read while non-transactional reads still
    return its rows;
  • TRUNCATE skips it silently from then on;
  • canBeRemoved short-circuits to true for a non-transactional removal, so the part
    may be deleted as soon as anything moves it to Outdated, ignoring
    old_parts_lifetime;
  • if the part carries txn_version.txt, i.e. it was created or removed by a
    transaction, the inconsistency is persisted, survives a restart, and the part is
    then loaded as removed.

The failure is reachable because MergeTreeTransaction::rollback restores the parts of
a rolled-back removal to Active and only resets and unlocks their removal TID in a
second loop, without holding the parts lock in between. A non-transactional TRUNCATE
or DROP PARTITION covering such a part gets SERIALIZATION_ERROR in the middle of
the loop, after earlier parts have already been marked.

Track the covered parts that were marked and reset removal_tid and removal_csn for
them if the loop throws. Only the non-transactional branch needs this: for transactions
MergeTreeTransaction::rollback already resets and unlocks. The undo is best effort —
every failure is logged per part, and the number of parts left inconsistent is appended
to the propagated exception together with a pointer to system.parts.

The second commit removes the getActivePartsToReplace call that was repeated inside
NOEXCEPT_SCOPE. The parts lock is held for the whole of commit, and parts in
precommitted_parts never cover each other, so the values computed before the scope
stay valid and are now reused. That also removes a termination path, since
getActivePartsToReplace throws LOGICAL_ERROR for intersecting or duplicate parts and
any exception inside NOEXCEPT_SCOPE reaches std::terminate.

Two failpoints and two tests cover the two ways the marking loop can fail:
04838_truncate_and_drop_part_transaction_rollback_race freezes a transaction rollback
between restoring the parts and unlocking their removal TID, then checks that a
concurrent TRUNCATE fails with SERIALIZATION_ERROR and leaves no part marked as removed;
04839_fail_to_remove_covered_part_in_the_middle_of_the_list injects a failure after
the first covered part of a merge has been marked.

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

Fixed a case where a failed non-transactional TRUNCATE, DROP PARTITION or merge left covered parts Active but marked as removed. Such parts were invisible to transactional reads while non-transactional reads still returned their rows, were silently skipped by later TRUNCATE queries, could be deleted ignoring old_parts_lifetime, and for parts carrying txn_version.txt the inconsistency survived a restart. This was only reachable when transaction were enabled.

Related: #96023
Related: #97211
Related: #92141


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

…::commit` fails

`MergeTreeData::Transaction::commit` marks the covered parts as removed before the
`NOEXCEPT_SCOPE` that moves them to `Outdated`, because that marking can fail:
a concurrent transaction may hold the removal lock, and storing txn_version.txt can fail
on I/O.
For a non-transactional commit nothing undid the marks that had already been
written, so those parts stayed `Active` with `removal_tid = Tx::NonTransactionalTID` and
`removal_csn = Tx::NonTransactionalCSN`.

Such a part is inconsistent in several ways:
 * it is invisible to every transactional read while non-transactional reads still return
   its rows;
 * `TRUNCATE` skips it silently from then on;
 * `canBeRemoved` short-circuits to true for a non-transactional removal, so the part may
   be deleted as soon as anything moves it to `Outdated`, ignoring `old_parts_lifetime`;
 * if the part carries `txn_version.txt`, i.e. it was created or removed by a transaction,
   the inconsistency is persisted and survives a restart and the part is then loaded as
   removed.

The failure is reachable because `MergeTreeTransaction::rollback` restores the parts of a
rolled-back removal to `Active` and only resets and unlocks their removal TID in a second
loop, without holding the parts lock in between. A non-transactional `TRUNCATE` or
`DROP PARTITION` that covers such a part gets `SERIALIZATION_ERROR` in the middle of the
loop, after earlier parts have been marked.

The vector that used to collect these parts in commit was dead code — it was filled but
never read.

Track the covered parts that were marked and reset `removal_tid` and `removal_csn` for
them if the loop throws. Only the non-transactional branch needs it: for transactions
`MergeTreeTransaction::rollback` already resets and unlocks.

The undo is best effort: every failure is logged per part, and the number of parts left
inconsistent is appended to the propagated exception with a pointer to `system.parts`.
`MergeTreeData::Transaction::commit` holds the parts lock for its whole
duration, so no other thread can change the set of active parts. The loop
inside `NOEXCEPT_SCOPE` does change it via `modifyPartState`, but parts in
`precommitted_parts` never cover each other, so the changes made for one
part cannot affect the result for another. The values computed before
`NOEXCEPT_SCOPE` therefore stay valid and are now reused from
`overlapping_parts_for_commit` instead of being recalculated.

This also removes a termination path: `getActivePartsToReplace` throws
`LOGICAL_ERROR` for intersecting or duplicate parts, and any exception
thrown inside `NOEXCEPT_SCOPE` calls `std::terminate`.
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [db4de03]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, sequential) FAIL
04839_remove_covered_part_throws_in_the_middle_of_the_list FAIL cidb

AI Review

Summary

This PR fixes a real non-transactional MergeTreeData::Transaction::commit failure mode by undoing already-written non-transactional removal marks when covered-part marking throws, and it reuses the precomputed overlap set during the later NOEXCEPT_SCOPE commit phase. I reviewed the current diff, the touched MergeTree/transaction metadata paths, the added tests, and the prior PR discussion state. I did not find a correctness, safety, compatibility, or test-coverage issue that warrants an inline review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.30% +0.10%

Changed lines: Changed C/C++ lines covered: 128/142 (90.14%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing db4de03e1 with master 581c15c46 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.08 MiB 699.08 MiB -3.00 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

8 object files changed (+38.75 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 3.96 MiB 3.98 MiB +21.96 KiB (+0.54%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@tuanpach tuanpach self-assigned this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@tuanpach

Copy link
Copy Markdown
Member

@groeneai Is it fixed by #105116?

@groeneai

Copy link
Copy Markdown
Collaborator

Yes for the case in the title, and #105116 is what fixed it: it prevents the partial state instead of undoing it.

On master (0d04f2bc) a non-transactional removal batch is locked first and stamped afterwards. NonTransactionalRemovalLocks::lock refuses a conflict before anything is written, store() runs only once the whole batch is locked, and locks that never get stored are released by the destructor (MergeTreeData.cpp:11277-11285 in Transaction::commit, :7043-7047 in removePartsFromWorkingSet).

Against the two tests in this PR:

  • 04838: the non-transactional TRUNCATE covers the parts with empty ones and lands in Transaction::commit, so all four covered parts go into one removal_locks batch and part 3's conflict with the paused ROLLBACK surfaces from lock(), before any of them is stamped. Same shape as the merged 05161 and 05162.
  • 04839: not covered, but the site moved. store() (MergeTreeTransaction.cpp:150-163) stamps the batch part by part, so a throw between two setAndStoreRemovalTID calls still leaves a durably removed prefix. Only the metadata write itself can throw there now (STALE_VERSION after the retries in updateInfoWithRefreshDataThenStoreAndSetMetadata, or an I/O error out of storeInfo); the conflicts that used to reach that point are refused in lock().

The second commit here is independent of #105116: master still recomputes getActivePartsToReplace inside NOEXCEPT_SCOPE (MergeTreeData.cpp:11304), that call throws LOGICAL_ERROR for an intersecting or duplicate part, and NOEXCEPT_SCOPE converts any throw into std::terminate (src/Common/noexcept_scope.h). Dropping it is not quite a no-op though: the pre-scope results are computed before any precommitted part is moved to Active at :11343, so for a multi-part batch the recomputed covering_part can differ. No CI trace of it in the last 45 days:

SELECT count() FROM default.checks
WHERE check_start_time > now() - INTERVAL 45 DAY AND test_status IN ('FAIL', 'ERROR')
  AND position(test_context_raw, 'getActivePartsToReplace') > 0
-- 0

@tuanpach tuanpach closed this Sep 14, 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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants