Skip to content

fix: avoid a second response start after a mid-stream ASGI error - #449

Open
rootkiller6788 wants to merge 2 commits into
GoogleCloudPlatform:mainfrom
rootkiller6788:fix-asgi-response-already-started
Open

rootkiller6788 wants to merge 2 commits into
GoogleCloudPlatform:mainfrom
rootkiller6788:fix-asgi-response-already-started

Conversation

@rootkiller6788

Copy link
Copy Markdown

A streaming HTTP function that raises after the first chunk lands in the ASGI exception middleware, which tries to write a 500 response start. The response had already started by then, so uvicorn rejects the message:

RuntimeError: Expected ASGI message 'http.response.body', but got 'http.response.start'.

So you get the user's traceback, then the same traceback again buried under a protocol error, and a truncated response either way.

Fix is to remember whether http.response.start went out and skip the crash response when it did. The traceback is still logged first - we just don't send a response we can no longer send.

Verified against a real uvicorn server with a streaming generator that raises on the second chunk: before, the log ends with the RuntimeError above; after, it ends with the user's ValueError plus uvicorn's "ASGI callable returned without completing response". Two tests cover both sides. Full suite 277 passed / 6 skipped, aio/init.py at 100% branch coverage, black + isort clean.

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.
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.
@rootkiller6788
rootkiller6788 marked this pull request as ready for review December 3, 2026 04:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant