Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

asyncio: a failed TCP_NODELAY leaves a stale transport registered, blocking its fd for every later connection (regression since 3.14.8) #162877

Backlog

Description

@jefffroman

Bug report

Bug description:

Summary

Since 3.14.8, if _make_socket_transport raises inside _create_connection_transport, the socket is closed (gh-153133). But _SelectorTransport.__init__ has already put the transport into loop._transports[fd], and it stays there, never marked closing. The fd number is now free at the OS level but blocked in asyncio. The kernel hands out the lowest free fd, so each later accepted or connected socket can land on that fd, fail _ensure_fd_no_transport with RuntimeError: File descriptor N is used by transport ..., and be dropped. On the accept path the error is only reported when the loop is in debug mode, so a server just resets every new client while established connections keep working.

The trigger is ordinary on macOS. _SelectorSocketTransport.__init__ calls base_events._set_nodelay() after registration, and setsockopt(TCP_NODELAY) fails with EINVAL on a socket whose peer has already sent RST.

Before 3.14.8 the same failure leaked the socket (fd still open), so the stale entry pointed at an fd nobody else could get. Closing the socket is what makes the stale entry harmful.

Reproducer (macOS; observed on 3.14.10, present since 3.14.8)

import asyncio, socket, struct, subprocess, time

def reset_socket():
    ls = socket.socket(); ls.bind(("127.0.0.1", 0)); ls.listen()
    s = socket.create_connection(ls.getsockname())
    c, _ = ls.accept(); ls.close()
    c.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)); c.close()
    time.sleep(0.05)
    return s

async def handle(r, w):
    await r.readline(); w.write(b"HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\nok"); await w.drain(); w.close()

async def curl(port):
    p = await asyncio.create_subprocess_exec("curl", "-s", "-m", "2", "-o", "/dev/null",
        "-w", "%{http_code}", f"http://127.0.0.1:{port}/", stdout=asyncio.subprocess.PIPE)
    out, _ = await p.communicate(); return f"exit={p.returncode} http={out.decode()}"

async def main():
    loop = asyncio.get_running_loop()
    srv = await asyncio.start_server(handle, "127.0.0.1", 0); port = srv.sockets[0].getsockname()[1]
    print("before:", await curl(port))
    s = reset_socket(); fd = s.fileno()
    try: await asyncio.open_connection(sock=s)
    except Exception as e: print("transport creation raised:", repr(e))
    t = loop._transports.get(fd)
    print(f"fd {fd}: socket closed={s.fileno() == -1}; registered={t!r} closing={t.is_closing()}")
    print("after:", await curl(port))

asyncio.run(main())

Output on 3.14.10, macOS (Darwin 25.6, arm64):

before: exit=0 http=200
transport creation raised: OSError(22, 'Invalid argument')
fd 8: socket closed=True; registered=<_SelectorSocketTransport fd=8 read=idle write=<idle, bufsize=0>> closing=False
after: exit=56 http=000

Seen in production

A long-running aiohttp + peer-to-peer daemon: after one peer reset mid-connect, its HTTP API and its listening port reset every new connection for ~20 hours. The process stayed up and existing connections kept working.

Suggested fix

Either of these, ideally both:

  • When a selector transport's __init__ fails after registration, unregister it (del loop._transports[fd] / server._detach) before the caller closes the socket.
  • Tolerate OSError from _set_nodelay. Nagle only matters on a live socket, and a dead one reports its reset on the first read.

Related

gh-153133, gh-155934 and gh-156365 close the socket when transport creation fails, which is right on its own, but none of them unregisters the transport, which is what turns a one-socket failure into a blocked fd. main still registers in _SelectorTransport.__init__ before _SelectorSocketTransport.__init__ calls _set_nodelay.

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs

Activity

  1. changed the title [-]asyncio: a failed TCP_NODELAY leaves a stale transport registered, blocking its fd for every later connection (3.14.10 regression)[/-] [+]asyncio: a failed TCP_NODELAY leaves a stale transport registered, blocking its fd for every later connection (regression since 3.14.8)[/+] on Nov 30, 2026
  2. jefffroman commented on Nov 30, 2026

    @jefffroman
    Author

    Correction to the original report: the socket-closing change from gh-153133 first shipped in 3.14.8, not 3.14.10, so 3.14.8 through 3.14.10 are affected. The title and body are updated. I'd attributed it to 3.14.10 because that's the version I first caught it on; the daemon had been running 3.14.8 and 3.14.9 for weeks before that, and the trigger depends on timing.

    A proposed fix, in the spirit of gh-153133: since the caller now closes the socket when transport construction fails, the transport should undo its own registration when anything after super().__init__() raises. Against 3.14.10's Lib/asyncio/selector_events.py:

             self._read_ready_cb = None
             super().__init__(loop, sock, protocol, extra, server)
    -        self._eof = False
    -        ...
    -        base_events._set_nodelay(self._sock)
    -        ...
    +        try:
    +            self._eof = False
    +            ...
    +            base_events._set_nodelay(self._sock)
    +            ...
    +        except BaseException:
    +            if self._loop._transports.get(self._sock_fd) is self:
    +                del self._loop._transports[self._sock_fd]
    +            if self._server is not None:
    +                self._server._detach(self)
    +                self._server = None
    +            raise

    (The ... lines are the rest of the existing __init__ body, unchanged and indented into the try.) With this applied, the reproducer leaves no stale transport, and test_selector_events, test_base_events, test_server, test_sock_lowlevel, test_streams and test_events all pass on 3.14.10/macOS. This fixes the defect for any exception in that window, not only TCP_NODELAY. A regression test could mock _set_nodelay to raise OSError and assert that loop._transports doesn't keep the fd.

  3. added
    stdlib
    type-bug
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-asynciotype-bug

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions