`asyncio` does not set `TCP_NODELAY` on macOS
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
On macOS, asyncio server silently skips setting TCP_NODELAY on accepted connections.
Reproduce
import asyncio
import socket
async def main():
async def on_connect(reader, writer):
sock = writer.transport.get_extra_info('socket')
nodelay = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)
print(f'server side: sock.proto={sock.proto} TCP_NODELAY={nodelay}')
writer.close()
await writer.wait_closed()
srv.close()
srv = await asyncio.start_server(on_connect, '127.0.0.1', 0)
port = srv.sockets[0].getsockname()[1]
reader, writer = await asyncio.open_connection('127.0.0.1', port)
sock = writer.transport.get_extra_info('socket')
nodelay = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY)
print(f'client side: sock.proto={sock.proto} TCP_NODELAY={nodelay}')
await asyncio.sleep(0.1)
writer.close()
await writer.wait_closed()
await srv.wait_closed()
asyncio.run(main())
| Platform | Side | sock.proto |
TCP_NODELAY |
|---|---|---|---|
| Linux | client | 6 ✅ | 1 ✅ |
| Linux | server | 6 ✅ | 1 ✅ |
| macOS | client | 6 ✅ | 4 ✅ |
| macOS | server | 0 ❌ | 0 ❌ |
Cause
In socket.__init__, CPython tries to detect proto with getsockopt + SO_PROTOCOL and falls back to 0 if SO_PROTOCOL is not supported, which is the case on macOS.
While socket.accept does pass in the proto from listening socket, it is silently overridden to zero by the above logic.
https://github.com/python/cpython/blob/82767780f8de2fc492567ceb6a590101ae3b19ad/Lib/socket.py#L300
asyncio sets TCP_NODELAY only when sock.proto == socket.IPPROTO_TCP, but it is 0 on macOS for the above reason.
Client socket works fine because no fd is passed to socket.__init__ so the proto detection doesn't happen.
CPython versions tested on:
3.13
Operating systems tested on:
macOS, Linux
Linked PRs
- gh-148784
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Review the linked implementation in Modules/socketmodule.c, Lib/socket.py, and Lib/asyncio/base_events.py, starting with socket.init and socket.accept. Check PR gh-148784 before beginning; done means accepted macOS connections receive the expected TCP protocol information and asyncio sets TCP_NODELAY consistently with client connections.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- networking
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100