uvicorn icon indicating copy to clipboard operation
uvicorn copied to clipboard

h11: data_received after connection close raises LocalProtocolError out of the protocol callback

Open Lushiyao5 opened this issue 2 weeks ago • 0 comments

When a response completes with connection: close (or the connection closes due to keep-alive timeout or a parse error), the h11 state machine reaches CLOSED/ERROR, but transport.close() is a graceful close and the event loop can still deliver another data_received. At that point H11Protocol.data_received calls conn.receive_data() / handle_events() and, on a parse-path error, send_400_response() tries conn.send(Response), which raises LocalProtocolError: can't handle event type Response when role=SERVER and state=CLOSED. The exception escapes the protocol callback into asyncio (fatal transport error, no response, noisy stack). The httptools implementation handles the same input without raising.

Reproduced on current main with a mocked transport: delivering stray data_received after a connection: close response completion raises out of data_received on h11, silently ignored on httptools.

Ready fix branch (entry guard in data_received: ignore late data when our_state is h11.CLOSED/h11.ERROR or their_state is h11.ERROR - the connection is already closing and dropping late bytes after close framing is semantically correct - plus a regression test; both are h11-specific, following the existing h11-only test precedent):

https://github.com/Lushiyao5/uvicorn/tree/audit/uvicorn-20261115 (commit d516d8d)

Happy to open a PR if maintainers prefer - noting that PR creation appears limited to collaborators for this repository (the API returns 404 for create_pull_request).

Lushiyao5 avatar Nov 15 '26 16:11 Lushiyao5