Skip to content

Fsync directory on Atomic DDL commit rename to survive power loss - #111405

Open
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111348-atomic-ddl-commit-fsync
Open

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111348-atomic-ddl-commit-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111348

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):

On an Atomic database, the commit of DROP/RENAME/EXCHANGE TABLE (and the CREATE/ALTER metadata commit) is a rename of the table's .sql file 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 when fsync_metadata is enabled (default true), the same way part commits honor fsync_part_directory.

Description

DatabaseAtomic commits a DROP/RENAME/EXCHANGE (and the CREATE/ALTER tmp -> .sql) by renaming the .sql metadata file via db_disk->replaceFile/moveFile/renameExchange. A rename only changes a directory entry, which on ext4 becomes durable when the journal commits (default commit=5s); the directory was never fsync'd. A power loss inside that window rolls the rename back and the acknowledged DDL undoes itself. 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=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 uses IDisk::getDirectorySyncGuard, the same primitive the MergeTree part-commit path uses for fsync_part_directory; it is a no-op on disks without directory sync support (e.g. object storage). DROP syncs both the source (metadata/<db>/) and target (metadata_dropped/) directories, plus the disk root when metadata_dropped is 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 existing NOTE warns about.

Regression test 04545_atomic_ddl_commit_fsync.sh asserts, via system.query_log DirectorySync ProfileEvents, that CREATE/RENAME/EXCHANGE/DROP take the directory-fsync path with fsync_metadata=1 and take none with fsync_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]

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]>
@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; 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.

# Sev Finding Verdict Evidence / action
1 ❌ DROP synced metadata_dropped's parent only when this call created it; a prior fsync_metadata=0 drop could create it unsynced, then an fsync-on drop would skip the root guard AGREE Always sync parentDir(dropped_dir) when fsync_metadata; verified DROP DirectorySync=3
2 ❌ UNDROP TABLE (DatabaseCatalog::undropTable) did the inverse metadata move with no directory sync AGREE Threaded fsync_metadata into undropTable, guarded source+target dirs; verified UNDROP DirectorySync=2
3 ⚠️ ALTER content-fsync used the DB global context while the new dir guard used the query context (could observe different fsync_metadata) AGREE DatabaseOrdinary::alterTable writer now uses local_context (matches the create path)
4 ⚠️ Test not restricted to the Atomic DB engine mode; under Ordinary/Replicated the counts would fail AGREE Added the atomic-database tag
5 💡 Same rationale repeated at 4 call sites AGREE Moved the invariant into the helper doc; trimmed each site
6 ⚠️ (delta) DROP asserted >=2 but the fix syncs 3 dirs, so removing the parent guard would still pass AGREE Tightened the DROP assertion to >=3

Severity: ❌ blocker / ⚠️ major / 💡 nit. All fixes were rebuilt (Build ID verified changed) and re-verified via the deterministic DirectorySync ProfileEvent repro and 50/50 randomized runs of the regression test.

Session id: cron:clickhouse-author-slot-1:20260722-122400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Per-DDL DirectorySync ProfileEvent is 0 on unpatched master and >=1 on the fix, on demand (no timing dependence).
b Root cause explained? Yes. The DDL commit is a rename of the .sql file; a rename only changes a directory entry, durable on ext4 only when the journal commits (default commit=5s). The parent directory was never fsync'd, so a power loss inside that window rolls the rename back and the acknowledged DDL reverts.
c Fix matches root cause? Yes. It fsyncs the parent directory of each commit rename (the exact missing barrier) via IDisk::getDirectorySyncGuard, gated on fsync_metadata. Not a symptom guard.
d Test intent preserved / new tests added? Yes. New regression test 04545_atomic_ddl_commit_fsync.sh asserts the DirectorySync barrier fires for CREATE/ALTER/RENAME/EXCHANGE/DROP/UNDROP and is 0 when fsync_metadata=0. No existing test weakened.
e Both directions demonstrated? Yes. Test FAILS on unpatched master (CREATE: DirectorySync=0, expected >= 1) and PASSES on the fix. 50/50 randomized runs pass.
f Fix is general across code paths? Yes. Covers the whole commit-rename class: DROP, RENAME, EXCHANGE, plus the sibling CREATE/ALTER .tmp -> .sql commits and the inverse UNDROP move (DatabaseCatalog::undropTable).
g Fix generalizes across inputs? Yes. Works through the IDisk abstraction: DiskLocal fsyncs; disks without directory-sync support (e.g. object storage) get a nullptr no-op. Same-db renames dedup to one directory; cross-db RENAME/EXCHANGE sync both. DROP handles the precreated metadata_dropped (default disk) and the newly-created case (custom metadata disk, +disk root).
h Backward compatible? Yes. Pure durability addition gated on the existing fsync_metadata setting (default true); no format/protocol/setting-default/ABI change. fsync_metadata=0 fully preserves old behavior (verified DirectorySync=0). No SettingsChangesHistory change needed.
i Invariants and contracts preserved? Yes. Guards are RAII locals that fsync on scope exit AFTER the rename, and are opened BEFORE the ZooKeeper commit so no new throw point widens the local-vs-ZooKeeper desync window; the "should never throw after rename" regions and mutex scopes are untouched; CREATE/ALTER tmp-cleanup (catch / SCOPE_EXIT) still runs if the open throws.

Session id: cron:clickhouse-author-slot-1:20260722-122400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @evillique @tuanpach — could you review this? It makes the DROP/RENAME/EXCHANGE/UNDROP metadata commit on Atomic databases durable by fsyncing the parent directory of the .sql rename (via IDisk::getDirectorySyncGuard, gated on fsync_metadata), so an acknowledged DDL no longer silently reverts after a power loss (#111348).

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [100daa9]

Summary: ✅


AI Review

Summary

Adds directory synchronization to table metadata commits in Atomic databases and database metadata commits, gated by the query's fsync_metadata. Reviewed head 100daa9565b9dd6eb7b60313f0b52870ed299916, the current diff, and all prior discussion. Earlier coverage and setting-description findings are addressed; no new inline findings. Two previously reported durability gaps remain deliberately deferred.

Findings

❌ Blockers

  • src/Databases/DatabaseAtomic.cpp:483 — New metadata-directory ancestors remain unsynced. [dismissed by author -- Fsync directory on Atomic DDL commit rename to survive power loss #111405 (comment)] commitCreateTable syncs only the directory containing the table's .sql file. DatabaseOnDisk::createDirectoriesUnlocked creates that directory and any missing ancestors without syncing their parents. Consequently, the first acknowledged CREATE TABLE, or a cross-database RENAME into a fresh destination, still lacks a complete directory-durability guarantee. Deferring this work does not establish persistence of the new ancestor entries. Sync the newly created ancestor chain through an existing durable directory and cover this boundary in a focused test.

  • src/Interpreters/InterpreterCreateQuery.cpp:4573 — Engine conversion still bypasses the metadata-commit barrier. [dismissed by author -- Fsync directory on Atomic DDL commit rename to survive power loss #111405 (comment)] convertMergeTreeTableIfPossible still follows writeMetadataFile with an unguarded replaceFile; clearTransactionMetadata also removes txn_version.txt and its temporary counterpart without syncing their directories. An acknowledged ATTACH TABLE ... AS [NOT] REPLICATED can therefore lose its engine conversion after power loss, and the metadata rewrite and transaction-file removals have no durability ordering. The separate follow-up, Fsync directories on ATTACH TABLE AS [NOT] REPLICATED to survive power loss #111507, is not included in this head. Add the metadata and part-directory barriers in that conversion path; the startup conversion in DatabaseOrdinary::convertMergeTreeToReplicatedIfNeeded shares the same unsynced cleanup and replace pattern.

Tests
  • ⚠️ 04545_atomic_ddl_commit_fsync passes on the current head in Fast test, including the positive/negative directory and content-sync assertions. It does not prove ancestor-directory durability or conversion ordering. Add focused regression coverage with the corresponding fixes. No local build or test was run.
Final Verdict

Status: ⚠️ Request changes. The two confirmed, previously deferred durability gaps remain unresolved. Complete their focused fixes here or in merged follow-ups. The author's scope decisions are recorded above; existing threads were left untouched, with no duplicate inline comments or replies.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
@StackSlayerAI

Copy link
Copy Markdown
Contributor

CI Triage (bot) — head b12d0a80 — 2026-07-22

Verdict: REAL FAILURE — PR's own test 04545_atomic_ddl_commit_fsync failing

Fast test shows 04545_atomic_ddl_commit_fsync failing at test 8911/12637.

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 04545_atomic_ddl_commit_fsync passes reliably.

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]>
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author
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):

Finding Sev Verdict Action
DB-metadata renames unsynced (renameDatabase, CREATE DATABASE, updateMetadataFile) blocker AGREE Added dir sync guards, gated on fsync_metadata
ALTER DATABASE MODIFY COMMENT ignored query fsync_metadata (read global ctx) major AGREE Threaded query context through updateMetadataFile (verified empirically)
ALTER DATABASE MODIFY SETTING (modifySettingsMetadata) unsynced + global ctx major AGREE Threaded query context + dir guard

Round 2 (4 findings — 2 AGREE fixed, 2 DEFER):

Finding Sev Verdict Action
DROP DATABASE unlink unsynced blocker AGREE Dir guard on the unlink (query ctx)
Test: negative path only covered DROP; same-db RENAME only major AGREE Added per-gate fsync_metadata=0 asserts + cross-db RENAME (>=2)
Fresh-db ancestor-directory chain durability (createDirectories) blocker DEFER Distinct filesystem-durability gap, not a .sql commit rename -> follow-up task
ATTACH ... AS [NOT] REPLICATED conversion replace unsynced blocker DEFER Distinct engine-conversion path -> follow-up task

Round 3 (3 findings — 1 AGREE fixed, 2 terminal DEFER):

Finding Sev Verdict Action
DROP DATABASE guard opened AFTER shutdown()/drop() (open-failure -> detached + Keeper divergence) blocker AGREE Moved guard before the destructive work, reattach-on-open-failure
ancestor-directory chain (re-surfaced) blocker DEFER Terminal (round-2 evidence)
ATTACH conversion (re-surfaced) blocker DEFER Terminal (round-2 evidence)

Deferred findings tracked as a separate follow-up in the #111348 family (not dismissed).

Verification: both directions proven (unpatched test FAILs, e.g. CREATE DATABASE DirectorySync=0; patched PASSes 3/3 via clickhouse-test harness + 20/20 direct). ALTER DATABASE/DROP DATABASE query-fsync honoring and DROP-DATABASE durability confirmed by direct DirectorySync experiments (fsync=1 -> synced, fsync=0 -> 0). No contrib drift.

/// 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());

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)});

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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
  • StressHouse run: df9a004b-722a-496b-8bd4-160e81a8d6ad
  • MIRAI run: 99d2b449-0a53-4822-864c-335106f5f3a3
  • PR check IDs:
    • clickbench_128955_1784776787
    • clickbench_128961_1784776787
    • clickbench_128972_1784776787
    • tpch_adapted_1_official_128990_1784776787
    • tpch_adapted_1_official_128999_1784776787
    • tpch_adapted_1_official_129023_1784776787

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.20% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 139/145 (95.86%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a497329

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
Integration tests (amd_tsan, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky (chronic trunk, 123 master + 626 PR hits/30d; write-side bypass=true race in ReplicatedMergeTree structure alter) #111029 (external, open)
CH Inc sync — CH Inc sync (private, not actionable by us)

Not PR-caused: this PR's diff is Atomic-database DDL commit-rename fsync (DatabaseAtomic/DatabaseCatalog/InterpreterCreateQuery + test 04545), unrelated to the Replicated-database structure-alter path. The single failing test is the known chronic test_replicated_table_structure_alter flake (retry_ok in this run; all other tests in the shard passed), owned by external fix PR #111029.

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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master (18 days of drift) and resolved the conflicts.

The three conflicts were all one class: master widened DatabaseCatalog::undropTable with a
throw_if_cancelled callback (making the busy-wait interruptible by KILL QUERY, #110997) while
this branch widened it with fsync_metadata. Both are kept, so neither change is lost:
undropTable(StorageID, bool fsync_metadata, std::function<void()> throw_if_cancelled = {}), and
InterpreterUndropQuery passes both.

Validated on the merged tree (build id 8c89f3ae):

  • 04545_atomic_ddl_commit_fsync (this PR's durability assertions) — pass
  • 04726_kill_undrop_table_busy_wait (master's cancellation regression test) — pass
  • full build clean; every updateMetadataFile caller in the merged tree passes 3 args, which is
    the git-invisible compile break this branch already hit once (DatabaseDataLake.cpp, arm_tidy)
  • all 8 non-conflicted files: this PR's contribution is byte-identical to its pre-merge form
  • no submodule pin moved (diff vs master has no contrib/* entries)

Also corrected the fsync_metadata setting description, which documented only the fsync of .sql
file contents. For Atomic databases the setting now additionally gates the directory-entry syncs
that commit a metadata rename or unlink, and 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.

Internal second-model review (3 rounds)

Adjudicated 4 distinct findings.

Fixed: the fsync_metadata description (both the original omission and, in the next round, an
over-broad first attempt of mine that promised durable DDL without scoping it to Atomic — guards
exist only in the DatabaseAtomic overrides of commitCreateTable/commitAlterTable).

Declined, with evidence:

Session id: cron:clickhouse-maint-slot-16:20260810-121100

groeneai and others added 2 commits August 10, 2026 20:32
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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed the flaky-check failure on the previous head: 04545_atomic_ddl_commit_fsync was
crossing the 180s per-test budget under amd_asan_ubsan.

It was not an occasional slow run: all 16 executed copies took 171-183s, so the budget was
crossed by noise. The cost was the assertion machinery, not the DDL under test. Each of the
20 assertions issued its own system flush logs query_log, and that flush is server-wide,
so under the 50x replay it serialized against every other copy. From the job's own
query_log artifact (23 copies): 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 is
now batched: one flush plus one grouped read per group. Flushes per copy drop from 20 to 2;
every assertion, threshold, exit code and DDL statement is unchanged, and no tag was added.

Verified the batching did not make the test vacuous: with the undropTable directory-sync
guard deleted the test still fails on the right assertion (UNDROP: DirectorySync=0, expected >= 2), and it passes with the guard restored. Mutating the batched read to return
no rows, or to shift the collected values, also fails as expected. 15/15 randomized runs pass.

Also trimmed the code comments on the new guards to the local invariant, since motivation and
context belong in the commit message.

Comment thread src/Core/Settings.cpp Resolved
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.
@clickhouse-gh

clickhouse-gh Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 100daa956 with master d500731c0 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.67, programs/clickhouse-keeper ×0.68 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.6 s 14.9 s +11.2 s (+299%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.3 s 7.7 s +5.5 s (+250%)
Compile time of recompiled translation units

319 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 matched translation units cost +177.1 s (+7%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

The 03753_join_runtime_filter_dynamically_disable Q4 failure on head 52132ba (Stateless tests (amd_debug, parallel)) is not caused by this PR and now has a fixing PR: #114265. It is a pre-existing flake in the join runtime filter test, where Q4 asserts RuntimeFilterBlocksProcessed = 0 but a SharedFixedHashTableRuntimeFilter with no full-disable path can serve the join depending on the process-global hash-table statistics cache.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 52132ba

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

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug) / Shard number is greater than shard count: shard_num=2 shard_count=1 (STID 5066-457d) prepareClusterForParallelReplicas keeps a shard scope that outlives the cluster that produced it, reached here through viewExplain under cluster_for_parallel_replicas = 'test_cluster_one_shard_three_replicas_localhost' #113589 (mine, open)
Stateless tests (amd_debug, parallel) / 03753_join_runtime_filter_dynamically_disable Q4 line only: the runtime filter is never attached, so the test prints Q4 0 <query_id> instead of Q4 1 Ok (1 failure of 12468) #114265 (mine, open)

175 jobs, 0 incomplete, 0 dropped, 155 green, 18 skipped. Config Workflow and Finish Workflow
both succeeded, last completion 2026-08-11T04:17:01Z.

Not caused by this PR: it fsyncs the directory on the Atomic DDL commit rename. The fuzzer abort is
in parallel-replicas cluster-proxy shard scoping and the flaky line is in join runtime filtering;
neither goes through the rename path. #114265 was opened from this PR's own sighting.

Session id: cron:our-pr-ci-monitor:20260811-060000

groeneai and others added 4 commits October 3, 2026 12:26
…/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]>
@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ba0ab0f

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

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) / 03247_create-same-table-concurrently-with-atomic-engine not from this PR: "Test runs too long (> 180s)" in 4 of 4 runs (318-347 s); with metadata on the object-storage database disk, the directory syncs this PR adds are no-ops, and the same test fails the same way in this lane on 2 unrelated PRs #122662 (mine, open)
Finish Workflow / Post Hooks the new-tests check found no Bugfix validation verdict, because both functional Bugfix validation jobs were dropped after the targeted job above failed #122662 (mine, open)
Mergeable Check, PR rollups: red because of the rows above; 72 jobs were dropped after the targeted job failed and did not run on this head #122662 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

04545_atomic_ddl_commit_fsync passed in all 282 runs that executed it and is skipped by design on the object-storage database disk. The dropped jobs, including Bugfix validation, need a new run once #122662 lands.

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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

3 participants