Skip to content

Commit 1cc5802

Browse files
gh-162016: Fix communicate() hang when a full stdin pipe is reported writable (GH-162058)
On macOS and FreeBSD, poll() and select() can report a pipe as writable when a write to it would block. communicate() assumed a writable event meant a PIPE_BUF-sized write could not block... this works around that potential deadlock. Changes: Popen._communicate() makes stdin non-blocking while _communicate_io_posix() runs and restores blocking mode afterwards if stdin is still open. A resumed communicate() after TimeoutExpired and direct proc.stdin writes behave as before. _communicate_io_posix() handles BlockingIOError by taking stdin out of the selector for a delay that doubles from 1 ms to 50 ms and resets on the next successful write. A timed retry is needed because the kernel keeps reporting the full pipe as writable, so there is no event to wait for. The other pipes are still serviced during the delay, and activity on them ends it early. Nothing changes when the kernel reports readiness truthfully. In the affected state, a child that reads stdin but writes no output receives its input more slowly than with a blocking write. --------- Co-authored-by: Johnny Wilson Dougherty <192861341+JohnnyWilson16@users.noreply.github.com> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent 639c34b commit 1cc5802

3 files changed

Lines changed: 127 additions & 14 deletions

File tree

‎Lib/subprocess.py‎

Lines changed: 55 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -237,11 +237,17 @@ def __repr__(self):
237237

238238
__del__ = Close
239239
else:
240-
# When select or poll has indicated that the file is writable,
241-
# we can write up to _PIPE_BUF bytes without risk of blocking.
242-
# POSIX defines PIPE_BUF as >= 512.
240+
# Write at most _PIPE_BUF bytes per writable event. POSIX defines
241+
# PIPE_BUF as >= 512. Some platforms report a full pipe as writable,
242+
# so communicate() keeps stdin non-blocking while it writes.
243243
_PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
244244

245+
# A full pipe that is reported as writable gives no event to wait for,
246+
# so communicate() retries the write after a delay that doubles from
247+
# _STDIN_BACKOFF_MIN to _STDIN_BACKOFF_MAX seconds.
248+
_STDIN_BACKOFF_MIN = 0.001
249+
_STDIN_BACKOFF_MAX = 0.05
250+
245251
# poll/select have the advantage of not requiring any extra file
246252
# descriptor, contrarily to epoll/kqueue (also, they require a single
247253
# syscall).
@@ -282,30 +288,54 @@ def _communicate_io_posix(selector, stdin, input_view, input_offset,
282288
- Appends to output_buffers lists in place
283289
"""
284290
stdin_fd = stdin.fileno() if stdin else None
285-
286-
while selector.get_map():
291+
# Seconds to keep stdin out of the selector after a write that
292+
# would have blocked; 0 when stdin is registered or finished.
293+
stdin_backoff = 0
294+
# The previous such delay, which the next one doubles. A
295+
# successful write resets it.
296+
stdin_paused_for = _STDIN_BACKOFF_MIN / 2
297+
298+
while selector.get_map() or stdin_backoff:
287299
remaining = _deadline_remaining(endtime)
288300
if remaining is not None and remaining <= 0:
289301
return (input_offset, False) # Timed out
290302

291-
ready = selector.select(remaining)
303+
if stdin_backoff and (remaining is None
304+
or stdin_backoff < remaining):
305+
ready = selector.select(stdin_backoff)
306+
else:
307+
ready = selector.select(remaining)
292308

293309
# Check timeout after select (may have woken spuriously)
294310
if endtime is not None and _time() > endtime:
295311
return (input_offset, False) # Timed out
296312

313+
if stdin_backoff:
314+
# The wait is over or the child made progress on another
315+
# pipe. Either way, ask about stdin again.
316+
selector.register(stdin, selectors.EVENT_WRITE)
317+
stdin_paused_for, stdin_backoff = stdin_backoff, 0
318+
297319
for key, events in ready:
298320
if key.fd == stdin_fd:
299321
chunk = input_view[input_offset:input_offset + _PIPE_BUF]
300322
try:
301323
input_offset += os.write(key.fd, chunk)
324+
except BlockingIOError:
325+
# The pipe was reported writable but is full, and
326+
# will be reported writable again right away. Stop
327+
# asking for a while instead of spinning.
328+
selector.unregister(key.fd)
329+
stdin_backoff = min(stdin_paused_for * 2,
330+
_STDIN_BACKOFF_MAX)
302331
except BrokenPipeError:
303332
selector.unregister(key.fd)
304333
try:
305334
stdin.close()
306335
except BrokenPipeError:
307336
pass
308337
else:
338+
stdin_paused_for = _STDIN_BACKOFF_MIN / 2
309339
if input_offset >= len(input_view):
310340
selector.unregister(key.fd)
311341
try:
@@ -2430,17 +2460,28 @@ def _communicate(self, input, endtime, orig_timeout):
24302460

24312461
stdin_to_write = (self.stdin if self.stdin and self._input
24322462
and not self.stdin.closed else None)
2463+
if stdin_to_write is not None:
2464+
# poll() and select() can report a pipe as writable
2465+
# when it has no free space (gh-162016). A blocking
2466+
# write() would then hang past the timeout.
2467+
os.set_blocking(stdin_to_write.fileno(), False)
2468+
try:
2469+
new_offset, completed = _communicate_io_posix(
2470+
selector,
2471+
stdin_to_write,
2472+
input_view,
2473+
input_offset,
2474+
self._fileobj2output,
2475+
endtime,
2476+
close_on_eof=True)
2477+
finally:
2478+
# Code that uses self.stdin after communicate() returns
2479+
# or times out expects writes to it to block.
2480+
if stdin_to_write is not None and not stdin_to_write.closed:
2481+
os.set_blocking(stdin_to_write.fileno(), True)
24332482
# Persist the returned offset on self so a subsequent
24342483
# communicate() after a TimeoutExpired resumes mid-input
24352484
# rather than re-sending bytes the child already consumed.
2436-
new_offset, completed = _communicate_io_posix(
2437-
selector,
2438-
stdin_to_write,
2439-
input_view,
2440-
input_offset,
2441-
self._fileobj2output,
2442-
endtime,
2443-
close_on_eof=True)
24442485
if self._input:
24452486
self._input_offset = new_offset
24462487

‎Lib/test/test_subprocess.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3590,6 +3590,74 @@ def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
35903590
proc.communicate(timeout=999)
35913591
mock_proc_stdin.close.assert_called_once_with()
35923592

3593+
def _spuriously_writable_selector(self):
3594+
# A selector that reports stdin as writable whenever it is
3595+
# registered. poll() on macOS and FreeBSD can do this for a full
3596+
# pipe when many pipes are in use system-wide (gh-162016).
3597+
class AlwaysWritableSelector(subprocess._PopenSelector):
3598+
spurious_events = 0
3599+
3600+
def select(self, timeout=None):
3601+
ready = super().select(0)
3602+
writable = {key.fd for key, events in ready
3603+
if events & selectors.EVENT_WRITE}
3604+
for key in self.get_map().values():
3605+
if (key.events & selectors.EVENT_WRITE
3606+
and key.fd not in writable):
3607+
ready.append((key, selectors.EVENT_WRITE))
3608+
type(self).spurious_events += 1
3609+
return ready or super().select(timeout)
3610+
3611+
return AlwaysWritableSelector
3612+
3613+
def test_communicate_timeout_stdin_spuriously_writable(self):
3614+
# The child never reads stdin, so the pipe fills up. communicate()
3615+
# must neither block in write() past its timeout nor spin on a pipe
3616+
# that keeps being reported as writable.
3617+
selector = self._spuriously_writable_selector()
3618+
sleep = support.SHORT_TIMEOUT
3619+
with mock.patch.object(subprocess, '_PopenSelector', selector), \
3620+
subprocess.Popen([sys.executable, '-c',
3621+
f'import time; time.sleep({sleep})'],
3622+
stdin=subprocess.PIPE,
3623+
stdout=subprocess.PIPE) as proc:
3624+
try:
3625+
start = time.monotonic()
3626+
with self.assertRaises(subprocess.TimeoutExpired):
3627+
proc.communicate(b'x' * support.PIPE_MAX_SIZE,
3628+
timeout=0.5)
3629+
self.assertLess(time.monotonic() - start, sleep)
3630+
# communicate() must wait between attempts to write to a
3631+
# full pipe. Retrying in a busy loop would produce many
3632+
# thousands of these events within the timeout.
3633+
self.assertLess(selector.spurious_events, 100)
3634+
self.assertTrue(os.get_blocking(proc.stdin.fileno()))
3635+
finally:
3636+
proc.kill()
3637+
3638+
def test_communicate_stdin_spuriously_writable_last_pipe(self):
3639+
# All input must still arrive when stdin is full, is reported as
3640+
# writable, and is the only pipe communicate() has left to service.
3641+
selector = self._spuriously_writable_selector()
3642+
data = bytes(range(256)) * (support.PIPE_MAX_SIZE // 256)
3643+
code = textwrap.dedent(f"""
3644+
import os, sys, time
3645+
os.close(1)
3646+
time.sleep(0.1) # Let the parent fill the stdin pipe.
3647+
data = bytes(range(256)) * {len(data) // 256}
3648+
sys.exit(sys.stdin.buffer.read() != data)
3649+
""")
3650+
with mock.patch.object(subprocess, '_PopenSelector', selector), \
3651+
subprocess.Popen([sys.executable, '-c', code],
3652+
stdin=subprocess.PIPE,
3653+
stdout=subprocess.PIPE) as proc:
3654+
try:
3655+
proc.communicate(data, timeout=support.SHORT_TIMEOUT)
3656+
self.assertEqual(proc.returncode, 0)
3657+
self.assertGreater(selector.spurious_events, 0)
3658+
finally:
3659+
proc.kill()
3660+
35933661
@unittest.skipUnless(_testcapi is not None
35943662
and hasattr(_testcapi, 'W_STOPCODE'),
35953663
'need _testcapi.W_STOPCODE')
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix :meth:`subprocess.Popen.communicate` hanging or blocking past its
2+
*timeout* while writing to the child's stdin on macOS and FreeBSD. This
3+
works around a kernel bug most likely seen on loaded hosts with many pipes
4+
in active use at once.

0 commit comments

Comments
 (0)