Files
headroom/tests/test_client_stream_lifecycle.py
Eren ŞahinandJD Davis 3d8dcf476c fix(client): close upstream responses when wrapped streams are closed (#4482)
## Description

Closing a streaming `HeadroomClient` response can leave its upstream
HTTP response open. Repeatedly closing unread streams retains
connections even after garbage collection and eventually exhausts the
connection pool.

`yield from stream` closes the generator returned by OpenAI's
`Stream.__iter__()`, rather than the original stream. Closing the
wrapper before its first iteration also skips its cleanup entirely.
Replace it with an owning iterator that closes the upstream stream and
saves metrics once on close, exhaustion, or error.

## Type of Change

- [x] Bug fix

## Changes Made

- Close the upstream source and its active iterator when distinct;
handle their cleanup independently and save metrics once.
- Add a runnable loopback reproducer for the connection and memory
measurements.

## Testing

- [x] 71 lifecycle, client, pipeline, and provider tests passed,
including 15 lifecycle tests. The OpenAI response-close tests fail
against the original implementation; two additional iterator-cleanup
tests fail against the first PR revision.
- [x] The Python pre-push suite passed: 177 passed, 4 skipped.
- [x] Ruff lint/format and `git diff --check` passed. `mypy --platform
linux headroom` passed for all 578 source files.

### Test Output

```text
71 passed in 10.81s
177 passed, 4 skipped, 1 warning in 27.62s
Success: no issues found in 578 source files
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.12, OpenAI SDK 2.41.0, HTTPX
0.28.1.
- Exact command / steps: From this PR's checkout, run the commands
below. The
[reproducer](https://github.com/ernsahin/headroom/blob/codex/close-sdk-streams/scripts/repro_client_stream_close.py)
starts a separate loopback SSE server and fresh client processes. It
compares the original `_wrap_stream` from commit `3fef15d` with the
patched method, using the same installed dependencies and normal GC.
- Observed result: All three runs released every connection after the
fix; memory results below.
- Not tested: Live model endpoints.

```sh
uv sync --extra dev
uv run python scripts/repro_client_stream_close.py --cycles 500 --repeats 3
uv run python scripts/repro_client_stream_close.py --cycles 1001 --repeats 1
uv run python scripts/repro_client_stream_close.py --cycles 500 --repeats 3 --started --no-trace --timeout 20
```

If the checkout is shallow, first fetch the baseline with `git fetch
origin 3fef15d376d9899f77a28464e2e91f8b99514930`. Each run prints JSON
with completed requests, connection counts, RSS, and Python heap
samples. RSS is measured in the client process, excluding the server.
Exact memory figures vary by environment.

Across three fresh-process runs of 500 unread streams:

| Result | Before | After |
| --- | ---: | ---: |
| Open connections after explicit GC | 500 | 0 |
| Median client RSS increase | 7.03 MiB | 0.93 MiB |
| Median Python heap retained after GC | 3.35 MiB | 0.10 MiB |

With a 1,000-connection pool, request 1,001 failed with `PoolTimeout`
before the fix; all 1,001 completed afterward.

Closing after the first chunk also reproduced a GC cleanup deadlock
inside the HTTPcore pool lock in 3/3 runs with memory tracing disabled.
Each original-code run was stopped after 20 seconds; the fixed code
completed 500/500 cycles in every run. GC timing depends on allocations.

## Runtime Rollout Safety

- Rollout-managed feature(s): N/A; Python SDK resource cleanup.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: Closing a wrapped stream releases its
upstream response.
- Kill switch / disable path: N/A.
- Unsafe override required: No.
- Qualification impact: No rollout-channel changes.
- Rollback path: Revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-28 23:36:10 -05:00

317 lines
8.1 KiB
Python

from __future__ import annotations
import gc
import weakref
from types import SimpleNamespace
import httpx
import pytest
from openai import OpenAI
from headroom.client import HeadroomClient
class _ClosableIterator:
def __init__(
self,
values: list[object] | None = None,
error: Exception | None = None,
close_error: Exception | None = None,
):
self._values = iter(values or [])
self._error = error
self._close_error = close_error
self.closed = 0
def __iter__(self):
return self
def __next__(self):
if self._error is not None:
error, self._error = self._error, None
raise error
return next(self._values)
def close(self):
self.closed += 1
if self._close_error is not None:
raise self._close_error
class _IterableOnly:
def __init__(self, values: list[object]):
self._values = values
self.closed = 0
def __iter__(self):
return iter(self._values)
def close(self):
self.closed += 1
class _RetainedIterable:
def __init__(self):
self.iterator = None
self.closed = 0
def __iter__(self):
def generate():
try:
yield "chunk"
yield "later"
finally:
self.closed += 1
self.iterator = generate()
return self.iterator
class _DistinctClosableSource:
def __init__(
self, owner_error: Exception | None = None, iterator_error: Exception | None = None
):
self.owner_error = owner_error
self.iterator_error = iterator_error
self.closed = 0
self.iterator = None
def __iter__(self):
self.iterator = _ClosableIterator(["chunk"], close_error=self.iterator_error)
return self.iterator
def close(self):
self.closed += 1
if self.owner_error is not None:
raise self.owner_error
class _Owner:
def __init__(self):
self.saved = []
self._storage = SimpleNamespace(save=self.saved.append)
class _ClosableSse(httpx.SyncByteStream):
def __init__(self):
self.closed = 0
def __iter__(self):
yield (
b'data: {"id":"x","object":"chat.completion.chunk","created":1,'
b'"model":"gpt","choices":[{"index":0,"delta":{"content":"hi"},'
b'"finish_reason":null}]}\n\n'
)
yield b"data: [DONE]\n\n"
def close(self):
self.closed += 1
def _openai_stream(body: _ClosableSse):
def handler(request: httpx.Request):
return httpx.Response(
200,
headers={"content-type": "text/event-stream"},
stream=body,
)
http_client = httpx.Client(transport=httpx.MockTransport(handler))
client = OpenAI(api_key="test", http_client=http_client)
stream = client.chat.completions.create(
model="gpt-test",
messages=[{"role": "user", "content": "hello"}],
stream=True,
)
return stream, http_client
def test_wrap_stream_closes_source_before_iteration_and_saves_once():
owner = _Owner()
source = _ClosableIterator(["chunk"])
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
wrapped.close()
wrapped.close()
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_closes_source_after_exhaustion_and_saves_once():
owner = _Owner()
source = _ClosableIterator(["chunk"])
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
assert list(wrapped) == ["chunk"]
wrapped.close()
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_does_not_iterate_after_close():
owner = _Owner()
source = _ClosableIterator(["chunk"])
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
wrapped.close()
with pytest.raises(StopIteration):
next(wrapped)
assert owner.saved == ["metrics"]
def test_wrap_stream_closes_source_on_error_and_saves_once():
owner = _Owner()
source = _ClosableIterator(error=RuntimeError("boom"))
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
with pytest.raises(RuntimeError, match="boom"):
next(wrapped)
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_supports_iterators_without_close():
owner = _Owner()
wrapped = HeadroomClient._wrap_stream(owner, iter(["chunk"]), "metrics")
assert list(wrapped) == ["chunk"]
assert owner.saved == ["metrics"]
def test_wrap_stream_supports_iterable_only_sources():
owner = _Owner()
source = _IterableOnly(["chunk"])
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
assert list(wrapped) == ["chunk"]
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_preserves_iteration_error_when_close_fails():
owner = _Owner()
source = _ClosableIterator(
error=RuntimeError("iteration"),
close_error=RuntimeError("close"),
)
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
with pytest.raises(RuntimeError, match="iteration"):
next(wrapped)
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_closes_retained_iterator_when_source_has_no_close():
owner = _Owner()
source = _RetainedIterable()
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
assert next(wrapped) == "chunk"
wrapped.close()
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_closes_distinct_source_and_iterator():
owner = _Owner()
source = _DistinctClosableSource()
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
assert next(wrapped) == "chunk"
wrapped.close()
assert source.closed == 1
assert source.iterator.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_closes_both_owners_when_each_close_fails():
owner = _Owner()
source = _DistinctClosableSource(
owner_error=RuntimeError("owner close"),
iterator_error=RuntimeError("iterator close"),
)
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
assert next(wrapped) == "chunk"
wrapped.close()
wrapped.close()
assert source.closed == 1
assert source.iterator.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_stream_finalizes_started_abandoned_stream():
owner = _Owner()
source = _ClosableIterator(["chunk"])
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
next(wrapped)
del wrapped
gc.collect()
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_closed_stream_releases_source_and_owner():
owner = _Owner()
source = _ClosableIterator(["chunk"])
owner_ref, source_ref = weakref.ref(owner), weakref.ref(source)
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
wrapped.close()
del owner, source
gc.collect()
assert owner_ref() is None
assert source_ref() is None
def test_wrap_stream_context_manager_closes_on_consumer_error():
owner = _Owner()
source = _ClosableIterator(["chunk"])
with pytest.raises(RuntimeError, match="consumer"):
with HeadroomClient._wrap_stream(owner, source, "metrics") as wrapped:
assert next(wrapped) == "chunk"
raise RuntimeError("consumer")
assert source.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_real_openai_stream_closes_before_first_chunk():
body = _ClosableSse()
source, http_client = _openai_stream(body)
owner = _Owner()
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
wrapped.close()
http_client.close()
assert body.closed == 1
assert owner.saved == ["metrics"]
def test_wrap_real_openai_stream_closes_after_first_chunk():
body = _ClosableSse()
source, http_client = _openai_stream(body)
owner = _Owner()
wrapped = HeadroomClient._wrap_stream(owner, source, "metrics")
next(wrapped)
wrapped.close()
http_client.close()
assert body.closed == 1
assert owner.saved == ["metrics"]