httpcore
httpcore copied to clipboard
Move HTTP/2 stream events cleanup inside state lock in _response_closed
In _response_closed, the del self._events[stream_id] happens outside the _state_lock, but the not self._events check that decides whether to transition to IDLE happens inside the lock. This creates a race window with multiplexed HTTP/2 requests:
- Request A is the last active stream.
_response_closedruns: releases semaphore, deletes events entry, yields before acquiring the lock - Request B enters
handle_async_request: acquires_state_lock, setsstate=ACTIVE, releases lock - Request B acquires semaphore and stream ID — but hasn't added
self._events[stream_id] = []yet - Request A resumes: acquires
_state_lock, seesnot self._eventsis True (B hasn't added its entry), setsstate=IDLEand_expire_at
Now the connection is marked IDLE with an expiry timer while Request B is actively using it. The connection pool may see the connection as expired and close it mid-request, or evict it as an excess idle connection.
Moving the del self._events[stream_id] inside the _state_lock ensures the events dict modification and the IDLE-transition check are atomic.
Applied to both async and sync implementations.