Repository navigation
Reject a RENAME DATABASE that would make an Alias table cyclic - #117253
Conversation
`RENAME DATABASE` moved tables without re-validating their stored engine arguments, so a table
`ENGINE = Alias('<new name>', '<its own name>')` - accepted at `CREATE` because the target
database did not exist yet - ended up aliasing itself. The resulting cycle in the server-wide
table dependency graph then made every later DDL statement that adds a dependency edge fail
with `INFINITE_LOOP`, anywhere on the server, and the database stopped being listable after a
restart. The only way out was to drop the offending table, with nothing pointing at the rename.
`RENAME TABLE` already refuses the same shape through the dependency graph, with the same error
code; `RENAME DATABASE` now checks the aliases of the database being renamed for a cycle among
themselves before doing anything.
`04946_storage_alias_attach_stored_definition` used that hole to build a stored
self-referential definition; that section is dropped, and with it the `no-parallel` tag, since
the remaining `Alias`-to-`Alias` chain does not make the global graph cyclic.
Closes: #116906
|
Workflow [PR], commit [de61b12] Summary: ✅
AI ReviewSummaryThis PR closes the obvious Findings
Tests
Final Verdict
|
|
Two gaps in the new preflight, both reachable by SQL after this patch:
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes8 object files changed (-13.25 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units317 translation units recompiled, 2376 s compile time in total, 317 of them have a recent master baseline. |
The intra-database `Alias` preflight only modelled aliases inside the renamed database that already pointed at the future name, so a cycle running through a third database still slipped through: `keep.u = Alias(db2, t)` plus `db1.t = Alias(keep, u)` closed the cycle `db2.t -> keep.u -> db2.t` when `db1` was renamed to `db2`, because `DatabaseCatalog::updateDatabaseName` merges the renamed table into the existing placeholder node. The check now applies the rename to a copy of the referential and loading dependency graphs and refuses the rename if the result is cyclic - the same way `checkTableCanBeRenamedWithNoCyclicDependencies` works for a single table - so it is engine-agnostic and covers chains of any length. `04946_storage_alias_attach_stored_definition` gets its self-referential section back, built through the route that remains: a detached table is not in the dependency graph, so its stored definition can still be moved into its own target namespace and re-attached. That state is tolerated on the load path (reading is bounded by `TOO_DEEP_RECURSION`) and adds no graph edge, since a self-dependency is erased when the dependencies are collected, so the test still does not need `no-parallel`.
…ver a cross-database cycle The copy assignment copied the `nodes` set, which holds the nodes by `shared_ptr` and cross-links them by raw pointer, so a copy shared its nodes with the source graph: modifying the copy modified the graph it was copied from. That made the rename preflight corrupt the real dependency graph - `CREATE` after a refused `RENAME DATABASE` then failed with `INFINITE_LOOP` on a cycle that did not exist. A copy now rebuilds its own nodes. The cross-database case in `05072_rename_database_alias_cycle` is built out of dictionaries: two `Alias` tables cannot form the chain, because `Alias` refuses to point at another `Alias` at `CREATE`, and the check is engine-agnostic anyway.
`DROP DATABASE db_05072_keep` ran before `DROP DATABASE db_05072_cross`, but `db_05072_cross.d` is a dictionary sourced from `db_05072_keep.u`, so the drop was refused with `HAVE_DEPENDENT_OBJECTS` and the test aborted. Drop the dependent database first. The abort also left the test unfinished in the parallel `Fast test` run, which is what made the unrelated `02024_merge_regexp_assert` report `Database ... does not exist` in the same report. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=13d4ca36d96c7b43e80138093eb2d9d8827e712a&name_0=PR&name_1=Fast%20test #117253 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ble set under the exclusive database DDL lock
The preflight in `InterpreterRenameQuery::executeToDatabase` snapshotted the table names and checked
the dependency graph before `DatabaseAtomic::renameDatabase` re-read `tables`, and `RENAME DATABASE`
only held the database-level `DDLGuard`, which does not touch `database_ddl_mutex`. A concurrent
`CREATE TABLE db1.t ENGINE = Alias('db2', 't')` could therefore be published after the check and be
renamed unchecked, recreating the `db2.t -> db2.t` cycle the check is meant to reject.
`RENAME DATABASE` now takes `getExclusiveDDLGuardForDatabase` on the source database, like
`CREATE DATABASE` and `DROP DATABASE` do, which excludes table-level DDL (it takes the shared side),
and the cycle check moved into `DatabaseAtomic::renameDatabase`, under `mutex`, right before
`updateDatabaseName`, so it sees exactly the set of tables that is re-keyed.
A `PAUSEABLE_ONCE` failpoint `rename_database_after_dependency_check` between the check and the
catalog rewrite lets the new test `05228_rename_database_alias_cycle_concurrent` hold a rename there and
prove that a racing `CREATE TABLE ... Alias(<new name>, 't')` is rejected instead of slipping in.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… database The flaky check runs a new test several times in parallel, and `05072_rename_database_alias_cycle` used fixed database names, so the concurrent runs failed each other with `DATABASE_ALREADY_EXISTS`: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=4df73ba695e80b5e0ef65ad69045de9316553098&name_0=PR&name_1=Stateless%20tests%20(amd_asan_ubsan%2C%20flaky%20check) #117253 The test is now a shell test, `05227_rename_database_alias_cycle`, that prefixes every database with `${CLICKHOUSE_DATABASE}`. The content is unchanged. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…-alias-cycle # Conflicts: # tests/queries/0_stateless/04946_storage_alias_attach_stored_definition.sh
…h the catalog rewrite DDL in other databases is not excluded by the locks of `RENAME DATABASE`, so a `CREATE TABLE` elsewhere could add a dependency edge after the preflight check and before `updateDatabaseName`, and the rename would then close a cycle. `updateDatabaseName` now repeats the check under `databases_mutex` before modifying anything, and `renameDatabase` moves the metadata file back if it refuses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=a9d9a2b9db38d0e8310e4ef0fb9cdf7d3be08691&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29 and provide a fix in a separate PR. If the fix is already in progress, link it here. |
|
The fix is already in progress in #122662 (test-only; approved by @ tuanpach, CI green, mergeable, waiting for a merge). The After #122662 is merged, a |
The style check `failpoint_tests_are_isolated` requires a test that arms a fail point to be tagged both `no-parallel` and `no-fasttest`. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=33d8210600e491f34b6923ed8c24af57ab7c1696&name_0=PR&name_1=Style%20check #117253 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Acknowledged. #121639 is already merged, so I'll add this |
|
🕵 CH Inc sync was red again because of |
|
📊 Cloud Performance Report ✅ AI verdict: No performance change is attributable to this PR. It only changes DDL paths: RENAME DATABASE now checks for dependency cycles and takes an exclusive database DDL lock, and copying a table dependency graph now rebuilds its nodes. Benchmark SELECT queries never run any of that code. The only flagged rows, ClickBench Q33 (+5.6%) and Q34 (+6.1%), are heavy GROUP BY aggregations with noisy history. Both fall inside master's normal run-to-run range, so marking them as not regressions is consistent with the diff. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
🕵 Status as of 2026-10-09: every public check is green. In the CH Inc sync run (ClickHouse/clickhouse-private#71712, commit
The branch merged |
…te in PREWHERE `EXPLAIN AST optimize = 1` analyses the query with the interpreter that preceded the analyzer, and `appendPrewhere` builds the set of an `IN` subquery in `PREWHERE`. Before ClickHouse#121639 that set was planned without a query tree, so reading `remote` through `StorageDistributed::read` dereferenced a null `PlannerContext`. None of ClickHouse#121639's tests goes through `EXPLAIN`, so this adds the minimal case from ClickHouse#117253. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=546cd65f39602b759209f1649d527c047d1bc250&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 Related: ClickHouse#121639 Related: ClickHouse#117253 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
The test still re-attaches a self-referential `Alias` table (detach, rename the database, attach), and while it exists any concurrent query that walks the tables of all databases fails: `04257_system_constraints` failed with `TOO_DEEP_RECURSION` in `StorageAlias::getInMemoryMetadataPtr` while reading `system.constraints` without a `database` filter. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=1c2eaf04b4d6e39fa24ceafd736530ad53796a9a&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20parallel%29 #117253 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged |
|
🕵 Merged The only red check was
Every other stuck query ( @groeneai, please investigate this failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117253&sha=663dae91bdc4c88ed2f5fbadab206d60e1578fe6&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29 (a |
|
Acknowledged. I am investigating the macOS libc |
|
The fix is in #125369. All three stuck threads were waiters, with no holder, on libc's private time zone rwlock ( |
macOS libc guards its time zone state with a private pthread_rwlock (`lcl_rwlock` in Libc stdtime/FreeBSD/localtime.c), taken by strftime(_l), wcsftime(_l), strptime(_l), localtime(_r), ctime(_r), mktime, timelocal, time2posix, posix2time, tzset and tzsetwall. It is the psynch rwlock that loses wakeups when its waiters are interrupted by signals (FB24027930), and the macOS query profiler signals every registered thread. The pthread_rwlock shim from ClickHouse#112267 does not reach it, because libsystem_c binds to libpthread through the two-level namespace. Seen in Fast test (arm_darwin) on ClickHouse#117253: S3 request signing (Aws::Utils::DateTime::ToGmtString), EnabledQuota::Impl::throwQuotaExceed and ExternalLoader::LoadingDispatcher::calculateNextUpdateTime (holding the ExternalLoader mutex) all wait in strftime_l -> _st_tzset_basic with no holder. Define these 16 functions in the force-loaded darwin-compatibility archive. Each resolves the libc function with dlsym(RTLD_NEXT) and calls it under one recursive mutex, so at most one thread of the binary is inside libc's time zone code and none waits on its rwlock. errno is preserved across the mutex, because a contended Darwin mutex retries an interrupted __psynch_mutexwait / __psynch_mutexdrop and can leave EINTR behind on success. Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov
left a comment
There was a problem hiding this comment.
This could be an overkill (as we could simply tolerate this case), but the changes are small - acceptable.
Since ClickHouse#117253, `executeToDatabase` takes `getExclusiveDDLGuardForDatabase` on the old database name itself, before `ViewDefinitionsRenaming::prepare` takes it again for both names. `SharedMutex` is not recursive, so every `RENAME DATABASE` blocked forever on the merged tree, including for an empty database. `prepare` now takes only the new name; the old one is held by the caller for the whole rename. `TimeSeriesVersion.h` moved to `Parsers/Prometheus`; the check function is declared in `Storages/TimeSeries/checkTimeSeriesVersion.h`. Since ClickHouse#126742, a new `TimeSeries` table of version 10 cannot have external target tables, so `05345` pins `version = 7` (the latest version when the test was written; tables of version 9 or earlier keep their external targets and are still rewritten). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #116906
Related: #116207
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Reject a
RENAME DATABASEthat would make the table dependency graph cyclic, for example one thatleaves an
Aliastable referring to itself. Such a rename put a cycle into the server-wide tabledependency graph, after which every unrelated
CREATEthat adds a dependency edge failed withINFINITE_LOOPand the renamed database stopped being listable after a restart.Description
CREATE TABLE db1.t ENGINE = Alias('db2', 't')is accepted whiledb2does not exist — theself-reference check in
StorageAliascan only judge a target that resolves.RENAME DATABASE db1 TO db2then relocated the table into its own target namespace without re-validating the stored enginearguments, leaving
db2.t = Alias(db2, t).The damage is not local to that table:
DatabaseCatalog::checkTableCanBeAddedWithNoCyclicDependenciestests the whole graph, so from that point on any
CREATE TABLE ... Alias,CREATE VIEWorCREATE MATERIALIZED VIEWanywhere on the server failed withCannot add dependencies for 'default.mv', because it will lead to cyclic dependencies: db2.t -> [db2.t],with nothing pointing the operator at the
RENAME. After a restart, listing the database threwASYNC_LOAD_WAIT_FAILED.RENAME TABLEandEXCHANGE TABLESalready refuse the same shape through the dependency graph, soRENAME DATABASEwas the last remaining route. It now goes through the graph as well:DatabaseCatalog::checkDatabaseCanBeRenamedWithNoCyclicDependenciesapplies the database-name mappingto a copy of the referential and loading dependency graphs and refuses the rename if the result is
cyclic. Being a graph check rather than an
Aliaswalk, it is engine-agnostic and covers chains of anylength, including cycles that run through a third database: the renamed table is merged into a node
other databases already reference by the future name, which is what closes such a cycle.
The check has to see exactly the tables that get renamed.
RENAME DATABASEused to hold only thedatabase-level
DDLGuard, which does not touchdatabase_ddl_mutex, so a concurrentCREATE TABLE db1.t ENGINE = Alias('db2', 't')could have been published between a preflight and thecatalog rewrite and been renamed unchecked.
RENAME DATABASEnow takes the exclusive database DDL lockon the source database - the lock
CREATE DATABASEandDROP DATABASEhold, and the one table-levelDDL takes on the shared side - and the check runs inside
DatabaseAtomic::renameDatabase, under itsmutex, right beforeupdateDatabaseName.That copy also uncovered a latent bug in
TablesDependencyGraph: its copy assignment copied thenodesset, whose nodes are held byshared_ptrand cross-linked by raw pointer, so a copy shared itsnodes with the source graph and modifying the copy modified the original. A copy now rebuilds its own
nodes.
04946_storage_alias_attach_stored_definitionbuilt a stored self-referential definition throughRENAME DATABASE. That route is closed for attached tables, but a detached table is not in thedependency graph, so the section is kept and rebuilt on the route that remains:
DETACH,RENAME DATABASE,ATTACH. That state adds no graph edge — a self-dependency is erased when thedependencies are collected — so it is a tolerated-but-broken table (reading it is bounded by
TOO_DEEP_RECURSION) rather than a poisoned graph, and the test no longer needs itsno-paralleltag.New test
05227_rename_database_alias_cyclecovers the self-loop, a two-table cycle, a cross-databasecycle built out of dictionaries, that the databases are left untouched and unrelated DDL keeps working,
and that a rename which creates no cycle still succeeds.
05228_rename_database_alias_cycle_concurrentholds a rename at the new failpoint
rename_database_after_dependency_check, between the check and thecatalog rewrite, and shows that a racing
CREATE TABLE ... Alias(<new name>, 't')is rejected ratherthan slipping into the renamed database.
Workflow [PR]
Sync PR [sync-upstream/pr/117253]
Version info
26.10.1.2339-master(included in26.10and later)