Skip to content

proxy: ensure handle_connection releases transports on cancellation - #8643

Open
jtoledo3970 wants to merge 2 commits into
mitmproxy:mainfrom
jtoledo3970:fix/8620-release-upstream-transports
Open

jtoledo3970 wants to merge 2 commits into
mitmproxy:mainfrom
jtoledo3970:fix/8620-release-upstream-transports

Conversation

@jtoledo3970

Copy link
Copy Markdown

Description

Fixes #8620

ConnectionHandler.handle_connection() previously only closed writer and popped the entry from self.transports at the end of the method, and only caught asyncio.CancelledError around reader.read() and drain_writers().

When an upstream task was cancelled while awaiting server_event(events.DataReceived(...)) or server_event(events.ConnectionClosed(...)) (for example, contending on _server_event_lock across multiplexed HTTP/2 streams), CancelledError bypassed cleanup and left the writer unclosed and the entry in self.transports.

This PR:

  • Extracts an idempotent ConnectionHandler._release_transport() helper to pop self.transports and close io.writer.
  • Wraps handle_connection() in try ... finally: self._release_transport(connection) so transport cleanup always runs on EOF, cancellation, or error.
  • Catches asyncio.CancelledError around await self.server_event(events.DataReceived(...)) (matching drain_writers()) so ConnectionClosed is still dispatched before cleanup.
  • Adds deterministic unit tests in test/mitmproxy/proxy/test_server.py verifying cleanup when cancelled during DataReceived and ConnectionClosed, as well as the normal EOF path.

(Note: open_connection() also acquires self.max_conns[address] outside its try block, which can leave a placeholder ConnectionIO entry in self.transports if cancelled while waiting for a semaphore slot — happy to address that in a follow-up if desired.)

Checklist

  • I have updated tests where applicable.
  • I have added an entry to the CHANGELOG.

@jtoledo3970
jtoledo3970 force-pushed the fix/8620-release-upstream-transports branch from 7722150 to 6149faa Compare November 24, 2026 19:41

This branch has not been deployed

No deployments
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.

Reclaim upstream socket writers after H2-to-H1 reverse-proxy requests

1 participant