Repository navigation
Do not ping the server from the client before every query - #111990
Conversation
Follow-up to #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 #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
|
Workflow [PR], commit [448b055] Summary: ✅
AI ReviewSummaryThis PR removes the pre-query Missing context / blind spots
Final Verdict✅ No new findings. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 133/166 (80.12%) · Uncovered code |
`04648_client_reconnect_without_ping` raced with the server: with `idle_connection_timeout = 0` the server closes the connection as soon as it is idle, but the `FIN` does not necessarily reach the client before it checks the socket for the next query, and then the query fails with `ATTEMPT_TO_READ_AFTER_EOF` instead of being run on a re-established connection. It failed in every stateless run of this pull request, always with `--output_format_parallel_formatting 0`, which happens to make the client fast enough to lose the race: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111990&sha=4744a66cefffdab16be9499aa7859338197ffdda&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29 #111990 Two tests replace it, neither of them timing-dependent. `04650_client_reconnect_without_ping` keeps the reconnection coverage, but as an `expect` test, so that there is a real pause between the queries: the server has certainly closed the connection and the client has certainly seen it. It also asserts that the client did re-establish the connection, rather than merely that the query succeeded. `04651_client_no_ping_before_query` asserts what this change is about, and fails if the `Ping` before a query comes back. All the traffic goes through a proxy that delays the beginning of every server response by two seconds, while the client is configured with `sync_request_timeout` of one second: a client that pings cannot get the `Pong` in time, so it reconnects and loses the temporary table created by the first query, while a client that does not ping is unaffected. Verified both ways - with `checkConnected` restored to `isConnected() && ping(timeouts)` the test fails with `UNKNOWN_TABLE`, which is exactly the session loss this change is about.
|
Pushed: the racy One thing worth flagging from the same CI run, in case it deserves a decision rather than a shrug: It is not reproducible (the harness re-ran it 111 times with the same settings, all passed), the test also failed once on |
Dropping the `Ping` before every query also dropped it from the two places where the client recovers from an error, and those need a round trip. A query whose exception is thrown before the server reads the block of external data leaves the protocol desynchronized: the server then reads that block, reports `Unexpected packet Data received from client` and closes the connection. This happens for every `serverError` hint in a `.sql` test, which is why `ClientBase` reconnects after an expected error. A non-blocking look at the socket cannot see a close that has not arrived yet, so under load the client kept the dead connection and the next query failed with `Connection reset by peer` - `02184_default_table_engine` failed this way in every stateless job. `02871_clickhouse_client_restart_pager` failed for the same reason on the client-error path: without the round trip the client did not notice the desynchronization and the second query continued the first one's stream instead of restarting it. `checkConnected` goes back to pinging and is used by the recovery paths. The check before every query - the one this pull request is about - uses the new `checkConnectedWithoutRoundTrip`. The new test `04655_client_reconnect_after_expected_error` makes the failure deterministic: all the traffic goes through a proxy that delays everything the server sends, the close included. It was verified to fail with `ATTEMPT_TO_READ_AFTER_EOF` when the recovery path uses the socket check, and to pass with the ping. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111990&sha=e20150aba04f61cd502ac6477b2740e388bdfcf9&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%29
A plain readability probe cannot tell a TLS post-handshake record - a session ticket or a `KeyUpdate` - from application data, so on a `tcp_secure` connection it reports a healthy idle session as unusable and the client re-establishes it, losing its temporary tables, current database and session settings. Use `getSocketState`, which decrypts just enough to tell the two apart.
|
Merged The |
|
The only red in the last run, |
|
🕵 CI status for Merged the latest |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 18/21 (85.71%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
A failed query can leave the protocol desynchronized: the server throws before it reads the block of external data of that query and then closes the connection. Only the two recovery paths that reconnect explicitly - the expected-error hint of a test and the client exception of the interactive loop - used the strong `checkConnected`. An ordinary server exception sets `have_error` and nothing else, so a session that continues after it (the interactive mode, or `--ignore-error`) went to the next query through `checkConnectedWithoutRoundTrip`, which cannot see a close that has not been delivered yet, and failed it with `ATTEMPT_TO_READ_AFTER_EOF`. Any failed query now marks the connection for resynchronization, and the check before the next query of the same session costs a round trip - the fast path stays free of it for a session that has no errors, which is what this pull request is about. `04666_client_reconnect_after_server_error` covers the case: an error without a test hint under `--ignore-error`, behind a proxy that delays everything the server sends, the close included. The proxy is moved to `helpers/delaying_tcp_proxy.py` and shared with `04655`.
|
🕵 Addressed the review blocker in The post-error contract was only preserved on the two paths that reconnect explicitly (an expected-error test hint, and a Now any failed query marks the connection for resynchronization ( New test The only red before this push was |
…y exchange starts A query can fail on the client before anything has been sent to the server - for example, on the local checks of `INTO OUTFILE`. The catch of the multi-query loop used to arm `connection_needs_resynchronization` for every client-side exception, so a session that continued after such a purely local failure (`--ignore-error`, the interactive mode) resynchronized the connection with a round trip; if the `Pong` did not arrive within `sync_request_timeout`, the client silently reconnected and lost the session state (temporary tables, the current database, session settings) even though the protocol never left sync. Now the flag is armed right before the query is sent (in `processOrdinaryQuery` and `processInsertQuery`) and cleared when the exchange completes cleanly, so only an error of a query whose exchange has actually started leads to the round trip. The `help` and AI-generator exchanges (`fetchDocumentation`, `executeQueryForSingleString`) follow the same discipline, so a failure there no longer leaves the connection silently desynchronized for the next query. The new test `04692_client_no_reconnect_after_local_error` is A/B verified: with the flag armed in the catch, the client reconnects after the local error and the subsequent query fails with `UNKNOWN_TABLE`.
… fallback fails with a server exception `Suggest::fetch` sends its query with the terminating empty block (`with_pending_data` is false), so a `Protocol::Server::Exception` is the terminal packet of a protocol-consistent exchange, just like in the `help` / AI helper exchanges. Keeping `connection_needs_resynchronization` armed after such a failure made the next query of the session pay the round-trip `checkConnected`, whose ping can time out on a slow but alive server and silently reconnect away the temporary tables, the current database and the session settings. `Suggest` now tracks whether the last exchange ended with the protocol in sync - with `EndOfStream` or with a server exception - and the fallback site clears the flag based on that instead of `getLastError`, which cannot distinguish a server exception from a transport failure. The new test `04814_client_no_reconnect_after_suggest_error` is deterministic: `max_sessions_for_user = 1` makes the background suggestions loader fail with `USER_SESSION_LIMIT_EXCEEDED` (waited for with `--wait_for_suggestions_to_load`), so the first interactive input triggers the fallback on the main connection - after the temporary table was created by the initial queries of the same session - and the fallback fails on the server with `max_result_rows = 1`. A/B verified: with the old condition restored, the client reconnects and the test fails with 'the client reconnected after the suggestions failure'. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 CI status of
The new commit |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units287 translation units recompiled, 1474 s compile time in total, 123 of them have a recent master baseline. Translation units without a recent master baseline:
|
…flight of `sendQuery` `connection_needs_resynchronization` was armed right before `connection->sendQuery`, but `Connection::sendQuery` can throw during its purely local preflight - for example, on the validation of `network_compression_method` - before the first byte of the query packet has been written. The flag stayed armed for a failure that never touched the wire, so the next query of an `--ignore-error` or interactive session resynchronized the connection with a round trip, and behind a slow server the ping could time out and silently reconnect away the session state. The arming is now encapsulated in `ClientBase::armResynchronizationAndSendQuery`, which disarms the flag again when the failed `sendQuery` has left the connection alive: a failure after `Connection::sendQuery` has started writing always disconnects the connection (see the `SCOPE_EXIT` there), so a connection that is still alive means that nothing has been sent. Applied to all four exchanges on the shared connection: ordinary queries, `INSERT`, and the two help exchanges. Adds `04818_client_no_reconnect_after_send_preflight_error`: a per-query `SETTINGS network_compression_method = 'T64'` fails exactly one query in the preflight, behind the delaying proxy with `sync_request_timeout = 1`. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 Addressed the AI review blocker in a0af351: The single CI red on ab3193f, |
|
🕵 CI on
@groeneai, investigate the read-path |
|
@alexey-milovidov Your read of the second red is right on both counts, and the fix is already open: #113925, published at 06:19Z, about 20 minutes after your comment, which is why it was not linkable yet. Confirming the distinction you drew, which I had measured the same way independently. #113891 is the write path ( It is my own regression, from my merged #113225, so One thing worth knowing given you tracked this by STID. This one signature carries two, On your first red I agree it is unrelated and have nothing to add. |
|
🕵 Triage of the three reds on
Review state is clean (no unresolved threads, AI verdict has no findings); nothing to push on this branch. Awaiting the fixes above to land, a CI re-run, and a human merge. |
…04757 and 04814 The expect-based tests 04757_client_help_error_keeps_session and 04814_client_no_reconnect_after_suggest_error ended with a teardown (`DROP USER`) whose exit status replaced the exit status of `expect`, so a failing expect script could not fail the test through the exit code (only through the output diff). Capture the status of `expect` and exit with it after the teardown. Both tests verified to still pass against a local server built from this branch. Co-Authored-By: Claude Fable 5 <[email protected]>
|
🕵 The The three failing private jobs are all unrelated to this client-only change:
The private sync PR's AI review posted a Block verdict; two findings fixed, one refuted:
The three public reds on |
…s runs The test copies a packed part directory with plain cp to simulate a stale tmp_merge directory. Stress jobs flip the default MergeTree storage_policy to (cached) S3 or Azure in the server config without passing the corresponding flag to clickhouse-test, so the no-object-storage tag does not protect them. On a remote disk, cp duplicates the metadata files without incrementing the blob reference counts, and reclaiming the stale directory deletes blobs still referenced by the live part - every later read of it fails with 'The specified key does not exist', tripping the stress check's no-such-key detector. Pin storage_policy = 'default' so the part directory is always a genuine local copy. Seen on every stress run since the test merged, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=111990&sha=279101c71314bcf8e46a083cbf950ecb2143aa44&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 (PR: ClickHouse#111990) Co-Authored-By: Claude Fable 5 <[email protected]>
Conflicts in `src/Client/ClientBase.cpp`, all with the connection resynchronization of #111990, which landed in master while this branch removed or renamed the two functions it touched: - `executeQueryForSingleString` no longer exists here (the client-side AI transport calls `executeInternalQueryForAI`/`executeScalarQueryForAI` instead), so its side of the conflict is dropped. - `fetchDocumentation` became `fetchInternalQueryResult`, which now follows the same discipline: resynchronize before the exchange, arm the flag while sending, and clear it on `EndOfStream` or on a server exception. The comments that referred to `executeQueryForSingleString` are inlined here and referenced from `runInteractive`. - `runQueryForAI` copied the old "reconnect after a client-side exception" pattern from the interactive loop, which #111990 replaced: it now resynchronizes only when the flag is armed, so a local failure no longer pays for a round trip that could silently reconnect away the session state.
Related: #110068
Related: #111982
Follow-up to #110068, which stopped pinging pooled connections and replaced the
Ping-Pongexchange with a non-blocking check of whether the connection is still usable.Connection::checkConnected, whichclickhouse-clientcalls before every query, was the last place still pinging. This extracts that check fromforceConnectedintoConnection::isStaleand uses it there too.The round trip goes away. For 300 trivial queries in one
clickhouse-client --multiquerysession (counted withstrace -c -e trace=sendto,recvfrom):sendtorecvfromAnd a slow server no longer costs the client its session. A pong that did not arrive within
sync_request_timeoutwas indistinguishable from a closed connection, so under load the client abandoned a perfectly alive session. Re-establishing a connection starts a new session, silently losing the temporary tables, the current database and the session settings of the old one - which surfaces much later in a script as a puzzling error. This is what made the03101_analyzer_identifiers_*tests flaky on loaded sanitizer runners:The server log for that run shows the client dropping a connection it had just used successfully and coming back on a new one 16 seconds later, with no server-side close in between:
This covers both flavours of that flakiness: the tests that combine
USE {CLICKHOUSE_DATABASE:Identifier}with unqualified table names (whose remaining client-side bug is fixed separately in #111982) and03101_analyzer_identifiers_2, which usesCREATE TEMPORARY TABLEand could not be fixed any other way, since temporary tables live in the session.Trade-off. A connection the server has closed is still re-established: closing it makes the socket readable, which is exactly what the check looks for. But only a close that has already arrived is seen - a connection closed microseconds ago still looks usable, and that failure is reported by the query that runs into it. There is no way around that without a round trip: the answer to a ping is equally out of date the moment it arrives. A server that went away without closing the connection is likewise no longer detected up front. This is the same trade-off #110068 made for pooled connections. The client does not retry such a query, because a query that may have already been executed is not safe to repeat.
Tests.
04651_client_no_ping_before_queryis the test for this change and fails if the ping before a query comes back: all the traffic goes through a proxy that delays the beginning of every server response by two seconds, while the client is configured withsync_request_timeoutof one second. A client that pings cannot get thePongin time, so it reconnects and loses the temporary table created by the first query; a client that does not ping is unaffected. Verified both ways - withcheckConnectedrestored toisConnected() && ping(timeouts)the test fails withUNKNOWN_TABLE, which is exactly the session loss described above.04650_client_reconnect_without_pingcovers the re-establishing of a connection that the server closed (idle_connection_timeout = 0), and asserts that the client did reconnect rather than merely that the query succeeded. It is anexpecttest, so that there is a real pause between the queries: the initial.sqlversion of it had no such pause and raced with the arrival of theFIN, which is why it failed in the first CI run of this pull request.The ping is also still used deliberately after a failed query, where it is not a liveness probe but a check that the protocol is still in sync - leftover unread packets make the connection readable, so the new check detects that case as well.
CI report the flakiness was found in: 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
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
clickhouse-clientno longer pings the server before every query, which removes a network round trip per query. It also no longer re-establishes the connection - silently starting a new session, and so losing temporary tables, the current database and session settings - just because the server was too slow to answer a ping.Documentation entry for user-facing changes
Version info
26.8.1.1245(included in26.8and later)