Repository navigation
Enforce handshake_timeout_milliseconds across the handshake paths - #121547
Conversation
The deadline was checked only at the top of `nextImpl`, so it could fire only on a read the peer itself unblocked. A peer that sent two bytes and then stopped held the handler thread for `receive_timeout`, 300 s by default, rather than the 30 s the setting promises. Trickling one byte per second was bounded; saying nothing was not, and the second shape is the cheaper one. Hold the socket receive timeout at the time left before the deadline, re-applied per read so that a byte sent just before each timeout cannot restart the timer and stretch the total to a multiple of the budget. The last window keeps a floor of 500 ms so bytes that are merely late still land; that is the only overdraft. `clearHandshakeTimeout` restores the timeout the socket had, and a request made through `setReceiveTimeout` while the deadline is armed is what gets restored. `TCPHandler` needs no change and gains the bound for the Hello, the Addendum and the PROXY header. `MySQLHandler` had no handshake bound at all and now arms the same one, handing the remaining budget to the buffer that replaces `in` on the SSL upgrade.
|
Workflow [PR], commit [bac7695] Summary: ✅
AI ReviewSummaryThis PR tightens Findings❌ Blockers
Final VerdictChanges requested. LLVM Coverage Report |
`MySQLHandler::finishHandshake` reads its first bytes with raw `socket().receiveBytes` - deliberately, so that Poco can still start SSL - and those reads never reach `nextImpl`, where the clamp lived. A client that took the greeting and then sent nothing still held the thread for `receive_timeout`. Translate the Poco timeout on that read into `SOCKET_TIMEOUT` the way `ReadBufferFromPocoSocket` does, so both paths name the peer and the millisecond value instead of logging a bare "Timeout". The tests no longer pass while the bound is missing: a client-side timeout fails rather than counting as a hangup, the disconnect has to land inside four times the budget, and both silence cases assert the server-side timeout in the log. The new case sends nothing at all, which is the read that bypasses the buffer.
`read_bytes` reads straight off the socket, and `receiveBytes` restarts the socket timeout on every call, so a client feeding one byte just before each expiry stretched the phase to about one budget per call: ~3x for the 3-byte header and ~36x for `SSLRequest`. Re-apply what is left of the budget before each call. `SecureStreamSocket::attach` negotiates TLS inline, before the new buffer exists, so it starts from the remaining budget too. Poco drives that loop itself, so this bounds each read there rather than their total: the TLS negotiation is not yet wall-clock bounded. The log assertions now count the lines already present and wait for one more. Both silence cases share a message and `wait_for_log_line` tails history, so either could have been satisfied by the other's line.
On a blocking socket OpenSSL reads inside its own state machine: `SSL_do_handshake` loops over `BIO_read` until it has a whole record, so only `SO_RCVTIMEO` applied, and only per read. A peer dribbling one byte before each timeout kept a handshake alive for as long as it liked - measured at 23 s against a 3 s budget, and unbounded in principle. Neither Poco's `remaining_time` nor the deadline in `ReadBufferFromPocoSocket` could intervene, because control never returned to either between reads. `completeHandshakeImpl` now drives the handshake non-blocking. OpenSSL hands control back with WANT_READ/WANT_WRITE, and the poll that waits for the peer is charged against the budget, so it runs out in wall-clock time. `BlockingRestorer` puts the socket back on every exit path, and `mustRetry` takes the caller's blocking mode, since the socket's own is temporarily false while we drive it. `getMaxTimeoutOrLimit` takes the greater of the two socket timeouts, so the send timeout is clamped alongside the receive one while a deadline is armed - without that the budget would be `send_timeout`, 300 s by default. Same drip-feed after the change: cut at 3.009 s.
`mustRetry` asks whether waiting for the peer is this class's job or the caller's, and it answered that by reading the socket's blocking mode. That stopped being true once `completeHandshakeImpl` started flipping the mode itself, so the answer was passed in as a parameter that contradicted the object's own state. `HandshakeDriver` now owns both facts: it makes the socket non-blocking and raises `_drivingHandshake`, restoring both on scope exit. `waitHere()` answers the question from that state, so `mustRetry` keeps its original signature and its three other call sites are untouched.
`read_bytes` wrote the remaining budget straight into the socket, so an operator who sets `receive_timeout` below `handshake_timeout_milliseconds` got the larger of the two on the reads that bypass the buffer: 3000 ms where 100 ms was asked for. The buffered path never did that, because its clamp takes the minimum with the timeout the socket had and applies the floor. `applyHandshakeDeadlineToSocket` exposes that same clamp for callers that cannot go through `nextImpl`, so the policy lives in one place and the raw reads get the minimum and the floor as well.
The floor is the only way the deadline is overdrawn, so keep it small: a tenth of a second is still long enough for bytes that are merely late. The setting text also says the budget covers the TLS negotiation now, which it does. The trickle tests pace under the floor on purpose - a slower client has its read time out first and reports the socket timeout rather than the deadline - so the interval follows it down, and the step count derives from the budget.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units399 translation units recompiled, 2554 s compile time in total, 399 of them have a recent master baseline. |
The header phase hand-rolled what `setHandshakeTimeout` now does: take the smaller of `http_headers_read_timeout` and `receive_timeout`, put it on the socket, check the elapsed time on every refill through `DeadlineReadBuffer`, and restore the timeout afterwards. Use the shared mechanism instead and delete the buffer, which had this one user. It is also stricter: the deadline is checked before each read and the window is held at the time left, so a header read can no longer overshoot it by up to a whole `receive_timeout`. A client too slow to send its headers now has the connection closed on `SOCKET_TIMEOUT` rather than receiving `400 Bad Request`.
The PostgreSQL listener passes a zero receive timeout, which means "wait forever", and unlike `MySQLHandler` the handler never sets one. A peer that connected to the port and sent nothing held its thread for good: measured still open after 40 s where MySQL on the same server closed at 3 s. That is one thread per TCP handshake, before authentication. Arm the same deadline around the startup exchange. Arming records the socket's current timeout - the listener's zero, which the clamp treats as "wait forever" and therefore never prefers - so the window becomes the budget, and clearing it after authentication restores that zero, leaving the session phase as it is. The TLS upgrade hands the remaining budget to the buffer that replaces `in`, as on the MySQL path.
`changeIO` is the function that replaces the buffers, so it is the one that should hand the remaining budget to the replacement. The TLS upgrade site is two lines again, and the constructor's first call is a no-op because there is no buffer to take a deadline from yet. Also trims the comments added along this branch to the ones a name cannot carry.
handshake_timeout_milliseconds while a read blocks, and bound the MySQL handshakehandshake_timeout_milliseconds across the handshake paths
`applyHandshakeDeadlineToSocket` only clamped, so the raw MySQL reads re-armed a floor-sized window forever once the budget was spent: `handshakeMillisecondsLeft` reported 1, never 0, and nothing threw. A client could finish the 36-byte `SSLRequest` a byte at a time well past the deadline. The helper now checks the stopwatch and throws before clamping, and `nextImpl` calls it rather than repeating the check, so the buffered and raw paths enforce the same thing. That sentinel existed because `setHandshakeTimeout(0)` means "no deadline", so an honest zero would have disarmed the deadline when a replacement buffer adopted it. `adoptHandshakeDeadlineFrom` transfers the budget and the stopwatch directly instead, which removes the overloading, and `handshakeMillisecondsLeft` with it. `test_trickled_first_bytes_are_disconnected` covers the raw loop, against a node with a 1 s budget: the loop reads at most 36 bytes, so outlasting a budget needs a small one, with bytes arriving faster than the floor on the read window.
`adoptHandshakeDeadlineFrom` sampled the replacement socket for the timeouts to restore later, but that socket is already clamped to the handshake window when the swap happens. On the PostgreSQL SSL path the listener leaves the socket without a receive timeout, so the baseline should be "wait forever"; instead the clamp was recorded, and `clearHandshakeTimeout` then left an authenticated TLS session with a few seconds of receive timeout. MySQL escaped it only because it resets the secure socket from the settings first. The baseline belongs to the phase rather than to whichever socket is current, so take it from the buffer being replaced. `test_postgresql_session_outlives_the_handshake_budget` authenticates over TLS, idles for twice the budget and then queries, which the clamped timeout fails.
…ption The PostgreSQL startup phase is armed with the same deadline, but the description named only the native and MySQL protocols. It is exposed through `system.server_settings` and the generated docs.
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes connection-setup code: the TLS handshake, MySQL and PostgreSQL handshake deadlines, and the HTTP header-read deadline. That code runs once per connection or request and not during query execution, so none of the three flagged ClickBench rows can be attributed to the PR. The Q23 improvement (-46.8%) is downgraded to not sure. The PR's 50 ms falls inside master's current range of 48 to 87 ms, while the 94 ms baseline sits above that range, so the old baseline is the likely cause of the gap. The envelope decisions for Q31 (+10.7%) and Q33 (-5.9%) match the data, since both PR medians fall inside master's current range and CPU time is flat. clickbenchFlagged queries (2 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
|
# Conflicts: # base/poco/NetSSL_OpenSSL/include/Poco/Net/SecureSocketImpl.h # base/poco/NetSSL_OpenSSL/src/SecureSocketImpl.cpp
`HTTPServerConnection` maps `Poco::Net::MessageException` to `400 Bad Request`. A handshake deadline raises `DB::NetException`, which reaches only the generic `Poco::Exception` handler, so the connection was torn down with no response. Translate the timeout back, and clear the handshake clamp while unwinding so the response is written with the restored send timeout rather than the 100 ms floor.
`ReadBufferFromPocoSocket` and `WriteBufferFromPocoSocket` dropped the `Poco::TimeoutException` message, so a TLS negotiation that ran out of budget logged the same line as a stalled read. Keep the message when there is one, and label the handshake in `completeHandshakeImpl` - `mustRetry` raises the common case and is shared with ordinary reads and writes, so it cannot say this itself.
`acceptSSL` defers the handshake to the first read, and `sendBytes` re-runs it while `_needHandshake` holds. So translating a TLS negotiation timeout into `MessageException` made `sendErrorResponse` start a second handshake, on the body timeouts the scope guard had just restored - 300 seconds by default against a 3 second `http_headers_read_timeout`. Translate only when the handshake is done; otherwise let the timeout close the connection.
| DECLARE(UInt64, tcp_close_connection_after_queries_num, 0, R"(Maximum number of queries allowed per TCP connection before the connection is closed. Set to 0 for unlimited queries.)", 0) \ | ||
| DECLARE(UInt64, tcp_close_connection_after_queries_seconds, 0, R"(Maximum lifetime of a TCP connection in seconds before it is closed. Set to 0 for unlimited connection lifetime.)", 0) \ | ||
| DECLARE(UInt64, handshake_timeout_milliseconds, 30000, R"(Wall-clock timeout in milliseconds for the entire TCP handshake phase (Hello + Addendum). Limits how long an unauthenticated connection can hold a thread. Set to 0 to disable.)", 0) \ | ||
| DECLARE(UInt64, handshake_timeout_milliseconds, 30000, R"(Wall-clock timeout in milliseconds for the entire handshake phase of a native protocol (Hello and Addendum), MySQL or PostgreSQL connection, including the TLS negotiation. Limits how long an unauthenticated connection can hold a thread: the deadline is checked on every read, and the socket receive timeout is clamped to it, so a client that sends nothing cannot outlast the budget either. That clamp keeps a floor of 100 milliseconds, so a small value overdraws the budget slightly rather than cutting reads too short. Set to 0 to disable.)", 0) \ |
There was a problem hiding this comment.
handshake_timeout_milliseconds is still bypassable on supported composable proxy1 endpoints. The protocol stack can start with proxy1 (programs/server/Server.cpp:4039), but ProxyV1Handler::run immediately resets the socket back to plain receive_timeout and then parses the PROXY header with raw socket().receiveBytes(&ch, 1) reads (src/Server/ProxyV1Handler.cpp:24-94).
That means a client that drip-feeds the PROXY header can still hold a worker for roughly receive_timeout on proxy1 -> tcp/http/mysql/postgres ports. On tls -> proxy1 -> ... ports it is worse: that first raw read is also where SecureSocketImpl performs the lazy TLS handshake, so the new wall-clock handshake budget is never armed there either. This breaks the contract this setting description now claims for supported protocol stacks.
Could we arm the same deadline in ProxyV1Handler before it starts reading, and either re-apply it per raw read or route the PROXY header through ReadBufferFromPocoSocket? A focused integration test for a slow proxy1 header would keep this from regressing again.
The `catch` in `~HandshakeDriver` cannot rethrow: it is a destructor, and it usually runs while the handshake exception is unwinding. Log the swallowed exception instead of dropping it silently.
# Conflicts: # base/poco/NetSSL_OpenSSL/include/Poco/Net/SecureSocketImpl.h
Silk fiber sockets report blocking but reject `setBlocking(false)`, so driving the handshake aborted `unit_tests_dbms` before it could write its results. Ask the socket first, through a new `SocketImpl::supportsNonBlocking`, and leave such a socket alone - it does its own waiting.
The test runs with `max_threads = 1`. In the `remote('127.0.0.{1,2}', ...)` query the only thread aggregates the
local shard and does not resume the `RemoteSource` that finishes the handshake with `127.0.0.2`. Since
ClickHouse#121547 the server enforces `handshake_timeout_milliseconds` (30 s),
so on slow builds it closes the connection and the query fails with `Broken pipe` (`NETWORK_ERROR`). It failed this
way 11 times on master in TSan jobs on 2026-10-15 and in
ClickHouse/clickhouse-private#81566.
Use `prefer_localhost_replica = 0` for this query, so both shards are remote and nothing heavy runs on the thread
before the handshakes finish.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
handshake_timeout_millisecondspromises a bound on how long an unauthenticated connection can hold athread. It did not hold: the deadline was checked only at the top of
ReadBufferFromPocoSocketBase::nextImpl, so it could fire only on a read the peer itself unblocked. Apeer that sent two bytes and then stopped waited out
receive_timeout, 300 s by default.While a deadline is armed, the socket receive timeout is now held at the time left before it,
re-applied per read so that a byte sent just before each timeout cannot restart the timer. The last
window keeps a floor of 100 ms so that bytes which are merely late still land; that is the only
overdraft.
clearHandshakeTimeoutrestores the timeout the socket had.TLS. On a blocking socket OpenSSL reads inside its own state machine -
SSL_do_handshakeloopsover
BIO_readuntil it has a whole record - so onlySO_RCVTIMEOapplied, per read, and a peerdribbling a byte held a handshake open indefinitely (measured: 23 s against a 3 s budget).
completeHandshakeImplnow drives the handshake non-blocking, so OpenSSL yields and the poll thatwaits for the peer is charged against the budget. Same drip-feed after the change: 3.009 s. That is in
base/poco/NetSSL_OpenSSLand therefore applies to every TLS connection the server accepts.Coverage.
TCPHandlerneeded no change and gains the bound for the Hello, the Addendum and thePROXY header.
MySQLHandlerhad none and now arms it, including the raw pre-SSL reads that bypass thebuffer. HTTP header parsing moves onto the same mechanism, which deletes
DeadlineReadBuffer.PostgreSQLHandlerhad none either, and its listener passes a zero receive timeout, so a silent peerthere held a thread with no bound at all - measured still open after 40 s where MySQL on the same
server closed at 3 s.
Tests:
test_mysql_handshake_timeoutcovers a trickled handshake, silence after a packet header,silence before any byte, a trickled TLS
ClientHello,receive_timeoutset below the budget, and asilent PostgreSQL client;
test_tcp_hello_string_limitsgains the native silent case. Each assertsthe server-side timeout in the log rather than inferring it from elapsed time.
Related: #103284
Closes: #121601
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
handshake_timeout_millisecondsnot bounding a connection that stops sending during thehandshake, which held a thread for
receive_timeout(300 seconds by default) instead. The setting nowalso covers the MySQL and PostgreSQL handshake phases and the TLS negotiation; previously a peer that
dribbled bytes during a TLS handshake, or stayed silent on the PostgreSQL port, could hold a thread
indefinitely. HTTP header reading keeps its own
http_headers_read_timeoutbudget, now enforced bythe same mechanism.
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/121547]
Version info
26.10.1.1020-master(included in26.10and later)