Skip to content

Fix DiskAccessStorage crash on restart when .sql file is missing - #99487

Closed
alexey-milovidov wants to merge 52 commits into
masterfrom
fix-disk-access-storage-missing-sql-file
Closed

alexey-milovidov wants to merge 52 commits into
masterfrom
fix-disk-access-storage-missing-sql-file

Conversation

@alexey-milovidov

Copy link
Copy Markdown
Member

Summary

  • Make DiskAccessStorage::insertNoLock exception-safe: if writeAccessEntityToDisk fails (e.g. due to memory fault injection in stress tests), roll back the memory_storage insert so the orphaned entity never appears in the list files.
  • Add a defense-in-depth check in readLists: validate that each listed entity has a corresponding .sql file on disk, and trigger reloadAllAndRebuildLists recovery if any are missing.

The root cause: insertNoLock first inserts the entity into memory_storage, then writes the .sql file to disk. If the disk write throws (e.g. MEMORY_LIMIT_EXCEEDED from fault injection), the entity remains in memory and gets persisted to the list files. On restart, DiskAccessStorage finds the UUID in the list, tries to read the missing .sql file, and throws a fatal FILE_DOESNT_EXIST exception that prevents the server from starting.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ba724855a1ff39014f1e254183c387b5cf9625eb&name_0=MasterCI&name_1=Stress%20test%20%28amd_msan%29

Test plan

  • Builds successfully
  • Stress test (amd_msan) passes without the "Cannot start clickhouse-server" failure

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

Fix server failing to start after an access entity creation was interrupted, leaving an entry in the list file without a corresponding .sql file on disk.

🤖 Generated with Claude Code

Make `insertNoLock` exception-safe: if `writeAccessEntityToDisk` fails
(e.g. due to memory fault injection in stress tests), roll back the
`memory_storage` insert so the orphaned entity never makes it into the
list files.

Also add a defense-in-depth check in `readLists`: validate that each
listed entity has a corresponding .sql file on disk, and trigger
`reloadAllAndRebuildLists` recovery if any are missing.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=ba724855a1ff39014f1e254183c387b5cf9625eb&name_0=MasterCI&name_1=Stress%20test%20%28amd_msan%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f774faee]

Summary: ✅


AI Review

Summary

This PR hardens DiskAccessStorage against missing *.sql files and improves exception-safety in insertNoLock rollback paths, including targeted failpoint tests. Verdict: ⚠️ one rollback consistency issue remains in the cleanup-failure path, so this is not ready to approve yet.

Findings

❌ Blockers

  • [src/Access/DiskAccessStorage.cpp:588] In rollback when old_entity_at_id is absent, failure to remove new_file_path is only logged and ignored. That can leave both <old_id>.sql and <id>.sql on disk while memory/list are rolled back to old state, recreating duplicate-file inconsistency and risking both entries being dropped on a later reloadAllAndRebuildLists conflict pass.
    Suggested fix: make this rollback branch fail-close and enforce the invariant “exactly one on-disk file per entity name” before exit (or surface a hard failure if invariant restoration is impossible).
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Rollback cleanup can leave duplicate *.sql files on disk
Compilation time ✅
No large/binary files ✅
Final Verdict

Status: ⚠️ Request changes

Minimum required action:

  1. Make the rollback cleanup path around new_file_path fail-close so a failed replace cannot leave duplicate on-disk entity files.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 14, 2026
Comment thread src/Access/DiskAccessStorage.cpp Resolved
alexey-milovidov and others added 2 commits March 16, 2026 02:43
…safe

Move deletion of the old name-collision `.sql` file to after the new
file is successfully written. This way, if `writeAccessEntityToDisk`
throws, the old file remains on disk and can be recovered on restart.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
Comment thread src/Access/DiskAccessStorage.cpp Resolved
Comment thread src/Access/DiskAccessStorage.cpp Resolved
alexey-milovidov and others added 2 commits March 24, 2026 15:03
Add cleanup (TRUNCATE TABLE, DROP COLUMN IF EXISTS, DROP DATABASE IF
EXISTS) at the start of each test function so that repeated runs in
targeted CI (which uses --count N --repeat-scope=function) don't fail
due to accumulated data or pre-existing objects from previous iterations.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Under TSan, the metric collection thread may only fire once during a
2.5s sleep with 1000ms interval, giving 2 rows (1 interval + 1 final)
instead of 3+. Change `count() > 2` to `count() >= 2` to tolerate this.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=99487&sha=3ca6c8c21ce1edfe740d99001743e6b0d4447eee&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
alexey-milovidov and others added 4 commits March 30, 2026 05:10
…rage-missing-sql-file

# Conflicts:
#	tests/integration/test_polymorphic_parts/test.py
…on safety

- Save old entity before `memory_storage.insert` so it can be restored if
  `writeAccessEntityToDisk` fails in the `replace_if_exists` path.
- Move `scheduleWriteLists` after successful disk write so list updates are
  not scheduled when the .sql file was never written.
- Tolerate missing old collision files instead of throwing
  `FILE_DOESNT_EXIST`, making the cleanup step non-throwing.
- Revert unrelated test relaxation in `03203_system_query_metric_log.sh`
  (count() > 2 back from >= 2).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
If `scheduleWriteLists` throws (e.g. during thread creation), the entity
would be in memory and on disk but the caller would see failure. Move it
inside the try block and clean up the .sql file in the catch block if
the disk write already succeeded.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Access/DiskAccessStorage.cpp Resolved
Comment thread src/Access/DiskAccessStorage.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

Comment thread src/Access/DiskAccessStorage.cpp Resolved
alexey-milovidov and others added 3 commits May 5, 2026 10:02
…nsertNoLock`

If `replace_if_exists` succeeds in writing the new `<id>.sql` but then fails to
remove the displaced (different UUID, same name) `<old_id>.sql`, leaving both
files on disk would let a later `reloadAllAndRebuildLists` see two same-name
entities, which `clearConflictsInEntitiesList` resolves by dropping *all*
same-name entries — silently losing the user/role.

Move the old-file removal into the same try/catch as the new file write and
list-update scheduling, and throw on failure so the existing rollback path
restores a single consistent on-disk state. Also adds a
`disk_access_storage_remove_old_file_fails` failpoint and an integration test
exercising this rollback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…rage-missing-sql-file

# Conflicts:
#	src/Common/FailPoint.cpp
@alexey-milovidov
alexey-milovidov requested a review from vitlibar May 6, 2026 08:54
@vitlibar vitlibar self-assigned this May 6, 2026
alexey-milovidov and others added 4 commits May 7, 2026 14:59
The gh CLI token used here lacks `workflow` scope, so pushes touching
`.github/workflows/*` are rejected. Restore those files byte-identical
to the previous PR tip content so the master merge can be pushed.
The previous "restore" commit reverted these files to the PR's old tip
to work around a `workflow` scope token limitation, but that made the
praktika `Check Workflows` job fail because the generated YAML for
`vectorsearchstress.yml` no longer matched what `python3 -m praktika yaml`
produces from the current configuration (master switched the runner from
`arm-large` to `arm-large-storage`).

Bringing all three workflow files to the current master state.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
/// No pre-existing entity at this UUID: the new file (if any) is orphaned.
/// Best-effort delete; don't mask the original exception on failure.
std::error_code ec;
std::filesystem::remove(new_file_path, 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.

⚠️ If this cleanup fails, we return with an exception but leave both <old_id>.sql and <id>.sql on disk while memory/list were rolled back to the old UUID.

That recreates the duplicate-file state this patch is trying to eliminate, and a later reloadAllAndRebuildLists can drop both entries via clearConflictsInEntitiesList.

Please make this path fail-close instead of best-effort: ensure rollback ends with exactly one on-disk file for the name (either fully restore old state or fully commit new state), and surface failure if that invariant cannot be maintained.

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.

I re-checked the current insertNoLock rollback and this concern is still live.

In the old_entity_at_id == nullptr branch (src/Access/DiskAccessStorage.cpp, around std::filesystem::remove(new_file_path, ec)), cleanup failure is only logged. If that cleanup fails after memory/list rollback, both <old_id>.sql and <id>.sql can remain on disk for the same name, and later reloadAllAndRebuildLists can drop both via conflict cleanup.

Please make this path fail-close so rollback finishes with exactly one on-disk file for the name (or surfaces a hard failure if that invariant cannot be restored).

throwReadonlyCannotInsert(new_entity->getType(), new_entity->getName());

/// In case of name collision old file should be removed.
/// Capture pre-existing state before any mutation, so the rollback path can restore it.

@vitlibar vitlibar May 8, 2026 •

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.

I think we should try to implement a different approach here - first update files, then memory_storage, in order to make them always consistent. I'll try to implement this.

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.

if (!std::filesystem::exists(getEntityFilePath(directory_path, id)))
{
LOG_WARNING(getLogger(), "Access entity {} ({}) is listed in {} but the corresponding .sql file doesn't exist", name, toString(id), file_path);
return false;

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.

This change is OK

@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.00% -0.10%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 79.41% (54/68) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Closing in favor of #104411

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ertNoLock` cleanup paths

The cleanup branches in `insertNoLock` called `std::filesystem::remove`
in its throwing form, which can throw `std::filesystem::filesystem_error`:

- In the `catch (...)` rollback path, a throw from the cleanup would mask
  the original exception (e.g. `MEMORY_LIMIT_EXCEEDED` from fault injection)
  and replace it with a less informative filesystem error.
- In the post-commit path that removes a replaced collision file, a cleanup
  error would turn a successful replacement into a reported failure, even
  though the new file is already durably on disk and the memory state is
  consistent.

Switch to the `std::error_code` overload and log a warning on failure. The
behavior is now "best-effort cleanup", consistent with the preexisting
comment that missing files are tolerated.

Addresses AI review feedback on ClickHouse#99487
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
ClickHouse uses `CREATE USER OR REPLACE name`, not the standard SQL
`CREATE OR REPLACE USER name`. The latter triggers a `SYNTAX_ERROR` and
prevents the failpoint from being exercised.

CI failures (all show the same `SYNTAX_ERROR` instead of `FAULT_INJECTED`):
ClickHouse#99487
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants