Repository navigation
Fsync DETACH PARTITION clone into detached/ to survive power loss - #111426
Algunenano merged 6 commits into
Conversation
Internal second-model review (click to expand)An independent model reviewed the resulting code before this PR was opened. Findings and dispositions: Blockers
Nits
Majors (found on recheck)
|
Pre-PR validation gate (click to expand)
Verified on btrfs + |
|
cc @Algunenano @CurtizJ - could you review this? |
|
Workflow [PR], commit [8f6e466] Summary: ❌
AI ReviewSummaryThis PR makes Missing context / blind spots
Final Verdict✅ No actionable findings in the current revision. |
|
CI Triage (bot) — head Verdict: REAL FAILURE — PR's own test Stateless tests (amd_debug, parallel) and (amd_debug, flaky check) both report repeated failures for This test was introduced by this PR ("Fsync DETACH PARTITION clone into detached/ to survive power loss") and is failing consistently, suggesting the feature itself or the test assertions need fixing. Action needed: Investigate why Run ID: 29938674190 |
|
Fixed the flaky-check failure on the new test Root cause: the test observes the DETACH directory fsyncs with an aggregate over Fix: pin Note: the CI |
Internal second-model review (follow-up test fix ebf73cf, click to expand)An independent model reviewed the resulting code before this push. Findings and dispositions: Major
Nit
Verification (Build IDs recorded): with-fix + local disk PASS; with-fix + remote disk PASS (was the CI failure); pre-fix + local disk FAIL (bug still caught); 50/50 randomized-MergeTree-settings runs PASS. |
Internal second-model review (test robustness fix 0024305, click to expand)An independent model reviewed the resulting test before this push. Finding and disposition:
|
|
The new test Symptom (deterministic values, non-deterministic occurrence). In failing runs the DETACH query records Why this is paradoxical. Not reproducible in isolation. detach=8 every time across: 150 debug runs, 60 ASAN runs via the runner, every individual MergeTree setting (25+), every session setting (10+), the exact 371 regular + 59 MergeTree randomized settings from a failing run applied together, and 8x concurrent DETACH/fsync load on debug. It only fails in CI under concurrent flaky-check load on sanitizer builds. The two candidates (opposite fixes).
Does |
Algunenano
left a comment
There was a problem hiding this comment.
@groeneai I cannot accept this as it is with the flaky test. Please download the logs, investigate what happened and what caused it to fail and improve it. If you don't find any information in the CI logs, focus again on reproducing it locally, or looking at settings. The normal (not flaky checks) seem to point to full vs packed part as possible issue (which makes sense).
Also, I find it hard to follow the test. If it's not possible to test with parallel replicas, then disable that directly and explain why, same with object storage, local vs remote. Having workarounds (detach_on_remote) and repeated calls to functions with odd parameters and output makes it hard to read. I'd rather have no functions and sql queries explicitly matching the behaviour, rather than relying on bash
Internal second-model review (Gate B) adjudication for b4c6f2bFollow-up to the two prior test-only attempts. Root cause of the 04622 flakiness: the test read Second-model review (codex): 1 finding, adjudicated.
Both directions re-verified through the real |
b4c6f2b to
473299d
Compare
|
@Algunenano thanks, addressed both points in 473299d. Root cause (investigated). I downloaded the logs and reproduced both directions locally. The failure is not full-vs-packed: The fix reads Readability. Rewrote it as plain SQL, one table per scenario, no bash helper and no runtime Verified both directions: with the fix all assertions hold (30x randomized plus concurrent detach load, 0 failures); with the freeze block reverted |
This is not true. Update your build and reference. packed parts are part of the OSS now |
This is wrong too. You should not disable all randomization, as it's clearly detecting problems. Instead find out which cause issues and test them separately by pinning them to their possible values |
|
You are right on both, thanks for the correction.
I will update the branch to master, verify Packed vs Full reproduces the collapse and that the pinned test passes under randomization, and report back here. |
|
Done in 09cc68e: dropped Why no pinning is needed: the checks are now relative (a DETACH must fsync at least two more directories than a DROP of the same partition, and a projection one more than a plain detach), so they hold whatever layout randomization produces. I verified this rather than assuming it:
Kept |
09cc68e to
c5bf342
Compare
|
Correction to my previous comment: I was wrong that no pinning was needed. min_bytes_for_full_part_storage does matter. On master, choosePartFormat returns a Packed (single-blob) part when bytes_uncompressed < min_bytes_for_full_part_storage; clickhouse-test randomizes that setting up to 512 MiB (~30% of runs), so the tiny test part becomes a Packed part with no per-directory layout and no directory fsyncs, and the DirectorySync counts collapse. My earlier "relative check holds under any layout" verification ran on the branch's base tree (2026-07-15), which predates the packed-parts merge and so only ever produced Full parts, hiding this. So the --diagnose-random-settings culprit was right after all. Pushed c5bf342: dropped the no-random-* tags and pinned only min_bytes_for_full_part_storage = 0 (forces Full/directory storage) in each CREATE TABLE, leaving every other setting randomized. Kept no-object-storage and no-parallel-replicas. The part_log DirectorySync read and the relative detach >= drop + 2 assertion are unchanged. |
CI finish ledger - 589f04fEvery failure below has an owner (a fixing PR). Only
The PR-caused Session id: cron:our-pr-ci-monitor:20260723-223000 |
CI finish ledger — 589f04fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260724-040000 |
ALTER TABLE ... DETACH PARTITION hardlink-clones the part into detached/ via makeCloneInDetached -> DataPartStorageOnDiskBase::freeze and fsyncs none of it, then commits an empty covering part that removes the rows from the active set (which IS fsynced when fsync_part_directory is on) and lazily deletes the original. The commit that removes the data is durable while the clone that preserves it is not, so on btrfs a power loss right after the acknowledgement rolls back the un-synced clone directory entries: detached/ ends up empty, the rows are gone from the active set, and the original is loaded as covered and cleaned up. The only copy of the detached data is destroyed. (ext4/xfs happen to persist the earlier clone through the single journal, an ordering accident.) DataPartStorageOnDiskBase::freeze now, when fsync_part_directory is set (and on a local disk, outside an external transaction), fsyncs the clone's part-directory subtree bottom-up (part dir plus projection subdirs, i.e. the hardlink entries) and every ancestor directory from the clone's immediate parent (detached/) up to and including the disk root. fsync(dir) persists the entries inside dir, not dir's own entry in its parent, and detached/ is created at table init without an fsync while normal part commits fsync only the child part dir, so the parent chain must be synced for the clone to survive a first-ever detach. freeze() returns before the caller commits the covering part, so this synchronous fsync orders the clone durable before that commit. Gated on the existing fsync_part_directory MergeTree setting (default false), so default behavior is unchanged and no SettingsChangesHistory entry is needed. A no-op on remote/object-storage disks (getDirectorySyncGuard returns nullptr). This is the DETACH variant of the same unsynced freeze/Backup clone path as issue ClickHouse#111331 (FREEZE, addressed in ClickHouse#111393); a FREEZE-only fix does not close it. Closes: ClickHouse#111382 Co-Authored-By: Claude fable-5 <[email protected]>
Regression test for ClickHouse#111382 (DETACH PARTITION must fsync the detached/ clone so a power loss right after the acknowledgement cannot destroy the only copy of the data). The directory fsyncs are observed via ProfileEvents['DirectorySync'] on the ALTER's covering empty part (part_name all_1_1_1) in system.part_log. part_log ProfileEvents are a synchronous snapshot taken on the query thread, so they capture the clone-freeze fsyncs deterministically; the per-query system.query_log counters do not, because the clone freeze runs in a nested profile-events scope whose increments do not reliably reach the query's thread-group snapshot under CI parallel load (this made an earlier query_log-based version flaky at detach=2 drop=2, the covering-part-only baseline). This is DETACH specific: 02361_fsync_profile_events reads the same counter from query_log for an INSERT and is not flaky. The test is plain SQL with one table per scenario (02378/03221 part_log style). The confounders are disabled at the tag level with an explanation each, rather than worked around at runtime: no-parallel-replicas (the runner otherwise points cluster_for_parallel_replicas at a cluster absent on the single-node test server), no-object-storage (freeze fsyncs local directories only), and no-random-settings/no-random-merge-tree-settings (the part layout must be fixed so the directory counts are deterministic). The signal is relative: a DETACH fsyncs the clone leaf and its ancestor chain on top of the covering part, a DROP fsyncs only the covering part, and fsync-off fsyncs nothing, so detach >= drop + 2, proj > plain, off = 0. The test also re-attaches every detached partition and checks all rows are preserved, and asserts all four covering NewPart rows were logged so a missing row cannot pass silently. Verified both directions: with the fix every assertion is true (30x randomized plus concurrent detach load, 0 failures); with the freeze block reverted clone_synced and proj_subtree_synced are false, matching the CI failure. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ation for 04622 Drop the no-random-settings / no-random-merge-tree-settings tags and instead pin only the setting that changes the on-disk layout the test measures. On master, choosePartFormat returns a Packed (single-blob) part when bytes_uncompressed < min_bytes_for_full_part_storage; clickhouse-test randomizes that setting up to 512 MiB, so the tiny test part becomes a Packed part with no per-directory fsyncs and the DirectorySync counts collapse. Pinning min_bytes_for_full_part_storage = 0 keeps the parts in Full (directory) storage; every other setting stays randomized. Keeps no-object-storage and no-parallel-replicas (the test genuinely cannot run under those). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rentDatabase() linter The new test 04622_detach_partition_fsync_part_directory.sql reads directory fsync counts from system.part_log (already scoped with database = currentDatabase()). It does not query system.query_log. The literal string system.query_log appeared only in an explanatory comment contrasting part_log's synchronous ProfileEvents snapshot with query_log's async per-query counters. check_style/various_checks.sh greps the whole file (comments included) for system.query_log/system.query_thread_log and then requires a current_database = currentDatabase() predicate, so the comment tripped a false positive and failed Style check. Adding such a predicate would be misleading since the test does not read query_log and system.part_log has a database column, not current_database. Reword the comment to drop the literal so the linter no longer matches; behavior is unchanged (comment-only).
589f04f to
7508efc
Compare
DataPartStorageOnDiskPacked::freeze is an independent override of DataPartStorageOnDiskBase::freeze. The base override was fsynced in the first commit of this PR, but the packed override hardlinks/copies data.packed into detached/<part>/ and issued no directory fsync, so a DETACH of a Packed part (a part satisfying min_bytes_for_full_part_storage etc.) had the same ClickHouse#111382 data-loss exposure on power loss. Extract the shared subtree-fsync + ancestor-walk into fsyncFrozenCloneTree() and call it from both overrides, gated identically (fsync_part_directory && !external_transaction && !isRemote). Packed clones store each projection as a <name>.proj subdirectory, so the per-projection freeze clears fsync_part_directory and the top-level walk fsyncs the whole clone subtree plus ancestor chain exactly once. Add a PACKED regression group to 04622 (min_bytes_for_full_part_storage set high to force Packed storage, guarded by an all_packed assertion) mirroring the Full group's relative DirectorySync checks. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review of the packed extension by an independent model (engine: codex; 3 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-0:20260724-150100 |
|
Packed-storage extension (commit 12c0104): pre-PR validation gate. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-0:20260724-150100 |
CI finish ledger - 12c0104CI has finished (Finish Workflow green). The PR's own new test
Neither failure is caused by this PR. The C++ durability fix (Full + Packed part storage) is unchanged. Session id: cron:our-pr-ci-monitor:20260725-000000 |
Two conflicts, both purely additive; keep-both in each. src/Storages/MergeTree/IDataPartStorage.h: master added ClonePartParams::invalidated_columns_to_write next to our fsync_part_directory field. Both kept; ours stays last so the designated-initializer order at every call site still matches declaration order. src/Storages/MergeTree/IMergeTreeDataPart.cpp: the conflict is textual only - master's side of the hunk in makeCloneInDetached is empty. Our .fsync_part_directory initializer is preserved unchanged, so the detached/ clone still honours fsync_part_directory on every DETACH path. Also checked the two auto-merged freeze() bodies: master's new writeInvalidatedSystemColumnsFile() call runs before our fsync block in both the Full and Packed overrides, so the clone (including the newly written invalidated-columns file) is still made durable before freeze() returns.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 30/31 (96.77%) · Uncovered code |
CI finish ledger - 8f6e466Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Sole red on this head: 174 check-runs, 155 success, 18 skipped, 1 failure, Not caused by this PR, and the evidence is the stack rather than the breadth alone. The Breadth over the last 30 days for I checked whether any fixing PR exists before falling back to a task: the one merged Session id: cron:our-pr-ci-monitor:20260728-193000 |
42b19a0
Resolves 3 conflicts from master PR #111426 (fsync DETACH/freeze clone for power-loss durability) against this branch's unified freeze/freezeRemote refactor: - IDataPartStorage.h: keep both ClonePartParams::forProjection and fsync_part_directory. - DataPartStorageOnDisk{Base,Packed}.cpp: keep the unified freeze(..., dst_disk_, ...), drop master's now-orphan separate freeze/freezeRemote, and graft fsyncFrozenCloneTree (local dst_disk, no external transaction). Packed threads fsync_part_directory=false into projection sub-freezes so one top-level fsync covers the whole subtree. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two changes on master do not compile for the Windows target: - The frozen-clone fsync (#111426) passes an `fs::path` to `fsyncFrozenCloneTree`, relying on the implicit `path`/`std::string` conversion that only exists on POSIX. Route it through `pathToGenericString`, like every other disk-path construction site. - The directory-name length check for async distributed INSERT moved from `Cluster.cpp` to `DistributedSink::checkDirectoryNameLengths`, bringing back a bare `NAME_MAX`, which Windows does not define. Reintroduce the `max_path_component_length` constant this branch had used in `Cluster.cpp` (where master removed the check) at the new site. PR: #112824 Co-Authored-By: Claude Fable 5 <[email protected]>
…-freeze-fsync The sibling DETACH PARTITION durability fix (ClickHouse#111426) merged into master on 2026-08-03 and carried the shared machinery this branch had introduced: syncDirectoryTree, the subtree+ancestor walk (now the free function fsyncFrozenCloneTree in DataPartStorageOnDiskBase), the ClonePartParams fsync_part_directory field, and the calls from both freeze overrides. Resolution therefore drops this branch's now-duplicated copies in favour of master's, rather than keeping both: - IDataPartStorage.h: identical fsync_part_directory member on both sides, only the doc comment differed. Took master's comment verbatim. - DataPartStorageOnDiskBase.{h,cpp}: dropped the private member function syncFrozenPartDirectory and its call, keeping master's equivalent free function fsyncFrozenCloneTree. Master's call site is strictly better placed: it runs after save_metadata_callback, so the freeze metadata the callback writes is covered by the same fsync. - DataPartStorageOnDiskPacked.cpp: dropped the duplicate directory-sync call, keeping master's. A naive keep-both would have walked and fsynced the whole clone subtree twice per frozen part. What remains unique to this branch is exactly the ClickHouse#111331 fix and its guard: the FREEZE call site in freezePartitionsByMatcher now populates fsync_part_directory from the table's setting (master only wires up the DETACH call site, so ALTER TABLE ... FREEZE still acknowledged a non-durable snapshot), the fsync of a rewritten data.packed archive's contents, and the 04621 regression test.
…-part-fsync Resolve the createEmptyPart signature conflict: master added a required patch_part_index parameter (patch-part support) while this branch added an optional force_sync. Both are kept, with force_sync last so it stays defaulted and the other callers (MutateTask, StorageReplicatedMergeTree, MergeTreeData::6871) are unaffected. Re-checked that master has not since closed the durability gap: createEmptyPart still gates the part-directory guard on fsync_part_directory and the content fsync on fsync_after_insert, both default off, and renameAndCommitEmptyParts still syncs nothing. The merged DETACH clone fsync (ClickHouse#111426) is itself gated on fsync_part_directory, so excluding DETACH from force_sync remains correct.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
ALTER TABLE ... DETACH PARTITION/PARTnow fsyncs the clone it creates underdetached/(the part subtree plus the directory chain up to the disk root) when the table'sfsync_part_directorysetting is enabled, for both Full (directory) and Packed part storage. Previously the clone was never fsynced while the empty covering part that removes the rows from the active set was, so a power loss right after the acknowledgement could destroy the detached data on btrfs (the un-synced clone directory entries roll back, leavingdetached/empty and nothing toATTACH). Gated on the existingfsync_part_directorysetting; default behavior is unchanged.Description
Closes: #111382
ALTER TABLE ... DETACH PARTITIONis not a rename.StorageMergeTree::dropPart/dropPartitionexecute it as: (1)IMergeTreeDataPart::makeCloneInDetached->freeze()hardlink-clones the part intodetached/<part>and fsyncs nothing; (2) an empty covering part that removes the rows from the active set is committed, which IS fsynced whenfsync_part_directoryis on; (3) the original part directory is deleted lazily. So the operation's two durable artifacts get opposite treatment: the commit that removes the data is fsynced, the clone that preserves it is not. On btrfs the covering part's per-inode log fsync persists only its own subtree, so the un-synced clone directory entries roll back on power loss:detached/is empty, the rows are gone from the active set, and the original is loaded as covered/outdated and cleaned up. The only copy of the acknowledged detached data is destroyed. (On ext4/xfs the single journal happens to persist the earlier clone, an ordering accident rather than a guarantee.)freeze(), whenfsync_part_directoryis set (and on a local disk, outside an external transaction), now fsyncs:detached/) up to and including the disk root.fsync(dir)persists the entries insidedir, notdir's own entry in its parent, anddetached/is created at table init without an fsync while normal part commits fsync only the child part dir, so the parent chain must be synced too for the clone to survive on a first-ever detach.freeze()returns before the caller commits the covering part, so this synchronous fsync orders the clone durable before that commit.There are two independent
freeze()implementations and both are fixed:DataPartStorageOnDiskBase::freeze(Full/directory storage, used byDataPartStorageOnDiskFull).DataPartStorageOnDiskPacked::freeze(singledata.packedarchive storage, chosen when a part satisfiesmin_bytes_for_full_part_storage/min_rows_for_full_part_storage/min_level_for_full_part_storage). This is a fully independent override that hardlinks/copiesdata.packedintodetached/<part>/and previously issued no directory fsync, so aDETACHof a Packed part had the same data-loss exposure on power loss. Packed clones store each projection as a<name>.projsubdirectory, so the per-projection freeze clearsfsync_part_directoryand the top-level walk fsyncs the whole subtree plus ancestor chain exactly once.The shared directory-sync logic (subtree fsync + ancestor walk) is extracted into a single
fsyncFrozenCloneTree()helper that both overrides call. Gated on the existingfsync_part_directoryMergeTree setting (defaultfalse), so default behavior is unchanged and noSettingsChangesHistoryentry is needed. On remote/object-storage disksgetDirectorySyncGuard()is a no-op, so the change is local-disk only.Verified on btrfs over
dm-flakey(power cut = drop_writes + unmount without flush, per the xfstests_flakey_drop_and_remountrecipe): on the unpatched build the detached data is lost after the cut (detached/empty,count() = 0, nothing toATTACH); with the fix the detached part survives andATTACH PARTITIONrestores all rows. Also verified viaProfileEvents['DirectorySync']on the covering empty part'sNewPartrow insystem.part_log: aDETACHfsyncs at least two more directories than aDROPof the same partition (clone leaf plus ancestor), a projection adds one more, and nothing is fsynced withfsync_part_directory = 0, for both Full and Packed storage. Regression test:tests/queries/0_stateless/04622_detach_partition_fsync_part_directory.sql.This is the
DETACHvariant of the same unsyncedfreeze/Backupclone path as #111331 (FREEZE, addressed in #111393). #111393 touches only theFREEZEcall site and does not close this: the durability boundary forDETACHis thedetached/clone plus the covering-part ordering. Both PRs add aClonePartParams.fsync_part_directoryfield and afreeze()directory-sync; the overlap is a trivial conflict for whichever merges first, and I am happy to consolidate them.Version info
26.8.1.677(included in26.8and later)