Repository navigation
Do not ping pooled connections before use; reconnect on failure instead - #110068
Conversation
A connection taken from the connection pool was pinged before every use (`forceConnected` sent a `Ping` and waited for `Pong`, reconnecting only if it failed). For a hot, already-established connection this Ping-Pong round trip is pure overhead - it roughly doubles the latency of small queries (very visible in `clickhouse-benchmark --client-side-time`) and adds a round trip to every distributed query that reuses a connection. The ping is unnecessary: sending the actual request already tells us whether the connection is alive. This makes the acquisition path optimistic everywhere: - `forceConnected` no longer pings; it just connects if not connected. - The `force_connected` parameter is removed from the whole connection pool API (`IConnectionPool::get`, `ConnectionPool`, `ConnectionPoolWithFailover`, `ConnectionEstablisher::run` and the async variant) and its callers (`RemoteQueryExecutor`, `HedgedConnectionsFactory`). A connection that the server closed while it was idle in the pool is now detected when it is first used and recovered by retrying on a freshly established connection: `ConnectionEstablisher::run` reconnects once if a connection it did establish fails its first request (synchronous path; the asynchronous path continues to rely on retrying the next replica, as `ConnectionPoolWithFailover` already did). This preserves the behaviour of the paths that previously depended on the pre-use ping (e.g. parallel replicas), while the common distributed `SELECT` path was already optimistic and validated the connection with its `TablesStatus` round trip. The `Ping` protocol command and `Connection::ping` / `checkConnected` remain available as a convenience (interactive client, fuzzer). A `connection_stale_on_establish` fail point and test 04508 exercise the stale-connection recovery deterministically. Follow-up: extend the same reactive reconnect to the paths that do not go through the establisher's round trip (no-`table_to_check` `SELECT`, synchronous distributed `INSERT` via `RemoteInserter`, and `clickhouse-benchmark`), where a gracefully-closed connection currently surfaces on the first response read. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [81abee0] Summary: ✅
AI ReviewSummaryThis PR removes the per-use Findings
Final VerdictStatus: Minimum required actions:
|
…gument
`StorageQueryRunner` was added on `master` after this branch diverged and
calls `IConnectionPool::get` with the old 3-argument signature
(`get(timeouts, settings, /*force_connected=*/ true)`). This branch removes
the `force_connected` parameter from the connection pool API, so after
merging `master` the call no longer compiles:
src/Storages/StorageQueryRunner.cpp:560:61: error: no matching member
function for call to 'get'
Drop the removed argument so `executeOnShard` uses the 2-argument overload,
consistent with the other callers. The behaviour is unchanged: the pooled
connection is used optimistically and a stale connection surfaces as a
normal query error, matching the rest of this PR.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110068&sha=9b667a735d74944209ff510ab894ac6fe5b0a515&name_0=PR
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `04508_connection_reconnect_on_stale` test runs one
`SELECT dummy FROM remote('127.0.0.1', system, one)`, which returns
exactly one row (`0`). The `connection_stale_on_establish` fail point is
`ONCE`: it fires a single time during connection establishment, the
establisher reconnects and retries once, and the query then executes a
single time. The committed reference erroneously expected two rows
(`0\n0`); a second row would in fact indicate the query was executed
twice. Correct the reference to a single `0` to match the actual (and
correct) behaviour observed in CI (Fast test).
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110068&sha=e7f9dcfcd822c789cd363af2fe3546c81ea4c112&name_0=PR&name_1=Fast%20test
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
The integration run for
So the reactive reconnect needs to be extended to the no- Reports: Integration 1/6 (s3_cluster_restart) · Integration 6/6 (hedged_requests) |
…ng establishment The integration tests surfaced two regressions on the asynchronous connection paths (test_s3_cluster_restart, test_storage_delta partitioned deltaLakeCluster, test_hedged_requests): 1. A pooled connection that the server closed while it was idle was no longer detected on the no-table_to_check path (cluster table functions such as s3Cluster and deltaLakeCluster): the establisher marked it usable without issuing any request, and the failure surfaced only as ATTEMPT_TO_READ_AFTER_EOF while reading the response, where there is no retry. Previously the ping in forceConnected recovered this case. Fixed by detecting a stale pooled connection in Connection::forceConnected with a zero-timeout poll: an idle pooled connection must have nothing pending to read, so anything readable means EOF (the server closed it), a socket error, or a protocol desync - all of which are recovered by reconnecting. Unlike the removed ping this is a single non-blocking system call and adds no round trip. It also covers the paths the PR description deferred to a follow-up (RemoteInserter-style INSERT and clickhouse-benchmark) for gracefully-closed connections. DistributedConnectionReconnectCount is incremented on this reconnect, as it was for the ping-based one. 2. ConnectionPool::get connected the entry before ConnectionEstablisher::run could install the async callback, so hedged connections performed a fully blocking connect and Hello handshake: a SIGSTOP-ed replica held the query for the whole handshake_timeout (test_stuck_replica exceeded its 10 s bound) and an unroutable replica was waited for synchronously instead of being preempted after hedged_connection_timeout_ms (test_async_connect saw no HedgedRequestsChangeReplica events). Fixed by splitting acquisition from establishment: the new IConnectionPool::getUnchecked hands out the connection without checking it, and the establisher connects/revalidates it via forceConnected after installing its async callback - with the callback installed, Connection::connect uses a non-blocking connect the caller can preempt. result.entry is assigned before connecting, keeping the connection visible to the multi-address timeout handling of ConnectionEstablisherAsync. Direct ConnectionPool::get callers keep receiving an established, poll-validated connection. The establisher's reconnect-and-retry is now gated on the connection having been taken from the pool already established (only such a connection can be stale); a failure of a freshly established connection is left to the caller's replica retry with its error accounting. Co-Authored-By: Claude Fable 5 <[email protected]>
| /// preempt a slow connect or handshake and switch to another replica. `result.entry` is | ||
| /// assigned before connecting, so the connection being established is visible to the | ||
| /// multi-address timeout handling of ConnectionEstablisherAsync. | ||
| result.entry->forceConnected(*timeouts); |
There was a problem hiding this comment.
forceConnected only filters sockets that already show EOF/RST or buffered junk. When table_to_check == nullptr, we still return is_usable immediately after this call, so a pooled socket that became half-open (the remote disappeared behind a blackhole / partition and never sent FIN/RST) goes straight to the real query. RemoteQueryExecutor then fails the first sendQuery / header read on the no-table_to_check paths instead of reconnecting, whereas the old pre-use Ping recovered that case. We still need a first-request retry for this branch, or some other safe probe before marking the connection usable.
There was a problem hiding this comment.
Correct that the no-table_to_check branch marks the pooled connection usable after only the zero-timeout poll, so a half-open socket whose peer vanished without sending FIN/RST is not detected during establishment. This is intentional and documented in the comment on Connection::forceConnected: detecting such a peer at acquisition time requires a blocking round-trip probe — i.e. exactly the per-use Ping this PR removes to avoid doubling the latency of small queries. The poll covers the common stale cases (server-closed/EOF, socket error, protocol desync) at zero round-trip cost; a true half-open peer is left to surface on first use and be recovered by the caller's next-replica retry, rather than paid for on every acquisition. Adding a reactive first-request reconnect on the read paths is a possible follow-up, kept out of this PR's scope by design.
| entry->forceConnected(timeouts); | ||
|
|
||
| Entry entry = getUnchecked(timeouts, settings); | ||
| entry->forceConnected(timeouts); |
There was a problem hiding this comment.
This now returns a connection that only passed the zero-timeout poll. That is enough for server-closed or desynchronized sockets, but not for half-open pooled sockets where the peer disappeared without FIN/RST. Plain ConnectionPool::get callers such as non-internally-replicated DistributedSink, distributed index analysis, and StorageQueryRunner have no ConnectionEstablisher retry around the first real request, so they now surface a user-visible network exception where the old Ping reconnected transparently. These paths still need either a safe first-request reconnect or a separate API that preserves the old “validated before return” contract.
There was a problem hiding this comment.
Right that plain ConnectionPool::get callers have no establisher-level retry after the poll. A reactive first-request reconnect could be added for the read callers (StorageQueryRunner, distributed index analysis), but it cannot be applied uniformly: on the DistributedSink INSERT path (DistributedSink.cpp:460, immediately followed by the RemoteInserter send) reconnecting and retrying after a partial send would risk duplicating rows, so it is not safe to retry blindly there. The alternative — preserving a "validated before return" path for these callers — would reintroduce the per-use Ping this PR removes. The common stale cases are already covered by the zero-timeout poll in forceConnected; extending recovery to true half-open peers on these direct-call sites is a scope/design decision left for the author.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 102/109 (93.58%) · Uncovered code |
Follow-up to ClickHouse#110068, which stopped pinging pooled connections and replaced the `Ping`-`Pong` exchange with a non-blocking check of whether the connection is still usable. `Connection::checkConnected`, which `clickhouse-client` calls before every query, was the last place still pinging; extract the check from `forceConnected` into `Connection::isStale` and use it there as well. Two things improve. The ping cost a round trip per query: for 300 trivial queries in one `clickhouse-client --multiquery` session, the number of network system calls drops from 1792 to 907 (604 -> 304 `sendto`, 1188 -> 603 `recvfrom`). And, more importantly, a pong that does not arrive within `sync_request_timeout` was indistinguishable from a closed connection, so on a loaded server the client abandoned a perfectly alive session. Re-establishing a connection starts a new session, which silently loses the temporary tables, the current database and the session settings of the old one, so this surfaced much later in a script as a puzzling error, e.g. `UNKNOWN_TABLE` for a table that certainly exists. It made the `03101_analyzer_identifiers_*` tests flaky on loaded sanitizer runners, both those using `USE {CLICKHOUSE_DATABASE:Identifier}` with unqualified table names and `03101_analyzer_identifiers_2`, which uses `CREATE TEMPORARY TABLE`: Code: 60. DB::Exception: Unknown table expression identifier 't' in scope SELECT COLUMNS('^c') FROM t. Maybe you meant test_qp0dhise.t?. (UNKNOWN_TABLE) with the server log showing the client dropping a connection it had just used and coming back on a new one 16 seconds later. A connection the server really has closed is still re-established: closing it makes the socket readable, which is what the check looks for. A server that went away without closing the connection is no longer detected up front - that failure now surfaces as an error of the query that runs into it, the same trade-off ClickHouse#110068 made for pooled connections. https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=a58de9c1a55e6577c3a6cafdac5609bc90234ef0&name_0=MasterCI&name_1=Stateless%20tests%20%28amd_msan%2C%20WasmEdge%2C%20parallel%2C%202%2F2%29
…nected-ping Do not ping pooled connections before use; reconnect on failure instead
`clickhouse-client` on 26.3 checks an established connection with a `Ping` before each query (`Connection::checkConnected`, called from `ClientBase`). #110068 and its follow-up 4744a66 removed that check and are not on the branch. The helper did not answer the `Ping` and serves one connection, so the client reconnected and hung, and the scenarios of 04616 that go through the helper ran into the helper's timeout. The helper now reads the addendum and answers every `Ping` with a `Pong` before it waits for the query. A client that does not ping sends the query right after the addendum and is served as before. Co-Authored-By: Claude Fable 5.2 <[email protected]>
A connection taken from the connection pool was pinged before every use:
forceConnectedsent aPingand waited forPong, reconnecting only if it failed. For a hot, already-established connection this Ping-Pong round trip is pure overhead — it roughly doubles the latency of small queries (very visible inclickhouse-benchmark --client-side-time, where the client-side stopwatch measures the ping round trip in addition to the query round trip) and adds a round trip to every distributed query that reuses a pooled connection.The ping is unnecessary: a stale pooled connection can be detected without a round trip. This PR makes the acquisition path optimistic everywhere and replaces the ping with a zero-timeout poll plus reactive retry.
What changes
force_connectedparameter is removed from the whole connection pool API (IConnectionPool::get,ConnectionPool,ConnectionPoolWithFailover,ConnectionEstablisher::runand the async variant) and its callers (RemoteQueryExecutor,HedgedConnectionsFactory).forceConnectedno longer pings an already-established connection. Instead it validates it with a zero-timeout poll: an idle pooled connection must have nothing pending to read, so anything readable means the server closed it (EOF), a socket error, or a protocol desync — all recovered by reconnecting. This is a single non-blocking system call and adds no round trip. It covers all users of the pool, including the no-table_to_checkpaths (cluster table functions such ass3ClusteranddeltaLakeCluster), non-internally-replicated distributedINSERT(DistributedSink), andclickhouse-benchmark.ConnectionEstablisher::runreconnects once and retries if a connection that was taken from the pool already established fails its first request (synchronous path); the asynchronous path relies on retrying the next replica, exactly asConnectionPoolWithFailoveralready did. The common distributedSELECTpath additionally validates the connection with itsTablesStatusround trip.ConnectionEstablishernow happens strictly under the caller's async callback: the newIConnectionPool::getUncheckedhands out the connection without checking it, and the establisher connects/revalidates it after installing the callback, soConnection::connectuses a non-blocking connect. Hedged connections can therefore preempt a slow connect or handshake and switch to another replica, as before (previouslypool->getcould block on connect before the callback was installed).Pingprotocol command andConnection::ping/checkConnectedremain available as a convenience (interactive client, fuzzer).A
connection_stale_on_establishfail point and test04508_connection_reconnect_on_staleexercise the stale-connection recovery deterministically;test_s3_cluster_restart,test_storage_deltaandtest_hedged_requestscover the poll-based reconnect and the non-blocking hedged establishment against real node restarts.Merge note. This makes the ping removal global and therefore supersedes the benchmark-specific change in #110054 (with this PR the benchmark no longer needs a special case). If #110054 merges first, its
get(..., /*force_connected=*/false)call must be simplified toget(timeouts, settings)when rebasing this PR, since theforce_connectedparameter is removed here.Related: #110054
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Pooled connections are no longer pinged before each use. This removes a
Ping-Ponground trip that was added to every reused connection, reducing the latency of distributed queries and ofclickhouse-benchmark. A stale pooled connection is detected with a zero-timeout poll (a non-blocking check that adds no round trip) and recovered by reconnecting.Documentation entry for user-facing changes
Version info
26.7.1.1198(included in26.7and later)