Skip to content

Reject a RENAME DATABASE that would make an Alias table cyclic - #117253

Merged
alexey-milovidov merged 26 commits into
masterfrom
fix-rename-database-alias-cycle
Oct 14, 2026
Merged

alexey-milovidov merged 26 commits into
masterfrom
fix-rename-database-alias-cycle

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #116906
Related: #116207

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

Reject a RENAME DATABASE that would make the table dependency graph cyclic, for example one that
leaves an Alias table referring to itself. Such a rename put a cycle into the server-wide table
dependency graph, after which every unrelated CREATE that adds a dependency edge failed with
INFINITE_LOOP and the renamed database stopped being listable after a restart.

Description

CREATE TABLE db1.t ENGINE = Alias('db2', 't') is accepted while db2 does not exist — the
self-reference check in StorageAlias can only judge a target that resolves. RENAME DATABASE db1 TO db2 then relocated the table into its own target namespace without re-validating the stored engine
arguments, leaving db2.t = Alias(db2, t).

The damage is not local to that table: DatabaseCatalog::checkTableCanBeAddedWithNoCyclicDependencies
tests the whole graph, so from that point on any CREATE TABLE ... Alias, CREATE VIEW or
CREATE MATERIALIZED VIEW anywhere on the server failed with
Cannot 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 threw
ASYNC_LOAD_WAIT_FAILED.

RENAME TABLE and EXCHANGE TABLES already refuse the same shape through the dependency graph, so
RENAME DATABASE was the last remaining route. It now goes through the graph as well:
DatabaseCatalog::checkDatabaseCanBeRenamedWithNoCyclicDependencies applies the database-name mapping
to 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 Alias walk, it is engine-agnostic and covers chains of any
length, 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 DATABASE used to hold only the
database-level DDLGuard, which does not touch database_ddl_mutex, so a concurrent
CREATE TABLE db1.t ENGINE = Alias('db2', 't') could have been published between a preflight and the
catalog rewrite and been renamed unchecked. RENAME DATABASE now takes the exclusive database DDL lock
on the source database - the lock CREATE DATABASE and DROP DATABASE hold, and the one table-level
DDL takes on the shared side - and the check runs inside DatabaseAtomic::renameDatabase, under its
mutex, right before updateDatabaseName.

That copy also uncovered a latent bug in TablesDependencyGraph: its copy assignment copied the
nodes set, whose nodes are held by shared_ptr and cross-linked by raw pointer, so a copy shared its
nodes with the source graph and modifying the copy modified the original. A copy now rebuilds its own
nodes.

04946_storage_alias_attach_stored_definition built a stored self-referential definition through
RENAME DATABASE. That route is closed for attached tables, but a detached table is not in the
dependency 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 the
dependencies 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 its no-parallel tag.

New test 05227_rename_database_alias_cycle covers the self-loop, a two-table cycle, a cross-database
cycle 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_concurrent
holds a rename at the new failpoint rename_database_after_dependency_check, between the check and the
catalog rewrite, and shows that a racing CREATE TABLE ... Alias(<new name>, 't') is rejected rather
than slipping into the renamed database.


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

Version info

  • Merged into: 26.10.1.2339-master (included in 26.10 and later)

`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
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [de61b12]

Summary: ✅


AI Review

Summary

This PR closes the obvious RENAME DATABASE → self-referential Alias routes by moving the rename-side check under the source database DDL lock and repeating it under databases_mutex, but the fix is still incomplete. A concurrent CREATE TABLE in another database can still validate against the pre-rename graph, wait until the rename commits, and only then publish its dependency edge, recreating exactly the post-rename cycle this PR is trying to reject.

Findings
  • ❌ Blockers
    • [src/Interpreters/DatabaseCatalog.cpp:842, src/Interpreters/InterpreterCreateQuery.cpp:2679, src/Interpreters/InterpreterCreateQuery.cpp:2407] [dismissed by author -- https://github.com/Reject a RENAME DATABASE that would make an Alias table cyclic #117253#discussion_r4094067836] RENAME DATABASE still does not serialize its "no new cycle" guarantee with dependency publication. checkDatabaseCanBeRenamedWithNoCyclicDependenciesUnlocked only sees edges that are already in the global graphs, but CREATE TABLE checks its edges earlier at checkTableCanBeAddedWithNoCyclicDependencies and adds them later at addTableDependencies, after the table is already published and after the rename-side re-check can finish. An interleaving like db1.t = Alias('keep', 'u') plus CREATE TABLE keep.u ENGINE = Alias('db2', 't') still allows the CREATE to pass before the rename, the rename to commit db1 -> db2, and the late addTableDependencies call to close db2.t -> keep.u -> db2.t. That violates the PR's contract: a RENAME DATABASE can still leave the dependency graph cyclic.
    • Suggested fix: move cycle validation into the mutation that actually publishes dependency edges (DatabaseCatalog::addDependencies / the attach path), or otherwise make dependency validation and edge publication atomic with respect to RENAME TABLE, EXCHANGE TABLES, and RENAME DATABASE.
Tests
  • ⚠️ 05228_rename_database_alias_cycle_concurrent only covers the case where the competing CREATE TABLE has already published its edge before the rename's second check. Add a focused regression hook that pauses CREATE TABLE after checkTableCanBeAddedWithNoCyclicDependencies but before addTableDependencies; that is the remaining window that still recreates the cycle.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Close the remaining CREATE TABLE / dependency-publication race, so the "reject any RENAME DATABASE that would make the graph cyclic" guarantee is actually true.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@zlareb1

zlareb1 commented Aug 31, 2026

Copy link
Copy Markdown
Member

Two gaps in the new preflight, both reachable by SQL after this patch:

  1. A cross-database chain still poisons the graph with the full severity of the original issue. assertRenameLeavesNoAliasCycle only admits into its map the aliases inside the renamed database whose target database is already the new name, so a chain through a third database passes: CREATE TABLE keep.u ENGINE = Alias('db2', 't') (db2 absent, so the edge is vacuous); CREATE DATABASE db1; CREATE TABLE db1.t ENGINE = Alias('keep', 'u'); RENAME DATABASE db1 TO db2. db1.t targets keep, not db2, so the map is empty and the rename proceeds; DatabaseCatalog::updateDatabaseName re-keys the edges with no cycle check and merges into the db2.t placeholder, producing the cycle db2.t → keep.u → db2.t — and every subsequent dependency-adding DDL server-wide fails with INFINITE_LOOP. Validating the rename against the full dependency graph with the name mapping applied (the way checkTableCanBeRenamedWithNoCyclicDependencies works for RENAME/EXCHANGE TABLE) would cover this.

  2. Detached tables evade the preflight, which iterates only attached tables: CREATE TABLE db1.t ENGINE = Alias('db2', 't'); DETACH TABLE db1.t; RENAME DATABASE db1 TO db2; ATTACH TABLE db2.t recreates exactly the stored self-referential state the removed 04946 test tail covered. One nuance on severity: DDLDependencyVisitorData::getDependencies erases self-dependencies, so the re-attach adds no graph edge — the result is a tolerated-but-broken table (TOO_DEEP_RECURSION on read) rather than graph poisoning. But it does mean "there is no SQL route left to that state" (the rationale for deleting the test coverage) does not hold, so keeping a variant of that test seems worthwhile.

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing de61b12e1 with master 371b23a4b (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

8 object files changed (-13.25 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/TablesDependencyGraph.cpp.o 238.38 KiB 216.91 KiB -21.46 KiB (-9.00%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

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.
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
alexey-milovidov and others added 2 commits September 10, 2026 04:46
`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]>
@clickhouse-gh clickhouse-gh Bot added comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). and removed comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. labels Sep 10, 2026
alexey-milovidov and others added 6 commits September 10, 2026 18:33
…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
Comment thread src/Databases/DatabaseAtomic.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 16:00
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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. 03247_create-same-table-concurrently-with-atomic-engine fails with Test runs too long (> 180s) in the targeted ASan + db disk job, and the same thing happens in #92472. The test only runs CREATE OR REPLACE TABLE on a Memory table, and this PR does not touch that code path (it changes only RENAME DATABASE and the copy of TablesDependencyGraph). Locally, 4 parallel runs finish in about 1-3 s.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress in #122662 (test-only; approved by @ tuanpach, CI green, mergeable, waiting for a merge).

The db disk lane has never passed this test: all 12 runs in the last 60 days outside #122662 (this PR and #92472) failed at 238-384 s, while the other lanes finish it in under 40 s. In that lane database_disk is the plain_rewritable S3 disk. The 400 same-name CREATE OR REPLACE statements are serialized on the table, and each metadata commit holds a disk-wide lock across its S3 requests, so under the targeted job's DDL load one statement costs 0.6-1 s. That is why a local run takes a few seconds. #122662 stops each thread after 60 s (as 03238 does); in its CI the same lane passes the test in 43-69 s.

After #122662 is merged, a master merge into this branch clears the red.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Acknowledged. #121639 is already merged, so I'll add this EXPLAIN AST optimize = 1 ... PREWHERE x IN (SELECT ... FROM remote(...)) case as a regression test in a separate test-only PR and link it here.

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

The regression test is in #124634 (05339_explain_ast_optimize_prewhere_in_subquery_over_remote). It segfaults a master build without #121639 and passes on current master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 CH Inc sync was red again because of 05228_rename_database_alias_cycle_concurrent, this time in the meta in keeper jobs. Those jobs do not pass --shared-catalog, so the no-shared-catalog tag has no effect there. The cause is in private code, not in the test. The private build calls its own (cloud) overload of InterpreterRenameQuery::executeToDatabase, the one that takes TableGuards, and that overload did not take getExclusiveDDLGuardForDatabase. So the racing CREATE TABLE waited on the database mutex instead of being rejected. I merged private master into the sync branch and added the same lock to that overload: https://github.com/ClickHouse/clickhouse-private/commit/c00265bf2ca (sync PR ClickHouse/clickhouse-private#71712). The other private failure, test_storage_paimon_with_spark/test_concurrent_reads.py::test_reads_during_commits[azure], is unrelated, as noted before. I also merged the latest master into this branch.

@clickhouse-gh

clickhouse-gh Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 31 queries analysed

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 33 not_sure 1027 1085 +5.6% <0.0001 aggregation: This heavy GROUP BY query does not execute the RENAME DATABASE or dependency-graph code changed here. The +5.6% stays inside master's normal range, and the query's history is noisy.
⚠️ 34 not_sure 1005 1066 +6.1% <0.0001 aggregation: Like Q33, this is an aggregation that never reaches the changed DDL code. The +6.1% stays inside master's normal range, and the query's history is noisy.

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
  • StressHouse run: e4389990-4912-42ef-849e-74731314f54c
  • MIRAI run: 739ee7a0-5cca-464f-8b58-9226e07077a2
  • PR check IDs:
    • clickbench_1023482_1791798013
    • clickbench_1023495_1791798013
    • clickbench_1023501_1791798013
    • tpch_adapted_1_official_1023511_1791798013
    • tpch_adapted_1_official_1023540_1791798013
    • tpch_adapted_1_official_1023554_1791798013

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status as of 2026-10-09: every public check is green. In the CH Inc sync run (ClickHouse/clickhouse-private#71712, commit 70e48bfa), 05228_rename_database_alias_cycle_concurrent now passes in all meta in keeper jobs after the private executeToDatabase overload got the exclusive database lock. The sync check is still red, but because of tests that don't touch RENAME DATABASE or Alias tables:

The branch merged master on 2026-10-08, so no code change is needed in this PR.

kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Oct 10, 2026
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (fe0f91b6) without conflicts, so CI and CH Inc sync will run again on the current base. The only red check was CH Inc sync, and its failures are the unrelated tests listed in the previous comment. The merged tree builds, and 05227_rename_database_alias_cycle, 05228_rename_database_alias_cycle_concurrent and 04946_storage_alias_attach_stored_definition pass locally.

alexey-milovidov and others added 2 commits October 11, 2026 10:24
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed 663dae91. The 04257_system_constraints failure (TOO_DEEP_RECURSION in StorageAlias::getInMemoryMetadataPtr while reading system.constraints without a database filter) came from this PR: removing no-parallel from 04946_storage_alias_attach_stored_definition was wrong, because that test still re-attaches a self-referential Alias and any concurrent query that walks all tables trips over it. I put the tag back with an updated reason. The test_refreshable_mv failures in Integration tests (amd_tsan, targeted) are connection timeouts that also hit master and 8 other PRs on 2026-10-10, so they are unrelated to this PR. 05317_local_read_throttler_filesystem_cache is a known flaky test (1 of 132 reruns failed).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed de61b12e. No conflicts, and the PR diff is unchanged.

The only red check was Fast test (arm_darwin), which reported Server died, and it is unrelated to this PR. Two other tests timed out first: 04403_normalized_query_hash_quota_async_insert and 03148_query_log_used_dictionaries. The lldb backtraces show three threads stuck in macOS libc strftime_l → _st_tzset_basic → _pthread_rwlock_lock_slow:

  • an ExternalLoader thread in calculateNextUpdateTime, which also holds the ExternalLoader mutex
  • a quota-exceeded message in EnabledQuota::Impl::throwQuotaExceed
  • AWS request signing in Aws::Utils::DateTime::ToGmtString

Every other stuck query (CREATE and the cleanup DROP DATABASE) is blocked behind that chain. No thread is in RENAME DATABASE, DatabaseAtomic::renameDatabase or TablesDependencyGraph code. 05227_rename_database_alias_cycle had already passed in that run. This is the only Server died in Fast test (arm_darwin) in CIDB over the last 14 days.

@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 tzset lock hang in macOS libc) and provide a fix in a separate PR. If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I am investigating the macOS libc tzset lock hang behind this Fast test (arm_darwin) Server died; I will follow up here with a PR (or my findings) shortly. No fix is in progress yet: #112267 replaced pthread_rwlock only for code linked into the binary, and the stuck _pthread_rwlock_lock_slow frames are the system implementation called from inside libc, which it does not cover.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in #125369.

All three stuck threads were waiters, with no holder, on libc's private time zone rwlock (lcl_rwlock), which strftime, localtime_r, mktime, tzset and a few others take internally. It is the same psynch lost-wakeup defect (FB24027930) as #112267, but libsystem_c binds that lock to the system implementation, so the pthread_rwlock shim cannot reach it. The PR adds base/darwin-compatibility/libc_timezone_shim.c, which defines the 16 libc functions that take that lock and serializes calls from the binary under one mutex, so no ClickHouse thread waits on it. I have no macOS host, so my evidence is a cross-built arm64 binary that no longer imports these functions from libSystem; Fast test (arm_darwin) on #125369 is the runtime check.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks, @groeneai, for #125369 (the macOS libc time zone lock hang behind the Fast test (arm_darwin) Server died). Nothing needs to change in this PR: every check on de61b12e is green, it merges cleanly with master, and no review threads are open.

leshikus pushed a commit to leshikus/ClickHouse that referenced this pull request Oct 13, 2026
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 alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This could be an overkill (as we could simply tolerate this case), but the changes are small - acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Oct 13, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 13, 2026
Merged via the queue into master with commit f3f8b76 Oct 14, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-rename-database-alias-cycle branch October 14, 2026 00:20
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 22, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). pr-bugfix Pull request with bugfix, not backported by default 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.

RENAME DATABASE can create a self-referential Alias table, denying all unrelated DDL server-wide with INFINITE_LOOP

4 participants