Repository navigation
Conversation
When a host name resolves to several addresses, an object storage endpoint behind a rotating set of front-end IPs for example, new connections are spread by usage only. The per-front-end difference in backend-path latency is not used. With `http_latency_aware_host_selection` enabled, `PocoHTTPClient` feeds the time-to-first-byte of every `GET` and `HEAD` response back to `HostResolver` per resolved address, which keeps an EWMA of it. `HostResolver::updateWeightsImpl` multiplies the base weight of an address by the squared ratio of the median latency to its own latency (clamped to 0.1..16, floored at weight 1, so a slow address is still probed and can recover). `HTTPConnectionPool` hands out the pooled connection bound to the fastest address, and opens a new connection instead of reusing one that is much slower than the fastest known address while the pool is below its soft limit. The setting is off by default and can be changed without a restart. A request through a proxy and a request with a body are not measured. Ported from #2181 Related: #2181 Co-authored-by: Cursor <[email protected]>
Unit tests for the per-address latency EWMA, for the preference of the fast address with a floor of weight for the slow ones, and for the weights staying even when the setting is off. The test server config enables the setting, and `05830_http_latency_aware_host_selection_s3` checks that it is applied and reads many files from the mock S3 over reused connections. Co-authored-by: Cursor <[email protected]>
ianton-ru
marked this pull request as draft
November 23, 2026 13:59
6 of 28 tasks
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
…edundant wiring Remove `HostResolver::getLatencyMs` and `HostResolver::getMinLatencyMs`: after the dispatch moved to `getLatencySnapshot`, they were used only by tests, which now use `LatencySnapshot::lookupLatencyMs` and `LatencySnapshot::min_non_failed_ms`. Do not wire `http_latency_aware_host_selection` in `clickhouse-local`: it does not configure `HTTPConnectionPools` either, and it is a short-lived process. Remove the functional test `05830_http_latency_aware_host_selection_s3`: the test server config enables the setting for the whole suite, so every S3 test already exercises this path. Co-authored-by: Cursor <[email protected]>
`wipeExpiredImpl` checks `isExpired` and `isStale` only for `top()`, which is what the default dispatch hands out. The latency-aware dispatch extracts the fastest connection from any position in the heap, so a connection that was closed by the peer while idle could be handed out unchecked and fail its first request. `selectBestStoredConnectionImpl` now validates the chosen connection (skipping the `top()` that `wipeExpiredImpl` has just validated). An invalid one is moved to `expired_connections`, accounted in `stored_count` and `expired`, and the selection is repeated; if no usable connection is left, a new one is opened. Add `LatencyAwareDispatchSkipsStaleNonTopConnection`, which fails without the fix. Co-authored-by: Cursor <[email protected]>
`HostResolversPool::getResolver` constructed `HostResolver` (which runs the initial DNS lookup in its constructor) while holding the global `mutex`. Under `http_latency_aware_host_selection`, `tryGetResolver` is called on every `getConnection` and after every successful S3 `GET`/`HEAD`, so a single slow or failing DNS lookup for any cold host stalled hot-path borrows and latency reports for all other hosts. Switch `HostResolversPool::mutex` to `SharedMutex`: `tryGetResolver` and the `getResolver` hit path take a shared lock so concurrent lookups do not serialize, and `getResolver` releases the lock while creating a missing resolver, then inserts it with `try_emplace` under an exclusive lock. Add `ColdHostResolveDoesNotBlockHotResolverLookups`, which fails without the fix. Co-authored-by: Cursor <[email protected]>
`HostResolver::reportLatency` recomputed weights with `updateWeights`, which also runs the "all addresses banned" fallback and un-bans every record once the total weight is zero. `setFail` zeroes the failed address's weight with `updateWeightsImpl` and releases the lock to refresh DNS, deliberately skipping that fallback so the refresh can discover a healthy replacement. A latency sample reported in that window (for example by a request completing on a pooled connection) un-banned the address that had just failed. Use `updateWeightsImpl` in `reportLatency`: a latency sample does not change which addresses are failed. Add `LatencyReportDoesNotUnbanAddressDuringFailRefresh`, which fails without the fix. Co-authored-by: Cursor <[email protected]>
…tions `HostResolver::reportLatency` ran `updateWeightsImpl` on every reported S3 read sample, doing an O(R) median + prefix-sum recomputation and allocating a temporary `std::vector` under `HostResolver::mutex` at the full request rate. When a query or server memory limit was exceeded, that allocation threw `MEMORY_LIMIT_EXCEEDED` inside `PocoHTTPClient` after `receiveResponse` had already read the HTTP response headers, aborting a completed read. - Mark `weights_dirty = true` in `reportLatency` (`noexcept`) and recompute weights lazily in `selectBest` when a new connection actually needs an address. - Pre-reserve `measured_latencies_scratch` to `records.size()` in `updateImpl` so `updateWeightsImpl` (`noexcept`) never allocates under `mutex`. - Return `const Poco::Net::IPAddress &` from `selectBest` to avoid an extra `IPv4AddressImpl`/`IPv6AddressImpl` copy allocation. - Guard the post-response latency report in `PocoHTTPClient::makeRequestInternalImpl` so an allocation failure in `getResolvedHost` logs and drops the telemetry sample instead of failing a completed S3 request. Add `ReportLatencyDoesNotAllocateOrThrowUnderMemoryLimit`, which fails without the fix. Co-authored-by: Cursor <[email protected]>
…ptions `reportLatency`, `updateWeights`, `updateWeightsImpl`, `lookupLatencyMs` and `tryGetResolver` take locks, compare `Poco::Net::IPAddress` (whose `pImpl` can throw) or use hash containers, none of which is guaranteed not to throw, so `noexcept` would turn an exception into `std::terminate`. Keep `noexcept` only on trivial accessors. Also reserve `measured_latencies_scratch` before swapping `records` in `updateImpl`, so the invariant `capacity >= records.size()` holds even if the reserve throws. Co-authored-by: Cursor <[email protected]>
`EndpointConnectionPool::getConnection` allocates the latency snapshot and the
`expired_connections` capacity under `MemoryTrackerSwitcher{&total_memory_tracker}` (the pool
is global, not charged to the query), but destroyed them at scope exit after the switcher was
gone. Their buffers were therefore freed against the query's tracker, crediting the query with
bytes it was never charged for and leaving them accounted in the total tracker.
Declare the snapshot before the `SCOPE_EXIT` and release both buffers (not just the elements)
inside it, under the same tracker they were allocated under.
Add `LatencyAwareSnapshotIsReleasedUnderTheTrackerItWasAllocatedUnder`, which fails without the fix.
Co-authored-by: Cursor <[email protected]>
…report latency Add `AddressesLatencyReported` (latency samples recorded per address) and `HTTPConnectionsSkippedAsSlow` (pooled connection to a much slower address not reused, new connection opened instead), so the effectiveness of `http_latency_aware_host_selection` is visible in production. Document in the setting description that only the S3 client reports latency, so other HTTP clients (for example Azure Blob Storage, `url`, replication fetches) are not biased by latency. Co-authored-by: Cursor <[email protected]>
`updateCachedResolvedIp` was `noexcept` but allocates (`IPAddress`, string copy), so an allocation failure there called `std::terminate` instead of reaching the `catch` in `atConnectionDestroy`. Remove `noexcept`. The `catch` handler itself also built a `std::string` for the log message and could throw a memory limit exception inside a `noexcept` function. Block memory limit exceptions in the handler. Add a regression test that preserves a connection under a 1 byte memory limit and checks the connection is reset and not stored. Co-authored-by: Cursor <[email protected]>
…ames Only the S3 client reports latency, but the measurements are kept per host name in `HostResolver`, so any other HTTP client connecting to the same host name also gets the biased address weights and the slow-connection skipping. The description claimed that other clients are not biased. Co-authored-by: Cursor <[email protected]>
…lips The toggle is process-wide and read only inside `updateWeightsImpl`, while `weights_dirty` is set by `reportLatency` only when the toggle is on. After turning the setting off, the latency-biased weights stayed in use until the next DNS refresh or a `usage` threshold crossing, and after turning it on the already collected samples were ignored for the same time. Remember the mode the weights were computed in and let `selectBest` recompute them when it differs from the current toggle value. Co-authored-by: Cursor <[email protected]>
`usesTargetResolution` rebuilt the Poco proxy configuration and matched the `no_proxy` regular expression on every `getConnection` (when latency-aware selection is on) and on every new connection, although `host` and the proxy configuration are constant. Compute the Poco proxy configuration and the result once in the constructor and keep them in `const` members. Co-authored-by: Cursor <[email protected]>
…iguration The previous commit made the Poco proxy configuration a member of `EndpointConnectionPool`, so the `poco_proxy_config` parameter of `prepareConnectionViaProxy` shadowed it (`-Wshadow`). Use the member. Co-authored-by: Cursor <[email protected]>
`getLatencySnapshot` runs on every borrow under the resolver mutex, which is shared with `reportLatency` (every S3 response) and `resolve`. It copied a `Poco::Net::IPAddress` per address, and every copy allocates its implementation object, so a snapshot of `R` addresses made `1 + R` heap allocations under the mutex. Store a fixed-size `AddressKey` (length, scope and bytes, ordered like `Poco::Net::IPAddress`) instead, so only the entry buffer is allocated. Co-authored-by: Cursor <[email protected]>
The report ran inside `catch (...)` that logged and dropped every exception, including memory limit exceptions and query cancellation. `reportLatency` no longer allocates, so what remains is the address parsing, whose failures should propagate like any other allocation of the request. Co-authored-by: Cursor <[email protected]>
The records, their `IPAddress` implementations and the latency scratch buffer are allocated by `update` under `total_memory_tracker`, but the destructor and `reset` ran under the query tracker of whichever thread dropped the last reference, crediting the query with bytes it was never charged for. Switch to `total_memory_tracker` in both and free the buffers explicitly in the destructor, because members are destroyed after the switcher is gone. Co-authored-by: Cursor <[email protected]>
`extractAt` called `pop`, which runs `std::pop_heap` with a comparator that is not declared not to throw, so the `noexcept` contract was not guaranteed. The only caller runs in `getConnection`, which propagates exceptions. Co-authored-by: Cursor <[email protected]>
When preparing the connection to store failed, the `catch` in `atConnectionDestroy` counted a reset, and then the destructor of the half-built `connection_to_store` called `atConnectionDestroy` again and counted a second one (and could even retry preserving a connected, completed connection that had already been reported as failed). Declare the connection outside the `try` and mark it expired in the `catch`. The regression test now requires exactly one reset. Co-authored-by: Cursor <[email protected]>
Only `create` and the heap `push` of `atConnectionDestroy` switched to `total_memory_tracker`. `assign` (sockets taken over by the new session) and `updateCachedResolvedIp` allocated under the tracker of the thread that returned the connection, so the query was charged for pool-owned memory that is freed later under the total tracker, and a query at its memory limit lost the connection. Switch to `total_memory_tracker` for the whole preserve path, including the destruction of the local reference. The `catch`-handler test now uses a limit on the total tracker, and a new test checks that a query memory limit does not prevent preserving a connection. Co-authored-by: Cursor <[email protected]>
`updateImpl` changed the address metrics while merging, set `last_resolve_time`, and only then did the allocation that can still throw (the scratch buffer reserve). A failure left `records` unchanged but the metrics already moved, so the next update counted the same expired addresses again, and the refresh was skipped until the next interval. Reserve the scratch buffer before the merge, count the changes in local variables, and apply them (and `last_resolve_time`) after the non-throwing swap. The regression test sweeps a memory budget over `updateImpl` so every allocation fails once, and checks nothing changes on each failed attempt. Co-authored-by: Cursor <[email protected]>
…getResolver` Concurrent callers for the same cold host each built a `HostResolver` and the loser was discarded after it had already counted `AddressesDiscovered` and hit DNS. Serialize creation with a per-host `PendingResolver` mutex; the pool mutex is still not held across DNS. Co-authored-by: Cursor <[email protected]>
…sPool::getResolver` callers A failed lookup left its per-host slot in `pending_resolvers` forever and made every waiting caller run its own lookup one after another. Publish the resolver or the exception through a `std::shared_future` in the slot, and remove the slot on both outcomes. Co-authored-by: Cursor <[email protected]>
`std::shared_future::get` rethrows the stored `std::exception_ptr` without copying the underlying object, so concurrent callers catching `Exception &` and calling `addMessage` raced on and polluted the shared message. Use `copyMutableException` both when storing the template in the promise and when each waiter rethrows it, matching `Context::getOrCreateDisk`. Co-authored-by: Cursor <[email protected]>
…cker` The `PendingResolver` slot, `HostResolver` object, and pool map nodes belong to the global `HostResolversPool`, not to whichever query reached a cold host first. Charging them to the leader's query tracker let a query at its memory limit fail `getResolver` and publish its query-specific `MEMORY_LIMIT_EXCEEDED` to unrelated waiting queries, and freed them later under a different tracker. Allocate and release them (including in `dropCache`) under `total_memory_tracker`. Co-authored-by: Cursor <[email protected]>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Latency-weighted host selection for endpoints that resolve to several addresses. This is one independent feature split out of #2181, rebased onto
antalya-26.8.An object storage endpoint can sit behind a rotating set of front-end IPs. Today new connections are spread by usage only, so a front-end with a slower backend path gets as many connections as a fast one. The connect round-trip time does not show that difference, the time to the first response byte does.
With the new server setting
http_latency_aware_host_selection(off by default, changeable without a restart):PocoHTTPClientreports the time to first byte of eachGETandHEADresponse for the resolved address. Requests with a body and requests through a proxy are not measured.HostResolverkeeps an EWMA (alpha 0.2) per address.updateWeightsImplmultiplies the base weight of an address by the squared ratio of the median latency to its own latency, clamped to 0.1..16 and floored at weight 1, so a slow address is still probed and can recover.HTTPConnectionPoolhands out the pooled connection bound to the fastest address. If even the fastest pooled one is more than 30% and 15 ms slower than the fastest known address, and the pool is below its soft limit, it opens a new connection instead of reusing it.Changes compared with the pull request above: latency is fed back only for
GETandHEAD(the wait for a response to an upload includes server-side processing and is not a property of the address), the setting is registered insystem.server_settingsas changeable without a restart, andclickhouse-localapplies it as well.Tests: unit tests for the latency EWMA, the preference for the fast address with a weight floor, and the setting being off (
gtest_resolve_pool.cpp); stateless test05830_http_latency_aware_host_selection_s3with the setting enabled in the test server config, reading from the mock S3 over reused connections.Related: #2181
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):
Add the server setting
http_latency_aware_host_selection(off by default). When an endpoint resolves to several addresses, new connections are weighted by the measured time to first byte ofGETandHEADrequests per address, and pooled connections to the fastest address are reused first.Documentation entry for user-facing changes
The setting is documented by its
DECLAREdescription inServerSettings.cpp.CI/CD Options
Exclude tests:
Regression jobs to run: