Skip to content

asyncio: writelines() on a full socket loses data with SelectorEventLoop on Windows (3.14) #162610

Backlog

Description

@alex-feel

Bug report

On Windows, a socket transport of asyncio.SelectorEventLoop loses data when writelines() is called while the socket is full: one buffered chunk never reaches the peer.

Where socket.socket has no sendmsg(), as on Windows, the transport writes through _SelectorSocketTransport._write_send(). It pops the head of the write buffer and calls send(), and when send() raises BlockingIOError the handler is except (BlockingIOError, InterruptedError): pass, so the popped item is gone. writelines() calls _write_ready() right after extending the buffer, so on a full socket it drops the head of the buffer. Linux writes through _write_sendmsg() and is not affected.

Reproducer: it fills a loopback socket with 1 MiB write() calls until data waits in the transport, then calls writelines().

import asyncio, os, socket, sys, threading

def serve(listener, go, received):
    conn, _ = listener.accept()
    with conn:
        go.wait(30)  # read nothing until the client has queued everything
        while data := conn.recv(65536):
            received += data

async def client(addr, go, sent):
    sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
    sock.connect(addr)
    _, writer = await asyncio.open_connection(sock=sock)
    for i in range(64):  # write 1 MiB chunks until the socket is full and data waits in the transport
        sent.append(os.urandom(1 << 20))
        writer.write(sent[-1])
        if writer.transport.get_write_buffer_size():
            break
    items = [os.urandom(1000) for i in range(4)]
    sent.extend(items)
    writer.writelines(items)
    go.set()  # let the server read everything
    await writer.drain()
    writer.close()
    await writer.wait_closed()

listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
listener.bind(("127.0.0.1", 0))
listener.listen()
go, received, sent = threading.Event(), bytearray(), []
server = threading.Thread(target=serve, args=(listener, go, received))
server.start()
loop = asyncio.SelectorEventLoop()
print(sys.version, type(loop).__name__)
loop.run_until_complete(client(listener.getsockname(), go, sent))
loop.close()
server.join()
sent = b"".join(sent)
print(f"sent {len(sent)} bytes, received {len(received)} bytes")
if received != sent:
    at = next((i for i, (a, b) in enumerate(zip(sent, received)) if a != b), len(received))
    print(f"lost {len(sent) - len(received)} bytes at offset {at}")

Output on 3.14.10:

3.14.10 (main, Nov 11 2026, 00:19:45) [MSC v.1944 64 bit (AMD64)] _WindowsSelectorEventLoop
sent 4198304 bytes, received 3149728 bytes
lost 1048576 bytes at offset 3145728

Output on 3.15.2:

3.15.2 (main, Nov 11 2026, 00:22:41) [MSC v.1951 64 bit (AMD64)] _WindowsSelectorEventLoop
sent 4198304 bytes, received 4198304 bytes

How many 1 MiB writes fit before the transport starts buffering varies between runs, so the totals and the offset vary too. 3.14.10 lost exactly 1048576 bytes in 19 of 20 runs and nothing in the other; 3.15.2 received everything in 20 of 20.

The fix is already on main and in 3.15: #146518 changed the handler to put the item back (self._buffer.appendleft(buffer), then return) as part of making get_write_buffer_size() O(1), and that change was not backported. The 3.14 branch still has pass.

I have a 3.14 pull request ready with that handler change and regression tests. The existing test_write_ready_tryagain compares the transport's buffer with itself, so it passes while the item is gone. A tests-only pull request for main is ready too.

CPython versions tested on:

3.14, 3.15

Operating systems tested on:

Windows

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Nov 25, 2026
  2. added
    3.14
    on Nov 25, 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

    3.14OS-windowsstdlibtopic-asynciotype-bug

    Projects

    • Status
      Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions