Potential Issue: `AsyncClient.stream` double-cancel may leak active connections
What I'm trying to do
I have a background task consuming an httpx.AsyncClient.stream(...) response, and I cancel the task when I want to stop early. In some real code paths the same task may get cancelled twice (eg, cascading shutdown).
What I'm seeing
If I call task.cancel() twice with an await asyncio.sleep(0) between, connections appear to remain "active" in the underlying pool after the task finishes, even though I explicitly close the response/iterator.
Repeating the pattern grows the pool's Connections: N active count until max_connections is reached, at which point the next request blocks waiting for a connection.
Single cancel does not leak: the pool returns to 0 connections after each iteration.
Key detail: the reproduction requires await asyncio.sleep(0) between the two cancel() calls; removing it or sleeping longer typically avoids the issue.
Minimal reproduction
Run:
uv run test.py
To make the hang deterministic, run more iterations than limits.max_connections (eg 12+ when max_connections=10).
Repro script: test.py
import asyncio
import httpx
from logging import INFO, basicConfig, getLogger
basicConfig(level=INFO)
logger = getLogger(__name__)
limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
client = httpx.AsyncClient(
verify=False,
limits=limits,
timeout=httpx.Timeout(30.0),
)
async def _stream():
async with client.stream("GET", "https://httpbin.org/stream/100") as response:
try:
async for line in response.aiter_lines():
yield line
finally:
# Ensure close runs even under cancellation.
await asyncio.shield(response.aclose())
logger.info("response aclose done")
async def _run_impl_task(name, stop_step, stop_signal: asyncio.Event):
iterator = _stream()
try:
cnt = 0
async for _ in iterator:
cnt += 1
if stop_step and cnt > stop_step and not stop_signal.is_set():
logger.info(f"[{name}] send stop signal")
stop_signal.set()
finally:
# Ensure iterator is closed.
await asyncio.shield(iterator.aclose())
logger.info(f"[{name}] iterator closed")
def log_pool_status(phase: str):
transport = getattr(client, "_transport", None)
pool = getattr(transport, "_pool", None) if transport else None
logger.info("Pool [%s]: %s", phase, pool)
async def simulate(name: str, stop_step: int):
log_pool_status(f"{name} before create_task")
stop_signal = asyncio.Event()
bg_task = asyncio.create_task(_run_impl_task(name, stop_step, stop_signal))
await stop_signal.wait()
log_pool_status(f"{name} before cancel")
# 1st cancel
bg_task.cancel()
# Critical for reproduction.
await asyncio.sleep(0)
# 2nd cancel triggers the leak.
bg_task.cancel()
try:
await bg_task
except asyncio.CancelledError:
logger.info(f"[{name}] CancelledError caught")
log_pool_status(f"{name} after cancel")
async def main():
log_pool_status("before run")
for i in range(12):
await simulate(f"simulate-{i}", stop_step=5)
log_pool_status("after run")
await client.aclose()
if __name__ == "__main__":
asyncio.run(main())
Observed output (representative)
With double-cancel, after each iteration the pool grows:
- after simulate-0:
Connections: 1 active, 0 idle - after simulate-1:
Connections: 2 active, 0 idle - ...
- after simulate-9:
Connections: 10 active, 0 idle - simulate-10 then blocks waiting for a connection, since
max_connections=10.
With a single cancel (remove the await asyncio.sleep(0) + second cancel()), the pool returns to:
Connections: 0 active, 0 idleafter each iteration.
With a longer sleep (await asyncio.sleep(0.1) + second cancel()), the pool also returns to:
Connections: 0 active, 0 idleafter each iteration.
Expected behavior
After cancelling a streaming task and closing the response/iterator, the connection should be closed/released so it does not remain counted as an active connection in the pool. Repeating should not exhaust max_connections.
Environment
- httpx: 0.28.1
- httpcore: 1.0.9
- anyio: 4.12.1
- h11: 0.16.0
- Python (uv): 3.14.0rc1
- OS: macOS 26.3 arm64
> uv pip list
Package Version
-------- ---------
anyio 4.12.1
certifi 2026.2.25
h11 0.16.0
httpcore 1.0.9
httpx 0.28.1
idna 3.11
Notes
- The script prints pool state via private attributes (
client._transport._pool) just for debugging/visibility. - The
await asyncio.sleep(0)between cancels seems to be the critical timing window.
Full terminial logs
INFO:__main__:Pool [before run]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 0 idle]>
INFO:__main__:Pool [simulate-0 before create_task]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 0 idle]>
INFO:httpx:HTTP Request: GET https://httpbin.org/stream/100 "HTTP/1.1 200 OK"
INFO:__main__:[simulate-0] send stop signal
INFO:__main__:Pool [simulate-0 before cancel]: <AsyncConnectionPool [Requests: 1 active, 0 queued | Connections: 1 active, 0 idle]>
INFO:__main__:response aclose done
INFO:__main__:[simulate-0] iterator closed
INFO:__main__:[simulate-0] CancelledError caught
INFO:__main__:Pool [simulate-0 after cancel]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 1 active, 0 idle]>
INFO:__main__:Pool [simulate-1 before create_task]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 1 active, 0 idle]>
INFO:httpx:HTTP Request: GET https://httpbin.org/stream/100 "HTTP/1.1 200 OK"
INFO:__main__:[simulate-1] send stop signal
INFO:__main__:Pool [simulate-1 before cancel]: <AsyncConnectionPool [Requests: 1 active, 0 queued | Connections: 2 active, 0 idle]>
INFO:__main__:response aclose done
INFO:__main__:[simulate-1] iterator closed
INFO:__main__:[simulate-1] CancelledError caught
INFO:__main__:Pool [simulate-1 after cancel]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 2 active, 0 idle]>
INFO:__main__:Pool [simulate-2 before create_task]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 2 active, 0 idle]>
INFO:httpx:HTTP Request: GET https://httpbin.org/stream/100 "HTTP/1.1 200 OK"
INFO:__main__:[simulate-2] send stop signal
INFO:__main__:Pool [simulate-2 before cancel]: <AsyncConnectionPool [Requests: 1 active, 0 queued | Connections: 3 active, 0 idle]>
INFO:__main__:response aclose done
INFO:__main__:[simulate-2] iterator closed
INFO:__main__:[simulate-2] CancelledError caught
INFO:__main__:Pool [simulate-2 after cancel]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 3 active, 0 idle]>
INFO:__main__:Pool [simulate-3 before create_task]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 3 active, 0 idle]>
INFO:httpx:HTTP Request: GET https://httpbin.org/stream/100 "HTTP/1.1 200 OK"
INFO:__main__:[simulate-3] send stop signal
INFO:__main__:Pool [simulate-3 before cancel]: <AsyncConnectionPool [Requests: 1 active, 0 queued | Connections: 4 active, 0 idle]>
INFO:__main__:response aclose done
INFO:__main__:[simulate-3] iterator closed
INFO:__main__:[simulate-3] CancelledError caught
INFO:__main__:Pool [simulate-3 after cancel]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 4 active, 0 idle]>
INFO:__main__:Pool [simulate-4 before create_task]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 4 active, 0 idle]>
INFO:httpx:HTTP Request: GET https://httpbin.org/stream/100 "HTTP/1.1 200 OK"
INFO:__main__:[simulate-4] send stop signal
INFO:__main__:Pool [simulate-4 before cancel]: <AsyncConnectionPool [Requests: 1 active, 0 queued | Connections: 5 active, 0 idle]>
INFO:__main__:response aclose done
INFO:__main__:[simulate-4] iterator closed
INFO:__main__:[simulate-4] CancelledError caught
INFO:__main__:Pool [simulate-4 after cancel]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 5 active, 0 idle]>
INFO:__main__:Pool [after run]: <AsyncConnectionPool [Requests: 0 active, 0 queued | Connections: 5 active, 0 idle]>
I independently reproduced this with a local HTTP/1.1 streaming server on Python 3.9.6, using the same dependency versions: httpx 0.28.1, httpcore 1.0.9, AnyIO 4.12.1, and h11 0.16.0. This suggests the issue is not specific to Python 3.14 or httpbin.
With max_connections=3:
- Single cancellation: no connections remained after each iteration.
- Double cancellation separated by
await asyncio.sleep(0): active connections accumulated from 1 to 3, and the next request raisedPoolTimeout. - A longer delay between cancellations avoided the issue in this test.
The likely failure window appears to be in httpcore’s HTTP11ConnectionByteStream.aclose(). It sets _closed = True before awaiting _connection._response_closed(), which acquires an async state lock. A second direct Task.cancel() can interrupt that cleanup, leaving the connection active while the byte stream is already marked closed. Subsequent aclose() calls then skip the unfinished cleanup.
The internal AsyncShieldCancellation uses an AnyIO shielded cancel scope, which does not protect this path from a direct asyncio Task.cancel(). Shielding response.aclose() in the caller’s finally appears to happen too late to recover this state.
Would a regression test in httpcore be the appropriate starting point? Ideally, it would synchronize the second cancellation with the cleanup checkpoint and assert that cleanup completes, cancellation still propagates, and a subsequent request can acquire a connection. Simply moving the _closed assignment may require additional consideration of concurrent close calls and the outer pool cleanup.
I traced the execution path and identified the exact root cause in httpcore. The leak happens due to how cancellation interacts with AnyIO's _state_lock checkpoint inside AsyncHTTP11Connection._response_closed.
Root Cause Analysis
-
Unwinding during stream cancellation: When the streaming generator task is cancelled during
aiter_lines(),httpxunwinds through:response.aiter_raw()$\to$response.aclose()$\to$BoundAsyncStream.aclose()$\to$PoolByteStream.aclose(). -
The checkpoint race on
_state_lock: Inhttpcore._async.connection_pool.PoolByteStream.aclose:if not self._closed: self._closed = True with AsyncShieldCancellation(): if hasattr(self._stream, "aclose"): await self._stream.aclose() with self._pool._optional_thread_lock: self._pool._requests.remove(self._pool_request) closing = self._pool._assign_requests_to_connections() await self._pool._close_connections(closing)Here
self._streamisHTTP11ConnectionByteStream. Itsaclose()method executes:if not self._closed: self._closed = True async with Trace("response_closed", logger, self._request): await self._connection._response_closed()Inside
AsyncHTTP11Connection._response_closed:async with self._state_lock: if ( self._h11_state.our_state is h11.DONE and self._h11_state.their_state is h11.DONE ): self._state = HTTPConnectionState.IDLE self._h11_state.start_next_cycle() ... else: await self.aclose() -
Why the double-cancel triggers the leak:
self._state_lockis ananyio.Lock. Acquiring this lock under AnyIO's asyncio backend performs an event loop checkpoint (await sleep(0)). When the task is cancelled a second time (await asyncio.sleep(0)followed bybg_task.cancel()), the second cancellation exception (asyncio.CancelledError) is raised directly inside_state_lock.__aenter__.Because
CancelledErrorinterrupts_response_closed()before it can acquire the lock:- Neither
self._state = HTTPConnectionState.IDLEnorawait self.aclose()ever executes. - The connection remains stranded in
self._state = HTTPConnectionState.ACTIVE. - Both
HTTP11ConnectionByteStream._closedandPoolByteStream._closedhave already been markedTrue. - As a result, subsequent calls to
response.aclose()(such as fromfinally:blocks orclient.aclose()) see_closed == Trueand immediately no-op. - The pool continues to count the stranded connection as
active, eventually exhaustingmax_connections.
- Neither
The Fix
In httpcore/_async/http11.py, HTTP11ConnectionByteStream.aclose needs to ensure that if _response_closed() is interrupted by cancellation or fails, the underlying connection is unilaterally closed rather than left stranded in ACTIVE state:
async def aclose(self) -> None:
if not self._closed:
self._closed = True
try:
async with Trace("response_closed", logger, self._request):
await self._connection._response_closed()
except BaseException:
# If _response_closed was interrupted by cancellation or error,
# unilaterally close the connection so it does not remain stranded in ACTIVE state.
await self._connection.aclose()
raise
Verification
I verified this fix against the reproduction script running 12 iterations on httpx 0.28.1 + httpcore 1.0.9:
- Before fix: Each iteration orphaned 1 connection in
ACTIVEstate until iteration 10 starved the pool. - With fix: Active connections return to 0 after every iteration; all 12 iterations complete cleanly with zero pool leakage or starvation.
Happy to open an upstream PR to encode/httpcore with a dedicated regression test if maintainers would like!
I can investigate the repeated-cancellation case and prepare a focused regression test for connection-pool cleanup. Since this is marked as a potential issue, would maintainers be open to a code change for it?
This bug is causing me a lot of trouble. The application gradually reaches a "pool timeout" state and begins to respond very slowly to client requests. I’ve also discovered that this is linked to request cancellations, which prevent active connections from being cleaned up. For now, I’ve had to implement a background loop that identifies and clears these connections, but this is a very inelegant solution—I hope you’ll fix this in future versions.
CancelledError during response close leaves the connection stuck in ACTIVE (leaked pool slot)
httpx 0.28.1, httpcore 1.0.9, Python 3.11, asyncio backend.
Symptom
After a fully-read response, if the task is cancelled while the response stream is being closed, the httpcore connection stays in _state == ACTIVE forever: is_available() is False, so the pool neither reuses nor closes it, _request_count stays frozen, and the slot is lost until the client is closed. h11 is already at our_state == DONE and their_state == DONE — nothing is pending on the wire, the exchange completed successfully.
Why
Response.aread() → aiter_raw() closes the stream with await self.aclose(), and Response.aclose() flips is_closed before awaiting the stream:
httpx/_models.py:1073
if not self.is_closed:
self.is_closed = True # set before the await below
with request_context(request=self._request):
await self.stream.aclose() # cancellation point
The transition to IDLE happens inside httpcore, after that await:
httpcore/_async/http11.py:238
async def _response_closed(self) -> None:
async with self._state_lock: # cancellation point
if self._h11_state.our_state is h11.DONE and self._h11_state.their_state is h11.DONE:
self._state = HTTPConnectionState.IDLE
A CancelledError at async with self._state_lock skips _state = IDLE. Nothing retries the close either:
Response.aclose()is a no-op on the second call (is_closedalreadyTrue), so the cleanup inClient.send()—except BaseException: await response.aclose()(httpx/_client.py:1642) — cannot fix it;HTTP11ConnectionByteStream.aclose()(httpcore/_async/http11.py:344) setsself._closed = Truebefore awaiting as well.
Places to fix (in order of importance)
httpcore/_async/http11.py:238—AsyncHTTP11Connection._response_closed(). Make the close survive cancellation, e.g. finish it in a separate task and re-raise:except asyncio.CancelledError: asyncio.create_task(self._response_closed()) raisehttpcore/_async/http11.py:344—HTTP11ConnectionByteStream.aclose(). Setself._closed = Trueafter the await, or roll it back when the close is interrupted, so a secondaclose()actually retries.httpx/_models.py:1073—Response.aclose(). Same ordering issue: setis_closedonly after the stream is closed (or roll it back onCancelledError), otherwise the retry inClient.send()is a no-op.httpcore/_async/http2.py:409—HTTP2Connection._response_closed(stream_id). Identical shape (await self._max_streams_semaphore.release()+async with self._state_lock): a cancellation there leaks thestream_identry inself._eventsand leaves the connectionACTIVE.httpcore/_synchronization.py:190—AsyncShieldCancellation. On asyncio it isanyio.CancelScope(shield=True), which does not shield against nativeasynciocancellation (Task.cancel()), typical for server timeouts (e.g. Sanic / uvicorn wrappers). The existing shields athttp11.py:133,340/http2.py:113,166,583therefore don't cover thetask.cancel()case.- Optional, pool level:
httpcore/_async/connection_pool.py:270—_assign_requests_to_connections()evicts only closed/expired connections. A connection alreadyDONE/DONEat the h11 level but stillACTIVEis never reclaimed, so the leak is permanent. Reclaiming such connections would make the pool self-healing regardless of the race.
Deterministic repro (widened window)
import asyncio, httpx
from httpcore._async import http11 as h11
async def handler(reader, writer):
try:
while True:
await reader.readuntil(b"\r\n\r\n")
writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
await writer.drain()
finally:
writer.close()
async def main():
server = await asyncio.start_server(handler, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
entered = asyncio.Event()
orig = h11.AsyncHTTP11Connection._response_closed
async def slow(self):
entered.set()
await asyncio.sleep(0.05) # window: body fully read, IDLE not set yet
await orig(self)
h11.AsyncHTTP11Connection._response_closed = slow
async with httpx.AsyncClient() as client:
task = asyncio.create_task(client.get(f"http://127.0.0.1:{port}/"))
await entered.wait()
task.cancel()
try:
await task
except BaseException:
pass
conn = client._transport._pool.connections[0]
print(conn._connection._state.name, conn._h11_state.our_state,
conn._h11_state.their_state, conn.is_available())
asyncio.run(main())
Current output: ACTIVE DONE DONE False — slot leaked.
With fix (1) the same script prints IDLE and is_available() == True (h11 states are reset by start_next_cycle()), while the task is still cancelled.
I would like to help validate this with Codex assistance. I see that encode/httpcore#1113 and encode/httpcore#1116 already address this case, and #1116 includes a localhost comparison. I will compare both current heads with the same local HTTPX probe, including cancellation propagation and a later request through a bounded pool. Is there a remaining case that maintainers want covered in the existing work?
Codex-assisted validation confirms that both existing PR heads fix the original double-cancel stream case in a common localhost probe. Cancellation still propagates, and a later complete GET succeeds through a one-slot pool.
The fully-read response case already reported above still fails in a separate controlled probe:
| HTTPcore source | Original double cancel: later GET | Fully-read close, one cancel: later GET |
|---|---|---|
| Release 1.0.9 | PoolTimeout |
PoolTimeout |
master 10a658221deb38a4c5b16db55ab554b0bf731707 |
PoolTimeout |
PoolTimeout |
#1113 1fb0ecec6d38da241c5aca08777195aae3830d1d |
200 ok |
PoolTimeout |
#1116 6d5f158bcad201a368d2d869d94882a2f865597e |
200 ok |
PoolTimeout |
HTTPX source: b5addb64f0161ff6bfe94c124ef76f6a1fba5254. Environment: Linux/WSL2, Python 3.12.3, AnyIO 4.12.1, h11 0.16.0. The released HTTPX 0.28.1 package gives the same result. This does not reproduce the reporter's exact Python/macOS environment.
For the fully-read case, a trace callback only sets an asyncio.Event. It adds no await, delay, monkeypatch, or injected exception. The second task cancels the request at the existing state-lock checkpoint. The failure traceback reaches AsyncHTTP11Connection._response_closed() → _state_lock → AnyIO's asyncio checkpoint. At that point, both h11 states are DONE, all two body bytes arrived, and the HTTPcore connection remains ACTIVE. CancelledError reaches the caller. A subsequent public response.aclose() returns, but the later GET still raises PoolTimeout. The result repeated five times on master and five times on #1116. Without cancellation, the same request and later GET both complete.
HTTPX sets Response.is_closed before the awaited stream close. Its retry in AsyncClient.send() and the caller's explicit retry therefore stop before they reach #1116's retryable HTTPcore stream. That is a different path from #1116's direct HTTPcore response retry test. This observation does not establish the intended retry-after-cancellation contract.
The existing PR regressions each fail on master and pass at their own heads. Connected cancellation, HTTP/1.1, and pool tests pass: master 98, #1113 106, #1116 100, each with six existing XPASS results. These are focused checks, not full-suite approval.
Should the fully-read case receive a focused HTTPX response-close change coordinated with #1116, or belong within the existing HTTPcore work? No competing patch was created.
Standalone localhost reproducer for the fully-read case
Use HTTPX 0.28.1 (or the HTTPX SHA above) with the selected HTTPcore source and the dependency versions above.
import asyncio
import contextlib
import httpx
async def main():
handlers = set()
async def serve(reader, writer):
handlers.add(asyncio.current_task())
try:
while True:
await reader.readuntil(b"\r\n\r\n")
writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
await writer.drain()
except (asyncio.IncompleteReadError, ConnectionError, asyncio.CancelledError):
pass
finally:
writer.close()
with contextlib.suppress(ConnectionError):
await writer.wait_closed()
handlers.discard(asyncio.current_task())
server = await asyncio.start_server(serve, "127.0.0.1", 0)
url = f"http://127.0.0.1:{server.sockets[0].getsockname()[1]}/"
closing = asyncio.Event()
responses = []
async def trace(name, info):
if name == "http11.response_closed.started":
closing.set() # No delay, await, monkeypatch, or injected exception.
async def capture(response):
responses.append(response)
try:
async with httpx.AsyncClient(
limits=httpx.Limits(max_connections=1),
timeout=httpx.Timeout(2, pool=0.2), trust_env=False,
event_hooks={"response": [capture]},
) as client:
task = asyncio.create_task(client.get(url, extensions={"trace": trace}))
await asyncio.wait_for(closing.wait(), 2)
task.cancel()
try:
await asyncio.wait_for(task, 2)
except asyncio.CancelledError:
print("CancelledError propagated")
else:
raise AssertionError("Cancellation did not propagate")
await responses[0].aclose()
try:
response = await client.get(url)
assert response.status_code == 200 and response.content == b"ok"
print("Later GET: 200 ok")
except httpx.PoolTimeout:
print("Later GET: PoolTimeout")
finally:
server.close()
await server.wait_closed()
for task in list(handlers):
task.cancel()
await asyncio.gather(*handlers, return_exceptions=True)
asyncio.run(main())
Observed output at #1116:
CancelledError propagated
Later GET: PoolTimeout
Comprehensively addressed with the hip architecture changes.