Skip to content

Commit 1247113

Browse files
miss-islingtongpsheadclaude
authored
[3.13] gh-87512: Fix subprocess using timeout= on Windows blocking with a large input= (GH-142058) (#142069)
gh-87512: Fix `subprocess` using `timeout=` on Windows blocking with a large `input=` (GH-142058) On Windows, Popen._communicate() previously wrote to stdin synchronously, which could block indefinitely if the subprocess didn't consume input= quickly and the pipe buffer filled up. The timeout= parameter was only checked when joining the reader threads, not during the stdin write. This change moves the Windows stdin writing to a background thread (similar to how stdout/stderr are read in threads), allowing the timeout to be properly enforced. If timeout expires, TimeoutExpired is raised promptly and the writer thread continues in the background. Subsequent calls to communicate() will join the existing writer thread. Adds test_communicate_timeout_large_input to verify that TimeoutExpired is raised promptly when communicate() is called with large input and a timeout, even when the subprocess doesn't consume stdin quickly. This test already passed on POSIX (where select() is used) but failed on Windows where the stdin write blocks without checking the timeout. (cherry picked from commit 5b1862b) Co-authored-by: Gregory P. Smith <68491+gpshead@users.noreply.github.com> Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
1 parent c4df097 commit 1247113

File tree

3 files changed

+82
-2
lines changed

3 files changed

+82
-2
lines changed

Lib/subprocess.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1616,6 +1616,10 @@ def _readerthread(self, fh, buffer):
16161616
fh.close()
16171617

16181618

1619+
def _writerthread(self, input):
1620+
self._stdin_write(input)
1621+
1622+
16191623
def _communicate(self, input, endtime, orig_timeout):
16201624
# Start reader threads feeding into a list hanging off of this
16211625
# object, unless they've already been started.
@@ -1634,8 +1638,23 @@ def _communicate(self, input, endtime, orig_timeout):
16341638
self.stderr_thread.daemon = True
16351639
self.stderr_thread.start()
16361640

1637-
if self.stdin:
1638-
self._stdin_write(input)
1641+
# Start writer thread to send input to stdin, unless already
1642+
# started. The thread writes input and closes stdin when done,
1643+
# or continues in the background on timeout.
1644+
if self.stdin and not hasattr(self, "_stdin_thread"):
1645+
self._stdin_thread = \
1646+
threading.Thread(target=self._writerthread,
1647+
args=(input,))
1648+
self._stdin_thread.daemon = True
1649+
self._stdin_thread.start()
1650+
1651+
# Wait for the writer thread, or time out. If we time out, the
1652+
# thread remains writing and the fd left open in case the user
1653+
# calls communicate again.
1654+
if hasattr(self, "_stdin_thread"):
1655+
self._stdin_thread.join(self._remaining_time(endtime))
1656+
if self._stdin_thread.is_alive():
1657+
raise TimeoutExpired(self.args, orig_timeout)
16391658

16401659
# Wait for the reader threads, or time out. If we time out, the
16411660
# threads remain reading and the fds left open in case the user

Lib/test/test_subprocess.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,62 @@ def test_communicate_timeout_large_output(self):
10331033
(stdout, _) = p.communicate()
10341034
self.assertEqual(len(stdout), 4 * 64 * 1024)
10351035

1036+
def test_communicate_timeout_large_input(self):
1037+
# Test that timeout is enforced when writing large input to a
1038+
# slow-to-read subprocess, and that partial input is preserved
1039+
# for continuation after timeout (gh-141473).
1040+
#
1041+
# This is a regression test for Windows matching POSIX behavior.
1042+
# On POSIX, select() is used to multiplex I/O with timeout checking.
1043+
# On Windows, stdin writing must also honor the timeout rather than
1044+
# blocking indefinitely when the pipe buffer fills.
1045+
1046+
# Input larger than typical pipe buffer (4-64KB on Windows)
1047+
input_data = b"x" * (128 * 1024)
1048+
1049+
p = subprocess.Popen(
1050+
[sys.executable, "-c",
1051+
"import sys, time; "
1052+
"time.sleep(30); " # Don't read stdin for a long time
1053+
"sys.stdout.buffer.write(sys.stdin.buffer.read())"],
1054+
stdin=subprocess.PIPE,
1055+
stdout=subprocess.PIPE,
1056+
stderr=subprocess.PIPE)
1057+
1058+
try:
1059+
timeout = 0.2
1060+
start = time.monotonic()
1061+
try:
1062+
p.communicate(input_data, timeout=timeout)
1063+
# If we get here without TimeoutExpired, the timeout was ignored
1064+
elapsed = time.monotonic() - start
1065+
self.fail(
1066+
f"TimeoutExpired not raised. communicate() completed in "
1067+
f"{elapsed:.2f}s, but subprocess sleeps for 30s. "
1068+
"Stdin writing blocked without enforcing timeout.")
1069+
except subprocess.TimeoutExpired:
1070+
elapsed = time.monotonic() - start
1071+
1072+
# Timeout should occur close to the specified timeout value,
1073+
# not after waiting for the subprocess to finish sleeping.
1074+
# Allow generous margin for slow CI, but must be well under
1075+
# the subprocess sleep time.
1076+
self.assertLess(elapsed, 5.0,
1077+
f"TimeoutExpired raised after {elapsed:.2f}s; expected ~{timeout}s. "
1078+
"Stdin writing blocked without checking timeout.")
1079+
1080+
# After timeout, continue communication. The remaining input
1081+
# should be sent and we should receive all data back.
1082+
stdout, stderr = p.communicate()
1083+
1084+
# Verify all input was eventually received by the subprocess
1085+
self.assertEqual(len(stdout), len(input_data),
1086+
f"Expected {len(input_data)} bytes output but got {len(stdout)}")
1087+
self.assertEqual(stdout, input_data)
1088+
finally:
1089+
p.kill()
1090+
p.wait()
1091+
10361092
# Test for the fd leak reported in http://bugs.python.org/issue2791.
10371093
def test_communicate_pipe_fd_leak(self):
10381094
for stdin_pipe in (False, True):
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix :func:`subprocess.Popen.communicate` timeout handling on Windows
2+
when writing large input. Previously, the timeout was ignored during
3+
stdin writing, causing the method to block indefinitely if the child
4+
process did not consume input quickly. The stdin write is now performed
5+
in a background thread, allowing the timeout to be properly enforced.

0 commit comments

Comments
 (0)