Skip to content

Rename a broken detached part aside when a replicated ATTACH claims it - #116734

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/quarantine-broken-detached-part-on-replicated-attach
Sep 20, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/quarantine-broken-detached-part-on-replicated-attach

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

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 ATTACH PARTITION on ReplicatedMergeTree failing to rename a broken part in detached/ aside. The broken part stayed an attach candidate, so every later ATTACH PARTITION for that partition kept failing on it.

Description

Related: #54748
Related: #116258

Reported by @ alexey-milovidov, from this Stateless tests (amd_asan, distributed plan, parallel, 2/2) report.

A replicated ATTACH_PART entry claims a candidate directory in detached/ by renaming it to attaching_<dir>, builds the part with a detached/-qualified part_dir, and loads it. On a non-retryable load error the part is supposed to be renamed aside with a broken_ prefix so it stops being an attach candidate.

That rename never worked. getPartDirForPrefix appends part_dir verbatim, so detached/attaching_X becomes detached/broken_detached/attaching_X, whose parent does not exist:

fail to rename part all_0_0_0 with broken prefix: ... in rename: No such file or directory
[".../detached/attaching_all_0_0_0/"] [".../detached/broken_detached/attaching_all_0_0_0/"

So the broken part is never quarantined, stays a candidate, and blocks its partition. No concurrency is needed. This is a regression: a5eeba9e90649d59 added the quarantine as a local rename inside detached/, and 56cd154bcdbf11c replaced it with renameToDetached under three hours later the same day.

I restore the local rename, targeting a free detached/broken_<dir>[_tryN]. That name parses as a valid detached part name, so it is excluded from both attach candidate filters and stays removable by DROP DETACHED PART and DROP DETACHED PARTITION; the rename refuses an occupied target instead of removing it, so an earlier quarantine is kept. Nothing generic changes, and the branch has no working caller to regress.

New integration test (it has to corrupt a part inside detached/): both arms fail before the change and pass after.

Not fixed here and unchanged: a rollback whose target name was re-taken concurrently still orphans attaching_X; the claim can still take a directory a concurrent DETACH is populating; and the pre-existing crash window between claim and rollback. This makes the quarantine work, it does not make detached/attaching_* leftovers impossible.


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

Version info

  • Merged into: 26.10.1.269-master (included in 26.10 and later)

A replicated `ATTACH_PART` log entry claims a candidate directory in
`detached/` by renaming it to `attaching_<dir>`, builds the part with a
two-component `part_dir` (`detached/attaching_<dir>`) and loads it. When
the load throws a non-retryable exception the part must be renamed aside
under a `broken_` prefix so it stops being an attach candidate, and
`old_dir` is then cleared so the rollback becomes a no-op.

That rename could never succeed. `renameToDetached` routes through
`DataPartStorageOnDiskBase::getPartDirForPrefix`, which appends `part_dir`
verbatim, and `getRelativePathForDetachedPart` prepends `detached/` again,
so the target is `detached/broken_detached/attaching_<dir>` and its parent
does not exist. The `_tryN` existence probe passes for the same reason, so
no retry fires. The rename dies with ENOENT, `old_dir` is left set, and
the broken part stays an attach candidate, so every later
`ATTACH PARTITION` for that partition keeps failing on it. No concurrency
is required.

This is a regression. a5eeba9 introduced
the quarantine as a local rename inside `detached/`, and
56cd154, under three hours later the
same day, replaced it with `part->renameToDetached("broken", false)`
while adding the correct retryable/non-retryable split. The branch has
been dead on arrival since.

Restore the local rename, targeting a free `detached/broken_<dir>[_tryN]`.
`broken_<dir>` parses with a non-empty prefix and a valid name, so it is
excluded from both attach candidate filters and stays removable by both
`DROP DETACHED PART` and `DROP DETACHED PARTITION`; routing through the
generic allocator would instead produce a name that does not parse, which
`DROP DETACHED PARTITION` skips. The target is handed to `renameTo`
explicitly, with `remove_new_dir_if_exists` false, so the rename refuses
an occupied directory instead of recursively removing a part an earlier
quarantine put there, and the collision advances to the next `_tryN` name.
`renameToDetached` cannot be reused for this because it passes true. On
any other error, or when the last attempt collides, the exception is
rethrown so the failure is logged, `old_dir` is left set and the rollback
runs as before.

Nothing generic changes and the branch has no working caller to regress.
A rollback whose target base name was re-taken concurrently can still
orphan `attaching_<dir>`, and the claim can still take a directory a
concurrent `DETACH` is populating; neither is addressed here.

Add an integration test rather than a functional one, because it has to
remove `count.txt` from a part directory inside `detached/`.

Reported on ClickHouse#116258
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116258&sha=629bd7e0f725f065b6ea8e783f98ae4b3e28e067&name_0=BackportPR&name_1=Stateless%20tests%20%28amd_asan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29
Related: ClickHouse#54748
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold by an independent reviewer, then by a second model against the frozen PR body. Every
finding below is adjudicated with code citations or measured output.

❌ Fixed before publication

The quarantine rename must be directory-aware. The first draft renamed the claimed part
directory with the file-move contract (IDisk::moveFile). On object-storage metadata backends that
rejects a non-file source outright (MetadataStorageFromPlainObjectStorageMoveFileOperation::execute
requires existsFile(path_from); InMemoryDirectoryTree::moveFile likewise), so the quarantine
would have thrown there and left the pre-fix outcome, while the changelog entry claims the fix
without qualification. The rename now goes through IMergeTreeDataPart::renameTo with an explicit
target and remove_new_dir_if_exists = false, so it uses existsDirectory plus moveDirectory on
every backend and still refuses an existing target instead of removing it. The target name is
unchanged, and the diff is smaller.

Exhausting the _tryN search was silent. After ten collisions the loop fell through with no
exception, so the existing fail to rename part ... with broken prefix diagnostic never fired and
the regression test's own negative-log assertion could not see the failure. The last attempt now
rethrows, which matches the generic detached-name allocator, where exhaustion also ends in a throw.
Verified load-bearing by lowering the bound to one in a scratch build: the test then fails, as it
should.

⚠️ Raised and answered with evidence

"Also cover a non-local writable backend in the test." Declined on structure, not on cost. After
the change the rename uses moveDirectory, the same primitive PartsTemporaryRename::tryRenameAll
already uses on this exact directory a few lines earlier in the same function. If moveDirectory did
not work on a backend, the claim that creates detached/attaching_<part> would fail there first and
this branch would be unreachable, so the fixed path cannot fail where the surrounding, already
exercised path succeeds. The two local-disk arms remain the discriminator for the naming, candidacy
and SQL-removability contract.

"Drop the fixed ten-attempt boundary and add an arm with all ten names occupied." Declined. The
bound is not chosen here: the generic detached-name allocator loops the same
for (int try_no = 0; try_no < 10; ++try_no) (DataPartStorageOnDiskBase.cpp:140), documented as
"no more than 10 attempts are made so that there are not too many junk directories left", and on
exhaustion it returns the occupied name so the caller's rename throws, which is the outcome here.
Every other rename-aside in the tree carries that ceiling. Both ways of removing it are worse: an
unbounded search is the junk accumulation the convention exists to prevent, and a unique
non-_tryN suffix stops the name parsing as a detached part name, which loses removal by
DROP DETACHED PARTITION (it requires valid_name, MergeTreeData.cpp:9595) -- the property this
fix depends on. Before this change the quarantine failed on the first attempt, unconditionally, so
with ten names occupied the outcome is today's rather than worse. Happy to add the ten-occupied arm
if you want that boundary pinned.

💡 Noted, not blocking

With ten same-named quarantines already present, the broken part is rolled back and stays an attach
candidate, so that partition is blocked again. That is the ceiling above, and it is where the code
already was.

The attempt bound 10 is written twice, in the loop condition and in the rethrow guard, so changing one
without the other would silently bring back the missing diagnostic described above. Left as a literal
because the generic allocator hardcodes the same bound; happy to hoist it into a constant.

The collision is detected by renameTo's existence check, so a target created between that check and
the move raises std::filesystem::filesystem_error rather than DIRECTORY_ALREADY_EXISTS and skips
the _tryN retry. That window ends in the pre-existing log-and-rollback path, so it is fail-safe.

PartsTemporaryRename::rollBackAll also spells its part-directory rename as moveFile, so on those
two metadata backends the rollback paths of this function remain affected. That is pre-existing,
untouched here, and unrelated to the defect this PR fixes.

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One command, no concurrency, no failpoint, no timing: the new integration test removes count.txt from one replica's detached/ copy, then attaches the partition on the other replica.
b Root cause explained? Yes. The part's part_dir is detached/-qualified, getPartDirForPrefix appends it verbatim, so the quarantine target is detached/broken_detached/attaching_X, whose parent does not exist; the rename fails ENOENT, old_dir.clear() is skipped, and the part never leaves attach candidacy.
c Fix matches root cause? Yes. The rename is done where the directory actually is, restoring the local rename a5eeba9e90649d59 used before 56cd154bcdbf11c replaced it. No bound widened, no tag added, no guard masking an upstream bug.
d Test intent preserved / new tests added? Yes. New integration test, two arms; nothing existing weakened. It lives in tests/integration/ because it must corrupt a part inside detached/.
e Both directions demonstrated? Yes. Unpatched: 2 failed, with fail to rename part ... broken_detached/attaching_all_0_0_0 in the log. Patched: 2 passed, that line absent. Build IDs verified distinct, and the server's own build id: line confirms which binary ran.
f Fix is general across code paths? Yes. attachPartHelperFoundValidPart has exactly one caller. Of the three sites that build a two-component part_dir, only this one reaches a prefixed rename. No generic code changed, so the other prefixed-rename callers are unaffected; SharedMergeTree overrides none of them.
g Fix generalizes across inputs? Yes. The input is a directory name, so both name cases are covered by the two test arms: free target (broken_X) and taken target (broken_X_try1), plus the bounded retry falling through to today's behaviour. Both produced names are excluded from the two attach candidate filters and removable by SQL, which the test asserts. Across disk types the rename uses moveDirectory, the same primitive the claim that creates attaching_X already uses on this directory, so it is directory-aware wherever this branch is reachable.
h Backward compatible? Yes. No setting, default, on-disk format or serialization version changes, so no SettingsChangesHistory.cpp entry. The touched branch cannot succeed today, so it has no working caller to regress, and an existing broken_X directory is never overwritten: the rename refuses an occupied target instead of removing it.
i Invariants and contracts preserved? Yes. The branch owes its caller "after a successful quarantine old_dir is empty so the rollback is a no-op". Success clears it; a target-exists collision retries under a bounded _tryN; any other error, or a collision on the last attempt, rethrows so the failure is logged and it stays set, and the rollback runs exactly as today. part_dir, the retryable branch and the surrounding rollback are unchanged, so the detached/attaching_<name>/ assertion in ReplicatedMergeTreeSink is untouched.

Regression sweep: 12 of 13 integration tests around detached parts and attach passed (including
test_deduplicated_attached_part_rename and test_covered_by_broken_exists).
test_detached_parts_metrics::test_numbers_of_detached_parts failed identically on an unpatched
build of the same tree, uses a non-replicated table, and passes 5 of 5 when run on its own, so it is
a pre-existing asynchronous-metrics timing flake rather than a regression here.
Stateless tests (amd_debug, parallel) over the detach/attach families gave 92 passed, 0 failed,
3 skipped.

Session id: cron:clickhouse-impl-slot-6:20260827-134700

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c2fe5fc]

Summary: ✅


AI Review

Summary

This PR fixes the replicated ATTACH PARTITION quarantine path for broken detached parts by renaming from the already-claimed detached/attaching_* directory to a local detached/broken_*[_tryN] target instead of routing back through renameToDetached. I did not find a remaining correctness issue in the current revision: the new path preserves the existing detached-name parsing contract, keeps occupied quarantine directories intact, and the added integration test covers both the free-name and collision cases.

Final Verdict

✅ No new blocking or major findings in the current revision.

LLVM Coverage Report

Measured on commit c2fe5fc.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 13/14 (92.86%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @CheSema, could you review this? The broken-part quarantine in the replicated ATTACH_PART path derives its target from the part's already detached/-qualified part_dir, so it has always aimed at detached/broken_detached/attaching_<part> and failed with ENOENT; the part is then rolled back, stays an attach candidate, and blocks every later ATTACH PARTITION for that partition.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing c2fe5fcdc with master e9fc4b47c (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
Binary Master PR Δ
programs/clickhouse-stripped 712.33 MiB 709.28 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — c2fe5fc

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Code Review (run 33093818711) infra: this commit dispatched two PR workflow runs, and the duplicate Code Review job resolved the pull-request number as -1, so post-or-update could not comment (gh pr comment -1), the CI database rejected the insert (Code: 72, Unsigned type must not contain '-' symbol), and the job-log upload then asserted #116701 (ours, open)
request-reviews-fork (run 33093817965) infra: same duplicate dispatch; this instance was cancelled while the instance in run 33093819440 succeeded #116701 (ours, open)

#116701 "Do not run two PR workflows at the same commit" is the fix for the mechanism, not a
same-area guess: I enumerated all 360 check-runs on this head and nearly every job name appears
twice, once under run 33093818711 and once under 33093832394, which is the duplicate dispatch that
PR removes.

Neither row is a review finding and neither hides a test failure:

  • The Code Review job in the other run concluded success and posted its verdict on this commit:
    "No new blocking or major findings in the current revision."
  • praktika's own report for this head records Code Review as OK and the top-level PR as OK;
    Mergeable Check, Finish Workflow and CH Inc sync are all green.
  • Of the 360 check-runs, 306 succeeded, 52 were skipped, and the only two non-success entries are the
    two above. Every duplicated job name is success/success apart from Code Review, so the duplicate
    dispatch did not shadow a red.

Session id: cron:our-pr-ci-monitor:20260827-223000

@clickhouse-gh clickhouse-gh Bot added the comp-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. label Sep 4, 2026

@alexey-milovidov alexey-milovidov 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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 20, 2026
Merged via the queue into ClickHouse:master with commit 710b4aa Sep 20, 2026
362 of 364 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 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-replication ReplicatedMergeTree* + replication log/state transitions, eventual consistency mechanics. 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