Repository navigation
Fsync backup files and directories when writing a backup to local disk - #111394
alexey-milovidov merged 45 commits into
Conversation
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-2:20260722-105200 |
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 7 findings on the first pass +
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-2:20260722-105200 |
|
cc @vitlibar @jkartseva - could you review this? It makes |
|
Workflow [PR], commit [eff0167] Summary: ✅
AI ReviewSummaryThis PR adds Findings❌ Blockers
Final Verdict❌ Request changes — the remaining |
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]>
ec6f50e to
3298150
Compare
CI finish ledger - 3298150Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
All other checks pass on this commit. This PR's own new test Session id: cron:our-pr-ci-monitor:20260727-083000 |
…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]>
Internal review rounds — pushed
|
| 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.
checkPathnow returns thebackups.allowed_pathentry 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_pathat startup, so the backup creates it and its ancestors. Measured with the allowed path pointing at a non-existentbndroot/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 + 1reads 0 on the plain cases:num_filesalso counts entries skipped as empty, already present in the base backup, or written by another host.num_entries + 1is the right oracle (the+1being the.backupmanifest); 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 —
Filearchive = 2,Diskarchive = 1 (a disk root has no configured parent to walk into).
Declined, with the measurement rather than silence
- Walk to the filesystem root.
fsyncBackupDirectoryopens withO_DIRECTORY, which needs read permission, while writing a backup only needs its ancestors searchable. Measured: a0311ancestor giveserrno=13, and a0711home 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 a0311parent, the backup still returnsBACKUP_CREATEDand logs a warning. - Force-propagate
fsync_backup_filesto 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 viaInterpreterSetQuery.cpp:243-246, and throws — measuredCode: 115 ... (UNKNOWN_SETTING). Propagation already fails closed, and omitting defaults is exactly what keeps cross-versionBACKUP ON CLUSTERworking (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
Diskroot. The facts are right (DiskLocal.cpp:762is a barefs::create_directories), but that directory is created by the disk at server start for every user of it, and is equally non-durable for aMergeTreepart on the same disk. That is aDiskLocalproperty, 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.
tiandiwonder
left a comment
There was a problem hiding this comment.
please fix the blocker.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 139/160 (86.88%) · Uncovered code |
CI finish ledger - 7b2a642CI fully finished on this head (no check queued or in progress, the praktika aggregator Session id: cron:our-pr-ci-monitor:20260729-093000 |
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.
…-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]>
|
🕵 Merged master (conflicts in @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 ( |
|
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 |
…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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
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]>
|
Merged master @ 0be730d. The conflicts were only in the failpoint declaration lists ( |
…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]>
|
🕵 @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: |
|
@groeneai @tiandiwonder @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
|
The ClickGap finding is correct; I opened #125911 for it. It also rejects a relative |
…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]>
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]>
Changelog category (leave one):
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.backupmanifest and the containing directories before reportingBACKUP_CREATED, so an acknowledged backup to local storage survives power loss. The guarantee coversbackups.allowed_pathand everything the backup writes below it. On aDisk(...)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 settingfsync_backup_files(defaulttrue).S3(...)/AzureBlobStorage(...)destinations are unaffected.Description
Fixes #111320.
BACKUP ... TO File()/Disk()returnedBACKUP_CREATEDwithout anyfsync/fdatasyncat the destination (there was nofsyncanywhere insrc/Backups/), so on power loss after the acknowledgement the backup could be lost entirely or left torn.S3()/AzureBlobStorage()destinations were already durable; on aDisk()over object storage the uploaded objects were, but the local metadata reaching them was not.Reproduced 3/3 with a
dm-flakeypower-loss simulation (issue #111320).Fix, gated on the new setting
fsync_backup_files(defaulttrue), following the durability audit family (#68958 -> #111346, #111269 -> #111335):IBackupWriter, overridden only by the localFile/Diskwriters:syncFileToDisk(file_name), called right after each data file is written inBackupImpl::writeFile(each call fsyncs its own file, so concurrent writes are safe), andsyncDirectoriesToDisk(), which fdatasyncs every directory the backup created, deepest-first.BackupImpl::finalizeWritingthe.backupmanifest (for archives, the archive file) is synced last, so a persisted manifest never precedes its payload. Directory syncing runs for every writer, including theBACKUP ON CLUSTERinternal writers, which write their own data files.Regression test
04412_backup_to_file_fsync.shasserts theBACKUPquery'sFileSync/DirectorySyncProfileEvents, present withfsync_backup_files=1and absent with0; integration coverage adds theDisk, archive andON CLUSTERinternal-writer cases.Two boundaries, both in the setting's docs row.
backups.allowed_pathand everything below it is synced with failures propagated. Ancestors above it are best-effort:fsyncBackupDirectoryneedsO_DIRECTORY, i.e. read permission, while writing a backup only needs them searchable, so under a0311ancestor throwing would newly fail backups that work today. Such an ancestor can still take the tree on power loss.For
BACKUP ON CLUSTERthe guarantee is per host and is documented as such.copySettingsToQueryomits settings equal to their default, so an unnamedfsync_backup_filesdoes 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-versionBACKUP ON CLUSTER, whichtest_backup_restore_on_cluster/test_different_versions.pycovers. 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
26.10.1.2312-master(included in26.10and later)