Skip to content

Prevent stale OpenSSL errors from breaking asynchronous TLS connections - #116692

Merged
thevar1able merged 20 commits into
ClickHouse:masterfrom
otselnik:fix-mdbextsupport-3916-openssl-error-queue
Sep 24, 2026
Merged

thevar1able merged 20 commits into
ClickHouse:masterfrom
otselnik:fix-mdbextsupport-3916-openssl-error-queue

Conversation

@otselnik

@otselnik otselnik commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

OpenSSL keeps its error queue in thread-local storage rather than in an individual SSL object. The SSL_get_error contract therefore requires the queue to be empty before TLS I/O, and the corresponding SSL_get_error call to run immediately afterwards on the same OS thread without intervening OpenSSL calls.

SecureSocketImpl did not clear the error queue before its TLS operations and evaluated SSL_get_error more than once for the same result. An error left while handling or shutting down one connection could consequently be interpreted as the result of an operation on another connection later using the same OS thread. This could surface as a misleading TLS exception and terminate a distributed query even though the reported peer connection was operating normally.

The Silk TLS BIO made this more likely because it could suspend a fiber from inside SSL_read or SSL_write. A suspended fiber may resume on another OS thread before OpenSSL finishes the operation and its result is classified.

Implementation

A common TLS operation wrapper now:

  • clears the current thread's OpenSSL error queue before every operation and retry;
  • saves errno immediately after the operation;
  • calls SSL_get_error exactly once and before any other OpenSSL function;
  • preserves the OpenSSL diagnostic used to construct the exception;
  • drains remaining queue entries before returning control to another connection.

The saved values are passed to mustRetry and handleError, so neither function queries mutable thread-local state again. Retry is restricted to explicitly retriable conditions rather than being inferred from an unrelated leftover EINTR.

Connections that encounter a fatal SSL_ERROR_SSL or SSL_ERROR_SYSCALL are marked unusable. Their underlying transport is closed without calling SSL_shutdown, as required by the SSL_shutdown contract. A zero return from SSL_shutdown is handled as an incomplete orderly shutdown rather than passed to SSL_get_error.

The previous write-error workaround performed an auxiliary SSL_read after a connection reset. It has been removed because it could silently consume application data that was already buffered by OpenSSL.

Silk integration

The Silk BIO now performs only non-blocking recv and send operations. On EAGAIN, it sets the appropriate BIO retry flag and returns control to OpenSSL. SecureSocketImpl then saves the SSL_get_error result before performing a timed fiber-aware wait through pollImpl.

This keeps the complete OpenSSL operation and its error classification on one OS thread while preserving asynchronous waiting and socket timeouts.

For immediately available data, the direct syscall avoids creating an I/O future. When a socket returns EAGAIN, the new path performs an additional non-blocking syscall and OpenSSL retry around the asynchronous poll. It does not add data copies, busy waiting, or blocking of an OS thread.

Regression coverage

The added tests verify that:

  • a stale shutdown while in init error does not change the result of another TLS connection;
  • the error queue is cleared independently for every retry;
  • fatal TLS errors do not trigger SSL_shutdown;
  • a failed SSL_write does not consume pending application data;
  • direct Silk SSL_read and SSL_peek calls return retry conditions without suspending inside OpenSSL;
  • TLS-aware pooled-socket probing continues to distinguish idle, pending-data, orderly-close, partial-record, and abrupt-close states.

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 asynchronous TLS connections occasionally failing with an unrelated OpenSSL error left by another connection on the same OS thread. This could terminate distributed queries with a misleading network exception.


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

Version info

  • Merged into: 26.10.1.616-master (included in 26.10 and later)
  • Backported to: 26.9.8.8, 26.8.11.48, 26.7.23.7, 26.3.33.154

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 27, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [61ad6d8]

Summary: ✅


AI Review

Summary

This PR hardens asynchronous TLS handling around OpenSSL's thread-local error queue, retry classification, fatal-shutdown rules, and Silk/connection-pool probing. I re-checked the current head against the full diff and every prior review thread; the previously reported issues are fixed in the current code, and I did not find any remaining blockers or major correctness risks.

Tests
  • Not run locally in this checkout; there is no existing build* directory available to execute the new TLS unit tests.
Final Verdict

✅ Approve from a code-review standpoint.

LLVM Coverage Report

Measured on commit 61ad6d8.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 61/71 (85.92%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
Address `catch_all` and `arm_tidy` diagnostics in the new TLS regression tests while keeping cleanup failures visible.

ClickHouse#116692
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 61ad6d8cfb717e4ad2f22a7ceab4f1b2ea5cbdde was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

Comment thread src/IO/SocketPeerClosed.cpp Resolved
Record fatal probe failures in `SecureSocketImpl` so later `shutdown` skips the forbidden `SSL_shutdown` path.

Related: ClickHouse#116692
Clear errno before each `performSSLOperation` invocation so a stale retriable value cannot affect OpenSSL error classification.

Initialize `SSLSocketStateResult` for static analysis and add a custom `BIO` regression test for the empty error-queue path.

Related: ClickHouse#116692
@otselnik

otselnik commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

None of the current CI failures appears to be introduced by this PR:

@toddyocum

Copy link
Copy Markdown
Contributor

Heh, I just spent the last day or so debugging this exact issue, so thanks for finding (and fixing) this!

FWIW, running 26.3 with skip_unavailable_shards enabled and one of the shard's being not reachable were the conditions that would trigger it for us, it would happen maybe like 2-3% of the time of all of our query calls.

And end up with a stack trace like this

DB::Exception: SSL Exception: error:0A000197:SSL routines::shutdown while in init, while reading from socket (peer: 172.18.11.39:9500, local: 172.18.2.244:11689): while receiving packet from 172.18.11.39:9500, local address: 172.18.2.244:11689: While executing Remote. Stack trace:

0. DB::Exception::Exception(DB::Exception::MessageMasked&&, int, bool) @ 0x0000000017991cea
1. DB::Exception::Exception(String&&, int, String, bool) @ 0x000000000fbdba8e
2. DB::NetException::NetException<String, String, String>(int, FormatStringHelperImpl<std::type_identity<String>::type, std::type_identity<String>::type, std::type_identity<String>::type>, String&&, String&&, String&&) @ 0x0000000017c283be
3. DB::ReadBufferFromPocoSocketBase::socketReceiveBytesImpl(char*, unsigned long) @ 0x0000000017c2a134
4. DB::ReadBufferFromPocoSocketBase::nextImpl() @ 0x0000000017c2ab15
5. DB::ReadBuffer::next() @ 0x0000000017ad083d
6. DB::Connection::receivePacket() @ 0x000000001e747fd6
7. DB::MultiplexedConnections::receivePacketUnlocked(std::function<void (int, Poco::Timespan, DB::AsyncEventTimeoutType, String const&, unsigned int)>) @ 0x000000001e7a3ef3
8. DB::RemoteQueryExecutorReadContext::Task::run(std::function<void (int, Poco::Timespan, DB::AsyncEventTimeoutType, String const&, unsigned int)>, std::function<void ()>) @ 0x000000001b8aff86
9. void boost::context::detail::fiber_entry<boost::context::detail::fiber_record<boost::context::fiber, FiberStack&, Fiber::RoutineImpl<DB::AsyncTaskExecutor::Routine>>>(boost::context::detail::transfer_t) @ 0x000000001b8af3f0

Digging through the clickhouse traces brought us to the same conclusion you reached and summarized nicely for the changelog

Fixed asynchronous TLS connections occasionally failing with an unrelated OpenSSL error left by another connection on the same OS thread. This could terminate distributed queries with a misleading network exception.

@clickhouse-gh clickhouse-gh Bot added the comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. label Sep 4, 2026
@thevar1able thevar1able self-assigned this Sep 21, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Sep 25, 2026
Cherry pick #116692 to 26.3: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
robot-clickhouse added a commit that referenced this pull request Sep 25, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 25, 2026
Backport #116692 to 26.8: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
PedroTadim added a commit that referenced this pull request Sep 25, 2026
Backport #116692 to 26.3: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
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]>
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Sep 26, 2026
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.
@PedroTadim

Copy link
Copy Markdown
Member

@thevar1able I am confused. You merged into 26.3, but closed to 26.7? What about the other backports? Should they be done?

@thevar1able

thevar1able commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

@PedroTadim Yes, I backported to LTS only. You're right, that's not right.

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 removed the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 28, 2026
PedroTadim added a commit that referenced this pull request Oct 1, 2026
Cherry pick #116692 to 26.9: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
robot-clickhouse added a commit that referenced this pull request Oct 1, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 1, 2026
Backport #116692 to 26.9: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
thevar1able added a commit that referenced this pull request Oct 5, 2026
…sl-error-queue

Prevent stale OpenSSL errors from breaking asynchronous TLS connections
robot-clickhouse added a commit that referenced this pull request Oct 5, 2026
Cherry pick #116692 to 26.7: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
robot-clickhouse added a commit that referenced this pull request Oct 5, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 5, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 5, 2026
Backport #116692 to 26.7: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
kute1654 pushed a commit to kute1654/ClickHouse that referenced this pull request Oct 10, 2026
The strict server rejects a client that sends no certificate. Under TLS 1.3
the client finishes its handshake before the server checks the client
certificate, so it writes its native Hello right away. The server tears the
failed session down with shutdown(SHUT_RDWR) (FIN) followed by close() with
the client's Finished record still unread (RST), so the client receives
alert, FIN, RST. If its Hello write comes after both, the RST hits a socket
in CLOSE_WAIT, the kernel reports EPIPE, and the client fails with
"I/O error: Broken pipe, while writing to socket" without reading the alert.

Before the orderly shutdown for sessions that died with a fatal error
(ClickHouse#116692) the teardown was RST only, which gives ECONNRESET, the case ClickHouse#93539
already accepts. Which TCP event reaches the client first is not what the
test checks: it checks that the connection is refused. pytest.raises still
fails the test if the connection is accepted, and the message list still
excludes a client-side verification failure.

Seen twice on the 26.3 release branch (amd_tsan) after the ClickHouse#116692 backport.
Forcing a 300 ms delay on every client socket write with strace reproduces
the CI message 5/5 on 26.3.43.4 and on master, and gives "Connection reset
by peer" on 26.3.33.24 (before the backport).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... and removed comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. labels Nov 22, 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-networking The connection layer under the protocols, on the server and on the client side: socket read / wri... pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR 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.

9 participants