From 1922d9ac74faa29bab451647de323eca1195407f Mon Sep 17 00:00:00 2001 From: rootkiller6788 Date: Thu, 24 Sep 2026 14:47:07 +0800 Subject: [PATCH 1/2] fix: avoid a second response start after a mid-stream ASGI error When a streaming function raises after the first chunk, the status line is already on the wire. The exception middleware still wrote a 500 response start at that point, which is an invalid ASGI message sequence - uvicorn rejects it with "Expected ASGI message 'http.response.body', but got 'http.response.start'" and the real traceback gets buried in a second, duplicate one. Track whether the response has started and only write the crash response when nothing has been sent yet. The traceback is still logged either way. --- src/functions_framework/aio/__init__.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/functions_framework/aio/__init__.py b/src/functions_framework/aio/__init__.py index a56fe942..ad0e17d3 100644 --- a/src/functions_framework/aio/__init__.py +++ b/src/functions_framework/aio/__init__.py @@ -181,8 +181,16 @@ async def __call__(self, scope, receive, send): await self.app(scope, receive, send) return + response_started = False + + async def send_with_state(message): + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + await send(message) + try: - await self.app(scope, receive, send) + await self.app(scope, receive, send_with_state) except Exception as exc: logger = logging.getLogger() tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__) @@ -194,6 +202,14 @@ async def __call__(self, scope, receive, send): logger.error(error_msg) + if response_started: + # The status line is already on the wire, so the only thing we could + # still send is a body. Sending another response start here is an + # invalid ASGI message sequence and the server rejects it, which + # replaces the traceback above with a confusing protocol error. Let + # the connection end instead; the client sees a truncated response. + return + headers = [ [b"content-type", b"text/plain"], [_FUNCTION_STATUS_HEADER_FIELD.encode(), _CRASH.encode()], From 81d1eef9d07fb685f06459f518cb3aa99c96b32c Mon Sep 17 00:00:00 2001 From: rootkiller6788 Date: Thu, 24 Sep 2026 14:47:12 +0800 Subject: [PATCH 2/2] test: cover ASGI crash handling before and after the response starts Two cases for ExceptionHandlerMiddleware: a plain failure still produces the 500 crash response, and a failure after the response started sends nothing further. The second one regressed silently before - the client only noticed a truncated body. --- tests/test_aio.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/test_aio.py b/tests/test_aio.py index e7533b1d..10f69e04 100644 --- a/tests/test_aio.py +++ b/tests/test_aio.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import logging import pathlib import re import sys @@ -26,6 +27,7 @@ from functions_framework import exceptions from functions_framework.aio import ( + ExceptionHandlerMiddleware, LazyASGIApp, _cloudevent_func_wrapper, _http_func_wrapper, @@ -169,3 +171,58 @@ def sync_cloud_event(event): assert called_with_event is not None assert called_with_event["type"] == "test.event" assert called_with_event["source"] == "test-source" + + +@pytest.mark.asyncio +async def test_exception_handler_middleware_returns_crash_response(caplog): + async def failing_app(scope, receive, send): + raise ValueError("boom") + + middleware = ExceptionHandlerMiddleware(failing_app) + sent = [] + + async def send(message): + sent.append(message) + + with caplog.at_level(logging.ERROR): + await middleware( + {"type": "http", "method": "GET", "path": "/"}, AsyncMock(), send + ) + + assert [message["type"] for message in sent] == [ + "http.response.start", + "http.response.body", + ] + assert sent[0]["status"] == 500 + assert [b"X-Google-Status", b"crash"] in sent[0]["headers"] + assert "boom" in caplog.text + + +@pytest.mark.asyncio +async def test_exception_handler_middleware_after_response_started(caplog): + async def failing_stream(scope, receive, send): + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send( + {"type": "http.response.body", "body": b"first chunk", "more_body": True} + ) + raise ValueError("boom mid-stream") + + middleware = ExceptionHandlerMiddleware(failing_stream) + sent = [] + + async def send(message): + sent.append(message) + + with caplog.at_level(logging.ERROR): + await middleware( + {"type": "http", "method": "GET", "path": "/"}, AsyncMock(), send + ) + + # The response start was already sent, so there is nothing left to send: an + # extra response start would be an invalid ASGI message sequence. + assert [message["type"] for message in sent] == [ + "http.response.start", + "http.response.body", + ] + assert sent[0]["status"] == 200 + assert "boom mid-stream" in caplog.text