MagicStack / MagicStack/uvloop
`connect_read_pipe` double-closes the underlying fd, possibly closing an unrelated fd
还没有人认领这个 Issue。
- 主要语言
- Cython
- 星标
- 11.9k
- 派生
- 616
- PR 合并指标
- 30 天内没有已合并 PR
描述
In our production use of uvloop, we found sporadic cases of file descriptors being randomly closed. (For more details of our specific case, see skypilot-org/skypilot#10681).
We traced this back to loop.connect_read_pipe double-closing its file descriptor. When the fd was re-allocated between the first and second close, this caused an unrelated thread to have its fd closed out from under.
I used this script to check the double-close behavior:
import asyncio, io, os, sys
class BufferedReaderWithProbe(io.BufferedReader):
def close(self):
# Probe before status
fd = self.fileno()
print(f"closing {self} (fd {fd})")
try:
os.fstat(fd); fd_state = "still OPEN"
except OSError as e:
fd_state = f"already closed ({e.strerror})"
# Open a new pipe to see what fds we get
# Kernel should reuse lowest free number
newfd_reader, newfd_writer = os.pipe()
print(f" is fd {fd} already closed? {fd_state}")
print(f" fresh os.pipe() got fds {newfd_reader},{newfd_writer}")
# Do normal BufferedReader close
try:
print("calling BufferedReader.close")
super().close()
finally:
# Probe after status
print("Status after close:")
for fd in (newfd_reader, newfd_writer):
try:
os.fstat(fd); print(f" fresh fd {fd}: alive")
except OSError as e:
print(f" fresh fd {fd}: DEAD ({e.strerror}) <-- stolen")
async def main():
loop = asyncio.get_running_loop()
pipe_read_fd, pipe_write_fd = os.pipe()
probe_reader = BufferedReaderWithProbe(io.FileIO(pipe_read_fd, "rb"))
transport, _ = await loop.connect_read_pipe(asyncio.Protocol, probe_reader)
print(f"transport {type(transport).__name__} on fd {pipe_read_fd}")
transport.close()
if __name__ == "__main__":
if sys.argv[1:] == ["uvloop"]:
import uvloop; uvloop.install(); print(f"== uvloop {uvloop.__version__}")
else:
print(f"== stdlib asyncio {sys.version.split()[0]}")
asyncio.run(main())
$ python repro.py
== stdlib asyncio 3.10.16
transport _UnixReadPipeTransport on fd 6
closing <BufferedReaderWithProbe name=6> (fd 6)
is fd 6 already closed? still OPEN
fresh os.pipe() got fds 8,9
calling BufferedReader.close
Status after close:
fresh fd 8: alive
fresh fd 9: alive
$ python repro.py uvloop
== uvloop 0.22.1
transport ReadUnixTransport on fd 13
closing <BufferedReaderWithProbe name=13> (fd 13)
is fd 13 already closed? already closed (Bad file descriptor)
fresh os.pipe() got fds 13,16
calling BufferedReader.close
Status after close:
fresh fd 13: DEAD (Bad file descriptor) <-- stolen
fresh fd 16: alive
Here you can see that a asyncio event loop correctly leaves fd 6 open, allowing the underlying file object (in this case, our custom BufferedReader) to close the fd.
However, uvloop has already closed the fd, so when the file object is closed, it re-closes fd 13 which is now an unrelated os.pipe() fd.
This specific case was already fixed for sockets: https://github.com/MagicStack/uvloop/commit/d5195d7c10fbae81ef1dcb4609cee50f8aa746fa. It was assumed that the EBADF for non-sockets was benign, but it can actually be a problem if the underlying fd is reassigned before the _fileobj.close() can run.
You can observe the same behavior if the transport is not explicitly closed but is instead GC'd - although in this case it seems that the file object is closed before the uv_close call double-closes the fd. (The order is inverted.) This is actually the case we saw in prod.
It also looks like connect_write_pipe is similarly affected.
AI disclosure: This investigation was heavily assisted by AI tools, but this report was entirely human written without assistance except for the original repro script. The original repro script was then modified by me for clarity and manually validated.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从传输入口 connect_read_pipe 和 connect_write_pipe 开始,将它们的文件描述符清理行为与提交 d5195d7c10fbae81ef1dcb4609cee50f8aa746fa 中的 socket 修复进行比较。使用 uvloop 和标准 asyncio 循环运行提供的复现程序。完成标准是,关闭或垃圾回收任一管道传输都不会关闭无关的文件描述符。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- networking
- Issue 类型
- 缺陷
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 活跃
- 描述清晰度
- 描述清楚
- 新手友好度
- 68/100