Skip to content

Do not delete hard-linked blobs when a metadata rollback fails part way - #123129

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-metadata-rollback-hardlink-undercount
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-metadata-rollback-hardlink-undercount

Conversation

@groeneai

@groeneai groeneai commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #87358

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 disks that keep metadata locally (S3, Azure, HDFS, local object storage): when removing a data part failed and rolling the removal back failed too, for example on a memory limit, a blob still used through a hard link could be deleted, so a part detached with ALTER TABLE ... DETACH PARTITION could no longer be attached (The specified key does not exist); a hard link that failed, for example during FREEZE or DETACH, could also delete a metadata file of the source part.

Description

On 26.3-26.9, ALTER TABLE ... DETACH PARTITION on an S3 disk whose part removal and rollback both fail (for example on a memory limit) deletes a blob that the detached/ copy still uses, and the following ATTACH PARTITION fails with The specified key does not exist. Seen in 3 stress-test runs since 2026-09-20 (example).

A metadata file shares its inode, and the reference count stored in it, with its hard links. UnlinkFileOperation decremented the count before moving the file aside and its undo moved the file back before restoring the count, so a rollback that stopped in between left a linked file counted as unshared, and the next removal queued its blob. RemoveRecursiveOperation had the same order, CreateHardlinkOperation::undo restored the count before removing the new link, and RemoveRecursiveOperation::undo restored its writes first to last (two links to one inode in the removed directory ended one count too low even after a complete rollback).

Now each step removes a link before decrementing its count and adds one after incrementing it, in both execute and undo; undo writes run in reverse. A rollback that stops part way now over-counts: at worst a leaked blob and an orphan metadata file, never a deleted blob still referenced. Without failures the files, counts and removal queue are unchanged. WriteFileOperation undo now deletes a file only if its check found none, so a failed check or read no longer deletes the file being unlinked or the source of a hard link.

Twelve new cases in gtest_metadata_local_disk.cpp use a test-local DiskLocal that fails chosen calls; eleven fail on master and pass with the fix, and each changed step is pinned by one. A DETACH/ATTACH loop with injected memory faults lost a blob 105 times in 10 minutes on master and 0 with the fix.


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

groeneai and others added 4 commits September 30, 2026 16:23
A metadata file of a disk with local metadata stores the reference count of its blobs, and that count lives in the
inode every hard link shares. Unlinking decremented the count and then moved the file aside; its undo moved the file
back and then restored the count. When the restore failed (a memory limit on the 1 MiB write buffer in stress tests),
`MetadataOperationsHolder::rollback` stopped there and left a live link counted as unshared. The next removal of that
link queued its blobs, and a part that still used them through a hard link, such as the copy DETACH puts into
`detached/`, lost them: ATTACH failed with `The specified key does not exist`.

`RemoveRecursiveOperation` had the same order, and `CreateHardlinkOperation::undo` restored the count before removing
the new link. `RemoveRecursiveOperation::undo` also restored its writes first to last, so two links to one inode inside
the removed directory ended one count too low even after a complete rollback.

Every operation now changes the link first on the way in and the count first on the way back: unlink and recursive
removal move the file or tree aside before decrementing (queued blobs keep their original `local_path`, and the
predicate still gets the path relative to the removed root), undo restores the counts, in reverse order, before moving
back, and the hard-link undo removes the new link before restoring the count. A rollback that stops part way now leaves
a count that is too high, so the worst outcome of a double failure is a leaked blob and an orphan metadata file instead
of a deleted blob that is still referenced. Without failures the resulting files, counts and removal queue are
unchanged.

The tests use a test-local `DiskLocal` that fails chosen calls, so they build against the previous code and six of
them fail there.

Closes ClickHouse#53905

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`WriteFileOperation::execute` set `file_existed` only after `readFileIfExists` returned, so a throw while opening the
read buffer (a memory limit, `EMFILE`) left it false and `undo` removed a file that existed before the transaction.
With the unlink order of the previous commit this deleted the temporary file of an unlink, the move back then threw
and the rollback stopped with the earlier unlinks of the transaction still executed. It also made
`CreateHardlinkOperation::undo` delete the source file of a failed hard link. `execute` now checks `existsFile` first
and reads with `readFile`, the same two calls `readFileIfExists` made.

Tests: read faults in `FaultInjectingDiskLocal` (`prepareRead`), a failed hard link that keeps its source, an unlink
rollback that completes after a read fault, and two faults in the single-file branch of `removeRecursive` (the
rollback restore and the move aside), which pin its undo order and its execute order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`DiskLocal::existsFile` can throw (a memory limit on the path allocation), and `file_existed` defaulted to false, so
`WriteFileOperation::undo` then removed a file that existed before the transaction: the source file of a failed hard
link, or the temporary file of an unlink. `file_existed` is now unset until the check completes, and `undo` removes
the file only when the check reported it missing.

Tests: an `existsFile` fault in `FaultInjectingDiskLocal` and a failed hard link that keeps its source when the check
throws. Every fault case now asserts how many injected faults fired, and the two move-fault cases that no count was
written before the move failed, so a drifted call index cannot turn a case into one that passes without its fault.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`RemoveRecursiveOperation::traverseFile` computed the path of a released
file inside the moved-aside tree with `fs::relative`, which runs
`weakly_canonical` on both arguments: it stat()s the relative metadata
path against the process working directory and resolves that directory.
A removed or unsearchable working directory made it throw
`std::filesystem_error`, which `MetadataOperationsHolder::commit` does not
roll back, so the tree stayed under its temporary name and its blobs
leaked; it also cost several syscalls per released file under
`metadata_mutex`. `lexically_relative` returns the same path without
touching the filesystem.

`UnlinkFileOperation::execute` copied the temporary name into
`tmp_file_path` after moving the file aside; the copy allocates, and if it
threw, `undo` could not move the file back. Move the string instead.

The unlink move-failure test now also checks the `local_path` of the
queued blob.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 30, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 rounds, 9 findings, 0 in the last round) plus own cold reviews.

# Sev Finding Verdict Evidence / action
1 ⚠️ A throw while WriteFileOperation::execute opens the read buffer leaves file_existed false, so undo deletes the existing file (the unlinked file, or the source of a hard link) AGREE, fixed existence is checked before the read; two read-fault cases
2 ⚠️ The single-file branch of RemoveRecursiveOperation has no fault test AGREE, fixed rollback-failure and move-failure cases for one file
3 ⚠️ A throwing existence check leaves file_existed false as well, with the same effect AGREE, fixed tri-state file_existed; existence-check fault case
4 ⚠️ Fault cases do not assert that their armed fault fired, so an index drift would make them pass vacuously AGREE, fixed every fault case asserts its fired count; move-failure cases assert no count write
5 ❌ CreateHardlinkOperation::undo removes path_to even when it existed before the link DISAGREE no caller links onto an occupied path (localBackup rejects a non-empty destination; clones and backups link into fresh directories); the reorder leaves that outcome unchanged
6 💡 Use Critical Bug Fix for a data-loss fix DISAGREE set only when a maintainer asks; Bug Fix holds (released versions, documented DETACH/ATTACH)
7 ❌ fs::relative now runs for every released file, stats paths against the process working directory and can throw std::filesystem_error, which skips the rollback AGREE, fixed lexically_relative on the temporary root: same string, no syscalls
8 ❌ Non-DB::Exception errors after the rename (e.g. from directory iteration) strand the tree under its temporary name; roll back on every exception DISAGREE the same throws on master hit the traversal after its decrements and under-count; with the fix they leave an orphan tree and leaked blobs, never a deleted referenced blob, and removal is the operation's purpose
9 ❌ tmp_file_path = tmp_path copies after the move; an allocation failure there makes the rollback skip the move back AGREE, fixed std::move, as the recursive removal already does
10 💡 No unlink case pins the queued blob's local_path AGREE, fixed the move-failure unlink case asserts the queued StoredObject
11 💡 The first commit message says every operation changes the link first on the way in; hard-link execute increments first noted, not blocking the PR description states the order correctly

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

Session id: cron:clickhouse-review-slot-8:20260930-190900

@groeneai

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.*' fails 11 of the new cases on master's operations file; the fault-injecting disk fails exact call indices (writes, moves, removals, reads, existence checks), verified on both trees, and each case asserts how many faults fired.
b Root cause explained? Unlink, recursive removal and hard-link undo changed the shared reference count and the link in an order where an interrupted rollback leaves a live link uncounted; recursive-removal undo also restored its writes first to last. The next removal then queues a blob still in use.
c Fix matches root cause? Yes: the link/count steps are reordered so every intermediate state over-counts, and undo writes are restored in reverse. No guard, no retry, no new setting.
d Test intent preserved / new tests added? 12 new gtest cases (11 fail on master); no existing test changed apart from a fixture template and a shared helper.
e Both directions demonstrated? Master 11 fail / 40 pass, fix 51/51, 50/50 repeats; the PR's earlier WriteFileOperation versions fail only the read-fault cases (2) and then only the existence-check case (1); each reordered step reddens its own case when reverted (the single-file removal branch separately for its execute and undo order); with fault injection disabled all 10 fault cases fail on their fired-fault count; E2E DETACH/ATTACH loop with memory faults: 105 lost blobs in 10 min on master, 0 with the fix.
f Fix is general across code paths? All three operations that change a link and the count are fixed, and the shared WriteFileOperation undo deletes a file only when its existence check completed and found none (a failed check or read deleted the unlinked file or the source of a hard link); ReplaceFileOperation goes through UnlinkFileOperation; the other metadata storages keep no reference counts.
g Fix generalizes across inputs (params/datatypes/wrappers)? File and directory branches of the recursive removal (predicate input and queued local_path pinned for both, faults in both), several links to one inode, move, write, read and existence-check failures. N/A for data types.
h Backward compatible? (maintainer-approved exception only) Yes: no setting, no format change; without failures the resulting files, counts and removal queue are unchanged.
i Invariants and contracts preserved? The stored count never drops below the number of other live links at any step of execute or undo; all steps still run under metadata_mutex; queued blobs keep their pre-move local_path; no working-directory-dependent call on the removal path.

Session id: cron:clickhouse-impl-slot-4:20260930-185300

@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [48835f4]

Summary: ✅


AI Review

Summary

This PR reorders the local metadata unlink and recursive-remove steps so interrupted rollbacks over-count hard links instead of under-counting them, which matches the bug it is trying to fix. I found one remaining exception-safety gap in the new move-before-decrement flow, so I cannot approve it as-is.

Findings
  • ⚠️ Major: [src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDiskTransactionOperations.cpp:167, 323-337] Moving the file or directory aside before the remaining allocations and traversal work is complete is only safe if every later failure is a DB::Exception, but MetadataOperationsHolder::commit rolls back only that type. A std::bad_alloc from object_metadata->serializeToString(), std::make_unique, append_range, or the recursive traversal bookkeeping now skips undo() and can leave the metadata reachable only via its random temporary name. Suggested fix: catch all exceptions in MetadataOperationsHolder::commit, or keep the post-rename sections allocation-free / noexcept.
Final Verdict

Status: ⚠️ Request changes
Minimum required action: close the uncaught-exception window introduced by the new move-before-decrement order so a failed unlinkFile or removeRecursive cannot strand metadata under its temporary path.

LLVM Coverage Report

Measured on commit 48835f4.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 56/57 (98.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 30, 2026
@Michicosun

Copy link
Copy Markdown
Member

This issue is invalid. It was fixed long ago #53905 - it is an incorrect reference to link it here.

@groeneai, give me timed logs on what happened that led to this issue. Without them and the clear evidence close this pr.


/// We need to move file to the random name for the possible undo and to save the fs hardlink count
auto tmp_path = getRandomASCIIString(32);
disk.moveFile(path, tmp_path);

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.

MetadataOperationsHolder::commit only rolls back DB::Exception, so moving the file aside before the remaining allocations are done is not exception-safe for std::bad_alloc and other non-DB::Exception failures. A concrete trace here is: moveFile(path, tmp_path) succeeds, then object_metadata->serializeToString() or std::make_unique<WriteFileOperation> throws, execute() unwinds past the holder's catch (Exception &), and the failed transaction leaves the metadata only under the random temporary name because undo() is never called. Before this patch those allocations happened before the rename for unlinkFile, and the same new window now exists in RemoveRecursiveOperation::execute after moveFile / moveDirectory.

Can we either make the post-move section allocation-free for all exception types, or broaden the holder to roll back on any exception instead of only DB::Exception?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed on #53905: #87358 fixed the new-inode problem it describes (unlink now moves the file aside, and undo moves it back). I removed the Closes: line.

This PR is about a different gap in the current UnlinkFileOperation. execute writes ref_count - 1 into the shared inode and only then moves the file aside, and undo moves the file back before it restores the count. If that restoring write fails, MetadataOperationsHolder::rollback stops there, so the file is back at its path with a count that no longer includes the detached/ hard link. The retried removal then sees the blob as unshared and deletes it.

Timed log from one of the stress runs (Stress test (arm_asan_ubsan, s3), clickhouse-server.stress.log.zst). Test 05259_mutation_of_part_without_table_columns, table test_s9r0q2r9b4y3.t_compact, server log time, logger names and paths shortened:

13:03:55.442718 [17531] {05cae385} Writing blob for path .../tmp_insert_all_1_1_0/count.txt, key test/tqd/bovfdflfkcwxcjhqusaxxmhcvvlgv, size 1
13:03:55.798435 [20776] {513d450c} executeQuery: ALTER TABLE t_compact DETACH PARTITION ALL
13:03:56.274585 [20776] {513d450c} Detaching all_1_1_0
13:03:56.410103 [20776] {513d450c} Removing 1 parts from filesystem (serially): Parts: [all_1_1_0]
13:03:56.766923 [20776] {513d450c} <Error> void DB::MetadataOperationsHolder::commit(): Code: 241. DB::Exception: Query memory tracker: fault injected ...
                While committing metadata operation #12: While rolling back operation #5: Code: 241. DB::Exception: Query memory tracker: fault injected ...
                (rollback stack: DiskLocal::writeFile <- WriteFileOperation::undo() :131 <- MetadataOperationsHolder::rollback :30)
                ... Rolling back the metadata transaction did not complete, so the metadata keeps a part of a transaction that is reported as failed.
13:03:56.768139 [20776] {513d450c} Cannot quickly remove directory .../delete_tmp_all_1_1_0 by removing files; fallback to recursive removal
13:03:56.993644 [20776] {513d450c} Failed to remove all parts, all count 1, removed 0
13:03:57.001216 [20776] {513d450c} Directory .../delete_tmp_all_1_1_0 (to which part must be renamed before removing) already exists ... Removing it.
13:03:57.020639 [17108] s3::BlobKillerThread: Removing 1 blobs from 'main' location
13:03:57.041417 [17108] deleteFileFromS3: Object with path test/tqd/bovfdflfkcwxcjhqusaxxmhcvvlgv was removed from S3
13:03:59.889192 [20776] {e2fcfeed} Reading from file: test/tqd/bovfdflfkcwxcjhqusaxxmhcvvlgv (.../detached/attaching_all_1_1_0/count.txt)
13:04:00.221865 [20776] {e2fcfeed} Part .../detached/attaching_all_1_1_0/ is broken and needs manual correction. Reason: Code: 499. DB::Exception: The specified key does not exist ... while reading key: test/tqd/bovfdflfkcwxcjhqusaxxmhcvvlgv

{e2fcfeed} is ALTER TABLE t_compact ATTACH PARTITION ALL. Between the INSERT and that ATTACH, this is the only delete of the key. A second run (Stress test (amd_tsan), 05046_lwu_patch_partition_detach_attach, log) shows the same sequence. There, at 12:47:49.197 the rollback stops at operation #3, and its stack has UnlinkFileOperation::undo() :195 calling WriteFileOperation::undo(). Blob test/gjz/lvokrmrlramriwvnszqxzcjmrkhqt is deleted at 12:47:49.237, and ATTACH reports it missing at 12:47:51.825.

Outside the stress harness: 11 of the 12 new MetadataLocalDiskTest cases fail on master and pass with this PR. I also ran a DETACH/ATTACH loop on a local_blob_storage disk with memory_tracker_fault_probability = 0.02 on the DETACH query. A blob was lost after 105 of 1266 successful DETACHes on master, and after 0 of 1285 with the fix.

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

clickhouse-gh Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 48835f4c5 with master 6ad0aa3dd (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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes only the rollback and ordering logic for transactions in the local metadata storage of object-storage disks: unlink, recursive remove, hard-link undo and the WriteFileOperation existence check. It also adds unit tests. None of this code runs on the read path of a SELECT. The only flagged query is clickbench Q33, at +5.2% (1138 ms to 1197 ms). That is inside master's current normal range of 1097–1350 ms, so the automated checks correctly left it as not_sure, and nothing in the diff gives a reason to reopen that. No performance impact is expected from this change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1138 1197 +5.2% 0.0107 aggregation: The +5.2% shift sits inside master's normal range for this heavy GROUP BY query. The PR changes only rollback logic for metadata transactions, which this SELECT never runs.

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: 52042f23-dc54-413d-9751-a96952551e86
  • MIRAI run: 40645ae3-7239-4497-8ab6-0eb76e80ba86
  • PR check IDs:
    • clickbench_2662946_1790832039
    • clickbench_2662975_1790832041
    • clickbench_2663014_1790832041
    • tpch_adapted_1_official_2663353_1790832096
    • tpch_adapted_1_official_2663466_1790832119
    • tpch_adapted_1_official_2663569_1790832147

@Michicosun

Copy link
Copy Markdown
Member

This will not fix anything; subsequent write operations can fail the same way as move.

undo here should be atomic, otherwise the logic does not stand.

@Michicosun Michicosun closed this Oct 1, 2026
@groeneai

groeneai commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun understood, I will leave it closed.

You are right that this does not make undo atomic. The rollback still stops part way: in the 10-minute DETACH/ATTACH loop the partial-rollback message is logged 335 times with the fix (350 on master). What the PR changes is the state it stops in. The steps of unlink, recursive removal and hard-link undo are ordered so that a failed write or move leaves the reference count too high. The result is a leaked blob and an orphan metadata file, never a deleted blob that detached/ still uses: 0 lost blobs in that loop, against 105 on master.

Do you want me to work on an atomic undo in a new PR, or would you rather handle it yourself?

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-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants