Skip to content

gh-162016: asyncio: Stop busy-looping when a full pipe is reported as writable - #162426

Open
maurycy wants to merge 5 commits into
python:mainfrom
maurycy:gh-162016-asyncio-pipe-write-retry
Open

maurycy wants to merge 5 commits into
python:mainfrom
maurycy:gh-162016-asyncio-pipe-write-retry

Conversation

@maurycy

@maurycy maurycy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

On macOS, a full pipe can keep reporting that it is writable even though os.write() raises BlockingIOError. When this happens, asyncio retries the buffered write on every event loop iteration.

If the write-ready callback gets BlockingIOError, pause write notifications for 1 ms, then resume them if there is still data.

ref #162016 (comment)

Reproduction fix
maurycy@gimel asyncio-pipe-write-retry (gh-162016-asyncio-pipe-write-retry 3ef834f?) % ./python.exe repro.py 
write attempts: 2
received: b'x'
import asyncio
import errno
from unittest.mock import patch


async def main():
    p = await asyncio.create_subprocess_exec(
        "/bin/cat",
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
    )
    error = BlockingIOError(errno.EAGAIN, "would block")
    with patch("os.write", side_effect=error) as write:
        p.stdin.write(b"x")
        await asyncio.sleep(0.01)
        print("write attempts:", write.call_count)
    print("received:", (await p.communicate())[0])


asyncio.run(main())

@maurycy

maurycy commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

@gpshead This is the simplest approach, no need to track delay per transport and for a local pipe I think the extra retries during a long stall are a reasonable trade-off. With a fast reader, a fixed 1ms gives the same throughput as #162058 (0.5 MiB/s on my box.)

We have a similar pattern already:

self._remove_reader(sock.fileno())
self.call_later(constants.ACCEPT_RETRY_DELAY,
self._start_serving,
protocol_factory, sock, sslcontext, server,
backlog, ssl_handshake_timeout,
ssl_shutdown_timeout, context)

More than happy to switch to the adaptive backoff approach. Thank you!

@kumaraditya303

Copy link
Copy Markdown
Contributor

On macOS, a full pipe can keep reporting that it is writable even though os.write() raises BlockingIOError. When this happens, asyncio retries the buffered write on every event loop iteration.

Are the retries causing any real world issue? This is technically a macOS bug and I don't think this needs to be worked around in asyncio given that is not a correctness issue.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants