Skip to content

Fsync ALTER TABLE FREEZE snapshot to survive power loss - #111393

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111331-freeze-fsync
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111331-freeze-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 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):

ALTER TABLE ... FREEZE now fsyncs the snapshot it creates when the table's fsync_part_directory setting is enabled: the snapshot directories and the chain up to the disk root, plus the rewritten data.packed archive for packed part storage. Previously the freeze path fsynced nothing but shadow/increment.txt, so a power loss right after FREEZE was acknowledged could erase the whole snapshot. Default behaviour is unchanged.

Description

Closes: #111331

ALTER TABLE ... FREEZE builds its snapshot with createDirectories plus createHardLink (Full storage), or by rewriting data.packed (Packed storage), and fsyncs none of it. For a hardlink snapshot the file data is already durable but the new directory entries are not, so a power loss between the acknowledgement and the operator's archive step drops every new directory entry, i.e. the whole snapshot.

The directory-fsync machinery this needs is already in master: the sibling DETACH PARTITION durability fix (#111426) merged the fsync_part_directory clone parameter, fsyncFrozenCloneTree, and the calls from both freeze overrides. It only wires up the DETACH call site, so FREEZE still acknowledged a non-durable snapshot. This PR is what remains:

  1. freezePartitionsByMatcher populates fsync_part_directory from the table setting, resolved once from the entry snapshot so a concurrent MODIFY SETTING cannot split one FREEZE across parts.

  2. For packed storage, FREEZE rewrites the data.packed archive instead of hardlinking it, so the archive contents are fsynced too, for the part and for each projection.

Gated on the existing fsync_part_directory setting (default false), so no SettingsChangesHistory entry is needed. A no-op on remote/object disks, where getDirectorySyncGuard returns nullptr.

Verified via ProfileEvents DirectorySync and FileSync on the FREEZE query for both layouts, including the setting-off baselines. Regression test 04621_freeze_fsync_part_directory.sh.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE ... SETTINGS fsync_part_directory=1; INSERT; ALTER TABLE ... FREEZE WITH NAME 'x' (with a query_id), then read ProfileEvents['DirectorySync'] for that query in query_log: 0 on master, 7 with the fix. Deterministic per case.
b Root cause explained? Yes. FREEZE -> DataPartStorageOnDiskBase::freeze -> Backup.cpp builds shadow/<name>/store/<prefix>/<uuid>/<part>/ with createDirectories+createHardLink and fsyncs nothing; only shadow/increment.txt is synced. For a hardlink snapshot the inodes are already durable but the new directory entries are not, so a power loss after FREEZE acks drops the whole snapshot.
c Fix matches root cause? Yes. Adds the missing directory fsyncs in freeze(): recursively fsync the created part-dir subtree (part dir + projection subdirs) plus every ancestor up to the disk root. Not a band-aid; it makes durable exactly the entries the bug leaves volatile.
d Test intent preserved / new tests added? Yes (new). 04621_freeze_fsync_part_directory.sh asserts FREEZE syncs the ancestor chain (count >= 4, not just the leaf) and the projection subtree (a table with a projection syncs exactly one more dir than one without) with the setting on, and 0 with it off. No existing test weakened.
e Both directions demonstrated? Yes, with distinct Build IDs. Pristine e139f057 + setting=1 -> DirectorySync=0, test FAILS. Fix fda61620 + setting=1 -> plain=7/proj=8, test PASSES (10/10 deterministic).
f Fix is general across code paths? Yes. The fix is in the single owning function freeze() (all FREEZE parts flow through it); the subtree sync covers projection .proj subdirs, and the ancestor walk covers every new directory entry, not just the leaf. Other freeze() callers (DETACH clone, MOVE) keep the flag false, so their behavior is unchanged.
g Fix generalizes across inputs? Yes. Directory-entry durability is type-independent (no type-gating logic). Verified counts are stable across compact/wide parts, index_granularity=1, and uncompressed marks (directory count depends on path structure + projection count, not file-level settings). Remote/object-storage disks: getDirectorySyncGuard() is a no-op (guarded by !disk->isRemote()).
h Backward compatible? Yes. Gated on the existing fsync_part_directory MergeTree setting (default false); no default changed, no SettingsChangesHistory entry needed, no on-disk/wire format change. With the setting off, behavior is byte-for-byte the old behavior (verified DirectorySync=0).
i Invariants and contracts preserved? Yes. The sync runs AFTER Backup + the metadata callback + the tmp-file cleanup removals, so it fsyncs the final on-disk state. Reuses the established getDirectorySyncGuard/LocalDirectorySyncGuard primitive (same contract as the rename/fetch paths); its destructor swallows+logs errors so it cannot throw out of freeze(). The per-part flag is resolved once from the entry settings snapshot so a concurrent ALTER MODIFY SETTING cannot make some parts sync and others not.

Session id: cron:clickhouse-author-slot-5:20260722-105200

@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 findings; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Each FREEZE worker re-read table settings independently, so a concurrent ALTER ... MODIFY SETTING could make some parts sync and others not. AGREE — fixed Resolve fsync_part_directory once from the entry settings snapshot into a const bool before the worker loop and capture it by value. Matches how the function already snapshots settings at entry.
2 ⚠️ Test asserted only that some directory sync occurred, not that the full subtree AND ancestor chain were synced. AGREE — fixed Test now asserts (a) plain count >= 4 (ancestor chain reaches the disk root, not just the leaf) and (b) a table with one projection syncs exactly one more directory than the same table without one (recursive .proj subtree). Robust to path depth.
3 💡 no-random-merge-tree-settings tag unnecessarily suppresses randomized coverage. AGREE — fixed Removed the tag (kept no-object-storage). Verified the assertion counts are stable across randomized min_bytes_for_wide_part, index_granularity, and compress_marks — directory count depends on path structure, not file-level settings.
4 💡 Call-site comment duplicated the field/algorithm docs. AGREE — fixed Removed the duplicate; the call-site comment now documents only the caller-specific concurrency invariant (resolve the setting once).

Severity: ❌ blocker / ⚠️ major / 💡 nit. All findings adjudicated AGREE and fixed; the source fix was rebuilt (Build ID changed) and re-verified in both directions (10/10 deterministic). The bounded delta recheck did not return within the session due to a degraded review endpoint (recorded as fail-open per the gate contract).

Session id: cron:clickhouse-author-slot-5:20260722-105200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @tiandiwonder — could you review this? It makes ALTER TABLE ... FREEZE fsync the snapshot's directories (and the chain up to the disk root) when fsync_part_directory is set, so a power loss right after FREEZE acknowledges no longer erases the hardlinked snapshot. Gated on the existing setting; mirrors the part-clone rename() durability path.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [32d3ffe]

Summary: ✅

/// power loss erases the acknowledged snapshot (for a hardlink snapshot the directory entries
/// *are* the snapshot). Gated on `fsync_part_directory`; a no-op on remote disks; skipped
/// under an external transaction (its writes are not materialized on disk here).
if (params.fsync_part_directory && !params.external_transaction && !disk->isRemote())

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.

!disk->isRemote() turns the new durability path off for every DiskObjectStorage, but a same-disk FREEZE there still creates a brand-new local metadata tree under shadow/... via DiskObjectStorage::createHardLink / createDirectories. Those metadata transactions (MetadataStorageFromDiskTransaction::commit -> WriteFileOperation::execute) only rewrite files and directory entries; they do not sync either the files or their parent directories. So a power cut after an acknowledged FREEZE can still drop the snapshot for object-storage tables even with fsync_part_directory = 1.

If the intention is to close this bug for all supported FREEZE backends, this needs a durability step for the metadata-storage side as well. Otherwise we should reject or very explicitly surface that fsync_part_directory is unsupported for object-storage FREEZE, instead of silently no-oping here.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fd401da

CI fully finished (Finish Workflow passed). Every failure below is a pre-existing chronic
flaky, unrelated to this PR's diff (ALTER FREEZE snapshot fsync in DataPartStorageOnDiskBase::freeze

  • Backup.cpp). Each has an owner.
Check / test Reason Owner / fixing PR
Integration (amd_asan_ubsan, db disk, old analyzer, 3/6 + amd_msan 7/8) / test_replicated_database::test_replicated_table_structure_alter known flaky, tracked in #110036 #111029 (external, open)
Integration (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (32 master + 60 PRs/30d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, 2/3) / 03800_use_const_adaptive_granularity_vertical_merge_nested coverage/DBReplicated/WasmEdge shard-death flaky (unrelated to FREEZE) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
CH Inc sync private CH Inc sync CH Inc sync (private, not actionable by us)
Mergeable Check / PR rollup of the above owned via the lines above

Session id: cron:our-pr-ci-monitor:20260723-023000

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 24, 2026
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]>
ALTER TABLE ... FREEZE builds the shadow/ snapshot with createDirectories +
createHardLink and fsyncs none of it; the only sync in the FREEZE path is
shadow/increment.txt. For a hardlink snapshot the data and inodes are already
durable, but the new directory entries are not, so a power loss right after
FREEZE acknowledges leaves nothing to archive even though every fsync-family
setting was enabled on the table.

DataPartStorageOnDiskBase::freeze now, when fsync_part_directory is set (and on
a local disk, outside an external transaction), fsyncs the created part-directory
subtree bottom-up (part dir plus projection subdirs, i.e. the hardlink entries)
and every ancestor directory up to and including the disk root. The disk root is
the durability boundary: freezePartitionsByMatcher creates shadow/ without an
fsync, so only fsyncing the root persists the shadow directory entry on the first
FREEZE. This mirrors the part-clone rename() path, which already takes a
getDirectorySyncGuard when fsync_part_dir is set.

Gated on the existing fsync_part_directory MergeTree setting (default false), so
default behavior is unchanged and no SettingsChangesHistory entry is needed.

Closes: ClickHouse#111331

Co-Authored-By: Claude fable-5 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-111331-freeze-fsync branch from fd401da to 278ec05 Compare July 24, 2026 13:28
DataPartStorageOnDiskPacked::freeze() is an independent override that never
read fsync_part_directory, so the previous commit's FREEZE durability fix only
covered Full part storage. A packed part (chosen when min_bytes_for_full_part_storage
/ min_rows_for_full_part_storage / min_level_for_full_part_storage is set) was still
non-durable on FREEZE in two ways: its snapshot directory entries were unsynced, and
its rewritten data.packed archive (FREEZE copies the whole archive because
keep_metadata_version is false) was finalized but never fsynced.

Extract the Full override's directory-sync block into a shared protected helper
DataPartStorageOnDiskBase::syncFrozenPartDirectory and call it from both freeze
overrides, and fsync the rewritten data.packed by requesting a member-buffer sync
in the packed copy loop. The content sync uses the deferred need_sync flag that
PackedFilesWriter::finalize propagates, so it also covers each projection's archive
(the projection recursion runs under the part's shared transaction).

Strengthen 04621_freeze_fsync_part_directory to exercise both the Full and Packed
layouts explicitly with exact DirectorySync counts and a FileSync content oracle.

Co-Authored-By: Claude fable-5 <[email protected]>
@groeneai

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

Pre-publication review of the packed-storage extension by an independent model (engine: codex; 2 findings, both nits; bounded: 1 full pass + 1 fix round + delta rechecks).

# Sev Finding Verdict Evidence / action
1 💡 no-random-merge-tree-settings tag over-suppresses randomized coverage; the explicit min_bytes_for_full_part_storage in each CREATE TABLE already wins over the injected randomizer AGREE — fixed Removed the tag (kept no-object-storage). Re-verified 50/50 under FULL MergeTree randomization; the earlier apparent failures were all CLUSTER_DOESNT_EXIST from a local parallel_replicas config gap, 0 real assertion diffs.
2 💡 Visible Closes should use the full GitHub URL, not #111331 AGREE — fixed Changed the Description line to Closes: https://github.com/ClickHouse/ClickHouse/issues/111331.

Severity: ❌ blocker / ⚠️ major / 💡 nit. No blockers or majors were found. A final full-scope delta re-review after both fixes returned 0 findings.

Session id: cron:clickhouse-author-slot-3:20260724-133100

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up commit 718386e7 extends this FREEZE fsync fix to packed part storage (the previous commit covered only Full storage). DataPartStorageOnDiskPacked::freeze() is an independent override that never read fsync_part_directory, so a packed part (chosen when min_bytes_for_full_part_storage/min_rows_for_full_part_storage/min_level_for_full_part_storage is set) was still non-durable on FREEZE, in two ways: unsynced snapshot directory entries, and an unsynced rewritten data.packed archive (including projection archives).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Strengthened 04621_freeze_fsync_part_directory.sh exercises Full and Packed explicitly (pins min_bytes_for_full_part_storage) and asserts exact DirectorySync counts (path-depth derived) + a FileSync delta oracle. Packed lines fail 100% on the pre-fix binary.
b Root cause explained? Yes. The packed freeze() override issues no directory fsync and only finalize()s (never sync()s) the rewritten data.packed, so need_sync stays false. Projections are frozen under the parent's shared transaction, so a content-sync gate excluding external_transaction would skip them.
c Fix matches root cause? Yes. A shared syncFrozenPartDirectory helper (extracted from the Full override) fsyncs the subtree + ancestor chain; the copy loop requests a member-buffer sync so finalizeWriter fsyncs the rewritten archive. No band-aid.
d Test intent preserved / new tests added? Strengthened, not weakened: the pre-existing test used a >= 4 lower bound on the randomizer-chosen layout; it now checks BOTH layouts with EXACT dir counts and a content oracle, catching directory AND content gaps for main AND projection archives.
e Both directions demonstrated? Yes. On the pre-fix binary all 4 packed assertions fail (DirectorySync=0; FileSync delta 0 vs expected 1/2); on the fix binary all 10 lines pass. Build IDs verified for each run.
f Fix is general across code paths? Yes. The durability helper is shared by both the Full and Packed freeze overrides (this is the sibling-path coverage that motivated folding it in). Content sync covers the main archive and every projection archive. The remote path (freezeRemote) is a documented no-op (isRemote()). DETACH's packed path (a separate PR) will reuse the same helper.
g Fix generalizes across inputs? Yes. Verified for Full and Packed layouts, with and without a projection, setting on and off — all asserted with exact counts. 50/50 under full MergeTree-setting randomization.
h Backward compatible? Yes. Gated entirely on the existing fsync_part_directory MergeTree setting (default false); default behavior is unchanged. No new setting, no SettingsChangesHistory entry, no on-disk/wire/replication format change. The helper extraction is a pure refactor (Full behavior is byte-identical).
i Invariants and contracts preserved? Yes. The helper only fsyncs already-created directories after copy/hardlink; the deferred need_sync flag flows through the existing PackedFilesWriter::finalize/out_buffer_getter contract that already fsyncs on merges. The !external_transaction exclusion stays on the eager directory sync (correct) and is intentionally absent on the deferred content flag (safe — consumed only at finalize time). No lock/ownership/format invariant touched.

Session id: cron:clickhouse-author-slot-3:20260724-133100

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — fd401da

CI fully finished (Finish Workflow passed). Every failure below is a pre-existing chronic
flaky, unrelated to this PR's diff (ALTER FREEZE snapshot fsync in DataPartStorageOnDiskBase::freeze

  • Backup.cpp). Each has an owner.
Check / test Reason Owner / fixing PR
Integration (amd_asan_ubsan, db disk, old analyzer, 3/6 + amd_msan 7/8) / test_replicated_database::test_replicated_table_structure_alter known flaky, tracked in #110036 #111029 (external, open)
Integration (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (32 master + 60 PRs/30d) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
Stateless (amd_llvm_coverage, old analyzer, s3, DBReplicated, WasmEdge, 2/3) / 03800_use_const_adaptive_granularity_vertical_merge_nested coverage/DBReplicated/WasmEdge shard-death flaky (unrelated to FREEZE) a fix task is moved to pending (investigating at full effort; fixing-PR link to follow here)
CH Inc sync private CH Inc sync CH Inc sync (private, not actionable by us)
Mergeable Check / PR rollup of the above owned via the lines above

Session id: cron:our-pr-ci-monitor:20260723-023000

…-freeze-fsync

# Conflicts:
#	src/Storages/MergeTree/IDataPartStorage.h
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 78.50% 78.50% +0.00%

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

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 21e0354

CI fully finished: Finish Workflow passed (2026-07-28T23:13:08Z), all 174 check-runs completed
(155 success / 18 skipped / 1 cancelled). Every failure below has an owner.

CIDB reports zero failing tests on this commit, and the one non-green check is the known
Fast test (arm_darwin) hang, not a result from this PR's diff (ALTER FREEZE snapshot fsync in
DataPartStorageOnDiskBase::freeze plus Backup.cpp).

Check / test Reason Owner / fixing PR
Fast test (arm_darwin) / Server died (+ victim 04328_delete_from_alter_delete_privilege, Reason: Timeout!) Darwin pthread_rwlock loses wakeups under the macOS profiler signal storm, wedging the fail-point cache lock; job sat 6 h and was cancelled #112267 (external, open)
Sync private CH Inc sync (private, not actionable by us)

Evidence that this is the tracked arm_darwin family and not a new failure:

  • The job log shows the runner reaching test 6088 of 12784, then BrokenPipeError ->
    WARNING: Server died? -> Fail [Server died] at 17:32:52, after which the job produced no
    further output until the 23:12:05 cancellation (started 17:11:52, so about 6 h wedged).
  • The paired victim 04328_delete_from_alter_delete_privilege carries Reason: Timeout!, the
    two-rows-one-event shape of this family; that test has 0 Fast test (arm_darwin) failures
    of its own in 30 days, so it is a victim rather than an independently flaky test.
  • Fast test (arm_darwin) / Server died has 67 hits across 62 distinct pull requests and
    0 master hits in the last 14 days, i.e. it is arch-wide and not PR-specific.

Session id: cron:our-pr-ci-monitor:20260728-233000

…-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.
The merge with master brought in the sibling DETACH fix's projection handling,
which unconditionally clears fsync_part_directory before the nested per-
projection freeze. That is correct for the directory walk it was written for,
but the same flag also gates the fsync of a rewritten projection archive's
contents, so clearing it dropped the projection half of the FREEZE content
durability this branch adds. Test 04621 caught it deterministically:

    packed proj content: projection archive synced FAILED
        (FileSync on=2 off=1 delta=1, expected 2)

10 of 10 runs failed. Clear the flag only when nothing else already suppresses
the nested directory walk. In this freeze path the nested call always receives
external_transaction = dest_storage->transaction, and a non-null
external_transaction already excludes the nested directory walk via the
existing `!params.external_transaction` term of the fsync gate, so the subtree
is still walked exactly once from the top level while the projection archive's
contents are fsynced again.

Verified on the merged tree (build id 85e8b287): 04621 10/10 pass with the
guard, and reverting just the guard fails 3/3 with the signature above, so it
is load-bearing rather than defensive. The merged DETACH regression test 04622
also passes 10/10, so the shared path is unaffected: DETACH sets to_detached,
which skips the archive-rewriting branch entirely.
`.claude/CLAUDE.md` requires function names written as `f` rather than `f()`,
and literal names wrapped in inline code. Also drop the cross-file rationale
about which callers share the transaction: that belongs in the commit history
(the previous commit states it), not at this line. Comment only; no behaviour
change.
The setting-off arm only asserted the plain table's DirectorySync, while the
projection run's count was collected and never checked. An implementation that
gated the part directory correctly but fsynced projection subdirectories
unconditionally would have produced the complete reference output, so the
default-behaviour-unchanged contract was only half covered.

Proven live rather than assumed: with the nested projection freeze forced to
fsync regardless of the setting, the new assertion reports
"with projection = 8 (expected 0)" and the test fails, while the unmutated
binary still passes with an unchanged reference.
The content oracle only compared the setting-on and setting-off FileSync
counts. A build that fsynced the rewritten archive unconditionally and then
added the requested sync on top would produce the same deltas off a higher
base, so the default-behaviour-unchanged half of the contract was unasserted.

Assert the baseline as well. Freeze itself writes only increment.txt, so the
setting-off count is 1 for both layouts; measured stable at 1 across six
independent runs with settings randomization enabled.

Proven live: with an extra unconditional write_buf sync in the archive copy
loop the new line reports "baseline FileSync = 2 / with projection 3
(expected 1 and 1)" and the test fails, while the unmutated binary passes.
@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master. The scope of this PR shrank substantially, so a note for whoever reviews it.

The sibling DETACH PARTITION fix (#111426) merged on 2026-08-03 and carried the shared machinery this branch had introduced: the fsync_part_directory clone parameter, fsyncFrozenCloneTree, and the calls from both freeze overrides. I resolved the conflicts by dropping this branch's now-duplicated copies in favour of master's rather than keeping both, since a keep-both would have walked and fsynced the whole clone subtree twice per frozen part. Master's call site is also better placed: it runs after save_metadata_callback, so the freeze metadata that callback writes is covered by the same fsync.

What remains here is the part master does not do: freezePartitionsByMatcher populates fsync_part_directory from the table setting (master only wires up the DETACH call site, so FREEZE still acknowledged a non-durable snapshot), plus the content fsync of a rewritten data.packed archive, plus the regression test. 4 files, +161/-4.

One real defect came out of the merge rather than the conflict markers. Master's projection loop clears fsync_part_directory before the nested per-projection freeze, which is right for the directory walk it was written for, but that same flag also gates the archive content fsync, so it silently dropped the projection half of the content durability. Test 04621 caught it deterministically, 10 of 10 runs:

packed proj content: projection archive synced FAILED (FileSync on=2 off=1 delta=1, expected 2)

The flag is now cleared only when nothing else already suppresses the nested walk; a non-null external_transaction, which this path always passes, already excludes it. Reverting just that guard fails 3 of 3, so it is load-bearing rather than defensive.

I also strengthened the test's setting-off assertions, which covered only half the default-behaviour-unchanged contract: the projection run's DirectorySync and both FileSync baselines were collected but never asserted, so an implementation that fsynced projections or the archive unconditionally would have passed. Both new assertions are proven live against mutated binaries.

Validated on the merged tree: 04621 10/10 and the merged 04622 DETACH test 10/10, settings randomization enabled, one build id throughout.

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 32d3ffeb7c18aa58ea0447e814eb191d43807aff was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1cc6edd

CI fully finished on this head: 174 of 174 check-runs completed (156 success, 17 skipped,
1 failure), 0 queued or in progress, Config Workflow and Finish Workflow both green,
past the 20-minute CIDB ingestion buffer.

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: ColumnBLOB should be converted to a regular column before usage (STID 3059-311c) pre-existing trunk defect: a ColumnBLOB reaches a consumer that requires a materialized column. Failing query SELECT __table1.b AS b, __table1.a AS a FROM merge(REGEXP('^default$'), 'sk_r16') AS __table1, produced by the fuzzer and unrelated to this PR's diff #111997 (mine, merged 2026-08-04T21:56:55Z) fixes this family. It is not on this head: comparing its merge commit a6827f5554f9 against this head reports diverged, 20 commits behind, so this build predates the fix and the failure is already resolved in master

The only failure on this head is that fuzzer-found logical error, and the build was produced
before the fix for it landed, so re-running this job on a base that contains a6827f5554f9 is
expected to clear it. No functional, integration, stress, sanitizer or performance check failed.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111393&sha=1cc6edd6e395f1aa1a331b4ba7e245d077791186&name_0=PR

Session id: cron:our-pr-ci-monitor:20260805-023000

@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
…-freeze-fsync

# Conflicts:
#	src/Storages/MergeTree/DataPartStorageOnDiskPacked.cpp
#	src/Storages/MergeTree/MergeTreeData.cpp

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

Development

Successfully merging this pull request may close these issues.

ALTER TABLE ... FREEZE snapshot is never fsynced: power loss silently erases the acknowledged snapshot (only shadow/increment.txt survives)

2 participants