Skip to content

Do not abort server startup when a database's named collection is missing - #115049

Open
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/tolerate-missing-named-collection-for-database-at-startup
Open

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/tolerate-missing-named-collection-for-database-at-startup

Conversation

@groeneai

@groeneai groeneai commented Aug 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #77366, #112805

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

Fixed the server refusing to start when a database created with S3, Remote, RemoteSecure, MySQL or PostgreSQL referenced a named collection that no longer exists. Such a database is now skipped with a logged error and the server starts; recreating the collection and then running ATTACH DATABASE (or restarting) brings the database back.

Description

A database whose engine arguments name a missing named collection stops the whole server from
starting: Caught exception while loading metadata: Code: 669 ... There is no named collection 'nc_cfg': while loading database 'db_cfg', then shutting down. Retiring a config.d/*.xml
collection and restarting reaches this. Recovery meant moving metadata/<db>.sql aside by hand:
the collection cannot be recreated with the server down.

A table in the same state does not: the server boots and only that table's load job fails, so
a plain CREATE NAMED COLLECTION recovers it. That asymmetry is the bug. loadDatabase
runs with create = true, so setForceAttach is never called and databases derive ATTACH rather
than the FORCE_ATTACH that gives tables their tolerance.

The two loadMetadata startup loops now skip such a database instead of aborting, under four
conditions, all required: the process is clickhouse-server, the error is exactly
NAMED_COLLECTION_DOESNT_EXIST, the database is not the configured default, and its engine is in
an audited list of engines owning no local table metadata (S3, Remote, RemoteSecure, MySQL,
PostgreSQL). Everything else is unchanged: other error codes still stop startup, Replicated and
MaterializedPostgreSQL still do because they own local tables, clickhouse-local still fails,
and ATTACH DATABASE still fails while the collection is missing. Once it is recreated,
ATTACH DATABASE restores the database with no restart, since the metadata file is untouched.
The default database is excluded because assertDatabaseExists(default_database) runs right after.

Validated both directions on identical on-disk state: the pre-fix binary exits 157, the fixed one
starts and logs the skip. test_named_collections passes 29/29 with 13 new cases, plus a
clickhouse-local stateless test. Each of the four conditions has its own test that fails on a
build with that condition removed, so none is vacuous.

#120734 is the counterpart for table engines.


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

groeneai and others added 3 commits August 16, 2026 17:19
…sing

A database whose engine arguments reference a named collection that is absent
at startup stops the whole server from booting:

  <Error> Application: Caught exception while loading metadata: Code: 669.
    DB::Exception: There is no named collection `nc_cfg`:
    while loading database `db_cfg` from file metadata/db_cfg.sql.
    (NAMED_COLLECTION_DOESNT_EXIST)
  <Information> Application: shutting down

The only recovery was moving metadata/<db>.sql aside by hand, since the
collection cannot be recreated over SQL while the server is down. Reaching this
does not require DROP NAMED COLLECTION: a config-file collection cannot be
dropped over SQL at all, yet retiring its config.d/*.xml and restarting is
enough.

A table in the same state does not do this. The server boots, only that table's
load job fails, and an admin recovers with a plain CREATE NAMED COLLECTION. The
asymmetry comes from the mode: loadDatabase calls executeCreateQuery with
create = true, which gates setForceAttach behind if (!create), so a database is
loaded as ATTACH while TablesLoader gets the FORCE_ATTACH that makes the table
path tolerant.

The two startup loops in loadMetadata now skip such a database instead of
aborting, under four conditions that must all hold:

  1. the process is clickhouse-server (clickhouse-local stays strict),
  2. the error is exactly NAMED_COLLECTION_DOESNT_EXIST, so metadata syntax
     errors, UNKNOWN_DATABASE_ENGINE and LOGICAL_ERROR still stop startup,
  3. the database is not the configured default, which assertDatabaseExists
     requires immediately afterwards,
  4. the engine is in an explicit audited list of engines that own no local
     table metadata: S3, Remote, RemoteSecure, MySQL, PostgreSQL.

Of the 17 registered database engines, 7 can raise this error. The two left out
are Replicated and MaterializedPostgreSQL: both extend DatabaseAtomic and own
persistent local tables, so silently dropping one would lose more than it saves.
An explicit list means a future engine has to be added deliberately, which is
the correct fail-closed direction here; an is_external-style flag would not be,
since that flag means "accesses a remote source" and is documented for restore.

The metadata file is never touched on the skip path, so recreating the
collection and restarting brings the database back.

Deliberately not addressed: if the default database is one of these, the server
still refuses to start. Deciding what a server with no default database should
do belongs in its own change. A test pins the current behaviour.

Tests: 5 integration tests in test_named_collections covering boot tolerance for
S3 and RemoteSecure, recovery through the config file and through SQL, the table
positive control, and the two strictness arms (Replicated and
MaterializedPostgreSQL must still abort, and a non-669 metadata error must still
abort). One clickhouse-local stateless test pins that clickhouse-local is
unchanged. Each strictness test was also run against a deliberately widened
build and fails there, so none of them is vacuous.

Related: ClickHouse#110529, which fixes the same startup-abort class for URL tables.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tests

The startup-tolerance test suite only exercised S3 and RemoteSecure, so removing
Remote, MySQL or PostgreSQL from the skip list left the whole suite green.
Parametrize the boot-tolerance arm over all five engine names; each uses a
collection that is never defined anywhere, so no external server is needed (in
every engine the collection lookup precedes any connection attempt).

Add an arm for a skippable engine failing with a non-669 error, which the
existing NoSuchEngine arm could not cover: NoSuchEngine is rejected by the
engine-name check regardless of the error-code check, so the code check had no
oracle. Four positional S3 arguments raise NUMBER_OF_ARGUMENTS_DOESNT_MATCH from
an engine that is on the skip list.

Add the missing arm for the default-database predicate, asserting both that the
original error is reported and that no skip is logged: with the predicate
removed the server would still refuse to start on the "default database must
exist" assertion, so a bare "does not start" oracle cannot tell the two builds
apart.

Tag the clickhouse-local test no-fasttest. It needs the S3 database engine,
which is compiled only under USE_AWS_S3, and the Fast test configures with
ENABLE_LIBRARIES=0.

Correct the skip-list comment: MySQL and PostgreSQL do persist local
.remove_flag/.removed markers, so those engines' local state is not re-derived.
What actually makes the skip safe is that they keep their metadata under
metadata/<name>/ rather than store/<uuid>/, which is what the store/ cleanup
task scans.

Co-Authored-By: Claude Fable 5 <[email protected]>
Same invariant, one line shorter, keeping the block within the per-block comment budget.

Co-Authored-By: Claude Fable 5 <[email protected]>
@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; 4 findings across 2 rounds)
plus my own cold review of the resulting code (2 findings). 1 fix round was bounced and
completed before this publication.

# Sev Finding Verdict Evidence / action
1 ❌ New stateless test carried no Tags: line, so it ran in Fast test where the S3 database engine does not exist (DatabaseS3.cpp:3 gates on USE_AWS_S3, and fast_test.py:269 configures -DENABLE_LIBRARIES=0) AGREE, fixed @ b415789 Added no-fasttest. Negative control through the real runner: tag present gives [ SKIPPED ] under --fast-tests-only, tag deleted gives [ OK ]
2 ⚠️ The code != 669 guard had no oracle: the only non-669 arm used an unknown engine, which the engine-name branch rejects regardless AGREE, fixed @ b415789 Added an arm using an allow-listed engine raising a non-669 error (4 positional S3 args gives code 42 at DatabaseS3.cpp:273). A build with that guard neutered fails it
3 ⚠️ Three of the five allow-list entries had no committed arm, and the argument that Remote inherits RemoteSecure's coverage does not transfer (the set is keyed on the engine name, and DatabaseRemote.cpp:1197/:1206 register the two names separately) AGREE, fixed @ b415789 Parametrized over all five names. A build with only "MySQL" removed from the list fails exactly 1 of the 5, so each entry is pinned individually
4 ⚠️ The default-database predicate had no arm although the description claimed it was pinned AGREE, fixed @ b415789 Added an arm with two assertions. Needed: with the guard removed the server still refuses to start, one line later at assertDatabaseExists, so a bare "does not start" oracle passes on both builds. The discriminator is the absence of the skip log
5 ⚠️ The skip-list rationale comment was factually wrong for MySQL and PostgreSQL, which do persist local per-table markers AGREE, fixed @ 676f518 Comment now states the invariant that actually makes the skip safe: these engines keep metadata under metadata/<name>/ rather than store/<uuid>/, so an omitted database is out of reach of the unmapped-UUID store cleanup. Provably comment-only: the two revisions' preprocessed token streams are byte-identical, with a control confirming that probe can see code changes
6 💡 The Related: line sat inside the template's leading HTML comment, so it did not render AGREE, fixed Moved it out. Verified empirically rather than from the template: a recently merged PR whose Closes: line sat inside that block rendered zero comment blocks, and its issue link came from a separate visible mention
7 💡 contains_in_log("... Code: 42") is a numeric prefix of the live codes 420 to 429 AGREE Noted, not blocking. Unreachable from this arm (>3 positional args deterministically yields 42), and the arm's discriminating assertion is the negative one. Raised independently by both reviewers
8 💡 The default-database arm's positive Code: 669 assertion can be pre-satisfied by an earlier test's log line on the same instance AGREE Noted, not blocking. The negative assertion is the discriminating one, which is what the mutated build fails. Raised independently by both reviewers
9 💡 The skip log message implies a restart is the only recovery, but ATTACH DATABASE also works once the collection is recreated AGREE Accurate: the metadata file is preserved, and InterpreterCreateQuery.cpp:264-276 re-reads it for a bare ATTACH. Not changed here, since it is operator-hint wording on an error path and the sentence is true of the state it is emitted in. Happy to reword if a reviewer prefers

Severity: ❌ blocker / ⚠️ major / 💡 nit. Findings on hunks unchanged by the fix
round are auto-dropped.

Session id: cron:clickhouse-review-self-slot-58:20260816-203500

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Define nc_cfg in config.d/nc.xml, CREATE DATABASE db_cfg ENGINE = S3(nc_cfg), remove the config file, restart. Pre-fix binary exits 157 every time with Caught exception while loading metadata: Code: 669 ... while loading database 'db_cfg'.
b Root cause explained? Yes. loadDatabase's catch annotates and unconditionally rethrows, so a code-669 throw from the engine's create_fn propagates out of loadMetadata and Server.cpp shuts down. Databases never had the table-side tolerance: loadDatabase passes create = true, executeCreateQuery gates the force flags behind if (!create), so setForceAttach is never called and the mode is ATTACH, not FORCE_ATTACH.
c Fix matches root cause? Yes. The startup loops tolerate exactly the one error code meaning "an external reference is absent", for exactly the engines that own no local metadata. The collection lookup itself is untouched, so CREATE/ATTACH semantics do not change, and no bound is widened.
d Test intent preserved / new tests added? Yes. 8 new integration tests (13 cases) plus one clickhouse-local stateless test. Nothing existing weakened or removed; the 16 pre-existing tests in test_named_collections still pass. Each of the four conditions has a test that fails on a build with that one condition removed, measured rather than argued.
e Both directions demonstrated? Yes, on identical on-disk state. Locally: base exits 157, fixed boots in about 10 s and logs the skip. In the CI harness: base 1 failed (Cannot start ClickHouse), fixed 29/29 passed.
f Fix is general across code paths? Yes. Both startup loops changed (databases and orphan_directories_and_symlinks). Each of the 5 allow-listed engine names has its own committed arm, and a build with "MySQL" alone removed reddens only the MySQL arm (4 passed / 1 failed). Membership is keyed on the engine name string, and Remote / RemoteSecure are registered as separate names, so neither inherits the other's coverage. The other two loadDatabase callers (system database, Ordinary to Atomic conversion) are deliberately untouched and keep the strict rethrow.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Of 17 registered database engines, 7 can raise code 669 and each is covered by its own arm: 5 tolerated, Replicated and MaterializedPostgreSQL asserted strict. The default-database boundary, the non-669 error class (an allow-listed engine raising code 42, so the code check is answered independently of the engine check), async_load_databases both ways, and the clickhouse-local entry point each have their own arm. Type wrappers are not applicable (no data types involved).
h Backward compatible? Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no serialization or on-disk format change; metadata is read, never written, on the skip path. The change is strictly "the server starts where it previously refused to". Checked the one test that greps for Caught exception while loading metadata (test_disk_over_web_server): it asserts a web-disk failure, not 669, so it is unaffected.
i Invariants and contracts preserved? Yes. The continue precedes loaded_databases.insert, so DatabaseCatalog::getDatabase is never called for a skipped database. A skipped database is simply absent from system.databases (measured count() = 0) with no dangling UUID mapping, since the failed createDatabase unwinds its own TemporaryLockForUUIDDirectory. The engine-name helper is read-only and fully swallowing: an unreadable or unparseable file returns no name, which rethrows the original 669 and keeps today's behaviour.

Session id: cron:clickhouse-impl-self-slot-57:20260816-181900

@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f10a895]

Summary: ✅


AI Review

Summary

This PR makes server startup tolerate NAMED_COLLECTION_DOESNT_EXIST for the audited read-through database engines by skipping the affected database instead of aborting the whole process, while keeping clickhouse-local, the default database, and engines with local table ownership on the strict path. After tracing the changed loader paths, the named-collection call sites in the database engines, and the new regression coverage, I did not find a remaining correctness or safety issue worth commenting on inline.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit f10a895.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 49/55 (89.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 16, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @tuanpach, could you review this? A database created over a named collection (S3, Remote, RemoteSecure, MySQL, PostgreSQL) makes the server refuse to start once that collection is gone, because loadDatabase passes create = true so databases never get the FORCE_ATTACH tolerance that keeps the equivalent table failure confined to one load job. The two startup loops in loadMetadata now skip such a database under four conditions (server process, error code 669 exactly, not the default database, engine in an audited list owning no local metadata), leaving the metadata file intact so recreating the collection restores it.

@groeneai groeneai added the groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR label Aug 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
@groeneai groeneai added the can be tested Allows running workflows for external contributors label Sep 10, 2026
`check_catch_all` in ci/jobs/check_style.py, added upstream after this
branch's base, flags every `catch (...)` whose block neither handles the
exception nor carries a comment containing 'Ok'. It reports
loadMetadata.cpp:171.

The swallow there is intentional and loses nothing. Reading a database's
engine name out of its metadata file is a best-effort step taken while
already recovering from a missing named collection; when it yields no name,
loadDatabaseAtStartup falls through to `throw`, so the original
NAMED_COLLECTION_DOESNT_EXIST reaches the operator exactly as before. Logging
instead would add a second message to a path that is about to rethrow, so the
sanctioned 'Ok' comment is the correct remedy.

Comment-only: `gcc -fpreprocessed -dD -E -P` token streams before and after
are byte-identical at 565 lines, while renaming one symbol in the same probe
makes them differ, so the probe is live.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Interpreters/loadMetadata.cpp Resolved
…ions in the fixture

The skip message offered a server restart as the only way back. Once the missing
named collection is recreated, the short `ATTACH DATABASE <name>` path in
InterpreterCreateQuery::createDatabase re-reads the preserved metadata file
(`need_write_metadata` stays false because the file exists) and the database
returns inside the running process, so the hint pushed operators into bouncing a
healthy server. Measured on a local server: uptime is monotonic across the
recovery, so no restart occurred.

test_startup_skipped_database_recovers_from_sql now recovers with ATTACH DATABASE
rather than a restart, which pins what the message promises; the restart path
stays covered by test_startup_skips_database_with_missing_collection.

The fixture teardown removed `db_extra_*.sql` but not the SQL-defined collection
that recovery arm creates, so an arm failing between the CREATE and the final
DROP left it on disk. The damage is larger than a leak into later arms: once the
teardown restores the config file, config and SQL both define the name, and
NamedCollectionFactory::add refuses the duplicate inside the loadIfNot call at
server startup ("A named collection `nc` already exists",
NAMED_COLLECTION_ALREADY_EXISTS), so the node cannot start again and every later
arm on it fails with "Cannot start ClickHouse". Measured with the recovery arm
forced to fail: without this cleanup the next arm errors, with it the next arm
passes.

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

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f10a89552 with master c108e273b (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

The new database-skip tests planted and probed definitions at
/var/lib/clickhouse/metadata/<db>.sql with cat, test -f, cp and rm. That path
only exists when the database disk is local. In the "db disk" flavour
<database_disk> points at a remote object-storage disk, so every write landed
where the server never reads and every probe answered about a file that was
never there:

  - the five skippable-engine arms and the two-database arm attached nothing, so
    no "Skipping database" line was ever logged;
  - the strict arms (Replicated, MaterializedPostgreSQL, NoSuchEngine, bad S3
    arguments) armed nothing, so the server started where the test requires it to
    fail, silently inverting this PR's negative controls;
  - the default-database arm failed earlier still, on cp of an absent file.

Route every definition read, write, move and delete through
helpers/database_disk.py, which drives clickhouse-disks against whichever disk
holds the metadata. The surviving-definition probes now assert the engine clause
is still in the stored statement rather than only that some file exists, which is
what the recovery claim actually needs. Teardown lists the planted databases by
name because that interface takes one path at a time and expands no glob.

The named_collections/*.sql cleanups keep using the container filesystem:
named-collection SQL metadata is rooted at the local path from
context->getPath(), not on the database disk.

Measured on a plain debug binary with test_named_collections -k startup: under
db disk 11 failed / 2 passed before and 13 passed after; the default flavour
stays 13 passed. A mutant deleting the definition before the surviving-definition
assert reddens it ("assert 'S3(db_collection_absent)' in ''"), so that probe is
not vacuous.

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

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: d1014abd-9eaa-49dc-9bbc-9ebb6778bfae
  • MIRAI run: 83be2832-6d18-43c9-b0f2-2bff422b7c68
  • PR check IDs:
    • clickbench_930791_1791755932
    • clickbench_930797_1791755932
    • clickbench_930803_1791755932
    • tpch_adapted_1_official_930814_1791755932
    • tpch_adapted_1_official_930827_1791755932
    • tpch_adapted_1_official_930863_1791755932

@tuanpach

Copy link
Copy Markdown
Member

@groeneai

What happen to the DBs with name collection exception?
Is there any issue related to this fix?

#110529 fixes this class for URL tables, not databases.

This PR is closed.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tuanpach

  1. With this PR the server skips such a database at startup instead of refusing to start, and logs the NAMED_COLLECTION_DOESNT_EXIST error with the database name and the recovery hint. Nothing on disk is touched: metadata/<db>.sql stays as is, and these five engines keep no local table data. Until the collection exists again, the database is not attached (absent from system.databases) and ATTACH DATABASE <db> fails with the same error. Once the collection is recreated, ATTACH DATABASE <db> brings it back without a restart. Other error codes, the default database, Replicated, MaterializedPostgreSQL and clickhouse-local still fail as before.

  2. No issue was filed for the database case; I found it while checking a review comment on Do not drop a named collection that a detached table still uses #112805. The closest report is Cannot startup when named collection dropped #77366, the same startup failure for MySQL tables, closed by Add check to ensure no named collection is dropped if still in use #96181. That drop-time check covers tables only: on master (46dfb81529c4), DROP NAMED COLLECTION is refused while an S3(nc) table uses the collection, but succeeds while only an S3(nc) database does. I can open an issue for it if you prefer one.

  3. Right, Do not abort server startup when a URL table's named collection is missing #110529 was closed without merging, and Do not abort server startup when a table engine's named collection is missing #120734 is the table-engine counterpart now. I updated the description.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants