Skip to content

Do not abort server startup when a table engine's named collection is missing - #120734

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:tolerate-missing-named-collection-at-startup
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:tolerate-missing-named-collection-at-startup

Conversation

@groeneai

@groeneai groeneai commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

A table that fails to load with NAMED_COLLECTION_DOESNT_EXIST, because its ENGINE names a named collection that is gone, no longer stops the server from starting, and no longer makes a system.tables or system.columns scan fail. In an Atomic database RENAME TABLE no longer reports an error for a rename that has already happened. The table is listed, reading it reports the missing collection, and recreating the collection makes the table work again without a restart. A streaming source, a force_restore_data start, and a table stored as AS <table function>(...) still stop as before.

Description

A table whose persisted ENGINE names a named collection that no longer exists cannot be constructed when its metadata is replayed at startup. With async_load_databases = 0 the server refuses to start. With the packaged default async_load_databases = 1 it starts, but every SELECT from system.tables for that database fails with ASYNC_LOAD_WAIT_FAILED, so the user cannot list their tables. That contradicts what async_load_databases documents: a failed load job is rethrown only to queries accessing that table.

Reachable with no other bug: SET check_named_collection_dependencies = 0 before the DROP, or removing the collection's config.d entry, where there is no SQL DROP to intercept. Reported on MySQL as #77366.

Root cause: an engine resolves its named collection while parsing its arguments, before the storage exists, so NAMED_COLLECTION_DOESNT_EXIST escapes createTableFromAST and fails the load job.

Fix: in DatabaseOrdinary::loadTableFromMetadata's existing catch, when the error is exactly NAMED_COLLECTION_DOESNT_EXIST and the mode is FORCE_ATTACH, log it and attach the lazy stand-in a lazy_load_tables database uses. registerStorageMergeTree.cpp already does this for a projection naming a dropped object. FORCE_ATTACH is the level metadata replay uses; a user CREATE or ATTACH TABLE runs below it and still fails immediately.

Such a stand-in is the first storage whose materialization always throws, so three consumers needed the guard their neighbours already carry: data_paths and metadata_version in system.tables, column sizes in system.columns, and DatabaseAtomic::tryCreateSymlink, which RENAME TABLE calls after committing the move.

Related: #77366

Happy to close #110529 (URL engine only) if you prefer this shape.

Scope, residuals, validation

Reuses shouldLazyLoad's exclusions (canUseLazyStandIn). Consequences chosen, not worked around:

  • A push source (Kafka, S3Queue, other streaming engines) always aborts: a stand-in never calls startup, so ingestion would stall silently, and it answers neither the engine's own rename veto nor its streaming classification.
  • Two stored forms stay outside: AS <table function>(<collection>), whose arguments createTableFromAST parses before StorageTableFunctionProxy sees them, and bare ENGINE = Remote(<collection>), which reports CLUSTER_DOESNT_EXIST since a lone identifier there is also a cluster name.
  • Under force_restore_data the boot still aborts: that flag is one-shot, a stand-in loads later.
  • While the collection is missing, DROP TABLE, DROP DATABASE and a table-less SYSTEM STOP MERGES still fail with 669: each reaches the storage. Recreating the collection or DETACH TABLE ... PERMANENTLY removes the table; on master they fail even after it returns.
  • RENAME TABLE in an Ordinary database also still fails, by design: there the rename moves the data directory, so DatabaseOnDisk::renameTable rolls the name back itself. Only Atomic throws after committing the move.
  • Open PRs: Do not drop a named collection that a detached table still uses #112805 adds addDependency on the stand-in path, so the two compose; Fix BACKUP and access checks for lazily loaded tables that are still a proxy #117972 and Replace the proxy of a lazily loaded table with the table itself #118699 only reach an already-materialized stand-in, which this one never is, so these guards stay; Fix data loss and silent behaviour changes in databases with lazy_load_tables #113389 reworks lazy_load_tables and the proxy accessors, fixes no named collection, and conflicts in shouldLazyLoad. Happy to rebase.

A/B validated on URL, S3 and via config removal: sync boot (Ready for connections 0 -> 1), async system.tables (ASYNC_LOAD_WAIT_FAILED -> listed), and a whole-catalog SELECT * from both system tables (669 -> clean); two new tests that fail on master; a missing storage policy still aborts; removing the new if returns every arm to master.


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

groeneai and others added 6 commits September 7, 2026 22:27
A table whose persisted `ENGINE = <X>(<named collection>)` names a collection that no
longer exists cannot be constructed when its metadata is replayed at startup:

  Code: 722 Waited job failed: Code: 695 Load job 'load table default.t_url' failed:
  Code: 669 There is no named collection `nc_url`: Cannot attach table `default`.`t_url`
  from metadata file store/d4c/.../t_url.sql (NAMED_COLLECTION_DOESNT_EXIST)

Every engine resolves its collection inside its registration lambda, before the storage
is constructed, through `tryGetNamedCollectionWithOverrides`, whose
`throw_unknown_collection` defaults to true. So the exception escapes `createTableFromAST`
and fails the table's load job, and a failed load job is fatal twice over: in sync mode
`loadMetadata`'s `waitLoad` rethrows it out of `Server.cpp` and the boot dies, and in
async mode `getTablesIterator` waits on every table's startup task, which is how
`StorageSystemTables` reaches it, so one broken table fails every `system.tables` scan
of its database.

Measured on a pristine build of the parent commit, three server generations over one
data directory: with `async_load_databases = 0`, `Ready for connections` = 0,
`Caught exception while loading metadata` = 1 and every process exits; with the packaged
default `async_load_databases = 1` the server starts, but
`SELECT name FROM system.tables WHERE database = 'default'` fails with
`ASYNC_LOAD_WAIT_FAILED`, so the user cannot list their tables to find the broken one.
The second arm contradicts what `async_load_databases` documents, namely that a failed
load job is rethrown to queries that access that table. Reachable in four ordinary
statements, and by two routes that need no other bug: `check_named_collection_dependencies
= 0` before `DROP NAMED COLLECTION`, or removing the collection's `config.d` entry, where
there is no SQL `DROP` to intercept. Reported on the MySQL engine as ClickHouse#77366.

Make the load job succeed instead of fail: in the existing `catch`, when the error is
exactly `NAMED_COLLECTION_DOESNT_EXIST`, attach the lazy stand-in that a
`lazy_load_tables` database already uses. The table is listed with
`engine = 'TableProxy'`, reading it raises the real error, and recreating the collection
makes it work with no restart. `registerStorageMergeTree.cpp` already takes this shape one
level deeper, skipping a projection that names a dropped dictionary or missing object
rather than refusing to start.

The catch runs in the frame that called the throwing constructor, so `e.code()` is still
live and nothing has to be recovered from a flattened message; and because the job no
longer fails, neither the sync-mode nor the async-mode contract is altered.

The gate is `mode == FORCE_ATTACH`, not `isLoadingFromExistingMetadata`. Ordinary metadata
replay runs at exactly `FORCE_ATTACH`, while a user `CREATE` or `ATTACH TABLE` runs at
`mode <= ATTACH` and still fails immediately. `FORCE_RESTORE` is excluded deliberately:
`force_restore_data` is one-shot and deleted during the boot, whereas `loadTableLazy`
captures `mode` and materializes at an arbitrary later time, so a stand-in born in a
force-restore boot would keep skipping sanity thresholds long after the flag was gone.
Under force-restore the boot therefore still aborts.

`shouldLazyLoad`'s body becomes `canUseLazyStandIn` so both paths share one predicate and
cannot drift; `shouldLazyLoad` is now that predicate plus its `lazy_load_tables` check, so
the lazy-load path is unchanged by construction. This inherits its exclusions, and one of
them costs coverage on purpose: a push source that feeds a materialized view still aborts
the boot, because a stand-in never calls `startup` and nothing reads a source table, so
ingestion would stall silently even after the collection came back. With no dependent view
such a table is covered.

Not a blanket swallow: a `MergeTree` table naming a storage policy that no longer exists
still aborts the boot identically, `Code: 478 UNKNOWN_POLICY`.

Related: ClickHouse#77366

Co-Authored-By: Claude Opus 5 <[email protected]>
The stateless test covers the arm that needs no server: `clickhouse local` replays the
metadata of its `--path` through the same loader, so re-entering it on one directory is a
restart. On the parent commit the second invocation fails with
`Code: 722 ... ASYNC_LOAD_WAIT_FAILED` instead of listing the table.

Its third assertion is anchored on the first line of the error rather than grepping for the
error name anywhere in the output. The unanchored form passes on the parent commit too,
because the wrapped `722 -> 695 -> 669` chain contains that name as well; what the fix
changes is that the collection error is reported directly instead of inside a failed load
job, and only a line-anchored match can see the difference.

The integration test covers the default `async_load_databases` and the route that has no
SQL `DROP` to intercept: a collection defined in `config.d`, a table created against it,
the entry removed, and a real server restart. It reuses the file's existing
`with_replace_config` fixture rather than adding one.

Restoring the collection before dropping the table is not just cleanup. Dropping a table
whose collection is still missing materializes the stand-in, through
`StorageTableProxy::checkTableCanBeDropped`, and so raises the same error; putting the
collection back first both removes the table and asserts that the table recovers without
another restart. On the parent commit that `DROP` fails as well, and keeps failing even
after the collection is recreated, because the failed load job is cached for the life of
the process.

Co-Authored-By: Claude Opus 5 <[email protected]>
…t be built

Handing a table whose storage cannot be constructed a `StorageTableProxy`
stand-in is the first thing in the tree that creates a proxy whose
materialization is guaranteed to throw. Every consumer that ships today only
ever meets a proxy that materializes successfully, so "handles a proxy" and
"tolerates a proxy that cannot be built" turned out to be different
properties, and three consumers had only the first one.

`system.tables` reached the storage twice without a guard: `data_paths` via
`tryGetDataPaths()` and `metadata_version` via `supportsReplication()`, both
routed through `StorageProxy::getNested()`. `metadata_snapshot` is non-null
for a stand-in, since `StorageTableProxy` returns its cached metadata, so the
`&&` did not short-circuit. A whole-server `SELECT * FROM system.tables`
therefore aborted on the first such table, not merely the row for it.

`system.columns` reached it once, through `tryGetColumnSizes()`. Leaving the
sizes empty is already a supported state: the per-column fill takes its
`insertDefault()` branch when a name is absent, which is what a `URL` table
produces anyway.

`DatabaseAtomic::tryCreateSymlink` read the table's data path outside its own
catch-all, and `renameTable` calls it from the `attach` lambda after the
metadata move has been committed, past the point the code documents as
"the following methods should not throw (if they do, it's a logical error)".
So `RENAME TABLE t TO t2` returned an error for a rename that had already
happened, and the user's retry then reported `UNKNOWN_TABLE` for a table that
did move. `EXCHANGE TABLES a AND b` was worse: the throw landed between the
two `attach` calls, leaving `b` attached to neither database in memory until
the next restart.

Each hunk copies an idiom already present in the function it edits, so nothing
that works today changes behaviour. The guards deliberately sit in the
consumers rather than in the proxy: making the proxy answer these questions
without materializing would change `data_paths`, `metadata_version` and column
sizes for every existing `lazy_load_tables` user, and forwarding the capability
predicates would construct storages in new places.

Under `FORCE_RESTORE` the startup job in `DatabaseAtomic` walks every table
through this same `tryCreateSymlink`, which is the second reason the tolerance
added earlier excludes `FORCE_RESTORE`, and the reason the ordinary
`FORCE_ATTACH` boot was already safe.

Coverage: neither shipped test would have caught the `system.tables` break,
because one selected `name, engine` and the other only `name`, and
`StorageTableProxy::getName()` deliberately avoids materializing. The stateless
test's listing is widened to name the two previously-throwing columns and gains
a `system.columns` arm; the integration test gains the rename.
The recovery arm of test_missing_collection_in_config_does_not_block_startup
only asserted that reading the table no longer fails with
NAMED_COLLECTION_DOESNT_EXIST. That is nearly vacuous: query_and_get_error
requires the query to fail, and the restored collection deliberately points at
an unreachable endpoint, so the read always fails on connection. The assertion
therefore said only "the failure is not spelled NAMED_COLLECTION_DOESNT_EXIST",
which passes just as well for a LOGICAL_ERROR or a stale get_nested factory. It
could not distinguish a stand-in that materialized into a real URL storage from
one that broke differently.

The engine column of system.tables is a sufficient and cheaper oracle than
standing up a reachable endpoint. It is filled from IStorage::getName(), and
StorageTableProxy::getName() reports TableProxy while nested is null, then
forwards to the nested storage once it is set. Because nested is only ever
assigned by a getNested() call that has constructed and started the storage,
engine = 'URL' is reachable only through a successful materialization, and
reading the column does not itself force one.

Asserting TableProxy while the collection is missing and URL after it comes
back makes the pair a before/after transition, so the test now polices the
contract the change claims: recreating the collection makes the table work
again without a restart.
The tolerance added earlier hands a table whose named collection is missing a
`StorageTableProxy` stand-in, so one dangling reference fails one table instead
of the whole database load. For an engine that ingests from a background job,
that stand-in is not a faithful placeholder, and unlike the `lazy_load_tables`
path it now appears in databases that never opted into a stand-in at all, so
two engine contracts become reachable in a default configuration.

`DatabaseAtomic::renameTable` validates `checkTableCanBeRenamed` on the object
the catalog holds, which is the proxy. `StorageProxy` forwards only `isRemote`
and `isView`, so the inherited no-op accepts a cross-database move that
`StorageObjectStorageQueue::checkTableCanBeRenamed` refuses while `keeper_path`
is implicit. `chooseZooKeeperPath` derives that path from the database and table
UUIDs, so once the collection came back the table would process against a
different Keeper path and lose the record of what it had already consumed.

`isStreamingStorage` is `final` in `IStreamingStorage` but only defaulted in
`IStorage`, and neither proxy overrides that default, so both of
`InterpreterSystemQuery`'s streaming paths classify a stand-in as not
streaming: the ALL form skips it while collecting tables, and the per-table
form authorizes and routes it as an ordinary table. `StorageProxy` does forward
`getActionLock`, but that materializes the storage only after the caller has
already taken the wrong branch. A materialized view created once the collection
is back materializes the stand-in and starts the nested engine, and
`SYSTEM STOP`/`SYSTEM CANCEL` then no longer reach an ingesting engine.

Forwarding either property through the proxy would call `getNested()`, so it
would materialize on every rename, change behaviour for every table that is
already loaded this way, and make `RENAME TABLE` fail on a table whose
collection is gone. Excluding these engines instead leaves both contracts
exactly where they are today: such a table fails its own load, which under
asynchronous loading is reported when the table is accessed, and on a
synchronous start still refuses the start.

The engine set is the one `canUseLazyStandIn` already keys on, so the two paths
cannot disagree about what a push source is. The eager path there excludes such
a table only once it has a dependent view, because a stand-in that is never read
would stall an otherwise working pipeline; here the table's load has already
failed, and the point is to keep failing it.

Coverage: the integration test gains a database holding both a `Kafka` table and
a `URL` table whose collections are both missing, and asserts that only the
`URL` table is attached, that its own load completed, and that the `Kafka` table
reports the missing collection out of a failed load job.

Co-Authored-By: Claude Opus 5 <[email protected]>
Drop the canUseLazyStandIn declaration comment (it restates the name) and the push-source line at the condition (isPushSourceEngine documents that set itself); condense the named-collection comment to the property that justifies the dangling-reference classification.
@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 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model, plus a cold pass I made before reading either the
implementation notes or that model's output. The last round narrowed the src change by one
condition; the final pass found nothing.

# Sev Finding Verdict Evidence / action
1 ❌ A stand-in whose materialization always throws broke SELECT * FROM system.tables and system.columns server-wide (data_paths, metadata_version and the column sizes reach the storage unguarded), and RENAME TABLE threw after DatabaseAtomic had committed the metadata move AGREE, fixed Those reads now carry the guard their neighbours already carry. Both proxy headers are untouched, so lazy_load_tables behaviour is unchanged by construction
2 ⚠️ Forward checkTableCanBeRenamed, isDataLake, isObjectStorage, isMessageQueue and isStreamingStorage through the proxy instead DISAGREE StorageProxy has never forwarded them, so those answers are already what every lazy_load_tables table gets, and forwarding would materialize storages in new places, including on every rename. #113389 and #117972 are adding non-materializing accessors there, which is the reason this PR guards the consumer instead
3 ❌ Two stored forms still abort: AS <table function>(<collection>), and a bare ENGINE = Remote(<collection>), which reports CLUSTER_DOESNT_EXIST rather than 669 AGREE, scoped Verified in the parsers: createTableFromAST parses a table function's arguments before StorageTableFunctionProxy sees them, and the Remote parser only forces the collection error when a key = value argument follows, so a lone identifier is read as a cluster name. The title, changelog entry and description now scope the claim to a load that reports NAMED_COLLECTION_DOESNT_EXIST, and name both forms
4 ❌ The rename tolerance does not hold in an Ordinary database: DatabaseOnDisk::renameTable calls the proxy's materializing rename AGREE, scoped Deliberate. There the rename moves the table's data directory and the call already re-attaches it under the old name, so the failure is pre-commit and consistent; only Atomic, which throws after committing the move, was leaving inconsistent state
5 ⚠️ The recovery assertion could not fail for the right reason: query_and_get_error requires the read to fail, and the restored collection points at a dead endpoint, so excluding one error name also passes for an unrelated materialization failure AGREE, fixed It is now a transition on the engine column, TableProxy while the collection is missing and URL once it returns. getName() forwards only after a successful materialization, so that is a positive oracle rather than the absence of one string
6 💡 DROP TABLE, DROP DATABASE and a table-less SYSTEM STOP MERGES still fail with 669, and so does a convert_ordinary_to_atomic start, whose conversion step takes every table's action lock AGREE, disclosed The first three are in the description with both remedies, and the blast radius is measured rather than argued: on master such a table cannot be dropped even after the collection returns, so every arm is strictly better here. Tolerating them at the storage would change behaviour for every lazy_load_tables user
7 💡 The shipped tests name the three columns that were throwing; the whole-catalog SELECT * form is A/B measured but not asserted AGREE, disclosed Reverting the guards already reddens the named-column form, so the broader assertion would only guard future changes elsewhere; the A/B result is in the description
8 ❌ A push-source stand-in (Kafka, S3Queue, RabbitMQ, NATS, FileLog, AzureQueue) silently accepted a cross-database RENAME that StorageObjectStorageQueue::checkTableCanBeRenamed would have vetoed, so once the collection returned the table would process against a different implicit Keeper path (zk_path_prefix / database_uuid / table_uuid) AGREE, fixed Fixed by keeping such a table out of the path entirely: one condition, so its load still fails exactly as on master. Deliberately not the forwarding suggested in row 2, which would materialize on every rename and would make RENAME of a stranded table throw 669 against this PR's own changelog. Measured both ways: with the exclusion reverted the Kafka table is attached as a stand-in and the new assertion reddens, while the URL table in the same database still gets its stand-in on the same binary
9 ❌ The same stand-in answers isStreamingStorage() = false, so SYSTEM STOP/CANCEL skipped an engine that would be actively ingesting once a materialized view materialized it AGREE, fixed Same one condition resolves both. isStreamingStorage is final-true only in IStreamingStorage, defaulted false in IStorage, and forwarded by neither proxy, so the classification is simply never asked of a proxy on this path now. Under lazy_load_tables the exposure is master's own (d1af6ff6c5b29d8 admits a push source with no dependent view) and this PR does not widen it
10 ⚠️ A stand-in registers its named-collection dependency only on materialization, so DROP NAMED COLLECTION sees no dependent in that window DISAGREE NamedCollectionsHelpers.cpp registers the edge only after a successful lookup, so every lazy_load_tables stand-in on master today is already in that state: the window belongs to the pre-existing lazy path, not to this PR. For this PR's population the collection is missing at load time, so no edge can exist on master either, where the table is additionally unreachable. #112805 adds addDependency immediately before make_shared<StorageTableProxy> on this exact path, so registering it here would duplicate and conflict with that hunk
11 💡 The first integration function has no try/finally, so an assertion failing after its restart leaves the stranded table behind for the rest of the module; the function added beside it uses its own database and a finally AGREE, noted Not blocking: the leftover exists only once the test has already failed, and the sibling that needed isolation has it
12 💡 Two statements in this description were invalidated by the last round's narrowing, and the one open PR whose title reads like a superseding fix (#118699) was unnamed AGREE, fixed Both corrected before publication, and the final gate re-run against the corrected text

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

@clickhouse-gh clickhouse-gh Bot closed this Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a626b23]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) FAIL
03262_filter_push_down_view FAIL cidb
01414_push_predicate_when_contains_with_clause FAIL cidb
03174_exact_rows_before_aggregation FAIL cidb

AI Review

Summary

This PR teaches DatabaseOrdinary::loadTableFromMetadata to attach a lazy StorageTableProxy instead of aborting startup when a stored engine refers to a missing named collection, and it hardens system.tables, system.columns, and Atomic rename against that proxy. The main remaining issue is that the recovered proxy still exposes several IStorage defaults until it materializes, so some first-write paths still fail after the collection is recreated; because that breaks the promised "works again without a restart" contract, I would request one more fix before merge.

Findings

⚠️ Majors

  • [src/Databases/DatabaseOrdinary.cpp:447-457] Attaching a stranded table via loadTableLazy also gives non-lazy URL/object-storage/external tables a StorageTableProxy whose insert-time capability bits are still the IStorage defaults. InterpreterInsertQuery::execute checks supportsPartitionBy and the external-engine classification before any call that would materialize the proxy, so after the collection is recreated a recovered URL/S3 table still rejects the first INSERT ... PARTITION BY with NOT_IMPLEMENTED, and with disable_insertion_and_mutation a plain insert into S3/MySQL is rejected as a forbidden local insert.
    Suggested fix: cache the capability values the insert path needs on the stand-in (at least supportsPartitionBy, isObjectStorage, and isExternalDatabase, or an equivalent classification), or exclude the affected engines from this recovery path until those bits can be answered without eager materialization.
Tests
  • ⚠️ Add a focused regression test that recreates the collection and exercises the first write through the stand-in, for example INSERT ... PARTITION BY into a URL/S3 table. The current tests only prove read-side recovery.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Preserve the insert-time capability contract for recovered stand-ins so the first write after recreating the collection can succeed without a warm-up read or restart.
  • Add a focused regression test for that first-write path.

LLVM Coverage Report

Measured on commit a626b23.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Changed C/C++ lines covered: 62/65 (95.38%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on every arm, both builds. Reduced to two clickhouse local --path invocations on one directory: create a URL(nc) table, drop the collection with check_named_collection_dependencies = 0, re-enter. No fuzzer, no CI harness, no injected setting. The three consumer defects fixed alongside the boot abort are equally deterministic against that same store.
b Root cause explained? Yes, two related facts, both frame chains read off real stacks. (1) Every engine resolves its named collection inside its registration lambda, before the storage is constructed, through tryGetNamedCollectionWithOverrides whose throw_unknown_collection defaults to true, so NAMED_COLLECTION_DOESNT_EXIST escapes createTableFromAST and fails the table's load job: fatal in sync mode (waitLoad rethrows out of Server.cpp) and in async mode (getTablesIterator waits on every table's startup task). (2) Such a table is the first thing in the tree given a StorageTableProxy whose materialization is guaranteed to throw; three consumers written for lazy_load_tables had only ever met proxies that materialize successfully, so they propagated it.
c Fix matches root cause? Yes. The failing load job is the defect, and the fix makes it succeed with the stand-in that already exists for tables that cannot be built eagerly, caught in the frame that called the throwing constructor so e.code() is still live and no message parsing is needed. Each consumer guard copies an exception idiom already present in the function it edits. No widened bound, no no-random-* tag, no reduced dataset. Scoping proved, not asserted: a MergeTree table naming a storage policy that no longer exists still aborts the boot identically on both builds (Code: 478 UNKNOWN_POLICY). The exclusion keys on the same engine predicate canUseLazyStandIn already uses, so the two paths cannot disagree about what a push source is.
d Test intent preserved / new tests added? No existing assertion weakened. Two new tests: a stateless test for the async arm, and one function in test_named_collections/test.py reusing that file's with_replace_config fixture for the restart-plus-config-removal route. One existing statement was deliberately widened rather than added to: name, engine became name, engine, data_paths, metadata_version, because StorageTableProxy::getName() avoids materializing and a column-pruned listing therefore could not have caught the system.tables defect. Oracles are discriminating: grepping for the error name matches on master too (the wrapped 722 -> 695 -> 669 chain contains it), so the shipped form anchors on the first error line; and the recovery arm asserts the engine column transitioning TableProxy -> URL, reachable only through a successful getNested(), rather than the near-vacuous "no longer fails with NAMED_COLLECTION_DOESNT_EXIST" (query_and_get_error requires the query to fail, and the restored collection points at an unreachable endpoint). A second function covers the exclusion, positive on both halves in one database: the URL table is EXISTS-attached and reports the missing collection without an ASYNC_LOAD_WAIT_FAILED wrapper, which proves its own load job completed, while the Kafka table is absent and its error names its own failed job. It reads EXISTS TABLE because no system.tables read of a database holding a failed load job can succeed, for any table in it.
e Both directions demonstrated? Yes, four ways. Arms A1/A2/A3, pristine-master build vs the fix (Ready for connections 0 -> 1; system.tables ASYNC_LOAD_WAIT_FAILED -> the table listed). Both tests through their real runners, driven only by swapping the binary: stateless [ FAIL ] (Code: 669 ... While executing Tables / ... Columns) vs [ OK ]; integration 1 failed in 62.42s at RENAME TABLE t_startup TO t_startup_renamed vs 1 passed in 179.49s. A mutation arm: deleting only the new if, keeping the refactor, returns every arm to master. A server-wide arm: SELECT * FROM system.tables FORMAT Null over 172 tables throws before, returns cleanly after. The recovery assertion carries its own two directions (with the collection deliberately not restored it fails 'TableProxy' == 'URL'), and on the mutant each new assertion reddens at its own line. The exclusion has a pair at shipped-test level: with only that one condition reverted and rebuilt, the new function fails at assert "ASYNC_LOAD_WAIT_FAILED" in error while the URL function still passes on that same binary.
f Fix is general across code paths? Yes, on both halves. The load-path edit covers DatabaseOrdinary, DatabaseAtomic, DatabaseReplicated and DatabaseBackup, none of which overrides loadTableFromMetadata or startupTableAsync, and DatabaseOverlay delegates; it covers every engine at once because they all resolve their collection inside creator_fn before construction. Deliberately not pushed down into createTableFromAST, which is also loadTableLazy's get_nested body. Every path reaching the stand-in's storage was enumerated and is guarded or documented safe: the temporary-tables branch emits defaults and reads neither accessor; tryGetSerializationHints resolves to IStorage's default because neither proxy overrides it; storesDataOnDisk() returns true unconditionally. The guards are on the CONSUMERS, never on the proxy: teaching the proxy to answer without materializing would change data_paths, metadata_version and column sizes for every existing lazy_load_tables user. The exclusion is set-based: StorageFileLog is in it although it is not an IStreamingStorage, because its ingestion task is likewise activated only in startup(), and StorageKafka2 is covered because the set keys on the engine name the DDL carries.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes along the axes that exist; not a type-dispatch change, so wrapper and boundary matrices do not apply. Measured: engine (URL and S3 receiving the stand-in, Kafka excluded), how the collection went away (SQL DROP with the documented opt-out, and removing its conf.d entry, which has no DROP to intercept), async_load_databases 0 and 1, force_restore_data present and absent, dependent materialized view present and absent, column list explicit vs inferred, and per-column-mask coverage of both system tables (single columns, and SELECT *). The column-list axis was an open question in the plan: a column-less CREATE TABLE ... ENGINE = URL(nc) still persists a full column list, so no guard was needed.
h Backward compatible? (maintainer-approved exception only) Yes. No new setting and no default changed, so no SettingsChangesHistory.cpp entry is owed; no on-disk format change; no marker file written; no new grant. The observable differences are a table reporting engine = 'TableProxy' until first access, which lazy_load_tables already produces today, and data_paths = [] / metadata_version = 0 / empty column sizes for such a table, which is what an engine with no on-disk data reports anyway.
i Invariants and contracts preserved? Yes, and one pre-existing violation is repaired. The throw path is byte-identical for every other exception and the Coordination::Exception hardware-retry catch above is untouched. startupTableAsync finds the stand-in and calls its no-op startup, so it never reaches its LOGICAL_ERROR for a parsed-but-unattached table. shouldLazyLoad is unchanged by construction: the extraction is a rename plus a three-line wrapper, so no predicate was added, removed or reordered. In the system tables the guarded blocks keep column-count alignment by using res_columns[res_index] inside the try and ++res_index after it, and the data_paths guard preserves the shared-lock release on both paths. The repair: DatabaseAtomic.cpp documents "After metadata was successfully moved, the following methods should not throw (if they do, it's a logical error)", yet tryCreateSymlink read the table's data path outside its own catch-all, so RENAME TABLE returned an error for a rename that had already committed (the user retries and gets UNKNOWN_TABLE for a table that did move), and EXCHANGE TABLES a AND b threw between the two attach calls, leaving b attached to neither database in memory until restart. Stated plainly rather than claimed as strengthenings: materialization runs under the global context loadTableLazy already captures, and a stand-in registers its collection dependency only when it materializes, exactly as lazy_load_tables does today. Two engine contracts a stand-in cannot carry are preserved by keeping such a table out of the path entirely: StorageObjectStorageQueue::checkTableCanBeRenamed, which DatabaseAtomic::renameTable would otherwise validate against IStorage's no-op because StorageProxy forwards only isRemote and isView; and isStreamingStorage, which both of InterpreterSystemQuery's streaming paths read and neither proxy overrides. Forwarding either calls getNested(), so it would materialize on every rename.

Session id: cron:clickhouse-impl-slot-40:20260917-234600

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 18, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 18, 2026
@PedroTadim

PedroTadim commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

@groeneai this still doesn't sound like the real solution. I think the real one is that if a table has a named collection dependency, it shouldn't be dropped. This is a backward-incompatible change, but the more defensive solution

The first run on this head produced no result: praktika's Config Workflow failed
its "Check CI DB" leg because the CI database refused every request with
"Code: 202. DB::Exception: Too many simultaneous queries. Maximum: 1000", so all
171 dependee jobs were set to DROPPED and no test job ran. The same leg failed
the same way on unrelated pull requests over the same period, so this was a
shared infrastructure event and not a property of this branch.

The run is already at attempt 2, and the hourly infra-retry workflow only
selects runs at attempt 1, so nothing upstream will re-dispatch it. A fresh head
is the only remaining path. No code change.

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

Copy link
Copy Markdown
Collaborator Author

The refusal you describe is already open as @ alexey-milovidov's #112805: it counts detached tables as dependents, so DROP NAMED COLLECTION is refused with NAMED_COLLECTION_IS_USED. I did not duplicate it, and the two compose (it registers the dependency on the stand-in path this PR adds).

I do not think a refusal can be the whole answer, because the collection can go missing with no DROP to intercept:

  • A collection defined in config.d disappears when its entry is edited out: NamedCollectionFactory::reloadFromConfig removes every config-sourced collection and re-adds only those still listed, both on SYSTEM RELOAD CONFIG and at startup. I validated that arm.
  • The dependency check sits entirely under if (settings[check_named_collection_dependencies]) in InterpreterDropNamedCollectionQuery, so a user can switch it off and strand an attached table today.
  • Metadata already stranded on disk, or restored from such a server, has to boot before anyone can repair it.

The abort is also only one of the two symptoms. With the packaged default async_load_databases = 1 the server does start, but a system.tables scan of that database fails with ASYNC_LOAD_WAIT_FAILED, which contradicts what that setting documents. A drop-side guard does not change that half.

#77366 is the same chain reported on MySQL: the drop-side guard was the fix chosen there, and the reporter had asked for this shape instead, "I think the check is so strict. Just throw exception when table used".

Making the refusal unbypassable is a call for you and @ alexey-milovidov, and I will take it if you want it. If you would rather the refusal be the whole answer, say so and I will close this PR.

fmt::format(
"Attaching {} without its storage, so reading the table reports this instead of the server refusing to start",
name.getFullName()));
loadTableLazy(local_context, name, ast, mode);

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.

Attaching the table through loadTableLazy also hands non-lazy URL/object-storage/external tables a StorageTableProxy whose insert-time capability bits are still the IStorage defaults until something else materializes it. InterpreterInsertQuery::execute reads those bits before any materializing call: the supportsPartitionBy guard runs before the first write, and the disable_insertion_and_mutation exemption branches on isObjectStorage / isExternalDatabase.

That means the PR's recovery contract is still broken on the first write after the collection is recreated. A recovered URL or S3 table will reject INSERT ... PARTITION BY with NOT_IMPLEMENTED, and on a server with disable_insertion_and_mutation even a plain insert into S3 / MySQL is rejected as if the table were local. This needs either cached capability answers on the stand-in for the insert path, or an exclusion for the affected engines until those bits can be answered without eager materialization.

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.

Checked both arms against the code and measured them; I am not changing the diff.

INSERT ... PARTITION BY is not reachable for a table. PARTITION BY is parsed only inside the INSERT INTO FUNCTION branch (ParserInsertQuery.cpp:110-121), the only place SQL sets ASTInsertQuery::partition_by, and when it is set getTable builds the storage from the table function (InterpreterInsertQuery.cpp:189), never from the catalog. So supportsPartitionBy() is never asked of a StorageTableProxy. Measured on this build: INSERT INTO t PARTITION BY a VALUES (1) gives Code: 62. Syntax error: failed at position 15 (PARTITION), while INSERT INTO FUNCTION file(...) PARTITION BY a SELECT 1 parses.

The disable_insertion_and_mutation arm is real, but it belongs to StorageProxy and predates this PR. Measured with no named collection anywhere and disable_insertion_and_mutation=1: an INSERT into an S3 table in a lazy_load_tables = 1 database is refused with Code: 392. Insert queries are prohibited, while the same insert into the same engine in an ordinary database passes that check and proceeds to I/O. StorageProxy does not forward isObjectStorage or isExternalDatabase, and this PR changes none of StorageProxy.h, StorageTableProxy.h, IStorage.h or InterpreterInsertQuery.cpp. #113389 and #117972 add the non-materializing accessors that answer those bits at the source; forwarding them from here would materialize storages on new paths, including on every rename.

Neither suggested remedy fits this path: at attach time there is no storage to read the capability bits from, because its collection is missing, and the "affected engines" are S3, URL, MySQL and the rest, which is every engine that takes a named collection.

On the requested test: writing through the stand-in is StorageProxy::write -> getNested(), master's code that the lazy_load_tables tests already cover, and test_missing_collection_in_config_does_not_block_startup asserts the stand-in materializes with no restart (the engine column flips from TableProxy to URL).

A design question on the whole approach is open above from @ PedroTadim, so I am leaving the diff as it is until that is settled.

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a626b2305 with master 8e93526d8 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 01b8f1c9f; 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

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

Median compile-time ratio to the baselines is ×1.08 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +24.5 s (+8%) in total before that adjustment.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a626b23

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01414_push_predicate_when_contains_with_clause not PR-caused: the same three tests fail in this lane on 110 other pull requests and on true master, first at 2026-09-17 19:36Z #120763 (external, merged 2026-09-18 09:15:34Z). Rule 3c, measured: not in the tree that ran
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03174_exact_rows_before_aggregation same lane, same family, same onset #120763 (external, merged 2026-09-18 09:15:34Z). Rule 3c, measured: not in the tree that ran
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 03262_filter_push_down_view same lane, same family, same onset #120763 (external, merged 2026-09-18 09:15:34Z). Rule 3c, measured: not in the tree that ran
Sync - CH Inc sync (private, not actionable by me)

Mergeable Check and PR carry no failure of their own: both are aggregators and both name the
stateless job above.

Root cause: merged #120477 deleted six entries from tests/parallel_replicas_blacklist.txt. In
this lane that file is an expected-to-fail list, so a listed test that fails is reported
SKIPPED; deleting an entry unmasks a pre-existing parallel-replicas divergence instead of
fixing it. #120763 restores all six. The three tests above are long-standing divergences (a lost
KeyCondition conjunct, a lost WITH-subquery pushdown, and a wrong rows_before_aggregation),
so they are not new breakage, and nothing in this pull request touches parallel replicas.

Why rule 3c and not 3d, measured rather than argued: praktika tested merge commit cd28f8f75e7e,
cut 2026-09-18 08:37:12Z, four seconds before this run was created. That tree is behind_by 2
relative to the fix merge 930ccf28 and carries none of the three entries, which is exactly why
the tests executed instead of being skipped. The entries do appear in this branch's own head, but
only because the branch predates #120477's deletion, so a presence check on the raw head cannot
tell "carries the fix" from "never received the breakage" when the fix is a revert.

I am deliberately not merging master to pick #120763 up on this head yet: a design ruling on
whether this pull request should exist at all is still outstanding on this thread, and I was
asked not to churn a queued pull request. Merging master is the first step once that ruling lands.

Session id: cron:our-pr-ci-monitor:20260918-140155

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-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.

2 participants