Repository navigation
Conversation
…r loss InterpreterCreateQuery::convertMergeTreeTableIfPossible (the ATTACH TABLE ... AS [NOT] REPLICATED engine conversion, Atomic databases only) makes two durability-relevant filesystem changes, neither of which fdatasync'd the containing directory: 1. clearTransactionMetadata unlinks each part's txn_version.txt(.tmp) via a bare unlink(). 2. writeMetadataFile writes the new definition to a .tmp (fsyncing file content only), then replaceFile renames it to .sql. A rename and an unlink are directory-entry changes; they are not durable until the containing directory is fdatasync'd. After the client is acknowledged, a power loss can lose either change: - The .sql rename is lost, restoring the old engine definition. - A txn_version.txt.tmp removal is lost and the .tmp file resurrects while its txn_version.txt is gone. VersionMetadataOnDisk::loadMetadata then reads the part as a rolled-back transaction (Tx::RolledBackCSN), marks it Outdated and discards it, losing committed data. This is the same data-loss class as ClickHouse#111348 and the stale-tmp case covered by test 04492. Acquire a directory sync guard on every directory whose entry the operation changes: the metadata directory (for the .sql rename) and each modified part directory (for the txn-file removals). Each guard fdatasyncs on scope exit, after the change. Guards are acquired before the destructive operation (guard construction opens the directory and can throw), so a failure leaves the old state untouched rather than half-converted. All gated on fsync_metadata, which already gates the file-content fsync here; a no-op on object storage. The sibling CREATE/RENAME/ALTER/DROP DATABASE metadata commits are handled separately in ClickHouse#111405; the general createDirectories() ancestor-chain gap is tracked separately. Related: ClickHouse#111348 New test 04546_attach_as_replicated_metadata_fsync observes the directory fsync via ProfileEvents['DirectorySync'] and checks the fsync_metadata gate. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review — adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 1 finding across 2 rounds; bounded: 1 full pass + 1 fix round + 1 delta recheck).
Delta re-review (full scope, stateful): 0 findings. Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-4:20260723-001054 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-4:20260723-001054 |
|
cc @tuanpach @tavplubix — could you review this? |
|
Workflow [PR], commit [fd4ae6f] Summary: ❌
AI ReviewSummaryThis PR adds directory-sync guards around the metadata rename and per-part Findings❌ Blockers
Tests
Final VerdictStatus: |
| /// because guard construction can throw and must not leave a half-converted table. | ||
| SyncGuardPtr metadata_dir_sync_guard; | ||
| if (getContext()->getSettingsRef()[Setting::fsync_metadata]) | ||
| metadata_dir_sync_guard = db_disk->getDirectorySyncGuard(fs::path(table_metadata_path).parent_path()); |
There was a problem hiding this comment.
This still leaves fsync_metadata=1 best-effort. On local disks getDirectorySyncGuard returns LocalDirectorySyncGuard, and its destructor catches/logs fdatasync failures instead of propagating them (src/Disks/LocalDirectorySyncGuard.cpp:39-64). So a failed directory sync here still lets ATTACH TABLE ... AS [NOT] REPLICATED succeed even though the metadata rename or the per-part txn_version.txt(.tmp) unlinks were never made durable, which is exactly the post-ack window this PR is trying to close. The new DirectorySync-count test will not catch that either, because the counter is incremented before the sync attempt. This needs a throwing directory-sync path (or an explicit sync() on the guard that is called before success is returned) rather than the destructor-only helper.
There was a problem hiding this comment.
The two facts here are correct: ~LocalDirectorySyncGuard catches and logs fdatasync/close failures (src/Disks/LocalDirectorySyncGuard.cpp:39-66), and the DirectorySync ProfileEvent is incremented before the sync attempt (line 41). But making the directory fsync fail-closed here is out of scope for this fix, for three reasons.
-
There is no throwing path to call.
ISyncGuard(src/Disks/IDisk.h:126-131) exposes only a virtual destructor; the sync is intentionally in an RAII dtor, which cannot throw. A non-swallowingsync()/finalize()does not exist, so this is new shared durability infra, not a call this PR omitted. -
Best-effort directory fsync via the guard dtor is the codebase-wide idiom. Every
getDirectorySyncGuardsite relies on it the same way this PR does:MergeTreeData.cpp:11581,DataPartStorageOnDiskBase.cpp:709/1022,MergeTreeDataWriter.cpp:929,DataPartsExchange.cpp:844,VersionMetadataOnDisk.cpp:344,DistributedSink.cpp:891,DeleteBitmapFileOps.cpp:70,DistributedAsyncInsertBatch.cpp:144/171. Converting only this one call site to fail-closed would diverge from every MergeTree commit path without closing the window anywhere else. -
This PR's contract is that the mutated directory entries get fdatasync'd at all, which is exactly the Acknowledged
DROP TABLE/RENAME TABLE/EXCHANGE TABLESon an Atomic database can silently revert after power loss: the DDL commit record is never fsynced #111348 gap: before this change the.sqlrename and the per-parttxn_version.txt(.tmp)unlinks were never directory-synced (DirectorySync = 0). Test04546asserts the sync is attempted on exactly the mutated directories (2 part dirs + 1 metadata = 3), which is the property that regressed. Note the file content in this same path is already fail-closed:writeMetadataFile(src/Databases/DatabasesCommon.cpp:344-354) callsout->sync(), andWriteBufferFromFileDescriptor::syncthrowsCANNOT_FSYNCon failure (src/IO/WriteBufferFromFileDescriptor.cpp:148).
Making the shared directory-sync guard fail-closed is a reasonable separate change across all durability paths, but it is not this bug and I would rather not diverge this one site. The same point was raised on the sibling PR #111423 and resolved the same way.
CI finish ledger — 3151c88Every 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
Not PR-caused: this PR touches only Session id: cron:our-pr-ci-monitor:20260723-063000 |
|
Ledger owner update for the This shard's Code-241 burst is the known ASan-parallel host-memory-pressure cohort (server RSS pinned at the 44.83 GiB cap, OvercommitTracker cancelling in-flight queries), not this PR: our diff only touches the ATTACH-AS-REPLICATED metadata fsync path + its stateless test, and all 12 sibling stateless shards passed. This branch also branched from master on 2026-07-15, before the mitigation #110574 merged (2026-07-18), so it does not yet carry the concurrency/ratio fix; the fix is already on master. No separate fix PR from us: the two right mitigations are merged (#110574 concurrency + 0.75 ratio, #110503 |
|
@groeneai Check the CI |
…-attach-as-replicated-metadata-fsync
|
Checked, and merged master to fix it. New head The two red checks at the old head were not this PR. What I had missed until now is why a re-run would not have helped. CI builds the synthetic merge ref, so the failing job's binary reports Measured on live CI artifacts of two other PRs on that shard:
And over every CIDB row on that shard carrying I re-verified the fix on the merged tree rather than assuming the merge was inert:
Thanks for the approval, and sorry for the noise on your side. Nothing else is outstanding on the PR from my end. |
| if (disk->existsFile(txn_file)) | ||
| { | ||
| if (fsync_metadata && !part_dir_sync_guard) | ||
| part_dir_sync_guard = disk->getDirectorySyncGuard(part_path); |
There was a problem hiding this comment.
ATTACH TABLE ... AS REPLICATED is supposed to make the per-part txn_version.txt(.tmp) removals durable before the query returns, but this only happens on disks that override getDirectorySyncGuard. DiskObjectStorage inherits IDisk::getDirectorySyncGuard's nullptr default, while removeFile still commits metadata moveFile / writeFile operations on the metadata store, so a power loss after the ACK can still resurrect those files and make the part load as rolled back on restart. The new regression test is explicitly no-object-storage, so this supported surface is still both unfixed and unverified. Can we either add a real durable-sync path for object-storage metadata stores here, or scope the fix and user-facing claim to local/encrypted disks instead of the general ATTACH ... AS [NOT] REPLICATED path?
There was a problem hiding this comment.
Every fact here is correct, and I verified all of them again at the current head fd4ae6fb41d0cda65ba0db1f855e97b2aa394e91: IDisk::getDirectorySyncGuard returns nullptr (src/Disks/IDisk.cpp:212-215), DiskObjectStorage has no override (grep -c getDirectorySyncGuard src/Disks/DiskObjectStorage/DiskObjectStorage.cpp = 0), and the local metadata backend issues no sync for the operations behind removeFile (grep -ci sync src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDiskTransactionOperations.cpp = 0; the two sync() calls in MetadataStorageFromDisk.cpp:258,280 are on the blob removal log, not on file metadata).
I am still not changing this PR, for three measured reasons.
1. This is not a regression introduced here. On master this code path issues no directory fsync at all:
$ git show origin/master:src/Interpreters/InterpreterCreateQuery.cpp | grep -c getDirectorySyncGuard
0
So the object-storage window described above is master's own current behaviour, untouched by this PR. The PR moves local and encrypted disks from 0 syncs to N and leaves object storage exactly as it was.
2. It is the wrong layer, and the right layer is already being fixed. Nothing at this call site can make an object-storage metadata store durable: getDirectorySyncGuard is an IDisk virtual, and all 21 of its invocations outside src/Disks/ (MergeTree part writes, part renames, DataPartsExchange, VersionMetadataOnDisk, the distributed async-insert queue, this one) behave identically on object storage today. The fix belongs in DiskObjectStorage plus the metadata storage, which is exactly what PR #111391 does:
DiskObjectStorage::getDirectorySyncGuardoverride, forwarding to the metadata storage (DiskObjectStorage.h:109-112)IMetadataStorage::getDirectorySyncGuardplusIMetadataStorage::syncMetadataFile(IMetadataStorage.h:173-177)MetadataStorageFromDisk::getDirectorySyncGuard, forwarding to the local disk holding the metadata (MetadataStorageFromDisk.cpp:86-89)
None of those primitives exist on master (git grep -l syncMetadataFile origin/master returns nothing), which is why they cannot be reached from here yet. Once #111391 lands, this call site inherits the durable path with no change to this PR, and git merge-tree --write-tree shows the two changes merge cleanly (exit 0, no conflicts). The remaining sliver after that, a disk with use_fake_transaction=false and local metadata where the guard is deliberately declined because the metadata file does not exist until commit, is tracked as a separate follow-up and is already referenced on #111391 in #111391 (comment).
3. The alternative asked for is already in the PR. The suggestion offers "or scope the fix and user-facing claim to local/encrypted disks". That is the current state: the PR description says the change is "a no-op on object storage", and the regression test carries no-object-storage with that exact justification in its header:
# no-object-storage: fsync of a directory is a local-filesystem operation; object storage
# disks return no directory sync guard, so DirectorySync stays 0 there.
This is consistent with the earlier adjudication on this PR and with the same finding on the sibling PR #111423.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 24/25 (96.00%) · Uncovered code |
CI finish ledger — fd4ae6fEvery failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
Both owners are open, so recurrence on this branch is expected until they merge; neither is Session id: cron:our-pr-ci-monitor:20260727-190000 |
|
Closed with no comment, so rather than guess at the reason I would like to ask once. What I checked first, in case it was superseded: on current master Was it superseded by work I did not find, or is the approach wrong? I am asking because the answer applies to more than this PR. Five other open PRs of mine use the same I am not reopening this. |
Related: #111348
Related: #111405
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a rare data-loss window in
ATTACH TABLE ... AS [NOT] REPLICATEDonAtomicdatabases: the metadata.sqlrename and the per-parttxn_version.txtremovals were not directory-fsynced, so a power loss right after the query was acknowledged could restore the old engine definition or discard committed parts. The changed directories are now fdatasync'd (whenfsync_metadatais enabled).Description
ATTACH TABLE ... AS [NOT] REPLICATED(Atomic databases only) makes two durability-relevant filesystem changes inInterpreterCreateQuery::convertMergeTreeTableIfPossible, neither of which fdatasync'd the containing directory:clearTransactionMetadataunlinks each part'stxn_version.txt(.tmp) via a bareunlink().writeMetadataFilewrites the new definition to a.tmp(fsyncing file content only), thenreplaceFilerenames it to.sql.A rename and an unlink are directory-entry changes and are not durable until the containing directory is fdatasync'd. After the client is acknowledged, a power loss can lose either one:
.sqlrename is lost, restoring the old engine definition.txn_version.txt.tmpremoval is lost and the.tmpfile resurrects with itstxn_version.txtgone.VersionMetadataOnDisk::loadMetadatathen reads the part as a rolled-back transaction (Tx::RolledBackCSN), marks itOutdatedand discards it, losing committed data (same class as AcknowledgedDROP TABLE/RENAME TABLE/EXCHANGE TABLESon an Atomic database can silently revert after power loss: the DDL commit record is never fsynced #111348 and the stale-.tmpcase covered by test04492).The fix acquires a directory sync guard on every directory whose entry the operation changes (the metadata directory for the
.sqlrename, and each modified part directory for the txn-file removals). Each guard fdatasyncs on scope exit, after the change, and is acquired before the destructive operation so a failure leaves the old state untouched. Gated onfsync_metadata(which already gates the file-content fsync here); a no-op on object storage.Sibling CREATE/RENAME/ALTER/DROP DATABASE metadata commits are handled separately in #111405; the general
createDirectories()ancestor-chain gap is tracked separately.Verified in both directions via
ProfileEvents['DirectorySync']: 0 on unpatched, >0 when patched withfsync_metadata=1, 0 withfsync_metadata=0. New test04546_attach_as_replicated_metadata_fsync.