Skip to content

Do not delete object storage blobs that a live part still hardlinks - #114046

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-hardlinked-blob-deletion-after-crash-111188
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-hardlinked-blob-deletion-after-crash-111188

Conversation

@groeneai

@groeneai groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Closes: #111188

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a loss of object storage blobs after an unclean shutdown. On a disk with local metadata, a part file removed while the server was killed could leave its persisted reference count one lower than the number of hard links to it, and the next removal then deleted blobs that a live part still pointed to, so reading that part failed with The specified key does not exist. A blob is now released only when the removal actually drops its last hard link. Closes #111188.

Description

The reference count in a local metadata file is a redundant copy of that file's hard-link count, and its decrement is not crash-atomic with the unlink it pairs with: UnlinkFileOperation::execute persists the decrement and renames the file aside, and only finalize() unlinks. An exception is safe, since the transaction rolls back, but a kill in that window leaves the count one too low while every directory entry survives. The next removal reads zero and deletes a blob a live part still references. RemoveRecursiveOperation has the same shape. Parts share an inode through FREEZE and partial mutations.

The persisted counter no longer authorizes destruction. Each removal operation decides in its own finalize(), immediately before its own unlink, and releases a blob only when that unlink drops the last hard link. RemoveRecursiveOperation counts links per inode within the subtree it removes. A retention-listed alias vetoes the release for its whole inode, so "keep this file's blobs" cannot be defeated by unlink order. Both operations now enqueue only after the unlink succeeds; the enqueue came first before, so a failing unlink could enqueue a blob whose link survived. A dedicated mutex serializes finalization so two transactions dropping an inode's last two links cannot both see two and both decline; widening metadata_mutex instead would block metadata reads for a whole recursive deletion.

The counter keeps its meaning and serialization, so getHardlinkCount, the zero-copy consumer and the on-disk format are unchanged. A decrement already lost to an earlier crash now leaks its blob rather than deleting it; reclaiming those needs a startup repair scan, out of scope.

A new integration test reproduces the loss from FREEZE/UNFREEZE plus a kill, using only supported operations: 5/5 fail without the fix, 25/25 pass with it. Sixteen new unit cases cover both directions, including the previously uncovered leak direction.

The reference count persisted in a `local` metadata file is a redundant copy of
that file's OS hard-link count, and the code that decrements it is not
crash-atomic with the unlink it pairs with. `UnlinkFileOperation::execute`
persists the decrement, renames the file aside for undo, and only unlinks in
`finalize()`. An exception is safe, because the transaction rolls back and
`undo()` restores the count, but a kill in that window leaves the count one too
low while every directory entry survives. The next removal that walks such a
file reads zero, treats the blob as unreferenced and hands it to the object
storage deleter, although a live part still points at it, so reading that part
then fails with `The specified key does not exist`.
`RemoveRecursiveOperation` has the same shape.

Parts come to share an inode through ClickHouse's own hardlink flow: `FREEZE`
hardlinks a part into `shadow/`, and a partial mutation carries over the
columns it does not rewrite.

Stop letting the persisted counter authorize destruction. Each removal
operation now decides in its own `finalize()`, immediately before its own
unlink, and releases a blob only when that unlink drops the last hard link.
Because finalizers run sequentially and each actually unlinks, aliases split
across operations resolve without any shared state, and an operation whose
unlink fails leaves the count high, so the decision is fail-closed for free.
`RemoveRecursiveOperation` removes a whole subtree in one call, so it counts
links per inode within its own renamed subtree; the `should_remove_objects`
verdicts are combined with AND across an inode's links, so a retention-listed
alias vetoes the release rather than being outvoted by link counting alone.

Both operations now enqueue blobs only after the unlink succeeds. Previously
the enqueue came first, and since `finalize()` exceptions are swallowed per
operation, a failing unlink could enqueue a blob whose metadata link survived,
an independent second route to the same loss.

A dedicated mutex serializes the finalization phase, which `commit()` runs
after releasing `metadata_mutex`. Without it two transactions each removing one
of an inode's two links could both observe two links and neither would release
the blob, leaking it. `metadata_mutex` is deliberately not widened: that would
block metadata reads for the whole of a potentially long recursive deletion,
and since `SharedMutex` is not recursive it would add a deadlock hazard. The
loss direction needs no lock, because before any finalizer runs the target has
been renamed to a transaction-private random name that no concurrent
`CreateHardlinkOperation` can resolve, and any other public alias is counted by
the `stat`.

A failed `stat` is treated as "do not release": leaking a blob is recoverable,
deleting one a live part points to is not. `finalize()` is non-throwing by
contract, so this is handled in place.

The reference count keeps its meaning and serialization, so `getHardlinkCount`,
its zero-copy consumer, the zeroing for zero-copy sends and the on-disk
metadata format are all unchanged. Only the destruction predicate moves. Where
a decrement was already lost to an earlier crash, such a blob is now leaked
instead of deleted; reclaiming those would need a startup scan comparing the
counter against `st_nlink` and is not part of this change.

The new integration test reproduces the loss deterministically from `FREEZE`,
`UNFREEZE` parked on a new pauseable failpoint, and a kill in that window. It
uses only supported operations, with no out-of-band part manipulation. The unit
tests cover both directions, including the leak direction, which had no
coverage: the two existing hardlink cases use inline data with zero blobs and
never assert the released set, so they could not detect either fault.

Closes ClickHouse#111188
A retention instruction was attached to a NAME but the release decision is a
property of the INODE, and each `UnlinkFileOperation` only ever sees its own
link. So for two hard links to one metadata file removed by one transaction,
where one link is retention-listed, the retention-listed operation still dropped
its own link unconditionally and the sibling then found a single remaining link,
concluded it was the last one, and released the very blob the retention listing
existed to protect. Reverse the order and the blob survived, so the outcome rode
on `NameSet` hash order. `RemoveRecursiveOperation` already combined those
verdicts per inode within its own subtree; the asymmetry was an omission, and it
is reachable because `removeSharedFiles` builds an independent operation per
entry, each with its own `should_remove_objects`, from a set of base names that
cannot distinguish two names sharing an inode.

The transaction now carries a per-inode veto that the unlink operations share.
Each operation records its own verdict during `execute()`, where every operation
runs before any finalizer, so by the time one decides, the map already reflects
every link the transaction will remove. A release needs both the per-operation
last-link test and that shared verdict. The map holds no counts and can only
turn a release off, so it cannot authorize an early release the way a shared
tally of link counts could; a missing entry vetoes nothing.

Give the finalization mutex a real test rather than an argument. A new pauseable
fail point between counting an inode's links and unlinking one opens the losing
window on demand, so two threads each removing one of two links reproduce the
leak deterministically enough to reject an implementation without the mutex,
which they do in every run, while every run passes with it.

The two stranded-reference-count cases asserted only that the blob is kept, so
they also passed an implementation that never releases anything for a stranded
inode, which is exactly the over-broad direction this change's leak-rather-than-
delete trade-off makes plausible. Each now also removes the surviving alias and
asserts the release, pinning that the decision reads `st_nlink` and not the
counter. The recursive retention case picked an alias while directory iteration
order is unspecified, so it is parameterized over both aliases, and a case where
no link is retention-listed pins that the veto has not become a blanket
suppression.
…ve enqueue ordering

Two properties this change asserts as contract had no test that could reject their
removal.

The finalization mutex was covered by a test that asserted a released blob, which
only follows from an interleaving each round has to hit by chance: a single round
reddened 2 times out of 5, so it took 200 rounds to be reliable. The pauseable fail
point between counting an inode's links and unlinking one blocks every thread that
reaches it, so while one transaction is parked there a second park is reachable
exactly when finalization is not serialized, and impossible when it is. Counting
parks discriminates by construction: removing the mutex now reddens on a single
round, 5 runs out of 5. Reading the count needs an accessor for the pause epoch the
channel already tracks.

RemoveRecursiveOperation had no arm for enqueueing only after the unlink succeeds,
which the unlink operation does have, so hoisting its enqueue loop above the removals
left every case green. A fail point before the removals plus a case on a single-link
file, where the link count cannot mask the ordering, rejects that. Its sibling arm
requires the same scenario to release when nothing fails, so the pair cannot be
satisfied by an implementation that never releases there.

No change to the removal logic itself.
The unit case asserting that two transactions cannot finalize concurrently
observed the second transaction through a flag set before commit(), which only
says it entered commit() - unlinkFile queues the operation, and both execute()
and finalize() run inside commit(). Arrival at the finalization gate was
therefore assumed rather than proven, and the assertion still depended on the
second thread traversing execute() within the deadline.

The same gap made every successful run pay the full deadline: with the mutex
present the poll loop's only exit is unreachable by construction, which is the
property under test, so the case cost 15.0 s of the suite's 48.3 s.

A pauseable failpoint immediately in front of the mutex acquisition, outside the
lock, makes "the second transaction is at the gate" directly observable. The
test now waits for that state and releases the thread from there, so what
remains before the assertion is a single mutex acquisition rather than a thread
start and a whole execute() pass, and the deadline drops to 500 ms.

The failpoint is outside the lock deliberately: parking inside it would
serialize the exclusion under test and deadlock the fixture.

Removing the mutex reddens the case on a single round in 5 of 5 runs, in 3-5 ms
rather than by waiting the deadline out. With the mutex intact, parking an extra
thread on a second metadata storage makes the assertion fire, so it genuinely
observes parks. The case is 1510 ms, and the suite 48.3 s -> 35.0 s, with
265/265 green and 20/20 under --gtest_repeat.

No change to the removal logic.
@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 4 rounds, final round clean (0 findings)

An independent model reviewed this change cold in each of 4 rounds, and a separate reviewer
adjudicated its findings against the code. Round 4 returned no findings. Summary of what changed
because of it:

❌ Blockers / majors fixed

Finding Resolution
A retention-listed hard link could be defeated by unlink order Release is now decided per inode; one disallowed link vetoes the whole inode
Blobs were enqueued before the unlink, so a failing unlink could enqueue a live blob Enqueue moved after the unlink in both removal carriers
The finalization-exclusion test rested on a proxy flag and a 5 s timeout, so it could pass without the mutex Replaced with an observation point immediately before the lock; the test now proves arrival instead of assuming it, and the case runs ~10x faster

⚠️ Raised and declined, with reasons

  • Critical Bug Fix category: not selected, since no maintainer asked for it.
  • Diff size above the plan's soft target: the growth is entirely test-observability plumbing that
    earlier review rounds required; no removal logic changed after round 1.

💡 Verified, no change

Fail-closed in every direction (a failed link count keeps the blobs), lock order acyclic, on-disk
format and getHardlinkCount semantics unchanged, so no SettingsChangesHistory.cpp entry is owed.
A reference count already lost to an earlier crash now leaks its blob instead of deleting it.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes. tests/integration/test_s3_metadata_hardlink_blob_release/test.py: 5/5 fail without the fix, 25/25 pass with it. Not an intermittent reproduction.
b Root cause explained? The persisted reference count is a redundant copy of the metadata file's hard-link count, and its decrement is not crash-atomic with the unlink it pairs with. A kill between the two leaves the count one too low while every directory entry survives, so the next removal reads zero and deletes a blob a live part still references.
c Fix matches root cause? Yes. It removes the fragile decider (the persisted counter) instead of guarding the deletion site: each removal operation asks the filesystem, in its own finalize(), immediately before its own unlink. No widened bounds, no tags, no defensive masking.
d Test intent preserved / new tests added? All 39 pre-existing cases in gtest_metadata_local_disk.cpp are untouched and green (55/55 total, and 265/265 over the wider disk and object-storage suites). 16 new unit cases (13 declarations, 3 of them parameterized over 2 values each) plus 1 integration test. Two of the new cases were also strengthened after review: the stranded-count pair asserted only that the blob is kept, so it could not reject an implementation that never releases for a stranded inode; each now also asserts the release once the surviving alias goes.
e Both directions demonstrated? Yes, with distinct Build IDs per arm. Without the fix the SELECT fails with The specified key does not exist while reading a live part; with the fix it returns the inserted values.
f General across code paths? Both carriers fixed: UnlinkFileOperation (the fast removal path, which creates the stranded state) and RemoveRecursiveOperation (the temp-directory cleanup, which deletes the blob). ReplaceFileOperation forwards to UnlinkFileOperation::finalize and inherits the fix. The removal helper is shared by StorageMergeTree and StorageReplicatedMergeTree, and the fix sits below both in the disk layer. Sibling metadata storages (Plain, PlainRewritable, both Web) hardcode getHardlinkCount() == 0 and have no hardlink refcount machinery; Cache delegates and inherits. Local is the only carrier.
g General across inputs? Unit matrix covers 1 link, 2 links in one operation, 2 links across two operations, 2 links across two transactions, 2 links removed concurrently by two transactions, an alias created after an unlink in the same transaction, a retention-listed alias inside a recursive removal (both aliases, since the walk order is unspecified), a retention-listed alias across two sibling unlinks (both orders, since that defect was order-dependent), a control where no link is retention-listed, and a failed unlink.
h Backward compatible? Yes. The reference count keeps its meaning and serialization; no format change, no new setting, no SettingsChangesHistory.cpp entry. An older server reads the same metadata files.
i Invariants and contracts preserved? finalize() stays non-throwing: the stat is wrapped and a failure is fail-closed (do not release), since leaking a blob is recoverable and deleting a live one is not. Lock ordering: the new mutex is taken after metadata_mutex is released and never while holding removed_objects_mutex, so there is no cycle and no re-entrancy. The fail point that observes arrival at the gate sits outside that mutex, so it cannot serialize the exclusion it exists to test, and it is inert unless a test enables it. metadata_mutex is deliberately not widened, which would block metadata reads for the whole of a long recursive deletion. The release decision is per inode rather than per name, so a retention instruction on one of an inode's names binds every operation in the transaction that removes another of its names and cannot be defeated by unlink ordering; the veto can only turn a release off, and a missing entry vetoes nothing.

Mutation arms, one per part of the diff: reverting the unlink decision, the recursive decision, either operation's append ordering, the retention veto, or the cross-operation inode veto each reddens at least one case. The finalization mutex has a structural oracle rather than a probabilistic one, on both sides. The inner fail point, between counting an inode's links and unlinking one, blocks every thread that reaches it, so while one transaction is parked there a second park is reachable only if finalization is not serialized. A second fail point immediately in front of the mutex acquisition, outside the lock, makes the other thread's arrival at the gate an observed state rather than an assumed one, so nothing is left to a deadline: removing the mutex reddens 5 runs out of 5 on a single round, in 3 to 5 ms. With the mutex intact, parking an extra thread on a second metadata storage makes the assertion fire, which shows it genuinely counts parks. The case costs 1.5 s, down from 15.0 s.

A blob leak check was also run: after INSERT + FREEZE + UNFREEZE + DROP TABLE SYNC the set of objects in storage returns exactly to its pre-test state.

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @Michicosun, could you review this? On a disk with local metadata the persisted reference count is a redundant copy of the hard-link count and its decrement is not crash-atomic with the unlink it pairs with, so a kill in that window leaves the count too low and the next removal deletes blobs a live part still hardlinks; each removal operation now decides in its own finalize(), immediately before its own unlink, and releases a blob only when that unlink drops the last link.

@Michicosun

Copy link
Copy Markdown
Member

not needed

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun which of the two do you mean, so that I do not act on the wrong one?

  1. The change is not needed. Then I would like the reason, because I did not pick this up on my own: @ alexey-milovidov asked me to fix Stress test: S3_ERROR "No such key" during background merge on cached_s3_encrypted (foreground merge-read variant, not covered by #108489) #111188 in a separate PR after the same failure hit his own PR's Stress run (Support INSERT ... VALUES in the polyglot SQL dialect #110321 (comment)).
  2. The review request was not needed, that is, you are declining to review rather than judging the change. Then the PR does not need to be closed and I will find another reviewer.

If it is 1: this is a deleted object, not a benign cache line. On a disk with local metadata a kill between the persisted reference-count decrement and the unlink it pairs with leaves the count one too low, and the next removal then deletes a blob that a live part still hardlinks. The integration test reproduces it with supported operations only, FREEZE plus UNFREEZE plus a kill: 5 of 5 runs fail without the change, 25 of 25 pass with it. CI carriers: the one #111188 was filed from and the one on #110321.

I am not reopening it, the disposition is yours. If it is 1, what should happen to #111188?

@groeneai groeneai mentioned this pull request Aug 11, 2026
1 task done
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

groeneai-origin-request PR origin: a maintainer pinged or directed groeneai

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Stress test: S3_ERROR "No such key" during background merge on cached_s3_encrypted (foreground merge-read variant, not covered by #108489)

2 participants