Skip to content

Fix server failing to start when an access entity's .sql file is missing - #120943

Closed
groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-access-storage-missing-entity-file
Closed

groeneai wants to merge 3 commits into
ClickHouse:masterfrom
groeneai:fix-access-storage-missing-entity-file

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #99487
Related: #104411

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 the server failing to start when an access entity is listed in a /var/lib/clickhouse/access/*.list file but its <uuid>.sql file is missing on disk. The list files are now rebuilt from the directory contents in that case.

Description

On 26.3 Stress test (arm_asan) the server could not start at all: seven consecutive attempts aborted with Code: 107 ... Cannot open file /var/lib/clickhouse/access/<uuid>.sql ... (FILE_DOESNT_EXIST). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.3&sha=0af5e9c36f9f9cc12344e8dd96cb7a7bd801f468&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_asan%29

ClickHouse created that state itself. In the same run the thread-pool fault injector made CREATE SETTINGS PROFILE fail with CANNOT_SCHEDULE_TASK inside scheduleWriteLists, which 26.3 calls after the in-memory insert, so the profile reached memory with no <uuid>.sql; a later access DDL wrote that phantom into settings_profiles.list and removed need_rebuild_lists.mark. #104411 fixed that ordering on master (26.5+), but 26.3 and 26.4 still create the state, and upgrading cannot repair a directory an earlier build already damaged.

This fixes the half that is still on master. readLists trusts the index, so a listed entity whose .sql is gone becomes a lazy placeholder that throws on first read; for a settings profile that read happens in Context::setDefaultProfiles, so Server::main aborts, permanently and with no in-product recovery. DiskAccessStorage already owns the recovery, reloadAllAndRebuildLists, reached for a missing or unparsable .list but not for a listed id with no .sql. readLists now checks each listed id and returns false into that same rebuild. The discarded entity is logged by name and id; its definition was already gone from disk. A settings profile that a server setting such as default_profile names is discarded too, so startup still stops with THERE_IS_NO_PROFILE, as master's own rebuild already does. A healthy directory pays one stat per listed entity; the rescan runs only on damage. A present but unparsable .sql stays out of scope: readLists never opens entity files.

The check is from #99487, closed in favour of #104411; its integration test is adapted here to damage a settings profile, so it reproduces the failed startup.

Validated both ways: the signature reproduced locally, and the new test fails on unpatched master.


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

`DiskAccessStorage` persists each access entity as `access/<uuid>.sql` and
indexes them in `access/<type>.list`. `readLists` trusted that index: every
listed id became a lazy `EntityOnDisk` placeholder, and the first real read
called `readEntityFile`, which throws `FILE_DOESNT_EXIST` once the file is
gone. For a settings profile that first read happens during startup, in
`Context::setDefaultProfiles` -> `SettingsProfilesCache::ensureAllProfilesRead`,
so `Server::main` aborted and the server could not start at all, on every
subsequent attempt, with no in-product recovery. The guard that looks like it
should cover this, `tryRead`, only suppresses the storage's own `NOT_FOUND`,
not a `FILE_DOESNT_EXIST` raised by `ReadBufferFromFile`.

`DiskAccessStorage` already owns the recovery for this class of damage:
`need_rebuild_lists.mark` leads to `reloadAllAndRebuildLists`, which rescans
the directory, skips what it cannot parse and rewrites the `.list` files. It
is already reached for a missing `.list`, an unparsable `.list`, an orphan
`.tmp` and duplicate names. A listed entity whose `.sql` file is gone was
not routed there. A file that is present but unparsable is still only
detected at the read; `readLists` never opens entity files. `readLists` now
checks each listed id and returns `false`, which routes into that same
rebuild. The discarded entity is logged by name and id, and its definition
was already gone from disk, so nothing recoverable is lost. A healthy
directory pays one `stat` per listed entity, cheaper than the lazy read it
guards, and the rescan happens only when damage is found.

How the state arises: on 26.3 and 26.4 `insertNoLock` mutates memory before
disk, so a `CANNOT_SCHEDULE_TASK` thrown out of `scheduleWriteLists` leaves the
entity in `memory_storage` with no `<uuid>.sql` written, and a later access DDL
bakes the phantom into the `.list` and removes the marker. That ordering defect
is already fixed on master by ClickHouse#104411 (26.5 and later), but upgrading cannot
repair a directory an earlier build already damaged, and the same state is
reachable from a partial restore of `access/`.

The check is taken from ClickHouse#99487, which proposed it at this exact site and was
closed in favour of ClickHouse#104411; only the ordering half landed there. Its
integration test is adapted here to damage a settings profile, so the test
reproduces the failed startup rather than a later read.

Found in 26.3 `Stress test (arm_asan)`, seven consecutive failed starts:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.3&sha=0af5e9c36f9f9cc12344e8dd96cb7a7bd801f468&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_asan%29

Related: ClickHouse#99487
Related: ClickHouse#104411

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 19, 2026
@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; 8 findings; 1 full pass + 1 fix
round + 1 delta recheck). The delta recheck on the final head returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ The test damaged a user, but only settings profiles are read eagerly at startup, so it reddened on a later system.users read instead of on the reported failed startup AGREE, fixed @ ac28a32 The test now damages a settings profile. Unpatched, it fails at instance.start_clickhouse() with Cannot start ClickHouse, and that server log carries the reported FILE_DOESNT_EXIST chain through ensureAllProfilesRead -> Server::main, with zero recovery lines.
2 ⚠️ The oracle could not distinguish repair from destruction, nor on-disk repair from skipping the phantom in memory AGREE, fixed @ ac28a32 Added a control entity that must survive the rebuild, plus an assertion that no file under the access directory still references the dropped id. That grep was proven falsifiable against a live entity's id first.
3 💡 The damaged precondition depended on the stop mode: on the harness's kill -9 escalation the rebuild marker survives and the next start rebuilds regardless of the fix AGREE, fixed @ ac28a32 SYSTEM RELOAD USERS before the stop writes every .list and removes the marker synchronously.
4 💡 The commit message claimed a missing .sql was the one damage shape bypassing readLists; a listed entity whose .sql is present but unparsable bypasses it too AGREE, fixed @ ac28a32 Claim removed; that shape is now stated as out of scope in both the commit message and the description.
5 ⚠️ start_clickhouse retries by default, so the test should start through a single-attempt path DISAGREE The damage is deterministic, so retries cannot mask it: the CI report shows seven consecutive failed starts, and the unpatched control exhausts every attempt and still fails. Removing retries would only add CI fragility.
6 💡 Restart a second time, before any new DDL, to prove the rebuilt index persisted DISAGREE An implementation that merely skipped the phantom in memory would skip it again on the second start and pass. The discriminating oracle is finding 2's on-disk assertion, which such an implementation fails.
7 💡 The test does not assert that the rebuild marker is absent at the restart AGREE, noted, not blocking Deterministic on this head: the marker's only creator is scheduleWriteLists, no DDL runs between the reload and the stop, and the background lists writer never recreates it. Non-vacuity is measured: the unpatched control fails at the start.
8 💡 The survivor control is a user while the damaged entity is a settings profile, so same-type survival is not asserted AGREE, noted, not blocking reloadAllAndRebuildLists has no per-type branch: it rescans the directory and reloads every parsable <uuid>.sql, so no type-specific loss is reachable.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20260919-003100

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [90daa43]

Summary: ✅


AI Review

Summary

This PR teaches DiskAccessStorage to reject .list entries whose <uuid>.sql file is missing and fall back to the existing rebuild path, plus it adds an integration test for the startup failure reproduced by a non-default settings profile. The main behavior change is directionally right, but one startup-critical profile case is still unhandled.

Findings

⚠️ Majors

  • src/Access/DiskAccessStorage.cpp:259 The new rebuild only fixes the lazy profile-loading path. If the missing file belongs to the profile named by default_profile, system_profile, buffer_profile, or an explicit background_profile, startup still aborts after the rebuild because Context::setDefaultProfiles / makeBackgroundContext resolve those names and throw THERE_IS_NO_PROFILE once the profile has been dropped from the rebuilt directory. The added test uses sp_recover, which is never referenced from config, so it does not cover this remaining startup-failure case.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 90daa43.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.70% -0.10%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@groeneai
groeneai requested review from pufit and vitlibar September 19, 2026 01:07
@clickhouse-gh clickhouse-gh Bot added the comp-rbac Authorization: roles, grants, quotas, row-level security, access checks. label Sep 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 90daa433bf0f6ba8bdbdd8c6bba6ce9cf19d6140 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ac28a32

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
Performance Comparison (arm_release, master_head, 5/6) / iceberg_suite_tpch perf harness, master-side. The shard reports "10 errors" and all 10 rows are one traceback for this single test, truncated by the report's head -10: TPC-H Q5 exceeds perf.py --max-query-seconds after a join-order plan flip. 150 distinct PRs hit the same test in the last 24 hours; this diff touches only src/Access/DiskAccessStorage.cpp plus one integration test, so it cannot reach the perf harness. #120762 (mine, open)
Mergeable Check, PR praktika aggregators, red only because of the shard above #120762 (mine, open)

Session id: cron:our-pr-ci-monitor:20260919-063230

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
Contributor

Choose a reason for hiding this comment

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

Routing this through reloadAllAndRebuildLists drops the missing entity itself, but that rebuild path never runs the dependency scrub that a normal remove uses via removeReferencesToRemovedIDs. If the missing .sql belonged to a role, user, or settings profile that is still referenced by some surviving access entity, the dead UUID stays serialized in those survivors' .sql files and is reloaded on every restart. For roles that is the same stale-reference class that test_drop_role_cascades_to_disk documents as leading to later ACCESS_ENTITY_NOT_FOUND failures. Please carry the set of discarded IDs into the rebuild path and scrub dependent entities before persisting the repaired directory.

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.

Reproduced the mechanism, and it is pre-existing rather than introduced here.

On a clean master build (015bf1203d344, none of this PR applied) I removed a role's .sql and ran SYSTEM RELOAD USERS, the user-facing entry into reloadAllAndRebuildLists: the role leaves system.roles and its UUID stays on disk in all three survivors (the user's DEFAULT ROLE ID(...) and ATTACH GRANT ID(...), the profile's TO ID(...), the row policy's TO ID(...)). With need_rebuild_lists.mark present, master boots on that same damaged directory, logs Recovering lists, and keeps the same three references. Control on the same server: DROP ROLE does scrub, so the cascade is only on the remove() path.

Neither entry goes through readLists, so this diff neither creates nor widens the class. It makes the marker-absent case behave like the marker-present one, which today is the difference between a server that boots and one that cannot.

I would rather not put the scrub inside recovery:

  • A missing .sql is not a removal decision. Recovery runs when the on-disk state is damaged in an unknown way and the file may still be restorable (a half-restored backup, a volume not mounted yet), while grants scrubbed out of healthy entities are gone for good. The same function keeps an unparsable .sql "on disk for inspection" instead of treating it as a removal.
  • The rebuild reads the directory alone. At startup nothing is in memory yet and the marker declares the index suspect, so the discarded set is not computable there. Scrubbing only where it happens to be computable would re-introduce the divergence this PR removes.

Whether recovery should scrub dependencies is a component-owner call and it applies to master independently of this PR. If it is wanted, I will send it as a separate change covering every entry into the rebuild.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7943960

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
Build profile diff RuntimeError: CI logs cluster query failed from a ReadTimeout against the CI logs cluster (log_cluster.py:333), infrastructure and not a build regression: 155 of 185 runs red today across 155 distinct pull requests #118708 (mine, open)
PR praktika aggregator over the row above #118708 (mine, open)

No test-level failure on this head: the Performance Comparison (arm_release, master_head, 5/6)
row owned by #120762 on the previous head ac28a321f4f6 is gone, and CH Inc sync is green, so
no exempt row is owed. Build profile diff is the only remaining red.

Session id: cron:our-pr-ci-monitor:20260920-063119

for (auto & [id, name] : readListFile(file_path))
{
/// The list files must not reference an entity without its `<id>.sql` file: such an entity throws when read.
if (!std::filesystem::exists(getEntityFilePath(directory_path, id)))

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 the missing <id>.sql belongs to a settings profile that startup resolves by name from config, this still leaves the server unable to boot. readLists() now forces a rebuild, but reloadAllAndRebuildLists() just drops the profile; Context::setDefaultProfiles() / makeBackgroundContext() then look up default_profile, system_profile, buffer_profile, or an explicit background_profile by name and throw THERE_IS_NO_PROFILE when that profile was the one whose file disappeared. The new integration test misses this because sp_recover is never referenced from config, so it only proves the lazy-profile path. Please cover one of the configured-profile cases or narrow the fix to the non-configured-profile startup failure.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this still needed? I don't like this change. It allows to start the server without an important file

@groeneai

Copy link
Copy Markdown
Collaborator Author

No, it is not needed anymore, and I agree with the objection. The .sql file went missing because of two write-path bugs, and both are fixed on master:

Since #125058 merged on 2026-10-12, CI has not shown this access/<uuid>.sql FILE_DOESNT_EXIST on any master-based build, against 3 builds in the two weeks before it. The release branches still lack #125058 (and 26.3 lacks #104411), so backporting those is the fix there, not this PR. It can be closed.

@PedroTadim PedroTadim closed this Oct 22, 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-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants