Skip to content

Do not ping pooled connections before use; reconnect on failure instead - #110068

Merged
alexey-milovidov merged 6 commits into
masterfrom
remove-force-connected-ping
Jul 19, 2026
Merged

alexey-milovidov merged 6 commits into
masterfrom
remove-force-connected-ping

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 10, 2026 •

Copy link
Copy Markdown
Member

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, 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

  • 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).
  • forceConnected no 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_check paths (cluster table functions such as s3Cluster and deltaLakeCluster), non-internally-replicated distributed INSERT (DistributedSink), and clickhouse-benchmark.
  • A failure the poll cannot see (the server went away without closing the socket) is detected on first use: ConnectionEstablisher::run reconnects 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 as ConnectionPoolWithFailover already did. The common distributed SELECT path additionally validates the connection with its TablesStatus round trip.
  • Connection establishment in ConnectionEstablisher now happens strictly under the caller's async callback: the new IConnectionPool::getUnchecked hands out the connection without checking it, and the establisher connects/revalidates it after installing the callback, so Connection::connect uses a non-blocking connect. Hedged connections can therefore preempt a slow connect or handshake and switch to another replica, as before (previously pool->get could block on connect before the callback was installed).
  • 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_connection_reconnect_on_stale exercise the stale-connection recovery deterministically; test_s3_cluster_restart, test_storage_delta and test_hedged_requests cover 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 to get(timeouts, settings) when rebasing this PR, since the force_connected parameter is removed here.

Related: #110054

Changelog category (leave one):

  • Improvement

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-Pong round trip that was added to every reused connection, reducing the latency of distributed queries and of clickhouse-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

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.1198 (included in 26.7 and later)

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [81abee0]

Summary: ✅


AI Review

Summary

This PR removes the per-use Ping from pooled connections and replaces it with a zero-timeout poll plus selective retry, which fixes the already-discussed EOF-after-restart cases and the async hedged-connect regression. The remaining problem is that two important surfaces still have only the poll half of that contract: the no-table_to_check establisher path and plain ConnectionPool::get callers can still hand a half-open pooled socket to the real query, so they regress from transparent reconnect to a user-visible network failure.

Findings

⚠️ Majors

  • [src/Client/ConnectionEstablisher.cpp:92] The no-table_to_check branch now marks a pooled connection usable after only the zero-timeout poll. A socket whose peer disappeared without sending FIN/RST is invisible to that poll, so remote/cluster-function style reads can still fail on the first real request instead of reconnecting as the old pre-use Ping did.
    Suggested fix: add the same first-request reconnect for the no-table_to_check path, or keep a separate safe probe before returning is_usable.

  • [src/Client/ConnectionPool.cpp:150] Plain ConnectionPool::get callers no longer have any reactive retry after the poll. That regresses non-internally-replicated DistributedSink, distributed index analysis, and StorageQueryRunner: a half-open pooled socket now becomes a user-visible exception where the old Ping reconnected before the query started.
    Suggested fix: preserve a “validated before return” path for these callers, or add a first-request reconnect at each direct-call site where the actual request cannot be safely retried after partial send.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Restore transparent reconnect for the no-table_to_check establisher path when a pooled socket is half-open.
  • Restore equivalent recovery for plain ConnectionPool::get callers that currently rely only on the zero-timeout poll.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 10, 2026
alexey-milovidov and others added 3 commits July 11, 2026 04:30
…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]>
Comment thread src/Client/ConnectionEstablisher.cpp Resolved
Comment thread src/Client/Connection.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The integration run for 00c207e7e3d surfaces four persistent (retry_failed) failures, all on the asynchronous connection paths this PR changes. All four are stable on master (CI database, last 21 days), so these are regressions rather than flakes:

Test master fails / runs
test_s3_cluster_restart::test_reconnect_after_nodes_restart 0 / 3843
test_s3_cluster_restart::test_reconnect_after_nodes_restart_no_wait 0 / 3843
test_hedged_requests::test_async_connect 0 / 3880
test_hedged_requests::test_stuck_replica 1 / 3880
  • The two test_s3_cluster_restart failures are the documented follow-up scope: s3Cluster is a no-table_to_check SELECT, so ConnectionEstablisher::run marks the pooled connection usable without any request. After the nodes restart, the stale socket is no longer detected during establishment (the async path has can_reconnect = false) and surfaces as ATTEMPT_TO_READ_AFTER_EOF during the response read (RemoteQueryExecutorReadContext → MultiplexedConnections::receivePacketUnlocked) instead of reconnecting. The test asserts the query still succeeds with DistributedConnectionReconnectCount == 2.
  • The two test_hedged_requests failures are not in the follow-up list: replacing resumeConnectionWithForceOption(error_count != 0) with plain resume() changes the hedged async-connect behaviour — test_async_connect no longer reaches the expected HedgedRequestsChangeReplica count, and test_stuck_replica exceeds its 10 s bound (10.58 s).

So the reactive reconnect needs to be extended to the no-table_to_check and hedged async paths (or those paths handled) for this PR to be green, rather than deferred.

Reports: Integration 1/6 (s3_cluster_restart) · Integration 6/6 (hedged_requests)

alexey-milovidov and others added 2 commits July 12, 2026 20:46
…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);

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.

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.

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.

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);

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.

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.

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 102/109 (93.58%) · Uncovered code

Full report · Diff report

@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.

Ok.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 19, 2026
Merged via the queue into master with commit 89a5afd Jul 19, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the remove-force-connected-ping branch July 19, 2026 21:24
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 19, 2026
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Aug 12, 2026
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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…nected-ping

Do not ping pooled connections before use; reconnect on failure instead
vdimir added a commit that referenced this pull request Nov 18, 2026
`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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product 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