From f305e37a1b7904ca64c6f6b9a525fbbaadfe02ad Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Wed, 25 Nov 2026 15:51:47 +0000 Subject: [PATCH 1/6] [bot] Fix compressed body corruption after a cancelled write --- aiohttp/http_writer.py | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/aiohttp/http_writer.py b/aiohttp/http_writer.py index bd59217a452..9941b6911c8 100644 --- a/aiohttp/http_writer.py +++ b/aiohttp/http_writer.py @@ -4,7 +4,7 @@ import re import sys from collections.abc import Awaitable, Callable, Iterable -from typing import TYPE_CHECKING, NamedTuple +from typing import TYPE_CHECKING, NamedTuple, NoReturn from multidict import CIMultiDict @@ -53,6 +53,7 @@ class StreamWriter(AbstractStreamWriter): chunked: bool = False _eof: bool = False _compress: ZLibCompressor | None = None + _compress_cancelled: bool = False def __init__( self, @@ -85,6 +86,19 @@ def enable_compression( ) -> None: self._compress = ZLibCompressor(encoding=encoding, strategy=strategy) + def _raise_compress_cancelled(self) -> NoReturn: + # The executor can't be interrupted, so the compressor may have + # consumed a chunk whose output was dropped. Nothing written after + # that would decompress, so the message can't be completed. Callers + # that let the cancellation propagate close the connection themselves; + # this is only reached by one that carried on. + transport = self._protocol.transport + if transport is not None: + transport.close() + raise ClientConnectionResetError( + "Cannot write after a compressed write was cancelled" + ) + def _write( self, chunk: "bytes | bytearray | memoryview[int] | memoryview[bytes]" ) -> None: @@ -183,7 +197,13 @@ async def write( body_size = len(chunk) if notify is not None else 0 if self._compress is not None: - chunk = await self._compress.compress(chunk) + if self._compress_cancelled: + self._raise_compress_cancelled() + try: + chunk = await self._compress.compress(chunk) + except asyncio.CancelledError: + self._compress_cancelled = True + raise if not chunk: if notify is not None and body_size: notify(body_size, self.output_size) @@ -280,11 +300,19 @@ async def write_eof(self, chunk: bytes = b"") -> None: # Handle body/compression if self._compress: + if self._compress_cancelled: + self._raise_compress_cancelled() chunks: list[bytes] = [] chunks_len = 0 - if chunk and (compressed_chunk := await self._compress.compress(chunk)): - chunks_len = len(compressed_chunk) - chunks.append(compressed_chunk) + if chunk: + try: + compressed_chunk = await self._compress.compress(chunk) + except asyncio.CancelledError: + self._compress_cancelled = True + raise + if compressed_chunk: + chunks_len = len(compressed_chunk) + chunks.append(compressed_chunk) flush_chunk = self._compress.flush() chunks_len += len(flush_chunk) From 3c7aeb6e7c002f118f94c24d615ddf2040c743ef Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Wed, 25 Nov 2026 15:53:25 +0000 Subject: [PATCH 2/6] [bot] Test a handler that survives a cancelled compressed write --- tests/test_web_server.py | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/tests/test_web_server.py b/tests/test_web_server.py index 06efc6e5c05..7664e5e4571 100644 --- a/tests/test_web_server.py +++ b/tests/test_web_server.py @@ -1,6 +1,8 @@ import asyncio import gc +import os import socket +from concurrent.futures import ThreadPoolExecutor from contextlib import suppress from typing import Any, NoReturn from unittest import mock @@ -9,6 +11,7 @@ from pytest_aiohttp import AiohttpClient, AiohttpRawServer, AiohttpServer from aiohttp import client, web +from aiohttp.http import StreamWriter from aiohttp.http_exceptions import BadStatusLine @@ -208,6 +211,57 @@ async def handler(request: web.BaseRequest) -> MyResponse: logger.debug.assert_called_with("Ignored premature client disconnection") +@pytest.mark.parametrize("keeps_writing", (True, False)) +async def test_compressed_write_cancelled_in_handler( + keeps_writing: bool, + aiohttp_client: AiohttpClient, + slow_executor: ThreadPoolExecutor, +) -> None: + """Test a handler that survives the cancellation of a compressed write. + + The executor can't un-run compress(), so the output of the cancelled chunk + is missing from the stream. The response must not be completed regardless, + or the peer gets a corrupt body on a connection that is then reused. + """ + transports: list[asyncio.Transport | None] = [] + + async def handler(request: web.Request) -> web.StreamResponse: + transports.append(request.transport) + resp = web.StreamResponse() + resp.enable_compression(web.ContentCoding.gzip) + writer = await resp.prepare(request) + assert isinstance(writer, StreamWriter) + assert writer._compress is not None + writer._compress._executor = slow_executor + with suppress(TimeoutError): + async with asyncio.timeout(0): + await resp.write(os.urandom(65536)) + if keeps_writing: + with suppress(ConnectionResetError): + await resp.write(b"more") + return resp + + async def ping(request: web.Request) -> web.Response: + transports.append(request.transport) + return web.Response() + + app = web.Application() + app.router.add_get("/", handler) + app.router.add_get("/ping", ping) + # Without decompression a corrupt body would be read without complaint. + cli = await aiohttp_client(app, auto_decompress=False) + + async with cli.get("/") as resp: + assert resp.status == 200 + with pytest.raises(client.ClientPayloadError): + await resp.read() + async with cli.get("/ping") as resp: + assert resp.status == 200 + + cancelled, reconnected = transports + assert cancelled is not reconnected + + async def test_raw_server_not_http_exception_debug( aiohttp_raw_server: AiohttpRawServer, aiohttp_client: AiohttpClient ) -> None: From ac765715b743aacfe09f7579e4f7f4c1c6911394 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Wed, 25 Nov 2026 16:03:28 +0000 Subject: [PATCH 3/6] [bot] Test that a cancelled compressed write cannot be continued --- tests/test_http_writer.py | 57 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index fb7b85ab415..78314899bed 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -3,6 +3,7 @@ import asyncio import zlib from collections.abc import Callable, Generator, Iterable +from concurrent.futures import ThreadPoolExecutor from typing import Any from unittest import mock @@ -709,6 +710,62 @@ async def test_write_payload_deflate_compression_chunked_connection_lost_all_zli await msg.write_eof(b"end") +@pytest.mark.parametrize("cancelled", ("write", "write_eof")) +@pytest.mark.parametrize("retried", ("write", "write_eof")) +async def test_compressed_write_cancelled( + cancelled: str, + retried: str, + buf: bytearray, + protocol: BaseProtocol, + transport: asyncio.Transport, + slow_executor: ThreadPoolExecutor, +) -> None: + """Cancelling compress() loses its output, so the message must not continue.""" + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) + msg.enable_compression("deflate") + msg.enable_chunking() + assert msg._compress is not None + msg._compress._executor = slow_executor + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0): + await getattr(msg, cancelled)(b"data" * 4096) + + # A caller that lets the cancellation propagate cleans up before closing + # the connection itself, so the writer must not get in first. + assert not transport.close.called # type: ignore[attr-defined] + with pytest.raises( + ClientConnectionResetError, match="compressed write was cancelled" + ): + await getattr(msg, retried)(b"data") + transport.close.assert_called_once_with() # type: ignore[attr-defined] + assert not buf + + +async def test_compressed_write_cancelled_connection_lost( + buf: bytearray, + protocol: BaseProtocol, + transport: asyncio.Transport, + slow_executor: ThreadPoolExecutor, +) -> None: + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) + msg.enable_compression("deflate") + assert msg._compress is not None + msg._compress._executor = slow_executor + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0): + await msg.write(b"data" * 4096) + + protocol.transport = None + with pytest.raises( + ClientConnectionResetError, match="compressed write was cancelled" + ): + await msg.write_eof() + assert not transport.close.called # type: ignore[attr-defined] + assert not buf + + async def test_write_payload_bytes_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: From f80d731ea774a4f65d28a66cc06e248e18a6f929 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Wed, 25 Nov 2026 16:05:24 +0000 Subject: [PATCH 4/6] [bot] Add changelog fragment --- CHANGES/14479.bugfix.rst | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 CHANGES/14479.bugfix.rst diff --git a/CHANGES/14479.bugfix.rst b/CHANGES/14479.bugfix.rst new file mode 100644 index 00000000000..494fe9d5171 --- /dev/null +++ b/CHANGES/14479.bugfix.rst @@ -0,0 +1,3 @@ +Fixed a compressed body being corrupted when a write was cancelled during +compression (e.g. by a timeout in a web handler) and the caller carried on +writing; the connection is now closed instead -- by :user:`Dreamsorcerer`. From ef8a9f5fffa91f69ce4f2f8a8a1634ebde8f8890 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Fri, 27 Nov 2026 01:56:24 +0000 Subject: [PATCH 5/6] Apply suggestions from code review --- CHANGES/14479.bugfix.rst | 3 +-- tests/test_http_writer.py | 26 -------------------------- tests/test_web_server.py | 6 ------ 3 files changed, 1 insertion(+), 34 deletions(-) diff --git a/CHANGES/14479.bugfix.rst b/CHANGES/14479.bugfix.rst index 494fe9d5171..ed9a5404d03 100644 --- a/CHANGES/14479.bugfix.rst +++ b/CHANGES/14479.bugfix.rst @@ -1,3 +1,2 @@ Fixed a compressed body being corrupted when a write was cancelled during -compression (e.g. by a timeout in a web handler) and the caller carried on -writing; the connection is now closed instead -- by :user:`Dreamsorcerer`. +compression and the caller continued writing -- by :user:`Dreamsorcerer`. diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index 78314899bed..83624809f56 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -731,8 +731,6 @@ async def test_compressed_write_cancelled( async with asyncio.timeout(0): await getattr(msg, cancelled)(b"data" * 4096) - # A caller that lets the cancellation propagate cleans up before closing - # the connection itself, so the writer must not get in first. assert not transport.close.called # type: ignore[attr-defined] with pytest.raises( ClientConnectionResetError, match="compressed write was cancelled" @@ -742,30 +740,6 @@ async def test_compressed_write_cancelled( assert not buf -async def test_compressed_write_cancelled_connection_lost( - buf: bytearray, - protocol: BaseProtocol, - transport: asyncio.Transport, - slow_executor: ThreadPoolExecutor, -) -> None: - msg = http.StreamWriter(protocol, asyncio.get_running_loop()) - msg.enable_compression("deflate") - assert msg._compress is not None - msg._compress._executor = slow_executor - - with pytest.raises(TimeoutError): - async with asyncio.timeout(0): - await msg.write(b"data" * 4096) - - protocol.transport = None - with pytest.raises( - ClientConnectionResetError, match="compressed write was cancelled" - ): - await msg.write_eof() - assert not transport.close.called # type: ignore[attr-defined] - assert not buf - - async def test_write_payload_bytes_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: diff --git a/tests/test_web_server.py b/tests/test_web_server.py index 7664e5e4571..2be1dc0dfe9 100644 --- a/tests/test_web_server.py +++ b/tests/test_web_server.py @@ -217,12 +217,6 @@ async def test_compressed_write_cancelled_in_handler( aiohttp_client: AiohttpClient, slow_executor: ThreadPoolExecutor, ) -> None: - """Test a handler that survives the cancellation of a compressed write. - - The executor can't un-run compress(), so the output of the cancelled chunk - is missing from the stream. The response must not be completed regardless, - or the peer gets a corrupt body on a connection that is then reused. - """ transports: list[asyncio.Transport | None] = [] async def handler(request: web.Request) -> web.StreamResponse: From 0bfeca0352eddba1b33c3f2435443d643eac0c3c Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Fri, 27 Nov 2026 02:08:21 +0000 Subject: [PATCH 6/6] Update tests/test_http_writer.py --- tests/test_http_writer.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/test_http_writer.py b/tests/test_http_writer.py index 83624809f56..e4380e43e84 100644 --- a/tests/test_http_writer.py +++ b/tests/test_http_writer.py @@ -740,6 +740,30 @@ async def test_compressed_write_cancelled( assert not buf +async def test_compressed_write_cancelled_connection_lost( + buf: bytearray, + protocol: BaseProtocol, + transport: asyncio.Transport, + slow_executor: ThreadPoolExecutor, +) -> None: + msg = http.StreamWriter(protocol, asyncio.get_running_loop()) + msg.enable_compression("deflate") + assert msg._compress is not None + msg._compress._executor = slow_executor + + with pytest.raises(TimeoutError): + async with asyncio.timeout(0): + await msg.write(b"data" * 4096) + + protocol.transport = None + with pytest.raises( + ClientConnectionResetError, match="compressed write was cancelled" + ): + await msg.write_eof() + assert not transport.close.called # type: ignore[attr-defined] + assert not buf + + async def test_write_payload_bytes_memoryview( buf: bytearray, protocol: BaseProtocol, transport: asyncio.Transport ) -> None: