Skip to content

Fsync backup files and directories when writing a backup to local disk - #111394

Merged
alexey-milovidov merged 45 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111320-backup-to-file-fsync
Oct 13, 2026
Merged

alexey-milovidov merged 45 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111320-backup-to-file-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):

BACKUP ... TO File(...) / Disk(...) now fsyncs the backup data files, the .backup manifest and the containing directories before reporting BACKUP_CREATED, so an acknowledged backup to local storage survives power loss. The guarantee covers backups.allowed_path and everything the backup writes below it. On a Disk(...) over object storage that keeps its metadata in local files, those metadata files are fsynced instead, since the backup is reached only through them. Controlled by the new backup setting fsync_backup_files (default true). S3(...)/AzureBlobStorage(...) destinations are unaffected.

Description

Fixes #111320. BACKUP ... TO File()/Disk() returned BACKUP_CREATED without any fsync/fdatasync at the destination (there was no fsync anywhere in src/Backups/), so on power loss after the acknowledgement the backup could be lost entirely or left torn. S3()/AzureBlobStorage() destinations were already durable; on a Disk() over object storage the uploaded objects were, but the local metadata reaching them was not.

Reproduced 3/3 with a dm-flakey power-loss simulation (issue #111320).

Fix, gated on the new setting fsync_backup_files (default true), following the durability audit family (#68958 -> #111346, #111269 -> #111335):

  • Two writer hooks with a no-op default on IBackupWriter, overridden only by the local File/Disk writers: syncFileToDisk(file_name), called right after each data file is written in BackupImpl::writeFile (each call fsyncs its own file, so concurrent writes are safe), and syncDirectoriesToDisk(), which fdatasyncs every directory the backup created, deepest-first.
  • In BackupImpl::finalizeWriting the .backup manifest (for archives, the archive file) is synced last, so a persisted manifest never precedes its payload. Directory syncing runs for every writer, including the BACKUP ON CLUSTER internal writers, which write their own data files.

Regression test 04412_backup_to_file_fsync.sh asserts the BACKUP query's FileSync/DirectorySync ProfileEvents, present with fsync_backup_files=1 and absent with 0; integration coverage adds the Disk, archive and ON CLUSTER internal-writer cases.

Two boundaries, both in the setting's docs row.

backups.allowed_path and everything below it is synced with failures propagated. Ancestors above it are best-effort: fsyncBackupDirectory needs O_DIRECTORY, i.e. read permission, while writing a backup only needs them searchable, so under a 0311 ancestor throwing would newly fail backups that work today. Such an ancestor can still take the tree on power loss.

For BACKUP ON CLUSTER the guarantee is per host and is documented as such. copySettingsToQuery omits settings equal to their default, so an unnamed fsync_backup_files does not reach the other hosts and a host predating the setting writes its share on the old path. Naming the setting in the query now forwards it even at its default value, so an old host refuses the internal query instead of downgrading silently; forcing the unnamed default in as well would break default cross-version BACKUP ON CLUSTER, which test_backup_restore_on_cluster/test_different_versions.py covers. Turning the remaining default case into a refusal needs capability negotiation through the backup coordination version, and is left as separate work.


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

Version info

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

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. BACKUP TABLE t TO File('bk1') records FileSync=0, DirectorySync=0 on unpatched master and FileSync=12, DirectorySync=8 with the fix (exact ProfileEvents in system.query_log). Not probabilistic.
b Root cause explained? Yes. src/Backups/ issues no fsync: every local write ends at WriteBuffer::finalize() (page-cache only), native copies use fs::copy/IDisk::copyFile, and the .backup manifest goes through the same non-syncing writer. After finalizeWriting() returns BACKUP_CREATED, nothing is durable, so power loss loses/tears the backup.
c Fix matches root cause? Yes. fsync exactly the files + directories + manifest that were never synced, at the write and finalize sites, gated on fsync_backup_files.
d Test intent preserved / new tests added? New stateless test 04412_backup_to_file_fsync.sh asserts the fsyncs are issued (File/Disk, plain/archive; FileSync>=2 for plain proves per-file data sync, not just manifest) and absent when disabled, plus RESTORE validity. No existing test weakened.
e Both directions demonstrated? Yes. Unpatched: FileSync=0; with fix: FileSync=12; same repro, Build-ID-verified binary.
f General across code paths? Yes. Covers buffered (copyDataToFile) and native (copyFileFromDisk/copyFile/fs::copy) paths, data-file copies, the manifest, both File and Disk writers, and the archive path.
g Generalizes across inputs? Yes. Nested Checksum-generator directory paths, plain vs archive, local File vs local Disk vs remote (remote = no-op, already durable), disk root and its parent, trailing-separator paths (normalized).
h Backward compatible? Yes. New backup setting fsync_backup_files defaults to true (safe/durable); set 0 to restore the old no-fsync behavior. Not a core Setting, so no SettingsChangesHistory entry; no on-disk/wire format change.
i Invariants and contracts preserved? Yes. Per-file sync runs only after a real local write and only for non-archive backups; concurrency-safe (each call opens its own fd; the tracked-dir set is mutex-guarded); manifest synced after all data files (manifest-last); manifest+lock stay initiator-only while directory syncing runs for every writer incl. BACKUP ON CLUSTER internal writers; getDirectorySyncGuard null-for-remote contract respected.

Session id: cron:clickhouse-author-slot-2: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; 7 findings on the first pass +
3 on a delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck). All blockers were
either fixed or refuted with recorded evidence.

# Sev Finding Verdict Evidence / action
1 ❌ Directory syncing missed the disk root for the Disk engine (relative root_path; archive Disk has empty root) AGREE — fixed Redesigned to track the ancestor dirs of each written file down to the disk root; verified Disk plain 12/8, Disk archive 1/1
2 ❌ A directory fsync failure was only logged (LocalDirectorySyncGuard), so a backup could report success despite a failed durability op AGREE — fixed Added a throwing fsyncBackupDirectory helper; the File path propagates the error
3 ❌ Object-storage Disk (incl. local-metadata) not synced DISAGREE Out of scope: the issue is local File/Disk; object-storage Disk metadata durability is a separate subsystem, and the isRemote() no-op keeps behavior identical to pre-fix (no regression). Valid follow-up
4 ⚠️ Finalization recursively scanned the entire writer root (sibling backups; remote ListObjects) AGREE — fixed Replaced the filesystem tree-walk with the tracked-paths set; File archive DirectorySync dropped 16→2
5 ⚠️ Regression test too weak (single-component File, only >0) AGREE — fixed Added File/Disk × plain/archive cases; plain cases assert FileSync>=2 (manifest alone = 1) so removing the per-file sync fails the test; added a default-setting case
6 ⚠️ New setting undocumented AGREE — fixed Added fsync_backup_files to the backup settings docs
7 💡 Comments restated the issue rationale AGREE — fixed Condensed to the invariant; moved rationale to the commit message
8 ❌ (delta) File trailing-separator / higher-ancestor edge PARTIAL AGREE Normalized paths (lexically_normal) so a trailing separator can't break the root comparison; higher ancestors above the pre-existing allowed_path root need no sync (already durable)
9 ❌ (delta) object-storage Disk durability DISAGREE Terminal re-raise of #3; same scope evidence, no regression
10 ⚠️ (delta) test would pass with only manifest+dir sync AGREE — fixed Same fix as #5: FileSync>=2 now proves the per-file data-file sync

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @jkartseva - could you review this? It makes BACKUP ... TO File()/Disk() durable on power loss by fsyncing the data files, then the .backup manifest last, then the containing directories before returning BACKUP_CREATED, gated on a new fsync_backup_files backup setting (default true). Object-storage destinations stay no-op. Fixes #111320.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [eff0167]

Summary: ✅


AI Review

Summary

This PR adds fsync_backup_files and wires per-file plus per-directory syncing for local backup destinations, including local metadata files for DiskObjectStorage with metadata_type = local, while also fixing the late-failure/publication ordering around published backups. I still see one remaining blocker: on local_blob_storage, the new default-on setting still returns BACKUP_CREATED even though the blob files themselves are never synced, so the advertised power-loss durability guarantee is still false for that supported Disk(...) backend.

Findings

❌ Blockers

  • [src/Backups/BackupIO_Disk.cpp:125] [dismissed by author -- https://github.com/Fsync backup files and directories when writing a backup to local disk #111394#discussion_r3632876667] ObjectStorageType::Local only emits a warning and then continues down the success path. For local_blob_storage, syncFileToDisk reaches at most the metadata side; the blob files themselves are still ordinary local writes with no fsync, so BACKUP ... TO Disk(...) SETTINGS fsync_backup_files = 1 can acknowledge a backup that is not power-loss durable. A default-on durability setting should reject unsupported backends instead of silently weakening its contract.
    Suggested fix: when fsync_backup_files is enabled and the destination disk is local_blob_storage (including wrapped variants), fail the backup with a user-facing exception unless the implementation is extended to sync the local blobs themselves.
Final Verdict

❌ Request changes — the remaining local_blob_storage path still violates the new durability contract.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
Comment thread src/Backups/BackupIO_File.cpp Resolved
Comment thread src/Backups/BackupIO_Disk.cpp Resolved
BACKUP ... TO File()/Disk() returned BACKUP_CREATED without fsyncing anything at
the destination: not the data files, not the .backup manifest, and not the
containing directories. On power loss after the acknowledgement the backup could
be lost entirely or left torn, even though an operator relies on BACKUP_CREATED
before dropping the source data.

Add a fsync_backup_files backup setting (default true) and, for the local File and
Disk writers, fsync each written data file, then the .backup manifest last, then
every directory that received a synced file (deepest-first, up to and including the
backup/disk root). The manifest is synced after all data files so a persisted
manifest never precedes its payload. The directory fsync throws on failure so a
backup cannot report success while its durability guarantee silently failed.
Object-storage destinations (S3/Azure) are unaffected: a completed upload is
already durable, so the writer hooks are no-ops there. Directory syncing also runs
for the internal writers of BACKUP ON CLUSTER, which write their own files.

Closes: ClickHouse#111320

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-111320-backup-to-file-fsync branch from ec6f50e to 3298150 Compare July 22, 2026 19:47
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Jul 22, 2026
@jkartseva jkartseva self-assigned this Jul 23, 2026
Comment thread src/Backups/BackupImpl.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3298150

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
Stress test (arm_release) / Cannot start clickhouse-server not PR-caused. The stress restart aborted metadata loading: Code: 246 ... Part all_5_6_1_0 intersects previous part all_1_5_4_1 and the transaction metadata of at least one of them could not be read, on table test_3.t_plt_evict_reinsert. That table name exists in exactly one place in the tree, the stateless test 04417_part_loading_tree_rollback_evict_reinsert_contains.sh, which fabricates a part directory and writes a raw plaintext txn_version.txt into it. The corrupted part survives into the stress restart and kills server startup. Nothing to do with this PR's diff (src/Backups/ fsync + one new stateless test). #112000 (ours, open) - it deletes that test and converts the whole part_loading_tree_rollback family to an integration test
Stress test (arm_release) / Check failed same job, aggregate roll-up of the line above (Failures: 2/3); Test script exit code is OK #112000 (ours, open)

All other checks pass on this commit. This PR's own new test 04412_backup_to_file_fsync is green everywhere it ran, including 50/50 in every flaky check and both Bugfix validation legs.

Session id: cron:our-pr-ci-monitor:20260727-083000

groeneai and others added 4 commits July 27, 2026 11:03
…eated ancestor directories

Three fixes to the backup fsync path, from review of ClickHouse#111394.

`finalizeWriting` removed the `.lock` file before `syncDirectoriesToDisk`, so a
directory fsync failure left a corrupted backup that could no longer be cleaned
up: `setIsCorrupted` leaves `writing_finalized` false, and `tryRemoveAllFiles`
returns immediately when `checkLockFile` cannot prove ownership of the
destination. The leftover tree kept `.backup`, so every retry failed with
`BACKUP_ALREADY_EXISTS` while looking like a finalized backup. Sync the
directories first and remove the lock last. Verified by injecting a directory
fsync failure: with the old order the tree survived and the retry was refused,
with the new order the cleanup removed it and the retry succeeded.

`BackupWriterFile` stopped the ancestor walk at the backup root, so for a nested
destination such as `File('a/b/c')` the intermediate directory `a`, created by
the same `create_directories` call, was never fsynced and its entry was not
durable when `BACKUP_CREATED` was returned. Walk up to the deepest ancestor that
already existed when the writer was constructed instead, which also subsumes the
previous special case for the root's parent. `DirectorySync` for one nested level
goes from 8 to 9 and for two levels to 10, while a flat destination is unchanged.

`BackupWriterDisk` decided whether to fsync from `IDisk::isRemote`, which is not
the property the code needs: `DiskObjectStorage` reports `isRemote() == true`
even over `LocalObjectStorage`, and `DiskBackup` reports false yet throws from
`getBlobPath`. Ask instead whether the destination stores the backup as plain
local files. A backup to a local object-storage disk keeps its previous
behaviour and now logs a warning rather than silently ignoring
`fsync_backup_files`, since there the backup is reached through the disk's
metadata and its durability belongs to the metadata storage.

Related: ClickHouse#111320

Co-Authored-By: Claude Opus 5 <[email protected]>
… make the fsync test exact

Two review findings on the fsync work.

The parent walk in `BackupWriterFile::syncFileToDisk` stopped at the deepest ancestor that
already existed when the writer was constructed. Existence does not imply durability: with
concurrent backups enabled by default, a second backup sharing an intermediate directory treats
it as the boundary and never fsyncs the directory holding it, so it can report BACKUP_CREATED
before the backup that created that directory has made its entry durable, and a power loss then
takes both away.

Walking to the filesystem root instead is not an option, because fsyncing a directory has to open
it with O_DIRECTORY, which needs read permission, while writing a backup only needs the ancestors
to be searchable. Measured on a directory at mode 0311: open fails with EACCES, so the walk would
turn a working BACKUP into a hard failure whenever any ancestor above the backup area is
search-only. `checkPath` already resolves which `backups.allowed_path` entry the destination lives
under, so it now returns that directory and the writer takes it as an explicit boundary. Every
directory a backup creates is below it and every backup in that area fsyncs it, which covers a
directory created by a concurrent backup, and the walk never leaves the configured area. For a
flat destination the set of synced directories is unchanged.

The regression test asserted `FileSync >= 2`, which also passes when only the manifest and one
arbitrary data file were synced, while the contract covers every data file. It now asserts the
exact count. The count is `num_entries + 1`, not `num_files + 1`: `num_files` also counts the
entries skipped as empty, as already present in the base backup, or as being written by another
host, and a file that is never written is never synced. How many entries get skipped depends on
the randomized merge-tree settings, so the difference is not a constant. Added a case for two
backups sharing an intermediate directory.

Verified with three mutations on the fixed build, each failing exactly the assertion that covers
it: syncing only the first data file fails the exact-count assertion in all three plain cases and
would have passed the old bound; stopping the walk at the backup root fails the nested-destination
assertion; inferring the boundary from existence fails the shared-ancestor assertion. Restoring
the sources rebuilt to the same build id, and the test passes 50/50 under randomized settings.

Co-Authored-By: Claude Opus 5 <[email protected]>
…absolute directory count

Nothing creates `backups.allowed_path`, so a `File` backup can create it together with some of its
ancestors and then acknowledge success while those directory entries are still volatile. With the
allowed path set to a non-existent `bndroot/x/y/z` the backup creates all four directories and only
the innermost one was fsynced, so a power loss could take the whole acknowledged backup away. The
writer now records that chain in its constructor, from the allowed path up to the deepest ancestor
that already exists, sampled before anything is written. The same measurement then reports four
directory fsyncs instead of one.

That also removes the explicit boundary test from the parent walk. The allowed path is now already
in the recorded set and `checkPath` guarantees every backup file is below it, so the walk always
meets an already recorded directory there and stops on the duplicate check. Disabling the explicit
test changed no observable behaviour, which is what showed it was dead, so it is gone and the member
it needed became a constructor local.

The directory assertions in the regression test were all relative: greater than zero, a difference
of two between a nested and a flat destination, and equality between two backups sharing an
ancestor. Omitting the same directory from every case preserved all of them, so dropping the new
constructor step passed the test. An archive is a single file written directly into the backup area,
which makes that area the only directory whose entry changes, so `DirectorySync` must be exactly
one. That assertion fails at zero if the backup area is not synced and above one if the walk runs
past it towards the filesystem root, and it fails as expected once the constructor step is dropped.
The plain destinations keep a "greater than zero" assertion because their exact directory count
follows the part layout, which the randomized merge-tree settings change from run to run.

Reviewed alongside a report that a `BACKUP ON CLUSTER` initiator could report `fsync_backup_files`
while an older host silently skips it, because only non-default settings are dispatched. Measured
that an old host does not skip it: an unrecognized backup setting becomes a core setting and is
applied to the context, which fails with `UNKNOWN_SETTING`, so a propagated request already fails
closed. Reporting the guarantee as unavailable during a rolling upgrade needs a coordination version
bump and is left out of this change.

Mutation-verified: syncing only the first data file fails the exact file count in all three plain
cases, stopping the walk at the backup root fails the nested-destination assertion, inferring the
boundary from existence fails it too, and dropping the constructor step fails the archive anchor.
Restoring the sources rebuilt to the same build id, and the test passes 50/50 under randomized
settings.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ectory oracles exact per engine

The previous step recorded the directories the backup creates up to the deepest one that already
exists, but syncing a directory does not persist its own entry, so the topmost link of that chain
stayed volatile. It also treated existence as proof of durability: if a concurrent backup created the
backup area and has not yet fsynced its parent, a second backup observed the area as existing,
recorded nothing above it, and could acknowledge a backup whose area can still disappear.

The writer now also fsyncs the directory holding the backup area, last. That directory is outside
what `backups.allowed_path` asked ClickHouse to write in, so a failure there is logged instead of
failing the backup: fsyncing a directory has to open it with `O_DIRECTORY`, which needs read
permission, while writing a backup only needs its ancestors to be searchable. Verified with the
backup area inside a search-only directory, where the backup completes and logs the warning; without
the tolerance that configuration would newly fail every backup.

The archive directory assertions in the test are now exact per engine, so they anchor the boundary
from both sides. A `File` archive must fsync exactly two directories, the backup area and the
directory holding it; a `Disk` archive exactly one, the disk root, which has no configured parent to
walk into. Dropping the new step fails the `File` assertion. The plain destinations keep a "greater
than zero" assertion, because their exact count follows the part layout that the randomized
merge-tree settings change, and the nested and shared cases pin those counts relative to each other.

Two reports were reviewed and left out on purpose. A newly created local disk root is not made
durable by `DiskLocal::setup`, but that directory is created by the disk for every one of its users
and is equally volatile for a `MergeTree` part, so making it durable belongs to the disk rather than
to a backup. And `BACKUP ON CLUSTER` cannot tell an older host to fsync, because only non-default
settings are dispatched; propagating the setting regardless does not silently skip the sync, it fails
the query with `UNKNOWN_SETTING`, and reporting the guarantee as unavailable during a rolling upgrade
needs a coordination version bump. Both are follow-ups.

Restoring the sources rebuilt to the same build id, and the test passes 50/50 under randomized
settings.

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

Copy link
Copy Markdown
Collaborator Author

Internal review rounds — pushed 7eb7eadb337dd5 (was 3298150778c010)

Three commits, all measured on Build-ID-verified builds. The three inline change requests are answered in their own threads; this is the summary of what my own second-model review found on top of them, and what I declined.

Commit What changed
b2b4987aca8cd1 Keep the .lock until the directory fsyncs succeed; fsync created ancestor directories
dec1ca94ccd9c4 Bound the durability walk at the configured backups.allowed_path; fix the test oracle
f7151d8e34211a Make the backup area itself durable; anchor the directory assertion absolutely
7eb7eadb337dd5 Persist the backup area's own entry; per-engine exact archive anchors

Fixed

  • Existence is not durability. An earlier revision inferred the durability boundary from what it observed to exist, so a second concurrent backup sharing an intermediate directory never fsynced the directory holding it. checkPath now returns the backups.allowed_path entry it resolved against, and the writer uses it as an explicit boundary, recording one level beyond it.
  • The backup area itself. Nothing creates backups.allowed_path at startup, so the backup creates it and its ancestors. Measured with the allowed path pointing at a non-existent bndroot/x/y/z: 1 directory fsynced before, 4 after, 5 once the containing level was added.
  • A dead check found by mutation. Once the constructor pre-seeded the boundary, the in-walk boundary check became unreachable — disabling it changed nothing. It and its member were removed, so this revision is smaller than the previous one.
  • The test oracle was wrong. FileSync = system.backups.num_files + 1 reads 0 on the plain cases: num_files also counts entries skipped as empty, already present in the base backup, or written by another host. num_entries + 1 is the right oracle (the +1 being the .backup manifest); measured 17=16+1 randomized and 13=12+1 isolated.
  • Every directory assertion was relative, so dropping the constructor seeding still passed. An archive writes a single file into the backup area, so that area's entry count is exact and two-sided — File archive = 2, Disk archive = 1 (a disk root has no configured parent to walk into).

Declined, with the measurement rather than silence

  • Walk to the filesystem root. fsyncBackupDirectory opens with O_DIRECTORY, which needs read permission, while writing a backup only needs its ancestors searchable. Measured: a 0311 ancestor gives errno=13, and a 0711 home directory is the everyday case — so this remedy would refuse every backup whose area sits under a search-only ancestor, which is a larger blast radius than the race it closes. The one level above the configured area is therefore fsynced best-effort (logged, never thrown); measured with the area inside a 0311 parent, the backup still returns BACKUP_CREATED and logs a warning.
  • Force-propagate fsync_backup_files to on-cluster hosts. The premise that an old host silently skips an unknown backup setting does not hold: an unrecognized backup setting becomes a core setting (BackupSettings.cpp:79-80), is applied via InterpreterSetQuery.cpp:243-246, and throws — measured Code: 115 ... (UNKNOWN_SETTING). Propagation already fails closed, and omitting defaults is exactly what keeps cross-version BACKUP ON CLUSTER working (test_different_versions.py). Reporting the guarantee as unavailable during a rolling upgrade needs a coordination-version bump, which is a separate change to the on-cluster protocol.
  • Physical parent of a Disk root. The facts are right (DiskLocal.cpp:762 is a bare fs::create_directories), but that directory is created by the disk at server start for every user of it, and is equally non-durable for a MergeTree part on the same disk. That is a DiskLocal property, not a backup one — filed as a follow-up.

Mutation matrix — each on a Build-ID-verified build, every restore bit-identical, test 50/50 green under randomized settings:

Mutation Result
sync only the first data file FAIL on exactly the 3 plain cases (a >= 2 bound could not see this)
stop the walk at the backup root FAIL
infer the boundary from existence FAIL
disable the in-walk boundary check PASS → proved dead, removed
drop the constructor seeding FAIL on the absolute anchor
drop the best-effort parent sync FAIL on the archive anchor

Still open, stated rather than claimed as done: an after-fix dm-flakey power-cut result for File and local Disk. The pre-fix side is in the issue's reproducer (BACKUP_CREATED, power cut, RESTORE → BACKUP_NOT_FOUND, empty directory), and the injected-sync-failure half is closed by the lock-ordering fix above. The ProfileEvents oracle proves the syscalls happen for every written file and directory, which is the part a stateless test can hold; the device-mapper run and the BACKUP ON CLUSTER internal-writer case belong in tests/integration/test_backup_restore_on_cluster and are filed as follow-ups.

Resolved src/Backups/registerBackupEnginesFileAndDisk.cpp.

Master (ClickHouse#111909) extracted the File/Disk argument parsing out of the creator
lambda into resolveLocalBackupLocation() so that the same resolution can also
produce a destination identity for the backup-engine registry. This branch had
made checkPath() return the 'backups.allowed_path' entry the destination
resolved against, and threaded it into BackupWriterFile as the boundary for the
directory fsyncs.

Both changes are kept: the allowed_path is now carried in master's
ResolvedLocalBackupLocation struct, so it is computed once in
resolveLocalBackupLocation() and handed to BackupWriterFile from there. The
identity function reuses the same resolution and is unaffected, because it only
reads disk_name/path/archive_name.
Comment thread src/Backups/BackupImpl.cpp Resolved
Comment thread src/Backups/BackupIO_Disk.cpp Resolved

@tiandiwonder tiandiwonder left a comment

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.

please fix the blocker.

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 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.40% 78.40% +0.00%

Changed lines: Changed C/C++ lines covered: 139/160 (86.88%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7b2a642

CI fully finished on this head (no check queued or in progress, the praktika aggregator
completed, and the CIDB ingestion buffer has elapsed). Zero failing checks on this head,
so there is nothing to own.

Session id: cron:our-pr-ci-monitor:20260729-093000

groeneai added 4 commits July 29, 2026 11:33
Two behaviours of the backup fsync work were unpinned because a stateless test
structurally cannot express them, and a regression in either would leave every
existing test green.

An internal (non-initiator) host of BACKUP ON CLUSTER fsyncs its own data files
and the directories it created: writeFile's fsync block and finalizeWriting's
syncDirectoriesToDisk call are both ungated. A stateless run is one node, so
BackupSettings::internal is never true there, and it cannot be set by hand
either - BackupsWorker throws ACCESS_DENIED unless the context is DDL or
on-cluster-internal. The new case asserts the follower's own FileSync count
from its internal operation's query_thread_log rows, plus a node-local
system.events DirectorySync delta, each against an exact-zero control.

The directory half has to be a process-level delta rather than an exact
per-query count: an internal backup is forced async, and its starter thread's
query_thread_log row is dropped when the weak ThreadGroup::query_context
expires with the BackupStarter. Both limitations are stated in the test.

The BackupWriterFile constructor walks the configured backup area up to the
deepest existing ancestor and syncs the whole created chain plus one level
beyond, but backups.allowed_path is a server config key a stateless test cannot
vary, and in CI it always exists, so that branch is dead code there. The new
case configures a second allowed_path entry whose ancestors do not exist and
asserts the directory-fsync difference between two backups to the same area,
which cancels the destination's own directories and so is independent of the
randomized merge-tree settings.

Each asserted half was proven load-bearing by a separate mutation of the
production code - gating the writeFile fsyncs, gating the syncDirectoriesToDisk
call, and collapsing the constructor walk - and each reddened only its own
assertion.

The concurrent variant of the second case, two backups racing to create a
shared intermediate directory, is deliberately not covered: it needs a
pauseable failpoint between the writer constructor's boundary sampling and its
first create_directories, which does not exist. The sequential pair must not be
read as covering it, because a sequential pair passes even under the old
boundary logic; the test says so.
A plain backup (deduplicate_files = 0) writes a reference entry as a copy of
its target's data file, and writeFile fsyncs those copies alongside the target.
Nothing asserted it: info.data_file_copies is filled only for a plain backup,
deduplicate_files defaults to true, and no test that touches the backup fsyncs
sets it, so deleting the copy loop left every test green while the manifest
could still reference an unsynced copy.

test_backup_restore_keeper_map::test_on_cluster already builds exactly the
required shape - two KeeperMap tables sharing one zk root, so one of them is
collected as a BackupEntryReference, backed up ON CLUSTER to a plain local disk,
parametrized over both values of deduplicate_files - so it is extended rather
than duplicated, and its deduplicate_files = 1 arm is the control.

The count is summed over the cluster instead of read from the initiator's own
operation. Each host fsyncs the data files it wrote itself, the initiator's own
operation writes only the .backup manifest, and coordination decides per run
which host owns a shared zk root, so no single host has a stable count: measured
per-node splits for one backup were 14/4/4 and 5/4/13 with the total invariant
at 22. Summed, the relation is exact - one fsync per entry actually written plus
the manifest - and it is an equality, so an unrelated fsync in the window fails
the test rather than hiding a missing one.

Separately, the follower's system.backup_log row is written by
setStatus(BACKUP_CREATED), which runs after backup_coordination->finish(). The
initiator waits only for the follower's finish node, so that row is not ordered
before BACKUP returns and reading it once could race. The read is now retried on
the same budget as the query_thread_log read beside it, and the comment that
claimed the wait covered the follower entirely now says what it does cover: the
writing and syncing, which is what licenses reading the DirectorySync delta
immediately.

Both halves were proven load-bearing. Deleting only the copy-sync loop, with a
verified moved build id, makes test_on_cluster[0] fail with 15 fsyncs against 22
expected while test_on_cluster[1] still passes. The retry is inert on the happy
path: the row was present on the first attempt and the counts are unchanged.
The ON CLUSTER FileSync assertion read a delta of process-wide system.events
counters summed over three nodes. Unlike DirectorySync, whose only non-backup
producer is gated on fsync_part_directory / fsync_directories (both default
false and unset in these suites), FileSync has an ambient producer that is on
by default: fsync_metadata defaults to true, so a CREATE TABLE fsyncs its
metadata file. System log tables are created lazily on their first flush, and
the measured BACKUP is itself the first producer for several of those queues,
so such a CREATE can land anywhere inside the sampling window and push the sum
above num_entries + 1. Measured on a cold module, which is the CI condition:
three log tables were created in the window and the process-wide delta read 24
against the 22 the relation predicts.

Read each host's count from the threads of its own backup operations instead,
via system.query_thread_log scoped by query id. That keeps the assertion an
exact equality rather than widening it, and makes it insensitive to any fsync
belonging to another query. The per-file syncs happen in writeFile on
BackupWorker pool threads and the manifest sync in finalizeWriting on the
BackupAsync thread, so all of the work is attributable. The query ids of the
internal operations come from each node's own system.backup_log, because
system.backups hides them. Summing over hosts is still required: which host
owns a shared Keeper root is decided by coordination, so no single host has a
stable count.

The module needs query_thread_log put back, because the common integration
config removes it.

Also open the two backup fsync descriptors with O_CLOEXEC, so a process
spawned concurrently by ShellCommand cannot inherit a descriptor to a backup
file or directory and keep it alive after the server closes or unlinks it. The
ordinary file buffers already set the flag unconditionally.
The on-cluster fsync assertion summed one FileSync figure over
system.query_thread_log for every operation of a node. Three independent
things could make that sum read short and redden an unrelated PR.

The manifest fsync runs in finalizeWriting on the BackupAsync thread. That
thread's query_thread_log row is written when its ThreadGroupSwitcher is
destroyed, which happens only after the callback that owns the last strong
reference to the query context has been released, and finalizePerformanceCounters
needs that context to still be alive to write the row at all. A synchronous
BACKUP returns before either happens, woken from inside the still-running
callback, so that row can be late or absent outright. Waiting longer for it is
therefore not a remedy.

The wait that was supposed to order the read accepted any row from either
backup thread name, and the BackupWorker rows land much earlier, so the
data-file rows alone satisfied it.

And the node the query was issued on runs two operations sharing one
destination name, distinguished only by the -internal- suffix on the operation
id. Accepting the first backup_log row found silently dropped the other
operation's fsyncs.

Read the manifest term from system.backups.ProfileEvents instead. That value is
ordered by construction (setStatus fills it and only then notifies the waiter,
both under one lock) and is a thread-group-wide snapshot, so the BackupAsync
thread's increment is included through the counter parent chain even when its
own row is never written, while staying scoped to the single operation. Keep the
data-file term in query_thread_log, but pin the expected operation count per
node and wait per query id rather than over their union.

Also make the destination unique per call with a uuid instead of a module
counter, and match it with position() instead of LIKE: the counter made one
run's name a prefix of a later one's, and _ is itself a LIKE wildcard.

The exact equality, the KeeperMap reference carrier and the deduplicate_files
control arm are unchanged.
alexey-milovidov and others added 3 commits October 6, 2026 07:39
…-backup-to-file-fsync

# Conflicts:
#	src/Backups/BackupSettings.cpp
#	tests/integration/test_backup_restore_keeper_map/test.py
… docs

`test_fsync_different_versions` followed `CLICKHOUSE_CI_MIN_TESTED_VERSION`, so once that floor
moves past the release that introduced `fsync_backup_files` the old host would accept the setting
and the refusal path would not be tested anymore. Pin it to a release known to predate it.

The documentation said naming the setting explicitly makes an old host "refuse the backup". It only
makes that host reject its internal query; the initiator is not told and keeps waiting for it.
Say so and point to `async = 1` with `KILL QUERY`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…p destination

The `disk_s3` / `disk_s3_encrypted` arms only asserted `FileSync >= 2` / `DirectorySync >= 1`,
which a bug syncing just the manifest plus one metadata file would pass. Assert
`FileSync == num_entries + 1` for directory destinations, as `04412_backup_to_file_fsync` does
for plain local ones, and add a `.tar` archive arm with exactly one file and one directory sync.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (conflicts in BackupSettings.cpp with the new data_file_name_prefix_length forwarding, kept both, and the imports of test_backup_restore_keeper_map) and addressed the open review threads.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=111394&sha=43eb98c7ad410f093aac347f8166df1e4d1ce17e&name_0=PR&name_1=Upgrade%20check%20%28amd_release%29 (UNEXPECTED_PACKET_FROM_CLIENT: Unexpected packet Hello received from client in the upgrade check, unrelated to backups) and provide a fix in a separate PR. If the fix is already in progress, link it here.

Comment thread src/Backups/BackupSettings.cpp Resolved
@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

The fix is already in progress in #119368 (still open), so no separate PR from me; the CI finish ledger for this head links it too. Same mechanism as on #109052: in this run 2 of the 9 replayed test_1.dist_in sends hit the injected memory fault inside NativeReader::readData (SerializationNumber<int>::deserializeBinaryBulk, mid-Data packet), and those are exactly the 2 Code 101 lines in the server log; the other 7 failed after the read and kept the connection.

…USTER`

`fsync_backup_files = DEFAULT` names the setting in the SETTINGS clause, but
`resolveDefaultedSettings` drops the reset before `fromBackupQuery` reads the
changes, so `fsync_backup_files_specified` stayed false. `copySettingsToQuery`
then omitted the setting for being at its default, and a host that predates
`fsync_backup_files` wrote its share of the backup without fsync instead of
rejecting the internal query, as it does for `fsync_backup_files = 1`.

A reset of this setting now counts as naming it. It is still sent as the
plain value `fsync_backup_files = true`, never as `= DEFAULT`, which older
parsers reject after a comma.

The new unit test fails without the change on both reset spellings and keeps
an unnamed setting as the control.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 9a0f1924-3e23-483e-b933-2684c100aeef
  • MIRAI run: 40acb0db-a349-4a1e-8c11-1a723f755a9c
  • PR check IDs:
    • clickbench_1131642_1791843431
    • clickbench_1131655_1791843431
    • clickbench_1131661_1791843431
    • tpch_adapted_1_official_1131668_1791843431
    • tpch_adapted_1_official_1131679_1791843431
    • tpch_adapted_1_official_1131713_1791843431

@alexey-milovidov alexey-milovidov self-assigned this Oct 12, 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.

I found this good.

@groeneai, resolve conflicts.

…-backup-to-file-fsync

Conflicts, all in failpoint declaration lists and includes, resolved by keeping both sides:
- src/Common/FailPoint.cpp, src/Backups/BackupImpl.cpp: master's new
  `backup_fail_lock_file_write_after_{commit,open}` next to this PR's `backup_fail_reading_archive_size`.
- src/Backups/BackupIO_File.cpp: master's `<fcntl.h>` (for the new `O_EXCL` `writeFileIfNotExists`)
  next to this PR's `<Common/Exception.h>`.

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

Copy link
Copy Markdown
Collaborator Author

Merged master @ 0be730d. The conflicts were only in the failpoint declaration lists (src/Common/FailPoint.cpp, src/Backups/BackupImpl.cpp, next to the new backup_fail_lock_file_write_after_*) and one include in src/Backups/BackupIO_File.cpp (<fcntl.h> for the new O_EXCL writeFileIfNotExists); both sides kept, the PR diff against master is unchanged. On the merged build 04412_backup_to_file_fsync (whose exact FileSync oracle now also covers the new O_EXCL lock-file path), 04909_backup_keeps_published_backup_on_late_error, the BackupSettings unit tests and the PR's integration arms pass.

Comment thread src/Backups/BackupImpl.cpp Resolved
…lain backup

The per-file durability fsyncs added a failure point after the copies of a
data file are materialized, but `tryRemoveAllFiles` only removed
`data_file_name`, so the copies were left behind in the destination.
All writers remove files best-effort, so missing copies are harmless.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e fsync boundary

`checkPath` returned the first `backups.allowed_path` entry containing the
destination, so with overlapping entries (e.g. `/srv` before `/srv/backups`)
the durability boundary, and thus whether the backup hard-fails on an
unreadable ancestor, depended on the order of entries in the config. Return
the deepest matching entry instead; the first entry is still used to resolve
relative destinations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @tiandiwonder, your change request from 2026-09-21 is the only remaining blocker. Its finding (the encryption sidecar was never fsynced) was fixed in 43eb98c. The sidecar is now fsynced before the manifest, on the initiator only. Since then, the later bot findings were also fixed: fsync_backup_files = DEFAULT in e2d4623, cleanup of data_file_copies in 3eee3d0, and the deepest backups.allowed_path boundary in eff0167. CI is green on eff0167d348. Could you re-review or dismiss the change request?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into ClickHouse:master with commit 8e66cc6 Oct 13, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 13, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @tiandiwonder @alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The ClickGap finding is correct; I opened #125911 for it. It also rejects a relative File() path whose .. leaves every backups.allowed_path entry when a later entry contains the first one, which 26.9 accepts.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 15, 2026
…r .. components

checkPath joined a relative File() destination with the raw first
backups.allowed_path entry, while ClickHouse#111394 started comparing it with the
lexically normalized entries. When the first entry was not in normal form
(`/w/./backups`, `/w/sub/../backups`, or a relative `../backups` resolved
against the data path), lexically_proximate returned a path starting with
`..` and every entry was rejected with BAD_ARGUMENTS. Absolute paths were
not affected because they are normalized before the check.

Normalize the joined path as well, so a relative destination resolves
exactly like its absolute spelling: a `..` that comes back into an allowed
entry is accepted, one that ends outside every entry is still rejected.

Closes ClickHouse#125871

Co-Authored-By: Claude Opus 5.5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Oct 15, 2026
clickhouse-local keeps a relative --path as given, so a relative
backups.allowed_path entry resolved to a relative backup area (for
example `--path ./data` with `../backups`, or `--path .` with
`backups`). The directory fsync added by ClickHouse#111394 assumes an absolute
area: for a relative one that does not exist yet, the boundary walk in
the BackupWriterFile constructor climbs to the empty path, and BACKUP
fails with `Cannot open directory  for fsync` after writing the whole
backup. 26.9 accepted these spellings.

Make the data path absolute before checkPath joins it. fs::absolute is
lexical, like the rest of checkPath, and is the identity for the server,
whose path is already absolute. The test gets the relative --path arm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-backup Backup/restore infrastructure and backup formats. groeneai-origin-unknown PR origin: unclassified (legacy task) manual approve Manual approve required to run CI 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.

BACKUP to File/Disk never fsyncs the destination: an acknowledged backup can be lost entirely on power loss

6 participants