René's URL Explorer Experiment


Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython · GitHub

Open Graph Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython

X Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython

Description: Bug report Bug description Since gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), PySSL_SetError maps an ERR_LIB_SYS entry on the OpenSSL error queue to OSError: if (ERR_GET_LIB(e) == ERR_LIB_SYS) { // A s...

Open Graph Description: Bug report Bug description Since gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), PySSL_SetError maps an ERR_LIB_SYS entry on the OpenSSL error queue to OSError: if ...

X Description: Bug report Bug description Since gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), PySSL_SetError maps an ERR_LIB_SYS entry on the OpenSSL error queue to OSError: if ...

Opengraph URL: https://github.com/python/cpython/issues/158313

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError","articleBody":"# Bug report\n\n### Bug description\n\nSince gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), `PySSL_SetError` maps an `ERR_LIB_SYS` entry on the OpenSSL error queue to `OSError`:\n\n```c\nif (ERR_GET_LIB(e) == ERR_LIB_SYS) {\n    // A system error is being reported; reason is set to errno\n    errno = ERR_GET_REASON(e);\n    return PyErr_SetFromErrno(PyExc_OSError);\n}\n```\n\nThe same block appears in both the `SSL_ERROR_SYSCALL` and the `SSL_ERROR_SSL` case. Both return early, before the `ERR_clear_error()` that every other exit of `PySSL_SetError` goes through (and that the neighbouring `e == 0` branch of `SSL_ERROR_SYSCALL` calls explicitly). The entry therefore stays on the **thread's** error queue.\n\nOpenSSL's `SSL_get_error()` inspects that queue before anything else — the man page says *\"The current thread's error queue must be empty before the TLS/SSL I/O operation is attempted, or SSL_get_error() will not work reliably\"* — so the next `SSL_read_ex()`/`SSL_write_ex()` on that thread that does not complete immediately (would-block, EOF, …), **on any connection**, is reported as `SSL_ERROR_SYSCALL`/`SSL_ERROR_SSL`; `PySSL_SetError` takes the same early return, raises the same stale `OSError`, and again does not clear. The thread stays poisoned for the life of the process.\n\nNothing in the ssl module recovers from this. What sometimes does is a coincidence: OpenSSL's `state_machine()` calls `ERR_clear_error()` on entry, so a post-handshake message (e.g. a TLS 1.3 NewSessionTicket) processed inside a later read cleans up by accident. That is why this is hard to see in small tests and easy to hit in a long-running client that handshakes connections on one thread and reads them on another.\n\n### Reproducer\n\nLoopback only; needs the `openssl` CLI for a throwaway certificate.\n\n```python\n\"\"\"Two TLS connections on loopback. The peer resets the first; sending on it raises ConnectionResetError,\nwhich is correct. The second connection is healthy and idle, so recv() on it should wait for the timeout.\nInstead it raises ConnectionResetError at once, and keeps doing so on every call.\n\nSession tickets are switched off on purpose: TLS 1.3 sends them after the handshake and the client processes\nthem inside its next read, which runs OpenSSL's state machine, whose entry point calls ERR_clear_error() and\nwould hide the bug by coincidence.\"\"\"\nimport os, socket, ssl, struct, subprocess, sys, tempfile, threading, time\n\nprint(sys.version.split()[0], ssl.OPENSSL_VERSION, sys.platform)\nd = tempfile.mkdtemp()\ncrt, key = os.path.join(d, \"cert.pem\"), os.path.join(d, \"key.pem\")\nsubprocess.run([\"openssl\", \"req\", \"-x509\", \"-newkey\", \"ec\", \"-pkeyopt\", \"ec_paramgen_curve:prime256v1\", \"-nodes\",\n                \"-keyout\", key, \"-out\", crt, \"-days\", \"1\", \"-subj\", \"/CN=localhost\"], check=True, capture_output=True)\nserver_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\nserver_ctx.load_cert_chain(crt, key)\nserver_ctx.num_tickets = 0\nclient_ctx = ssl.create_default_context()\nclient_ctx.check_hostname, client_ctx.verify_mode = False, ssl.CERT_NONE\n\nlistener = socket.socket()\nlistener.bind((\"127.0.0.1\", 0))\nlistener.listen(5)\nheld = []\n\ndef serve():\n    while True:\n        conn, _ = listener.accept()\n        tls = server_ctx.wrap_socket(conn, server_side=True)\n        tls.settimeout(10)\n        if tls.recv(16) == b\"reset\":\n            raw = socket.socket(fileno=tls.detach())\n            raw.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack(\"ii\", 1, 0))\n            raw.close()                      # RST, no close_notify\n        else:\n            held.append(tls)                 # stays open and silent\n\nthreading.Thread(target=serve, daemon=True).start()\n\ndef connect(first_message):\n    c = client_ctx.wrap_socket(socket.create_connection(listener.getsockname()), server_hostname=\"localhost\")\n    c.settimeout(1)\n    c.send(first_message)\n    return c\n\ndef show(label, op):\n    t = time.time()\n    try:\n        r = op()\n        print(f\"{label}: returned {r!r} after {time.time() - t:.2f}s\")\n    except Exception as e:\n        print(f\"{label}: {type(e).__name__}({getattr(e, 'errno', None)}) after {time.time() - t:.2f}s\")\n\nhealthy = connect(b\"idle\")\nshow(\"healthy.recv() before      \", lambda: healthy.recv(100))     # TimeoutError after 1s: correct\nbroken = connect(b\"reset\")\ntime.sleep(0.2)\nshow(\"broken.send() after peer RST\", lambda: broken.send(b\"x\"))      # ConnectionResetError: correct\nfor i in range(3):\n    show(f\"healthy.recv() after, try {i + 1}\", lambda: healthy.recv(100))  # expected: TimeoutError after 1s\n```\n\nPython 3.12.13, OpenSSL 3.5.5, Linux aarch64 (the `python:3.12-slim` image):\n\n```\nhealthy.recv() before      : TimeoutError(None) after 1.00s\nbroken.send() after peer RST: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 1: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 2: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 3: ConnectionResetError(104) after 0.00s\n```\n\nThe `ConnectionResetError` from `broken.send()` is correct. The three from `healthy.recv()` are not: that connection is open and idle, and `recv()` should have waited 1 s and raised `TimeoutError`, as it did before.\n\nSame script on Python 3.12.8, OpenSSL 3.5.7, macOS (predates the backport):\n\n```\nhealthy.recv() before      : TimeoutError(None) after 1.00s\nbroken.send() after peer RST: SSLError(5) after 0.00s\nhealthy.recv() after, try 1: TimeoutError(None) after 1.00s\nhealthy.recv() after, try 2: TimeoutError(None) after 1.00s\nhealthy.recv() after, try 3: TimeoutError(None) after 1.00s\n```\n\n(The `SSLError` for the reset connection is the older, less precise report that GH-127361 improved on; the healthy connection is unaffected because that code path ends in `fill_and_set_sslerror()` + `ERR_clear_error()`.)\n\n### How it was found\n\nslack_sdk's builtin Socket Mode client reads every WebSocket connection it will ever have on one long-lived thread and handshakes new ones on another. One TLS connection reset by a network gateway put the receive thread's queue in this state. From then on every new connection was established fine, delivered one record, and failed with `BrokenPipeError` on the first would-block read — reconnect, repeat every 10 seconds, for three days, with the process otherwise healthy. `strace` showed no failing syscall at all in those cycles (the read returned `EAGAIN`), and reading the thread's queue through ctypes showed two entries: `SSL_R_UNEXPECTED_EOF_WHILE_READING` from the reset and `ERR_LIB_SYS`/`EPIPE` from OpenSSL's attempt to send the alert (`tls_retry_write_records`), so `SSL_get_error()` answered `SSL_ERROR_SSL` and the early return in *that* case was the one taken. Calling `ERR_clear_error()` from the receive thread recovered the client immediately.\n\n### Suggested fix\n\nCall `ERR_clear_error()` before the two `return PyErr_SetFromErrno(PyExc_OSError);` in the `ERR_LIB_SYS` branches, as the `e == 0` branch of `SSL_ERROR_SYSCALL` already does. (The broader request to clear the queue before every I/O call is gh-81891 / bpo-37710; this report is about the specific regression from GH-127361.)\n\n### CPython versions tested on\n\n3.12.13 (affected); 3.12.8 (not affected). The same two early returns are on `main` today.\n\n### Operating systems tested on\n\nLinux (aarch64, Debian-based `python:3.12-slim`); macOS for the unaffected comparison.\n\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-158333\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/liaoruoxing","@type":"Person","name":"liaoruoxing"},"datePublished":"2026-09-28T06:11:58Z","url":"https://github.com/python/cpython/issues/158313"}

react-profiling0
react-import-mapreact,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322
route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:82952b63-fa82-1112-95c6-6fdc25c7429a
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE0CE:17FB7:3C39ED9:4C3EA4C:6B023ABE
html-safe-nonce3ed2379092958f5a57ed3ec777dc8e0d251e017a7afbccc074687f91e9c5d43b
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMENFOjE3RkI3OjNDMzlFRDk6NEMzRUE0Qzo2QjAyM0FCRSIsInZpc2l0b3JfaWQiOiIzODMwODY5MjMzNjIxOTQwOTI2IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0=
visitor-hmacca87a0ddc6e90beedd750cde43ab9bfb05739dcdbdf6e86a324f3094b1e550a9
hovercard-subject-tagissue:5610179156
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/158313/issue_layout
twitter:imagehttps://opengraph.githubassets.com/2f9ff1eeaf85ae73f13d76e6c81ee31b4d77a68fd1c374c673f053af72a23c1c/python/cpython/issues/158313
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/2f9ff1eeaf85ae73f13d76e6c81ee31b4d77a68fd1c374c673f053af72a23c1c/python/cpython/issues/158313
og:image:altBug report Bug description Since gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), PySSL_SetError maps an ERR_LIB_SYS entry on the OpenSSL error queue to OSError: if ...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernameliaoruoxing
hostnamegithub.com
expected-hostnamegithub.com
None87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release423dbb54c5e7bfecc838eb387c1435eb3d0e760d
ui-targetfull
theme-color#1e2327
color-schemelight dark
react-app-nameissues

Links:

Skip to contenthttps://github.com/python/cpython/issues/158313#start-of-content
https://github.com/
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F158313
GitHubRepository hosting, code review, and collaborationhttps://github.com/platform
CopilotAI coding agent for tasks, projects, and automated workhttps://github.com/features/copilot
ActionsCI/CD and automationhttps://github.com/features/actions
Code QualityQuality analysis, fixes, and enforcementhttps://github.com/features/code-quality
CodespacesCloud development environmentshttps://github.com/features/codespaces
Code SecurityVulnerability detection and remediationhttps://github.com/security/advanced-security/code-security
Secret ProtectionSecret scanning and leak preventionhttps://github.com/security/advanced-security/secret-protection
All Featureshttps://github.com/features
Documentationhttps://docs.github.com/en
Traininghttps://learn.github.com/skills
Certificationshttps://learn.github.com/credentials
Build with Copilothttps://github.com/features/ai
Customize Copilothttps://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-copilot-overview
Integrationshttps://github.com/marketplace
Trending reposhttps://github.com/trending
GitHub Sponsorshttps://github.com/open-source/sponsors
Developer articleshttps://github.com/resources/articles
ChangelogYour source for the latest features, improvements, and fixes across GitHub products, all in one place.https://github.blog/changelog/
Enterpriseshttps://github.com/enterprise
Teamhttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
See all industrieshttps://github.com/solutions/industry
Why GitHubhttps://github.com/why-github
Customer Storieshttps://github.com/customer-stories
Business insightshttps://github.com/solutions/executive-insights
Trust Centerhttps://github.com/trust-center
GitHub Advanced SecurityEnterprise-grade code securityhttps://github.com/security/advanced-security
Copilot for businessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/enterprise/premium-support
Documentationhttps://docs.github.com/en
Resource centerhttps://github.com/resources
Bloghttps://github.blog/
Events & webinarshttps://github.com/resources/events
Community Forumhttps://github.com/orgs/community/discussions
Customer Storieshttps://github.com/customer-stories
Integrationshttps://github.com/marketplace
Customer supporthttps://help.github.com/
Traininghttps://learn.github.com/skills
GitHub Statushttps://www.githubstatus.com/
Abouthttps://github.com/about
Partnershttps://github.com/partners
Changeloghttps://github.blog/changelog/
GitHub UniverseThe event for developers, by developers — talks, workshops, and what’s next for GitHub.https://githubuniverse.com/
Pricinghttps://github.com/pricing
Sign inhttps://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F158313
Sign uphttps://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/158313
Reloadhttps://github.com/python/cpython/issues/158313
Reloadhttps://github.com/python/cpython/issues/158313
pythonhttps://github.com/python
cpythonhttps://github.com/python/cpython
Codehttps://github.com/python/cpython
Issues5k+ (5k+)https://github.com/python/cpython/issues
Pull requests2.4k (2.4k)https://github.com/python/cpython/pulls
Actionshttps://github.com/python/cpython/actions
Projectshttps://github.com/python/cpython/projects
Security and qualityhttps://github.com/python/cpython/security
Insightshttps://github.com/python/cpython/insights
https://github.com/python/cpython
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/158313
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/158313
ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSErrorhttps://github.com/python/cpython/issues/158313#top
topic-SSLhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-SSL%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/liaoruoxing
liaoruoxinghttps://github.com/liaoruoxing
on Sep 28, 2026https://github.com/python/cpython/issues/158313#issue-5610179156
gh-127257https://github.com/python/cpython/issues/127257
GH-127361https://github.com/python/cpython/pull/127361
GH-127905https://github.com/python/cpython/pull/127905
GH-127812https://github.com/python/cpython/pull/127812
GH-127361https://github.com/python/cpython/pull/127361
gh-81891https://github.com/python/cpython/issues/81891
bpo-37710https://bugs.python.org/issue?@action=redirect&bpo=37710
GH-127361https://github.com/python/cpython/pull/127361
gh-158313: Clear the OpenSSL error queue when ssl raises OSError #158333https://github.com/python/cpython/pull/158333
aiskhttps://github.com/aisk
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
topic-SSLhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-SSL%22
on Sep 28, 2026https://github.com/python/cpython/issues/158313#event-31968747057
kevinprimeraquecreo-stackhttps://github.com/kevinprimeraquecreo-stack
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/158313#event-33592137602
github-project-automationhttps://github.com/apps/github-project-automation
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/158313
kevinprimeraquecreo-stackhttps://github.com/kevinprimeraquecreo-stack
Project_VKhttps://github.com/users/kevinprimeraquecreo-stack/projects/1
on Oct 18, 2026https://github.com/python/cpython/issues/158313#event-33592173470
https://github.com/jonathan-simms
jonathan-simmshttps://github.com/jonathan-simms
on Oct 23, 2026https://github.com/python/cpython/issues/158313#issuecomment-6376085553
zochttps://github.com/zoc
on Oct 24, 2026https://github.com/python/cpython/issues/158313#event-34113630515
fix: clear the thread's OpenSSL error queue before router API usehttps://github.com/zoc/mktxp/commit/6dbd15ae8e5b8283f97f78dda5635a40fd623284
6dbd15ahttps://github.com/zoc/mktxp/commit/6dbd15ae8e5b8283f97f78dda5635a40fd623284
https://github.com/ifor
iforhttps://github.com/ifor
on Nov 3, 2026https://github.com/python/cpython/issues/158313#issuecomment-6600017217
https://github.com/totaam
totaamhttps://github.com/totaam
on Nov 13, 2026https://github.com/python/cpython/issues/158313#issuecomment-6848895770
libressl/portable#1466https://github.com/libressl/portable/issues/1466
Xpra-org/xpra#5145https://github.com/Xpra-org/xpra/issues/5145
gh-158333https://github.com/python/cpython/pull/158333
gh-148594https://github.com/python/cpython/issues/148594
gh-159641https://github.com/python/cpython/pull/159641
picnixzhttps://github.com/picnixz
CPython Bug Report: ssl — Stale OpenSSL thread-local ERR queue entries poison unrelated SSL connections (SSLSocket read raises ConnectionResetError immediately after another connection on the same thread hit ECONNRESET) #162365https://github.com/python/cpython/issues/162365
on Nov 21, 2026https://github.com/python/cpython/issues/158313#event-36846681147
Sign up for freehttps://github.com/signup?return_to=https://github.com/python/cpython/issues/158313
Sign in to commenthttps://github.com/login?return_to=https://github.com/python/cpython/issues/158313
topic-SSLhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22topic-SSL%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.