Repository navigation
pytester: handle bytes stdin without blocking or BrokenPipeError - #15478
Sudhakar7J wants to merge 3 commits into
Conversation
Write bytes stdin in a background thread so Pytester.run() can enforce timeouts even when the child process does not read stdin, and catch BrokenPipeError when the child exits before consuming the input. Closes pytest-dev#15472 Assisted-by: opencode (Iceman Contributor Free)
| handle_timeout() | ||
| finally: | ||
| if stdin_writer is not None: | ||
| stdin_writer.join(timeout=1) |
There was a problem hiding this comment.
When a helper process inherits stdin, killing the launcher leaves the pipe open. The timeout path then waits at both one-second joins, in handle_timeout() and here in finally. On 458eb2f9e9de86d20765f0b2f78a13a85c2bc1ef under WSL with CPython 3.13.14, timeout=0.5 raised TimeoutExpired after 2.504 s, with the writer still blocked.
Save as test_inherited_stdin.py and run pytest -p pytester -q -s test_inherited_stdin.py.
import sys
import threading
import time
import pytest
def test_inherited_stdin_timeout(pytester):
launcher = """
import subprocess, sys, time
subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(4)"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
time.sleep(4)
"""
start = time.monotonic()
with pytest.raises(pytester.TimeoutExpired):
pytester.run(
sys.executable, "-c", launcher,
stdin=b"x" * 2**20, timeout=0.5,
)
elapsed = time.monotonic() - start
writers = [t.name for t in threading.enumerate() if "_write_stdin_bytes" in t.name]
print(f"{elapsed:.3f}s, active writers: {writers}")
assert elapsed < 1.5Could you use one cleanup path with a single timeout budget and add regression coverage for the inherited-stdin case?
Codex (GPT-6) assisted with the investigation and ran both probes.
There was a problem hiding this comment.
Thanks for the detailed repro and analysis.
I updated the fix in 4a419ccc to use a single stdin-writer cleanup path with one timeout budget. On timeout, run() now sets a cancel event, kills/waits the child, and joins the writer once with the remaining budget; the finally path only joins when no timeout path already handled it.
To cover the inherited-stdin case, the writer now writes bytes through a non-blocking/cancellable loop (with a blocking fallback if non-blocking mode is unavailable), so a grandchild holding the read end doesn't keep the main thread blocked or leave an active writer behind. I added test_run_stdin_bytes_timeout_with_inherited_stdin as regression coverage.
Verified locally on Windows (Python 3.x venv): pytest testing/test_pytester.py -k stdin_bytes passed (5 passed).
There was a problem hiding this comment.
Thanks—the original reproducer now times out in 0.508 s with no surviving writer on WSL at ed66a02.
I found a remaining issue when non-blocking mode is unavailable. Forcing os.set_blocking() to raise ENOTSUP on WSL leaves the fallback writer blocked:
- Without a timeout, a successful launcher waited 4.269 s for its helper to close inherited stdin. The unconditional join() could wait indefinitely for a long-lived helper.
- With timeout=0.5, it raised after 1.505 s with one writer still blocked.
Could fallback cleanup remain bounded even when no timeout is supplied, with regression coverage for this path?
This is a forced fallback test on WSL, not native Windows validation.
Fixes #15472.
When
Pytester.run(stdin=<bytes>)orPytester.popen(stdin=<bytes>)is used and the child process exits before reading stdin (or never reads it), the background write can raiseBrokenPipeError/connection errors or preventtimeoutfrom being enforced.This change writes bytes stdin via a small helper (
_write_stdin_bytes) in a daemon thread and catchesOSErrorfrom the write/close. Forpopen(), it setspopen.stdin = NonesoPopen.communicate()does not race with the background writer. Forrun(), it keepsstdin=PIPE, starts the background writer, and joins the writer on normal completion and onTimeoutExpiredso the configured timeout is still enforced.Test plan
test_run_stdin_bytes_child_exits_without_readingtest_run_stdin_bytes_timeout_when_child_does_not_readtest_popen_stdin_bytes_child_exits_without_readinguv run --group dev pytest testing/test_pytester.py -k stdin -v(7 passed, 51 deselected)uv run --group dev pytest testing/test_pytester.py -q(56 passed, 1 skipped, 1 xfailed)uvx ruff check src/_pytest/pytester.py testing/test_pytester.pyuvx ruff format --check src/_pytest/pytester.py testing/test_pytester.pyVerified locally on Windows (Python 3.14.10).
AI-assisted (opencode); reviewed and submitted by @Sudhakar7J.