Skip to content

Detect HTTP keep-alive peer disconnect with MSG_PEEK/SSL_peek, not poll - #110402

Merged
alexey-milovidov merged 7 commits into
masterfrom
http-pool-peer-closed-detection
Jul 19, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
http-pool-peer-closed-detection

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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 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 https://github.com/ClickHouse/clickhouse-private/pull/64217, and applies the follow-up that that PR explicitly deferred: switching HTTPConnectionPool::isStale to it. Underneath the boolean helper sits a three-state probe getSocketState — Idle (alive, nothing to read), DataPending (alive, unread data waiting), Closed — and isStale requires Idle: a pooled idle keep-alive connection must have nothing to read, and unread bytes (e.g. a queued idle-timeout 408 a 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 old poll check did.

  • for a plain socket, a single non-blocking, non-destructive 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);
  • 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 (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_peek decrypts just enough to distinguish real application data (DataPending), harmless post-handshake messages (a session ticket or KeyUpdate), which it processes without surfacing as data (Idle), and a close_notify (SSL_ERROR_ZERO_RETURN) or a broken session (Closed), without consuming application data. SSL_ERROR_WANT_READ/WANT_WRITE alone 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_pending resolves the ambiguity: it reports on OpenSSL's internal buffer regardless of whether the buffered record is complete, so a session ticket / KeyUpdate fully consumed by SSL_peek reads as Idle (nothing left buffered), while a partial record reads as DataPending.

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, asserting the exact state in every scenario: an unread session ticket reads as Idle; pending plain and TLS application data reads as DataPending (and is not consumed by the check); a partial TLS record - split across two raw send() calls to reproduce the in-flight window - reads as DataPending, not Idle; 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. The existing ConnectionPoolTest suite (real local HTTP server, keep-alive reuse) passes unchanged.

Changelog category (leave one):

  • Improvement

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 poll on the socket, which misreports a live secure connection carrying an unread TLS post-handshake record (a session ticket or KeyUpdate) as closed; it now uses a non-blocking MSG_PEEK on plain sockets and SSL_peek/SSL_has_pending on 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

  • Documentation is written (mandatory for new features) — not applicable

Version info

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

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

clickhouse-gh Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e657179]

Summary: ✅


AI Review

Summary

This PR replaces HTTPConnectionPool::isStale's raw readability probe with a TLS-aware getSocketState helper and adds focused tests for plain sockets, TLS session tickets, close_notify, and split TLS records. I did not find any remaining blocker or major issue in the current code; the previously reported stale-reuse hazards are addressed in the current diff.

Final Verdict

✅ No new inline findings.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 14, 2026
Comment thread src/Common/HTTPConnectionPool.cpp Resolved
alexey-milovidov and others added 6 commits July 15, 2026 06:21
…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.
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 86.00% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 176/179 (98.32%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 503 561 +11.5% <0.0001 cache: The +11.5% is already not_sure and within master's variance band; CPU barely moved and the PR touches only the HTTPS pool, so this is borderline noise rather than a PR regression.

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
  • StressHouse run: 05e9ae97-55aa-4938-ad06-a3d2567c1ed0
  • MIRAI run: 9d49e73d-c2be-4d41-9550-6e057cde8822
  • PR check IDs:
    • clickbench_108554_1784317849
    • clickbench_108560_1784317849
    • clickbench_108570_1784317849
    • tpch_adapted_1_official_108578_1784317849
    • tpch_adapted_1_official_108590_1784317849
    • tpch_adapted_1_official_108601_1784317849

Comment thread src/IO/SocketPeerClosed.h
#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);

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, but according to our style, we always write SSL, not Ssl.

@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 self-assigned this Jul 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 19, 2026
Merged via the queue into master with commit e5463d9 Jul 19, 2026
350 of 351 checks passed
@alexey-milovidov
alexey-milovidov deleted the http-pool-peer-closed-detection branch July 19, 2026 20:37
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, send a follow-up PR that renames Ssl to SSL.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. Sending a follow-up PR that renames Ssl to SSL across the identifiers #110402 added; I will post the link here.

@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up PR renaming Ssl to SSL: #111018 (getSslSocketState -> getSSLSocketState, isSslPeerClosed -> isSSLPeerClosed). Pure rename, no behavior change.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…losed-detection

Detect HTTP keep-alive peer disconnect with MSG_PEEK/SSL_peek, not poll
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