Repository navigation
Run the rollback of a local metadata transaction to completion - #123888
Michicosun merged 5 commits into
Conversation
`MetadataOperationsHolder::rollback` stops at the first `undo` that throws and leaves every operation below it executed. On an object storage disk with `local` metadata that loses data: a removal that decremented the hard link counts of a part's files and then failed keeps the counts decremented when restoring one of them fails, and the next removal of another link of those files deletes their blobs. Seen in `Stress test (arm_tsan)` on ClickHouse#110626, where `DROP DETACHED PARTITION` failed on an injected memory limit, its rollback failed on the same fault while restoring a count, and a concurrent `DETACH` then deleted the blobs of the detached part that `ATTACH PARTITION` read next. Following ClickHouse#119235 (`plain_rewritable`), the rollback now runs to the end: - `MetadataOperationsHolder::rollback` blocks memory-limit exceptions and their fault injection. A rollback runs inside the `catch` of `commit`, where the memory tracker may throw, and a query at its own limit cannot free memory before its rollback ends. - Every step of an `undo` of a local operation repeats until it succeeds. The retry loop of ClickHouse#119235 moves to `MetadataStorages/UndoWithRetries` with the profile event as a parameter; the plain-rewritable entry point forwards to it with its own event, and `local` metadata counts `MetadataFromDiskUndoStageRetries`. - Each operation records what its `execute` did, so its `undo` reverts only that and each step can fail only on a real error. Before, a move onto an existing file, `createDirectory` of an existing non-empty directory, `chmod` of a missing file or a failed read of the old modification time made the `undo` throw, which stopped the rollback with no fault at all; `createHardLink` deleted a destination it did not create (also one that already was a link to the same file), and `WriteFileOperation` deleted an existing file whose read failed. - `RemoveRecursiveOperation` restores its count writes in reverse order: two links to one file inside the removed tree ended one count too low after a complete rollback. - `DiskLocal::removeDirectoryIfExists` checked a path that already carried the disk path, so for a relative disk path it never removed anything and the rollback of `createDirectoryRecursive` left the directories behind. A step that keeps failing on an I/O error now holds the rollback, and the metadata lock with it, instead of returning with the metadata half rolled back, as for `plain_rewritable`. The order of the steps is unchanged; a crash during a rollback is still not covered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold review (3 nits).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20261004-184900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20261004-154600 |
|
Workflow [PR], commit [8e632a1] Summary: ✅
AI ReviewSummaryThis change protects metadata rollback from memory-limit exceptions, records which local disk operations need undoing, and restores recursive-removal writes in reverse order. Two data-loss paths remain: an allocation can prevent rollback from starting, and the previously reported hard-link undo ordering still permits an undercount after an unlink failure. Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block. Ensure rollback starts before fallible diagnostic work, and remove newly created links before decrementing their shared counts during undo. Add the focused failure-path coverage above. |
Michicosun
left a comment
There was a problem hiding this comment.
explain the problems with the log examples from a failed test.
Disk operations should not be retried in general.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units10 translation units recompiled, 25 s compile time in total, 10 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
Disk operations are not retried. The failure seen in CI is not a disk error: the rollback of `DROP DETACHED PARTITION` stopped because the memory tracker of the query threw an injected `MEMORY_LIMIT_EXCEEDED` while `WriteFileOperation::undo` allocated the write buffer for a restored hard link count. Blocking memory-limit exceptions covers that, and the fault-injection loop on a `local_blob_storage` disk recorded no undo step that had to be repeated. Remove `undoWithRetries` from the local operations and the `MetadataFromDiskUndoStageRetries` event, and keep the plain-rewritable retry loop where it was. Every `undo` calls the disk operation directly again; each operation still records what its `execute` did and reverts only that. The memory-limit lock moves from `rollback` to the start of the `catch` in `commit`, so the message added to the error before the rollback cannot throw either. `WriteFileOperation::undo` removes only a file: a write that failed on an existing directory left nothing to revert, and `unlink` of the directory stopped the rollback. `UnlinkFileOperation` moves the temporary name into `tmp_file_path` instead of copying it, so nothing can throw between the rename and recording it for the undo. The rollback matrix gets rows where the operation succeeds and a later one fails, so each recorded flag is shown to enable its undo. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@Michicosun the failed run is
The rollback was stopped by the memory tracker, not by a disk error. I removed the retries in b76dbee: no disk operation in an
The same DETACH/ATTACH loop with memory faults on a |
`DiskLocal::moveDirectory` is a plain `rename`, which replaces an empty destination directory. `MoveDirectoryOperation::undo` only renamed the directory back, so when a later operation of the transaction failed, the rollback left the replaced empty directory missing. The operation now records that the destination existed and recreates it after moving the directory back. The rollback matrix gets a row where the move onto an empty directory succeeds and a later operation fails. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| void CreateHardlinkOperation::undo() | ||
| { | ||
| if (write_operation) |
There was a problem hiding this comment.
CreateHardlinkOperation::undo restores the shared metadata file before it removes the new hard link. If removeFileIfExists(path_to) then throws (for example on a real metadata-disk error), the rollback stops with both links still present but the refcount already decremented back to the pre-link value. The next unlinkFile will then treat one of those live links as the last one and can delete blobs that the remaining link still needs.
Please delete path_to first and only restore the source metadata after that, so a failed rollback leaves either the committed state or the rolled-back state, but never the undercounted state.
|
This zone should be a no-exception zone; rollback of tx operations on this disk should not fail, especially because of some injected errors. |
Review: ClickHouse#123888 (comment) The rollback of a transaction on the local metadata disk must not fail. Each `undo` now runs in `NOEXCEPT_SCOPE`: the memory limit and its fault injection are blocked there, and any other exception terminates the server instead of leaving the transaction partially rolled back with hard link counts that no longer match the links on disk. Only the local metadata storage opts in. `plain_rewritable` keeps its documented behaviour, where a stage that reports a lost blob with a logical error stops the rollback. The per-operation bookkeeping of this PR is what makes the scope safe: an `undo` now reverts only what its `execute` did, so a failed `execute` no longer makes its own `undo` throw. A death test checks that a failed `undo` reaches `std::terminate`; with the scope disabled the commit throws instead and the test fails. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done in aba3ae393e0b6: each This is safe because each |
|
Another run of this defect, through a different caller, where active parts lose blobs:
Three incomplete rollbacks, three lost blobs, each in the hard-link chain of the part whose rollback stopped. The head of this PR covers this path too (every |
| IDisk & disk; | ||
|
|
||
| bool moved = false; | ||
| /// The rename replaced an empty directory at `path_to`. |
There was a problem hiding this comment.
| /// The rename replaced an empty directory at `path_to`. |
| IDisk & disk; | ||
|
|
||
| std::unique_ptr<WriteFileOperation> write_operation; | ||
| /// False when the destination existed, even as a link to the same file. |
There was a problem hiding this comment.
| /// False when the destination existed, even as a link to the same file. |
| // (safe to delete on undo) from "file already existed, execute() failed | ||
| // before overwriting it" (must NOT delete — the file is unchanged). | ||
| bool file_existed = false; | ||
| /// Set before the write, so a write that stopped part way is undone too. |
There was a problem hiding this comment.
| /// Set before the write, so a write that stopped part way is undone too. |
| { | ||
| auto fs_path = fs::path(disk_path) / path; | ||
| if (!existsDirectory(fs_path)) | ||
| if (!existsDirectory(path)) |
There was a problem hiding this comment.
Reverted in 8e632a1, together with the test that needed it. With an absolute disk_path, which a server always has (getCanonicalPath in Server.cpp), both forms check the same directory; only the relative path of the gtest fixture made them differ.
| if (replaced_destination) | ||
| disk.createDirectory(path_to); |
There was a problem hiding this comment.
that is strange, I suppose in this case move directory in execute will fail.
There was a problem hiding this comment.
Removed in 8e632a1. On Linux the move does not fail: DiskLocal::moveDirectory is fs::rename, which replaces an empty destination directory. But part renames remove or reject an existing destination first (DataPartStorageOnDiskBase::rename), so nothing reaches this case.
| if (noexcept_rollback) | ||
| { | ||
| NOEXCEPT_SCOPE(operations[i]->undo()); | ||
| continue; | ||
| } |
There was a problem hiding this comment.
not needed, exceptions here can be thrown, why do we need to crash in this case?
There was a problem hiding this comment.
Removed in 8e632a1: an undo that throws ends the rollback as partial again, without a crash.
| /// Neither the memory limit nor its fault injection can stop the rollback. | ||
| LockMemoryExceptionInThread lock_memory_exception(VariableContext::Global); | ||
|
|
There was a problem hiding this comment.
Removed from commit() in 8e632a1. I kept LockMemoryExceptionInThread only for the scope of rollback(): without it, the injected memory limit in WriteFileOperation::undo (step 2 of the log) stops the rollback again, and the DETACH/ATTACH loop with memory faults loses 52 blobs in 5 minutes, as on master; with it, none over 2156 rollbacks. If you prefer no lock there either, I will remove it.
… restore Per review on ClickHouse#123888: - An undo that throws ends the rollback as partial again, without `NOEXCEPT_SCOPE` or `std::terminate`; `MetadataOperationsHolder` has no `noexcept_rollback` mode any more. - `commit()` no longer takes a memory lock in its `catch`. `rollback()` takes `LockMemoryExceptionInThread` for its own scope instead, so the memory limit and its fault injection cannot stop an undo. Without it, the DETACH/ATTACH loop with memory faults loses blobs at the master rate (52 in 5 minutes, 80 rollbacks stopped in `WriteFileOperation::undo`); with it, 0 over 2156 rollbacks. - `MoveDirectoryOperation` no longer recreates an empty destination replaced by the rename: no caller moves a directory onto an existing one. - `DiskLocal::removeDirectoryIfExists` is back to master: the server's disk paths are absolute, so both forms check the same directory. - Removed three field comments, the death test, the recursive directory creation test (it needed the relative path of the gtest fixture), and the matrix row for the empty destination. - Added a matrix row for a hard link to a fresh destination, so an undo that does not remove the link it created fails the test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| void MetadataOperationsHolder::rollback(size_t until_pos, Exception & rollback_reason) noexcept | ||
| { | ||
| LockMemoryExceptionInThread lock_memory_exception(VariableContext::Global); |
There was a problem hiding this comment.
❌ Run rollback before allocating the diagnostic message
The memory-limit guard is entered too late to guarantee that a failed transaction reaches rollback. commit first calls error.addMessage(fmt::format(...)) (line 95), which allocates outside this scope. With min_allocation_size_to_throw_on_memory_limit = 1 and max_untracked_memory = 0, those generic allocations can throw MEMORY_LIMIT_EXCEEDED too; std::uncaught_exceptions is already zero inside the handler. If a removal has decremented a shared file's count and then fails, this second exception skips rollback altogether, leaving the same undercount that lets a later removal delete a live blob.
Please call rollback before formatting/appending the diagnostic, or protect the path into rollback as well. The new disk-level fault injector only exercises allocations inside undo, so add a focused case that injects an allocation failure while entering the commit handler and verifies that the shared count is restored.
Related: #123129
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed data loss on object storage disks with
localmetadata (the default for S3, Azure and HDFS disks): when a failed metadata transaction, such as a part removal, could not be rolled back completely, for example because the rollback hit the memory limit, a hard link count stayed too low and a later removal deleted blobs still used by another part, such as its detached copy, soATTACH PARTITIONfailed withThe specified key does not exist.Description
Stress test (arm_tsan)on #110626:ATTACH PARTITION ID 'all'in01164_detach_attach_partition_race(cached_s3_encrypted) found a detached part broken: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110626&sha=85d4dbade0a99fe1bae43881405309aa17c5d01b&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29On 26.8, when the rollback of a failed part removal on an object storage disk with
localmetadata hits the memory limit, a hard link count stays decremented and the next removal of the other link deletes a blob that a detached part still uses.MetadataOperationsHolder::rollbackstops at the firstundothat throws. In the log,DROP DETACHEDdecremented the counts of a detached part's files and failed on an injected memory limit, and restoring one count in the rollback failed on the same fault (log excerpts: #123888 (comment)). Someundos also threw for anexecutethat changed nothing.MetadataOperationsHolder::rollbackholdsLockMemoryExceptionInThread, so the memory limit and its fault injection cannot stop anundo;executedid and undoes only that;RemoveRecursiveOperationrestores counts in reverse order.Disk operations in an
undoare not retried. Anexecutethat throws something other thanDB::Exceptionstill skips the rollback; #122696 adds thatcatch.Validation: four gtests fail on master and pass here. A DETACH/ATTACH loop with memory faults on a
local_blob_storagedisk: 111 lost blobs and 320 incomplete rollbacks in 10 minutes on master, none here (2156 rollbacks in 5 minutes); without the lock, 52 lost blobs in 5 minutes.Workflow [PR]
Sync PR [sync-upstream/pr/123888]
Version info
26.11.1.1453-master(included in26.11and later)