Skip to content

Run the rollback of a local metadata transaction to completion - #123888

Merged
Michicosun merged 5 commits into
ClickHouse:masterfrom
groeneai:run-local-metadata-rollback-to-completion
Nov 5, 2026
Merged

Michicosun merged 5 commits into
ClickHouse:masterfrom
groeneai:run-local-metadata-rollback-to-completion

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #123129

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 data loss on object storage disks with local metadata (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, so ATTACH PARTITION failed with The specified key does not exist.

Description

Stress test (arm_tsan) on #110626: ATTACH PARTITION ID 'all' in 01164_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%29

On 26.8, when the rollback of a failed part removal on an object storage disk with local metadata 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::rollback stops at the first undo that throws. In the log, DROP DETACHED decremented 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)). Some undos also threw for an execute that changed nothing.

  • MetadataOperationsHolder::rollback holds LockMemoryExceptionInThread, so the memory limit and its fault injection cannot stop an undo;
  • each operation records what its execute did and undoes only that;
  • RemoveRecursiveOperation restores counts in reverse order.

Disk operations in an undo are not retried. An execute that throws something other than DB::Exception still skips the rollback; #122696 adds that catch.

Validation: four gtests fail on master and pass here. A DETACH/ATTACH loop with memory faults on a local_blob_storage disk: 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

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

`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
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).

# Sev Finding Verdict Evidence / action
1 ❌ createHardLink onto an existing link of the same inode increments the count on a successful commit, so the blob is never removed (CreateHardlinkOperation::execute) DISAGREE The success path is unchanged by this PR (same on master, createHardLink.cpp:20-42); the result is a kept blob, not a lost one; no caller found that commits such a duplicate (clones and backups link into fresh paths). I can make a same-inode duplicate a no-op here if wanted.
2 💡 commit rolls back only on DB::Exception, so a std::filesystem_error from an execute skips the rollback AGREE Stated in the description; #122696 adds that catch.
3 💡 The commit message does not carry the CI report URL AGREE Not blocking; the description links it.
4 💡 The test fixture checks its dynamic_pointer_cast with chassert only AGREE Not blocking; every caller passes the fault-injecting disk.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-8:20261004-184900

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter='MetadataLocalDiskTest.*': a fault-injecting DiskLocal throws on numbered calls (or a memory-limit error where the query memory tracker would), so every failure point is fixed.
b Root cause explained? MetadataOperationsHolder::rollback stops at the first undo that throws. The memory limit can throw inside the rollback, and several undos throw for an execute that changed nothing, so decremented hard link counts stay decremented and a later removal deletes blobs another link uses.
c Fix matches root cause? Yes. The rollback no longer stops: the memory limit is blocked for it, each local undo step repeats until it succeeds (as #119235 does for plain_rewritable), and each operation undoes only what its execute did. No reordering, no guard at the read site.
d Test intent preserved / new tests added? Six new gtests; the 39 existing cases are unchanged. They use only master interfaces, so they also build on the merge base.
e Both directions demonstrated? Master: exactly the six new tests fail, each case on its own assertion. Fix: 45/45, 50/50 repeats. Each mechanism removed one at a time makes its test fail or hang. Loop with memory faults: 111 lost blobs in 10 min on master, 0 with the fix.
f Fix is general across code paths? All 12 primitive local operations (composites delegate to WriteFileOperation); the cache metadata storage uses the same transaction; plain and plain_rewritable get the memory-limit block in the shared holder.
g Fix generalizes across inputs (params/datatypes/wrappers)? Inputs are operation kinds and failure points: one case per operation whose undo assumed success, plus count restore, shared inode, failed read and recursive directory creation.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change. Only on failure: a step that keeps failing on an I/O error now retries instead of returning half rolled back (the #119235 trade).
i Invariants and contracts preserved? A failed transaction's rollback restores every operation it executed. Success path unchanged except two existence checks. Steps still run under metadata_mutex; LOGICAL_ERROR is not retried.

Session id: cron:clickhouse-impl-slot-4:20261004-154600

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e632a1]

Summary: ✅


AI Review

Summary

This 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

  • MetadataOperationsHolder.cpp:25: The memory-limit guard starts inside rollback, but commit allocates in fmt::format and Exception::addMessage before calling it (line 95). With generic allocation enforcement enabled, for example min_allocation_size_to_throw_on_memory_limit = 1 and max_untracked_memory = 0, a second memory-limit exception escapes the handler and skips all undo operations. A previously decremented shared-file count remains too low, allowing subsequent removal to delete a live blob. Run rollback before allocating diagnostics, or protect its entry path too.
  • MetadataStorageFromDiskTransactionOperations.cpp:389: CreateHardlinkOperation::undo restores the shared metadata count before removing the new link. If removeFileIfExists fails, both links remain with the old, lower count; removing one can delete the blob still referenced by the other. Remove the new link before restoring the count, so interruption leaves a conservative overcount. This remains present in the current code and is already tracked in the existing review thread; no duplicate inline comment was posted.
Tests
  • ⚠️ Add a deterministic allocation failure in the diagnostic path before rollback and assert that earlier shared-file count changes are undone. The current disk-level injector cannot exercise this gap.
  • ⚠️ Inject failure when undo removes a newly created hard link, then verify that deleting either surviving link does not queue a blob still referenced by the other.
Final Verdict

Status: ❌ 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.

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

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

explain the problems with the log examples from a failed test.

Disk operations should not be retried in general.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8e632a14a with master feeeb91ec (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

10 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.
The matched translation units cost +1.1 s (+5%) in total before that adjustment.

Job report

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]>
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun the failed run is Stress test (arm_tsan) on #110626 (report, clickhouse-server.stress.log.zst), test 01164_detach_attach_partition_race, table mt on cached_s3_encrypted (local metadata).

  1. DETACH PARTITION ID 'all' hard-links the active parts into detached/, so all_14_14_0 and detached/all_14_14_0 share every metadata file:
12:01:05.276894 [ 33139 ] {fabb310c-...} <Information> test_c3n6u3k6m1h6.mt (ed1f78bd-...): Detaching all_14_14_0
  1. A concurrent DROP DETACHED PARTITION ID 'all' removes detached/all_14_14_0. RemoveRecursiveOperation::execute decrements the counts file by file and one of these writes hits an injected memory limit. The rollback moves the directory back and restores the counts, and one restore hits the same fault while DiskLocal::writeFile allocates its buffer, so the rollback stops with 5 files of the part still at count 0:
12:01:06.065088 [ 7300 ] {6c94ce86-...} <Error> void DB::MetadataOperationsHolder::commit(): Code: 241. DB::Exception: Query memory tracker: fault injected. Would use 1.00 MiB (attempt to allocate chunk of 1.00 MiB), maximum: 9.31 GiB: While committing metadata operation #0: While rolling back operation #0: Code: 241. DB::Exception: Query memory tracker: fault injected. ... Rolling back the metadata transaction did not complete, so the metadata keeps a part of a transaction that is reported as failed. (MEMORY_LIMIT_EXCEEDED)
15. src/Disks/DiskLocal.cpp:442:12: DB::DiskLocal::writeFile(...)
16. src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDiskTransactionOperations.cpp:131:25: DB::WriteFileOperation::undo()
17. src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDiskTransactionOperations.cpp:343:19: DB::RemoveRecursiveOperation::undo()
18. src/Disks/DiskObjectStorage/MetadataStorages/MetadataOperationsHolder.cpp:30:28: DB::MetadataOperationsHolder::rollback(...)
  1. DETACH then removes the source parts. For those 5 files its link now looks like the last one, so their blobs are deleted:
12:01:06.127049 [ 33139 ] {fabb310c-...} <Debug> test_c3n6u3k6m1h6.mt (ed1f78bd-...): Removing 4 parts from filesystem (serially): Parts: [all_14_14_0, all_15_15_0, all_16_16_0, all_17_17_0]
12:01:06.144004 [ 61882 ] {} <Trace> s3::BlobKillerThread: Removing 5 blobs from 'main' location
12:01:06.152384 [ 61882 ] {} <Debug> deleteFileFromS3: Objects with paths [test/rsl/lhmxqlqejcmtcswmzqtppqgerpocb, test/mio/mtpboqqvzhbdzbyjvzljygtemujze, test/jjp/hvkcdesopaikikyfdllrrolyyplfc, test/hmn/drestqzuimlqtvdsygppmkyipsbyo, test/rze/pozbewgovrekbnrclepcbnkkvcrcx] were removed from S3
  1. ATTACH PARTITION ID 'all' reads one of them (the blob was written for all_14_14_0 at 12:01:04.081 by the INSERT):
12:01:06.637504 [ 71824 ] {2d90cbed-...} <Test> ReadBufferFromRemoteFSGather: Reading from file: test/hmn/drestqzuimlqtvdsygppmkyipsbyo (.../detached/attaching_all_14_14_0/metadata_version.txt)
12:01:07.189432 [ 71824 ] {2d90cbed-...} <Error> test_c3n6u3k6m1h6.mt (ed1f78bd-...): Part .../detached/attaching_all_14_14_0/ is broken and needs manual correction. Reason: Code: 499. DB::Exception: The specified key does not exist. ... (S3_ERROR)

The rollback was stopped by the memory tracker, not by a disk error. I removed the retries in b76dbee: no disk operation in an undo is repeated. What is left:

  • LockMemoryExceptionInThread from the catch in MetadataOperationsHolder::commit, so the memory limit and its fault injection cannot stop the rollback (step 2);
  • every operation records what its execute did and its undo reverts only that, so an undo fails only on a real disk error. On master, for example, MoveFileOperation::undo throws for a move that never happened and stops the rollback without any fault;
  • RemoveRecursiveOperation restores the counts in reverse order (two links to one file inside the removed directory ended one count too low).

The same DETACH/ATTACH loop with memory faults on a local_blob_storage disk, 10 minutes: master 111 lost blobs and 320 incomplete rollbacks; this head (b76dbee) 0 and 0 over 4474 rollbacks.

@groeneai
groeneai requested a review from Michicosun October 4, 2026 22:19
`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)

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.

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.

@Michicosun

Copy link
Copy Markdown
Member

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]>
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Done in aba3ae393e0b6: each undo of a local metadata transaction 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 a partial rollback. plain_rewritable keeps its current rollback.

This is safe because each 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. The DETACH/ATTACH loop with memory faults on this head: 2205 rollbacks in 5 minutes, none incomplete, no termination.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Another run of this defect, through a different caller, where active parts lose blobs: Stress test (amd_tsan), report, clickhouse-server.stress.log.zst, table test_1.t_mutation_param on cached_s3 (local metadata).

  1. Mutations that change nothing clone 20260625_2_2_0 into _4 ... _12, and 20260625_3_3_0 the same way, by hard links, so each chain shares every metadata file.
  2. DROP PARTITION removes the outdated parts concurrently under injected memory faults. For three of them clearDirectory -> removeSharedFiles fails and the rollback stops in WriteFileOperation::undo <- UnlinkFileOperation::undo:
09:29:24.210433 ... delete_tmp_20260625_3_3_0_8 ... While committing metadata operation #16: While rolling back operation #11: ... fault injected
09:29:24.600665 ... delete_tmp_20260625_2_2_0_4 ... While committing metadata operation #4: While rolling back operation #2: ... fault injected
09:29:24.794673 ... delete_tmp_20260625_2_2_0 ... While committing metadata operation #15: While rolling back operation #3: ... fault injected

UnlinkFileOperation::undo moves the file back before it restores the count, so each of these three files is back with a decremented count, and the recursive fallback decrements it once more.
3. The background removal of the _11 parts (09:30:01.607 - 09:30:01.931) reaches count 0 for exactly three files and deletes their blobs while both _12 parts are active:

09:30:01.855235 deleteFileFromS3: Writing Delete operation for blobs [jlq-.../gnsjtcyydnsskxhosgdmfltwwweon, mck-.../ellwskxcrayjrmrnveyudjviafmnp]   <- serialization.json, flag.cmrk2 of 20260625_2_2_0_12
09:30:01.926932 deleteFileFromS3: Writing Delete operation for blob ohr-.../drllxrvodfpntxqclzdzyzybiqksm                                                 <- flag.null.bin of 20260625_3_3_0_12
  1. After the restart 20260625_2_2_0_12 is detached as broken (The specified key does not exist on serialization.json). 20260625_3_3_0_12 loads, because nothing reads flag.null.bin at load.

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 undo of a local metadata transaction runs in NOEXCEPT_SCOPE), and it still merges cleanly with master.

@Michicosun Michicosun self-assigned this Oct 23, 2026
IDisk & disk;

bool moved = false;
/// The rename replaced an empty directory at `path_to`.

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.

Suggested change
/// 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.

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.

Suggested change
/// 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.

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.

Suggested change
/// Set before the write, so a write that stopped part way is undone too.

Comment thread src/Disks/DiskLocal.cpp Outdated
{
auto fs_path = fs::path(disk_path) / path;
if (!existsDirectory(fs_path))
if (!existsDirectory(path))

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? This is incorrect.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +436 to +437
if (replaced_destination)
disk.createDirectory(path_to);

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.

that is strange, I suppose in this case move directory in execute will fail.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Comment on lines +30 to +34
if (noexcept_rollback)
{
NOEXCEPT_SCOPE(operations[i]->undo());
continue;
}

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.

not needed, exceptions here can be thrown, why do we need to crash in this case?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removed in 8e632a1: an undo that throws ends the rollback as partial again, without a crash.

Comment on lines +98 to +100
/// Neither the memory limit nor its fault injection can stop the rollback.
LockMemoryExceptionInThread lock_memory_exception(VariableContext::Global);

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.

remove

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

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

@Michicosun
Michicosun added this pull request to the merge queue Nov 5, 2026
Merged via the queue into ClickHouse:master with commit 561973a Nov 5, 2026
178 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 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-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants