Skip to content

Fsync detached directory on DROP DETACHED PART/PARTITION - #111375

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-111349-drop-detached-part-fsync
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-111349-drop-detached-part-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111349

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

ALTER TABLE ... DROP DETACHED PART/PARTITION now fsyncs the detached directory when the fsync_part_directory MergeTree setting is enabled, so an acknowledged drop of a detached part is no longer rolled back by a power loss (the removed part could previously reappear).

Description

MergeTreeData::dropDetached renames detached/<part> to detached/deleting_<part> and then unlinks it, but never fsync'd the detached directory and consulted no durability setting. A rename or unlink is durable only once the parent directory is fsync'd, so after a power loss in the filesystem journal window the directory-entry changes could roll back and the acknowledged-dropped detached part reappeared intact. Reported and reproduced 3/3 with a dm-flakey power-loss simulation in #111349.

Fix, gated on the existing fsync_part_directory setting (default false, so no behavior change by default): before the rename, acquire one directory sync guard per involved disk on the detached directory and hold it across the rename and the removal; the guard fsyncs the directory on destruction. The guards are declared before PartsTemporaryRename so they outlive it and also cover the rollback rename on the error path. This uses the disk-agnostic IDisk::getDirectorySyncGuard (local disks fsync; object storage is a no-op), matching the existing fsync_part_directory handling for part directories in IMergeTreeDataPart::renameTo.

Test: 04620_drop_detached_part_fsync asserts the DirectorySync ProfileEvent is emitted for DROP DETACHED PART when fsync_part_directory = 1 and not when 0, and that the part is removed in both cases.

MergeTreeData::dropDetached renamed detached/<part> to
detached/deleting_<part> and unlinked it without ever fsync'ing the
detached directory, and consulted no durability setting. A rename or
unlink is durable only once the parent directory is fsync'd, so a power
loss in the filesystem journal window could roll the directory-entry
changes back and the acknowledged-dropped detached part reappeared.

Gate the fsync on the existing fsync_part_directory setting (default
false, no behavior change by default): acquire one directory sync guard
per involved disk on the detached directory before the rename and hold
it across the rename and removal. The guards are declared before
PartsTemporaryRename so they outlive it and also cover the rollback
rename on the error path. Uses the disk-agnostic
IDisk::getDirectorySyncGuard (local disks fsync, object storage no-op).

Closes: ClickHouse#111349

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Table setting fsync_part_directory=1, INSERT, DETACH PARTITION, then ALTER TABLE t DROP DETACHED PART '<p>' SETTINGS allow_drop_detached=1; read ProfileEvents['DirectorySync'] from system.query_log for that query_id.
b Root cause explained? Yes. MergeTreeData::dropDetached renames detached/<part> to detached/deleting_<part> then removeRecursive, but never fsyncs the detached directory and reads no durability setting. A rename/unlink persists only once the parent directory is fsync'd, so a power loss in the journal window rolls the entry changes back and the dropped part reappears.
c Fix matches root cause? Yes. Fsync the detached directory around the rename+unlink, via a directory sync guard held across both operations.
d Test intent preserved / new tests added? Yes. New stateless test 04620_drop_detached_part_fsync asserts DirectorySync>=1 when the setting is on, ==0 when off, and that the part is removed either way.
e Demonstrated both directions? Yes. On the pristine binary DirectorySync=0 even with fsync_part_directory=1 (the bug); with the fix DirectorySync=1 when on and 0 when off.
f Fix general, not a narrow patch? Yes. dropDetached is the single method behind DROP DETACHED PART and PARTITION (both route through PartitionCommand::DROP_DETACHED_PARTITION). Covers part- and partition-level and multi-disk (dedup per disk). Not placed in removeDetachedPart, which is also called from dropAllData/backup where a detached dir fsync is meaningless.
g Generalizes across inputs? Yes. Part / partition / partition-all; local disk fsyncs, object storage no-ops via a null guard; multi-disk partition drop dedups per disk; setting values 0 and 1 both covered.
h Backward compatible? Yes. Reuses the existing fsync_part_directory setting (default false). No default change, no SettingsChangesHistory.cpp entry; default path is byte-for-byte today's behavior.
i Invariants/contracts preserved? Yes. Guards declared before PartsTemporaryRename so their fsync runs after the rename rollback; matches LocalDirectorySyncGuard's documented open-across-op / fsync-on-destroy contract and the DistributedAsyncInsertDirectoryQueue precedent. Uses the IDisk API (no API/format/protocol change).

Session id: cron:clickhouse-author-slot-1:20260722-110200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (adjudicated) - click to expand

An independent second model reviewed this change before it was opened. All findings and dispositions below; nothing is a blocker.

Blockers: none.

Majors:

  • local-policy-not-pinned (test determinism) - AGREE, fixed. no-object-storage is honored only when the runner is told it is an object-storage run (--s3-storage/azure), but the stress runner can make an object-storage policy the implicit MergeTree default without that flag, where the directory fsync is a no-op and DirectorySync=0 would fail the reference. Pinned storage_policy = 'default' in the test's CREATE TABLE (same fix as the sibling test 04063_drop_detached_part_with_try_n_suffix.sh); re-verified.

Nits:

  • random-mt-optout (test determinism) - AGREE, fixed. The MergeTree-settings randomizer only injects settings absent from the CREATE TABLE, and the test pins fsync_part_directory explicitly, so no-random-merge-tree-settings was redundant. Removed it (kept no-object-storage); re-verified 50/50 with randomization on.
  • test-comment-narrative (verbosity) - AGREE, fixed. Trimmed the test header comment to the issue link plus why DirectorySync is used as the durability proxy.
  • class-name-inline-code (style) - AGREE, fixed. Backticked PartsTemporaryRename in the source comment.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun - could you review this? It makes ALTER TABLE ... DROP DETACHED PART/PARTITION durable by fsync'ing the detached directory around the rename+unlink in MergeTreeData::dropDetached, gated on the existing fsync_part_directory setting (issue #111349).

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b57431f]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) FAIL
test_check_table/test.py::test_check_all_tables FAIL cidb, issue
Stress test (amd_tsan) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-23fd) FAIL cidb
Stress test (arm_tsan) FAIL
Cannot start clickhouse-server FAIL cidb, issue
Check failed FAIL cidb

AI Review

Summary

This PR makes MergeTreeData::dropDetached hold a directory-sync guard across the rename to deleting_ plus the recursive removal, so DROP DETACHED PART/PARTITION becomes durable on plain local disks when fsync_part_directory is enabled. That local-disk fix looks sound, but the same durability contract is still unimplemented for supported object-storage tables whose metadata lives on a local disk, so I cannot approve it as a complete fix yet.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:8538] The new guard is routed through IDisk::getDirectorySyncGuard, but DiskObjectStorage does not override that API and therefore inherits the default nullptr. DROP_DETACHED_PARTITION is still allowed on MetadataStorageType::Local disks, and those local metadata operations still commit plain moveDirectory / removeRecursive changes without any sync. A power loss can therefore still resurrect a dropped detached part on supported object-storage tables with local metadata, violating the PR's durability contract.
    Suggested fix: implement DiskObjectStorage::getDirectorySyncGuard by delegating to the underlying metadata disk when the metadata storage is MetadataStorageType::Local, then add coverage for that carrier. If that layout is intentionally out of scope, narrow the contract explicitly instead of advertising the fix as general DROP DETACHED durability.
Final Verdict

Changes requested: the fix is correct for DiskLocal, but it still leaves the reported post-ack power-loss window open for supported object-storage tables with local metadata.

{
if (!synced_disks.emplace(rename_info.disk->getName()).second)
continue;
if (auto guard = rename_info.disk->getDirectorySyncGuard(fs::path(relative_data_path) / DETACHED_DIR_NAME))

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.

DiskLocal and DiskEncrypted are fixed here, but this still does nothing for supported object-storage tables with local metadata. DiskObjectStorage does not override IDisk::getDirectorySyncGuard, so this line gets the default nullptr; meanwhile MergeTreeData::checkAlterPartitionCanBeExecuted still allows DROP_DETACHED_PARTITION on MetadataStorageType::Local disks, and their metadata rename/remove path still goes through MetadataStorageFromDiskTransaction::commit() to plain moveDirectory / removeRecursive calls on the local metadata disk with no sync. That leaves the same post-ack power-loss resurrection window open for this supported carrier of the feature.

Could we delegate DiskObjectStorage::getDirectorySyncGuard to the underlying metadata disk when the metadata storage is MetadataStorageType::Local, or otherwise scope/reject that layout explicitly?

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.

Confirmed and correct on all three points: DiskObjectStorage does not override getDirectorySyncGuard (default IDisk returns nullptr), checkAlterPartitionIsPossible allows DROP_DETACHED_PARTITION on MetadataStorageType::Local, and the metadata moveDirectory/removeRecursive in MetadataStorageFromDiskTransactionOperations are unsynced. So the object-storage-with-local-metadata layout keeps the window open.

Keeping this PR scoped to local disks (DiskLocal/DiskEncrypted), where the #111349 repro lives and the fix is proven, for two reasons:

  1. getDirectorySyncGuard is a shared IDisk primitive with 23 call sites (part renameTo, MergeTreeDataWriter, DistributedAsyncInsert*, VersionMetadataOnDisk, DeleteBitmapFileOps, ...). Delegating DiskObjectStorage::getDirectorySyncGuard to the metadata disk changes durability/perf for all of them, which is a broad change on its own.
  2. The directory guard alone would not close the object-storage window anyway: the metadata file operations (WriteFileOperation and friends) are also unsynced, so the complete object-storage fix is the multi-leg metadata-durability change (file sync + dir sync), not a one-liner here.

Rejecting the layout is not an option since it removes currently-working functionality. The limitation is documented (the no-object-storage tag on the test and the no-op note in the description). Tracking the object-storage local-metadata durability gap as separate follow-up work alongside the rest of the metadata-durability effort.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b57431f

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt. None are caused by this PR's diff (fsync of the detached/ directory on DROP DETACHED).

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (180 PRs / 254 hits / 24 master in 14d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stress test (amd_tsan) / Logical error: Block structure mismatch (STID 0993-23fd) chronic trunk (liftUpUnion quantileExactTuple; 10 PRs / 1 master in 14d) #110745 (ours, open)
Stress test (arm_tsan) / Cannot start clickhouse-server + Check failed chronic host-memory server-start failure (186 PRs / 263 hits in 7d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
CH Inc sync private sync CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260722-183000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PRs for the Stress test / Cannot start clickhouse-server + Check failed ledger line on this PR.

That row is emitted by the stress harness itself (tests/docker_scripts/stress_tests.lib:298) after the readiness probes fail, so it only says the server was not answering; the cause is on a sibling row of the same job. On this PR the cause was the part_loading_tree_rollback test family, which fabricates part directories out of band and left an unparsable part behind across a fault-injected restart:

Check Boot error
Stress test (arm_tsan) Code 722 -> 695 -> Code 246, part all_2_3_1_0 intersects all_1_2_2_1 in test_1.t_plt_reparent

Fixed by, all merged:

The object-storage variant of the same family is pinned by #111922 (open).

Verification: all three merge commits are ancestors of master, and the signature stops dead in CIDB. Boot failures caused by t_plt_* ran 35 / 63 / 64 / 64 / 66 / 36 per day over 07-19..07-24 and then 0 from 2026-07-24 04:48 onward. Occurrences after that date are confined to Upgrade check, which runs the frozen previous-release copies of the tests, so no master-side change can reach them.

Nothing about this failure was related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026

This branch has not been deployed

No deployments
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants