python / python/cpython

`asyncio` does not set `TCP_NODELAY` on macOS

未关闭
#148,783 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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.

https://github.com/python/cpython/blob/82767780f8de2fc492567ceb6a590101ae3b19ad/Modules/socketmodule.c#L5749-L5764

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.

https://github.com/python/cpython/blob/82767780f8de2fc492567ceb6a590101ae3b19ad/Lib/asyncio/base_events.py#L193-L201

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

检查 Modules/socketmodule.c、Lib/socket.py 和 Lib/asyncio/base_events.py 中链接的实现,从 socket.init 和 socket.accept 开始。在开始之前检查 PR gh-148784;完成的标准是,macOS 接受的连接能够收到预期的 TCP 协议信息,并且 asyncio 与客户端连接一致地设置 TCP_NODELAY。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
networking
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。