Skip to content

fix: stdio-expose --stdin hangs when subprocess produces large output - #28

Merged
hyperrealist merged 2 commits into
epics-containers:mainfrom
hyperrealist:26-stdio-expose-hang-bugfix
Jun 16, 2026
Merged

hyperrealist merged 2 commits into
epics-containers:mainfrom
hyperrealist:26-stdio-expose-hang-bugfix

Conversation

@hyperrealist

@hyperrealist hyperrealist commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

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() used asyncio.connect_read_pipe() to attach to sys.stdin. That call internally invokes os.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's sys.stdout.buffer.write() to raise BlockingIOError once 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. Since process.wait() has no timeout, stdio-expose hung indefinitely.

The bug only manifests with --stdin on 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 call os.set_blocking(sys.stdout.fileno(), True) to restore blocking mode on stdout. Also replaces the deprecated asyncio.get_event_loop() with asyncio.get_running_loop().

Test

Adds a regression test that wraps stdio-expose --stdin in 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

    • Fixed an issue where using the --stdin flag with large output could cause the application to hang on terminal environments. Proper terminal mode handling is now restored during asynchronous operations.
  • Tests

    • Added regression test to prevent future hangs when using --stdin flag with large amounts of output.

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

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.66667% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.33%. Comparing base (20fa78b) to head (5657e33).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
src/stdio_socket/expose.py 66.66% 2 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI 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.

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 after connect_read_pipe().
  • Add a PTY-based regression test that runs stdio-expose --stdin and 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.

Comment thread src/stdio_socket/expose.py Resolved
Comment thread tests/test_cli.py Resolved
Comment thread tests/test_cli.py Resolved
Comment thread tests/test_cli.py Resolved
- 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
@hyperrealist
hyperrealist requested a review from shihab-dls June 12, 2026 12:42
@gilesknap

Copy link
Copy Markdown
Member

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

monitor_system_stdin now uses asyncio.get_running_loop() and adds a best-effort call to os.set_blocking to restore sys.stdout to blocking mode after connect_read_pipe may have set it non-blocking on TTY connections. A new regression test reproduces the hang using a real PTY pair with a drain loop and a kill-on-timeout guard.

Changes

TTY Non-Blocking Stdout Fix

Layer / File(s) Summary
Restore stdout blocking mode after connect_read_pipe
src/stdio_socket/expose.py
Switches to asyncio.get_running_loop() and adds a TTY-conditional os.set_blocking(sys.stdout.fileno(), True) call with exception suppression after connect_read_pipe to prevent stdout from being left in non-blocking mode.
PTY-based regression test for large output hang
tests/test_cli.py
Adds imports for errno, os, pty, and time, then adds test_stdin_flag_does_not_hang_with_large_output which opens a PTY pair, spawns the CLI with --stdin producing large output, drains the master fd in a loop handling EIO/BlockingIOError, and kills the process if a timeout is exceeded, asserting exit code 0.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A bunny once got stuck in a pipe,
O_NONBLOCK left stdout not quite right. 🐰
But now with a flag flipped back to true,
The TTY flows and the output comes through!
No more big traces lost in the night,
Just blocking mode set, and everything's bright! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately and concisely describes the main fix: preventing hangs in stdio-expose when subprocesses produce large output.
Linked Issues check ✅ Passed The PR fully addresses issue #26 by fixing the hang caused by non-blocking stdout and adding a regression test with large output.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the issue: core fix to restore blocking mode on stdout, defensive error handling, and a regression test for the hang scenario.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/test_cli.py (1)

47-70: ⚡ Quick win

Strengthen 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0da00ca and 5657e33.

📒 Files selected for processing (2)
  • src/stdio_socket/expose.py
  • tests/test_cli.py

Comment on lines +220 to +224
try:
if sys.stdin.isatty() and sys.stdout.isatty():
os.set_blocking(sys.stdout.fileno(), True)
except (OSError, AttributeError, ValueError):
pass

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Suggested change
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.

@gilesknap gilesknap left a comment •

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.

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.

https://gitlab.diamond.ac.uk/controls/containers/beamline/i13-1-services/-/blob/odin-eiger/services/bl13j-ea-eiger-01/values.yaml

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.

@hyperrealist

Copy link
Copy Markdown
Contributor Author

As per discussion with @gilesknap I am merging this PR as other processes that already use --stdin could benefit from this, even though --stdin is unnecessary.

@hyperrealist
hyperrealist merged commit 0e4eeae into epics-containers:main Jun 16, 2026
9 checks passed
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.

Large console output can cause stdio-expose to hang and not print everything

3 participants