Skip to content

Fix spurious "TLS/SSL error: Interrupted system call" from MySQL client reads - #120526

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mysql-tls-stale-openssl-error-queue
Sep 19, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-mysql-tls-stale-openssl-error-queue

Conversation

@groeneai

@groeneai groeneai commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #105987

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Bumped mariadb-connector-c to clear the OpenSSL error queue before every TLS operation. This removes spurious TLS/SSL error: Interrupted system call failures of mysql(), the MySQL table and database engines and MySQL dictionaries, where a leftover queue entry made a signal-interrupted read fatal.

Description

mysqlxx connections always use TLS and the query profiler is on by default, so their blocking TLS reads take periodic signals. OpenSSL marks EINTR retryable through the BIO retry flag, but SSL_get_error() reports those flags only while the calling thread's error queue is empty, and libmariadb/secure/openssl.c never cleared it: ossl_ssl_get_error() checks ERR_peek_error() first and returns SSL_ERROR_SYSCALL for any ERR_LIB_SYS entry before the retry flag. A leftover entry from an earlier operation on the same thread therefore makes ma_tls_read() treat a retryable read as fatal and report strerror_r(errno). ma_recv()'s EINTR loop is not on this path: OpenSSL reads the socket directly.

This bumps contrib/mariadb-connector-c to branch fix-tls-clear-openssl-error-queue: ERR_clear_error() before every SSL_connect/SSL_read/SSL_write read through SSL_get_error(), and errno captured first in ma_tls_set_error(). Same convention as src/IO/SocketPeerClosed.cpp.

I could not identify what left the entry behind, but with an empty queue this message is unreachable on the old pin: sock_read() zeroes errno before every recv, EINTR is retryable, and pvio_socket_wait_io_or_timeout() re-polls it and reports ETIMEDOUT (#109592).

Validation: with a stale ERR_LIB_SYS entry forced on the reading thread, 20 of 20 reads and 2-3 of 20 02479_mysql_connect_to_self runs failed as above; with the fix, 20 of 20 and 50 of 50 are green while 125319 stale entries were still measured at SSL entry, so the green arm is not vacuous.

Un-injected, 428000 instrumented reads produced none and no SQL-reachable producer was found, so no ClickHouse-side regression test is possible; the category is the one the fix-carrying bumps #118828 and #118927 used rather than Bug Fix. 26.7 and 26.8 pin the defective commit, so this needs a backport.

Seen in Stateless tests (arm_binary, parallel) on 9bd06dabfe74 (report).

#119510 (v3.4.10) does not supersede this: it also lacks the clear, and a stale entry defeats its new SSL_ERROR_SYSCALL && !ERR_peek_error() EOF shortcut. Forward-ported there on fwd-v3.4.10-tls-clear-openssl-error-queue.


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

Version info

  • Merged into: 26.10.1.165 (included in 26.10 and later)

@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 17, 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 review
of the resulting code (5 findings, none of them in the shipped diff). The tracked diff here is only
the submodule pointer, so instead of trusting the reviewing model's coverage claim I checked its
transcript: it read the patched libmariadb/secure/openssl.c, the bundled OpenSSL SSL_get_error
path, the pvio layer, the other TLS backends and the build wiring.

# Sev Finding Verdict Evidence / action
1 ⚠️ The provenance link sat inside the template's HTML comment, so nothing visible pointed at the requesting thread AGREE, fixed before publication Related: is now the first visible line of the body
2 ⚠️ The body linked the CI failure without showing that an empty error queue cannot produce this message AGREE, fixed before publication The body now gives it: sock_read() zeroes errno before every recv, EINTR is classified retryable, and the wait re-polls EINTR to its deadline and reports ETIMEDOUT
3 💡 The connector branch carrying the pinned commit was not named AGREE, fixed before publication Named in the body
4 💡 One SSL_get_error() in the connector is left unguarded, in mariadb_async.c DROPPED Dead code: #ifdef HAVE_TLS_FIXME is defined nowhere in the tree and the block would not compile
5 💡 The MySQL test family was run 10 times per test rather than the 50 planned AGREE, noted, not blocking ERR_clear_error() is inert when the queue is already empty at entry, which 428000 un-injected reads measured as the normal case, and 02479 itself ran 50 of 50

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260917-064400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. With a stale ERR_LIB_SYS entry forced on the calling thread (outside the connector, so the fix runs after it), one mysql() read of a 500k-row table under query_profiler_real_time_period_ns = 1000000 fails 20 of 20 times, and 02479_mysql_connect_to_self fails 2-3 of 20 runs. Both factors of the two-factor mechanism are forced; this is not a hope-for-the-flake reproduction.
b Root cause explained? Yes. SSL_get_error() reports the last operation's retry flags only while the thread's OpenSSL error queue is empty, and libmariadb/secure/openssl.c never cleared it. ossl_ssl_get_error() checks ERR_peek_error() first and returns SSL_ERROR_SYSCALL for any ERR_LIB_SYS entry before it looks at the retry flag, so a leftover entry turns a read that OpenSSL had already marked retryable (sock_read -> BIO_sock_non_fatal_error, whose case list includes EINTR) into a fatal one; ma_tls_set_error() then pops the stale entry, gets NULL from ERR_reason_error_string() and prints strerror_r(errno). Confirmed at runtime: at the failing call the queue held code=0x80000004 lib=2 reason=4, SSL_get_error returned 5 (SSL_ERROR_SYSCALL) and errno was 4 (EINTR), on a blocking socket.
c Fix matches root cause? Yes. It restores the documented SSL_get_error() precondition in the file that violates it. No widened bound, no no-random-* tag, no data reduction, and deliberately not an errno == EINTR retry: 428000 instrumented reads on a blocking socket under a ~1 kHz profiler produced 0 failures with a clean queue, so such a retry would be dead code there while still misreporting on a dirty queue.
d Test intent preserved / new tests added? Yes, and no new test ships, deliberately. No existing test is weakened and 02479 is untouched. A census of 428000 SSL reads found no SQL-reachable producer of a stale ERR_LIB_SYS entry (5 candidates probed: decrypt with a wrong key and with a bad AEAD tag, url('https://...') into a plaintext port and into a refused port, a failed-then-retried mysql() connection), so a test built on a producer would have an unobservable failing arm. 04507_mysql_connect_timeout_under_profiler remains as the guard that a genuine timeout still reports a timeout, and it passes.
e Both directions demonstrated? Yes, four arms with three distinct Build IDs. Injection off / fix off: 02479 20/20 green, 0 forced-repro failures. Injection on / fix off: 02479 17/20 then 18/20, forced repro 20/20 FAIL with the verbatim TLS/SSL error: Interrupted system call (4). Injection on / fix on: 02479 20/20, forced repro 0 failures, with 125319 stale entries still measured at SSL_* entry, so the green arm is not vacuous. Shipped binary: 02479 50/50.
f Fix is general across code paths? Yes. All five SSL_get_error() consumers in the file are covered: ma_tls_connect, ma_tls_read, ma_tls_write, ma_tls_read_async, ma_tls_write_async. Not changed, with reasons: ma_tls_close's SSL_shutdown result never reaches SSL_get_error and SSL_set_quiet_shutdown means it performs no I/O; ma_verification_callback records verify errors in the X509_STORE_CTX, not the ERR queue; schannel.c/gnutls.c have no OpenSSL error queue. Fixed in the consumer that must not depend on a queue it does not own rather than guarded at the failure site, because the set of producers is open-ended.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for the ClickHouse type system (this is C socket/TLS code, no column types involved). The relevant axes are covered: read and write, blocking and async, handshake and steady state, schema query and data read, and both IPv4 (127.0.0.1:9004) and IPv6 (::1:9004) reddened in the base arm. Behaviour is unchanged whenever the queue is already empty, which the 428000-read census shows is the normal case.
h Backward compatible? Yes. No API or ABI change, no setting, no format, so no SettingsChangesHistory.cpp entry. The only behavioural delta is confined to the non-empty-queue case: today the call fails, after the fix it is classified on its own merits. A genuine system error still raises its own ERR_LIB_SYS entry inside the cleared window and is still reported; a genuine timeout still reports through wait_io_or_timeout.
i Invariants and contracts preserved? Yes. The loop restructures preserve the originals exactly: in ma_tls_read/ma_tls_write the original entered the body on rc <= 0 and broke on anything other than SSL_ERROR_WANT_READ/WANT_WRITE, and the new for(;;) breaks on rc > 0, so rc == 0 still reaches SSL_get_error and the rc <= 0 -> ma_tls_set_error tail is unchanged. In ma_tls_connect the original called SSL_connect only while try_connect was true and exited retaining the last rc; the new form does the same for rc == 1, rc == 0 and try_connect = 0. ERR_clear_error() discards only the calling thread's queue and nothing between it and the SSL_* call can raise. No lock, allocation, error path or early return is altered, and no persistent state is involved.

Session id: cron:clickhouse-impl-slot-4:20260917-052700

@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [06506cb]

Summary: ✅


AI Review

Summary

This PR bumps contrib/mariadb-connector-c from 111ec1a to a5abc0b to pick up the connector-side fix that clears the OpenSSL error queue before SSL_get_error-classified SSL_connect/SSL_read/SSL_write calls. I did not find a correctness issue in the bumped connector diff itself, and the PR body gives a clear exception for why no in-tree regression test can reproduce the stale-queue path, but there is still one metadata nit: the change is categorized as Build/Testing/Packaging Improvement even though the promised user-facing effect is a stable-release bug fix.

PR Metadata

Changelog category is not semantically correct for the actual change. This gitlink bump fixes stable user-visible misbehavior in mysql, the MySQL table and database engines, and MySQL dictionaries, so it belongs under Bug Fix, not Build/Testing/Packaging Improvement.

Changelog entry would still be required under Bug Fix, and the current entry is already specific and user-readable enough to keep unchanged.

Exact replacement:

### Changelog category (leave one):
- Bug Fix
Findings

💡 Nits

  • [contrib/mariadb-connector-c:1] [dismissed by author -- https://github.com/Fix spurious "TLS/SSL error: Interrupted system call" from MySQL client reads #120526#discussion_r4037870015] The PR promise is a stable user-visible runtime fix, but the selected changelog category files it under packaging work instead of bug-fix behavior. The current rationale addresses the new_tests_check.py gate, not the changelog semantics, so I still think the release-note category is wrong. Suggested fix: switch the category to Bug Fix; the existing changelog entry can stay as-is.
Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 06506cb.

Metric Baseline Current Δ
Lines 88.40% 88.40% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 80.60% 80.60% +0.00%

Changed lines: Uncovered code analysis did not run: No coverable C/C++ source files changed (contrib/ is excluded from coverage).

Newly covered: +130 lines in 37 files (-188 lines lost coverage) · Details

Full report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default submodule changed At least one submodule changed in this PR. labels Sep 17, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-external-dependencies Third-party deps updates in contrib/, vendored code, and platform base libraries. label Sep 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 06506cb91 with master e6019455e (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

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

Job report

@groeneai
groeneai force-pushed the fix-mysql-tls-stale-openssl-error-queue branch from ce7b5e0 to 291e302 Compare September 17, 2026 13:46
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Sep 17, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Finish Workflow was red on ce7b5e0 for Post Hooks, not for any test: new_tests_check.py blocks a PR labeled pr-bugfix whose diff adds no test, and the diff here is a single submodule pin.

I corrected the changelog category to Build/Testing/Packaging Improvement rather than manufacture a test to clear the gate. With an empty OpenSSL error queue this message is unreachable on the old pin, 428000 instrumented un-injected reads produced none, and no SQL-reachable producer of a stale ERR_LIB_SYS entry was found, so the failing arm of a functional test would be unobservable and Bugfix validation would have nothing to reproduce. Fix-carrying contrib bumps use this category (#118828, #118927); the one recent pr-bugfix bump, #117422, could ship a test because its defect was reachable from SQL. The change itself is untouched: same tree, same pinned connector commit a5abc0b, only the commit message gained the reasoning. If you would rather keep Bug Fix, making this regression testable would need a test-only injection point in the client read path, and I did not add one on my own judgement.

26.7 and 26.8 pin the defective commit, so this still needs a backport. Merge order also matters here: ClickHouse/mariadb-connector-c#25 carries the actual code change and has to land first, and a squash or rebase merge there changes a5abc0b, which then has to be re-pinned in this PR.

…nt reads

Bump contrib/mariadb-connector-c to pick up a single connector change:
ERR_clear_error() before every SSL_connect/SSL_read/SSL_write whose result is
interpreted through SSL_get_error(), plus capturing errno as the first
statement of ma_tls_set_error().

SSL_get_error() only reports the retry flags of the operation just attempted
while the calling thread's OpenSSL error queue is empty, and openssl.c never
cleared it. A leftover ERR_LIB_SYS entry from any earlier OpenSSL operation on
the same thread is therefore reported first (ossl_ssl_get_error() returns
SSL_ERROR_SYSCALL for ERR_LIB_SYS before it looks at SSL_want_read() and the
BIO retry flag), so a read that OpenSSL had already marked retryable becomes
fatal. ma_tls_set_error() then pops the stale entry, gets NULL from
ERR_reason_error_string() and prints strerror_r(errno) instead, producing

  mysqlxx::BadQuery: TLS/SSL error: Interrupted system call (4)

on a healthy connection, with an errno that need not belong to the failing
call. Every mysql() table function, MySQL table/database engine and MySQL
dictionary read is affected: mysqlxx::Connection::connect enables TLS
unconditionally via mysql_ssl_set, the sampling query profiler is on by
default so query threads take periodic signals, and the TLS path bypasses
ma_recv()'s EINTR retry loop because OPENSSL_USE_BIOMETHOD is undefined and
SSL_set_fd() lets OpenSSL read the socket directly.

No regression test ships with this. With an empty error queue the message is
unreachable on the old pin: sock_read() zeroes errno before every recv, EINTR is
classified retryable, and pvio_socket_wait_io_or_timeout() re-polls it against
its deadline and reports ETIMEDOUT. 428000 instrumented un-injected reads
produced none, and no SQL-reachable producer of a stale ERR_LIB_SYS entry was
found, so the failing arm of a functional test would be unobservable. The fix
was validated by forcing a stale entry on the reading thread instead: 20 of 20
reads and 2-3 of 20 02479_mysql_connect_to_self runs failed before it, 20 of 20
and 50 of 50 passed after, and 125319 stale entries were still measured at SSL
entry on the green arm, so that arm is not vacuous.

The changelog category is the one the fix-carrying contrib bumps use (usearch
ClickHouse#118828, openssl ClickHouse#118927) rather than Bug Fix: the change in this repository is
only the dependency pin, and the Bug Fix category's validation expects a
regression test that reddens on master, which this defect cannot supply.

Connector change: ClickHouse/mariadb-connector-c#25
Related: ClickHouse#105987
@@ -1 +1 @@
Subproject commit 111ec1a5958cf984f50a28b0fb82a4087918d677
Subproject commit a5abc0b46c34df6274e65eb9c50d53733a2b3385

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.

Attaching this to the gitlink because it is the only changed line: the Changelog category looks semantically wrong here. This pin fixes stable user-visible runtime failures in mysql(), the MySQL table and database engines, and MySQL dictionaries, so it matches Bug Fix, not Build/Testing/Packaging Improvement, even though the implementation arrives via a submodule update.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The runtime effect is user-visible, agreed: on 26.7 and 26.8 this shows up as a spurious TLS/SSL error: Interrupted system call from mysql(), the MySQL table and database engines and MySQL dictionaries. I did not pick the category on visibility alone, because pr-bugfix also commits this PR to a contract it cannot satisfy.

new_tests_check.py makes pr-bugfix merge-blocking unless the diff adds a test, and for a functional or integration test it further requires at least one per-arch Bugfix validation job to report OK or XFAIL, i.e. the test has to fail on master HEAD. That arm is unobservable here: with an empty OpenSSL error queue this message is unreachable on the old pin, 428000 instrumented un-injected reads produced none, and no SQL-reachable producer of a stale ERR_LIB_SYS entry exists. The gate already fired on ce7b5e0 and took Mergeable Check with it.

Merged contrib bumps split on exactly that line. #117422 is the recent pr-bugfix one, and it could ship 05104_uniq_theta_compressed_state.sql because its defect was reachable from SQL. The fix-carrying bumps that could not ship a test merged as #118828 Not for changelog, #118927 Build/Testing/Packaging Improvement and #119262 Improvement, with no category objection raised on any of the three. The entry itself is not lost either: pr-build is not in NO_CHANGELOG_REQUIRED_LABELS, so the user-facing text still goes into CHANGELOG.md.

If a maintainer prefers Bug Fix, the honest way to earn it is a test-only injection point in the client read path so a gtest can force the stale entry. I will add that on request rather than on my own judgement.

@groeneai
groeneai force-pushed the fix-mysql-tls-stale-openssl-error-queue branch from 291e302 to 06506cb Compare September 17, 2026 14:17
@clickhouse-gh clickhouse-gh Bot added pr-build Pull request with build/testing/packaging improvement and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 17, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit 9fe808b Sep 19, 2026
177 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 19, 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 manual approve Manual approve required to run CI pr-build Pull request with build/testing/packaging improvement pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants