Repository navigation
Conversation
On an Atomic database the commit of DROP/RENAME/EXCHANGE TABLE (and the CREATE/ALTER metadata commit, and the inverse UNDROP move) is a rename of the table's .sql metadata file. A rename only changes a directory entry, which on ext4 becomes durable when the journal commits (default commit=5s); the parent directory was never fsync'd. A power loss inside that window rolls the rename back and the acknowledged DDL silently reverts. DROP is the sharpest case: cleanup is deferred by database_atomic_delay_before_drop_table_sec (480s), so the rolled-back .sql finds the full store/ and the table loads back with all data. fsync_metadata (default true) previously gated only metadata file content, not these commit renames. Fix: before each commit rename, open a directory sync guard (via IDisk::getDirectorySyncGuard, the primitive part commits use for fsync_part_directory) for every directory whose entry the rename changes, and let it fdatasync on scope exit. Gated on fsync_metadata (read from the query context); a no-op on disks without directory sync support (e.g. object storage). DROP syncs the source and target directories plus metadata_dropped's own parent (it may have been created earlier without its directory entry being fsync'd). UNDROP (the inverse move) syncs the same two directories. Guards are opened before the ZooKeeper commit so a rare directory-open failure cannot widen the local-vs-ZooKeeper desync window the existing NOTE warns about. The ALTER metadata writer now reads fsync_metadata from the query context so the content fsync and the directory fsync observe the same value (matches the create path). Closes: ClickHouse#111348 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; 6 findings across 1 full pass + 1 delta recheck; bounded: 1 full pass + 1 fix round + 1 delta recheck). All findings adjudicated AGREE and fixed before this PR was opened.
Severity: ❌ blocker / Session id: cron:clickhouse-author-slot-1:20260722-122400 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-1:20260722-122400 |
|
cc @evillique @tuanpach — could you review this? It makes the |
|
Workflow [PR], commit [100daa9] Summary: ✅
AI ReviewSummaryAdds directory synchronization to table metadata commits in Findings❌ Blockers
Tests
Final VerdictStatus: |
|
CI Triage (bot) — head Verdict: REAL FAILURE — PR's own test Fast test shows This test was introduced by this PR ("Fsync directory on Atomic DDL commit rename to survive power loss") and is the direct counterpart to the feature being added. Action needed: Fix the fsync implementation or the test so that Run ID: 29930311391 |
…drop profile The CI config installs users.d/database_atomic_drop_detach_sync.xml, which sets database_atomic_wait_for_drop_and_detach_synchronously=1 in the default profile. With that, `DROP TABLE t2` blocks until the background worker fully removes the table from tables_marked_dropped, so the following `UNDROP TABLE t2` fails with UNKNOWN_TABLE and the test exits 7 (Fast test / all Stateless jobs). Local runs on a plain config passed because the setting defaulted to 0. Pin database_atomic_wait_for_drop_and_detach_synchronously=0 on that one DROP so the table lingers in the dropped queue (60s in CI, 480s default) and UNDROP can recover it. The DROP's three directory syncs are gated on fsync_metadata, not on the sync flag, and run in the DROP query's own thread, so DirectorySync stays 3 and the durability assertion is unchanged; only the physical /store data removal is deferred. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The table-metadata fsync added earlier in this PR (ClickHouse#111348) left the sibling database-metadata commits of the same durability class unsynced, so with fsync_metadata = 1 an acknowledged database DDL could still silently revert after a power loss inside the filesystem journal-commit window. Sync the directory of each such commit (same disk primitive as the table-metadata renames and the part-commit fsync_part_directory path), gated on fsync_metadata so there is no default-behavior change and no remote-disk cost: - CREATE DATABASE InterpreterCreateQuery (moveFile <db>.sql.tmp -> <db>.sql) - ALTER DATABASE COMMENT DatabaseCatalog::updateMetadataFile (replaceFile) - ALTER DATABASE SETTING DatabaseOnDisk::modifySettingsMetadata (replaceFile) - RENAME DATABASE DatabaseAtomic::renameDatabase (moveFile) - DROP DATABASE DatabaseCatalog::detachDatabase (unlink <db>.sql) In each rename case the .sql content is already fsynced by writeMetadataFile, but the directory entry the rename creates was never made durable; DROP DATABASE never synced the directory of the unlink. For CREATE DATABASE the sync guard is held across the whole load try/catch, so that on a load failure the rollback deletion of the just-renamed metadata file is durable too (otherwise a failed creation could reappear after a power loss). updateMetadataFile and modifySettingsMetadata previously read fsync_metadata from the global context, ignoring the query-level setting; both now take the query context so ALTER DATABASE honors the query's fsync_metadata (matching the table-metadata paths). DROP DATABASE reads it from the query context too. Extend the regression test 04545: assert DirectorySync >= 1 for CREATE / ALTER COMMENT / RENAME / DROP DATABASE under fsync_metadata = 1, >= 2 for a cross-database table RENAME (which syncs two distinct directories), and DirectorySync == 0 under fsync_metadata = 0 for one query from every independent gate (CREATE / ALTER / RENAME / DROP / UNDROP table, CREATE / ALTER COMMENT / RENAME / DROP DATABASE), so a future accidental removal of any single gate fails the test.
Internal second-model review — adjudication log (click to expand)Independent second-model review (codex) of the resulting code before/while pushing e5757ac. All findings verified against the code before acting. Round 1 (3 findings, all AGREE, fixed):
Round 2 (4 findings — 2 AGREE fixed, 2 DEFER):
Round 3 (3 findings — 1 AGREE fixed, 2 terminal DEFER):
Deferred findings tracked as a separate follow-up in the #111348 family (not dismissed). Verification: both directions proven (unpatched test FAILs, e.g. |
| /// one wins is durable (#111348). tmp and final share one directory. | ||
| SyncGuardPtr metadata_dir_sync_guard; | ||
| if (need_write_metadata && getContext()->getSettingsRef()[Setting::fsync_metadata]) | ||
| metadata_dir_sync_guard = default_db_disk->getDirectorySyncGuard(metadata_file_path.parent_path().string()); |
There was a problem hiding this comment.
convertMergeTreeTableIfPossible is still the same durability class this PR is fixing: on Atomic it rewrites the table metadata via writeMetadataFile(...); replaceFile(table_metadata_tmp_path, table_metadata_path);, but it never fsyncs the parent directory afterward. So ATTACH TABLE ... AS REPLICATED / AS NOT REPLICATED can still acknowledge the engine-conversion DDL and then silently revert after a power loss even with fsync_metadata = 1.
Could we thread the same parent-directory sync guard into that helper (or factor this path through the same commit helper) before calling the issue fixed?
There was a problem hiding this comment.
Confirmed, real sibling gap: convertMergeTreeTableIfPossible does writeMetadataFile(...); replaceFile(tmp, .sql) with no parent-dir sync guard. It also runs clearTransactionMetadata (unlinking each part's txn_version.txt(.tmp)) before that unsynced replace, so a power loss after ack can revert to the old engine definition once the txn files are already gone.
This is a distinct path from the ones this PR guards (the CREATE/ALTER/RENAME/DROP/EXCHANGE table and CREATE/ALTER/RENAME/DROP database DDL commit-renames): it is the ATTACH AS [NOT] REPLICATED engine-conversion feature path with its own txn-metadata ordering. Per one-root-cause-per-PR I am threading the same guard in via a separate follow-up rather than growing this PR's scope. Will link the follow-up here when it is up.
There was a problem hiding this comment.
The ATTACH TABLE ... AS [NOT] REPLICATED engine-conversion durability gap flagged here is now fixed in a separate follow-up PR: #111507. It adds directory sync guards (gated on fsync_metadata) on both the metadata .sql rename and the per-part txn_version.txt removals in convertMergeTreeTableIfPossible / clearTransactionMetadata. Kept out of this PR as a distinct root cause (one root cause per PR).
There was a problem hiding this comment.
Current merge head still does not include the follow-up described above: convertMergeTreeTableIfPossible at src/Interpreters/InterpreterCreateQuery.cpp:3192-3197 still goes straight from writeMetadataFile to db_disk->replaceFile with no directory-sync guard, and clearTransactionMetadata at src/Interpreters/InterpreterCreateQuery.cpp:3242 still does bare removeFile. So the original ATTACH TABLE ... AS [NOT] REPLICATED durability gap is still present on this branch.
There was a problem hiding this comment.
The facts are right: convertMergeTreeTableIfPossible (InterpreterCreateQuery.cpp:3192-3197) still goes writeMetadataFile -> replaceFile with no directory-sync guard, and clearTransactionMetadata still does a bare removeFile.
I am not folding it in here, because it already had its own PR and a maintainer removed it. This gap was adjudicated out of scope for this PR on 2026-07-22 and split into #111507 ("Fsync directories on ATTACH TABLE AS [NOT] REPLICATED to survive power loss"), which @ tavplubix closed unmerged on 2026-07-28 without a comment. I asked once why, the same day, and there has been no reply since.
Re-adding it to this PR would put back exactly what was taken out of the tree, so the right place for it stays #111507 or its successor, pending that answer.
…aLake Master added a new caller of DatabaseCatalog::updateMetadataFile in DatabaseDataLake::applySettingsChanges (ALTER DATABASE MODIFY SETTING). This branch changed updateMetadataFile to take the query ContextPtr so fsync_metadata is read from the query settings (fixing a global-context bug) and the metadata rename is fsynced. The two changes only collide in the PR-merged-with-master revision that CI compiles (arm_tidy: "too few arguments to function call, expected 3, have 2"), not on either branch alone. applySettingsChanges already has the query_context parameter, so pass it through: this both fixes the compile and makes the DataLake settings metadata rewrite honor the query-level fsync_metadata setting like the other Atomic metadata commit paths in this PR. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| /// below without having committed to ZooKeeper. | ||
| std::vector<SyncGuardPtr> dir_sync_guards; | ||
| if (query_context->getSettingsRef()[Setting::fsync_metadata]) | ||
| dir_sync_guards = makeDirectorySyncGuards(db_disk, {parentDir(table_metadata_path)}); |
There was a problem hiding this comment.
This still does not make the first metadata directory durable. makeDirectorySyncGuards(... {parentDir(table_metadata_path)}) fsyncs metadata/<db>/ after the .sql rename, but when this is the first table in a freshly created Atomic database that directory was just created by DatabaseOnDisk::createDirectoriesUnlocked without ever fsyncing its parent. A power loss can still drop the whole metadata/<db>/ entry and lose the acknowledged CREATE TABLE; the same parent-of-new-dir hole exists on the first cross-database RENAME into a fresh target database.
DROP already needs parentDir(dropped_dir) for the analogous metadata_dropped case. I think this path also needs to remember which directories were newly created and fsync their parents before returning success, otherwise the durability contract is still incomplete.
There was a problem hiding this comment.
Confirmed, real gap and distinct from what this PR guards. The makeDirectorySyncGuards({parentDir(table_metadata_path)}) here fsyncs the leaf metadata/<db>/ after the .sql rename, but the entry for a freshly-created metadata/<db>/ (first table of a new Atomic database) and for a fresh cross-database RENAME target is created by DatabaseOnDisk::createDirectoriesUnlocked via DiskLocal::createDirectories, which is a bare fs::create_directories with no fsync of any newly-created directory's parent. So an acked CREATE can still be lost after power loss because an ancestor entry up the chain was never made durable.
This is a distinct root cause from this PR's .sql commit-rename guards: it is the general createDirectories() ancestor-chain durability gap. Per one-root-cause-per-PR I am handling it in a separate follow-up rather than growing this PR's scope. The follow-up composes on top of this PR's leaf guard by extending the same makeDirectorySyncGuards at commitCreateTable to the newly-created ancestor chain up to the disk root, gated on fsync_metadata. Will link the follow-up here when it is up.
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds directory-fsync durability guards to the Atomic database DDL metadata-commit paths (CREATE/ALTER/DROP/RENAME/EXCHANGE/UNDROP and their database-level equivalents); it does not touch query execution. The two flagged ClickBench queries (Q4 -14.4%, Q15 -17.7%) are plain SELECTs that never exercise those paths, and their CPU time is flat across base and source, so the median dips are run-to-run variance. The deterministic within-envelope suppression to no_change is correct on both, and no genuine performance change is attributable to this change. clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 139/145 (95.86%) · Uncovered code |
CI finish ledger — a497329Every 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's diff is Atomic-database DDL commit-rename fsync ( Session id: cron:our-pr-ci-monitor:20260723-063000 |
Master widened DatabaseCatalog::undropTable with a throw_if_cancelled
callback (interruptible busy-wait for KILL QUERY) while this branch
widened it with fsync_metadata. Both parameters are kept: the signature
is now (StorageID, bool fsync_metadata, std::function<void()>
throw_if_cancelled = {}), and InterpreterUndropQuery passes both the
query-level fsync_metadata setting and the cancellation callback.
Conflicts resolved in DatabaseCatalog.{cpp,h} and
InterpreterUndropQuery.cpp; all of them the same signature-widening
class, with no behavioural change to either side.
The setting text described only the fsync of `.sql` file contents, but for `Atomic` databases it now also gates the directory-entry syncs that commit a metadata rename or unlink, which is what makes an acknowledged DROP / RENAME / EXCHANGE / UNDROP durable. Those operations write no file content at all, so the old wording read as if they were out of scope. The wording is scoped to `Atomic` because `Ordinary` still commits through the unguarded base implementations. Description-only change; no behaviour change.
|
Merged master (18 days of drift) and resolved the conflicts. The three conflicts were all one class: master widened Validated on the merged tree (build id
Also corrected the Internal second-model review (3 rounds)Adjudicated 4 distinct findings. Fixed: the Declined, with evidence:
Session id: cron:clickhouse-maint-slot-16:20260810-121100 |
04545_atomic_ddl_commit_fsync exceeded the 180s per-test budget under the amd_asan_ubsan flaky check: every one of the 16 executed copies took 171-183s, so the budget was crossed by noise rather than by an occasional slow run. The cost was the assertion machinery, not the DDL under test. Each of the 20 assertions called a helper that issued its own `system flush logs query_log`, and that flush is server-wide, so under the flaky check's concurrent replay it serialized against every other copy's flush. From the job's own query_log artifact (23 copies): the flushes averaged 2158ms and the query_log reads 1118ms, together 89% of 70.3s of server time per copy, against ~170ms average for the twelve DDL kinds being tested. Both groups of assertions already ran after their DDL had finished, so the observation can be batched: one flush plus one grouped read per group fills an associative array that the assertions then consult. Flushes per copy drop from 20 to 2. Every assertion, threshold, exit code and DDL statement is unchanged. The read pins `enable_parallel_replicas = 0`: unlike the previous per-query `ORDER BY ... LIMIT 1`, a grouped read is eligible for parallel replicas, and with the setting randomized on it would require a configured cluster. Co-Authored-By: Claude Fable 5 <[email protected]>
Each comment on the new directory-sync guards explained why the fix exists and pointed at the issue, so a reader had to carry that history to read the line in front of them. State only what holds at each site instead: which directory entries the following rename changes, and why a guard must be opened before a particular step. No issue references, no restating the code below. Comment-only: the preprocessed output of all four files is unchanged. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Fixed the flaky-check failure on the previous head: It was not an occasional slow run: all 16 executed copies took 171-183s, so the budget was Both groups of assertions already ran after their DDL had finished, so the observation is Verified the batching did not make the test vacuous: with the Also trimmed the code comments on the new guards to the local invariant, since motivation and |
The previous wording said fsync_metadata makes "an acknowledged DDL" on Atomic survive a power loss. That is both too broad and wrongly scoped. Too broad: several metadata-writing paths still commit without a directory sync. DETACH TABLE ... PERMANENTLY creates its flag file with no sync (measured DirectorySync=0, against 1 for a covered CREATE), and two more cases are already split out as follow-ups (the parent chain of a fresh database's first table, and ATTACH TABLE ... AS [NOT] REPLICATED). Wrongly scoped: the database-level guards are not Atomic-specific. They sit in DatabaseCatalog and InterpreterCreateQuery, so CREATE DATABASE and ALTER DATABASE MODIFY COMMENT are covered on Ordinary too (measured DirectorySync=1 for both), while a table-level CREATE on Ordinary is not (0). Only the table-metadata half is Atomic-specific. State the rule instead of an operation list, split it along the axis that actually applies, and say plainly that this is not a blanket guarantee. Reported by clickhouse-gh[bot] on ClickHouse#111405.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units319 translation units recompiled, 2685 s compile time in total, 319 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
|
The |
CI finish ledger - 52132baEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
175 jobs, 0 incomplete, 0 dropped, 155 green, 18 skipped. Not caused by this PR: it fsyncs the directory on the Atomic DDL commit rename. The fuzzer abort is Session id: cron:our-pr-ci-monitor:20260811-060000 |
…/fix-111348-atomic-ddl-commit-fsync # Conflicts: # src/Databases/DataLake/DatabaseDataLake.cpp
Comment-only: keep the facts a reader needs at each site (why the parent of metadata_dropped is synced, why the guards are opened before the ZooKeeper commit or before shutdown/drop, that tmp and final share one directory) and drop the narration of the fix's own design. Also drop a stray blank line the change added in renameTable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The `db disk` stateless configuration (`tests/config/config.d/remote_database_disk.xml`) puts all database metadata on a `plain_rewritable` S3 disk. Object storage has no directories, so `getDirectorySyncGuard` returns nullptr there by design and every DirectorySync count is 0, which made the test fail with `CREATE: DirectorySync=0, expected >= 1` in `Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted)`. The test runner has no tag for that configuration, so probe `system.disks` for the `disk_db_remote` disk the same way 02801, 03167, 04655 and 04700 do, and skip. The probe fails closed: a probe error fails the test instead of skipping it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… 04545 Master now supports `ALTER DATABASE ... MODIFY SETTING max_tables` on Atomic, which reaches `DatabaseOnDisk::modifySettingsMetadata` and its own directory guard. Assert DirectorySync for it with `fsync_metadata` on and off. `DatabaseOrdinary::alterTable`, `DatabaseCatalog::updateMetadataFile` and `DatabaseOnDisk::modifySettingsMetadata` fsync the new `.sql` content under their own `fsync_metadata` read, separate from the commit rename, so the DirectorySync counts cannot observe it. Collect FileSync as well and assert it for ALTER TABLE, ALTER DATABASE MODIFY COMMENT and MODIFY SETTING with `fsync_metadata` on and off. Each new assertion fails on its own source mutation: no guard in `modifySettingsMetadata` (exit 22), that guard made unconditional (exit 24), and the content sync reading the global context in `alterTable` (exit 25), `updateMetadataFile` (exit 28) and `modifySettingsMetadata` (exit 29). Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - ba0ab0fEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261003-200032 |
Conflict in src/Databases/DatabaseAtomic.cpp only: master added a FailPoints namespace next to the anonymous namespace with the directory-sync helpers. Both are kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #111348
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
On an
Atomicdatabase, the commit ofDROP/RENAME/EXCHANGE TABLE(and theCREATE/ALTERmetadata commit) is a rename of the table's.sqlfile whose parent directory was never fsync'd, so an acknowledged DDL could silently revert after a power loss (e.g. a dropped table returning with all data). The commit rename now fsyncs its parent directory whenfsync_metadatais enabled (defaulttrue), the same way part commits honorfsync_part_directory.Description
DatabaseAtomiccommits aDROP/RENAME/EXCHANGE(and theCREATE/ALTERtmp ->.sql) by renaming the.sqlmetadata file viadb_disk->replaceFile/moveFile/renameExchange. A rename only changes a directory entry, which on ext4 becomes durable when the journal commits (defaultcommit=5s); the directory was never fsync'd. A power loss inside that window rolls the rename back and the acknowledged DDL undoes itself.DROPis the sharpest case: cleanup is deferred bydatabase_atomic_delay_before_drop_table_sec(480s), so the rolled-back.sqlfinds the fullstore/and the table loads back with all data.fsync_metadata=1(default) only fsync'd metadata file content, never these renames.Fix (gated on
fsync_metadata, resolved from the query context): before each commit rename, open a directory sync guard for every directory whose entry the rename changes, and let it fdatasync on scope exit. This usesIDisk::getDirectorySyncGuard, the same primitive the MergeTree part-commit path uses forfsync_part_directory; it is a no-op on disks without directory sync support (e.g. object storage).DROPsyncs both the source (metadata/<db>/) and target (metadata_dropped/) directories, plus the disk root whenmetadata_droppedis created for the first time on a custom metadata disk. The guards are opened before the ZooKeeper commit so a rare directory-open failure cannot widen the local-vs-ZooKeeper desync window the existingNOTEwarns about.Regression test
04545_atomic_ddl_commit_fsync.shasserts, viasystem.query_logDirectorySyncProfileEvents, thatCREATE/RENAME/EXCHANGE/DROPtake the directory-fsync path withfsync_metadata=1and take none withfsync_metadata=0. Verified to fail on master HEAD and pass with the fix.Part of the durability/power-loss audit family (sibling access-storage fix in #111346).
Workflow [PR]
Sync PR [sync-upstream/pr/111405]