An interrupted response close leaves the transport stream open and cannot be retried

Aperta
#1,326 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@dsfaccini ci sta già lavorando.

Dal 10/11/2026.

  • #1327 di @dsfaccini — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Ferma
Stack tecnologico
python

Direzione di ricerca

Start by reading Response.aclose() and aiter_raw() in the response implementation, then inspect the streaming cancellation tests. Reproduce with the stalled stream and cancellation example in the issue. Done means the transport stream closes after cancellation and a later shielded close can complete it; linked pull request #1327 is already open.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

This issue was posted by OpenCode on behalf of David.

Summary

Response.aclose() sets is_closed = True before awaiting stream.aclose(). From 2.12.0, aiter_raw() awaits self.aclose() in a finally, so a cancellation that interrupts a streaming read runs that close inside the cancelled scope: the await is cut short, the transport stream is never closed, and the response is already flagged closed so no later aclose() retries it. The connection is leaked.

The caller cannot repair this through the public API: response.aclose() is a no-op once is_closed is set, and response.stream.aclose() is the only remaining handle.

Reproduction

A response body that stalls after one chunk, read under a deadline, then closed from a shielded scope:

import anyio, httpx2
from contextlib import AsyncExitStack


class StalledStream(httpx2.AsyncByteStream):
    def __init__(self) -> None:
        self.closes = 0

    async def __aiter__(self):
        yield b' '
        await anyio.sleep_forever()

    async def aclose(self) -> None:
        # Awaits like a real transport's close, so a cancelled scope cuts it short.
        await anyio.sleep(0)
        self.closes += 1


async def main() -> None:
    stream = StalledStream()
    stack = AsyncExitStack()
    response = None
    try:
        client = await stack.enter_async_context(
            httpx2.AsyncClient(transport=httpx2.MockTransport(lambda request: httpx2.Response(200, stream=stream)))
        )
        with anyio.fail_after(0.05):
            response = await stack.enter_async_context(client.stream('GET', 'https://example.test/'))
            async for _chunk in response.aiter_bytes():
                pass
    except TimeoutError:
        pass
    finally:
        with anyio.CancelScope(shield=True):
            await stack.aclose()
    print(f'is_closed={response.is_closed} stream closes completed={stream.closes}')


anyio.run(main)

Output, run against each version:

Version is_closed Completed closes
httpx 0.28.1 True 1
httpx2 2.7.0 True 1
httpx2 2.12.0 True 0
httpx2 2.13.0 True 0

When it started

The close only moved into a finally in 2.12.0:

  • 2.7.0 through 2.11.0 call await self.aclose() after the iteration loop, not in a finally. A cancellation skips that line entirely, so is_closed stays False and a caller's shielded aclose() still performs the close.
  • 2.12.0 through 2.16.0 wrap the loop in try: ... finally: await self.aclose(). The finally runs in the cancelled scope, so the close is dropped and the response is marked closed first.

Why it matters

Any caller that streams a response under a deadline or any cancel scope leaks the connection on every timeout or cancellation, with no way to release it. In pydantic-ai-harness this shows up in HttpKeenableClient, which reads a body under anyio.fail_after and closes the response in a shielded scope; its transport-stream close is silently a no-op on 2.12.0+ unless it reaches past the response and closes response.stream itself.

Suggested fix

Either shield the close in aiter_raw's finally, or set is_closed only after the await completes (and leave it False when the close raises), so a caller can finish an interrupted close.

Lingua principale
Python
Stelle
1.6k
Fork
103
Merge medio
1g 19h
PR unite (30g)
25

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di pydantic/httpx2

Tutte le issue di pydantic/httpx2

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.