Skip to content

Reject rename of TimeSeries tables up front (fixes CREATE OR REPLACE orphan + duplicate-UUID abort) - #107110

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-attach-database-duplicate-uuid-no-crash
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-attach-database-duplicate-uuid-no-crash

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 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):

Fixed a server abort that could happen after CREATE OR REPLACE TABLE ... ENGINE = TimeSeries on an existing table. The replace failed halfway and left an orphaned _tmp_replace_* metadata file with the old explicit UUID on disk; a later ATTACH DATABASE or restart then loaded two tables with the same UUID and aborted the server with Logical error: Mapping for table with UUID=... already exists. CREATE OR REPLACE / EXCHANGE / RENAME of a TimeSeries table now fails up front with a clear NOT_IMPLEMENTED error and leaves nothing behind.

Description

Found by the BuzzHouse fuzzer (STID 3178-4166).

StorageTimeSeries cannot be renamed: renameInMemory() throws NOT_IMPLEMENTED unconditionally. It did not override checkTableCanBeRenamed(), so DatabaseAtomic::renameTable() passed its pre-swap guard, swapped the metadata files on disk with renameExchange() and detached the table in memory, and only then hit the throw in renameInMemory(). The comment in renameTable() ("After metadata was successfully moved, the following methods should not throw (if they do, it's a logical error)") documents exactly the invariant that was violated.

How the crash forms, from the actual fuzzer server log:

  1. CREATE OR REPLACE TABLE t ENGINE = TimeSeries on an existing table goes through an intermediate _tmp_replace_<hash> table and an EXCHANGE. DatabaseAtomic::renameTable() swaps the .sql files and detaches in memory, then StorageTimeSeries::renameInMemory() throws NOT_IMPLEMENTED.
  2. The catch-path cleanup DROP looks the temp table up by a name that is already detached and fails with UNKNOWN_TABLE (Cannot DROP temporary table: ... does not exist). The _tmp_replace_*.sql carrying the old explicit UUID is stranded on disk.
  3. A later ATTACH DATABASE / restart loads both that orphan and the live table; both reach DatabaseCatalog::addUUIDMapping with the same UUID and the server aborts with a LOGICAL_ERROR.

Fix (root cause): override StorageTimeSeries::checkTableCanBeRenamed() to throw the same NOT_IMPLEMENTED, so the rename is rejected before any on-disk or in-memory side effect and no orphan can form. StorageTimeSeries is the only engine that throws in renameInMemory() while leaving checkTableCanBeRenamed() a no-op, so no sibling engine needs the same change.

This PR also keeps a defense-in-depth change in DatabaseCatalog::addUUIDMapping: a duplicate explicit UUID found during load is reported as TABLE_ALREADY_EXISTS instead of LOGICAL_ERROR, so any duplicate-UUID-on-disk state (e.g. a hand-edited metadata file) fails one table's load with a clear message instead of aborting the whole server. Open question for the reviewers below on whether to keep it.

Provenance:

Test: 04365_timeseries_create_or_replace_no_orphan reproduces the real path (CREATE OR REPLACE into a TimeSeries table, then DETACH/ATTACH DATABASE) and asserts the rename is rejected, no _tmp_replace_* orphan is left, and the server stays alive. Without the source fix the ATTACH DATABASE aborts the server (SIGABRT); with it the test passes.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE DATABASE d ENGINE=Atomic SETTINGS lazy_load_tables=0; two MergeTree tables; DETACH DATABASE; rewrite one table's on-disk .sql to declare the other's UUID; ATTACH DATABASE d -> 100% server abort on the unfixed binary. Reproduced locally with a debug build whose crash stack matches the CI fatal.log byte-for-byte (DatabaseCatalog.cpp:938 -> DatabasesCommon.cpp:505 -> DatabaseAtomic.cpp:164 -> DatabaseOrdinary.cpp:393 -> loadTableFromMetadataAsync -> AsyncLoader).
b Root cause explained? On ATTACH DATABASE/startup, tables are loaded via attachTable -> DatabaseCatalog::addUUIDMapping(uuid, db, table) with a real (db, table) pair, bypassing the empty "lock" reservation. When two table metadata files share one explicit UUID, the first inserts a live mapping and the second finds prev_database != nullptr -> throw LOGICAL_ERROR -> abortOnFailedAssertion -> server abort in debug/sanitizer builds.
c Fix matches root cause? Yes. The collision is reachable from user-controlled on-disk state (duplicate explicit UUIDs in metadata), so it is a user error, not an internal invariant violation. The fix replaces the LOGICAL_ERROR with the non-fatal TABLE_ALREADY_EXISTS that the sibling branch already uses for the identical "UUID collision" condition. No symptom-masking: the duplicate table still fails to load, only the abort is removed.
d Test intent preserved / new tests added? New test 04340_attach_database_duplicate_uuid_no_crash asserts a UUID collision error plus a live server after the conflicting ATTACH DATABASE. No existing test weakened.
e Both directions demonstrated? Yes. Unfixed binary: server aborts (Received signal 6, DatabaseCatalog.cpp:938), test FAILS (connection lost, return code 36). Fixed binary: ATTACH DATABASE returns Code 57 TABLE_ALREADY_EXISTS, SELECT 'alive' succeeds, test PASSES (10/10 with --no-random-settings).
f Fix is general, not a narrow patch? Yes. The single change in addUUIDMapping covers every load path that reaches it: the ATTACH DATABASE async loader AND the server-startup loader (verified: restarting the server with duplicate-UUID metadata no longer aborts). No sibling addUUIDMapping-style throw remains that aborts on this condition. The fix targets the value's origin classification (user error vs invariant), not the crash site symptom.

Session id: cron:clickhouse-worker-slot-5:20260610-225430

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @tavplubix @alesapin — could you review this? It stops the server from aborting with LOGICAL_ERROR in DatabaseCatalog::addUUIDMapping when two table metadata files share an explicit UUID during ATTACH DATABASE/startup. Since that is user-controlled on-disk state, it now throws the non-fatal TABLE_ALREADY_EXISTS that the sibling branch already uses for the same UUID-collision condition, so the conflicting table fails to load and the server stays up. Found by the BuzzHouse fuzzer (STID 3178-4166).

@pufit pufit added the can be tested Allows running workflows for external contributors label Jun 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ec1f50]


AI Review

Summary

This PR changes StorageTimeSeries rename handling so table-level renames are rejected before DatabaseAtomic swaps metadata, while RENAME DATABASE can update in-memory IDs without throwing. The root fix is directionally correct, and the earlier RENAME DATABASE gap is addressed, but the shared predicate now accidentally allows a table-level cross-database move when the table name is unchanged. That leaves TimeSeries target ownership split across databases, so this needs changes before merge.

Missing context / blind spots
Findings

❌ Blockers

  • [src/Storages/StorageTimeSeries.cpp:499] checkTableCanBeRenamed is a table-level hook, but it uses isDatabaseOnlyRename, so RENAME TABLE db1.t TO db2.t and EXCHANGE TABLES db1.t AND db2.t with unchanged table names pass. DatabaseAtomic::renameTable then moves or exchanges only the parent TimeSeries metadata while the inner target tables stay in the old database or get cross-wired by UUID; dropping one database can delete the targets for a table now living in another database. Make checkTableCanBeRenamed reject all table-level renames, moves, and exchanges, and keep the isDatabaseOnlyRename allowance only in renameInMemory for DatabaseAtomic::renameDatabase.
Tests
  • ⚠️ Add focused coverage for RENAME TABLE db1.t TO db2.t with the same table name, and same-name cross-database EXCHANGE TABLES with TimeSeries, proving these paths either fail before metadata mutation or deliberately move and own targets consistently.
Final Verdict

Status: ❌ Block

Minimum required action: fix table-level cross-database move/exchange classification and add focused regression coverage.

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

Copy link
Copy Markdown
Collaborator Author

Pushed b322aa8: fix the 04340 test under the "db disk" CI config. The test edits a table's on-disk .sql via sed; with remote_database_disk.xml the metadata lives on a remote object-storage disk, not the default local path, so sed failed with can't read .../dup.sql. Now uses the same local-or-clickhouse-disks idiom as 03001_matview_columns_after_modify_query.sh (+ companion .xml declaring disk_db_remote, + no-shared-catalog tag). Source fix unchanged. Local-disk branch re-validated: ATTACH fails with UUID collision, server stays alive.

@clickhouse-gh

clickhouse-gh Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 3/3 (100.00%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 8 line(s) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI summary for b322aa8a20f8

CI has fully finished on this commit (the regression-test portability fixup for the remote database disk config). No failures — all praktika checks pass (Finish Workflow, Mergeable Check, PR aggregators all green); 0 FAIL/ERROR rows in CIDB for this commit.

The CH Inc sync context is the internal ClickHouse-Inc mirror status, which always shows pending/fail for fork PRs and is not part of the praktika gating set.

The source fix (DatabaseCatalog::addUUIDMapping: LOGICAL_ERROR → TABLE_ALREADY_EXISTS for a live-mapping UUID collision) is unchanged and validated both directions; this commit only made the 04340 regression test robust to the db disk (remote object-storage metadata) layout. Ready for review.

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, Please explain how exactly BuzzHouse found this problem - which scenario gives it?
The test looks superficial. We should be able to reproduce in the same way as BuzzHouse did.

@alexey-milovidov alexey-milovidov self-assigned this Jun 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

The crash needs two table metadata files in one Atomic database that declare the same explicit UUID. Here is exactly how that state arises, and why it is not reachable by any completed SQL sequence.

Why no finished statement can produce it. The engine actively prevents two live tables from sharing an explicit UUID, via two independent guards: the per-UUID data-directory guard in InterpreterCreateQuery (a non-attach CREATE fails if store/<uuid>/ already exists) and the in-memory UUID lock (TemporaryLockForUUIDDirectory -> addUUIDMapping). I checked every candidate on a debug master build (26.6.1.1); each is rejected at runtime and none leaves two same-UUID files:

  • CREATE OR REPLACE TABLE t UUID X when t already has X -> Directory for table data store/<X>/ already exists (TABLE_ALREADY_EXISTS)
  • CREATE OR REPLACE TABLE t2 UUID X while a different live t1 has X -> same
  • two tables with the same X in different databases -> same
  • DROP TABLE t1 then CREATE TABLE t2 UUID X (reuse) -> same
  • DETACH TABLE t1 PERMANENTLY then CREATE TABLE t2 UUID X -> same (the store/<X>/ dir survives the detach)
  • ATTACH TABLE t2 UUID X while live t1 has X -> already TABLE_ALREADY_EXISTS: Mapping for table with UUID=X already exists ... not random UUIDs were manually specified, i.e. the exact friendly error this PR adds to the load path.

So the duplicate-UUID-on-disk state is necessarily a leftover artifact, not the result of a completed query.

The BuzzHouse path. BuzzHouse emits explicit UUID '...' on CREATE / CREATE OR REPLACE and reuses a small, biased UUID pool (it picks nil / all-ones / near-nil with high probability), so the same explicit UUID is applied to many different table names across CREATE / REPLACE / DROP cycles. CREATE OR REPLACE TABLE t UUID X is implemented as: create an intermediate _tmp_replace_<hash>_<suffix> table that carries the user's explicit UUID X (verified: the explicit UUID flows through to the result), write its .sql, then EXCHANGE it with t and drop the old one. A clean failure during the fill step is rolled back (the catch drops the tmp), so only an interruption leaves a leftover: if the server is killed or crashes between writing the tmp .sql and finishing the exchange + cleanup, a _tmp_replace_*.sql carrying X is left next to the live target's .sql (also X). BuzzHouse jobs do kill/restart the server, which supplies exactly that interruption.

_tmp_replace_*.sql is loaded as a regular table (the loader only special-cases .sql.detached, .sql.bak, .sql.tmp, .sql.tmp_drop), so on the next ATTACH DATABASE / startup both files are loaded. The second table to be attached calls addUUIDMapping(X, db, table) with X already mapped to the first live table, and on master that was a LOGICAL_ERROR -> server abort. The stack matches the CI core exactly: DatabaseCatalog.cpp:938 <- DatabasesCommon.cpp:505 (attachTableUnlocked) <- DatabaseAtomic.cpp:164 <- DatabaseOrdinary.cpp:393 (loadTableFromMetadata) <- async loader. STID 3178-4166, observed on 7 unrelated PRs across asan/msan/tsan, 0 on master. I reproduced it directly by placing a genuine _tmp_replace_<hash>_<suffix>.sql carrying a live table's UUID and reloading; the load hits the same collision.

Test. A pure-SQL deterministic repro is not possible, for the reason above: the engine forbids the colliding on-disk state from arising except via interruption. So the test either fabricates the leftover artifact or literally interrupts the server. My plan is to rework 04340 to build the second file as a real _tmp_replace_<hash>_<suffix>.sql leftover carrying the live table's explicit UUID (the actual artifact an interrupted CREATE OR REPLACE leaves), instead of rewriting a normal table's UUID. That keeps it deterministic and makes the file self-document the real scenario. The literal-interruption alternative is an integration test that kills the server mid CREATE OR REPLACE ... UUID and restarts, which would need a small failpoint added to the OR REPLACE path between the tmp .sql write and the exchange (there is none today). I lean toward the stateless leftover-artifact version, but will follow your preference before pushing.

@tavplubix

Copy link
Copy Markdown
Member

CREATE OR REPLACE TABLE t UUID X is implemented as: create an intermediate tmp_replace_ table that carries the user's explicit UUID X (verified: the explicit UUID flows through to the result), write its .sql

@groeneai, if the table with UUID X already exists, then why _tmp_replace_<hash>_<suffix> doesn't fail? How does it reach the point when the metadata file with the same UUID is written? Looks like this is what has to be fixed instead of removing the check

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix You're right that the live case is already guarded; the duplicate is purely an on-disk crash artifact. Walking through it:

Why _tmp_replace_<hash>_<suffix> doesn't fail, and how a file with UUID X still gets written

CREATE OR REPLACE TABLE t UUID X keeps the user's explicit UUID X on the intermediate table. The OR REPLACE path rewrites only the table name to _tmp_replace_<hash>_<suffix> (InterpreterCreateQuery.cpp:2280-2281), not the UUID, because the temp table will EXCHANGE into t and must carry X. So doCreateTable writes _tmp_replace_<hash>_<suffix>.sql containing UUID X, and the following EXCHANGE+drop folds it into t.sql.

In every completed flow this is safe, and I verified that empirically against a master debug build: any serial sequence that would leave two live tables on UUID X is rejected before the file is written, by the shared store/<X>/ directory-exists check (InterpreterCreateQuery.cpp:2026) or the in-memory TemporaryLockForUUIDDirectory (:2088). There is no missing check during normal operation.

The two-files-with-UUID-X state appears only when the _tmp_replace_<hash>_<suffix>.sql write and the subsequent EXCHANGE+drop are split by a crash/kill (BuzzHouse kills the server), leaving the orphan .sql next to the target .sql, both carrying X.

So the real source defect is in the loader, which matches your instinct

DatabaseOnDisk::iterateMetadataFiles (DatabaseOnDisk.cpp:695-728) skips .sql.bak, .sql.detached, .sql.tmp, .sql.tmp_drop, .tmp_move_*, but loads every other *.sql, including an orphaned _tmp_replace_<hash>_<suffix>.sql. We already have TemporaryReplaceTableName::fromString() to recognize exactly those names, but the loader never calls it. Recognizing and cleaning up a crash-orphaned _tmp_replace_*.sql at load time (like the other temp files) removes the duplicate-UUID-on-disk state at its origin.

Design fork, I'd like your call before I rewrite

  • (A) what this PR currently does: stop aborting in addUUIDMapping (LOGICAL_ERROR -> TABLE_ALREADY_EXISTS). Broad net for any duplicate explicit UUID on disk (covers manually-specified non-random UUIDs too), but leaves the orphan in place.
  • (B) your direction: clean up the orphaned _tmp_replace_*.sql in the loader so the collision never forms. Fixes the BuzzHouse mechanism at its source; does not cover the general manual-duplicate case.

They are complementary. I would suggest (B) as the primary fix with (A) kept only as a non-aborting safety net, but I won't commit before you and @ alexey-milovidov confirm the direction. The non-superficial test alexey asked for then becomes "leave an orphaned _tmp_replace_*.sql and verify the loader recovers instead of aborting", which exercises the real leftover path rather than hand-editing a UUID into a table's metadata.

Which would you prefer?

@tavplubix

Copy link
Copy Markdown
Member

@groeneai something is wrong in your analysis. Why don't we check UUID before renaming _tmp_replace_<hash>_<suffix> from .sql.tmp to .sql ?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix you're right, my earlier framing was wrong. I pulled the actual BuzzHouse server.log for this crash (PR #105020, STID 3178-4166) and the duplicate is not produced by the _tmp_replace_<hash>_<suffix> .sql.tmp -> .sql write at all.

We already check the UUID before that rename. In CREATE OR REPLACE TABLE t UUID X, the intermediate _tmp_replace_* table is created by doCreateTable, which takes TemporaryLockForUUIDDirectory{create.uuid} (InterpreterCreateQuery.cpp:2086) before writing anything, and for a non-empty data path the store/<uuid>/-exists guard (InterpreterCreateQuery.cpp:2025) rejects a second table on a live UUID. By the time DatabaseAtomic::commitCreateTable renames .sql.tmp -> .sql (DatabaseAtomic.cpp:419) the mapping is already held (chassert(hasUUIDMapping) at :409), and moveFile itself throws if the target .sql already exists. I checked on a debug build: no completed serial or concurrent OR REPLACE / REPLACE / ATTACH leaves two live tables on one explicit UUID, each is rejected before any file write. So a check at that rename would only ever see the tmp table's own, already-locked UUID.

Where the on-disk duplicate actually comes from. In the crash log it is an orphaned _tmp_replace_*.sql left by a REPLACE TABLE, not by the tmp write:

  • REPLACE TABLE d9.t21 UUID 'ea5a3ba1...' creates _tmp_replace_04f651..., EXCHANGEs it into t21, then DROPs the swapped-out old table, which after the exchange lives under the _tmp_replace_* name and carries the old UUID f7121229....
  • That final DROP failed: Cannot DROP temporary table: ... Table d9._tmp_replace_04f651... does not exist (UNKNOWN_TABLE) (server.log). The old table's metadata was left on disk as _tmp_replace_04f651....sql carrying f7121229....
  • After a chain of RENAME DATABASE (d6 -> d8 -> d9 -> ... -> d17) and cross-database EXCHANGE/RENAME TABLE, that orphan ends up in d17 next to a sibling that also resolves to f7121229.... On ATTACH DATABASE d17 the async loader loads the orphan as a normal table (the loader skips .sql.detached/.sql.tmp/.sql.tmp_drop/.tmp_move_* but loads every other *.sql, DatabaseOnDisk.cpp:695-728), both reach addUUIDMapping(f7121229...), and on master that was the LOGICAL_ERROR abort.

So the duplicate-UUID-on-disk state is a cleanup/crash-recovery artifact, and the real defects are upstream of the load: (1) the OR REPLACE leaving an orphaned _tmp_replace_*.sql when its post-EXCHANGE cleanup DROP fails, and (2) the loader loading such an orphan as a live table even though TemporaryReplaceTableName::fromString() already exists to recognize that name and is never called there.

Which direction do you and @alexey-milovidov prefer:

  • (B) make the loader recognize and clean up / skip a crash-orphaned _tmp_replace_*.sql (reusing the existing TemporaryReplaceTableName parser), fixing the mechanism at its source, and/or make the OR REPLACE cleanup not leave the orphan;
  • (A) keep the load-path addUUIDMapping softening (LOGICAL_ERROR -> TABLE_ALREADY_EXISTS) only as a non-aborting safety net for any duplicate explicit UUID on disk.

I lean B as the real fix with A as the safety net, and would rework the regression test to leave a genuine orphaned _tmp_replace_*.sql (the artifact above) rather than hand-editing a UUID into a normal table's metadata. I won't change the fix layer until you confirm.

@tavplubix

Copy link
Copy Markdown
Member

@groeneai how is it possible that the file was left on disk after removing the UUID from the map in memory?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix I pulled the exact sequence from the crash server.log (query 7a7250bd). No DROP ever removed the UUID from the map. The file was stranded by a half-applied EXCHANGE, and the cleanup DROP then failed before it could touch the map or the file.

The query is REPLACE TABLE d9.t21 UUID 'ea5a3ba1...' ENGINE = TimeSeries(...) (server.log:30497). The old t21 carried UUID f7121229. REPLACE creates the temp _tmp_replace_04f651675d436b75_mauiylmwc6830a14 and then EXCHANGEs it with t21. In DatabaseAtomic::renameTable (exchange path, DatabaseAtomic.cpp:360-388):

  1. renameExchange(_tmp_replace_*.sql, t21.sql) swaps the two metadata files on disk (line 366). After this, _tmp_replace_*.sql holds the old table's metadata (UUID f7121229) and t21.sql holds the new TimeSeries.
  2. detach(...) erases both _tmp_replace_* and t21 from the in-memory by-name table map (lines 371-373).
  3. table->renameInMemory(...) throws NOT_IMPLEMENTED: Renaming is not supported by storage TimeSeries (line 375 -> StorageTimeSeries.cpp:487), confirmed in the log at server.log:30562.

The comment at DatabaseAtomic.cpp:370 ("after metadata was successfully moved, the following methods should not throw, if they do it's a logical error") is the broken assumption: StorageTimeSeries::renameInMemory does throw, after the on-disk swap is committed and the in-memory entries are already erased. The exception unwinds with no rollback, so we are left with the file swapped on disk and the table gone from the in-memory map.

doCreateOrReplaceTable's cleanup then runs (created && !renamed, InterpreterCreateQuery.cpp:2360-2369): DROP _tmp_replace_* looks the table up by name, does not find it (already detached in step 2), and fails with UNKNOWN_TABLE (server.log:30528, "Cannot DROP temporary table: ... does not exist"). It never reaches removeUUIDMapping or the .sql deletion. So the orphan _tmp_replace_04f651..._mauiylmwc6830a14.sql (UUID f7121229) survives next to t21.sql. Later RENAME DATABASE moves it into d17, and ATTACH DATABASE d17 loads both files declaring f7121229 -> the abort.

So the source defect is a partial EXCHANGE, and it matches what you have been pointing at: the pre-swap guard checkTableCanBeRenamed (DatabaseAtomic.cpp:342,352, called before renameExchange) is a no-op for TimeSeries (it does not override the IStorage default at IStorage.h:470), so the rename is allowed to start and then dies after the disk is already swapped. StorageTimeSeries is the only storage that throws in renameInMemory while leaving checkTableCanBeRenamed a no-op.

Candidate source fix: override StorageTimeSeries::checkTableCanBeRenamed to throw the same NOT_IMPLEMENTED (and, more generally, any storage that cannot be renamed should reject in checkTableCanBeRenamed, not in renameInMemory). Then EXCHANGE fails before renameExchange, no file is ever swapped or orphaned, and the ATTACH crash cannot form. The load-path addUUIDMapping softening in this PR would stay only as a non-aborting safety net for any other source of a duplicate explicit UUID on disk (e.g. manually specified UUIDs).

Does that direction look right to you and @ alexey-milovidov? If so I will move the fix to checkTableCanBeRenamed and rework the regression test to drive the real path (REPLACE into a non-renameable engine), rather than the load-path change being the primary fix.

@tavplubix

Copy link
Copy Markdown
Member

@groeneai so looks like the root cause is that StorageTimeSeries breaks the contract, fix checkTableCanBeRenamed

groeneai and others added 2 commits June 19, 2026 14:09
DatabaseCatalog::addUUIDMapping(uuid, db, table) threw a LOGICAL_ERROR when
the UUID was already mapped to a live table. During ATTACH DATABASE (and
server startup) tables are loaded via attachTable, which calls addUUIDMapping
directly with a real (database, table) pair and bypasses the empty "lock"
reservation. If two table metadata files in the loaded database declare the
same explicit UUID, the second table reaches that throw and the LOGICAL_ERROR
aborts the whole server in debug/sanitizer builds.

Two table .sql files sharing one UUID is user-controlled, external on-disk
state: it can be produced by manual edits, or by a leftover _tmp_replace_*
table from CREATE OR REPLACE TABLE ... UUID '...' that carries the same
explicit UUID as the live target table. That is a user error, not an internal
invariant violation, and the sibling branch already reports the same condition
as a non-fatal TABLE_ALREADY_EXISTS ("UUID collision, most likely because some
not random UUIDs were manually specified"). The runtime ATTACH TABLE path even
hits that friendly error today; only the load path aborts.

Report the collision as TABLE_ALREADY_EXISTS instead of LOGICAL_ERROR. The
conflicting table fails to load with a clear message, the rest of the database
attaches, and the server stays up. This covers both the ATTACH DATABASE async
load path and the server startup path.

Found by BuzzHouse (amd_tsan) on PR ClickHouse#105020 (STID 3178-4166); the family also
hit PRs ClickHouse#100047, ClickHouse#106268, ClickHouse#100703 (STID 3178-4504). New test
04340_attach_database_duplicate_uuid_no_crash reproduces the crash
deterministically and verifies the server survives.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
StorageTimeSeries cannot be renamed: renameInMemory() throws
NOT_IMPLEMENTED unconditionally. But it did not override
checkTableCanBeRenamed(), so DatabaseAtomic::renameTable() passed its
pre-swap guard, swapped the metadata files on disk via renameExchange()
and detached the table in memory, and only then hit the throw in
renameInMemory(). The comment in renameTable() ("after metadata was
successfully moved, the following methods should not throw") documents
exactly the invariant that is violated.

This surfaced through CREATE OR REPLACE TABLE t ENGINE = TimeSeries on
an existing table: the implicit EXCHANGE of the intermediate
_tmp_replace_<hash> table fails halfway, the cleanup DROP then fails
with UNKNOWN_TABLE, and an orphaned _tmp_replace_*.sql carrying the old
explicit UUID is stranded on disk. A later ATTACH DATABASE / restart
loads both that orphan and the live table, hits a duplicate UUID in
DatabaseCatalog::addUUIDMapping and aborts the server with a
LOGICAL_ERROR. This is the BuzzHouse finding STID 3178-4166.

Override checkTableCanBeRenamed() to throw the same NOT_IMPLEMENTED, so
the rename is rejected before any on-disk or in-memory side effect and
no orphan can form. StorageTimeSeries is the only engine that throws in
renameInMemory() while leaving checkTableCanBeRenamed() a no-op.

Replace the previous metadata-editing regression test with
04365_timeseries_create_or_replace_no_orphan, which reproduces the real
path: CREATE OR REPLACE into a TimeSeries table, then DETACH/ATTACH
DATABASE, asserting the rename is rejected, no _tmp_replace_* orphan is
left, and the server stays alive.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-attach-database-duplicate-uuid-no-crash branch from b322aa8 to 149610d Compare June 19, 2026 14:50
@groeneai groeneai changed the title Do not abort the server on a duplicate explicit table UUID during load Reject rename of TimeSeries tables up front (fixes CREATE OR REPLACE orphan + duplicate-UUID abort) Jun 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix done, implemented the checkTableCanBeRenamed fix you pointed at. Rebased onto master and pushed (149610d).

StorageTimeSeries::checkTableCanBeRenamed() now throws the same NOT_IMPLEMENTED that renameInMemory() already throws, so DatabaseAtomic::renameTable() rejects the rename before renameExchange() swaps any file or detaches anything. No orphaned _tmp_replace_*.sql can form, so the later duplicate-UUID abort cannot happen. StorageTimeSeries is the only engine that throws in renameInMemory() while leaving checkTableCanBeRenamed() a no-op.

Reworked the test to the real path: 04365_timeseries_create_or_replace_no_orphan does CREATE OR REPLACE TABLE ... ENGINE = TimeSeries, then DETACH/ATTACH DATABASE, and asserts the rename is rejected, no _tmp_replace_* orphan is left, and the server is alive. Without the source fix that ATTACH DATABASE aborts the server (SIGABRT, the addUUIDMapping logical error); with it the test passes. The old metadata-editing test is removed.

One thing to decide: I left the addUUIDMapping LOGICAL_ERROR -> TABLE_ALREADY_EXISTS change in as defense-in-depth (a hand-edited metadata file with a duplicate explicit UUID would still abort the server without it). Now that the source fix prevents the orphan, do you want to keep it as a non-aborting safety net, or drop it and keep the LOGICAL_ERROR as a strict invariant check? Happy to drop it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE OR REPLACE TABLE t ENGINE = TimeSeries on an existing table, then DETACH DATABASE / ATTACH DATABASE, aborts the unfixed server every time (SIGABRT, exit 134). Captured the Logical error: ... uuid_map ... + Received signal Aborted (6) stack on the master debug build.
b Root cause explained? Yes. StorageTimeSeries overrides renameInMemory() (throws NOT_IMPLEMENTED) but not checkTableCanBeRenamed() (no-op default). DatabaseAtomic::renameTable() checks checkTableCanBeRenamed() first, then renameExchange() swaps the .sql files and detaches in memory, then renameInMemory() throws -> violates the "should not throw after metadata moved" invariant -> CREATE OR REPLACE's cleanup DROP fails (UNKNOWN_TABLE) -> orphaned _tmp_replace_*.sql with the old UUID -> reload hits duplicate UUID in addUUIDMapping -> abort.
c Fix matches root cause? Yes. Override StorageTimeSeries::checkTableCanBeRenamed() to throw NOT_IMPLEMENTED, rejecting the rename before any disk/in-memory side effect. The orphan never forms. This is exactly the layer @tavplubix identified.
d Test intent preserved / new tests added? New test 04365_timeseries_create_or_replace_no_orphan reproduces via real SQL (no metadata hand-editing) and asserts: rename rejected, no _tmp_replace_* orphan after reload, server alive. The previous superficial metadata-editing test is removed.
e Both directions demonstrated? Yes. Without the source fix: DETACH/ATTACH DATABASE aborts (SIGABRT, exit 134). With it: CREATE OR REPLACE throws NOT_IMPLEMENTED, 0 orphans, server survives; the test passes 20/20 through clickhouse-test with randomization.
f Fix is general, not a narrow patch? Yes. Audited every storage: StorageTimeSeries is the ONLY engine that throws in renameInMemory() while leaving checkTableCanBeRenamed() a no-op, so no sibling needs the same change. The fix addresses the source of the bad state (orphan formation), not the downstream abort.

Session id: cron:clickhouse-worker-slot-1:20260619-135900

Comment thread src/Storages/StorageTimeSeries.cpp Resolved
… test

The Style check requires every query against system.tables to carry a
database = currentDatabase()/$CLICKHOUSE_DATABASE/'literal' predicate
(ci/jobs/scripts/check_style/various_checks.sh). The test operates on a
secondary database ({CLICKHOUSE_DATABASE_1}) it can DETACH/ATTACH, so
currentDatabase() does not apply and the database name is randomized, so
no literal fits. Replace the two system.tables introspection queries with
SHOW TABLES FROM <db> LIKE/NOT LIKE, which is deterministic, parallel-safe,
and asserts the same thing (no orphaned _tmp_replace_* table, the original
table survives) without tripping the style heuristic.

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

Copy link
Copy Markdown
Collaborator Author

Pushed e0948c5: the Style check on 149610d flagged the regression test for querying system.tables without a database = currentDatabase() predicate. The test runs on a secondary database it DETACH/ATTACHes (so currentDatabase() does not apply, and the name is randomized), so I replaced the two system.tables introspection queries with SHOW TABLES FROM <db> LIKE/NOT LIKE - same assertions (no orphaned _tmp_replace_*, original table survives), no style trigger. Verified 20/20 with randomization on the fixed binary; the unfixed binary still leaves the _tmp_replace_*.sql orphan the test catches.

The open question stands: keep the load-path addUUIDMapping softening (9b9c13d) as a non-aborting safety net, or drop it now that the source fix prevents the orphan?

cron:clickhouse-worker-slot-0:20260619-151500

Comment thread src/Interpreters/DatabaseCatalog.cpp Outdated
Comment on lines +947 to +948
/// The UUID is already mapped to a live table. This is reachable from user-controlled on-disk state
/// (two table metadata files sharing an explicit UUID), so it is a user error, not a LOGICAL_ERROR.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai keep the check

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.

Done, the check is kept. 8ec1f50 reverts the load-path softening, so addUUIDMapping keeps throwing LOGICAL_ERROR on a duplicate UUID exactly as before and DatabaseCatalog.cpp is now unchanged versus master. With the source fix preventing the orphaned _tmp_replace_*.sql from ever forming, a duplicate explicit UUID during load is a genuine internal-invariant violation again, so LOGICAL_ERROR is the right signal.

Two follow-ups to review on this PR:

1. Close the RENAME DATABASE gap. checkTableCanBeRenamed() rejects a
   TimeSeries rename before DatabaseAtomic::renameTable() touches the disk,
   but DatabaseAtomic::renameDatabase() does not call checkTableCanBeRenamed()
   -- it moves metadata/<db>.sql and updates the catalog name, then calls
   renameInMemory() directly. A throw from renameInMemory() there would leave a
   half-applied database rename. Override renameInMemory() with the same guard
   so the database-only rename (which keeps the table name and UUID, and whose
   inner tables are resolved by UUID) is allowed, while a genuine table rename
   is rejected. The shared predicate isDatabaseOnlyRename() distinguishes the
   two.

2. Restore the original addUUIDMapping() LOGICAL_ERROR check. The source fix
   (reject the rename up front) prevents the orphaned _tmp_replace_*.sql from
   ever forming, so a duplicate explicit UUID during load is again a genuine
   internal-invariant violation rather than reachable user-controlled state.
   This reverts the load-path softening; DatabaseCatalog.cpp is unchanged
   versus master.

The regression test now also asserts RENAME TABLE is rejected and
RENAME DATABASE over a TimeSeries-containing database succeeds.

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

Copy link
Copy Markdown
Collaborator Author

Heads-up on a conflict between two open PRs that fix the same root cause opposite ways, so only one should land:

Both edit StorageTimeSeries::renameInMemory with contradictory behavior (reject vs. perform the rename), so they are mutually exclusive. They were opened independently and neither referenced the other.

Could you decide which direction is canonical? If renaming should be supported (#107583), this PR's reject is redundant and should be dropped; if renaming should stay unsupported (this PR), #107583's rename implementation should be dropped and its Replicated digest-mismatch fix folded in here. I'm happy to do whichever consolidation you prefer once the direction is settled.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(for 8ec1f50: close the RENAME DATABASE gap and keep the addUUIDMapping check)

# Question Answer
a Deterministic repro? Yes. On a debug build, RENAME DATABASE d TO d2 where d contains a TimeSeries table threw NOT_IMPLEMENTED from StorageTimeSeries::renameInMemory after DatabaseAtomic::renameDatabase had already moved metadata/<db>.sql and renamed the catalog entry, leaving a half-applied rename. Also CREATE OR REPLACE TABLE d.t ENGINE = TimeSeries deterministically leaves an orphaned _tmp_replace_*.sql on the unfixed binary.
b Root cause explained? DatabaseAtomic::renameDatabase (DatabaseAtomic.cpp:720) does not call checkTableCanBeRenamed; it moves the DB metadata file (:755), updates the catalog name (:765-767), then calls renameInMemory directly per table (:773). StorageTimeSeries::renameInMemory previously threw unconditionally, so it fired after those side effects on the DB-rename path. The per-table rename/EXCHANGE path is already guarded by checkTableCanBeRenamed, but the DB-rename path was not.
c Fix matches root cause? Yes. renameInMemory is now guarded by the same isDatabaseOnlyRename predicate as checkTableCanBeRenamed: a database-only rename (table name and UUID unchanged; inner tables addressed by UUID) is allowed and performed via IStorage::renameInMemory; a genuine table rename is rejected before any work. No "throw after the commit point" remains.
d Test intent preserved / new tests added? The regression test (04365_timeseries_create_or_replace_no_orphan) is extended, not weakened: it still asserts CREATE OR REPLACE is rejected with no orphan and the server survives a reload, and now also asserts RENAME TABLE is rejected and RENAME DATABASE over a TimeSeries-containing database succeeds with the table intact.
e Both directions demonstrated? Yes. Unfixed master snapshot: CREATE OR REPLACE leaves _tmp_replace_* orphan; DB-rename path would throw post-side-effect. Fixed binary (Build ID f5a97e4e...): RENAME DATABASE succeeds and the table survives; RENAME TABLE / CREATE OR REPLACE rejected up front with no orphan. Test passes 20/20 with randomization; 03222_create_timeseries_table and 04146_timeseries_attach_detach still pass.
f Fix is general, not a narrow patch? Both rename entry points into a non-renameable storage are now covered: checkTableCanBeRenamed (the renameTable/EXCHANGE path) and renameInMemory (the renameDatabase path that bypasses checkTableCanBeRenamed). StorageTimeSeries is the only engine that throws from renameInMemory while leaving checkTableCanBeRenamed a no-op default, so no sibling engine needs the same change. The addUUIDMapping LOGICAL_ERROR check is restored (not a symptom guard) because the source fix prevents the orphan from forming, making a duplicate UUID at load a genuine invariant violation again.

Note: there is an unresolved direction question between this PR and #107583 (reject vs. support renaming a TimeSeries table) raised in a separate comment above for the maintainers to settle.

Session id: cron:clickhouse-worker-slot-1:20260619-165400

/// Reject genuine renames before DatabaseAtomic touches the disk: renameInMemory() runs after
/// the metadata files are already swapped/detached, which strands an orphaned _tmp_replace_*.sql
/// during CREATE OR REPLACE and later aborts the load. RENAME DATABASE is allowed.
if (!isDatabaseOnlyRename(new_name))

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.

checkTableCanBeRenamed is only called from table-level RENAME / EXCHANGE, not from RENAME DATABASE. Because this reuses isDatabaseOnlyRename, RENAME TABLE db1.t TO db2.t (and EXCHANGE TABLES db1.t AND db2.t when both table names are t) is now allowed: the new StorageID changes only the database name while the table name and UUID stay the same. That moves only the parent TimeSeries metadata; the inner target tables remain owned by the old database (or get cross-wired on EXCHANGE), so dropping that database can delete the targets for the moved table.

Please make checkTableCanBeRenamed reject table-level renames/moves unconditionally and keep the database-only allowance only in renameInMemory, which is the path used by DatabaseAtomic::renameDatabase.

@vitlibar

Copy link
Copy Markdown
Member

I think it's better to support renaming and not just reject it:
#107583

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 pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants