Repository navigation
Detect HTTP keep-alive peer disconnect with MSG_PEEK/SSL_peek, not poll - #110402
Conversation
`HTTPConnectionPool::isStale` decided whether a pooled keep-alive connection was still usable with `poll(SELECT_READ, 0)`: readable meant stale, on the assumption that an idle keep-alive connection has no data pending. On a plain socket that holds, but on an HTTPS connection it produces a false positive. `poll` reflects the raw TCP socket, so an unread TLS post-handshake record (a session ticket or `KeyUpdate`) makes an entirely live secure connection look readable, i.e. stale, and the pool discards it and reconnects - at the cost of a fresh TLS handshake - on nearly every borrow. This ports the shared, TLS-aware helper `isSocketPeerClosed` (added in `src/IO`) from the distributed cache fix and switches `HTTPConnectionPool::isStale` to it: - for a plain socket, a single non-blocking, non-destructive `recv(..., MSG_PEEK | MSG_DONTWAIT)`: `0` means the peer sent a FIN (closed); `> 0` means bytes are on the wire (alive); `EAGAIN` / `EWOULDBLOCK` means a healthy idle connection; any other error (e.g. `ECONNRESET`) is treated as closed/broken; - for a TLS (`SecureStreamSocket`) socket, an `SSL_peek` on a temporarily non-blocking socket. A raw `MSG_PEEK` cannot tell TLS records apart - an unread `close_notify` looks the same as unread application data or a session ticket, and in TLS 1.3 the record content type is encrypted. `SSL_peek` decrypts just enough to distinguish real application data and harmless post-handshake messages (a session ticket or `KeyUpdate`), treated as alive, from a `close_notify` (`SSL_ERROR_ZERO_RETURN`) or a broken session, treated as closed, without consuming application data. A small `ssl` accessor is added to Poco's `SecureSocketImpl` / `SecureStreamSocketImpl` to reach the underlying OpenSSL `SSL` object. `gtest_socket_peer_closed` covers both paths, including a `socketpair`-backed TLS connection: an unread session ticket and pending application data read as alive; a `close_notify` and an abrupt close read as closed. The `close_notify` case also asserts that a raw `MSG_PEEK` misfires there, which is exactly why the TLS-aware path is needed. This is the public-repo counterpart, and the follow-up promised in, the distributed cache fix ClickHouse/clickhouse-private#64217 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [e657179] Summary: ✅
AI ReviewSummaryThis PR replaces Final Verdict✅ No new inline findings. |
…_closed` The `arm_tidy` build failed with `readability-make-member-function-const`: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110402&sha=fc0110924d90278ecd45080550a1eb9ee5b7e3fe&name_0=PR&name_1=Build%20%28arm_tidy%29 Co-Authored-By: Claude Fable 5 <[email protected]>
…losed one `isSocketPeerClosed` answers "has the peer closed?", but `HTTPConnectionPool::isStale` needs the stronger "is this idle connection safe to reuse?": an idle keep-alive connection must have nothing to read, and unread bytes (e.g. a queued `408 Request Timeout` a server sends before closing an idle connection) would be misparsed by the next borrower as the response to its own request. The old `poll(SELECT_READ)` check rejected such connections; the peer-closed predicate would have kept them. Introduce a three-state probe `getSocketState` (`Idle` / `DataPending` / `Closed`, with `getSslSocketState` as the TLS core) and make `isStale` treat anything but `Idle` as stale. This preserves the old `poll` semantics for plain sockets exactly, while still fixing the TLS false positive: `SSL_peek` processes an unread session ticket / `KeyUpdate` without surfacing it as data, so a live idle secure connection reads as `Idle`. `isSocketPeerClosed` / `isSslPeerClosed` remain as thin wrappers (state == `Closed`) with unchanged behavior. Tests now assert the exact state in every scenario, including `DataPending` for pending plain and TLS application data and `Idle` for a session ticket. Co-Authored-By: Claude Fable 5 <[email protected]>
…ocketState SSL_ERROR_WANT_READ/WANT_WRITE from SSL_peek conflated two different situations: a truly idle connection with nothing on the wire, and a connection where a TLS record has started arriving but is not yet complete enough for SSL_peek to decrypt. Both end in the same SSL_get_error result, so the previous check reported both as Idle. A connection pool must not reuse a connection in the second case: once the rest of that record arrives, a later borrower's SSL_read would decrypt it and misparse it as the response to its own unrelated request - the same hazard already handled for a fully-arrived pending record, just with a narrower timing window. SSL_has_pending reports on OpenSSL's internal buffer regardless of whether the buffered record is complete, so it distinguishes a partial record (still returns 1) from a session ticket / KeyUpdate that was fully consumed by SSL_peek (returns 0, safe to call Idle). Adds SocketPeerClosed.SecurePartialRecordIsPendingNotIdle, which splits a real ciphertext record across two raw sends to reproduce the partial-arrival window and fails without this fix. Addresses review feedback from clickhouse-gh on this PR.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 176/179 (98.32%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR is a TLS-aware rewrite of the HTTPS connection-pool stale-connection check (SocketPeerClosed / HTTPConnectionPool) — none of the ClickBench SELECTs execute that outbound-connection path. The three flagged clickbench queries (Q4 -14.7%, Q15 -11.9%, Q17 +11.5%) all land inside master's current variance band with essentially flat CPU, so the deterministic gates correctly suppressed them as within_baseline_envelope; the deltas are run-to-run noise, not a PR effect. No plausible performance regression or improvement from this change. Envelope suppressions look consistent with the diff and the data. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
| #if USE_SSL | ||
| /// TLS-aware core of the check, exposed for testing. The socket underlying `ssl` MUST be in | ||
| /// non-blocking mode (the caller guarantees this) so that `SSL_peek` cannot block. | ||
| SocketState getSslSocketState(ssl_st * ssl); |
There was a problem hiding this comment.
Ok, but according to our style, we always write SSL, not Ssl.
|
@groeneai, send a follow-up PR that renames Ssl to SSL. |
|
Acknowledged. Sending a follow-up PR that renames |
|
Follow-up PR renaming Ssl to SSL: #111018 (getSslSocketState -> getSSLSocketState, isSslPeerClosed -> isSSLPeerClosed). Pure rename, no behavior change. |
Follow-up to ClickHouse#110402: rename getSslSocketState -> getSSLSocketState and isSslPeerClosed -> isSSLPeerClosed to match the all-caps SSL initialism used across the codebase. Pure rename, no behavior change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…losed-detection Detect HTTP keep-alive peer disconnect with MSG_PEEK/SSL_peek, not poll
Related: https://github.com/ClickHouse/clickhouse-private/pull/64217
HTTPConnectionPool::isStale— the stale-connection check for every pooled HTTP/HTTPS/S3 keep-alive connection — decided whether a connection was still usable withpoll(SELECT_READ, 0): readable meant stale, on the assumption that an idle keep-alive connection has no data pending. On a plain socket that holds, but on an HTTPS connection it produces a false positive.pollreflects the raw TCP socket, so an unread TLS post-handshake record (a session ticket orKeyUpdate) makes an entirely live secure connection look readable, i.e. stale, and the pool discards it and reconnects — at the cost of a fresh TLS handshake — on nearly every borrow.This ports the shared, TLS-aware helper
isSocketPeerClosed(added insrc/IO) from the distributed cache fix https://github.com/ClickHouse/clickhouse-private/pull/64217, and applies the follow-up that that PR explicitly deferred: switchingHTTPConnectionPool::isStaleto it. Underneath the boolean helper sits a three-state probegetSocketState—Idle(alive, nothing to read),DataPending(alive, unread data waiting),Closed— andisStalerequiresIdle: a pooled idle keep-alive connection must have nothing to read, and unread bytes (e.g. a queued idle-timeout408a server sends before closing the connection) would be misparsed by the next borrower as the response to its own request, so such a connection is discarded exactly as the oldpollcheck did.recv(..., MSG_PEEK | MSG_DONTWAIT):0⇒ the peer sent a FIN (Closed);> 0⇒ bytes on the wire (DataPending);EAGAIN/EWOULDBLOCK⇒ a healthy idle connection (Idle); any other error (e.g.ECONNRESET) ⇒ closed/broken (Closed);SecureStreamSocket) socket, anSSL_peekon a temporarily non-blocking socket. A rawMSG_PEEKcannot tell TLS records apart — an unreadclose_notify(an orderly shutdown) looks the same as unread application data or a session ticket, and in TLS 1.3 the record content type is encrypted, so inspecting the bytes cannot disambiguate them either.SSL_peekdecrypts just enough to distinguish real application data (DataPending), harmless post-handshake messages (a session ticket orKeyUpdate), which it processes without surfacing as data (Idle), and aclose_notify(SSL_ERROR_ZERO_RETURN) or a broken session (Closed), without consuming application data.SSL_ERROR_WANT_READ/WANT_WRITEalone is ambiguous, though: it also covers a record that has only partially arrived (e.g. the first fragment of a queued response), which is not idle either — the rest of that same record could complete after the connection is handed to the next borrower and be misparsed as the response to its own request.SSL_has_pendingresolves the ambiguity: it reports on OpenSSL's internal buffer regardless of whether the buffered record is complete, so a session ticket /KeyUpdatefully consumed bySSL_peekreads asIdle(nothing left buffered), while a partial record reads asDataPending.A small
sslaccessor is added to Poco'sSecureSocketImpl/SecureStreamSocketImplto reach the underlying OpenSSLSSLobject.gtest_socket_peer_closedcovers both paths, including asocketpair-backed TLS connection, asserting the exact state in every scenario: an unread session ticket reads asIdle; pending plain and TLS application data reads asDataPending(and is not consumed by the check); a partial TLS record - split across two rawsend()calls to reproduce the in-flight window - reads asDataPending, notIdle; aclose_notifyand an abrupt close read asClosed. Theclose_notifycase also asserts that a rawMSG_PEEKmisfires there, which is exactly why the TLS-aware path is needed. The existingConnectionPoolTestsuite (real local HTTP server, keep-alive reuse) passes unchanged.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed spurious reconnections of pooled HTTP keep-alive connections over TLS (HTTPS, S3). The stale-connection check used
pollon the socket, which misreports a live secure connection carrying an unread TLS post-handshake record (a session ticket orKeyUpdate) as closed; it now uses a non-blockingMSG_PEEKon plain sockets andSSL_peek/SSL_has_pendingon TLS sockets, which also correctly detects an orderly TLS shutdown and a TLS record that has only partially arrived.Documentation entry for user-facing changes
Version info
26.7.1.1197(included in26.7and later)