Skip to content

Do not wait for the peer in TLS shutdown when a write is still pending - #122222

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-tls-shutdown-pending-write-stall
Sep 26, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-tls-shutdown-pending-write-stall

Conversation

@groeneai

@groeneai groeneai commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122108
Related: #116692

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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) inside SecureSocketImpl::shutdown(), then threw Poco::TimeoutException.
Measured on INSERT INTO FUNCTION url('https://...') against a peer that stops reading, with
http_send_timeout=1, http_receive_timeout=9: 27.3 s before, 18.3 s after, exactly one
max(send, receive) removed from socket teardown. The consequence is latency: all five direct
shutdown() callers in src/ already catch Poco::TimeoutException.

Root cause: an abandoned SSL_write leaves the OpenSSL record layer with a pending record write,
and ssl3_send_alert refuses to dispatch close_notify while RECORD_LAYER_write_pending() is
true, so it does no I/O and SSL_get_error reports whatever the stale rwstate says. Every
SSL_shutdown retry in that state is a no-op, yet the retry loop added in #116692 still waited a
fresh max(send, receive) on the socket before giving up.

The fix tracks the pending write where it is created: sendBytes sets a flag when SSL_write
returns SSL_ERROR_WANT_WRITE and clears it when a write completes, and shutdown() does not
retry while it is set, calling SSL_shutdown once, as before #116692. SSL_want_write() is not
enough, because any later read replaces rwstate: a timed-out receiveBytes in between turned the
stall into a SELECT_READ poll. SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite,
which pins the backpressure retry, passes unchanged.

Validation: two gtests in the existing src/Common/tests/gtest_ssl_send_timeout.cpp, with and
without a timed-out read before the close, fail without the flag with elapsed 10009 ms and
Poco::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-backport and v26.8-must-backport labels.


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

Version info

  • Merged into: 26.10.1.722-master (included in 26.10 and later)
  • Backported to: 26.8.12.53, 26.3.35.6

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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold
re-review of the resulting tree (1 finding). Bounded: 1 full pass + 1 fix round + 1 delta recheck.

# Sev Finding Verdict Evidence / action
1 💡 The description claimed without qualification that SSL_want_write() implies a pending record write, but statem_flush (ssl/statem/statem.c:945) can leave rwstate == SSL_WRITING with wpend_tot == 0 AGREE, fixed in the description Narrowed to the abandoned-write path, where rec_layer_s3.c:446/:467 and :497 co-assign the two. The unqualified case arises only under SSL_in_init, where SSL_shutdown returns after SSL_R_SHUTDOWN_WHILE_IN_INIT and mustRetry returns false with or without the guard, so the conclusion itself was unaffected

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Also checked cold, by reading source rather than trusting the author's evidence: the root cause
re-derived from contrib/openssl 3.5.8 (ssl/s3_msg.c:68, and the "API misuse?? Give up" arm at
:107-116 that makes the second SSL_shutdown a no-op); all five socket shutdown() call sites in
src/ do catch Poco::TimeoutException; the preserved backpressure retry has a non-vacuous control
in SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite; and the new test carries two
independent red-makers plus an anti-degenerate SSL_SENT_SHUTDOWN check.

Session id: cron:clickhouse-review-slot-8:20260925-110900

@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a3e331b]

Summary: ✅


AI Review

Summary

This PR fixes the extra shutdown() wait introduced by #116692 when a timed-out SSL_write leaves an OpenSSL record write pending, and it adds focused regression tests for both the direct timeout case and the timeout-then-read sequence raised in discussion. I reviewed the current diff and prior discussion and did not find a remaining correctness, compatibility, or coverage issue in the current code.

Final Verdict

✅ No findings.

LLVM Coverage Report

⚠️ No coverage measurement for commit a3e331b: no coverage data for the changed C/C++ source files (they may be new or not instrumented).

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter="SSLSocketTimeout.ShutdownAfterSendTimeoutDoesNotWaitForPeer" fails 100% of runs without the guard: elapsed_ms = 10009 and Poco::TimeoutException. Also reproduced from SQL, 3 runs per arm, against a peer that stops reading.
b Root cause explained? Yes. An abandoned SSL_write leaves the record layer with a pending record write; ssl3_send_alert refuses to dispatch close_notify while RECORD_LAYER_write_pending() is true, so it does no I/O and reports SSL_ERROR_WANT_WRITE off the stale rwstate. Every SSL_shutdown retry is therefore a no-op.
c Fix matches root cause? Yes. It suppresses a retry OpenSSL cannot honour, at the only site whose operation cannot make progress. No widened bound, no reduced dataset, no no-random-* tag, no try/catch at a call site, no new setting.
d Test intent preserved / new tests added? Yes. One new gtest in the existing src/Common/tests/gtest_ssl_send_timeout.cpp; no new file and no CMake change. No existing test weakened, renamed or refactored. SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite, which pins the retry being preserved, is untouched and green.
e Both directions demonstrated? Yes. Without the guard: FAILED (10717 ms), elapsed 10009 vs 2000, Poco::TimeoutException. With it: OK (510 ms). Build IDs differ between the two binaries. SQL arm: 27.3 s before, 18.3 s after.
f Fix is general across code paths? Yes. SSL_shutdown has exactly one production call site in the tree (SecureSocketImpl.cpp:398), so there is no sibling implementation to fix. close(), reset() and ~SecureSocketImpl reach it and inherit the fix; abort() bypasses TLS. The other three mustRetry loops are deliberately unchanged: there a pending write is exactly the reason to retry.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. No column-type surface, so no Nullable/LowCardinality/Const matrix applies. Axes covered: blocking socket (the defect, fixed and tested); non-blocking socket (mustRetry already returns false for WANT_WRITE there, so the guard is a no-op); the Silk fiber subclass (green); both sendBytes timeout exits, :459 and :706, both observed; _fatalError already set (earlier return); SSL_SENT_SHUTDOWN already set (existing short circuit); zero timeouts (getMaxTimeoutOrLimit remapping, unchanged).
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or changed, so no SettingsChangesHistory.cpp entry; no header, ABI, format or serialization change; no experimental flag. The behaviour moves back toward what 26.3, 26.7, 26.8 and 26.9 do today.
i Invariants and contracts preserved? Yes. SSL_shutdown is still called at least once and SSL_SENT_SHUTDOWN is still set, asserted by the new test, so a later shutdown() still short-circuits. handleError is still invoked on rc < 0 and still returns ERR_SSL_WANT_WRITE without setting _fatalError; _pSocket->shutdown() still runs for a blocking socket; the mutex scope and the remaining-time accounting are untouched.

Session id: cron:clickhouse-impl-slot-6:20260925-102600

@groeneai
groeneai requested review from CheSema, mstetsyuk and thevar1able and removed request for CheSema September 25, 2026 11:49
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @otselnik, could you take a look? This guards the SSL_shutdown retry loop from #116692 with SSL_want_write(), because OpenSSL will not dispatch close_notify while a record write from an abandoned SSL_write is still pending, so in that state the retry cannot make progress and spent a full max(send, receive) polling for writability; the backpressure retry itself is preserved, and SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite passes unchanged.

@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 25, 2026
@thevar1able thevar1able self-assigned this Sep 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a3e331b9b with master fb2810634 (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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4af7842

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 4/6) / formats_columns_nullable #1 dashboard confirmed_regression, client_time 0.0092 -> 0.0154 (+65.7%). The fixture reads File(<format>) tables, and the performance harness connects without TLS (perf.py --secure is not passed in CI), so the TLS shutdown path this PR changes is never entered. CIDB flags this query slower or unstable on unrelated PRs and on master throughout the last three days ClickHouse/performance-comparison#5 (external, open): the dashboard's confidence scoring, where @ fm4v handles these verdicts after #121847. That repository is not publicly readable, so its state cannot be measured from here
Performance Comparison (arm_release, master_head, 6/6) / read_in_reverse_order_final #0, #1 dashboard confirmed_regression, client_time +40.6% and +23.9%. On master these two FINAL queries went from 2-3 ms to 8-9 ms on both servers at the merge commit of #122073 (302e001eeb33), which stopped background merges during the measured runs, and since then they are flagged on unrelated PRs across several shards. No TLS connection is involved here either a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR rollup rows, red only because of the two shards above ClickHouse/performance-comparison#5 (external, open) and a fix task is created, the same owners as the two rows above

All 173 check runs completed (146 pass, 25 not selected, 2 red), Finish Workflow is green and
CH Inc sync passed on this head.

Session id: cron:our-pr-ci-monitor:20260925-182007

@otselnik

Copy link
Copy Markdown
Contributor

@groeneai, could you please check one additional sequence?
SSL_want_write reflects the current rwstate, not whether RECORD_LAYER::wpend_tot is still non-zero. After a timed-out SSL_write leaves a record pending, a subsequent SSL_read can change rwstate to SSL_READING without clearing that pending write. Then has_pending_write is false, and SSL_shutdown may enter mustRetry and wait for the full receive timeout.
Could you extend the test with a receiveBytes timeout between the send timeout and shutdown? If this reproduces, SecureSocketImpl may need to track an unfinished write explicitly instead of relying on SSL_want_write.

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Thanks, it reproduces. After a timed-out receiveBytes, SSL_want_write() is false (ssl3_read_bytes resets rwstate and sets SSL_READING on the retry, wpend_tot is untouched), so shutdown() retried and waited the full 10 s budget in poll(POLLIN), then threw Poco::TimeoutException.

Fixed in a3e331b9b608c as you suggested: sendBytes sets _pendingWrite when SSL_write returns SSL_ERROR_WANT_WRITE and clears it when a write completes, and shutdown() does not retry while it is set. The test now runs with and without the timed-out read. Without the flag both cases fail with elapsed 10009 ms (in poll(POLLOUT) and poll(POLLIN) respectively); with it both pass in under 1 s, and SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite still passes. I updated the description.

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 v26.3-must-backport and v26.8-must-backport labels as #116692.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the read_in_reverse_order_final Performance Comparison rows created: #122335

@clickhouse-gh clickhouse-gh Bot added comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. and removed comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... labels Sep 25, 2026
pull Bot pushed a commit to Lobinson1/ClickHouse that referenced this pull request Sep 26, 2026
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]>
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into ClickHouse:master with commit 846c162 Sep 26, 2026
177 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 26, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 26, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 26, 2026
Backport #122222 to 26.8: Do not wait for the peer in TLS shutdown when a write is still pending
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 26, 2026
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]>
PedroTadim added a commit that referenced this pull request Sep 28, 2026
Backport #122222 to 26.3: Do not wait for the peer in TLS shutdown when a write is still pending
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 29, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SecureSocketImpl::shutdown blocks a full timeout after a TLS send timeout

7 participants