Skip to content

pytester: handle bytes stdin without blocking or BrokenPipeError - #15478

Open
Sudhakar7J wants to merge 3 commits into
pytest-dev:mainfrom
Sudhakar7J:fix/pytester-stdin-bytes-broken-pipe
Open

Sudhakar7J wants to merge 3 commits into
pytest-dev:mainfrom
Sudhakar7J:fix/pytester-stdin-bytes-broken-pipe

Conversation

@Sudhakar7J

Copy link
Copy Markdown

Fixes #15472.

When Pytester.run(stdin=<bytes>) or Pytester.popen(stdin=<bytes>) is used and the child process exits before reading stdin (or never reads it), the background write can raise BrokenPipeError/connection errors or prevent timeout from being enforced.

This change writes bytes stdin via a small helper (_write_stdin_bytes) in a daemon thread and catches OSError from the write/close. For popen(), it sets popen.stdin = None so Popen.communicate() does not race with the background writer. For run(), it keeps stdin=PIPE, starts the background writer, and joins the writer on normal completion and on TimeoutExpired so the configured timeout is still enforced.

Test plan

  • Added test_run_stdin_bytes_child_exits_without_reading
  • Added test_run_stdin_bytes_timeout_when_child_does_not_read
  • Added test_popen_stdin_bytes_child_exits_without_reading
  • uv 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.py
  • uvx ruff format --check src/_pytest/pytester.py testing/test_pytester.py

Verified locally on Windows (Python 3.14.10).

AI-assisted (opencode); reviewed and submitted by @Sudhakar7J.

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)
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided (automation) changelog entry is part of PR label Nov 28, 2026
Comment thread src/_pytest/pytester.py Outdated
handle_timeout()
finally:
if stdin_writer is not None:
stdin_writer.join(timeout=1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.5

Could 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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided (automation) changelog entry is part of PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pytester.run(stdin=<bytes>) raises BrokenPipeError / can block when the child doesn't read stdin

2 participants