aiohttp icon indicating copy to clipboard operation
aiohttp copied to clipboard

Unretrieved "Cannot write to closing transport" exception from the shielded WebSocket send task when the sender is cancelled

Open cerealkiller57540 opened this issue 1 month ago • 3 comments

Describe the bug

Since #11726, WebSocketWriter.send_frame() sends compressed frames larger than 16 KiB from a separate send_task and awaits it through asyncio.shield(). The only done-callback on that task is self._background_tasks.discard:

https://github.com/aio-libs/aiohttp/blob/f17c631bddcfd4ec712342db28f1d3381a3fec71/aiohttp/_websocket/writer.py#L114-L117

If the task that called send_str() is cancelled while send_task is still running (for instance while the frame is being compressed in the executor) and the peer goes away in the meantime, send_task fails with ClientConnectionResetError("Cannot write to closing transport") and nothing retrieves that exception: shield() removes its done-callback from the inner task once the outer future is cancelled, and discard ignores the result. asyncio then reports it through the loop exception handler:

  • Python 3.11 to 3.13: Task exception was never retrieved, when the task is garbage collected (measured on 3.11.0; 3.12 and 3.13 have the same shield() code);
  • Python 3.14.0 to 3.14.8: ClientConnectionResetError exception in shielded future, logged by shield() itself (python/cpython#156321);
  • the 3.14 branch after python/cpython#158599, which is not in 3.14.8: Task exception was never retrieved again.

So the 3.14 regression only changes the message. The unretrieved exception comes from the writer and is reported on all the versions above.

To Reproduce

  1. pip install aiohttp==3.14.5
  2. Save the script below as repro.py.
  3. Run python repro.py cancel, then python repro.py nocancel.

The handler sends a 64 KiB text message from a separate task, so it takes the compressed, shielded path, while a raw client negotiates permessage-deflate and drops the connection with a RST. The only patch to aiohttp is a 0.3 s delay in ZLibCompressor.compress(), so the peer is reliably gone by the time the frame is written; without it the race only triggers now and then. In cancel mode the handler cancels the sending task once the connection is closed; nocancel awaits it instead, as a control.

"""The exception of the shielded compressed-send task is never retrieved when the
task calling send_str() is cancelled after the peer went away.

    python repro.py [cancel|nocancel]

cancel   : the task calling send_str() is cancelled once the connection is closed.
nocancel : control, the task calling send_str() is awaited instead.
"""

import asyncio
import base64
import gc
import os
import socket
import struct
import sys

import aiohttp
from aiohttp import web
from aiohttp._websocket import writer as ws_writer

MODE = sys.argv[1] if len(sys.argv) > 1 else "cancel"
logged = []
caller = []

# Frames larger than 16 KiB are compressed in an executor inside a shielded task.
# Delay the compression so the peer is reliably gone by the time the frame is
# written; without this the race only triggers occasionally.
_compress = ws_writer.ZLibCompressor.compress


async def slow_compress(self, data):
    await asyncio.sleep(0.3)
    return await _compress(self, data)


ws_writer.ZLibCompressor.compress = slow_compress


async def handler(request: web.Request) -> web.WebSocketResponse:
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    payload = base64.b64encode(os.urandom(48 * 1024)).decode()  # 64 KiB
    sender = asyncio.create_task(ws.send_str(payload))
    async for _ in ws:
        pass
    if MODE == "cancel":
        sender.cancel()
    try:
        await sender
    except asyncio.CancelledError:
        caller.append("cancelled")
    except Exception as exc:
        caller.append(f"got {exc!r}")
    else:
        caller.append("no error")
    return ws


async def connect_and_reset(port: int) -> None:
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    key = base64.b64encode(os.urandom(16)).decode()
    writer.write(
        f"GET /ws HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUpgrade: websocket\r\n"
        f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
        "Sec-WebSocket-Version: 13\r\n"
        "Sec-WebSocket-Extensions: permessage-deflate\r\n\r\n".encode()
    )
    head = await reader.readuntil(b"\r\n\r\n")
    assert b" 101 " in head and b"permessage-deflate" in head.lower(), head
    await asyncio.sleep(0.05)
    # Drop the connection with a RST while the server is still compressing.
    sock = writer.get_extra_info("socket")
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
    writer.transport.abort()


async def main() -> None:
    loop = asyncio.get_running_loop()
    loop.set_exception_handler(
        lambda _loop, ctx: logged.append(f"{ctx['message']}: {ctx.get('exception')!r}")
    )
    app = web.Application()
    app.router.add_get("/ws", handler)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, "127.0.0.1", 0)
    await site.start()
    await connect_and_reset(runner.addresses[0][1])
    await asyncio.sleep(1)
    # "Task exception was never retrieved" is only reported once the task is collected.
    for _ in range(3):
        gc.collect()
        await asyncio.sleep(0.1)
    await runner.cleanup()
    print(f"Python {sys.version.split()[0]}, aiohttp {aiohttp.__version__}, mode={MODE}")
    print(f"  caller           : {', '.join(caller) or '-'}")
    print(f"  logged by asyncio: {'; '.join(logged) or 'nothing'}")


asyncio.run(asyncio.wait_for(main(), 15))
Python cancel nocancel (control)
3.11.0 Task exception was never retrieved the caller gets the exception, nothing logged
3.14.4 ClientConnectionResetError exception in shielded future the caller gets the exception, nothing logged
3.14.4, asyncio.tasks._log_on_exception replaced by a no-op (what python/cpython#158599 removes) Task exception was never retrieved not run

All with aiohttp 3.14.5; aiohttp 3.14.4 gives the same results on Python 3.14.4. Repeated runs give the same results.

Raw output
$ python repro.py cancel
Python 3.11.0, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: Task exception was never retrieved: ClientConnectionResetError('Cannot write to closing transport')
$ python repro.py nocancel
Python 3.11.0, aiohttp 3.14.5, mode=nocancel
  caller           : got ClientConnectionResetError('Cannot write to closing transport')
  logged by asyncio: nothing
$ python repro.py cancel
Python 3.14.4, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: ClientConnectionResetError exception in shielded future: ClientConnectionResetError('Cannot write to closing transport')
$ python repro.py nocancel
Python 3.14.4, aiohttp 3.14.5, mode=nocancel
  caller           : got ClientConnectionResetError('Cannot write to closing transport')
  logged by asyncio: nothing
$ python repro.py cancel
Python 3.14.4, aiohttp 3.14.4, mode=cancel
  caller           : cancelled
  logged by asyncio: ClientConnectionResetError exception in shielded future: ClientConnectionResetError('Cannot write to closing transport')
$ python repro.py nocancel
Python 3.14.4, aiohttp 3.14.4, mode=nocancel
  caller           : got ClientConnectionResetError('Cannot write to closing transport')
  logged by asyncio: nothing
$ python -c "import asyncio.tasks, runpy, sys; asyncio.tasks._log_on_exception = lambda fut: None; sys.argv = ['repro.py', 'cancel']; runpy.run_path('repro.py', run_name='__main__')"
Python 3.14.4, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: Task exception was never retrieved: ClientConnectionResetError('Cannot write to closing transport')

Expected behavior

When the task that called send_str() has been cancelled, nobody is left to receive the send error and the peer is already gone, so nothing should reach the loop exception handler. A caller that is not cancelled should keep getting the exception, as it does today.

Logs/tracebacks

From a Home Assistant 2026.10.1 instance (aiohttp 3.14.4, Python 3.14). Home Assistant cancels its websocket writer task in some cases, for example on shutdown or when a client can't keep up with pending messages; the trigger for these particular entries was not identified. Both messages appear, with the same traceback:

2026-10-15 15:40:18.386 ERROR (MainThread) [homeassistant] Error doing job: ClientConnectionResetError exception in shielded future (task: None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.14/site-packages/aiohttp/_websocket/writer.py", line 247, in _send_compressed_frame_async_locked
    self._write_websocket_frame(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        (
        ^
    ...<8 lines>...
        0x40,
        ^^^^^
    )
    ^
  File "/usr/local/lib/python3.14/site-packages/aiohttp/_websocket/writer.py", line 158, in _write_websocket_frame
    raise ClientConnectionResetError("Cannot write to closing transport")
aiohttp.client_exceptions.ClientConnectionResetError: Cannot write to closing transport
2026-10-15 15:41:13.633 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (task: None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.14/site-packages/aiohttp/_websocket/writer.py", line 247, in _send_compressed_frame_async_locked
    self._write_websocket_frame(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        (
        ^
    ...<8 lines>...
        0x40,
        ^^^^^
    )
    ^
  File "/usr/local/lib/python3.14/site-packages/aiohttp/_websocket/writer.py", line 158, in _write_websocket_frame
    raise ClientConnectionResetError("Cannot write to closing transport")
aiohttp.client_exceptions.ClientConnectionResetError: Cannot write to closing transport

Python Version

$ python --version
Python 3.14.4

Also reproduced with Python 3.11.0.

aiohttp Version

$ python -m pip show aiohttp
Name: aiohttp
Version: 3.14.5

Also reproduced with aiohttp 3.14.4.

multidict Version

$ python -m pip show multidict
Name: multidict
Version: 7.1.0

propcache Version

$ python -m pip show propcache
Name: propcache
Version: 0.5.4

yarl Version

$ python -m pip show yarl
Name: yarl
Version: 1.25.1

OS

Windows 11 for the reproducer, same results with ProactorEventLoop and SelectorEventLoop; Linux (Home Assistant OS) for the production log above.

Related component

Server

WebSocketWriter is shared with ClientWebSocketResponse, so the client is probably affected too; only the server side was reproduced.

Additional context

A possible fix, in the spirit of _ping_task_done() (#8433): retrieve the exception in the done-callback of send_task. The diff is against v3.14.5; master has the same lines.

--- a/aiohttp/_websocket/writer.py
+++ b/aiohttp/_websocket/writer.py
@@ -113,7 +113,7 @@
                 send_task = asyncio.create_task(coro)
             # Keep a strong reference to prevent garbage collection
             self._background_tasks.add(send_task)
-            send_task.add_done_callback(self._background_tasks.discard)
+            send_task.add_done_callback(self._send_task_done)
             await asyncio.shield(send_task)
 
         # It is safe to return control to the event loop when using compression
@@ -128,6 +128,13 @@
             if self.protocol._paused:
                 await self.protocol._drain_helper()
 
+    def _send_task_done(self, task: "asyncio.Task[None]") -> None:
+        self._background_tasks.discard(task)
+        # The caller may have been cancelled while the shielded send was
+        # still running; nobody else will retrieve the exception then.
+        if not task.cancelled():
+            task.exception()
+
     def _write_websocket_frame(self, message: bytes, opcode: int, rsv: int) -> None:
         """
         Write a websocket frame to the transport.

With this patch applied to an installed aiohttp 3.14.5:

Python cancel nocancel
3.11.0 nothing logged the caller gets the exception, nothing logged
3.14.4 still ClientConnectionResetError exception in shielded future the caller gets the exception, nothing logged
3.14.4, _log_on_exception replaced by a no-op nothing logged not run
Raw output with the patch
$ python repro.py cancel
Python 3.11.0, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: nothing
$ python repro.py nocancel
Python 3.11.0, aiohttp 3.14.5, mode=nocancel
  caller           : got ClientConnectionResetError('Cannot write to closing transport')
  logged by asyncio: nothing
$ python repro.py cancel
Python 3.14.4, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: ClientConnectionResetError exception in shielded future: ClientConnectionResetError('Cannot write to closing transport')
$ python repro.py nocancel
Python 3.14.4, aiohttp 3.14.5, mode=nocancel
  caller           : got ClientConnectionResetError('Cannot write to closing transport')
  logged by asyncio: nothing
$ python -c "import asyncio.tasks, runpy, sys; asyncio.tasks._log_on_exception = lambda fut: None; sys.argv = ['repro.py', 'cancel']; runpy.run_path('repro.py', run_name='__main__')"
Python 3.14.4, aiohttp 3.14.5, mode=cancel
  caller           : cancelled
  logged by asyncio: nothing

On 3.14.0 to 3.14.8 the remaining message comes from shield() itself: _log_on_exception logs the inner exception whether or not anything else retrieves it, so aiohttp can't silence it. It goes away with python/cpython#158599.

If you'd rather keep unexpected errors visible, the callback could pass anything that is not a ConnectionError to loop.call_exception_handler() instead of dropping it.

There is also a narrower window on 3.14.x. If the caller is cancelled after send_task has failed but before its done-callbacks have run, shield()'s inner callback returns early without retrieving the exception, so it is reported as Task exception was never retrieved even on 3.14.0 to 3.14.8. This is probably where the second message in the log above comes from; 3.11 retrieves the exception in that case. Forcing this window locally (a wrapper around _send_compressed_frame_async_locked cancels the caller just before re-raising) gives Task exception was never retrieved on 3.14.4 and nothing with the patch above; 3.11.0 logs nothing either way.

Related: #12281, fixed by #12307, the same kind of problem with shield() in _drain_helper.

Code of Conduct

  • [X] I agree to follow the aio-libs Code of Conduct

Drafted with Claude Code (Claude Opus 5.5). All results above come from local runs.

cerealkiller57540 avatar Oct 16 '26 10:10 cerealkiller57540

Your diagnosis of the mechanism is right, and I can confirm it empirically — plus I think the fix belongs in the done-callback rather than around the shield().

Reproduced

Minimal model of the current code — bg is self._background_tasks, the discard callback is the strong-reference drop, and cancelling outer() stands in for the send_str() caller being cancelled while the frame compresses:

import asyncio, gc

async def scenario():
    loop = asyncio.get_running_loop()
    seen = []
    loop.set_exception_handler(lambda l, c: seen.append(c.get("message")))
    bg = set()                                    # self._background_tasks

    async def inner():
        await asyncio.sleep(0.01)                 # compression in the executor
        raise RuntimeError("Cannot write to closing transport")

    async def outer():
        t = asyncio.create_task(inner())
        bg.add(t)
        t.add_done_callback(bg.discard)           # <-- the drop
        await asyncio.shield(t)

    o = asyncio.create_task(outer())
    await asyncio.sleep(0.005)                    # inner is in flight
    o.cancel()                                    # send_str() caller cancelled
    await asyncio.sleep(0.05)
    gc.collect()
    await asyncio.sleep(0.05)
    return seen

print(asyncio.run(scenario()))
# ['Task exception was never retrieved']

Confirmed on CPython 3.13 with main at 9af1fce6. The detail worth recording: the leak needs both the shield to be abandoned and GC to run. My first attempt at this repro didn't leak, because the Task was still referenced at handler time. It only surfaces once discard removes the last strong reference and the task is collected — which is why this shows up intermittently in production rather than every time.

Suggested fix

Retrieve in the done-callback, keeping the discard:

def _send_task_done(self, task: asyncio.Task[None]) -> None:
    self._background_tasks.discard(task)
    if not task.cancelled():
        task.exception()

self._background_tasks.add(send_task)
send_task.add_done_callback(self._send_task_done)
await asyncio.shield(send_task)

Verified against the same harness:

def done(t):
    bg.discard(t)
    if not t.cancelled():
        t.exception()
...
# WITH retrieve: []

task.exception() marks the failure as observed and returns it; nobody wants it here because the outer awaiter is already gone, and the connection is unusable by definition (the error is ClientConnectionResetError).

One subtlety: add_done_callback is invoked through loop.call_soon, so if the caller of send_frame is still awaiting, retrieval happens before the await asyncio.shield(send_task) resumes. That is harmless — the shield still delivers the exception to the real awaiter, shield() has already installed its own _inner_done_callback, and Task.exception() does not consume anything for other getters.

On the eager-start interaction

Worth noting that eager_start=True on 3.12+ shrinks the window but doesn't close it. With eager start the coroutine runs to its first suspension immediately; if the peer is already gone the ClientConnectionResetError can still be raised at transport.write() after the executor hop, which is past the eager segment. So the leak remains reachable on 3.12–3.14 and the callback fix is still needed.

Tests

Three worth adding to tests/test_websocket_writer.py, all deterministic with no real socket:

  1. Exception retrieval — the harness above against WebSocketWriter directly: patch _send_compressed_frame_async_locked to sleep then raise, cancel the awaiting task mid-flight, gc.collect(), assert the loop exception handler recorded nothing.
  2. Normal completion still propagates — a successful shielded send with a cancelled awaiter must not raise, and the frame must still land (the shield is load-bearing; this guards against a fix that breaks atomicity).
  3. _background_tasks is drained — after the fix the set should be empty, so no task is retained forever on a long-lived connection.

For (1), the _closing guard at the top of send_frame() gives a cheaper trigger: set writer._closing = True after scheduling, so the write raises without needing a dead peer.

Relation to #14079

I posted on #14079, which is the same failure mode on the client side: a writer task holding an exception loses its last reference (ClientRequest._terminate() drops _writer_task without retrieving). Same root cause, different subsystem. A shared internal helper — something like _discard_and_retrieve(task) in aiohttp/helpers.py — would cover both the websocket discard callback and the client teardown path, and keep the two from drifting.

wahajahmed010 avatar Oct 20 '26 08:10 wahajahmed010

I'd like to work on this — retrieving the exception in the send task's done-callback so a cancelled sender plus dead peer doesn't leave an unretrieved exception.

rinopatrick avatar Nov 02 '26 06:11 rinopatrick

Confirming this from a real application, in case it helps prioritising #14063.

Home Assistant hits this regularly. The same traceback (_send_compressed_frame_async_locked → _write_websocket_frame → ClientConnectionResetError: Cannot write to closing transport, reported by the loop exception handler as "Task exception was never retrieved") is in home-assistant/core#188681 and #188417 (aiohttp 3.14.5). It was already reported with aiohttp 3.13.4 in home-assistant/core#166875 (April 2026), so it predates 3.14 and fits the change in #11726.

Home Assistant's websocket handler awaits send_frame() in a writer task and cancels that task when it closes a connection (shutdown, a client that can't keep up, a revoked token). So the "sender is cancelled while the compressed frame is in flight" case in this issue is not rare for a server like this.

I reproduced it end to end in a real Home Assistant (current dev, aiohttp 3.14.5, Python 3.14.9): a client requests a large result, the server cancels the connection's writer and the client resets the connection while the frame is being compressed (I delayed the compression to widen the window). That produces exactly the traceback above. With a done-callback that retrieves the exception (discard, then task.exception() if the task wasn't cancelled, as in #14063) nothing is logged anymore.

On Python 3.14.9 the message is "Task exception was never retrieved", not "exception in shielded future", which matches what is described above for the 3.14 branch after python/cpython#158599.

The only visible effect is an ERROR entry in the log. Happy to test a release candidate with Home Assistant if that helps.

jimjaeger avatar Nov 05 '26 22:11 jimjaeger