Skip to content

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

Closed
groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-url-named-collection-missing-on-attach
Closed

groeneai wants to merge 14 commits into
ClickHouse:masterfrom
groeneai:fix-url-named-collection-missing-on-attach

Conversation

@groeneai

@groeneai groeneai commented Jul 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105045

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 failing to start (Cannot start clickhouse-server) when a URL table references a named collection that no longer exists. A collection can be legitimately dropped while a dependent URL table exists (with check_named_collection_dependencies = false), and the ATTACH replayed at startup then threw NAMED_COLLECTION_DOESNT_EXIST. The table now attaches and the error is reported at query time.

Description

Reported on #105045 but unrelated to it: Stress test on
03822_named_collection_drop_dependency_check fails to restart the server, with
ATTACH TABLE ... ENGINE = URL(...) hitting NAMED_COLLECTION_DOESNT_EXIST. Reproduces on master.

Root cause: the URL engine resolves its named collection eagerly at attach time
(StorageURL::getConfiguration), but check_named_collection_dependencies = false lets a
collection be dropped while dependent URL tables exist. The persisted ATTACH replayed at startup
then aborts the server under synchronous loading.

Fix: when replaying a definition stored on this server, a missing collection attaches a lazy proxy
instead of aborting; it is re-resolved on first read/write, and if still missing the query fails
NAMED_COLLECTION_DOESNT_EXIST. A definition the user supplies now (CREATE, full-definition
ATTACH, RESTORE, Replicated DDL) still fails its own DDL instead of persisting an unusable
table, gated on the predicate StorageDistributed uses.

Also fixed while under review, every case where StorageProxy answers through getNested() (which
materializes), so the proxy reported the missing collection where eager URL answers directly:
the engine classification (isObjectStorage/isDataLake/isMessageQueue/isExternalDatabase),
read by InterpreterInsertQuery before the materializing write(), so an object-storage-backed
URL(nc) was rejected QUERY_IS_PROHIBITED under disable_insertion_and_mutation where the eager
form inserted; and checkAlterPartitionIsPossible, alterPartition, getCheckTaskList,
getActionLock, supportsReplication, getColumnSizes, where partition DDL and CHECK TABLE
reported NAMED_COLLECTION_DOESNT_EXIST instead of NOT_IMPLEMENTED and the last three are swept
over every table, so one unresolvable table made system.tables, system.columns and bulk
SYSTEM STOP MERGES throw.

Validated in both directions with 04540_url_named_collection_missing_on_attach and
tests/integration/test_disable_insertion_and_mutation, including a real restart with the
collection still missing. S3/Azure/HDFS resolve collections in their own fromAST path and
may share this.


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

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @kssenii @Algunenano could you review this? On ATTACH/startup the URL engine resolves its named collection eagerly, so a named collection dropped with check_named_collection_dependencies=false makes a dependent URL table abort synchronous server startup (NAMED_COLLECTION_DOESNT_EXIST -> Cannot start clickhouse-server, the 03822 stress failure from #105045). This defers URL named-collection resolution to the first query on ATTACH, so the table attaches and the error surfaces at query time instead of at startup.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Ordinary DB + CREATE TABLE t (x UInt32) ENGINE=URL(nc), then SET check_named_collection_dependencies=false; DROP NAMED COLLECTION nc, then restart with --async_load_databases=0. Server fails to start every time with the exact Code 722 Waited job failed -> Code 669 NAMED_COLLECTION_DOESNT_EXIST chain. Also reproducible interactively via DETACH TABLE + ATTACH TABLE t.
b Root cause explained? The URL engine resolves its named collection eagerly in StorageURL::getConfiguration (throw_unknown_collection=true) at attach time. When the NC was legitimately dropped (allowed by check_named_collection_dependencies=false), the persisted ATTACH TABLE ... ENGINE=URL(nc) replayed on startup throws NAMED_COLLECTION_DOESNT_EXIST. Under synchronous database loading the throw propagates as a load-job failure and aborts the whole server.
c Fix matches root cause? Yes. On mode != CREATE with persisted columns, a missing NC no longer throws at attach; the table attaches from persisted columns and the NC is re-resolved lazily on the first read/write (still throwing if missing at query time). This addresses the eager-resolution mechanism directly rather than suppressing the error.
d Test intent preserved / new tests added? Added regression test 04540_url_named_collection_missing_on_attach asserting: table attaches with the NC missing, the table exists, SELECT fails with NAMED_COLLECTION_DOESNT_EXIST, and recreating the NC makes it usable again. No existing test weakened.
e Both directions demonstrated? Yes. Pre-fix binary: synchronous startup fails to start and interactive ATTACH TABLE throws. Post-fix binary: server starts (startup table odb.t OK, Ready for connections), ATTACH TABLE succeeds, SELECT fails at query time as expected, NC recreation restores it. Regression test passes.
f Fix is general across code paths? Covered for the URL engine (the reported failure; NC is http://). Scheme-dispatch (file/s3/azure/hdfs) already swallows classification errors and falls back to the plain-URL path, so it is covered too. S3/Azure/HDFS object-storage engines resolve NCs in their own fromAST path and may have a similar issue on ATTACH; noted as out-of-scope follow-up in the PR body since it is a separate code path with no deterministic repro here.
g Fix generalizes across inputs? The deferral triggers on NAMED_COLLECTION_DOESNT_EXIST regardless of column types/format/compression; columns come from persisted metadata so datatype/wrapper variance is irrelevant to the attach path. Lazy re-resolution uses the same getConfiguration as CREATE, so all argument forms (bare NC, NC + overrides) resolve identically at query time.
h Backward compatible? Yes. No setting default, on-disk/wire format, or metadata change. Behavior only changes for the previously-fatal case (missing NC on attach): startup now succeeds instead of aborting, and the error is reported at query time. No downgrade concern (persisted metadata is unchanged).
i Invariants and contracts preserved? Yes. The deferred StorageURL sets full metadata (persisted columns + virtuals) so the storage snapshot contract holds. read()/write() call finalizeConfigurationIfDeferred before using uri, so no code path observes an empty uri. Resolution is guarded by a mutex (published safely to concurrent readers). addInferredEngineArgsToCreateQuery is a no-op while deferred, preserving the persisted engine args (which already reference the NC).

Session id: cron:clickhouse-worker-slot-2:20260715-092300

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

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aea6de7]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR fixes the startup/ATTACH failure for URL tables whose named collection was dropped by deferring reconstruction until first use, and the current implementation now carries the needed URL-specific metadata, DDL, dependency-tracking, and scheme-dispatch behavior through that deferred path. I did not find any remaining correctness, safety, or contract regressions in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit aea6de7.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 156/210 (74.29%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 15, 2026
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reworked (52fd292). The in-place deferred StorageURL was too lossy: a storage's type is fixed at construction, so it could never rebuild the scheme-dispatch delegate, hive partitioning, or infer a format. All three points come from that.

New approach defers the whole construction instead of just the uri. When named-collection resolution throws NAMED_COLLECTION_DOESNT_EXIST on ATTACH/startup, the creator returns a StorageTableProxy whose factory re-runs the full URL creator via createTableFromAST on first access. Once the collection is recreated, scheme dispatch (file/s3/az/hdfs), hive partitioning, virtual columns and format inference are all rebuilt through the identical eager path. A thread-local guard stops the retry from deferring again, so a still-missing collection re-throws the real error at query time.

Addresses all three:

  1. storage class: file:// nc now dispatches to the File delegate on first use (verified rows returned via File, not HTTP StorageURL).
  2. hive/virtuals: the year virtual column is rebuilt with the resolved sample path (verified with use_hive_partitioning=1, both query-level and stored table setting).
  3. implicit format: no more format=auto/UNKNOWN_FORMAT; the concrete format is inferred as in the normal ctor.

Regression test extended to cover all three cases plus DROP-while-deferred (StorageTableProxy drop checks now tolerate an unloadable table). Local A/B: pristine master aborts ATTACH with NAMED_COLLECTION_DOESNT_EXIST; patched binary attaches and resolves all cases after the collection is recreated.

Comment thread src/Storages/StorageTableProxy.h Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Reverted the tryGetNested()-returns-nullptr shortcut in StorageTableProxy checkTableCanBeDropped / checkTableSizeBelowDropLimit back to master (9c0225f). You are right that this silently turned "cannot materialize" into "safe to drop": it bypassed max_table_size_to_drop for lazy MergeTree and, for a deferred URL(nc) that dispatches to StorageObjectStorage, let DatabaseOnDisk remove only local metadata while StorageObjectStorage::drop never ran, leaking remote objects.

Since the URL lives inside the missing collection, the backend is unknown while the collection is missing, so no subset of drops (e.g. plain-HTTP-only) can be safely allowed. DROP now propagates NAMED_COLLECTION_DOESNT_EXIST until the collection is recreated, then drops normally through the real backend. Added a regression covering both (DROP while missing surfaces the error; DROP after recreate succeeds). The startup-abort fix and its other regressions are unchanged.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 0990454. The deferred URL(nc) table now uses a dedicated StorageDeferredURL proxy (subclass of StorageTableProxy) that keeps the plain URL DDL contract while the collection is still missing, without materializing the nested storage:

  • rename: metadata-only (renameInMemory), like IStorage::rename / StorageURLSchemeDispatch::rename. storesDataOnDisk()/getDataPaths() also report empty while unmaterialized so DatabaseAtomic::tryCreateSymlink (reached on RENAME) does not force getNested().
  • supportsTruncate: false (bulk TRUNCATE ALL/LIKE skips it).
  • truncate: throws NOT_IMPLEMENTED (the URL contract), and checkTableCanBeDropped/checkTableSizeBelowDropLimit are no-ops while unmaterialized so an explicit TRUNCATE TABLE reaches this instead of surfacing the missing collection.

DROP while the collection is missing is now allowed (metadata-only), matching the plain URL engine: StorageFile::drop and plain object storage configuration->drop() (S3/Azure/HDFS) are no-ops, and URL(nc) only dispatches to those, so no external objects are leaked. The shared StorageTableProxy is unchanged (only made subclassable), so lazy MergeTree keeps max_table_size_to_drop.

Test 04540 extended with RENAME (succeeds, metadata-only) and TRUNCATE (NOT_IMPLEMENTED) while the collection is missing; the DROP-while-missing case now asserts success.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Added the remaining URL-specific overrides on StorageDeferredURL (commit 8a66b7f), so the deferred proxy keeps the plain-URL contract while the collection is missing without materializing:

  • checkAlterIsPossible/alter: while unmaterialized, use the IStorage defaults (metadata-only comment alters allowed, else NOT_IMPLEMENTED), matching plain URL. So ALTER TABLE ... MODIFY COMMENT no longer retries the creator / throws NAMED_COLLECTION_DOESNT_EXIST. Once materialized it forwards to the resolved storage.
  • supportedPrewhereColumns/canMoveConditionsToPrewhere: forwarded to the resolved storage (which materializes at planning time), matching IStorageURLBase/StorageURLSchemeDispatch instead of the broader IStorage std::nullopt default, so a recovered hive/default-column table gets the narrow URL PREWHERE contract.
  • supportsTrivialCountOptimization: forwarded for parity with StorageURLSchemeDispatch (StorageProxy does not forward it).

Change is confined to StorageDeferredURL; the shared StorageTableProxy is unchanged.

04540 extended: ALTER ... MODIFY COMMENT while the collection is missing succeeds (metadata-only) and a non-metadata ALTER ADD COLUMN returns NOT_IMPLEMENTED, not the missing-collection error. Verified fails-without-fix (pristine binary throws NAMED_COLLECTION_DOESNT_EXIST on the comment alter) and passes with the fix.

Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Addressed the create_query staleness and dependency-graph gaps (169004c).

  • The deferred proxy no longer replays the frozen attach-time create_query. get_nested now receives the proxy's current StorageID and rebuilds from the table's current CREATE query (getCreateTableQuery), so a metadata-only ALTER MODIFY COMMENT or RENAME applied while the collection was missing survives first materialization, and the dependency is re-registered under the current table name.
  • The named-collection dependency is now registered at ATTACH time (from the first engine-arg identifier, available even when the collection is missing), not only after first read. After a restart the dependency graph starts empty, so without this a recreate+drop before the first SELECT would let DROP NAMED COLLECTION wrongly succeed with check_named_collection_dependencies=1. The attach-time placeholder is removed before the creator re-registers on materialization (and restored if the collection is still missing) so the table is never left untracked or double-counted.

Test 04540 extended: comment survives materialization; DROP NAMED COLLECTION is rejected before any read and after a rename-while-missing (dependency tracked under the current name), verified fails-without-fix.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 7546f80. `StorageDeferredURL` now overrides `drop()` to not materialize while unmaterialized (forwards to the nested storage once materialized). A URL table drop is metadata-only (plain URL/File/object-storage backends have a no-op `drop()`, external objects are never deleted), so nothing needs the nested storage. This stops the resurrected `getConfiguration(..., &current_id)` re-registration for a table being dropped, which in an Ordinary DB left a stale name-based dependency that made a later unrelated same-named table trip `NAMED_COLLECTION_IS_USED`. Regression added to 04540 (drop deferred table, recreate an unrelated same-named table, DROP NAMED COLLECTION must succeed).

Comment thread src/Storages/StorageURL.cpp Resolved
Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Both addressed in 6c4ee72.

  • Dependency handoff gap: made NamedCollectionFactory::addDependency idempotent (a (collection, table) dependency is set membership; removeDependencies erases all entries for a table and there is no remove-one op, so no caller relies on duplicates). The deferred creator now keeps the attach-time placeholder in place across the whole handoff instead of remove-then-restore, so getConfiguration re-registration is a no-op and check_named_collection_dependencies never sees a zero-dependent gap.

  • URL virtuals invisible: StorageDeferredURL now seeds its cached metadata with the URL file-like virtuals (_path/_file/_size/_time/_headers, ...) at construction, so they resolve from getInMemoryMetadataPtr() before materialization. Verified with DESCRIBE ... describe_include_virtual_columns=1 (before: only the real column; after: URL virtuals listed). Hive-partition virtuals stay path-dependent and are rebuilt on materialization.

04540 extended with both cases.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Flaky-check FAIL on amd_asan_ubsan (test runs too long, >180s) fixed in 49738e8: tagged 04540 long. The test runs ten independent DETACH/ATTACH-replay scenarios (each a reviewer-required case) so it cannot be trimmed without dropping coverage; long exempts the 180s flaky-check limit and reduces its repeat count. No result mismatch was involved. Comment-only Tags change, so all functional coverage is preserved.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixed in 034c324. StorageDeferredURL now takes args.constraints and args.comment and seeds both into its cached StorageInMemoryMetadata alongside the columns/virtuals, matching the eager IStorageURLBase / StorageURLSchemeDispatch constructors. So the INSERT metadata snapshot carries the CHECK constraints (first INSERT after the collection is recreated is rejected with VIOLATED_CONSTRAINT), and system.tables.comment / system.constraints are correct before materialization.

Regression added to 04540: attach a deferred URL(nc) with a CHECK constraint and a table comment, drop the collection, ATTACH; the comment is visible from system.tables before any read, and after recreating the collection the first INSERT violating the constraint fails with VIOLATED_CONSTRAINT. Build-ID A/B: pristine drops the comment and skips the constraint; fixed enforces both.

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

I could not reproduce this and I do not think the gate is reachable here, so I have not made a change.

InterpreterInsertQuery's supportsPartitionBy() check at InterpreterInsertQuery.cpp:1039 fires only when query.partition_by is set, and ParserInsertQuery sets partition_by only for the INSERT INTO FUNCTION ... form (ParserInsertQuery.cpp:107-118). For an attached/named table there is no grammar production that accepts PARTITION BY, so the query fails at the parser before the gate:

-- eager (non-deferred) URL(nc) table, master behavior:
CREATE NAMED COLLECTION nc AS url='http://localhost:8123', format='CSV';
CREATE TABLE u (x UInt32) ENGINE=URL(nc);
INSERT INTO u PARTITION BY x VALUES (1);
-- Code: 62 SYNTAX_ERROR: failed at position 16 (PARTITION) ...

-- same on Memory (supportsPartitionBy()==false): also SYNTAX_ERROR, not NOT_IMPLEMENTED.

Because a deferred URL(named_collection) is always an attached table, the supportsPartitionBy() gate is never consulted for it (nor for an eager attached URL table), so there is no eager-vs-deferred divergence and no test can drive the reported NOT_IMPLEMENTED. StorageURL::supportsPartitionBy()==true is only relevant to the INSERT INTO FUNCTION url(...) path, which never produces this proxy.

If you have a concrete query that reaches the gate through an attached deferred URL(nc) table, I will add the override plus a regression; otherwise I would rather not forward supportsPartitionBy() for a path that cannot be exercised.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 034c324

All checks green on this head. No failures.

Check / test Reason Owner / fixing PR
(all checks) — passed
Sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260716-090000

…ssing

A URL table whose named collection was dropped with
check_named_collection_dependencies=false used to abort synchronous server
startup with NAMED_COLLECTION_DOESNT_EXIST because the URL engine resolves its
named collection eagerly on ATTACH.

Defer the resolution behind a lazy StorageDeferredURL proxy (based on
StorageTableProxy) so a missing named collection no longer prevents startup;
the real StorageURL is materialized on first use once the collection exists.

The proxy preserves the eager URL storage contract: DDL semantics
(CREATE/ALTER metadata-only path, planner contract), DROP safety for
unresolvable tables, named-collection dependency tracking at attach time,
up-front URL virtual columns, and table-level constraints and comment seeded
into the cached metadata. Adds regression test
04540_url_named_collection_missing_on_attach (tagged long to stay under the
flaky-check time limit).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-url-named-collection-missing-on-attach branch from 034c324 to d35585d Compare July 21, 2026 11:49
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

Resolution of the Finish Workflow / Post Hooks (new_tests_check.py) row on my CI finish ledger

I promised a fixing-PR link for this row. There will not be one: I investigated the hook
and concluded no fix to it is warranted. Recording that here rather than leaving the
promise open.

new_tests_check.py reds Post Hooks when no per-arch Bugfix validation job reported a
strict success. Measured over the last 30 days, that happens for two reasons, and neither
is a defect in the hook:

  1. The per-arch jobs were dropped or skipped by an upstream failure. In a 12 hour
    sample every one of the 10 rows with this text resolved to a real upstream red on the
    same head (a Fast test failure, a Build (arm_tidy) failure) that dropped the whole
    downstream matrix, or to a genuine "bug does not reproduce on this arch" verdict. The
    hook is relaying that faithfully; suppressing it would remove signal. Fix or re-run the
    upstream job and this row clears on its own.
  2. The validation job aborted with no completed test row. I first read this as the
    gate passing on zero evidence. It is not: in 12 of 12 sampled runs the job uploaded a
    core dump whose thread matches that PR's own bug (core.MergeMutate for a mutation
    bug, core.QueryPullPipeEx for a SELECT bug, and so on). On a debug or sanitizer
    master-HEAD binary a reproduced logical error aborts the server, which is exactly a
    zero-row abort, and reconcile_bugfix_crash_repro documents that abort as the bug
    reproducing. So the verdict is correct.

Two smaller diagnostics gaps I am not fixing here, since both change what
clickhouse-test reports rather than fixing a bug: the wedged server's logs are not
collected, so the fatal-message check greps an empty directory and the report shows
Failed: 0, Passed: 0, Skipped: 0 with no hint that a core was captured; and distinct
StopTesting causes are not given distinct exit codes the way the global time limit and
max-failures stops are.

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you are the only one who can review this

One conflict, in the `URL` storage creator registered by `registerStorageURL`.

Master added `checkStorageSettingNames(args)` as the creator's first statement
(SETTINGS-name rejection for File/URL/S3/Log), directly above the scheme dispatch.
This branch had moved that dispatch, with the rest of the creator body, into
`createStorageURLImpl` so the lambda can wrap the whole construction in the
deferral for a missing named collection.

Resolved by keeping master's check as the first statement of the lambda, ahead of
the deferral decision, so the resulting order is the same as master's: validate
the SETTINGS names, then dispatch by scheme (now reached through
`createStorageURLImpl`, which both the eager and the deferred-retry branch call).
Putting it inside `createStorageURLImpl` instead would have re-run it on every
materialization attempt of a deferred table.

Verified after resolution that `createStorageURLImpl`'s body is line-for-line
master's creator body, so none of master's edits to that code were lost to the
move, and that the net diff against master is still exactly this PR's 8 files
with no submodule gitlink drift.
Two things this branch relied on changed under it while it was stale.

`IStorage::alter` gained a `DDLGuardPtr & ddl_guard` parameter, so the deferred
proxy's three-parameter override no longer overrode anything and did not compile.
Forward the new parameter to both bases; a proxy has nothing of its own to do with
the guard.

`system.tables` now asks every row whether it is a data lake
(StorageSystemTables.cpp:945), unconditionally rather than inside the total_rows and
total_bytes column branches it used to be gated behind. isDataLake answered by
materializing, so a catalog sweep over a table whose named collection is missing
reported that absence instead of a row: SELECT comment FROM system.tables and SELECT
metadata_version FROM system.tables both failed with NAMED_COLLECTION_DOESNT_EXIST,
and 04540 caught it.

Answer isDataLake from the proxy while the delegate is absent. It is the only one of
the four classifications a catalog sweep reads -- system.tables is the sole caller
outside InterpreterInsertQuery -- and false is also the delegate's answer, because no
engine a URL can dispatch to (URL, File, S3, AzureBlobStorage, HDFS) carries a data
lake configuration; isDataLakeConfiguration is false outside DataLakeConfiguration.

The other three keep materializing. They are reached only by the
disable_insertion_and_mutation guard, which runs before the write that would
materialize anyway, and which engine serves a URL depends on the resolved URL, so the
delegate has to answer: an s3:// collection must be exempted as object storage.
Suppressing the missing-collection error here instead would have cost the promise the
deferred creator makes, that first use surfaces the real resolution error -- measured,
that insert reported QUERY_IS_PROHIBITED rather than the missing collection.

Measured with the Build IDs asserted against SELECT buildId(). Without this commit
04540 fails on three hunks with Code: 669; with it 04540 passes byte-exact, the sweep
over the unresolved table returns its row with zero materializations in the server log,
and the same insert reports Code: 669 while the collection is missing and consults the
delegate once it is recreated. Separately, a real restart with the collection's
metadata file deleted brings the server up with no "Cannot attach table", keeps the
table catalogued as URL, and still reports Code: 669 when the table is read.
The deferral predicate was written to mirror StorageDistributed, which answers the same
question: is this definition being introduced now, or replayed from metadata this server
already stored? Master has since added a third term to that predicate at every site
carrying it, because one replay route is invisible to the other two.

DatabaseReplicated::recoverLostReplica and SYSTEM RESTORE DATABASE REPLICA re-execute the
CREATE statement stored in Keeper. parseQueryFromMetadata sets create.attach = false, so
the replay arrives below LoadingStrictnessLevel::ATTACH with no short syntax: both
existing terms are false and it is indistinguishable from a user CREATE by mode alone.
Context::isRecoveryFromStoredMetadata carries the provenance instead.

Without the third term a URL table whose named collection is absent fails its own stored
definition during recovery, which is the failure this PR exists to prevent, one level up:
the replica rejects its own metadata and retries forever rather than deferring and
recovering. StorageDistributed.cpp:2702, StorageFactory.cpp:66 and
registerStorageMergeTree.cpp:590 all consult it for the same reason.
The stress profile sets ast_fuzzer_runs=5 (ci/jobs/scripts/fuzzer/query-fuzzer-tweaks-users.xml),
so the server re-runs a mutated copy of every statement. This test repeatedly creates tables and
then drops the named collections they reference, which is exactly the shape where a fuzzed CREATE
or DROP leaves a table behind that references a collection the test then drops: the assertions stop
being deterministic and the run can strand metadata that no later test can load.

The sibling 03822_named_collection_drop_dependency_check pins ast_fuzzer_runs = 0 in three blocks
for this reason. Every query here goes through $CLICKHOUSE_CLIENT, so pin it once on the variable
rather than in 29 separate settings blocks.
The deferral predicate's comment and the isDataLake comment both restated their commit
messages. Keep the properties a reader cannot derive from the code -- that only a replayed
definition may defer, that a Replicated replay is invisible to `mode` alone, that
`system.tables` reads the classification per row, and that no engine a `URL` dispatches to
carries a data lake configuration -- and drop the retelling.

Comments only: the comment-stripped file is byte-identical.
Comment thread src/Storages/StorageURL.cpp Resolved
AlterCommands::validate reads supportsTTL and supportsStatistics on the storage the ALTER is
addressed to, and it runs before checkAlterIsPossible (InterpreterAlterQuery.cpp:366 vs :373).
StorageDeferredURL inherited both from StorageProxy, which forwards through getNested(), so
ALTER ... MODIFY TTL and ALTER ... ADD COLUMN c UInt64 STATISTICS(...) on an attached-but-unresolved
URL(named_collection) table reported NAMED_COLLECTION_DOESNT_EXIST instead of the plain URL engine's
own refusal. Same class as the AlterPartition and CHECK TABLE overrides already on this branch:
unsupported DDL must not depend on whether the named collection happens to exist.

Answering both from the proxy while unmaterialized restores the eager path's errors byte for byte
(BAD_ARGUMENTS "Engine URL doesn't support TTL clause", NOT_IMPLEMENTED "Engine URL doesn't support
statistics"), and the table stays unmaterialized: SELECT still reports the missing collection. These
two are the complete set for that function; every other storage predicate validate() consults is
either already non-materializing here or a cast on the proxy itself. No engine a URL dispatches to
supports TTL or statistics, so false is also the delegate's answer once materialized.

statistics needs allow_statistics = 1 to reach the gate, since validate() rejects statistics with
INCORRECT_QUERY first when the setting is off; the new test row sets it.

Also trims the comment above overrideURLInEngineArgs from 15 lines to 4, dropping the url_base
illustration and the cross-file policy citation while keeping why the AST copy skips userinfo
(credential exposure through SHOW CREATE TABLE) and why the object storage uses a scratch copy.
Comment-only, no code change in that hunk.
@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit aea6de7f426e56591cd22ea91a872b63640b700b with master failed: RuntimeError: CI logs cluster query failed: SELECT file, countIf(side = 'pr') AS pr_count, countIf(side = 'base') AS base_count FROM ( SELECT 'pr' AS side, file FROM build_time_trace WHERE date >= today() - 7 AND (repo = 'ClickHouse/ClickHouse' OR repo = '') AND pull_request_number = 110529 AND commit_sha = 'aea6de7f426e56591cd22ea91a872b63640b700b' AND check_name = 'arm_release' AND check_start_time = '2026-09-20 19:49:08' AND instance_id = 'i-016b7fedef7bac643' ...(+356 chars elided)...uest_number = 0 AND commit_sha = 'e3b91968f4ea38357c9e033ef52aef9842b72ff9' AND check_name = 'arm_release' AND check_start_time = '2026-09-20 17:36:12' AND instance_id = 'i-0b436bf8b9f20bbf7' AND file IN ('./ci/tmp/build/programs/clickhouse', './ci/tmp/build/programs/clickhouse-keeper') AND name = 'OptFunction' ) GROUP BY file.

See the job log for details.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 99aaca7

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 the TPC-H-over-Iceberg perf test exceeds the harness max_query_seconds, so the whole test errors and reds the shard; the 10 errors count is one test's traceback reported line by line #120923 (external, merged), merged master to pick it up @ 4367182
Performance Comparison (arm_release, master_head, 6/6) / dashboard confirmed_regression the dashboard-verdict gate added by #120927 reds a shard on a confirmed_regression that this job's own report does not call slower #121090 (mine, open)

Mergeable Check and PR are the aggregators of those two shards and carry no independent failure.
Bugfix validation (integration tests, *) is green: the only row it inverts to OK is the new
test_disable_insertion_and_mutation_deferred_url_named_collection, which is the regression test for
this bug, so it does fail on the unfixed build as intended.

Evidence for the 5/6 owner, since a bare count of "10 errors" hides which test failed: the shard's
own report.html Run Errors table attributes all 10 rows to iceberg_suite_tpch, and the same job's
log shows the Iceberg tables attaching at the correct user_files root, so this is not the earlier
PATH_ACCESS_DENIED path defect fixed by #120964. The tested tree of job 105987294739 does not
contain #120923, while PR #121090, whose base does, measured success on the same 5/6 shard at
2026-09-20 01:23Z. The build therefore predates the fix, so I merged master rather than link a fix
that was not in it.

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

Comment thread src/Storages/StorageURL.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4367182

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, and it passed on this
head, so nothing here is ownerless.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 05147_ngrambf_like_escaped_backslash_run CI signal loss, not reachable from this diff: that test asserts on the rendered text of EXPLAIN indexes = 1, so a plan-render change reds it. It was reverted from master by #121135 (merged 2026-09-20T04:10:40Z) and true master has not failed it since 04:25:37Z, 16 rows in 3 days all before the revert. This head diverged from that revert, so the tree under test still carries the pre-remedy oracle. This diff is StorageURL/named-collection startup handling and one integration test #121136 (external, open), the re-land that carries the render-decoupled extract(explain, 'Granules: [0-9]+/[0-9]+') form at both assertion sites
Integration tests (amd_asan_ubsan, db disk, 4/8) / test_storage_nats/test_nats_jetstream_credentials_rotation.py::test_jetstream_credentials_rejected_after_rotation flaky, not reachable from this diff: create_pipeline() cannot reach the NATS broker, Code: 665 Cannot connect to Nats ... poll error: 4. Family breadth in 30 days: rows on more than 25 distinct pull requests plus true master, and this diff contains no NATS file #120202 (external, open), which retries poll on EINTR in the vendored nats-io client
Performance Comparison (arm_release, master_head, 1/6) / order_by_read_in_order #1 (slower), index_bulk_filtering #2 (unstable) perf harness threshold loss, not a change in this diff: Select historical data fetches the learned per-query thresholds with a hardcoded 10 s read timeout while the query itself takes 8 to 10 s, so on a timeout the shard is judged on the bare 0.15/0.25 floors. order_by_read_in_order #1 carries the same slower verdict on 112 distinct pull requests in the last 3 days on arm_release master_head shards, so it tracks the harness rather than any one change, and a named-collection startup fix cannot affect ORDER BY read-in-order or index filtering #121189 (mine, open); #121090 (mine, open) covers the complementary dashboard-verdict gate, and neither duplicates the other
Build profile diff infra, not reachable from this diff: the CI logs cluster read raises RuntimeError: CI logs cluster query failed in ci/jobs/build_profile_diff_job.py, so the job aborts with a traceback instead of degrading to "no baseline". Its only work is reading that cluster; it neither builds nor runs the server. Tracked upstream as issue #120462 #118708 (mine, open), which reports the cluster's own error and skips the comparison when the cluster is unavailable
Mergeable Check, PR aggregator rows, no independent failure: they mirror the four rows above #121136, #120202, #121189 and #118708, the four owners above

Bugfix validation (integration tests, *) is green: the only row it inverts to OK is
test_disable_insertion_and_mutation_deferred_url_named_collection, the regression test for this bug,
so it does fail on the unfixed build as intended.

Gates: (a) 0 of 176 checks queued or running (155 pass, 15 skipped, 6 red); (b) Finish Workflow and
Mergeable Check both completed; (c) 77 min since the last job finished, anchored at
2026-09-20T13:02:54Z; (d) all 6 red rows owned, 0 ownerless, 0 new fix tasks needed.

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

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai is this PR still needed?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, the defect is live, but I would not keep this PR as the carrier.

Remeasured on a debug build of master at 688ee332dbe7 (26.10.1), no patch, using the route that needs no non-default setting: a collection defined in config.d, a URL table on it, the entry edited out, restart. There is nothing to intercept on that route, and the drop-side guard already works (DROP NAMED COLLECTION on it is refused with 769 NAMED_COLLECTION_IS_USED).

  • async_load_databases = 0: Caught exception while loading metadata: Code: 722 ... Load job 'load table default.t_cfg' failed ... Cannot attach table default.t_cfg from metadata file ... (NAMED_COLLECTION_DOESNT_EXIST), then shutting down. The server does not come up.
  • Packaged default async_load_databases = 1: the server starts, but SHOW TABLES, SELECT count() FROM system.tables and SELECT count() FROM system.columns all fail with 722 ASYNC_LOAD_WAIT_FAILED wrapping the 669, and DROP TABLE / DETACH TABLE of that one table fail too. Recreating the collection does not clear it; only another restart does.

What has expired is the CI reason this PR was opened for: the stranded-metadata windows were closed test-side (#115326, #118504, plus the 03822 restart-safety commits), and CIDB has no master failure in the last 30 days for 03822/04003 or with NAMED_COLLECTION_DOESNT_EXIST in the captured log. Only the user-facing half above is left.

That half is better served by #120734: 265 lines, all engines, in the catch that DatabaseOrdinary::loadTableFromMetadata already has. This PR is URL-only and 1006 added lines, 436 of them in src/, because the review rounds grew a StorageDeferredURL proxy with 26 overrides that answer DDL and catalog calls without materializing. Your objection on #120734, that the real fix is to refuse the drop, applies to both PRs, so it is worth settling once, there.

What only this PR adds, for URL(collection) tables: DROP TABLE while the collection is missing, partition DDL and CHECK TABLE reporting NOT_IMPLEMENTED instead of 669, a catalog-wide SYSTEM STOP MERGES not throwing, virtuals and DESCRIBE without materializing, and the engine classification disable_insertion_and_mutation reads. I do not think that is worth 436 lines of src/ on its own.

So: close this one and keep #120734, if you agree. I have not closed it myself because alexey-milovidov merged master into this branch yesterday. The database-level variant is a separate layer, open as #115049.

@PedroTadim PedroTadim closed this Sep 21, 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-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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