Skip to content

Do not leave metadata referencing a dropped named collection - #115326

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:close-named-collection-stress-restart-window
Aug 19, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:close-named-collection-stress-restart-window

Conversation

@groeneai

@groeneai groeneai commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #77366
Related: #112805

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Three stateless tests briefly leave table metadata on disk referencing a named collection that no longer
exists. The stress test kills and restarts the server at arbitrary points and randomizes
async_load_databases=false; in that mode loadMetadata waits every table load job and rethrows, so the
server cannot boot:

Caught exception while loading metadata: Code: 722 ... Code: 695 ... Code: 669 ...
There is no named collection `nc_missing_sk_test_3`: Cannot attach table ... ENGINE = Remote(...)

Measured: 16 occurrences across 13 PRs and 2 master runs in 30 days.

Changes, copying the pattern already in 04626_s3_base_setting.sh:

  • 04512_remote_missing_named_collection.sh detaches PERMANENTLY. Startup skips a permanently
    detached table without constructing its storage, while ATTACH TABLE still replays the on-disk
    definition, so every assertion is unchanged and the .reference file is untouched.
  • 04320_url_engine_dispatch_partition_and_format.sh and 04327_s3queue_server_credentials.sh create
    the collection before dropping a possible leftover table, and chain the two teardown drops so the
    collection outlives the table.

Validation. A restart injected where the stress kill lands reproduces the abort deterministically on
master and boots cleanly with the change; restarting at every statement boundary of the changed regions
shows two boundaries dying before and none after. Each change was reverted one at a time and each
reverted half reddens on its own oracle, and pointing an arm at a live collection makes it fail, so the
arms are not vacuous. 200/200 randomized runs of these tests plus 04626 pass.

Server startup behaviour is unchanged, so the underlying gap remains: dropping a collection while a
dependent table is detached still leaves an unstartable server when async_load_databases = 0. That was
reported in #77366 and closed in favour of a drop-side guard (#96181), which #112805 is extending to
detached tables.

Tests only: no setting, default or serialization change, so no SettingsChangesHistory.cpp entry.


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

Version info

  • Merged into: 26.8.1.1687 (included in 26.8 and later)

groeneai and others added 2 commits August 18, 2026 12:37
… stress restart

Three stateless tests briefly leave table metadata on disk that references a
named collection which no longer exists. SQL normally forbids that state:
check_named_collection_dependencies defaults to true and the DROP is refused
with NAMED_COLLECTION_IS_USED, so each of these tests reaches it only by
opting out of the guard or by leaving its setup and teardown drops unordered.

Under the stress test the server is killed and restarted at arbitrary points,
and the runner randomizes async_load_databases=false. In that mode
loadMetadata waits every table load job and AsyncLoader::wait rethrows, which
Server.cpp rethrows in turn, so a restart landing inside the window means the
server cannot boot:

  Caught exception while loading metadata: Code: 722 ... Code: 695 ...
  Code: 669 ... There is no named collection `nc_missing_sk_test_3`:
  Cannot attach table ... ENGINE = Remote(nc_missing_sk_test_3, ...)

The check then goes red on a PR whose diff cannot touch named collections.
Measured over 30 days: 16 occurrences across 14 pull requests and 2 master
runs, all of them Stress test jobs.

04512 now detaches PERMANENTLY. detachTablePermanently writes a marker file
that loadTablesMetadata skips before constructing any storage, while the .sql
definition survives and a short ATTACH still replays it, and the marker is
removed only after a successful attach. So every statement and every assertion
of the two affected arms is unchanged and the reference file is untouched, yet
a restart at any point inside an arm boots cleanly.

04320 and 04327 adopt both halves of the pattern already used by
04626_s3_base_setting.sh: create the collection before dropping a possible
leftover table, so a leftover collection is reused rather than dropped while a
leftover table still references it, and chain the two teardown drops so the
collection outlives the table.

Server startup behaviour is not changed here, so the underlying gap remains.
It was reported in ClickHouse#77366 and closed in favour of a drop-side dependency
guard, ClickHouse#96181, which ClickHouse#112805 is extending to detached tables.

Related: ClickHouse#77366
Related: ClickHouse#112805
Each states the same invariant in one sentence instead of three lines.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change cold, and I adjudicated its findings against the code and
against CI history. Four findings, two applied, two disagreed with evidence.

# Finding Verdict
⚠️ 1 The Related: links sat inside the leading HTML comment, so they would not render. AGREE - moved below the closing -->.
💡 2 The occurrence count in the description was overstated. AGREE - it said 14 PRs; uniqExact(pull_request_number) counts the master bucket (0) as a distinct value, so the correct figure is 16 occurrences / 13 PRs / 2 master runs. Corrected.
❌ 3 Blocker: sibling tests (03822, 04003, 04318, 04070, 04511) still leave the same unsafe state, so the startup abort remains possible. DISAGREE - see below.
❌ 4 Major: the restart-safety claim needs deterministic boundary-injection evidence, since the reference files carry no restart oracle. DISAGREE - that evidence exists and the repro is not probabilistic; see below.

On 3. Every one of the 16 occurrences in the last 30 days names the collection that caused it, and
all 16 attribute to the three files changed here plus 04626: 04320_..._nc x11, s3queue_creds_nc x2,
nc_missing_tf / nc_missing_sk x2, nc_04626_s3_base_setting x1. None names a collection belonging to
03822, 04003, 04318, 04070 or 04511.

04626 is the counter-proof rather than a gap: its single occurrence is 2026-08-05 01:45, and the
chained teardown landed in f4ae15d at 2026-08-05 16:14, fourteen hours later. It has not recurred in
the thirteen days since, and this change copies that pattern.

03822 and 04003 must not be reordered. Their arms assert the guard itself
(-- { serverError NAMED_COLLECTION_IS_USED }) and deliberately reach the abandoned state via
SET check_named_collection_dependencies = false. InterpreterDropNamedCollectionQuery.cpp:41 consults
that setting only when a dependent still exists, so dropping the object first makes both setting values
behave identically and the bypass arm asserts nothing. The abandoned state is the assertion.

04511, 04070 and 04318 do not hold the state across a client round trip: in each, the tables are
dropped before the collections inside a single client invocation (04511:40-48, 04070:129-130,
04318:77-78). 04318's order is already the safe one.

The remaining scope is disclosed rather than claimed complete - a broader setup-ordering class exists and
is named in my notes, and the description states that the product-side gap is unchanged.

On 4. The repro is deterministic, not a stress coin flip: the restart is injected exactly where the
kill lands, with async_load_databases=false pinned in the config. Both directions were produced twice,
in two independent sessions: without the change the server dies with the full 722 -> 695 -> 669
chain; with it the server boots, the .sql.detached marker is on disk and the log shows
Skipping permanently detached table.

The boundary-injection run requested already exists. Arm (a) is replayed from an empty data directory to
each of six stop points and then restarted once; the two stop points where the collection is gone die
with Code: 669 before the change and boot after it, while the other four boot in both arms. Each of the
three changes was additionally reverted on its own, with a separate oracle per half, and a live-collection
control makes the arm fail - so the arms assert the specific 669 plus the collection name, not merely
that an error occurred.

On the specific worry that PERMANENTLY could silently lose its effect: the marker is observed still
present after the failing short ATTACH and removed only after the successful one. That follows from
the code as well - DatabaseOnDisk::createTable removes the marker, but doCreateTable constructs the
storage first (InterpreterCreateQuery.cpp:2433) and only then calls createTable (:2481), so a 669
thrown during construction never reaches a removal site.

The finding is right that a stateless test cannot restart a server, so no reference file can carry a
restart oracle. That is inherent to this class of fix, which is why the artifacts above exist and the
description summarizes them.

Binary identity was asserted for every measurement, and the three tests plus 04626 pass 200/200
randomized runs.

Session id: cron:clickhouse-review-slot-48:20260818-160900

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fa341ec]

Summary: ✅


AI Review

Summary

This PR hardens three stateless tests so they no longer drop a named collection before the referring table is safely gone, which is the right direction for the files it touches. I did not find a bug in the modified lines themselves, but the CI-fix contract is still incomplete: an unmodified sibling Remote(named_collection) test keeps the old unchained cleanup, so the post-stress restart can still end up loading table metadata that points at a missing named collection.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04318_remote_storage_engine_access.sh:77-78] [dismissed by author -- https://github.com/Do not leave metadata referencing a dropped named collection #115326#issuecomment-5331550564] This PR correctly switches the touched tests to guarded cleanup, but 04318_remote_storage_engine_access.sh still runs DROP TABLE and DROP NAMED COLLECTION as separate commands. InterpreterDropQuery removes named-collection dependencies before it calls database->dropTable (src/Interpreters/InterpreterDropQuery.cpp:364-366), while DatabaseAtomic does not move the metadata file out of the active path until later (src/Databases/DatabaseAtomic.cpp:230-233). If the stress harness kills that DROP TABLE in the gap, the following DROP NAMED COLLECTION can still succeed and the post-stress restart can hit the same boot failure this PR is trying to eliminate.
    Suggested fix: apply the same guarded cleanup pattern to 04318_remote_storage_engine_access.sh, and re-check the remaining named-collection shell tests for the same DROP TABLE then DROP NAMED COLLECTION sequence.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro Yes. A restart injected where the stress kill lands: server exits with Caught exception while loading metadata + Code: 722 -> 695 -> 669. Not a percentage.
b Root cause explained The tests briefly leave metadata referencing a dropped collection; the stress runner randomizes async_load_databases=false, and in that mode loadMetadata waits every table load job and rethrows, so Server.cpp aborts startup. Only the synchronous mode does this, which is why the signature is stress-only.
c Fix matches root cause Yes for the CI defect: the tests open the window, and the change removes it. No widened bound, no no-random-* tag, no dataset reduction, no relaxed assertion. Server startup behaviour is deliberately not changed.
d Test intent preserved Yes. .reference files are untouched; each of the four assertions of 04512 arms (a)/(b) was mapped to its producing statement and observed (live read 3, failing short ATTACH Code: 669 naming the collection, definition round-trip 3, and the same three for the sharding_key arm). Arms (c)-(h) and 04320's DETACH/rm/ATTACH regression sequence are not in the diff.
e Both directions demonstrated Yes. Unmodified tree: server DIED with the full 722/695/669 chain. With the change: BOOTED, and the log shows Skipping permanently detached table. Also measured per statement boundary: 2 of 6 boundaries die before, 0 of 6 after.
f General across code paths Scoped and disclosed. The three carriers with observed startup failures are fixed; 04626_s3_base_setting.sh is the in-tree pattern and is unchanged. 03822/04003 are deliberately excluded because reordering there would make their guard-bypass arms vacuous. A wider setup-ordering class (02918, 04070, 04318, 04648, 04820) is named, not claimed fixed. tests/integration/ is out of scope: each integration test owns its server and volumes, so a mid-test kill cannot carry metadata into another test's restart.
g Generalizes across inputs The change is DDL ordering plus a DETACH modifier, so there is no type or boundary surface. Both 04512 override shapes are covered (table-function database = merge(...) and non-table-function sharding_key = rand()), across three engines: Remote, URL, S3Queue.
h Backward compatible Tests only. No setting, no default, no serialization change, therefore no SettingsChangesHistory.cpp entry.
i Invariants preserved PERMANENTLY changes only where the table lives. The detached marker survives a failing ATTACH and is removed only after a successful one, so the assertion still runs with the window closed. # Tags: no-replicated-database is preserved; no no-parallel added, since the names are already scoped to the unique test database.

Mutation check: each change reverted one at a time. Reverting PERMANENTLY reddens the two
missing-collection boundaries. For the other two tests the setup and teardown halves were reverted
separately, because they guard different failures: unchaining the teardown drops makes the restart die
with Code: 669, and reverting the setup ordering makes the next run fail with Code: 769 then
Code: 670 against a leftover from an interrupted run, while a clean run still passes.

Negative control: pointing an arm at a collection that still exists makes it fail, so the arms are not
vacuous, and they assert NAMED_COLLECTION_DOESNT_EXIST specifically rather than merely that an error
occurred.

Randomized runs: 200/200 passed over the three changed tests plus 04626_s3_base_setting.sh.

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pamarcos, could you review this? It is a test-only change: three stateless tests briefly left table metadata on disk referencing a named collection they had already dropped, which aborts startup under the stress test when async_load_databases is randomized to false, so 04512 now detaches PERMANENTLY (startup skips such a table without constructing its storage) and the other two create the collection before dropping a leftover table and chain their teardown drops.

@PedroTadim PedroTadim self-assigned this Aug 18, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fa341ec41 with master 3436fefff (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
Binary Master PR Δ
programs/clickhouse-stripped 701.97 MiB 698.94 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 19, 2026
Merged via the queue into ClickHouse:master with commit 7a6c38d Aug 19, 2026
364 of 366 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 19, 2026
pull Bot pushed a commit to TCeason/ClickHouse that referenced this pull request Aug 23, 2026
…the CI randomizers

The test deliberately holds a URL table whose named collection has been
dropped, since that is the property it asserts with
check_named_collection_dependencies = false. Under the stress profile the CI
randomizers turn that deliberate window into persisted metadata that the next
server start cannot load, so the job dies at boot with
NAMED_COLLECTION_DOESNT_EXIST wrapped in 695/722. It shows up as
"Cannot start clickhouse-server", never as a failure of the test itself.

Three randomizers reach that state. QueryFuzzer::fuzzCreateQuery renames a
cloned CREATE TABLE without inspecting the engine arguments, so a bare
identifier first argument (the named-collection form) is copied verbatim into
a __fuzz_N sibling; the test cleans up only its own table name, and the
server-side fuzzer has no clone cleanup at all
(getDropQueriesForFuzzedTables is only reachable from the client fuzzer).
ignore_drop_queries_probability = 0.2 can rewrite a cleanup DROP into a
TRUNCATE that URL does not support. The random query killer can SIGTERM the
client between two statements of the same block, so no cleanup ordering
inside a block is safe.

The first incarnation, the only one inside the guard-disabled window, moves
into a Memory database, whose table metadata is never written, so no restart
can replay it. It is removed with DROP DATABASE, which the drop injector
excludes, so it needs no pin. The second incarnation stays in the Atomic
database and keeps the RENAME and EXCHANGE arms unchanged, since
DatabaseMemory does not implement renameTable. ast_fuzzer_runs = 0 is pinned
on the four blocks that create a URL table, ignore_drop_queries_probability =
0 on the drops the test depends on, and the setup cleanup now removes
leftover tables and databases before the collection.

The ten serverError NAMED_COLLECTION_IS_USED assertions are unchanged, and
each was confirmed to still fire individually. Each pinned item was shown
load-bearing on its own: omitting any one of them reproduces the boot
failure.

Related: ClickHouse#115326
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants