Skip to content

Fsync access entities in DiskAccessStorage to survive power loss - #111346

Merged
alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-68958-diskaccessstorage-fsync
Oct 31, 2026
Merged

alexey-milovidov merged 10 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-68958-diskaccessstorage-fsync

Conversation

@groeneai

@groeneai groeneai commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #68958

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

Access entities stored on local disk (users, roles, grants, quotas, row policies, settings profiles created via SQL) are now fsync'd when fsync_metadata is enabled, so an acknowledged CREATE/ALTER/DROP USER (and GRANT/REVOKE) is no longer silently lost on power loss. Previously DiskAccessStorage wrote and removed the .sql entity files without any fsync.

Description

On 26.9 (and every earlier release), an acknowledged CREATE USER + GRANT on the default local_directory access storage can vanish after a power loss: neither the <uuid>.sql file nor its rename is forced to disk, and the user then fails with AUTHENTICATION_FAILED (reproduced 3/3 with dm-flakey in #68958). DiskAccessStorage was the only on-disk DDL-entity store ignoring fsync_metadata.

Fix, gated on fsync_metadata (default true; the session value on the query thread, the global one otherwise):

  • writeEntityFile fsyncs the file, renames it, then fsyncs the directory; deleteAccessEntityOnDisk fsyncs the directory after the unlink. The directory is opened before each change. A failed directory fsync after the change is only logged, as for the other LocalDirectorySyncGuard users: the access storages and their callers take an exception as "nothing has changed".
  • need_rebuild_lists.mark, which makes the next start rescan the .sql files instead of trusting the .list index, is fsynced with its directory, and writeListFile fsyncs the .list files.
  • The .list files are rewritten later by a background thread that has no query context, so pending_lists_fsync carries to it the strongest requirement of the changes made meanwhile, and a rebuild that finds a mark left by earlier changes always fsyncs the lists before removing the mark. As the .list files on disk may be unsynced, a GRANT or password change at fsync_metadata 1 also goes through the mark.

tests/integration/test_access_storage_fsync checks the FileSync/DirectorySync ProfileEvents of each statement with fsync_metadata 1 and 0, the session requirement carried to the deferred .list write, the mark-driven rebuild, and that the mark is what makes a stale .list recoverable on restart. Each assertion fails with the mechanism it covers removed. It is an integration test because stateless tests use the <memory/> access storage.


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

Version info

  • Merged into: 26.11.1.965-master (included in 26.11 and later)

DiskAccessStorage wrote access-entity .sql files (and the *.list index
files), and removed them, without any fsync. An acknowledged CREATE/ALTER/
DROP USER or GRANT/REVOKE could therefore be silently lost on power loss:
the tmp->final rename was never forced to disk, so the <uuid>.sql file
disappears and the user cannot authenticate after restart. It was the only
on-disk DDL-entity store not honoring fsync_metadata.

Gated on fsync_metadata (default true), matching UDF/named-collection/
workload/table-metadata stores:
- writeEntityFile (create/update): fsync the file content, then fsync the
  parent directory around the rename (a rename is durable only once the
  directory entry is persisted).
- deleteAccessEntityOnDisk (DROP/REVOKE, old-file removal on replace): fsync
  the parent directory around the unlink.
- writeListFile: fsync the file content (.list files are rebuilt from the
  .sql files, so no directory fsync).

The parent-directory fsync reuses LocalDirectorySyncGuard. The setting is
resolved from the query context and falls back to the global context for the
background .list writer, mirroring getWriteSettings().

Adds integration test test_access_storage_fsync asserting the FileSync/
DirectorySync path via system.query_log ProfileEvents (integration, because
stateless tests override the access storage to <memory/>).

Closes: ClickHouse#68958

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

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Run access DDL with a query_id, SYSTEM FLUSH LOGS query_log, read ProfileEvents['FileSync']/['DirectorySync']. On baseline HEAD every op shows 0/0 even with fsync_metadata=1; with the fix create/grant/alter show file+dir sync and drop shows dir sync. On demand, not probabilistic.
b Root cause explained? Yes. writeEntityFile wrote a tmp file, close()d it, then renamed without syncing the file content OR the parent directory. A rename is a directory-entry change that is not durable until the directory is fsync'd, so a power loss loses the <uuid>.sql file. Same gap for updates (rewrite) and removals (unlink is also a directory-entry change), and for the .list writer.
c Fix matches root cause? Yes. Adds out.sync() (file content) before close AND a LocalDirectorySyncGuard (fdatasync of the parent dir) around the rename (writeEntityFile) and the unlink (deleteAccessEntityOnDisk); .list gets a file-content fsync. All gated on fsync_metadata. Targets the lost-rename mechanism directly, not a symptom.
d Test intent preserved / new tests added? Yes. New integration test test_access_storage_fsync asserts the fsync path is taken for CREATE/GRANT/ALTER/DROP and for .list writes (SYSTEM RELOAD USERS), and that fsync_metadata=0 takes neither. Integration (not stateless) because stateless tests override access storage to <memory/>. No existing test weakened.
e Both directions demonstrated? Yes. Both test functions FAIL on baseline HEAD (CREATE USER: 0, 0; list files not fsynced on RELOAD USERS: FileSync=0) and PASS with the fix. Binaries were Build-ID-verified distinct.
f Fix is general across code paths? Yes. Covers all three DiskAccessStorage disk paths: writeEntityFile (create+update), deleteAccessEntityOnDisk (remove), writeListFile (index). Scope limited to DiskAccessStorage on purpose (one concern per PR); sibling stores already fsync.
g Fix generalizes across inputs? Yes. All access-entity types (user/role/quota/profile/row-policy) route through the same write/remove functions, so the durability fix is type-independent; no datatype/type-wrapper dimension applies (filesystem durability, not query typing). Both fsync_metadata values tested.
h Backward compatible? Yes. No format/protocol/setting-default change. fsync_metadata already exists (default true); behavior only becomes more durable under the default, and fsync_metadata=0 preserves the previous no-sync behavior exactly. No SettingsChangesHistory entry needed.
i Invariants and contracts preserved? Yes. Standard tmp->fsync->rename->dir-fsync ordering (matches LocalDirectorySyncGuard prior art); the guard is opened before the mutation and fsyncs in its destructor per its close-reopen-fsync note. The existing SCOPE_EXIT tmp cleanup and the "modify files first, then memory" ordering are untouched. The guard destructor is noexcept (logs on failure) so a successful rename is never turned into a throw; the file-content out.sync() does throw before the rename, correctly aborting a non-durable write.

Session id: cron:clickhouse-author-slot-0:20260722-084600

@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; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test did not exercise the new .list file fsync (writeListFile) AGREE — fixed .list writes run off the query thread (background 1-min timer / shutdown), so they don't attribute to DDL queries. SYSTEM RELOAD USERS -> reloadAllAndRebuildLists() -> writeLists() runs synchronously on the query thread, so its FileSync event covers the path. Added test_list_files_are_fsynced (test-only); re-verified both directions on Build-ID-distinct binaries: baseline FAILS (FileSync=0), fix PASSES.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-author-slot-0:20260722-084600

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pufit @kcmannem — could you review this? It makes DiskAccessStorage fsync access-entity .sql writes/removals and the .list index (gated on fsync_metadata, matching the UDF/named-collection/table-metadata stores), so an acknowledged CREATE/ALTER/DROP USER isn't silently lost on power loss (#68958). The key point is the parent-directory fsync around the rename/unlink, since that's what makes the operation durable.

@zlareb1 zlareb1 added the can be tested Allows running workflows for external contributors label Jul 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e83997b]

Summary: ✅


AI Review

Summary

The PR makes local access-entity writes and removals in DiskAccessStorage honor fsync_metadata, durably records the rebuild marker, and preserves the strongest pending sync requirement for deferred .list writes and restart recovery. The latest change also protects name-preserving updates after an earlier unsynced list rewrite has completed. All prior findings are addressed in head e83997b47a1a2406f4a435cb3d434b64bef31892; no new actionable findings remain.

Missing context / blind spots
  • ⚠️ The current CI report contains no test results yet for the targeted integration or integration bugfix-validation jobs. I did not run the integration suite locally. A completed run of test_access_storage_fsync at this head would confirm the updated regression coverage.
Final Verdict

✅ Approve — no unresolved code findings. Current-head integration results remain pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 22, 2026
Comment thread src/Access/DiskAccessStorage.cpp Resolved
scheduleWriteLists() writes the fsync'd <id>.sql, then defers the .list index
rewrite to a background thread and drops the need_rebuild_lists.mark marker so
the next startup rescans the .sql files instead of trusting the stale .list
indexes. The marker was created with a plain std::ofstream and never fsync'd,
so a power loss between the .sql write and the background .list rewrite could
lose the marker: on restart the constructor misses it, trusts the stale .list,
and never rescans the surviving .sql, making an acknowledged CREATE/ALTER/DROP
USER unreachable. This closed the .sql durability gap but left the PR missing
its own end-to-end contract.

Fsync the marker file and its parent directory when it is written, gated on
fsync_metadata, reusing the WriteBufferFromFile + LocalDirectorySyncGuard
pattern already used for the entity files. Write the marker before the
early return taken when the background writer is still waiting:
reloadAllAndRebuildLists() removes the marker without stopping that writer, so
a following DDL would otherwise commit its entity file with no marker on disk.

Extends the integration test with a recovery case (a fresh .sql absent from a
stale .list is recovered on restart only when the marker is present, proving
the marker is the load-bearing signal) and a marker-fsync case (a DDL syncs the
marker file and directory on top of the entity write, honoring fsync_metadata).

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

Copy link
Copy Markdown
Collaborator Author

Confirmed and fixed in e10e707.

need_rebuild_lists.mark is now written durably in scheduleWriteLists (WriteBufferFromFile + out.sync() on the file, LocalDirectorySyncGuard on the parent directory), gated on fsync_metadata, matching the pattern used for the entity files. It is also (re)created before the early-return taken when the background writer is still waiting: reloadAllAndRebuildLists() removes the marker without stopping that writer, so a following DDL would otherwise commit its entity file with no marker on disk.

Added an integration recovery test for the "fresh .sql + stale .list + missing marker" startup state: the forged entity is recovered on restart only when the marker is present (marker absent -> not recovered, proving the marker is the load-bearing signal), plus a marker-fsync assertion (a DDL syncs the marker file and directory on top of the entity write; fsync_metadata=0 -> no sync).

One residual power-loss window remains and is out of scope for this change: the background list-writer runs without a query context, so it uses the global fsync_metadata; with query 1 and global 0 it can rewrite .list unsynced and then remove the durable marker. This is pre-existing and belongs in the async-writer path (preserve the strongest pending fsync requirement, or write .list synchronously before returning); it involves a durability-vs-performance tradeoff, so I left it for a separate change rather than bundling it here.

@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; two rounds: 1 full pass + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 # Marker skipped on the scheduleWriteLists early-return: reloadAllAndRebuildLists() removes the marker without stopping the still-waiting writer, so a following DDL commits its entity file with no marker on disk AGREE - fixed @ e10e707 Moved marker (re)creation before the early-return; verified two consecutive CREATE USER now each sync the marker (FileSync/DirectorySync 2/2)
2 # Background list-writer uses the global fsync_metadata (no query context); with query=1/global=0 it can rewrite .list unsynced then remove the durable marker AGREE - DEFERRED Pre-existing, in the async-writer path, distinct from the marker-creation contract; correct fix (preserve strongest pending fsync requirement) is a durability-vs-perf tradeoff left for a focused change
3 warn New recovery test does not exercise the marker fsync implementation specifically AGREE - fixed @ e10e707 Added a deterministic marker-fsync ProfileEvents assertion (marker now synced on every DDL): CREATE USER -> FileSync/DirectorySync >= 2; fsync_metadata=0 -> 0/0
4 . Test docstring said scheduleWriteLists writes the entity file AGREE - fixed @ e10e707 insertNoLock calls scheduleWriteLists first, then writeAccessEntityToDisk; docstring corrected and tightened

Severity: # blocker / warn major / . nit. DEFERRED findings are recorded for a follow-up. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-maint-slot-8:20260722-113200

Comment thread src/Access/DiskAccessStorage.cpp Resolved
scheduleWriteLists() writes the fsync'd <id>.sql, records need_rebuild_lists.mark,
and defers the .list index rewrite to a background thread (1-min timer) or shutdown.
That deferred writeLists() runs with no query context, so it re-resolved
fsync_metadata to the GLOBAL value and silently dropped a session fsync_metadata=1:
with global fsync_metadata=0 the background thread rewrote the .list unsynced and then
removed the durable marker, leaving a power-loss window where the marker removal
persists but the .list content does not. On restart the stale .list is trusted and the
acknowledged CREATE/ALTER/DROP USER disappears even though its <id>.sql survived.

Carry the strongest pending fsync requirement from scheduleWriteLists (pending_lists_fsync,
OR-accumulated) into writeLists so the deferred .list write is as durable as the
most-durable pending change, resetting it once the batch is written. The direction is
safe: it can only fsync more, never less.

Regression test: a session fsync_metadata=1 CREATE USER followed by a session
fsync_metadata=0 SYSTEM RELOAD USERS must still fsync the .list (proving the carry).
Verified both directions with distinct Build IDs (fails pre-fix, passes with fix).
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review log (Gate B, round 3 delta) — click to expand

Independent code review of the round-2 delta (base e10e707, engine codex). 2 findings, adjudicated:

id severity verdict resolution
pending-fsync-on-failure blocker AGREE (partial) FIXED. The write-failure path cleared pending_lists_fsync, but the batch was not durably written; a later SYSTEM RELOAD USERS at fsync_metadata=0 resets failed_to_write_lists, rewrites .list unsynced and removes the marker, recreating the window. Now the obligation is preserved across failure. Sub-claim (c) (a latched-failure DDL commits with no marker): DISAGREE with evidence — the marker is already durable from the earlier scheduleWriteLists and the failure path returns before the marker-removal block, so restart rescans the surviving .sql. No window.
duplicated-fsync-rationale nit AGREE FIXED. Trimmed the 23-line test docstring to the invariant + mechanism, corrected the inaccurate claim that scheduleWriteLists writes the entity file, dropped () when naming functions.

Both-directions verified with distinct Build IDs; full suite 5/5.

Comment thread src/Access/DiskAccessStorage.cpp Resolved
A marker-driven rebuild (reloadAllAndRebuildLists on startup, or after a
latched failed_to_write_lists) has no query context and pending_lists_fsync
does not survive a restart, so writeLists() fell back to the global
fsync_metadata. With global fsync_metadata=0 that rewrote the .list files
unsynced and then removed the durable marker, re-opening the power-loss
window across a restart: a second power loss left stale .list files with no
marker and the acknowledged access change disappeared even though its
fsync'd <uuid>.sql survived.

The need_rebuild_lists.mark file's presence is the persistent, restart-
surviving encoding of the obligation to durably materialize the .list from
the .sql files, so force the fsync whenever the marker is present at rebuild
entry. This also covers the latched failed_to_write_lists path, whose eventual
rebuild runs with the marker still on disk.

Adds test_marker_driven_rebuild_forces_list_fsync: a marker-present rebuild at
fsync_metadata=0 must fsync the .list (FileSync>=1), while a no-marker rebuild
at fsync_metadata=0 must not (targeted, not a blanket fsync).

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

Copy link
Copy Markdown
Collaborator Author
Internal review log (Gate B, round 3 — cross-restart marker fsync; click to expand)

Second-model review (engine=codex) of the delta over base 3c6099fb (diffstat matched: 2 files, +54).

  • marker-comment-semantics (nit) - AGREE, FIXED. The marker is created regardless of fsync_metadata and can linger after an interrupted/unacknowledged rebuild, so its presence is a conservative proxy for "a durable .list is still owed", not strict proof of an acknowledged durable DDL. The fsync behavior is correct; only the code comment and test docstring overstated it. Softened and shortened both (comment-only; binary unaffected).

No blockers or majors. The fsync-forcing logic was not contested.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 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.20% -0.10%

Changed lines: Changed C/C++ lines covered: 65/71 (91.55%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 1a0fd09

CI fully finished (Finish Workflow = pass; 0 checks queued/in_progress; >20 min ingest buffer). This PR's own diff is src/Access/DiskAccessStorage.cpp fsync/durability + an integration test. None of the failures below are in a code path this PR touches; every one has an owner.

Note: the Bugfix validation (integration tests, amd64/aarch64) job passed — its "master-HEAD fails / PR passes" contract is satisfied for the new test_access_storage_fsync regression test.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / test_check_table::test_check_all_tables chronic flaky (27 master hits + many unrelated PRs, 30d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter chronic flaky (121 master hits, 30d) #111029 (external, open)
Stateless (amd_llvm_coverage, ParallelReplicas, s3, parallel) / Logical error !part.empty() (STID 5217-5b3d) pre-existing engine bug (backquoted dot-terminated lambda arg formatted as AST for an error message) #108735 (ours, merged 2026-07-21; not yet on this branch, clears on next rebase)
Stateless (amd_llvm_coverage, ...) / 04490_any_join_constant_condition_reorder (ERROR) + Server died fallout of the !part.empty() server abort above (same run, coverage build) #108735 (ours, merged)
Mergeable Check / PR rollup of the above resolves when the owners land / on rebase
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260722-233000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the test_check_all_tables flaky (Integration amd_asan_ubsan, db disk, old analyzer): #111353 (merged 2026-07-22, backported to 26.7 by #111574).

The failure is the plain-rewritable metadata_dropped concurrent-create race, not anything in this PR. Every occurrence after that merge is on a build whose base predates it: I checked all 49 distinct commits that produced this failure since 2026-07-22 17:31Z, and 49 of 49 lack the fix. Merging master into this PR picks it up. Details: #111477 (comment)

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 4, 2026
…diskaccessstorage-fsync

Resolve the conflict with ClickHouse#125058, which moved the creation of
`need_rebuild_lists.mark` to the start of `scheduleWriteLists` and added
one more in `reload`. Both now go through `createNeedRebuildListsMark`,
which syncs the mark and its directory when `fsync_metadata` is set.

`reload` now creates the mark itself before `reloadAllAndRebuildLists`, so
the check "a mark already exists, so its lists are owed durably" moves out
of `reloadAllAndRebuildLists` to before that creation in `reload`, and to
the constructor. Otherwise every `SYSTEM RELOAD USERS` would sync the lists
even with `fsync_metadata = 0`. `scheduleWriteLists` now accumulates
`pending_lists_fsync` before the `failed_to_write_lists` early return, like
the mark creation, so a change made after a failed list write keeps its
requirement too.

Also trim the comments added by this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`LocalDirectorySyncGuard`'s destructor only logs a failed `fdatasync`, so
call `sync` explicitly. A DDL whose rename, unlink or
`need_rebuild_lists.mark` cannot be made durable now fails instead of
being acknowledged.

`need_rebuild_lists.mark` is synced too, so its syncs satisfied some of the
old lower bounds by themselves. `DROP USER` now needs two directory syncs,
`SYSTEM RELOAD USERS` one file sync per `.list` file, and the deferred-write
test removes the mark so that only the requirement kept in memory can force
the sync. Each assertion fails with the mechanism it covers removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
The directory was opened for `fdatasync` only after the rename, unlink
or mark creation. `LocalDirectorySyncGuard` warns that a close-reopen-fsync
sequence is kernel dependent, so hold the directory fd across the change
and sync that same fd, as `KeeperSnapshotManager` does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
A failed directory fdatasync after the rename or unlink was thrown, but the
change was already on disk while memory kept the old entity, so the failed
DDL was applied later by `SYSTEM RELOAD USERS` or a restart. Moving the sync
after the in-memory update is not enough either: the access storage callers
take an exception as "nothing has changed" (the rollback of `MOVE`, the
dependency cleanup of `remove`, the notifications in `AccessControl`).

The directory is still opened before the change and synced after it, but a
failure there is only logged by the `LocalDirectorySyncGuard` destructor, as
for the other users of that guard. A failed sync of `need_rebuild_lists.mark`
is still thrown: it happens before any entity file changes.

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

Copy link
Copy Markdown
Collaborator Author

@vitlibar one design choice for you to decide here: when fdatasync of the access/ directory fails after the rename or unlink of <uuid>.sql has already been applied, should the DDL

(a) succeed, with the error logged, as it does now (like the other LocalDirectorySyncGuard users), or
(b) fail?

I tried (b). Failing before the in-memory update lets SYSTEM RELOAD USERS apply the failed DDL later, and failing after it breaks callers which take an exception as "nothing has changed": the rollback in MultipleAccessStorage::moveAccessEntities, the dependency cleanup in IAccessStorage::remove, the notifications in AccessControl. So (b) would need those to change too. A reply with (a) or (b) is enough.

Comment thread src/Access/DiskAccessStorage.cpp Resolved
…write

A GRANT, REVOKE or password change keeps the entity name, so updateNoLock does
not call scheduleWriteLists and never raised pending_lists_fsync. With the
global fsync_metadata=0, a CREATE USER at session fsync_metadata=0 followed by
a GRANT at session fsync_metadata=1 left the deferred writer rewriting
users.list without fsync and then removing need_rebuild_lists.mark; a power
loss could keep the mark removal and lose the list write, so restart trusted the
stale index and the user with its acknowledged grant became unreachable.

Raise pending_lists_fsync from such an update while a list write is pending:
that write removes the mark which also guards the updated file.

Measured with strace on the real background writer (global fsync_metadata=0,
CREATE@0 then GRANT@1): before, users.list is truncated and rewritten with no
fdatasync, then the mark is unlinked; after, fdatasync(users.list) precedes the
unlink.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
A rename-free update (GRANT, REVOKE, password change) did not schedule a
.list rewrite, so at fsync_metadata=1 it synced only `<id>.sql`. The .list
files on disk can still be unsynced: their rewrite may be pending (the mark
was created at fsync_metadata=0, not synced), or already done by a writer or
a clean shutdown running at a global fsync_metadata=0. A power loss could
then leave the synced `<id>.sql` next to a stale .list and no mark, so the
user and the acknowledged change were unreachable after restart.

Such an update now goes through scheduleWriteLists like a rename: the synced
mark is created before the change and removed only after a synced .list
rewrite. This replaces the narrower carry of the previous commit, which
covered only a pending rewrite and left the mark itself unsynced.

Cost at the default fsync_metadata=1: one more file and directory sync per
update plus a batched .list rewrite; 300 GRANTs took 0.64-0.94 s before and
0.74-0.83 s after on local NVMe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Oct 31, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 31, 2026
Merged via the queue into ClickHouse:master with commit 94d1a63 Oct 31, 2026
176 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 31, 2026
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-rbac Authorization: roles, grants, quotas, row-level security, access checks. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Access/DiskAccessStorage writeEntityFile should respect fsync_metadata

4 participants