Skip to content

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

Open

Description

@cerealkiller57540

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:

# Keep a strong reference to prevent garbage collection
self._background_tasks.add(send_task)
send_task.add_done_callback(self._background_tasks.discard)
await asyncio.shield(send_task)

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:

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

  • 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.

Activity

  1. wahajahmed010 commented on Oct 20, 2026

    @wahajahmed010
  2. rinopatrick commented on Nov 2, 2026

    @rinopatrick

    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.

  3. jimjaeger commented on Nov 5, 2026

    @jimjaeger

    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.

  4. minimicro34 commented on Nov 23, 2026

    @minimicro34

    I can also confirm that this issue is still present in Home Assistant Core 2026.11.2, with the exact same traceback:

    aiohttp.client_exceptions.ClientConnectionResetError: Cannot write to closing transport

    The proposed fix in PR #14063 is still pending. Hopefully it can be merged and included in an upcoming aiohttp release.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions