Skip to content

Add the Cluster database engine - #114417

Merged
alexey-milovidov merged 52 commits into
masterfrom
database-cluster
Sep 28, 2026
Merged

alexey-milovidov merged 52 commits into
masterfrom
database-cluster

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Closes: #114411
Related: #59304
Related: #110975

Implement the Cluster database engine, a follow-up to the Remote database engine (#110975). It provides real-time access to tables in a configured cluster database. Each table is exposed as a Distributed proxy that forwards SELECT and INSERT, with the same local-shard visibility rules and remote-replica fallback as Remote.

The cluster is resolved from server configuration by name on every access, supports macros, and follows configuration reloads. Connections use each replica's configured credentials, secure connections, compression, and inter-server secret; the engine stores no credentials.

SHOW CREATE TABLE reports THERE_IS_NO_QUERY for a table of a Cluster database: the proxy follows configuration reloads (a reload can add shards and give the proxy an implicit rand() sharding key that is used only for INSERT, while a standalone Distributed table would also use it for read shard pruning), it expands macros on every access, and it falls back to a remote replica on the metadata lookup, so no standalone Distributed definition is equivalent to it. Best-effort paths, such as the create_table_query column of system.tables, return nothing instead of failing.

Changelog category (leave one):

  • New Feature

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

Added the Cluster database engine, which provides real-time access to the tables of a configured cluster database and forwards SELECT and INSERT queries to it.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

Version info

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

A follow-up to the `Remote` database engine: provides real-time access
to the tables of a database on a cluster from the server configuration,
the same way the `cluster` table function relates to the `remote` table
function.

    CREATE DATABASE db ENGINE = Cluster('cluster_name', 'database');

The engine shares the metadata and query machinery with
`DatabaseRemote`. The named cluster is re-resolved from the server
configuration on every access, so the database follows configuration
reloads and cluster auto-discovery; connections use the per-replica
settings of the cluster configuration (credentials, secure connections,
compression, the inter-server secret) instead of credentials of its
own, and `SHOW CREATE TABLE` prints a re-executable
`Distributed(cluster_name, database, table)` definition.

The remote-only metadata-lookup fallback (the cluster with the local
replicas stripped from their shards) is derived by the new
`Cluster::tryGetClusterWithoutLocalReplicas`, which preserves the
per-replica settings; the `Remote` database engine now uses it too.

Closes: #114411

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Sep 26, 2026, 8:10 PM

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [65276f9]

Summary: ✅


AI Review

Summary

This PR adds the new Cluster database engine and folds a substantial amount of fallback / cycle-handling logic into the shared Remote machinery. The overall design is solid, but the new fallback-cluster constructor drops shard-scope provenance even when the shard numbering is unchanged, so one important nested-query path still changes behavior under fallback.

Findings

⚠️ Majors

  • [src/Interpreters/Cluster.cpp:1048] RemoteReplicasTag strips local replicas without renumbering shards, but it does not preserve shard_scope_identity. As soon as a Cluster database proxy falls back to remote_only_cluster, nested Distributed / parallel-replicas reads on the answering replica will treat the shipped _shard_num scope as foreign and stop using the original shard scope, which changes query behavior on the fallback path. Copy from.shard_scope_identity before initMisc().
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 65276f9.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 349/398 (87.69%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 12, 2026
Comment thread src/Databases/DatabaseCluster.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 65276f941 with master 199f114be (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

69 object files changed (+181.74 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseCluster.cpp.o new 155.66 KiB +155.66 KiB

716 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

1293 translation units recompiled, 8689 s compile time in total, 1292 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +469.7 s (+6%) in total before that adjustment.

Job report

`master` moved the documentation from `docs/en/**/*.md` to the Mintlify tree
`docs/**/*.mdx` and made the database-engine reference pages generated from
`system.database_engines`, so the docs part of the branch is relocated:

- The new `Cluster` page moves to `docs/reference/engines/database-engines/cluster.mdx`
  with the Mintlify frontmatter (`sidebarTitle`, no `sidebar_position`, no `H1`) and
  the links rewritten to the new tree, and is registered in
  `docs/reference/navigation.json`, `docs/_site/redirects.json` and
  `docs/_migration/slug-map.csv`, exactly as the `Remote` page was moved in
  05df4be.
- The cross-reference from the `Remote` page to the `Cluster` engine moves into the
  `Documentation` description in `src/Databases/DatabaseRemote.cpp`: the body of
  `remote.mdx` now lives between the `AUTOGENERATED` markers and is regenerated from
  that description, and direct edits to it are rejected by the generated-region
  guard in `ci/jobs/docs_job_mintlify.py`.
…TE and skip it in listings

A cyclic chain of `Remote`/`Cluster` databases on the same server (e.g. `a` -> `b` -> `a`)
was reported lazily: `LocalTraversalGuard` threw `INFINITE_LOOP` from the local-shard
traversal on re-entry. The listing path (`fetchTablesList`) also serves whole-server scans,
so while such a pair of databases existed, every `SELECT ... FROM system.tables` /
`system.columns` of every user failed with `INFINITE_LOOP` — in CI, the cycle case of the
tests `04541_remote_database_engine` and `04846_cluster_database_engine` made unrelated
concurrent tests (`00938_fix_rwlock_segfault_long`, `00821_distributed_storage_with_join_on`)
fail with that exception:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=114417&sha=26b4fa30e58ff7401d7b32c614638491d816d768&name_0=PR
(#114417)

Now the chain is rejected eagerly, at `CREATE DATABASE` of the database that would complete
it (`throwIfLocalChainRefersBack` walks the local proxy chain by database name, following an
edge only while the cluster of the hop currently has a local shard). The check deliberately
does not run on any form of attach: a server that persisted such a chain must still start,
and the metadata loading of server startup attaches the databases with the same `ATTACH`
mode as the explicit query.

A cycle can still come into existence later (e.g. a configuration reload turns a shard of a
`Cluster` database into a local one, or an explicit `ATTACH DATABASE` completes it), so
`LocalTraversalGuard` remains as the lazy backstop, but it no longer throws from the listing
path: the re-entered database is skipped (with a warning in the log) and lists no tables, so
whole-server scans are unaffected; table resolution (`fetchTableStructure`) still reports
`INFINITE_LOOP`, because it only affects queries that name a database of the cycle.

Also covers the scenario with an integration test case (a cycle formed by a configuration
reload) and updates the stateless tests to the eager rejection.
…ists in the fallback state

Address the review finding on `SHOW CREATE TABLE` of the `Cluster` database engine: when the
live proxy is bound to the remote-only fallback cluster (the local replica of a shard does not
have the database or the table), the emitted `Distributed('cluster_name', ...)` definition
recreated a different object — a `Distributed` table over the whole cluster performs no such
fallback on the metadata lookup, so replaying it fails on the missing local objects.

Unlike the `Remote` engine, which serializes the effective fallback addresses together with
its stored credentials, the connections of the `Cluster` engine are defined by the per-replica
settings of the cluster configuration, which no explicit address list can carry, and the
fallback subset has no name of its own — no equivalent re-executable definition exists for this
transient state. `SHOW CREATE TABLE` now reports `THERE_IS_NO_QUERY` with an explanation
instead of emitting a misleading definition; the best-effort paths (e.g. the
`create_table_query` column of `system.tables`) return nothing for it and do not fail.

Covered by a new case in the `test_replica_fallback` integration test.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and pushed two fixes:

  1. The two CI failures were caused by this PR (report): the cycle case of the new test kept a pair of mutually-referring proxy databases alive for a moment, and while they existed, every whole-server scan (SELECT ... FROM system.tables / system.columns) of every concurrently running test failed with the INFINITE_LOOP exception thrown by LocalTraversalGuard from the listing path (00938_fix_rwlock_segfault_long and 00821_distributed_storage_with_join_on in the report; the pre-existing cycle case of 04541_remote_database_engine had the same latent race on master). Fixed in 9e1f439 by the "reject eagerly, skip lazily" rule: a chain of Remote/Cluster databases that refers back to itself is now rejected at CREATE DATABASE of the database that would complete it, and the lazy guard no longer throws from the listing path — a cycle that nevertheless comes into existence later (a configuration reload can turn a shard of a Cluster database into a local one, and an explicit ATTACH DATABASE bypasses the check because server startup attaches databases with the same ATTACH mode) is skipped in listings (the cyclic chain lists no tables, with a warning in the log), while table resolution still reports INFINITE_LOOP, since it only affects queries that name a database of the cycle. The eager check does not run on any form of attach, so a server that persisted such a chain still starts. Covered by the updated stateless tests and a new integration test case with a cycle formed by a configuration reload.

  2. The AI-review Major on SHOW CREATE TABLE is fixed in 361f039: when the live proxy is bound to the remote-only fallback cluster, no equivalent re-executable definition exists (the fallback subset has no name, and the per-replica settings of the cluster configuration cannot be carried by an explicit address list), so SHOW CREATE TABLE now reports THERE_IS_NO_QUERY with an explanation instead of emitting a Distributed('cluster_name', ...) definition that would recreate a different object; best-effort paths (create_table_query in system.tables) return nothing for it and do not fail. Covered by a new test_replica_fallback case and documented.

Verified locally: 04541_remote_database_engine and 04846_cluster_database_engine pass; a live cycle (constructed via ATTACH) leaves system.tables scans unaffected while SELECT reports INFINITE_LOOP; the fallback state against a second server serves SHOW TABLES/SELECT and rejects SHOW CREATE TABLE with THERE_IS_NO_QUERY.

- The `catch (...)` in `DatabaseRemote::tryGetLocalChainNext` is a deliberate
  negative answer of the cycle walk, so mark it as such for the `catch_all`
  style check.
- The chain-cycle note belongs to the generator source of the docs, the engine
  description registered in `DatabaseRemote.cpp`, not to the `AUTOGENERATED`
  region of `docs/reference/engines/database-engines/remote.mdx`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and fixed the two CI failures (report) — both were caused by this PR, and both jobs are early gates, so everything else was skipped:

  1. Style check (catch_all) — the catch (...) in DatabaseRemote::tryGetLocalChainNext looked like a silently swallowed exception. It is a deliberate negative answer of the cycle walk: a hop whose clusters cannot be resolved right now (e.g. the named cluster of a Cluster database is temporarily absent from the configuration) cannot be followed through this server either, and an unrelated database must not fail the query of the database being walked. The comment now says so and matches the Ok marker the check asks for.

  2. Docs check (Mintlify) — the chain-cycle note was added inside the AUTOGENERATED region of docs/reference/engines/database-engines/remote.mdx. That region is generated from the engine description registered in src/Databases/DatabaseRemote.cpp, so the note moved there and the generated file is back to its master content; the autogeneration workflow will propagate it.

No behavior change; the binary builds. The only unresolved review thread is the SHOW CREATE TABLE fallback one, already addressed in 361f039.

Comment thread src/Databases/DatabaseCluster.cpp Resolved
Carry one `ProxyClusters` snapshot through `fetchTable` and `getCreateTableQueryImpl`, so a configuration reload cannot make `SHOW CREATE TABLE` compare clusters from separate resolutions.
Comment thread src/Databases/DatabaseCluster.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
Comment thread src/Databases/DatabaseCluster.cpp Resolved
Comment thread src/Databases/DatabaseRemote.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

It reappeared, so here is the fix in a separate PR as you asked: #120928.

The recurrence was on 2026-09-18, on another PR's head, in the same two amd_asan_ubsan ... selected tests jobs, with the error string byte-identical to the one you quoted. Counting from your report, I measured 8 such job deaths over 6 days and 6 PRs; 4 of them, including both on 09-18, are the CI database answering HTTP 500 Code: 202 ... Too many simultaneous queries. Maximum: 1000.

Root cause: queue_max_wait_ms defaults to 0, and that setting is honoured by exactly the 202 branch this hits (ProcessList.cpp:183-193, the max_size branch). At 0 the server throws at once; at a positive value it waits for an admission slot. praktika never sends it, so every CI database request asks to be rejected rather than queued, and the client then spends its 5 retries in 31 s re-asking a saturated server. strict=True on a selected tests run makes that fatal. The PR sends the setting at half the caller's timeout, in the one shared request helper. I did not touch the fail-closed selection policy, since #114730 made it deliberate.

One thing worth knowing for anyone measuring this family: it leaves no row in default.checks, because the failing step is the CI database round-trip itself and the job's own result insert fails the same way. The 8 occurrences above come from job logs, not from CIDB.

pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Sep 19, 2026
…ection step

A `Stateless tests (..., selected tests)` job dies before running a single test
with `Failed to select tests: Failed to get previously failed tests required for
test selection`. Eight such job deaths were measured over six days on six PRs
between 2026-08-20 and 2026-09-18; four of them, including both on 2026-09-18,
are the CI database answering HTTP 500 `Code: 202. DB::Exception: Too many
simultaneous queries. Maximum: 1000`.

`queue_max_wait_ms` defaults to 0, and it is honoured by exactly the 202 branch
these requests hit: `ProcessList.cpp:183-193`, the `max_size`
(`max_concurrent_queries`) branch. At 0 the server throws immediately; at a
positive value it logs "Too many simultaneous queries, will wait N ms." and waits
on `have_space` for an admission slot, throwing only if the wait expires. The
sibling 202 branches carry different messages ("for all users", "for user X",
"insert/select queries", "for table X"), so the attribution is exact. praktika
never sends the setting, so every CI database request asks to be rejected rather
than queued, and `_post_with_retries` then spends its five attempts in 31 s
re-asking a saturated server. Because a `selected tests` run passes
`include_changed_tests=True`, `find_tests.py` has `strict=True` and converts that
into an ERROR result with zero tests run.

Send `queue_max_wait_ms` at half the caller's own timeout (30000 ms for queries,
10000 ms for inserts and the smoke test) from the single shared helper, so the
server waits for a slot instead of rejecting, and without issuing another request
to an already saturated server. This covers `query`, `insert_rows` and `check`.
The fail-closed selection policy itself is deliberate and is left untouched.

Separately, the selected-tests error handler rendered only `str()` of the outer
exception, whose message is a fixed string, so the preserved `__cause__` chain
was never shown. One of the eight occurrences (2026-09-06) therefore carries no
diagnostic at all and cannot be attributed today. Render `traceback.format_exc()`
as well; that handler catches every selection leg, and `Result.info` reaches all
three places a human looks: the job log, the HTML report and the CI database.

Validated on a server with `max_concurrent_queries=1` and the only slot held:
plain `SELECT 1` returns 500 `Code: 202` in 0.06 s; with
`queue_max_wait_ms=30000` it returns 200 after a 4.01 s wait, the holder's
remaining time, and the server logs "will wait 30000 ms."; with
`queue_max_wait_ms=1` it returns 500 again, which isolates the wait duration as
the causal variable. Seam assertions cover both hunks, each with a patch-revert
negative control.

Related: ClickHouse#114417

Co-Authored-By: Claude Opus 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Dear @thevar1able, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

alexey-milovidov and others added 2 commits September 26, 2026 19:14
…-shard `Remote` proxy

`getCreateTableQuery` is not specific to `SHOW CREATE TABLE`: it also serves
`CREATE TABLE dst AS remote_db.t` and the `create_table_query` / `engine_full`
columns of `system.tables`. Rejecting a multi-shard `Remote` proxy with
`THERE_IS_NO_QUERY` therefore regressed an existing engine. Restore the `master`
behavior (the emitted `Remote(...)` definition carries the `rand()` key) together
with its test coverage. The new `Cluster` engine keeps reporting `THERE_IS_NO_QUERY`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master and addressed the open review thread on DatabaseRemote::getCreateTableQueryImpl (a4b987e): a multi-shard Remote proxy serializes its implicit rand() key again, as on master, so CREATE TABLE ... AS and system.tables keep working for the existing engine. Only Cluster reports THERE_IS_NO_QUERY. 04813/04541 pass locally.

The only red on the previous head was Upgrade check (amd_release) (countResample ATTACH errors plus the mutation-across-upgrade check). That is the fleet-wide 26.9 upgrade-check issue addressed by #121590, not this PR.

throw Exception(ErrorCodes::LOGICAL_ERROR, "Cluster is empty");

secret = from.secret;
name = from.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.

tryGetClusterWithoutLocalReplicas keeps the original shard numbering here: it only strips local replicas from each shard and preserves the shard order, weights and names. That means _shard_num provenance must carry over as well, exactly like it does in SubclusterTag.

Right now RemoteReplicasTag leaves shard_scope_identity empty, so any query that reaches remote_only_cluster and then hits a nested Distributed / parallel-replicas read on the answering replica will treat the shipped shard scope as Foreign. The inner read then becomes unscoped (or disables parallel replicas) even though the fallback cluster is supposed to be “the same cluster without local replicas”.

Please copy from.shard_scope_identity before initMisc(). Without that, the new Cluster database fallback path changes query semantics for nested distributed reads as soon as the local replica is missing the table or database.

@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 looks ok. Some parts look excessive, but the reasoning is well-thought.

@alexey-milovidov alexey-milovidov self-assigned this Sep 28, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 28, 2026
Merged via the queue into master with commit c8b9523 Sep 28, 2026
173 checks passed
@alexey-milovidov
alexey-milovidov deleted the database-cluster branch September 28, 2026 02:04
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
alexey-milovidov pushed a commit to mneedham/ClickHouse that referenced this pull request Oct 11, 2026
… into 2 batches

`Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel)` and
`Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel)`
are the only coverage stateless *parallel* shards that still run the whole
suite un-batched, and they are the two shards that hit the 9000 s job timeout:
21 at-cap runs in 90 days, every single one reported as `error`.

An at-cap kill is an unattributable red. The ordinary functional-test path
passes `global_time_limit=0`, so there is no graceful stop: praktika's job
watchdog SIGTERMs the process group and the job exits -15 with zero failing
tests. On PR ClickHouse#114417 head f1b87f1 the shard
reported 13153 of 13154 tests and died 184 s past its budget with one worker
still inside its last test.

Runtime is drifting: over Mar->Aug the AsyncInsert parallel shard's p99 went
4397 -> 5936 s (p50) and 5121 -> 7655 s (p99), and runs over 8000 s went from
0 in April to 127 in August, against a 9000 s cap.

`prepare_stateful_data` costs ~1431 s and is paid per shard, so the model is
`setup + (total - setup)/N`. N=2 puts the observed max at 5276 s (59% of the
cap) and, at the measured 507 s/month test-phase drift, buys ~15-18 months of
headroom. N=3 would cost 2862 extra runner-seconds per workflow for headroom
nobody has asked for, and 3708b71 merged two-way stateless splits back
into single jobs, so the batch count is kept at the measured minimum.

The two `sequential` counterparts are deliberately left un-batched: their p99
is 4071 s and 3296 s.

Cost: 2 jobs become 4, i.e. +2 AMD_MEDIUM runners per PR and per master run.

The per-batch coverage artifact names had to be generated rather than listed:
the four `_ft_s3*` entries in `LLVM_FT_ARTIFACTS_LIST` were hardcoded
singletons, unlike every sibling shard's generated list, and that list feeds
both `ArtifactConfigs.llvm_profdata_file` and `llvm_coverage_job.requires`.

Workflow YAML is regenerated, not hand-edited.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. pr-feature Pull request with new product feature 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.

Cluster database engine

4 participants