Skip to content

Make on-disk SQL objects (UDFs, named collections, workloads) crash-durable - #111423

Open
groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111381-sql-objects-fsync
Open

groeneai wants to merge 17 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111381-sql-objects-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Make on-disk SQL objects crash-durable. CREATE/DROP of user-defined functions, named collections and workload entities (WORKLOAD/RESOURCE) now fsync the parent directory after the commit rename and after the file removal (gated on fsync_metadata, default enabled), so an acknowledged CREATE no longer vanishes and an acknowledged DROP no longer reverts after a power loss; a statement whose directory fsync fails now reports that error instead of success. A corrupt unencrypted local named-collection file is skipped and logged at startup instead of failing server startup.

Description

Closes: #111381

UserDefinedSQLObjectsDiskStorage, NamedCollectionsMetadataStorage (local) and WorkloadEntityDiskStorage committed a create by renaming <object>.sql.tmp into place and a drop with fs::remove, fsyncing only the temporary file's content: neither the rename, the removal nor the lazy directory creation synced the parent directory, and the drop path never read fsync_metadata. An fsync of a file does not persist its directory entry, so after a power loss an acknowledged CREATE could disappear and an acknowledged DROP could revert, bringing back stale credentials.

The three stores now share one directory-sync helper in src/Disks/. It opens the parent directory before the rename or unlink, so one it cannot open leaves nothing committed, syncs it afterwards, and persists the entry of every component of the store path, whoever created it: a component left by a disabled write, or by an operator's mkdir -p, is no more durable than the object inside it. A failed sync fails the statement instead of being logged and dropped. LocalDirectorySyncGuard is untouched, so its other callers stay best-effort. Gated on fsync_metadata (default enabled), read from the query context except for named collections (global).

NamedCollectionsMetadataStorage::getAll also only caught Keeper ZNONODE, so a corrupt or zero-byte local .sql file raised a parse error out of startup. It now skips and logs one for plain local storage, still rethrowing for replicated and encrypted storage, where a parse failure means a wrong key.

No setting default, on-disk format or validation change. That walk stops at the server's data path, so a store configured outside it still persists only its own entry; the local SQL-defined handler store (newer than this branch) has the same defect and gets its own PR.

test_sql_objects_fsync covers, per store, the create and drop directory fsync, a failed one failing the statement without leaving an unpersisted directory, and the corrupt-file startup path.


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

…urable

The disk storages for user-defined functions, named collections and workload
entities committed a create by renaming a temp file and a drop with fs::remove,
fsyncing only the temp file content (gated on fsync_metadata). An fsync of a
file's content does not persist its directory entry, and the commit rename, the
removal and the first-time directory creation were never followed by a
parent-directory fsync (the drop path did not read fsync_metadata at all). So an
acknowledged CREATE could vanish and an acknowledged DROP could revert after a
power loss.

Wrap the commit rename, the drop unlink and the initial directory creation with
LocalDirectorySyncGuard, gated on fsync_metadata. UDFs and workload entities take
the setting from the query context (the drop path uses the previously-unused
current_context); named collections use the global context, matching their
existing content fsync.

Also, NamedCollectionsMetadataStorage::getAll only caught Keeper ZNONODE, so a
corrupt/zero-byte local .sql file (which fsync_metadata=0 can leave via delayed
allocation) raised a parse error that propagated out of loadIfNot at boot and
failed server startup. Skip and log such a file for local storage (rethrowing for
replicated storage so ZooKeeper-backed collections are never silently dropped),
matching the user-defined-function and workload disk storages.

Add integration test test_sql_objects_fsync.

Closes: ClickHouse#111381

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With all three storages on local disk, ProfileEvents['DirectorySync'] per DDL query is 0 on every create/drop before the fix and >=1 after (at fsync_metadata=1), same config. Startup brick: a zero-byte named-collection .sql deterministically fails startup before, starts+skips after.
b Root cause explained? An fsync of a file's content does not persist its directory entry. The three disk stores fsynced only the temp file content; the commit rename, the fs::remove drop, and the first-time directory creation had no parent-directory fsync (the drop path did not read fsync_metadata). And NamedCollectionsMetadataStorage::getAll caught only Keeper ZNONODE, so a local parse error from a torn .sql propagated out of loadIfNot at boot and failed startup.
c Fix matches root cause? Yes. Wrap the commit rename, the drop unlink and the lazy directory creation with LocalDirectorySyncGuard (opens the parent dir O_DIRECTORY, fdatasyncs on scope exit), gated on fsync_metadata; and skip+log an unparseable local named-collection file at startup instead of aborting. Targets the mechanism, not a symptom.
d Test intent preserved / new tests added? New integration test test_sql_objects_fsync: DirectorySync per create/drop for all three families (a second create isolates the rename fsync from the mkdir fsync), and a torn named-collection file no longer bricks startup. No existing test weakened.
e Both directions demonstrated? Yes. Pristine build (Build ID 63b006a8): DirectorySync=0 on all 6 DDLs and startup bricks on a torn file. Fixed build: DirectorySync>=1 on all 6, startup starts+skips. Distinct Build IDs, same repro.
f Fix general across code paths? All three disk stores and both operations (create-rename AND drop-unlink) plus the lazy directory-creation edge in each. ZooKeeper/Keeper stores are deliberately untouched (they own their own durability).
g Fix generalizes across inputs? Path/argument-agnostic: fires for every object name, every entity type (FUNCTION/WORKLOAD/RESOURCE/NAMED COLLECTION), replace and no-replace renames, the first-create directory boundary, and multi-component new paths (each newly-created component's parent is synced). Honored under fsync_metadata=0 for UDFs/workloads. Startup skip is scoped to SYNTAX_ERROR on plain local storage (encrypted and replicated rethrow).
h Backward compatible? Yes. No setting default, on-disk/wire/replication format, or new validation change. Gated on the existing fsync_metadata (default true): default becomes durable (improvement); fsync_metadata=0 behavior unchanged for UDFs/workloads. Startup skip is strictly more permissive. No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. The directory guard is opened BEFORE each rename/removal (mirrors the existing guard-before-mutation pattern) so a guard-open failure never commits a disk change while reporting a failed DDL. getAll rethrows for replicated storage, for encrypted storage (a parse failure signals a wrong key, since the fingerprint is not validated pre-decryption), and for any non-SYNTAX_ERROR (I/O) error, so a present collection is never silently dropped.

Session id: cron:clickhouse-author-slot-3:20260722-143100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Independent code review (approach gate + code gate + one delta recheck). All findings adjudicated AGREE and fixed; each source fix was rebuilt (Build ID changed) and re-verified in both directions.

❌ Blockers

Finding Verdict Resolution
First acknowledged CREATE still vulnerable: stores create their subdir lazily, and syncing only the file's parent leaves the new subdir's own directory entry unpersisted. AGREE createDirectoriesAndSync fsyncs every newly-created path component's parent.
getAll blanket skip would change replicated semantics (it serves both local and ZooKeeper storage). AGREE Skip is scoped to non-replicated storage; ZooKeeper errors rethrow.
Directory guard opened AFTER the rename/removal could report a failed DDL after the disk mutation already committed (disk/memory divergence). AGREE Guard is now opened BEFORE each rename/unlink (mirrors the existing guard-before-mutation pattern); its destructor fsyncs after.
create_directories can create a whole chain, but only the leaf's parent was synced, leaving higher new components unsynced. AGREE Each newly-created component's parent is synced (deepest-first collection, shallowest-first fsync).
A wrong key for local_encrypted named collections decrypts to garbage → SYNTAX_ERROR, which the new skip would suppress, silently dropping every encrypted collection. AGREE Added isEncrypted(); encrypted storage always rethrows (its parse failure signals a wrong key, since the fingerprint is not validated before decryption).

⚠️ Majors

Finding Verdict Resolution
getAll catch (...) classified every local exception as corruption, so operational (I/O) errors could omit persisted collections. AGREE Narrowed to DB::Exception with code == SYNTAX_ERROR (unparseable content); all other errors propagate.
First write to a missing relative local-storage path failed (open("") on the empty parent) when directory syncing is enabled. AGREE fsyncParentDirectory syncs "." when the parent path is empty.
CREATE regression assertions could pass without the rename fsync, because the first create's directory-creation fsync alone bumps DirectorySync. AGREE The test now does a second create (directory already present) and asserts DirectorySync>=1 on that, isolating the rename fsync.

💡 Nits

Finding Verdict Resolution
The cited sibling PRs are open, not review-approved precedent. AGREE The description references the established parent-directory-fsync / guard-before-mutation pattern; sibling PRs are cited as related durability work.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @serxa @vitlibar — could you review this? It makes the three on-disk SQL-object stores (UDFs, named collections, workload entities) crash-durable by fsyncing the parent directory after the commit rename and after the drop unlink (gated on fsync_metadata), and makes a corrupt local named-collection file skip+log at startup instead of bricking the server. @serxa for WorkloadEntityDiskStorage; @vitlibar for named collections + UDFs.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bc77f01]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[s3] FAIL cidb
test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch[local] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[s3] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[azure] FAIL cidb
test_storage_iceberg_with_spark/test_bucket_partition_pruning.py::test_bucket_partition_pruning[local] FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED
Build (amd_freebsd) DROPPED
Build (ppc64le) DROPPED
Build (amd_compat) DROPPED
Build (amd_musl) DROPPED

AI Review

Summary

This PR moves the local UDF, named-collection, and workload stores onto a shared checked directory-fsync path and adds focused integration coverage around create/drop durability and corrupt local named-collection files. The current head fixes the earlier in-tree gaps, but two blocker-level durability holes remain in supported configurations, so it is not ready to merge.

Findings

❌ Blockers

  • [src/Disks/LocalDirectorySyncGuard.cpp:249-255] [dismissed by author -- https://github.com/Make on-disk SQL objects (UDFs, named collections, workloads) crash-durable #111423#discussion_r3974351422] createDirectoriesAndSync still falls back to syncing only created plus normalized when existing_root does not contain the configured store path. user_defined_path, workload_path, and named_collections_storage.path are supported configurable paths, so a later fsync_metadata=1 write can still acknowledge a CREATE or DROP inside an out-of-tree chain whose pre-existing ancestors were never persisted. That leaves acknowledged SQL-object DDLs crash-revertible in supported setups. Suggested fix: either reject out-of-tree local SQL-object paths when fsync_metadata=1, or persist the full existing ancestor chain up to an explicit durable boundary outside path.
  • [src/Common/SQLDefinedHandlers/SQLDefinedHandlersMetadataStorage.cpp:139-169] [dismissed by author -- https://github.com/Make on-disk SQL objects (UDFs, named collections, workloads) crash-durable #111423#discussion_r3928208210] The newer local handler store still uses bare create_directories, temp-file rename, and fs::remove with no checked parent-directory fsync. query_rules_storage.type defaults to local, and the docs advertise the local path, so CREATE and DROP HANDLER still have the same acknowledged-create-loss / acknowledged-drop-revert failure mode this PR is fixing for the other local SQL-object stores. Suggested fix: move SQLDefinedHandlersMetadataStorage::LocalStorage onto the same createDirectoriesAndSync + CheckedDirectorySync path and cover it in a handler-focused durability test.
Final Verdict

Changes requested. The in-tree UDF, named-collection, and workload paths look fixed, but the branch still leaves supported local SQL-object storage on crash-vulnerable paths.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
The createDirectoriesAndSync helper added by the fsync fix uses a small
transient std::vector<fs::path> to collect the not-yet-existing directory
components (bounded by the configured path depth). fs::path is not
trivially relocatable, so there is no drop-in *WithMemoryTracking variant;
add the sanctioned STYLE_CHECK_ALLOW_STD_CONTAINERS marker, matching the
40+ existing precedents in src/Functions. Applied to all three disk stores
so the identical helper does not diverge across the files.

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

clickhouse-gh Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 118/135 (87.41%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 95d3f7c

Every failure below has an owner: a fixing PR (ours or external). This PR's own diff (crash-durable on-disk SQL objects: UDFs, named collections, workloads) does not touch the Replicated-database structure-alter path, so the failure is not PR-caused.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky / master-wide regression since 2026-07-10 (626 PRs / 30d, 123 master; umbrella #110036) #111029 (external, open, Closes #110036)

Session id: cron:our-pr-ci-monitor:20260723-040000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 95d3f7c

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_database::test_replicated_table_structure_alter flaky, master-wide regression since 2026-07-10 (tracked #110036; ~123 master hits/30d; not in this PR's diff) #111029 (external, open) - @tiandiwonder root-cause write-side fix, Closes #110036
PR aggregate reflecting the integration failure above clears when #111029 lands
CH Inc sync - CH Inc sync (private, not actionable by us)

Session id: cron:our-pr-ci-monitor:20260723-050000

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Aug 19, 2026
@serxa serxa self-assigned this Sep 2, 2026
@serxa

serxa commented Sep 2, 2026

Copy link
Copy Markdown
Member

@groeneai two changes before this is ready — both about the new fsync helpers, not the durability logic itself:

1. De-duplicate the directory-sync helpers. fsyncParentDirectory and createDirectoriesAndSync are copy-pasted into all three storages (NamedCollectionsMetadataStorage.cpp, WorkloadEntityDiskStorage.cpp, UserDefinedSQLObjectsDiskStorage.cpp), and the named-collections copy has already diverged (it has no std::error_code overload and uses the throwing fs::create_directories). Please factor them into a single shared helper — a natural home is alongside LocalDirectorySyncGuard in src/Disks/, which all three translation units already include. Expose one implementation and let the throwing vs error_code call sites wrap it.

2. Make a failed directory fsync fail the DDL. The parent-directory fsync currently rides the LocalDirectorySyncGuard destructor, which logs and swallows any fdatasync/close error. So if the directory sync itself fails, the CREATE/DROP still returns success — i.e. we acknowledge a write we could not make durable, which defeats the point of the fix. Please fsync the directory explicitly after the rename/unlink and check the result, throwing on failure rather than relying on the swallow-in-destructor. (The swallow pattern is fine and intentional elsewhere, e.g. MergeTree, so this is a deliberately stricter choice for this DDL path rather than a change to the shared guard.)

The rest looks sound: the content-fsync → rename → dir-fsync ordering, opening the dir before the mutation, the per-store fsync_metadata gating, and the plain-local-only SYNTAX_ERROR skip on startup all check out.

groeneai and others added 5 commits September 2, 2026 21:02
…fails

Review feedback on the on-disk SQL-object durability fix.

The parent-directory fsync helpers were copy-pasted into all three disk stores,
and the named-collections copy had already drifted (no error_code overload, and
the throwing fs::create_directories). They now live next to
LocalDirectorySyncGuard in src/Disks/, which all three translation units already
include, with one implementation and a throwing wrapper for the call site that
wants an exception rather than an error_code.

The parent-directory fsync also rode the LocalDirectorySyncGuard destructor,
which logs an fdatasync or close failure and drops it. A CREATE or DROP could
therefore report success after failing to persist the directory entry, which is
the outcome the fsync exists to prevent. CheckedDirectorySync still opens the
directory before the mutation, so a directory that cannot be opened does not
leave the mutation committed, but the sync is now an explicit call whose failure
propagates and fails the DDL. This is deliberately stricter than the shared
guard, which keeps its best-effort behaviour for MergeTree and its other
callers.

The new `directory_sync_fail` failpoint makes that contract testable: without
it, a test can only observe the happy path and cannot tell a propagating sync
from a swallowed one. The integration test now checks that a failed directory
sync fails both a create and a drop in each of the three stores, since a shared
helper is exactly the kind of change that can silently stop syncing one store.

Co-Authored-By: Claude Opus 5 <[email protected]>
…e sync ordering

Two gaps found while reviewing the previous commit.

A directory created for a store was kept even when persisting its entry in its
parent failed. The next call would then see it already present, collect nothing
to persist, and sync only the file's own directory after the commit rename, which
does not persist that directory's entry in its parent. The CREATE it then
acknowledged could still be lost together with the directory, which is the bug
this whole change exists to prevent. Directories this call created are now
removed again when a sync fails, so a retry starts over. A directory that is no
longer empty belongs to a concurrent writer, so removing it fails and keeps it.

The test could not see where the sync happens: an exception is raised whether the
sync runs after the mutation it persists or before it. It now also checks the
file state at the point of failure, so a create that failed has already renamed
its `.sql` into place and a drop that failed has already unlinked it. The
workload store is configured two levels down, and a separate case removes it and
injects a failure, so directory creation is covered on a multi-component path
rather than only the commit rename with the directory already present.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ip log

Three oracles in the durability tests were weaker than the properties they name.

Matching store files by substring also matched the `.sql.tmp` file that a create
leaves behind when it fails before its rename, so the named-collection case would
have accepted a sync that runs before the rename instead of after it. The tests
now name the exact committed path.

The rollback case only checked that the retry created the resource, which stays
true if just one component of the nested chain is synced. It now counts the
directory syncs, so all three components plus the commit rename have to be
covered.

Skipping a corrupt named collection at startup is only safe because it is logged,
and nothing checked that the message is emitted.

Co-Authored-By: Claude Opus 5 <[email protected]>
Each of the four new comment blocks restated why the change was made, which the
commit messages already carry. They now state only what is not visible at the
call site: that a directory kept after a failed sync is treated as already
created by the next call, that a parse failure on encrypted storage means a wrong
key rather than corruption, and how the explicit sync differs from the
best-effort guard beside it.

Co-Authored-By: Claude Opus 5 <[email protected]>
A syntax error quotes the text it failed to parse. A named-collection metadata
file holds credentials in plaintext, so a corrupt one skipped at startup could
copy part of a secret into the server log. Only the collection name and the error
code are logged now, which is what identifies the file to repair.

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

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

@serxa Both done, in 65acf18.

1. Shared helper. The parent-directory sync and createDirectoriesAndSync now live once, in src/Disks/LocalDirectorySyncGuard.{h,cpp}, which all three stores already included. There is one implementation; the throwing and std::error_code forms are thin wrappers over it, so the named-collections divergence is gone. The three STYLE_CHECK_ALLOW_STD_CONTAINERS markers went with it, since src/Disks is not in the std-container lint's directory list.

2. Checked directory fsync. CheckedDirectorySync opens the directory before the mutation, as before, but the sync is now an explicit call whose fdatasync/close failure propagates and fails the statement. LocalDirectorySyncGuard itself is untouched, so MergeTree and its other callers keep the best-effort behaviour. A directory_sync_fail failpoint makes that contract testable: without it a test can only observe the happy path and cannot tell a propagating sync from a swallowed one.

Verified per store, both directions: with the failpoint enabled a create and a drop each fail for all three stores, and the file state at the failure pins the sync after the rename or unlink rather than before it. As a check on exactly the risk you named, removing the sync() call from only the workload store reddens both the new test and the existing DirectorySync assertions.

Also, the corrupt-file skip used to log the parse exception, and a syntax error quotes the text it failed on, which for a named collection is credentials. It now logs the name and error code only.

Two things I hit while doing this. The second is your call:

  • A create or drop that fails at the sync has already renamed or unlinked its file, so disk and the in-memory view disagree until restart. That is inherent to failing closed, and the tests pin it rather than hide it.
  • A store directory first created with fsync_metadata=0 is never synced later, so a subsequent fsync_metadata=1 create is acknowledged while the directory's own entry may not be durable. Closing that means either an extra directory fsync per DDL, or syncing at directory creation even when the setting is off. I did not want to pick either silently, so it is noted as a known gap in the description. I can do it here or in a follow-up, whichever you prefer.

@serxa serxa left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, take care of conflicts and this can be merged

The only conflict was the APPLY_FOR_FAILPOINTS macro list in
src/Common/FailPoint.cpp, where master and this branch each appended an
entry next to REGULAR(lazy_pipe_fds_fail_close).

Resolution keeps master's REGULAR(claim_inject_stale_part_dir) and this
branch's REGULAR(directory_sync_fail), and drops
ONCE(create_empty_part_inject_stale_dir): master renamed that failpoint
to claim_inject_stale_part_dir, moving its declaration and both
MergeTreeData.cpp uses together, so keeping the old name would resurrect
a failpoint with no callers.

Verified by comparing the declared-name sets: nothing master declares is
missing from the merged file, and the only name it adds over master is
directory_sync_fail. The merged tree differs from the merged master
commit in exactly the twelve files this pull request touches, with no
submodule pin drift.
…emporary file on failure

Two error paths of the new durability code could leave state that makes a
later attempt worse than the first one.

fs::create_directories is allowed to create some components before it
reports a failure. createDirectoriesAndSync returned on that error without
syncing or removing them, and the next call recollects only the components
that are still missing, so a component left behind would never have its
entry persisted while an object created inside it is acknowledged. The
components are now undone on that path too, reusing the removal the sync
failure path already performed.

The named collection store opens its temporary file with O_EXCL and, unlike
the user-defined function and workload stores, did not remove it when the
write, the rename or the directory sync raised. Opening the parent directory
and syncing it are new raise points between creating that file and renaming
it away, so a transient failure there would have made every later CREATE or
ALTER of the same collection fail with a file that already exists. It now
removes the temporary file on an exceptional exit, like its two siblings.

Neither path is reachable from the integration suite, which cannot make
create_directories fail halfway or make a directory unopenable; both restore
symmetry with code paths that already handle the same failure.
The startup skip of a corrupt local named-collection file reports the error
code and not the parser message, because the message quotes the text it
failed on. The test asserted only that the skip is logged, so restoring the
message would have kept it green.

The malformed file now ends inside a quoted credential, which is what a torn
write produces, and the test asserts the credential is absent from the log.
The position matters: the message quotes the failure position, so a secret
placed earlier in the file never appears and the assertion would hold for the
wrong reason. Verified by logging the message again, which puts
"failed at position 59 ('sentinel_secret_..." in the log and fails the
assertion.
The previous commit also undid the directory components collected for creation
when create_directories itself reported an error. Membership of that list comes
from fs::exists, which follows symlinks, so a configured path that is a symlink
to a missing target is absent to the scan, makes create_directories fail with
an already-exists error, and would then have been removed. Deleting a path put
there by the configuration is worse than the case that change addressed, where
a component left by a failed attempt keeps its entry unsynced while a later
attempt succeeds, so that path is restored to returning the error untouched.

Removing only components this call created needs create_directory per
component rather than create_directories, which changes how the reviewed
directory-creation path works; that is left to the reviewer.
@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

@serxa conflicts resolved, merged master at df8d7ac753f08afcddf484bb9568f7e9fec5f36e. mergeable is back to MERGEABLE.

The only conflict was the APPLY_FOR_FAILPOINTS list. Master had renamed create_empty_part_inject_stale_dir to claim_inject_stale_part_dir, moving the declaration and both MergeTreeData.cpp uses together, so I kept master's name plus mine and dropped the old one rather than keeping both sides. system.fail_points in the rebuilt binary registers 339 entries, and nothing master declares is missing. test_sql_objects_fsync passes after the merge.

Two things I fixed while re-checking, both mine:

  • The named collection store opens its temporary file with O_EXCL and, unlike the user-defined function and workload stores, did not remove it when the write, the rename or the new directory sync raised. Opening the parent directory and syncing it are new raise points between creating that file and renaming it away, so a transient failure there made every later CREATE or ALTER of that collection fail on a file that already exists. It now removes it on an exceptional exit, like its two siblings.
  • The corrupt-file skip test asserted only that the skip is logged, so restoring the parser message would have stayed green. The file is now torn inside a credential, which is what a power loss produces, and the test asserts the credential is absent from the log. Restoring the old logging puts failed at position 59 ('sentinel_secret_... in the log and fails the assertion.

Two I did not decide on my own, because one remedy covers both and it changes the directory creation path you reviewed:

  • a partial fs::create_directories failure leaves an ancestor behind, and a later successful DDL excludes it from the scan and never syncs its entry;
  • the sync-failure rollback derives ownership from the pre-operation existence scan, so it can remove an empty component another actor created in between.

Creating the components one at a time with fs::create_directory and rolling back only the ones this call created fixes both. I can do that here or in a follow-up, whichever you prefer, along with the fsync_metadata 0 to 1 question in the description.

Comment thread src/Disks/LocalDirectorySyncGuard.cpp Resolved
Comment thread src/Disks/LocalDirectorySyncGuard.cpp Outdated
ProfileEvents::increment(ProfileEvents::DirectorySyncElapsedMicroseconds, watch.elapsedMicroseconds());
}

void createDirectoriesAndSync(const String & dir, bool fsync, std::error_code & ec)

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 sweep leaves the remaining local SQL-metadata store on the old crash-vulnerable path: SQLDefinedHandlersMetadataStorage::LocalStorage still does create_directories + temp-file rename / bare fs::remove with only out.sync() (src/Common/SQLDefinedHandlers/SQLDefinedHandlersMetadataStorage.cpp:146-169).

So CREATE/DROP HANDLER with query_rules_storage.type=local can still acknowledge an unpersisted directory entry even when fsync_metadata=1, and vanish/reappear after a power loss for the same reason this PR fixes UDFs, named collections, and workloads. Since this helper is now the shared durability mechanism for local SQL-object stores, I think handlers need to move onto it in the same PR.

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.

Major, and correct. LocalStorage::write fsyncs the content (out.sync()) but nothing after fs::rename, and removeIfExists is a bare fs::remove that never reads fsync_metadata.

Measured on this branch's binary, one server, fsync_metadata=1 on every statement, and with no query_rules_storage section in the config at all, so this is the default local handler store:

DDL DirectorySync FileSync
CREATE FUNCTION / DROP FUNCTION 2 / 1 1 / 0
CREATE NAMED COLLECTION / DROP NAMED COLLECTION 2 / 1 1 / 0
CREATE HANDLER / DROP HANDLER 0 / 0 1 / 0

FileSync = 1 on the handler create shows the setting was on, so the zero is specifically the missing directory sync. Handlers are a real fourth instance of this defect.

Not in this PR, though. src/Common/SQLDefinedHandlers/ did not exist at this branch's base: master added it on 2026-07-29, a week after this PR opened, and it arrived here through today's master merge, after the current scope had been reviewed. It also needs its own family in test_sql_objects_fsync, plus the temporary-file cleanup the named-collections store turned out to need once a checked sync added raise points inside its O_EXCL window, which is a further change to a file this PR does not touch.

A fix task is created for it, and I will post the fixing-PR link in this thread when it opens.

@clickhouse-gh

clickhouse-gh Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bc77f011f with master c7a9fe7c9 (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.

Object file sizes

24 object files changed (+60.36 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/LocalDirectorySyncGuard.cpp.o 54.33 KiB 93.82 KiB +39.49 KiB (+72.69%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

14 translation units recompiled, 30 s compile time in total, 14 of them have a recent master baseline.

Job report

@clickhouse-gh clickhouse-gh Bot added the comp-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... label Sep 4, 2026
@serxa

serxa commented Sep 9, 2026

Copy link
Copy Markdown
Member

@groeneai continue work here

…what a rollback removes

Two things about the lazy creation of a store directory, both left to the reviewer until now.

Only a directory this call created was persisted. A store directory created earlier by a
write with fsync_metadata disabled therefore kept an entry that was never persisted, so an
object a later enabled write acknowledged could still be lost together with the directory
holding it. An enabled write now persists the store directory's own entry as well, whoever
created it: DirectorySync per create with the directory already present goes from 1 to 2,
its entry and the commit rename.

fs::create_directories does not report which components it created, so the rollback that
removes a directory whose entry could not be persisted took ownership from an existence
scan made before the call, and could remove a component another writer created in between.
fs::create_directory per component reports it exactly, so only what this call created is
removed. That also makes rolling back a creation that fails halfway safe: the component the
failure is about is never in that set, so a configured path that is a symlink to a missing
target, which the scan reports as absent and mkdir then rejects, is left alone. Such a path
used to stay half made, and the next call took the components already there for finished
ones and never persisted their entries.

The store-directory sync precedes the object write, so a create whose directory syncs all
fail now stops before its rename. The integration test's create-side ordering assertion
becomes that state, and its drop path keeps the witness that a sync follows the mutation it
persists. Its create counts move from one directory sync to two, since one of the two alone
would leave the other unproven.

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

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Both here, in 8716b65d, as one commit on top of the head you approved.

Directory creation. Components are created one at a time with fs::create_directory, so the call knows exactly which ones it created and removes only those when a sync fails, never an empty component another writer created in between. That also makes rolling back a half-made path safe again (the thing I backed out last round): the component the failure is about is never in that set, so a configured path that is a symlink to a missing target is left alone rather than deleted.

fsync_metadata 0 to 1. An enabled write now persists the store directory's own entry too, whether it created the directory or an earlier disabled write did. Measured on one binary, with the store directory created by a disabled create: DirectorySync on the next enabled create is 2 (that entry plus the commit rename); with only that sync disabled it is 1 and the new test case fails.

That sync precedes the object write, so with directory_sync_fail armed a create now stops before its rename rather than after it. The create side of test_failed_directory_sync_fails_the_ddl asserts that state (nothing committed, no temporary file left), the drop side is unchanged, and the create counts in test_sql_object_writes_are_fsynced went to >= 2, so neither of the two syncs alone satisfies them.

Not chased, noted in the description: for a store configured several levels deep, only its own entry is persisted this way, not its ancestors'. Doing the whole chain would fsync directories above the data path on every DDL.

test_sql_objects_fsync is 5/5 locally and the style legs are clean. I will report back here when CI finishes.

Comment thread src/Disks/LocalDirectorySyncGuard.cpp Resolved
groeneai and others added 3 commits September 9, 2026 21:05
…leaf

A write that ran with fsync_metadata=0 creates every missing component of the
store path and persists none of them. The recovery added for a later enabled
write only persisted the store directory's own entry, so on a store configured
below one level the directories holding it stayed unpersisted and power loss
could still drop one and take the acknowledged object with it.

Measured on the test config's three-level workload store
(<path>/workload/entities/local): creating the store from nothing syncs 4
directories (one per component, plus the commit rename), while an enabled write
into a chain a disabled write had created synced only 2. The same contract now
holds either way.

The walk needs a directory to stop at, since which components an earlier call
created cannot be recovered from the filesystem. The callers pass the server's
data path, which no create reaching this helper makes: ancestors are persisted
down from it, shallowest first, so a directory only becomes durably visible
after the one holding it, and nothing above it is ever opened. A configured
store path outside the data path has no such boundary and keeps persisting its
own entry alone.

Walking to the filesystem root instead was rejected: the sync is fail-closed by
design, so it would make every DDL depend on fsyncing directories the server
does not own.

The test's assertion is raised from >= 2 to >= 4 for the same reason the
creation-path test already counts 4. At >= 2 it was satisfied by persisting the
leaf alone, so it could not tell the two behaviours apart.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit only walked the chain when the store directory itself was
already present. A path whose parents exist but whose leaf does not is the same
situation: the parents' entries are no more persisted than the leaf's, and
`mkdir -p` of the parents before starting the server is an ordinary way to
arrive there.

Measured on the three-level workload store with only the parents pre-created:
2 directory syncs before, 4 after, the same as when the whole path was already
there. The one-level shipped defaults stay at 2 for a create and 1 for a drop,
and fsync_metadata = 0 stays at 0.

Who created a component turns out not to matter, so the two sync loops collapse
into one walk of the whole path below the root. This also covers a component
another process created between the existence check and the create, which the
per-component ownership tracking treated as somebody else's to persist. The
tracking is still needed to decide what a rollback may remove.

Co-Authored-By: Claude Opus 5 <[email protected]>
A configured store path equal to the server data path made the walk fall through
to the no-boundary case, which persists the store directory's own entry, so it
opened the data path's parent. Nothing above the root is this protocol's to
persist, and the header says so.

Distinguishing "contained, nothing below" from "not contained" needs the
containment answer separately from the list, hence the optional.

Measured with user_defined_path set to the data path, on one CREATE FUNCTION
with fsync_metadata = 1: 2 directory syncs before and 1 after, and with
directory_sync_fail armed the reported path moves from the data path's parent to
the data path itself, so the boundary now holds where the header claims it. No
test is added for it: the case needs a second server instance configured to keep
SQL-object files directly in the data path, while the invariant it would pin is
already counted by the three-level store.

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-multidisk Multiple disks/volumes storage policies, disk abstractions. and removed comp-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... labels Sep 9, 2026
Comment thread src/Disks/LocalDirectorySyncGuard.cpp Resolved
createDirectoriesAndSync bounds its walk at the server data path, but the two
paths reach it from different configuration plumbing: a store path is passed
through weakly_canonical() by its caller, while getCanonicalPath() canonicalizes
<path> only when it is relative, so an absolute one keeps its symlinks and ..
segments. The lexical comparison then never matched, the walk fell through to
the no-boundary fallback, and a store configured below a symlinked <path> only
had its own entry persisted.

Measured on a nested workload store, DirectorySync per DDL at fsync_metadata=1,
recovering a chain left by an fsync_metadata=0 write: 2 syncs with a symlinked
<path> against 4 with a plain one; 4 in both after this change. Counts for a
plain <path>, for creation from nothing and for fsync_metadata=0 are unchanged.

Both paths are resolved or neither is used. Resolving one alone could miss a
containment that the two spellings would have matched, which would persist less
than comparing them unresolved, so a resolution failure keeps the old
comparison rather than narrowing the walk or failing the statement: what it
cannot do is make a DDL fail because a data path would not canonicalize.

The parents-exist-leaf-missing case in the test used mkdir -p <dir>/.., which
has to create <dir> as an intermediate component before it can resolve .., so
that branch was the whole-path-exists case again and stayed green when only the
partial-prefix path regressed. It now names the parents and asserts the leaf is
absent first. Verified against a build with that walk cut back to the leaf: the
new form fails, the old one passes.

Co-Authored-By: Claude Opus 5 <[email protected]>
auto below = componentsBelow(resolved_dir, resolved_root);
if (!below)
{
/// Nothing bounds the walk, so persist only what is known to be owed here: the

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.

createDirectoriesAndSync still loses crash durability when the configured store path is outside Context::getPath(). In the !below fallback we only sync created (or just normalized when the whole chain already exists). A concrete trace is workload_path=/mnt/sql_objects/workload/entities/local/: let an fsync_metadata=0 CREATE RESOURCE build that chain, then run another CREATE RESOURCE with fsync_metadata=1. componentsBelow() returns nullopt, created is empty, so this helper syncs only .../entities (persisting local) and the later rename path syncs only local. workload/ and entities/ themselves are still unpersisted, so the acknowledged DDL can still disappear with one of those ancestors after a power loss.

Because user_defined_path, workload_path, and named_collections_storage.path are valid outside path, I think this fallback needs to resync the whole existing chain up to a durable boundary, or those out-of-tree configurations need to be rejected when fsync_metadata=1.

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, and measured. With <workload_path> three levels under an operator-provisioned sql_objects/ and <path> elsewhere, DirectorySync per DDL at fsync_metadata=1:

case syncs
creation from nothing 4
recovery after an fsync_metadata=0 write 2
parents pre-created by the operator, leaf absent 2

With directory_sync_fail armed the first sync of the recovery case names sql_objects/workload/entities, so workload/ is never synced, exactly as your trace says. That is the residual the description already carves out: "That walk stops at the server's data path, so a store configured outside it still persists only its own entry."

The measurement does narrow it. Creation from nothing is fully persisted out of tree as well, and there the first sync names sql_objects/ itself, so every component the call creates is covered. What stays uncovered is only a component that already existed when the enabled call ran: either an fsync_metadata=0 write created it, and that write opted out of metadata durability, or the operator created it, which puts it in the same category as <path> itself.

On the two remedies. Resyncing the whole existing chain has no stopping point out of tree: componentsBelow returns nullopt precisely because no directory there is known to predate the store, so the walk would run to /, and since a failed sync now fails the statement that makes CREATE RESOURCE depend on fsyncing /mnt and /. Rejecting out-of-tree paths is not a durability fix but a compatibility change: fsync_metadata defaults to true, so it would refuse configurations that work in released versions.

Both are calls I do not think I should make unilaterally on a PR that is already approved, and this is my fourth round on this one, so I am leaving the choice to a human.

@clickhouse-gh clickhouse-gh Bot added comp-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... and removed comp-multidisk Multiple disks/volumes storage policies, disk abstractions. labels Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ac5f259

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
Fast test (arm_darwin) / 05076_error_trace_file_offsets oracle column 2 (countIf(x > (SELECT max(address_end) FROM system.symbols)) > 0) is unsatisfiable on Darwin by construction: StackTrace::resolveAddress is compiled only under __ELF__, so Darwin stores raw runtime addresses, while the Mach-O collector extends each dyld image's last symbol to that image's max_addr, putting the bound above every captured frame. The test carries no Tags: line, so it runs on the darwin Fast test. Not caused by this PR, whose diff is the on-disk SQL-object write path; the test has never passed on this arm since my #117449 merged #119145 (mine, open) tags the test no-darwin
Mergeable Check aggregator reflecting the Fast test (arm_darwin) red above #119145 (mine, open)
PR workflow aggregator reflecting the Fast test (arm_darwin) red above #119145 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260910-053056

@clickhouse-gh

clickhouse-gh Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Dear @serxa, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

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-disk-abstractions Core disk abstractions: IDisk interface, DiskLocal, storage policies, volumes, disk management to... groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

3 participants