Repository navigation
Conversation
…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]>
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-author-slot-3:20260722-143100 |
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 |
|---|---|---|
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. |
|
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 |
|
Workflow [PR], commit [bc77f01] Summary: ❌
AI ReviewSummaryThis PR moves the local UDF, named-collection, and workload stores onto a shared checked directory- Findings❌ Blockers
Final VerdictChanges 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. |
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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 118/135 (87.41%) · Uncovered code |
CI finish ledger — 95d3f7cEvery 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.
Session id: cron:our-pr-ci-monitor:20260723-040000 |
CI finish ledger — 95d3f7cEvery failure below has an owner. Only
Session id: cron:our-pr-ci-monitor:20260723-050000 |
|
@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. 2. Make a failed directory fsync fail the DDL. The parent-directory fsync currently rides the The rest looks sound: the content-fsync → rename → dir-fsync ordering, opening the dir before the mutation, the per-store |
…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]>
|
@serxa Both done, in 1. Shared helper. The parent-directory sync and 2. Checked directory fsync. 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 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:
|
serxa
left a comment
There was a problem hiding this comment.
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.
|
@serxa conflicts resolved, merged master at The only conflict was the Two things I fixed while re-checking, both mine:
Two I did not decide on my own, because one remedy covers both and it changes the directory creation path you reviewed:
Creating the components one at a time with |
| ProfileEvents::increment(ProfileEvents::DirectorySyncElapsedMicroseconds, watch.elapsedMicroseconds()); | ||
| } | ||
|
|
||
| void createDirectoriesAndSync(const String & dir, bool fsync, std::error_code & ec) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes24 object files changed (+60.36 KiB total), 0 added.
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units14 translation units recompiled, 30 s compile time in total, 14 of them have a recent master baseline. |
|
@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]>
|
Both here, in Directory creation. Components are created one at a time with
That sync precedes the object write, so with 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.
|
…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]>
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
CI finish ledger - ac5f259Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260910-053056 |
|
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. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Make on-disk SQL objects crash-durable.
CREATE/DROPof 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 onfsync_metadata, default enabled), so an acknowledgedCREATEno longer vanishes and an acknowledgedDROPno 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) andWorkloadEntityDiskStoragecommitted a create by renaming<object>.sql.tmpinto place and a drop withfs::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 readfsync_metadata. An fsync of a file does not persist its directory entry, so after a power loss an acknowledgedCREATEcould disappear and an acknowledgedDROPcould 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'smkdir -p, is no more durable than the object inside it. A failed sync fails the statement instead of being logged and dropped.LocalDirectorySyncGuardis untouched, so its other callers stay best-effort. Gated onfsync_metadata(default enabled), read from the query context except for named collections (global).NamedCollectionsMetadataStorage::getAllalso only caught KeeperZNONODE, so a corrupt or zero-byte local.sqlfile 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_fsynccovers, 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]