Repository navigation
Do not wait for the peer in TLS shutdown when a write is still pending - #122222
alexey-milovidov merged 2 commits into
Conversation
Closing a TLS socket whose last write timed out blocked for another
max(send_timeout, receive_timeout) inside SecureSocketImpl::shutdown() and then
threw Poco::TimeoutException. Measured on an INSERT INTO FUNCTION
url('https://...') against a peer that accepts, handshakes and never reads, with
http_send_timeout=1 and http_receive_timeout=9: 27.3 s before this change,
18.3 s after, i.e. exactly one max(send, receive) removed from socket teardown,
and the delta scales with that setting (7.4 s -> 5.6 s at receive_timeout=2).
Every direct shutdown() caller reachable from src/ already catches
Poco::TimeoutException, so the consequence is latency rather than a new escaping
exception.
An abandoned SSL_write leaves the OpenSSL record layer with wpend_tot > 0 and
rwstate == SSL_WRITING (contrib/openssl/ssl/record/rec_layer_s3.c:497), and
neither sendBytes timeout exit sets _fatalError, so shutdown() enters its retry
loop with a fresh getMaxTimeoutOrLimit() budget. There, ssl3_send_alert refuses
to dispatch close_notify while RECORD_LAYER_write_pending() is true
(contrib/openssl/ssl/s3_msg.c:68) and returns without performing any I/O, so
SSL_get_error reports SSL_ERROR_WANT_WRITE off the stale rwstate and Poco polls
SELECT_WRITE against a peer whose TCP window is zero until the budget is gone.
Retrying in that state can never succeed. A second SSL_shutdown reaches
ssl3_dispatch_alert, whose pending-write arm only retries when alert_dispatch is
SSL_ALERT_DISPATCH_RETRY; it is SSL_ALERT_DISPATCH_PENDING here, so it takes the
"API misuse?? Give up" branch (s3_msg.c:107-116). Only re-calling SSL_write with
the identical buffer could flush the pending record, and Poco has already
discarded it. A third call would fall into ssl_read_bytes and wait for the peer's
close_notify, the wait the comment above this block says Poco deliberately
avoids.
SSL_want_write() is the public spelling of rwstate == SSL_WRITING, and rwstate is
only set to SSL_WRITING on the same ossl_tls_handle_rlayer_return retry path that
assigns wpend_tot, so the predicate implies a pending record write and cannot
disable a retry that could have worked. The backpressure retry is preserved:
SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite still asserts two
SSL_shutdown writes and a close_notify observed by the peer. Everything after the
loop is unchanged, so handleError still returns ERR_SSL_WANT_WRITE without
setting _fatalError and the transport is still shut down. That is the observable
behaviour of 26.3, 26.7, 26.8 and 26.9, none of which carry the retry loop.
The loop condition dates from 001fb05 (ClickHouse#116692, merged 2026-09-24), so no
released version is affected and no changelog entry is required. That PR's
backports ClickHouse#122201 (26.3) and ClickHouse#122197 (26.8) are still open and would import the
regression.
A successful read before the close resets rwstate while wpend_tot stays positive,
so the stall persists in that narrower shape. The exact predicate,
RECORD_LAYER_write_pending(), is declared in the private header
ssl/record/record.h and is not reachable from base/poco.
The new test goes in the existing src/Common/tests/gtest_ssl_send_timeout.cpp,
whose SSLSocketTimeout suite already builds the precondition: a never-reading TLS
peer and a sendBytes that throws. It requires that timeout first, then times
shutdown() with the receive timeout raised to 10 s, and also asserts that
SSL_SENT_SHUTDOWN is set so that skipping the orderly shutdown altogether cannot
pass. Without the guard it fails with elapsed 10009 ms and Poco::TimeoutException;
with it the whole test takes 0.5 s. All 38 TLS and socket unit tests pass, 50x
repeated.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold
Severity: ❌ blocker / Also checked cold, by reading source rather than trusting the author's evidence: the root cause Session id: cron:clickhouse-review-slot-8:20260925-110900 |
|
Workflow [PR], commit [a3e331b] Summary: ✅
AI ReviewSummaryThis PR fixes the extra Final Verdict✅ No findings. LLVM Coverage Report |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-6:20260925-102600 |
|
cc @otselnik, could you take a look? This guards the |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units17 translation units recompiled, 34 s compile time in total, 17 of them have a recent master baseline. |
CI finish ledger - 4af7842Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 173 check runs completed (146 pass, 25 not selected, 2 red), Session id: cron:our-pr-ci-monitor:20260925-182007 |
|
@groeneai, could you please check one additional sequence? |
SSL_want_write() reads rwstate, which the next SSL_read overwrites. When a read times out after a timed-out SSL_write, ssl3_read_bytes resets rwstate at start: and the retry path of ossl_tls_handle_rlayer_return sets it to SSL_READING (contrib/openssl/ssl/record/rec_layer_s3.c:683, :497), while wpend_tot stays positive. The guard in shutdown() then saw no pending write, the first SSL_shutdown queued close_notify behind the pending record without doing any I/O, SSL_get_error reported SSL_ERROR_WANT_READ off the stale state, and mustRetry polled SELECT_READ for a fresh max(send, receive) before throwing Poco::TimeoutException. Any other read in between does the same, e.g. the SSL_peek probe in src/IO/SocketPeerClosed.cpp. Record the state where it is created instead. sendBytes sets _pendingWrite when SSL_write returns SSL_ERROR_WANT_WRITE, which leaves its record pending, and clears it when SSL_write completes; acceptSSL and connectSSL reset it together with the new SSL object. shutdown() does not retry while it is set: only a retried SSL_write flushes that record, so the retry could never make progress. The new SSLSocketTimeout.ShutdownAfterSendAndReceiveTimeoutsDoesNotWaitForPeer adds a timed-out receiveBytes between the send timeout and shutdown(), and asserts that SSL_want_write() is false at that point. With the previous guard it fails with elapsed 10009 ms and Poco::TimeoutException; now it takes 0.7 s. Removing the assignment in sendBytes makes both shutdown tests fail the same way. All 39 TLS, socket and Silk fiber unit tests pass, including SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite, which pins the backpressure retry from ClickHouse#116692; the shutdown tests passed 40x repeated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, it reproduces. After a timed-out Fixed in a3e331b9b608c as you suggested: Separately: #122197 (26.8) and #122201 (26.3) merged today, so both branches now carry the retry loop without this fix; this PR needs the same |
|
Fixing PR for the |
Since ClickHouse#122073 the measured perf.py runs stop merges on both servers right after the fill. The old fill writes 54 parts in about a second, so each server keeps whatever part set its background merges reached, and the two servers of one run measure different layouts (21 vs 38 parts on ClickHouse#122222, 24 vs 44 on ClickHouse#122154, 22 vs 44 on master 52a67f8). FINAL ... ORDER BY x DESC LIMIT n reads the first reverse ranges of every part (about 23K rows each), so its time grows with the part count, and the dashboard scores the side with more parts as a confirmed regression. The fill now merges the first insert, stops merges on the table and writes the second insert as exactly one part, so both servers read the same two parts whatever the merge timing, like final_read_in_order_limit.xml: - OPTIMIZE ... FINAL waits for the running merges before it selects, so the background merges of the first insert cannot leave it partial, and optimize_throw_if_noop = 1 makes a no-op OPTIMIZE fail with its reason instead of surfacing as a wrong part count. - min_insert_block_size_rows = 16777216 (2^24, above the 10M rows) with min_insert_block_size_bytes = 0: the INSERT squashes on one stream before it fans out to the sinks and never reaches the minimum, so the whole insert is flushed as one part, independent of max_insert_threads, max_block_size and how the numbers_mt threads interleave. - The throwIf over system.parts fails the job unless exactly 2 parts are active, because SYSTEM STOP MERGES on a missing table is a silent no-op. Validated on two servers of one master release build with perf.py --stop-merges, 5 runs per side of the change: before, 14 to 19 parts, different on the two servers in every run, right/left up to 1.18; after, 2 parts and identical SelectedRows on both servers, right/left within 3%. Related: ClickHouse#122073 Related: ClickHouse#121937 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…en a write is still pending
Backport #122222 to 26.8: Do not wait for the peer in TLS shutdown when a write is still pending
The backport of ClickHouse#122222 does not compile `unit_tests_dbms` on 26.3: the new tests call `EphemeralCert::makeContext` and `SecureStreamSocketImpl::ssl()`, which 26.3 does not have (`gtest_ephemeral_certificate.h` and fc01109 are not on this branch). Use the file's own `makeContext(cert, usage)` helper, and drop the three checks that read the `SSL` object (the non-null check, the `SSL_want_write` precondition and the `SSL_SENT_SHUTDOWN` check), because 26.3 has no accessor for it. The two checks that fail without the Poco change, `shutdown()` not throwing and returning within 2 s, are unchanged, and so is the Poco part of the backport. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Backport #122222 to 26.3: Do not wait for the peer in TLS shutdown when a write is still pending
…hutdown when a write is still pending
Closes: #122108
Related: #116692
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Unreleased regression from #116692, not present in any release, no changelog entry required.
Description
Closing a TLS socket whose last write timed out blocked for another
max(send_timeout, receive_timeout)insideSecureSocketImpl::shutdown(), then threwPoco::TimeoutException.Measured on
INSERT INTO FUNCTION url('https://...')against a peer that stops reading, withhttp_send_timeout=1, http_receive_timeout=9: 27.3 s before, 18.3 s after, exactly onemax(send, receive)removed from socket teardown. The consequence is latency: all five directshutdown()callers insrc/already catchPoco::TimeoutException.Root cause: an abandoned
SSL_writeleaves the OpenSSL record layer with a pending record write,and
ssl3_send_alertrefuses to dispatchclose_notifywhileRECORD_LAYER_write_pending()istrue, so it does no I/O and
SSL_get_errorreports whatever the stalerwstatesays. EverySSL_shutdownretry in that state is a no-op, yet the retry loop added in #116692 still waited afresh
max(send, receive)on the socket before giving up.The fix tracks the pending write where it is created:
sendBytessets a flag whenSSL_writereturns
SSL_ERROR_WANT_WRITEand clears it when a write completes, andshutdown()does notretry while it is set, calling
SSL_shutdownonce, as before #116692.SSL_want_write()is notenough, because any later read replaces
rwstate: a timed-outreceiveBytesin between turned thestall into a
SELECT_READpoll.SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite,which pins the backpressure retry, passes unchanged.
Validation: two gtests in the existing
src/Common/tests/gtest_ssl_send_timeout.cpp, with andwithout a timed-out read before the close, fail without the flag with
elapsed 10009 msandPoco::TimeoutException, and pass in under 1 s. All 39 TLS, socket and Silk fiber unit tests pass.A gtest, not a stateless test: the trigger is a TLS peer that handshakes then never reads, and the
oracle is client-side teardown latency.
Scheduling note: #116692's backports #122201 (26.3) and #122197 (26.8) merged on 2026-09-25, so
both branches carry the retry loop (no release tag contains it yet); this fix needs the same
v26.3-must-backportandv26.8-must-backportlabels.Workflow [PR]
Sync PR [sync-upstream/pr/122222]
Version info
26.10.1.722-master(included in26.10and later)26.8.12.53,26.3.35.6