Repository navigation
Description
Bug report
On macOS, the multiprocessing forkserver exits when its listening socket is non-blocking and a client connects a moment before sending its request. The process being started then fails with BrokenPipeError, and the next one with ConnectionRefusedError.
How we ran into it. OpenDocKit converts each uploaded document in a fresh worker process started from the forkserver. One of its integrations runs under gevent, and a test there sends two requests at once. On the macOS CI runners that test lost a conversion now and then; on Linux it never did. Locally, on macOS under CPU load, 2 runs in 100 failed.
Why it happens.
ForkServer.ensure_running()creates the listening socket withsocket.socket(socket.AF_UNIX). When thesocketmodule has been monkey-patched (gevent and eventlet both do this), that socket is non-blocking at the OS level.- The forkserver wraps the inherited descriptor in a plain socket object, which assumes blocking mode.
- On macOS and the BSDs,
accept()passesO_NONBLOCKfrom the listening socket on to the accepted one. Linux does not. - If the client has connected but not written yet, the forkserver's first read — the authentication handshake, or
reduction.recvfds()on 3.12 and 3.13 — raisesBlockingIOError, and the forkserver exits.
Reproducer. No gevent needed; the subclass does what a patched socket module does:
import os, socket, time
from multiprocessing import forkserver
class NonBlockingSocket(socket.socket):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
os.set_blocking(self.fileno(), False)
if __name__ == "__main__":
original = socket.socket
socket.socket = NonBlockingSocket
forkserver.ensure_running()
socket.socket = original
server = forkserver._forkserver
with socket.socket(socket.AF_UNIX) as client:
client.connect(server._forkserver_address) # connected, nothing sent yet
time.sleep(0.5)
print("died" if os.waitpid(server._forkserver_pid, os.WNOHANG)[0] else "alive")On macOS this prints died on 3.12, 3.13, 3.14, 3.15 and main. On main the forkserver's traceback ends with:
File ".../multiprocessing/connection.py", line 417, in _recv
chunk = read(handle, to_read)
BlockingIOError: [Errno 35] Resource temporarily unavailable
On Linux the forkserver survives, because accept() there does not inherit O_NONBLOCK: the same check with gevent's patched sockets keeps it alive on Ubuntu with 3.12, 3.13 and 3.14.
Proposed fix. Make the accepted socket blocking in the forkserver before reading from it, with s.setblocking(True) right after listener.accept(). On Linux that changes nothing. I have a PR with this change and a test.
CPython versions tested on:
3.12, 3.13, 3.14, 3.15, CPython main branch
Operating systems tested on:
macOS, Linux
Activity