Commit Graph
1 Commits
Author SHA1 Message Date
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