Skip to content

Retry transaction metadata writes in noexcept commit and rollback - #123134

Merged
tuanpach merged 20 commits into
ClickHouse:masterfrom
filimonov:fix/transaction-metadata-write-retry
Nov 10, 2026
Merged

tuanpach merged 20 commits into
ClickHouse:masterfrom
filimonov:fix/transaction-metadata-write-retry

Conversation

@filimonov

@filimonov filimonov commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

COMMIT of a MergeTree transaction terminates the server when a write of transaction metadata fails. MergeTreeTransaction::afterCommit is noexcept; it writes txn_version.txt of each part and the CSN into mutation_N.txt, and any storage exception there ends in std::terminate. Retry transient errors for a bounded time instead.

Why terminate was the only option

Changes

  • retryTransientStoreError wraps the two writes: txn_version.txt in VersionMetadataOnDisk::storeInfoToDataPartStorage, mutation_N.txt in StorageMergeTree::setMutationCSN (each attempt takes currently_processing_in_background_mutex afresh, nothing is held between attempts).
  • Retries happen only inside a TransientStoreRetryScope, opened by afterCommit and rollback, with one 60 s budget per callback. On a query path the first error goes to the client as before: a retry there would hold the query's table locks, and on ENOSPC block the cleanup that could free space.
  • Transient = isRetryableException plus the errnos of a failed local write (ENOSPC, EDQUOT, EROFS, EIO, EBUSY, ETIMEDOUT, EAGAIN), minus memory limits. Anything else, an exhausted budget, or a server shutdown rethrows at once, so a lost write is never silent.
  • MergeTreeMutationEntry::writeCSN rewrites the whole record through a temporary file instead of appending a csn: line, so a retry is idempotent. loadMutations tolerates a temporary file consumed by a repair in the same pass.
  • The directory sync after the rename (fsync_part_directory) is explicit, ISyncGuard::sync: the guard's destructor only logs a failed fdatasync, so a non-durable rename passed as success.
  • StorageMergeTree::setMutationCSN logs a warning instead of LOGICAL_ERROR when KILL MUTATION erased the entry between the log write and afterCommit; that throw also terminated the server.

Risks / notes

  • A commit or rollback can block its thread for up to 60 s while storage is failing. A persistent error still ends in std::terminate after the budget; a read-only mode with an in-process reload would be the better answer and is a separate change.
  • rollback already logs and continues on a failed write (Split TransactionLog into TransactionManager, TransactionLog and TransactionSession #117822). The retry is added inside those try blocks; before it, a failed removal_tid clear left the part locked until restart, and later DROP PARTITION/mutations over it failed with SERIALIZATION_ERROR.
  • On a query path a failed directory sync is now thrown to the client instead of logged.
  • killMutation is not retried: it erases the map entry before deleting the file.
  • Test-only failpoints: transaction_metadata_store_fail, transaction_mutation_csn_store_fail, transaction_mutation_csn_store_fail_after_write, local_directory_sync_fail (ONCE), transaction_pause_before_mutation_csn_store (pauseable).

Testing

  • 05315_transaction_metadata_store_retry: one injected failure per scenario. A–D fail before I/O (commit of parts, commit of a mutation, rollback of created parts, rollback of DROP PARTITION); E fails with ENOSPC after the mutation's temporary file is written (one csn: line, no temporary left); F fails with EIO in the part directory sync. Without the retry the commit scenarios terminate the server.
  • 05338_mutation_killed_during_commit: KILL MUTATION while afterCommit is paused before the CSN store. The commit succeeds and the log carries Mutation N was killed before its CSN could be stored; without the change setMutationCSN threw LOGICAL_ERROR.

Related: #99494
Related: #84084
Related: #117822
Related: #115501

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 server termination on COMMIT of a MergeTree transaction when the write of the part's version metadata or of a mutation CSN fails (for example on ENOSPC, a read-only disk, or an object-storage write error); the write is now retried for a bounded time, in ROLLBACK as well. Also fix a server termination when KILL MUTATION raced with the commit of a transactional mutation.


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

Version info

  • Merged into: 26.11.1.1818-master (included in 26.11 and later)

@filimonov
filimonov marked this pull request as draft September 30, 2026 20:13
`MergeTreeTransaction::afterCommit` is `noexcept`. It writes part version
metadata (`creation_csn`, `removal_csn`) and the CSN of a mutation to disk.
A storage error in one of these writes escaped and terminated the server,
although the transaction log already held the outcome and a restart
repairs the files from it. `rollback` catches its errors already; it gets
the same retry so a transient error does not leave the files unrepaired.

The writes now go through a bounded retry with backoff. One 60 s budget
covers the whole callback. `LOGICAL_ERROR` and `NOT_IMPLEMENTED` are
rethrown at once; an exhausted budget or a server shutdown rethrows too,
so a lost write is not hidden. `killMutation` is not retried: it erases
the map entry before deleting the file, so a second attempt cannot finish
the deletion.

In `rollback` the retry covers the `RolledBackCSN` store of the parts the
transaction created and the `removal_tid` clear of the parts it was removing
(`resetRemovalTID`); a swallowed storage error in the latter left the part
removal-locked until restart. Its `ABORTED` and `NO_SUCH_DATA_PART` outcomes
are answers of the fingerprint check and of a peer's removal, not storage
errors, and are not retried.

`MergeTreeMutationEntry::writeCSN` appended one line to the mutation file,
so a write that failed half-way or was repeated could leave a partial or
duplicate `csn` line, which the loader rejects. It now rewrites the whole
record through a temporary file, which makes a retry idempotent.
`loadMutations` lists the directory before touching any file, and
tolerates a temporary file that a repair in the same pass has already
consumed.
@filimonov
filimonov force-pushed the fix/transaction-metadata-write-retry branch from 246746d to c848b98 Compare September 30, 2026 20:20
@filimonov
filimonov marked this pull request as ready for review September 30, 2026 20:21
@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization labels Sep 30, 2026
@filimonov filimonov mentioned this pull request Oct 1, 2026
1 of 74 tasks
@filimonov

Copy link
Copy Markdown
Contributor Author

fsync for directory is missing...

@murphy-4o
murphy-4o requested a review from tuanpach October 7, 2026 06:48
@murphy-4o murphy-4o added the can be tested Allows running workflows for external contributors label Oct 7, 2026
@murphy-4o

Copy link
Copy Markdown
Member

@copilot resolve the merge conflicts in this pull request

@clickhouse-gh

clickhouse-gh Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f4e56b1]

Summary: ✅


AI Review

Summary

PR #123134 adds bounded retries for transient transaction-metadata write failures during COMMIT and ROLLBACK, makes mutation-CSN writes idempotent, and handles concurrent KILL MUTATION. Reviewed head f4e56b100596e1994a9f2d937a5de6e815b99010; no unresolved actionable findings remain.

Missing context / blind spots
  • ⚠️ Current-head CI is still running; execution results for the added regression tests are not yet available. No local build or test binary is available. Completed current-head runs of 05315_transaction_metadata_store_retry and 05338_mutation_killed_during_commit would close this validation gap.
Final Verdict

✅ Approve — no additional code changes requested. Current-head CI should complete before merge.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 7, 2026
filimonov and others added 2 commits October 7, 2026 17:34
`writeCSN` renames a temporary file over `mutation_N.txt`; without a directory fsync a power loss after the file sync can bring back the old file without the `csn:` line, or only `tmp_mutation_csn_N.txt`, which the loader removes. Gate it on `fsync_part_directory` like `txn_version.txt`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
…etadata-write-retry

# Conflicts:
#	src/Storages/StorageMergeTree.cpp
The style check requires `no-parallel` and `no-fasttest` on every test that arms a fail point.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
…tryableException

Move the retry from MergeTreeTransaction, which does not know what storage a VersionMetadata
writes to, into the two disk writes: VersionMetadataOnDisk::storeInfoToDataPartStorage and
MergeTreeMutationEntry::writeCSN. Retry only what isRetryableException calls transient; every
other error is rethrown at once, so no error code is special-cased. One 60 s budget per write.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
filimonov and others added 4 commits October 10, 2026 23:14
… broken disks

`isRetryableException` lists the read-side errnos only; a local write fails
with `ENOSPC`, `EROFS`, `EIO`, which its `filesystem_error` branch already
treats as transient. Memory limits belong to the calling query and were
retried under its locks (`removePartsFromWorkingSet` holds `DataPartsLock`).

`loadMutations`: `listFiles` throws on a broken disk or a disk without the
table's directory, where `iterateDirectory` is empty; snapshot through the
iterator.

`storeInfoToDataPartStorage`: remove a leftover temporary file before the
exclusive `createFile`, so an attempt whose cleanup failed does not wedge
the next one on `CANNOT_CREATE_FILE`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`DiskLocal::replaceFile` is `fs::rename` and reports `EIO` or `EDQUOT` as
`std::filesystem::filesystem_error`, which the `ErrnoException` branch does
not see and the `filesystem_error` branch of `isRetryableException` does not
list.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…r callback

`removePartsFromWorkingSet` writes the removal metadata under `DataPartsLock`;
a retry there held the lock for 60 s on `ENOSPC` and blocked the part
cleanup that could free the space. On a query path the client gets the
error, as before. `afterCommit` and `rollback` open a
`TransientStoreRetryScope`, which is also the 60 s budget shared by all
their writes instead of 60 s per part.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The empty `catch (...)` failed the style check and `bugprone-empty-catch`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Storages/StorageMergeTree.cpp Resolved
filimonov and others added 4 commits October 11, 2026 08:46
`createFile` refusing an existing `txn_version.txt.tmp` is deliberate: a
leftover of an interrupted write must fail the store, as
`test_broken_tmp_txn_version_startup::test_packed_part_stale_txn_version_guard`
checks. Removing the file before `createFile` disabled that guard and the
test failed in every integration job. A retried attempt needs no removal
here: the `catch` block already removes the temporary file of the failed
attempt, and when that removal fails too the next attempt gets
`CANNOT_CREATE_FILE`, which is not transient and is rethrown.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
When a failed attempt cannot remove its temporary file (the removal hits
the same transient error), the next attempt would get `CANNOT_CREATE_FILE`
from `createFile`, which is not transient, and the commit would give up
even after the storage recovers. `own_tmp_left` records that the file was
created by this call; only then is it removed before `createFile`. A file
left by an earlier, interrupted write still fails the store, as
`test_packed_part_stale_txn_version_guard` expects.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
`transaction_pause_before_mutation_csn_store` pauses `afterCommit` after
the transaction log commit and before `setMutationCSN`. The test kills the
mutation in that window: the entry is gone when the CSN is stored, the
commit must succeed, and `setMutationCSN` logs `Mutation N was killed
before its CSN could be stored` instead of throwing `LOGICAL_ERROR` out of
the `noexcept` callback.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@filimonov
filimonov requested a review from tuanpach October 13, 2026 17:41
Comment thread src/Storages/StorageMergeTree.cpp Resolved

/// Marks the scope of the `noexcept` commit and rollback callbacks of `MergeTreeTransaction`,
/// whose metadata writes have no caller to report an error to. The scope carries the retry
/// budget of `retryTransientStoreError`, 60 seconds shared by all the writes made inside it.

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.

60s is quite long.
We can pass this as a parameter to TransientStoreRetryScope.
WDYT if we also limit it with max_attempts instead?
If we have 3 parts, and storing the 1st part exceeds the budget (60s), other parts don't have a chance to retry.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

60s is long, but the alternative is worse: when we give up here the server calls std::terminate, and a restart means minutes of loading parts. So the question is really "how long can a commit hang before we crash the server", and 60s looks cheap next to that. Also with s3 disks (plain rewritable etc.) you do get SlowDown / throttling for seconds, and the s3 client has its own retries under ours, so a single attempt can already take tens of seconds.

That's also why I went with time instead of max_attempts. One attempt can take a millisecond (DNS refuses) or 30 seconds (PUT times out), so a count doesn't really bound anything: N × timeout is way too long, N × 1ms doesn't survive a 20-second DNS restart. Fast errors are already kept in check by the backoff (100ms → 2s cap, ~35 attempts in 60s).

The budget is per callback, not per write, on purpose. Per write, a commit with K parts could hang K × 60s. And if any part's write gives up, the commit terminates anyway, so the other parts don't get a second chance in either scheme. In rollback, which logs and continues, they still get their first attempt.

Passing the budget to TransientStoreRetryScope is easy, but nobody would pass anything other than the default today. If you'd rather have it as a server setting than a constant, I can do that.

Longer term I think the right answer for the give-up path is a read-only table + in-process reload (like restart replica, but for non-replicated tables) instead of a server restart. That's a separate change though.

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.

Considering this is a workaround, we have no better option than to wait.

I think a long-term solution is to allow failures when storing CSN and have it self-heal afterward.

@tuanpach tuanpach self-assigned this Oct 14, 2026
filimonov and others added 2 commits October 15, 2026 00:27
… mutex

`MergeTreeMutationEntry::writeCSN` retried under
`currently_processing_in_background_mutex`, held by `setMutationCSN` for the
whole budget. The retry now wraps the lookup as well: every attempt takes
the mutex and finds the entry again, and the waits between attempts hold
no lock. `writeCSN` writes once; its other caller, `loadMutations`, runs
outside a `TransientStoreRetryScope`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
tuanpach and others added 4 commits October 19, 2026 14:11
…retry

`LocalDirectorySyncGuard` syncs in its destructor and logs a failure, so with
`fsync_part_directory` a non-durable rename of `txn_version.txt` or
`mutation_N.txt` passed as a success. `storeInfoToDataPartStorage` and
`writeCSN` now call `ISyncGuard::sync` after `replaceFile`.

Test `05315` gets two scenarios that fail after I/O started: `ENOSPC` after
the mutation's temporary file is complete, and `EIO` from the directory sync.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
Scenario F of 05315 threw before the explicit `sync` call, so it passed
with the destructor-only sync it is meant to catch. The failpoint now
fires inside `sync`: left to the destructor the error is logged and the
write passes, so no retry line appears and the test fails.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Mikhail Filimonov <[email protected]>
@filimonov
filimonov requested a review from tuanpach November 3, 2026 23:32
@tuanpach
tuanpach added this pull request to the merge queue Nov 10, 2026
Merged via the queue into ClickHouse:master with commit 4e5768a Nov 10, 2026
186 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 10, 2026
…k-failed-store-demote

Conflict in src/Interpreters/MergeTreeTransaction/VersionMetadataOnDisk.cpp
(declarations only, after ClickHouse#123134): kept master's CANNOT_WRITE_TO_OSTREAM
and both FailPoints blocks, added FAULT_INJECTED and
version_metadata_on_disk_store_fail.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... external Author is not a member of the ClickHouse organization 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.

4 participants