Skip to content

Improve system.clusters performance: filter pushdown and pipelined Keeper requests for Replicated databases - #122223

Merged
antonio2368 merged 10 commits into
ClickHouse:masterfrom
kolsha:system-clusters-79300
Nov 6, 2026
Merged

antonio2368 merged 10 commits into
ClickHouse:masterfrom
kolsha:system-clusters-79300

Conversation

@kolsha

@kolsha kolsha commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #79300

Part of that issue: this covers the open-source Replicated databases. The shared-catalog clusters of ClickHouse Cloud are filled by a private implementation of tryGetReplicasInfo that this PR does not change (the name filter skips it when the cluster is not selected, nothing more); if the reporter's warehouses use the shared catalog, that part needs a follow-up in the private repository.

Changelog category (leave one):

  • Performance Improvement

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

Queries to system.clusters are now much faster on servers with many Replicated databases: replica state is requested from Keeper concurrently in a bounded window instead of one round trip per database, and a WHERE cluster = ... condition is applied before going to Keeper, so only the selected clusters are queried.

Details

system.clusters fills is_active, unsynced_after_recovery, replication_lag, recovery_time and is_shared_catalog_cluster from Keeper via DatabaseReplicated::requestReplicasInfo and awaitReplicasInfo, one multi-read per Replicated database. Before this change the databases were processed one after another, so the latency was number of Replicated databases × Keeper round trip, and a filter on cluster did not prevent the requests for the other databases.

The first item of the issue (rewriting the table to IStorage to know the requested columns) is already covered by IStorageSystemOneBlock::supportsColumnsMask, which system.clusters uses: the Keeper requests were already skipped when none of the replica-state columns is requested.

Changes:

  1. Filter pushdown. The part of the WHERE clause that refers to cluster is applied to the cluster names before anything is read from Keeper (getFilterSampleBlock + VirtualColumnUtils::filterBlockWithPredicate, the same approach as system.databases). Names are not unique (a configured cluster can shadow a Replicated database of the same name), so the filter yields a set of names and the clusters keep their order. The "are replica-state columns requested" check now looks the columns up by name in the sample block instead of relying on them being the last five columns of the table.
  2. zkutil: ZooKeeper::asyncTryGet. tryGet with the MultiRead feature sends one request and waits for it in the call; without MultiRead it already returns futures that are awaited on the first access (MultiReadResponses::ResponsesWithFutures). This commit adds the lazy counterpart for MultiRead: the request is sent in the call and awaited on the first access to the result or in waitForResponses (MultiReadResponses::MultiResponseWithFuture, ~40 lines, all in the header). The error rule of tryMulti is kept: a hardware error of the request is thrown on the first access instead of in the call; the per-path results, a missing node included, stay in the sub-responses. Repeated access to a failed request throws a KeeperException with the same error code. The lazy variant exists only for try-requests (static_assert in the constructor). tryGet itself does not change, because the retry loops rely on a hardware error surfacing in the call. The lazy wait is a plain future.get, as in the futures path: it is bounded by the receive thread of the client, but it does not go through waitForFutureWithProgress and creates no zookeeper.multi OpenTelemetry span; tryGetReplicasInfo still uses synchronous tryGet, retaining the timeout diagnostics and zookeeper.multi tracing span for ClusterProxy::executeQuery. Covered by a TestKeeper gtest and a promise-based hardware-error gtest.
  3. Pipelined requests in system.clusters. Alongside DatabaseReplicated::tryGetReplicasInfo, requestReplicasInfo sends the request with asyncTryGet and returns an opaque PendingReplicasInfo (its own small header, so DatabaseReplicated.h does not include ZooKeeper.h), and awaitReplicasInfo awaits and parses the response; both use the same paths and parser as the synchronous method, and neither new method throws. system.clusters admits requests into a sliding window, then awaits them while writing rows in cluster order. The window targets 512 pending Keeper requests: with MultiRead, each cluster uses one request; without it, admitting one cluster can take the total above 512 by that cluster’s requests. The 200-database measurement below still fits in one window. Each database keeps its own request and its own error handling: a failed request yields an empty replica state (NULL columns) for that database only and is logged at information for expected coordination failures, exactly as before. tryGetReplicasInfo keeps the synchronous path for its other caller (ClusterProxy::executeQuery).

Cloud: the #if CLICKHOUSE_CLOUD block applies the same name filter to the two shared-catalog clusters and otherwise keeps calling the synchronous SharedDatabaseCatalog::tryGetReplicasInfo. It cannot be compiled in the public CI, please double-check it.

Not changed / known limits:

  • The first system.clusters query after a restart still builds the cluster of each Replicated database from Keeper one by one (tryGetCluster cold path, until the DDL worker has cached it).
  • pool->getStatus() per shard and the DNS lookup for host_address are unchanged.
  • Not covered by a stateless test (it would need a Replicated database named like a configured cluster, which interferes with parallel tests): a configured cluster shadowing a Replicated database of the same name. Both rows are still emitted, in the same order as before, by construction.

Measurement

Dev VM, Debug build, embedded Keeper on localhost, 200 Replicated databases with one replica each, 5 runs, median. The network latency to the Keeper port is emulated with tc netem (delay on packets to port 9181 only), to make the round trips visible.

SELECT is_active, replication_lag FROM system.clusters (all databases):

Keeper delay master this PR
none 63 ms 17 ms
+1 ms 277 ms 28 ms
+5 ms 1071 ms 55 ms

Both send 200 ZooKeeperMultiRead requests; in master they are sequential round trips (the time grows as 200 × RTT), here they are in flight together.

... WHERE cluster = 'one_database': master 62 / 270 / 1070 ms and 200 requests (the filter did not prevent them), this PR 14 / 12 / 15 ms and 1 request.

SELECT cluster, host_name FROM system.clusters (no replica-state columns, no Keeper): 2 ms in both.

Test

05244_system_clusters_predicate_pushdown.sh: two Replicated databases; checks the returned rows and the number of ZooKeeperMultiRead profile events per query from system.query_log: 1 for a filter on one database (also via the alias name and via an IN (subquery) predicate), 2 for two databases (one request each), 0 when no replica-state column is requested, >= 1 for a filter that cannot be pushed down and for the unfiltered query (concurrent tests may add databases). Finally it deletes max_log_ptr of one database and checks that the other database requested with it still gets its state (NULL vs 1) and that nothing leaks into the client stderr.

gtest_zookeeper.cpp: asyncTryGet over TestKeeper (two requests in flight, size known before the response, accessed out of order, a missing node stays per path, waitForResponses) and a hardware error thrown on every access to the response, which only a unit test can produce.

tests/performance/system_clusters_replicated_databases.xml (4th commit): 100 Replicated databases, the replica-state query for all of them and for one of them, so that the CI performance comparison shows a slowdown if the requests become sequential again or the filter stops being applied before Keeper. On the dev VM (Debug) the whole test, setup and teardown included, takes 10 s.


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

Version info

  • Merged into: 26.11.1.1528-master (included in 26.11 and later)

`SELECT ... FROM system.clusters WHERE cluster = 'x'` used to build the
clusters of all `Replicated` databases and read the replica state of
every one of them from Keeper, one round trip per database, only to
drop the rows afterwards.

Apply the part of the `WHERE` clause that refers to `cluster` to the
cluster names first (`getFilterSampleBlock` and
`filterBlockWithPredicate`, as `system.databases` does), and only build
and query the selected clusters. Names are not unique (a configured
cluster may have the name of a `Replicated` database), so the filter
yields a set of names and the clusters keep their order.

Decide whether the replica-state columns are requested by looking them
up by name in the sample block instead of relying on them being the
last five columns of the table.

Related: ClickHouse#79300
`tryGet(paths)` with the MultiRead feature sends one request and waits
for it before returning, so a caller that reads the state of many
independent objects pays one round trip per object. Without MultiRead
the same call already returns futures that are awaited on the first
access (`MultiReadResponses::ResponsesWithFutures`).

Add the lazy counterpart for MultiRead: `asyncTryGet(paths)` sends the
request and returns a `MultiTryGetResponse` whose responses are awaited
on the first access or in `waitForResponses`
(`MultiReadResponses::MultiResponseWithFuture`). The error rule of
`tryMulti` is kept: a hardware error of the request is thrown on the
first access instead of in the call, the per-path results, a missing
node included, stay in the sub-responses. The lazy variant exists only
for try-requests (`static_assert`), and the size of the result is known
without waiting.

`tryGet(paths)` itself does not change: retry loops rely on a hardware
error surfacing in the call.
`system.clusters` fills `is_active`, `replication_lag` and the other
replica-state columns of `Replicated` databases from Keeper, one
`DatabaseReplicated::tryGetReplicasInfo` call per database, each of
them a full Keeper round trip. On a server with many `Replicated`
databases the query time is `number of databases x round trip`: 200
databases take 60 ms with a local Keeper and over a second with 5 ms of
network latency.

Split `tryGetReplicasInfo` into `requestReplicasInfo`, which sends the
Keeper request with `ZooKeeper::asyncTryGet` and returns an opaque
`PendingReplicasInfo`, and `awaitReplicasInfo`, which awaits and parses
the response. `system.clusters` sends the requests of all databases
first and awaits them while writing the rows, so they are in flight
together and the query takes about one round trip. Each database still
has its own request and its own error handling: a failed request yields
an empty replica state for that database only and is logged as before.
`tryGetReplicasInfo` remains as a wrapper for its other callers.

The test checks the returned rows, the number of Keeper requests per
query and that a database whose `max_log_ptr` is missing does not
affect the others requested with it.

Part of ClickHouse#79300 (the
shared-catalog clusters of ClickHouse Cloud are filled by private code
and are not changed here).
The gain of the previous commits is a latency property that a stateless
test cannot assert: the Keeper requests of all `Replicated` databases
are in flight together instead of one round trip per database, and a
filter on `cluster` is applied before going to Keeper. Pin it with a
performance test: 100 `Replicated` databases, the replica-state query
for all of them and for one of them. If the requests become sequential
again, the comparison in CI shows the slowdown.
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a9491a3]

Summary: ✅


AI Review

Summary

PR #122223, reviewed at a9491a30238e3d465b5d424d4871a515671b5347, pushes filters on cluster ahead of Keeper reads and pipelines replica-state requests for Replicated databases in a bounded window. No unresolved actionable findings remain. The earlier fan-out, synchronous timeout, and test-initialization findings are addressed; the fixed test thread has been resolved. Consumers of the new lazy response form were traced through DatabaseReplicated::tryGetReplicasInfoBatch and parseReplicasInfo (storage, moves, sizing, and indexing), and the added Keeper tests (waitForResponses and repeated error access). ClusterProxy::executeQuery retains the synchronous response path.

Missing context / blind spots
  • ⚠️ The current CI workflow is still running. Relevant stateless, unit, and performance jobs were pending when checked. Tests were not run locally; completed CI results would close this validation gap. The PR supplies focused regression tests, a performance test, and before/after measurements.
  • ⚠️ The private SharedDatabaseCatalog implementation is unavailable in this checkout. Its Cloud branch needs confirmation from the private sync build and tests.
Final Verdict

✅ Approve — no new inline findings or unresolved code-review findings. Runtime CI and private Cloud validation remain pending.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-system-table system.* tables (introspection, system metadata, performance visibility). labels Sep 25, 2026
@kolsha kolsha added the can be tested Allows running workflows for external contributors label Sep 25, 2026
Two findings of the CI on the previous commits, no behaviour change:

- Style check `catch_all`: the `catch (...)` blocks of `requestReplicasInfo`
  and `awaitReplicasInfo` log through `logReplicasInfoFailure`, which the
  check does not know as handling. The blocks now take the code of the
  exception with `getCurrentExceptionCode` themselves and pass it to the
  helper, which only chooses the log level.
- clang-tidy `performance-move-const-arg`: a ternary with a `std::move`
  inside one of its branches, passed to the `const ReplicasInfo &` of
  `writeCluster`, is reported as "passing result of std::move() as a const
  reference argument" (the check matches any conditional operator that
  contains a `std::move`). The awaited replica state goes into a local
  first.
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a9491a302 with master d2d24986c (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 13b6ea75d; 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

33 object files changed (+385.87 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Databases/DatabaseReplicated.cpp.o 1.23 MiB 1.28 MiB +47.57 KiB (+3.77%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemClusters.cpp.o 252.33 KiB 285.39 KiB +33.06 KiB (+13.10%)
src/CMakeFiles/dbms.dir/Storages/StorageKeeperMap.cpp.o 1.19 MiB 1.21 MiB +22.16 KiB (+1.83%)
src/CMakeFiles/dbms.dir/Storages/StorageReplicatedMergeTree.cpp.o 4.81 MiB 4.83 MiB +18.42 KiB (+0.37%)
src/Storages/System/CMakeFiles/clickhouse_storages_system.dir/StorageSystemZooKeeper.cpp.o 710.66 KiB 729.07 KiB +18.41 KiB (+2.59%)

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

431 translation units recompiled, 4159 s compile time in total, 430 of them have a recent master baseline.

Translation units without a recent master baseline:

  • programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s

Job report

Keep a 512-request window while filling `system.clusters` to avoid
unbounded Keeper fan-out on large installations. Preserve the synchronous
`tryGet` diagnostics for `ClusterProxy`, and retain failed multi-read
responses so repeated access keeps throwing `KeeperException`.
@kolsha
kolsha requested a review from antonio2368 October 19, 2026 08:52
@kolsha
kolsha marked this pull request as ready for review October 19, 2026 08:52
@antonio2368 antonio2368 self-assigned this Oct 19, 2026
Comment thread src/Common/ZooKeeper/ZooKeeper.h Outdated
Comment on lines +108 to +109
/// The number of Keeper requests submitted by this response, without waiting for them.
size_t numKeeperRequests() const

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.

Nit: numKeeperRequests returns 0 for RegularResponses, although a request was sent there too. It counts only the requests that are awaited on access, and it does not drop after they are awaited. Maybe rename it (and PendingReplicasInfo::numKeeperRequests) to something like numDeferredRequests, and say in the comment that a result that was already received gives 0?

Comment thread src/Databases/DatabaseReplicated.h Outdated
Comment on lines +291 to +292
/// Parses the responses to `getReplicasInfoPaths` of a request in flight; throws when `max_log_ptr` is missing.
ReplicasInfo parseReplicasInfo(PendingReplicasInfo & pending) const;

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.

Nit: tryGetReplicasInfo also passes a response that has already been received, not only a request in flight. Maybe "Parses the responses to getReplicasInfoPaths; for a request in flight, the first access waits for it"?

…`tryGetReplicasInfoBatch`

Replace `requestReplicasInfo` / `awaitReplicasInfo` and the opaque
`PendingReplicasInfo` handle with one static `DatabaseReplicated::tryGetReplicasInfoBatch`.
The bound on Keeper requests in flight now lives next to the code that reads Keeper,
and counts databases instead of Keeper requests, following the `deque` window of
`StorageReplicatedMergeTree` (`max_batches_in_flight`). This removes
`MultiReadResponses::numKeeperRequests`, the request accounting in `system.clusters`
and `PendingReplicasInfo.h`.

The bound is for fairness on the Keeper session shared with the rest of the server:
a full client request queue blocks the caller instead of failing the request.

`parseReplicasInfo` takes the responses instead of the handle, so the synchronous
`tryGetReplicasInfo` no longer builds a fake handle; it reads the `ddl_worker` state
once per cluster instead of once per replica. `tryGetReplicasInfo` is no longer
`noexcept`, as before this PR.
…s_predicate_pushdown`

`CREATE DATABASE` returns before the DDL worker creates the `active` node of the
replica, so `is_active` could be 0 under load. Poll until both replicas are active.
Also require at least two `ZooKeeperMultiRead` requests for the queries whose filter
is not pushed down: one request would also pass with a pushed-down filter.
…site

The `catch_all` style check accepts a `catch (...)` only when its body visibly handles
the exception, e.g. calls `getCurrentExceptionCode`; a helper that reads the code
itself is not recognized.
…onditional expression

The conditional expression copied the result anyway, which `clang-tidy` reports as
`performance-move-const-arg`. Bind both branches to `const` lvalues instead, so that
nothing is copied.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=122223&sha=04d86391a4affa965f533d46d547632a636e79cb&name_0=PR&name_1=Build%20(arm_tidy%2C%201%2F4)
PR: ClickHouse#122223
@antonio2368
antonio2368 added this pull request to the merge queue Nov 6, 2026
Merged via the queue into ClickHouse:master with commit 63c4b93 Nov 6, 2026
366 of 367 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
The check of the tests a PR adds or changes (ClickHouse#129330) failed a PR only when
a query's time grows run over run on the tested server. A test whose runs
are noisy without a trend passed its own PR, and in master_head PR mode the
report's own unstable/changed verdict never fails a PR. That is how
system_clusters_replicated_databases (ClickHouse#122223) got in: tested-server
spread (stddevPop / median of its runs) 0.41-2.1 in its PR, now > 0.5 on
both master servers in about 99% of runs and the noisiest test on master.

The check now also fails on an unstable query of such a test:

- PR changes only files under tests/ and the reference is the performance
  reference build of the tested master commit's sources (find_prev_build's
  new third value; a reference of an older commit, as in about a quarter
  of PR jobs, does not count): both servers run the same code built the
  same way, so the report's verdict judges the test; fail on changed_fail
  or unstable_fail of report/all-queries.tsv. A query that failed on the
  reference server and ran only on the tested one is not in that file; it
  is judged by the rule below.
- Any other PR or reference (code changes, the official-build fallback, or
  an older reference): the report measures the PR's change, not the test
  (the floors flag 79% of the heads of the 214 code PRs that changed a
  perf test in 2026-11-12..21, their own speedups). Fail when stddevPop /
  median of the tested server's runs is above 0.5 (at least 5 runs). A
  spread the change causes also fails: after the merge both master servers
  run that code.

The bar 0.5 flags 0.5% of those code-PR heads and 0.2% of quiet tests'
master heads (CIDB backtest), and all 4 jobs of ClickHouse#122223. A query the trend
check already reports gets only its trend row. The reading loop of
find_run_trends moves to read_query_runs, shared by both checks;
run_trend_gate becomes changed_tests_gate.

Validated locally on downloaded job logs (no test of the test
infrastructure): ClickHouse#122223's 4 jobs fail (the old check passes them); the
new tests of ClickHouse#129328, ClickHouse#124553, ClickHouse#131203 (code PRs) and the tests-only
ClickHouse#130763, ClickHouse#129627 pass; the run-trend output is unchanged on all 1754 tests
of 14 jobs.

Related: ClickHouse#100759

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
The two queries of the test (2-15 ms) wait on the server's embedded Keeper.
Its request and response threads poll their queues (BusyWaitBackoff):
100 us sleeps while busy, backing off to dispatch_busy_wait_long_sleep_us
(10 ms) after ~5-8 ms of idleness (ClickHouse#109255). perf.py alternates the server
order (L,R / R,L), so each server's runs alternate between a polling Keeper
(it ran right before: #0 ~5 ms) and a backed-off one (it waited through the
other server's query: #0 ~18 ms). The median lands between the two modes
(in-run CV 47-77% on master CI). perf.py's stop-condition checks before
runs 8, 10, 14 and 20 all precede reference-first runs, which is why on
master CI (two consecutive master builds) the candidate measured 8-20%
faster than the reference.

Disable #0 and ClickHouse#1 (they keep their numbers and history) and append the same
scans run 128 (ClickHouse#2) and 512 (ClickHouse#3) times in one query with loop(view(...)).
LoopSource plans the inner query and builds its pipeline on every pass, so
every pass goes to Keeper again (12800 and 512 ZooKeeperMultiRead per
query); passes 2..N find the Keeper polling, so the wake-up is paid at most
once per query (up to ~20 ms of a 0.5-1 s query).

Validated on CI's amd layout (8 CPUs, one hyperthread per physical core,
max_threads 8, an embedded Keeper per server, master a2126db on both
sides) with CI's stat_threshold method, 10 accepted invocations:
- ClickHouse#2: stat_threshold 0.080-0.119, median |diff| 0.037, in-run CV 6.3%.
  In one invocation |diff| was 0.105, above the 0.10 bar I set for it but
  below its stat_threshold 0.114, so the report would not show it.
- ClickHouse#3: stat_threshold 0.009-0.084, max |diff| 0.066, in-run CV 2.8%.
- Old #0 in the same session: stat_threshold 0.568-0.724, CV 56%; old ClickHouse#1
  0.712-1.127, CV 82%.
- Ratio of the second to the first server position: ClickHouse#2 1.025, ClickHouse#3 1.021,
  old #0 4.07. With dispatch_busy_wait_long_sleep_us=100 the old #0 ratio
  drops from 3.0-4.6 to 0.85-0.96.
- Before ClickHouse#122223 (f0e4854 vs 63c4b93) ClickHouse#2 is 8.2x and ClickHouse#3 19.2x slower
  (ClickHouse#3: 51200 vs 512 multi-reads), so both still measure that change.

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

can be tested Allows running workflows for external contributors comp-system-table system.* tables (introspection, system metadata, performance visibility). pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants