Skip to content

Fix optional OpenSSL duplex I/O on Unix - #9173

Merged
youknowone merged 2 commits into
RustPython:mainfrom
youknowdot:fix/openssl-full-duplex
Oct 17, 2026
Merged

youknowone merged 2 commits into
RustPython:mainfrom
youknowdot:fix/openssl-full-duplex

Conversation

@youknowdot

@youknowdot youknowdot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Fix optional OpenSSL duplex I/O on Unix

Follow-up to #9167. A blocking read currently holds the connection lock while waiting for network input, preventing a concurrent write on the same TLS connection from making progress.

This change removes that deadlock on Unix platforms with MSG_DONTWAIT, without changing the shared socket's blocking flags. Windows and AIX retain the legacy transport and its blocking-I/O limitation. Linux and macOS optional OpenSSL runtime validation passed in hosted CI; the local results below are Linux only.

Implementation

  • Serialize each native SSL attempt, error inspection and callback snapshot, then release the connection lock before waiting for socket readiness.
  • Preserve OpenSSL's write-retry contract with stable owned pending bytes and explicit retry ownership. WANT_WRITE prevents conflicting native calls; WANT_READ permits safe read progress.
  • Register anonymous-pipe wakeups before unlocking, and notify waiters on native progress, ownership changes and socket invalidation.
  • Allocate socket identity tracking lazily for SSL. Close, detach and reinitialization wake waiters; each native transport call validates identity to reject descriptor reuse. Reinitialization unlocks and notifies before dropping the old native socket.
  • Settle write ownership and capture owned callback/native-error metadata under the SSL guard, then construct Python exceptions after unlocking. Preserve certificate-verification metadata when a debug callback also fails.
  • Extend the existing SSL snippet for buffer-export release, writer-return/reader-callback cleanup, and an explicitly reached application WANT_WRITE followed by valid saved-byte retry and exact delivery/EOF. Positive partial writes are supported.
  • Extend the existing OpenSSL build step with the shared snippet and full canonical SSL suite on Linux/macOS, preserving the minimal-feature and vendored build checks. Canonical Lib/test/test_ssl.py remains untouched, with no new exclusion or weakened assertion.

A timed-out, interrupted or nonblocking write can retain a native continuation. Retry with the same bytes and length. Until an abandoned WANT_WRITE continuation is retried, conflicting I/O reports SSLWantWriteError instead of making a forbidden native call. Close/detach remain escape routes; equal concurrent writes are still distinct calls.

This addresses the lock held across a read-readiness wait. Strict OpenSSL WANT_WRITE ownership does not guarantee liveness under arbitrary two-peer backpressure. Acquiring the native lock behind a long-running Python callback is not newly deadline-aware.

Validation

Locally on the final tree rebased onto fc9f4a9 (native tests/checks use their normal Cargo profiles; interpreter runtime checks use fresh release binaries):

  • 14 native retry-ownership, progress-waiter and socket-identity tests passed.
  • Threaded/nonthreaded OpenSSL checks and the OpenSSL 1.1.1w compile-only floor check passed.
  • Full unchanged test_ssl: OpenSSL 215 total / 189 executed passes / 26 skips; default rustls 215 total / 175 executed passes / 40 skips.
  • Canonical callback-exception/duplex selectors: 2 passes.
  • Exact final snippet passed on CPython 3.15 first, then OpenSSL and rustls; the existing focused pytest harness also passed once per RustPython backend.
  • Normal repository hooks passed. Optional OpenSSL Clippy still fails with 41 inherited diagnostics; comparison against the earlier log confirms the introduced findings were removed.

Additional completed evidence before the importlib rebase and mechanical lint cleanup: workspace native 1,369 passes; separate ABI3T C-API 123 passes / 4 ignores; workspace docs 24 passes / 18 ignores; C-API docs had no cases. Workspace and separate C-API Clippy passed. The production retry/wakeup implementation was unchanged by that cleanup.

That earlier source also passed 20 TLS 1.3 and 20 TLS 1.2-bound invocations of the canonical duplex method, plus CPython-first timeout/callback and certificate-metadata checks. These are bounded scheduling/compatibility checks, not exhaustive stress or fuzz coverage. Existing resource/platform skips remain. Broad local test_socket was not run; socket evidence consists of native identity tests and canonical SSL lifecycle coverage.

Main hosted CI passed all 25 jobs at 0617d622, including actionlint and the mandatory zizmor scan. The optional OpenSSL build, shared snippet and unchanged full SSL suite passed on both Linux (OpenSSL 3.0.13) and macOS (OpenSSL 4.0.3). Each hosted SSL run reported 215 total / 186 executed passes / 29 skips, with the canonical duplex and callback-exception methods executed successfully. Windows default-backend CI passed; optional OpenSSL runtime steps were intentionally not run there. The consolidated Linux/macOS Rust jobs finished in 29m32s and 26m50s, within the unchanged 45-minute job limit.

The separate CodSpeed run failed during its build with exit code 143 before any benchmarks executed. No Rust diagnostic was reported; a maintainer rerun is needed. This remains a failed check, separate from the successful main CI.

Windows needs a separately agreed transport compatibility contract. The existing trailing-None SSL exception args mismatch and rustls callback-settlement follow-ups are outside this change.

AI assistance

Implementation, test preparation and review were assisted by OpenAI Codex (model version unavailable).

Summary by CodeRabbit

  • Bug Fixes

    • Improved TLS socket handling on Unix, including nonblocking I/O, timeouts, interruption handling, and connection-close notifications.
    • Made concurrent TLS reads and writes more reliable by preserving pending write data and enforcing correct retries.
    • Improved certificate-verification error reporting across platforms.
  • Tests

    • Added coverage for TLS write retries, concurrent socket activity, and bounded echo-server behavior.
    • Expanded OpenSSL build and SSL test coverage across non-Windows platforms.

Release connection locks before readiness waits while serializing native SSL
attempts and preserving owned write retries. Wake waiters on native progress
and socket identity invalidation, and construct callback/native exceptions
after unlocking.

Add regression coverage to the existing SSL snippet and run the optional
OpenSSL backend in the existing Unix CI matrix. Windows and AIX retain the
legacy transport pending a separate compatibility-safe driver.

Assisted-by: OpenAI Codex:model version unavailable
@coderabbitai

coderabbitai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: RustPython/RustPython/.coderabbit.yml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b922b438-ce9f-4c0a-8b6b-51b6ea9f5268
📥 Commits

Reviewing files that changed from the base of the PR and between fc9f4a9 and 0617d62.

📒 Files selected for processing: 6
  • .github/workflows/ci.yaml
  • crates/stdlib/src/openssl.rs
  • crates/stdlib/src/openssl/driver.rs
  • crates/stdlib/src/openssl/waiter.rs
  • crates/stdlib/src/socket.rs
  • extra_tests/snippets/stdlib_ssl.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📝 Walkthrough

Unix OpenSSL socket operations now use nonblocking I/O with readiness waiting, progress notifications, and coordinated write retries. Socket identities track closure and replacement. The change also updates SSL error conversion, retains non-Unix operation paths, and expands SSL tests and CI coverage.

Changes: Unix OpenSSL I/O coordination

Layer / File(s) Summary
Socket identity and readiness primitives
crates/stdlib/src/socket.rs, crates/stdlib/src/openssl/waiter.rs
PySocket tracks SSL socket identities and notifies observers when sockets close or change. ProgressWaiter polls socket readiness and notifications, while ProgressRegistry tracks registered waiters.
SSL transport and progress wiring
crates/stdlib/src/openssl.rs
Socket and BIO streams use the shared SslTransport and SslConnection structures. Unix connections track I/O progress and install SSL progress callbacks.
Nonblocking SSL operations and write retries
crates/stdlib/src/openssl.rs, crates/stdlib/src/openssl/driver.rs
Unix SSL operations coordinate readiness waits, deadlines, signals, and concurrent I/O. The write driver retains pending buffers and enforces retry ownership.
Error snapshots and non-Unix SSL paths
crates/stdlib/src/openssl.rs
Legacy non-Unix SSL operations pass the SSL pointer to error conversion. Verification details are captured in SslErrorSnapshot while the native pointer is available.
SSL tests and CI coverage
extra_tests/snippets/stdlib_ssl.py, .github/workflows/ci.yaml
The SSL tests cover mutable-buffer retries, concurrent reads and writes, and bounded nonblocking writes. CI enables OpenSSL on macOS and runs SSL tests on non-Windows runners.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant SslConnection
  participant SSLDriver
  participant SocketStream
  participant ProgressWaiter
  Caller->>SslConnection: Start SSL operation
  SslConnection->>SSLDriver: Run operation with retry state
  SSLDriver->>SocketStream: Nonblocking send or receive
  SocketStream-->>SSLDriver: Bytes transferred or WouldBlock
  SSLDriver->>ProgressWaiter: Wait for readiness or progress
  ProgressWaiter-->>SSLDriver: Readiness, notification, or timeout
  SSLDriver-->>SslConnection: Settle retry state and return result
  SslConnection-->>Caller: Return result or error
Loading

Suggested reviewers: youknowone

Merge Risk: ⚪ Minimal · up to 0617d

On Unix, OpenSSL sockets now release the connection lock while waiting for the network, so a concurrent write can proceed while a read is blocked. Windows and AIX keep their existing behavior. No concrete defect was identified in the new coordination, socket-lifecycle, or error-reporting paths, and the change appears ready to merge. The concurrency logic is intricate, so follow-up stress testing remains worthwhile.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 36.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 139 functions across 5 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: fixing optional OpenSSL duplex I/O on Unix.
Full details: Docstring Coverage

Explanation

Docstring coverage is 36.69% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 139 functions across 5 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
🧪 Generate unit tests (beta)
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

check once again not to add duplicated test in test_ssl.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rechecked against the canonical cases. The connection/handshake setup overlaps, but these added failure conditions are different:

  • MemoryBIOTests.test_buffer_types checks accepted buffer types. The snippet resizes the original exporter after WANT_READ, then retries with the saved original bytes.
  • test_nonblocking_send fills the socket until WANT and closes it. The snippet requires application WANT_WRITE, releases/resizes the exporter, then checks valid retry and exact delivery through EOF.
  • The canonical duplex test covers a blocking reader with a concurrent sender. test_msg_callback_deadlock_bpo43577 covers an SNI context switch. The added callback case specifically waits for the writer to return while the other thread's read callback is running, exercising write-owner cleanup.

I couldn't find those assertions in test_ssl.py. The snippet reuses its server implementation with bounded cleanup; test_ssl.py itself remains unchanged and is still run in full.

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.

@youknowone It sounds like these failure conditions are good candidates to add to the upstream CPython test suite.

Comment thread .github/workflows/ci.yaml Outdated

# Keep this after the default-backend checks: rebuilding replaces the
# release interpreter. Windows still needs a nonblocking OpenSSL driver.
- name: Build optional OpenSSL runtime

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

didn't we arleady have openssl test in CI?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, the existing OpenSSL and vendored OpenSSL steps check minimal-feature compilation on Linux. They don't run SSL tests. The normal snippet/CPython jobs use CARGO_ARGS with ssl-rustls-aws-lc.

The added steps run the shared snippet and unchanged canonical test_ssl with ssl-openssl on Linux/macOS. This covers the backend affected by this PR. I kept the existing compile-only gates because their minimal feature configurations are distinct; replacing them with the runtime build would remove that coverage. Windows retains its existing default-backend checks while the OpenSSL transport limitation remains documented.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ok combine this test to the existing one. do not add new task for that

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Combined in 0617d62. The existing “Test openssl build” step now runs the release build, SSL snippet and canonical test_ssl; the three separate steps are removed. The original minimal-feature build command and vendored build check are preserved. The existing step also runs on macOS with its OpenSSL dependency enabled. Fresh CI is running for this commit.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up #9177 removes the added macOS OpenSSL build and runtime work. The consolidated checks now stay in the existing Linux OpenSSL step; its minimal-feature, runtime and vendored coverage are preserved. Other macOS jobs are unchanged.

Keep the minimal system and vendored OpenSSL build checks, and run the
Unix SSL regressions in the existing system OpenSSL step. Preserve the
runtime feature set and enable its macOS dependency in that job.

Assisted-by: OpenAI Codex:model version unavailable
@youknowone
youknowone marked this pull request as ready for review October 17, 2026 13:31
@youknowone
youknowone enabled auto-merge (squash) October 17, 2026 13:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T13:44:29.511378Z 0617d62 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0617d62275

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +35 to +36
try:
client.write(exporter)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove the prohibited test logic additions

This starts a newly added test scenario, and the remainder of this file adds substantial test data, assertions, helper classes, and test bodies; the repository's critical test rule permits test-file changes only for adding or removing expectedFailure markers, so these additions need to be removed from this change regardless of whether the runtime implementation passes them.

AGENTS.md reference: AGENTS.md:L276-L282

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The maintainer's snippet-specific policy is to avoid Lib/test duplication and add new cases to the closest existing snippet, as recorded in AGENTS.md. These additions follow that direction. The canonical-test comparison identifies the distinct exporter-release, saved-byte retry and callback-cleanup assertions. Existing assertions and Lib/test/test_ssl.py are unchanged. I'm retaining this regression coverage rather than removing it solely because it adds test logic.

@youknowone
youknowone disabled auto-merge October 17, 2026 14:36
@youknowone
youknowone merged commit 51e886c into RustPython:main Oct 17, 2026
28 of 29 checks passed
youknowone pushed a commit that referenced this pull request Oct 17, 2026
Remove the macOS OpenSSL build and runtime expansion from #9173 while preserving the existing Linux checks and other macOS jobs.

Assisted-by: OpenAI Codex:model version unavailable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants