Skip to content

Commit 13854ae

Browse files
JohnnyWilson16gpshead
authored andcommitted
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. --------- (cherry picked from commit 1cc5802) Co-authored-by: Johnny Wilson Dougherty <johnnydougherty09@gmail.com> Co-authored-by: Johnny Wilson Dougherty <192861341+JohnnyWilson16@users.noreply.github.com> Co-authored-by: Gregory P. Smith <greg@krypto.org>
1 parent e251753 commit 13854ae

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:
@@ -2406,17 +2436,28 @@ def _communicate(self, input, endtime, orig_timeout):
24062436

24072437
stdin_to_write = (self.stdin if self.stdin and self._input
24082438
and not self.stdin.closed else None)
2439+
if stdin_to_write is not None:
2440+
# poll() and select() can report a pipe as writable
2441+
# when it has no free space (gh-162016). A blocking
2442+
# write() would then hang past the timeout.
2443+
os.set_blocking(stdin_to_write.fileno(), False)
2444+
try:
2445+
new_offset, completed = _communicate_io_posix(
2446+
selector,
2447+
stdin_to_write,
2448+
input_view,
2449+
input_offset,
2450+
self._fileobj2output,
2451+
endtime,
2452+
close_on_eof=True)
2453+
finally:
2454+
# Code that uses self.stdin after communicate() returns
2455+
# or times out expects writes to it to block.
2456+
if stdin_to_write is not None and not stdin_to_write.closed:
2457+
os.set_blocking(stdin_to_write.fileno(), True)
24092458
# Persist the returned offset on self so a subsequent
24102459
# communicate() after a TimeoutExpired resumes mid-input
24112460
# rather than re-sending bytes the child already consumed.
2412-
new_offset, completed = _communicate_io_posix(
2413-
selector,
2414-
stdin_to_write,
2415-
input_view,
2416-
input_offset,
2417-
self._fileobj2output,
2418-
endtime,
2419-
close_on_eof=True)
24202461
if self._input:
24212462
self._input_offset = new_offset
24222463

‎Lib/test/test_subprocess.py‎

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

3578+
def _spuriously_writable_selector(self):
3579+
# A selector that reports stdin as writable whenever it is
3580+
# registered. poll() on macOS and FreeBSD can do this for a full
3581+
# pipe when many pipes are in use system-wide (gh-162016).
3582+
class AlwaysWritableSelector(subprocess._PopenSelector):
3583+
spurious_events = 0
3584+
3585+
def select(self, timeout=None):
3586+
ready = super().select(0)
3587+
writable = {key.fd for key, events in ready
3588+
if events & selectors.EVENT_WRITE}
3589+
for key in self.get_map().values():
3590+
if (key.events & selectors.EVENT_WRITE
3591+
and key.fd not in writable):
3592+
ready.append((key, selectors.EVENT_WRITE))
3593+
type(self).spurious_events += 1
3594+
return ready or super().select(timeout)
3595+
3596+
return AlwaysWritableSelector
3597+
3598+
def test_communicate_timeout_stdin_spuriously_writable(self):
3599+
# The child never reads stdin, so the pipe fills up. communicate()
3600+
# must neither block in write() past its timeout nor spin on a pipe
3601+
# that keeps being reported as writable.
3602+
selector = self._spuriously_writable_selector()
3603+
sleep = support.SHORT_TIMEOUT
3604+
with mock.patch.object(subprocess, '_PopenSelector', selector), \
3605+
subprocess.Popen([sys.executable, '-c',
3606+
f'import time; time.sleep({sleep})'],
3607+
stdin=subprocess.PIPE,
3608+
stdout=subprocess.PIPE) as proc:
3609+
try:
3610+
start = time.monotonic()
3611+
with self.assertRaises(subprocess.TimeoutExpired):
3612+
proc.communicate(b'x' * support.PIPE_MAX_SIZE,
3613+
timeout=0.5)
3614+
self.assertLess(time.monotonic() - start, sleep)
3615+
# communicate() must wait between attempts to write to a
3616+
# full pipe. Retrying in a busy loop would produce many
3617+
# thousands of these events within the timeout.
3618+
self.assertLess(selector.spurious_events, 100)
3619+
self.assertTrue(os.get_blocking(proc.stdin.fileno()))
3620+
finally:
3621+
proc.kill()
3622+
3623+
def test_communicate_stdin_spuriously_writable_last_pipe(self):
3624+
# All input must still arrive when stdin is full, is reported as
3625+
# writable, and is the only pipe communicate() has left to service.
3626+
selector = self._spuriously_writable_selector()
3627+
data = bytes(range(256)) * (support.PIPE_MAX_SIZE // 256)
3628+
code = textwrap.dedent(f"""
3629+
import os, sys, time
3630+
os.close(1)
3631+
time.sleep(0.1) # Let the parent fill the stdin pipe.
3632+
data = bytes(range(256)) * {len(data) // 256}
3633+
sys.exit(sys.stdin.buffer.read() != data)
3634+
""")
3635+
with mock.patch.object(subprocess, '_PopenSelector', selector), \
3636+
subprocess.Popen([sys.executable, '-c', code],
3637+
stdin=subprocess.PIPE,
3638+
stdout=subprocess.PIPE) as proc:
3639+
try:
3640+
proc.communicate(data, timeout=support.SHORT_TIMEOUT)
3641+
self.assertEqual(proc.returncode, 0)
3642+
self.assertGreater(selector.spurious_events, 0)
3643+
finally:
3644+
proc.kill()
3645+
35783646
@unittest.skipUnless(_testcapi is not None
35793647
and hasattr(_testcapi, 'W_STOPCODE'),
35803648
'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)