Repository navigation
Improve system.clusters performance: filter pushdown and pipelined Keeper requests for Replicated databases - #122223
Conversation
`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.
|
Workflow [PR], commit [a9491a3] Summary: ✅
AI ReviewSummaryPR #122223, reviewed at Missing context / blind spots
Final Verdict✅ Approve — no new inline findings or unresolved code-review findings. Runtime CI and private Cloud validation remain pending. |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes33 object files changed (+385.87 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 units431 translation units recompiled, 4159 s compile time in total, 430 of them have a recent master baseline. Translation units without a recent master baseline:
|
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`.
| /// The number of Keeper requests submitted by this response, without waiting for them. | ||
| size_t numKeeperRequests() const |
There was a problem hiding this comment.
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?
| /// Parses the responses to `getReplicasInfoPaths` of a request in flight; throws when `max_log_ptr` is missing. | ||
| ReplicasInfo parseReplicasInfo(PendingReplicasInfo & pending) const; |
There was a problem hiding this comment.
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
63c4b93
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]>
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]>
Related: #79300
Part of that issue: this covers the open-source
Replicateddatabases. The shared-catalog clusters of ClickHouse Cloud are filled by a private implementation oftryGetReplicasInfothat 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Queries to
system.clustersare now much faster on servers with manyReplicateddatabases: replica state is requested from Keeper concurrently in a bounded window instead of one round trip per database, and aWHERE cluster = ...condition is applied before going to Keeper, so only the selected clusters are queried.Details
system.clustersfillsis_active,unsynced_after_recovery,replication_lag,recovery_timeandis_shared_catalog_clusterfrom Keeper viaDatabaseReplicated::requestReplicasInfoandawaitReplicasInfo, one multi-read perReplicateddatabase. Before this change the databases were processed one after another, so the latency wasnumber of Replicated databases × Keeper round trip, and a filter onclusterdid not prevent the requests for the other databases.The first item of the issue (rewriting the table to
IStorageto know the requested columns) is already covered byIStorageSystemOneBlock::supportsColumnsMask, whichsystem.clustersuses: the Keeper requests were already skipped when none of the replica-state columns is requested.Changes:
WHEREclause that refers toclusteris applied to the cluster names before anything is read from Keeper (getFilterSampleBlock+VirtualColumnUtils::filterBlockWithPredicate, the same approach assystem.databases). Names are not unique (a configured cluster can shadow aReplicateddatabase 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.zkutil:ZooKeeper::asyncTryGet.tryGetwith 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 inwaitForResponses(MultiReadResponses::MultiResponseWithFuture, ~40 lines, all in the header). The error rule oftryMultiis 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 aKeeperExceptionwith the same error code. The lazy variant exists only for try-requests (static_assertin the constructor).tryGetitself does not change, because the retry loops rely on a hardware error surfacing in the call. The lazy wait is a plainfuture.get, as in the futures path: it is bounded by the receive thread of the client, but it does not go throughwaitForFutureWithProgressand creates nozookeeper.multiOpenTelemetry span;tryGetReplicasInfostill uses synchronoustryGet, retaining the timeout diagnostics andzookeeper.multitracing span forClusterProxy::executeQuery. Covered by aTestKeepergtest and a promise-based hardware-error gtest.system.clusters. AlongsideDatabaseReplicated::tryGetReplicasInfo,requestReplicasInfosends the request withasyncTryGetand returns an opaquePendingReplicasInfo(its own small header, soDatabaseReplicated.hdoes not includeZooKeeper.h), andawaitReplicasInfoawaits and parses the response; both use the same paths and parser as the synchronous method, and neither new method throws.system.clustersadmits 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 (NULLcolumns) for that database only and is logged atinformationfor expected coordination failures, exactly as before.tryGetReplicasInfokeeps the synchronous path for its other caller (ClusterProxy::executeQuery).Cloud: the
#if CLICKHOUSE_CLOUDblock applies the same name filter to the two shared-catalog clusters and otherwise keeps calling the synchronousSharedDatabaseCatalog::tryGetReplicasInfo. It cannot be compiled in the public CI, please double-check it.Not changed / known limits:
system.clustersquery after a restart still builds the cluster of eachReplicateddatabase from Keeper one by one (tryGetClustercold path, until the DDL worker has cached it).pool->getStatus()per shard and the DNS lookup forhost_addressare unchanged.Replicateddatabase named like a configured cluster, which interferes with parallel tests): a configured cluster shadowing aReplicateddatabase 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
Replicateddatabases with one replica each, 5 runs, median. The network latency to the Keeper port is emulated withtc netem(delay on packets to port 9181 only), to make the round trips visible.SELECT is_active, replication_lag FROM system.clusters(all databases):Both send 200
ZooKeeperMultiReadrequests; in master they are sequential round trips (the time grows as200 × 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: twoReplicateddatabases; checks the returned rows and the number ofZooKeeperMultiReadprofile events per query fromsystem.query_log: 1 for a filter on one database (also via the aliasnameand via anIN (subquery)predicate), 2 for two databases (one request each), 0 when no replica-state column is requested,>= 1for a filter that cannot be pushed down and for the unfiltered query (concurrent tests may add databases). Finally it deletesmax_log_ptrof one database and checks that the other database requested with it still gets its state (NULLvs1) and that nothing leaks into the client stderr.gtest_zookeeper.cpp:asyncTryGetoverTestKeeper(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): 100Replicateddatabases, 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
26.11.1.1528-master(included in26.11and later)