Skip to content

Enforce handshake_timeout_milliseconds across the handshake paths - #121547

Merged
CheSema merged 22 commits into
masterfrom
bound-handshake-phase
Sep 29, 2026
Merged

CheSema merged 22 commits into
masterfrom
bound-handshake-phase

Conversation

@CheSema

@CheSema CheSema commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

handshake_timeout_milliseconds promises a bound on how long an unauthenticated connection can hold a
thread. 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. A
peer 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. clearHandshakeTimeout restores the timeout the socket had.

TLS. 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, per read, and a peer
dribbling a byte held a handshake open indefinitely (measured: 23 s against a 3 s budget).
completeHandshakeImpl now drives the handshake non-blocking, so OpenSSL yields and the poll that
waits for the peer is charged against the budget. Same drip-feed after the change: 3.009 s. That is in
base/poco/NetSSL_OpenSSL and therefore applies to every TLS connection the server accepts.

Coverage. TCPHandler needed no change and gains the bound for the Hello, the Addendum and the
PROXY header. MySQLHandler had none and now arms it, including the raw pre-SSL reads that bypass the
buffer. HTTP header parsing moves onto the same mechanism, which deletes DeadlineReadBuffer.
PostgreSQLHandler had none either, and its listener passes a zero receive timeout, so a silent peer
there 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_timeout covers a trickled handshake, silence after a packet header,
silence before any byte, a trickled TLS ClientHello, receive_timeout set below the budget, and a
silent PostgreSQL client; test_tcp_hello_string_limits gains the native silent case. Each asserts
the server-side timeout in the log rather than inferring it from elapsed time.

Related: #103284
Closes: #121601

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed handshake_timeout_milliseconds not bounding a connection that stops sending during the
handshake, which held a thread for receive_timeout (300 seconds by default) instead. The setting now
also 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_timeout budget, now enforced by
the same mechanism.

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/121547]

Version info

  • Merged into: 26.10.1.1020-master (included in 26.10 and later)

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

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bac7695]

Summary: ✅


AI Review

Summary

This PR tightens handshake_timeout_milliseconds across the native, MySQL, PostgreSQL, HTTP-header, and TLS handshake paths, and the current code fixes the earlier issues raised on those paths. One blocker remains, though: supported composable proxy1 protocol stacks still parse the PROXY header outside the new deadline machinery, so a slow client can still hold a worker for receive_timeout instead of the configured handshake budget.

Findings

❌ Blockers

  • [programs/server/Server.cpp:4115-4184, src/Server/ProxyV1Handler.cpp:24-108] The PR's contract is that the handshake budget now covers the whole unauthenticated connection setup, but composable proxy1 endpoints still bypass it. buildProtocolStackFromConfig allows proxy1 in front of tcp, http, mysql, postgres, and even under tls, yet ProxyV1Handler::run immediately restores the plain receive_timeout and then parses the PROXY header one byte at a time with raw socket().receiveBytes. That means a client can still trickle the PROXY header and pin a worker for roughly receive_timeout on every proxy1 -> ... endpoint, and on tls -> proxy1 -> ... stacks the first read also triggers the lazy TLS handshake before any deadline is armed. Suggested fix: arm the same handshake deadline in ProxyV1Handler and either read the header through ReadBufferFromPocoSocket or re-apply applyHandshakeDeadlineToSocket before each raw read, then add a focused integration test for a slow proxy1 header.
Final Verdict

Changes requested.

LLVM Coverage Report

⚠️ No coverage measurement for commit bac7695: incomplete coverage measurement: 1 of 21 shard profiles are missing: LLVM_COVERAGE_FILE_it_7.profdata.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 22, 2026
Comment thread src/Server/MySQLHandler.cpp Resolved
`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.
Comment thread src/Server/MySQLHandler.cpp Resolved
Comment thread src/Server/MySQLHandler.cpp Resolved
`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.
Comment thread src/Server/MySQLHandler.cpp Resolved
Comment thread src/Core/ServerSettings.cpp Resolved
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.
Comment thread src/Server/MySQLHandler.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 22, 2026
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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bac7695c3 with master 13d023155 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

399 translation units recompiled, 2554 s compile time in total, 399 of them have a recent master baseline.

Job report

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.
@CheSema CheSema changed the title Enforce handshake_timeout_milliseconds while a read blocks, and bound the MySQL handshake Enforce handshake_timeout_milliseconds across the handshake paths Sep 23, 2026
@Michicosun Michicosun self-assigned this Sep 23, 2026
`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.
Comment thread src/IO/ReadBufferFromPocoSocket.cpp Resolved
`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.
Comment thread src/Core/ServerSettings.cpp Resolved
Comment thread src/Server/HTTP/HTTPServerRequest.cpp Resolved
…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.
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 94 50 -46.8% <0.0001 This PR only changes handshake and header-read timeouts, so it cannot make this SELECT -46.8% faster. The PR's 50 ms falls inside master's current range of 48 to 87 ms, while the 94 ms baseline sits above it.
⚠️ 31 not_sure 270 299 +10.7% <0.0001 The +10.7% delta is inside master's current range, and CPU time is flat. The changed handshake-timeout code does not run during query execution.

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: 7abf2dea-ab95-47fe-be56-ff5c0f17d0d1
  • MIRAI run: 01eaecb6-401b-4458-9ede-70bf8de9c866
  • PR check IDs:
    • clickbench_2370953_1790682574
    • clickbench_2370959_1790682574
    • clickbench_2370965_1790682574
    • tpch_adapted_1_official_2370971_1790682574
    • tpch_adapted_1_official_2370977_1790682574
    • tpch_adapted_1_official_2371024_1790682574

# Conflicts:
#	base/poco/NetSSL_OpenSSL/include/Poco/Net/SecureSocketImpl.h
#	base/poco/NetSSL_OpenSSL/src/SecureSocketImpl.cpp
Comment thread src/Server/HTTP/HTTPServerRequest.cpp Resolved
`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.
Comment thread src/Server/HTTP/HTTPServerRequest.cpp Resolved
`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) \

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.

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.

Comment thread src/IO/ReadBufferFromPocoSocket.h Resolved
Comment thread src/Server/MySQLHandler.cpp Resolved
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.
@CheSema
CheSema added this pull request to the merge queue Sep 29, 2026
Merged via the queue into master with commit 505c5c0 Sep 29, 2026
149 checks passed
@CheSema
CheSema deleted the bound-handshake-phase branch September 29, 2026 16:39
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 29, 2026
alexey-milovidov added a commit to soda4fries/ClickHouse that referenced this pull request Oct 17, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-bugfix Pull request with bugfix, not backported by default 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.

MySQL TLS negotiation is not bounded by handshake_timeout_milliseconds

3 participants