Repository navigation
fix: stdio-expose --stdin hangs when subprocess produces large output - #28
hyperrealist merged 2 commits into
Conversation
asyncio.connect_read_pipe() sets O_NONBLOCK on the stdin fd. On a TTY, stdin (fd 0) and stdout (fd 1) share the same open file description, so stdout silently becomes non-blocking too. This caused do_stdout's sys.stdout.buffer.write() to raise BlockingIOError when the subprocess produced large output (>PTY buffer size). The crashed task left the subprocess pipe unread, filling the 64 KB pipe buffer and deadlocking process.wait() indefinitely. Fix: call os.set_blocking(sys.stdout.fileno(), True) immediately after connect_read_pipe() to restore blocking mode on stdout. Also update the deprecated asyncio.get_event_loop() call to asyncio.get_running_loop(). Adds a regression test that wraps stdio-expose in a real PTY (required to reproduce the shared file-description condition) and verifies it exits cleanly with 200 KB of subprocess output.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #28 +/- ##
==========================================
+ Coverage 1.50% 63.33% +61.82%
==========================================
Files 6 6
Lines 133 180 +47
==========================================
+ Hits 2 114 +112
+ Misses 131 66 -65 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Pull request overview
Fixes a hang in stdio-expose --stdin when the wrapped subprocess emits large output on a real TTY/PTY by preventing stdout from being left in non-blocking mode after asyncio.connect_read_pipe() modifies fd flags. Adds a regression test that reproduces the shared-PTY file-description behavior and verifies the CLI exits cleanly with large output.
Changes:
- Update stdin monitoring to use
asyncio.get_running_loop()and restore blocking mode on stdout afterconnect_read_pipe(). - Add a PTY-based regression test that runs
stdio-expose --stdinand drains the PTY while the subprocess prints ~200 KB.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
src/stdio_socket/expose.py |
Restores stdout blocking mode after connecting stdin read pipe; modernizes loop retrieval. |
tests/test_cli.py |
Adds PTY regression test to prevent hangs with large subprocess output under --stdin. |
- Guard os.set_blocking() with isatty() checks and catch (OSError, AttributeError, ValueError) since stdout may not have a real fd in all environments - Use sys.executable + '-m stdio_socket' instead of 'stdio-expose' in the regression test so it works without console scripts on PATH - Narrow OSError catch to errno.EIO only; re-raise anything else (e.g. EBADF) to avoid masking real failures - Kill the child process before re-raising TimeoutExpired to prevent leaking it into the rest of the test session
|
@coderabbitai full review |
✅ Action performedFull review finished. |
📝 WalkthroughWalkthrough
ChangesTTY Non-Blocking Stdout Fix
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
tests/test_cli.py (1)
47-70: ⚡ Quick winStrengthen the regression to verify output completeness (not only exit/no-hang).
The current test proves liveness, but it doesn’t verify that the large payload was fully forwarded. Counting drained payload bytes (or at least
'x'bytes) makes the test align with the “prints full output” objective and also lets you handle empty-byte EOF explicitly in the drain loop.Proposed refactor
os.set_blocking(master_fd, False) deadline = time.monotonic() + 15 + x_count = 0 while time.monotonic() < deadline: try: - os.read(master_fd, 4096) + chunk = os.read(master_fd, 4096) + if chunk: + x_count += chunk.count(b"x") + elif proc.poll() is not None: + break except BlockingIOError: if proc.poll() is not None: break time.sleep(0.05) @@ except subprocess.TimeoutExpired: proc.kill() proc.wait(timeout=5) raise assert proc.returncode == 0 + assert x_count >= 200_000🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_cli.py` around lines 47 - 70, The test verifies that the process exits successfully without hanging, but it does not verify that the large payload was actually fully forwarded through the output. Add a counter variable before the while loop to track the total bytes read from the file descriptor. Inside the try block where os.read(master_fd, 4096) is called, accumulate the byte count from each read operation. After the process completes and exits the loop, add an assertion to verify that the expected number of bytes were received, ensuring the large payload was fully printed and forwarded as intended.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/stdio_socket/expose.py`:
- Around line 220-224: The broad OSError exception handling in the try-except
block silently catches and ignores all file descriptor errors, including
unexpected ones like EBADF that indicate real bugs. Instead of catching all
OSError exceptions indiscriminately, narrow the exception handling to only catch
expected errno values that indicate harmless PTY-related failures (such as those
that occur during terminal state operations), and re-raise unexpected OSErrors
that indicate actual descriptor or state problems. Keep the AttributeError and
ValueError catches as-is since those represent expected attribute/value issues
from the isatty() and fileno() calls. Check the errno attribute of caught
OSError exceptions in the except block and selectively re-raise those that are
not in the set of expected/harmless errno values.
---
Nitpick comments:
In `@tests/test_cli.py`:
- Around line 47-70: The test verifies that the process exits successfully
without hanging, but it does not verify that the large payload was actually
fully forwarded through the output. Add a counter variable before the while loop
to track the total bytes read from the file descriptor. Inside the try block
where os.read(master_fd, 4096) is called, accumulate the byte count from each
read operation. After the process completes and exits the loop, add an assertion
to verify that the expected number of bytes were received, ensuring the large
payload was fully printed and forwarded as intended.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 7734600c-0ef8-429a-a0b3-451c339e219f
📒 Files selected for processing (2)
src/stdio_socket/expose.pytests/test_cli.py
| try: | ||
| if sys.stdin.isatty() and sys.stdout.isatty(): | ||
| os.set_blocking(sys.stdout.fileno(), True) | ||
| except (OSError, AttributeError, ValueError): | ||
| pass |
There was a problem hiding this comment.
Narrow OSError handling instead of swallowing all fd failures.
At Line [223], catching all OSError and silently continuing can hide real descriptor/state bugs (for example EBADF) and make regressions hard to detect. Keep best-effort behavior for expected PTY noise, but re-raise unexpected OSErrors.
Proposed fix
import asyncio
+import errno
import os
import sys
@@
- except (OSError, AttributeError, ValueError):
- pass
+ except OSError as exc:
+ if exc.errno != errno.EIO:
+ raise
+ except (AttributeError, ValueError):
+ pass📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try: | |
| if sys.stdin.isatty() and sys.stdout.isatty(): | |
| os.set_blocking(sys.stdout.fileno(), True) | |
| except (OSError, AttributeError, ValueError): | |
| pass | |
| try: | |
| if sys.stdin.isatty() and sys.stdout.isatty(): | |
| os.set_blocking(sys.stdout.fileno(), True) | |
| except OSError as exc: | |
| if exc.errno != errno.EIO: | |
| raise | |
| except (AttributeError, ValueError): | |
| pass |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/stdio_socket/expose.py` around lines 220 - 224, The broad OSError
exception handling in the try-except block silently catches and ignores all file
descriptor errors, including unexpected ones like EBADF that indicate real bugs.
Instead of catching all OSError exceptions indiscriminately, narrow the
exception handling to only catch expected errno values that indicate harmless
PTY-related failures (such as those that occur during terminal state
operations), and re-raise unexpected OSErrors that indicate actual descriptor or
state problems. Keep the AttributeError and ValueError catches as-is since those
represent expected attribute/value issues from the isatty() and fileno() calls.
Check the errno attribute of caught OSError exceptions in the except block and
selectively re-raise those that are not in the set of expected/harmless errno
values.
There was a problem hiding this comment.
Hi @hyperrealist this fix looks fine and coderabbit agrees.
However I have discovered that its all a horrible mistake and I did not document things enough.
The above uses --stdin and that is why it had issues. I knew that --stdin was a little unreliable and therefore made all the templates in the services-template-argocd not use it. Its completely unecessary for a kubernetes pod because kubernetes almost never uses attach to process - and worse, the whole point of stdio-socket is to avoid having to do that and using console instead.
I suspect that Gary was implementing the odin entrypoints before those templates were created and assumed --stdin was needed.
To be clear: --stdin means that the wrapper has stdin so therefore process 0 on the pod has stdio and you could interactively attach to it. BUT the stdio-socket console that attaches always has stdin.
TLDR: this fix is all good. But we'd be better off not using --stdin for K8S processes anyway.
|
As per discussion with @gilesknap I am merging this PR as other processes that already use |
Closes #26
Problem
stdio-expose --stdin <cmd>would hang indefinitely if the wrapped command wrote more than ~4 KB of output to stdout/stderr.Root cause
monitor_system_stdin()usedasyncio.connect_read_pipe()to attach tosys.stdin. That call internally invokesos.set_blocking(fd0, False). On a TTY, stdin (fd 0) and stdout (fd 1) share the same open file description — so stdout also becomes non-blocking as a side effect.This caused
do_stdout'ssys.stdout.buffer.write()to raiseBlockingIOErroronce the PTY write buffer was full, crashing the asyncio task. With nothing draining the subprocess's stdout pipe, the pipe buffer (64 KB) filled up, and the subprocess blocked forever trying to write. Sinceprocess.wait()has no timeout,stdio-exposehung indefinitely.The bug only manifests with
--stdinon a real TTY — with piped I/O, fd 0 and fd 1 are independent file descriptions and O_NONBLOCK on one doesn't affect the other.Fix
After
connect_read_pipe()runs, immediately callos.set_blocking(sys.stdout.fileno(), True)to restore blocking mode on stdout. Also replaces the deprecatedasyncio.get_event_loop()withasyncio.get_running_loop().Test
Adds a regression test that wraps
stdio-expose --stdinin a real PTY (necessary to reproduce the shared file-description condition) and asserts it exits cleanly when the subprocess emits 200 KB of output.Summary by CodeRabbit
Bug Fixes
--stdinflag with large output could cause the application to hang on terminal environments. Proper terminal mode handling is now restored during asynchronous operations.Tests
--stdinflag with large amounts of output.