fix(api): clean up Responses model stream iterators #6107
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #6107"
general
weight: 0.35
Jackmeson1
What happens
Physical-model
/v1/responsesstreams do not deterministically clean up their acquired iterators: teardown releases accounting but does not explicitly close the model generator or destroy its remoteIteratorWrapper. This also leaves P/D router finalizers and shared scheduler capacity dependent on later cleanup. Eventual GC behavior is not established by these tests.Cause
Responses uses accounting-only cleanup instead of the existing stream-cleanup contract: abort interrupted work, close the direct model observer, explicitly destroy the acquired remote iterator, and release accounting even if abort or close fails.
An abort timeout implemented with
asyncio.wait_foralso waits for cancellation to finish. With a real Xoscar RPC, a blocked prefill abort can therefore hold up iterator cleanup and keep a healthy decode replica's slot occupied beyond that timeout.Change
Keep acquisition before SSE headers, pass a private top-level model request ID, and bind the acquired iterator to the existing abort controller. The body finalizer, disconnect callback, and background task await one retained, shielded cleanup task. Mark normal exhaustion before terminal Responses events; keep failed acquisition outside stream ownership.
Follow-up
e17475f9configures a five-second abort timeout for Responses. Follow-up087ce714separates the API's wait from RPC cancellation: retain the plain abort task and useasyncio.waiton a shielded reference. Reaching the timeout leaves the RPC running, allowing iterator destruction and serve-slot release to proceed. Retrieve the task's eventual result, log any RPC failure once, and consume the shield's propagated exception.The final adjustment shares one abort-wait deadline across repeated cleanup callers and reports its expiration once. The same bounded-wait behavior applies to the Anthropic chat path and the shared non-streaming request helper. Callers configured with
abort_timeout=None, including OpenAI chat and completion streaming, remain unbounded.This bounds the abort wait. Iterator destruction, accounting release, and process shutdown retain their existing waits.
| Lifecycle | Before | After |
|---|---|---|
| Disconnect before body, during send, or during a model read | Accounting-only teardown | Join active iteration, close/destroy the acquired iterator, and release accounting once |
| Stream error or early error payload | Failure event with accounting-only teardown | Preserve failure events and clean up interrupted work |
| Normal exhaustion | Accounting-only teardown | Explicit iterator cleanup without disconnect abort |
For tracked ModelActor streams, the controller targets the admitting actor and stream UID, preventing a delayed disconnect from cancelling a replacement owner. Cleanup does not add an abort block after an explicit zero-block abort reaches EOF. Public schemas, event ordering, setup error responses, non-streaming Responses, and Token Router HTTP streams are unchanged.
| Engine/path | Scope |
|---|---|
| vLLM | Existing tracked native stream cleanup and abort behavior |
| SGLang | Existing native tracking and cancellation |
| TRT-LLM | Existing tracked async stream cleanup; no shared fallback added |
| Transformers | Actor-owned streams through existing shared scheduling/batching paths |
| llama.cpp | Actor wrapper destruction and existing sync/native cleanup |
| MLX | Existing actor cleanup and shared scheduling |
| P/D: vLLM, MLX, TRT-LLM | Router destruction runs sequential decode/cache finalizers |
| P/D: SGLang, heterogeneous | Router destruction runs concurrent prefill/decode cleanup |
Cleanup has no engine gate. Transformers/llama.cpp P/D support is not introduced. Distribution-specific engines retain the actor iterator contract. The tests use fake engines/stages; they do not validate native GPU or Metal execution.
Tests
The original 23 new or strengthened Responses cases fail against
cad04961on Windows Python 3.10 and 3.14 and pass with the iterator-cleanup fix. The two additional stalled-abort cases fail againstb26551d1and pass withe17475f9. The real-Xoscar blocked-prefill case and two late-exception cases fail againste17475f9and pass with087ce714on both Windows versions. The Linux fail-before check againstcad04961also fails as expected.ASGI event gates cover disconnect before body iteration, during send, and during the next model read. The earlier stalled-abort cases shorten the configured timeout to 10 ms and verify iterator destruction and slot release while simulated remote work remains pending. Other cases cover errors, normal completion, repeated background cleanup, await checkpoints, close failure, and disabled GC destruction. Strong references remain alive through the assertions.
The real-Xoscar regression uses a local actor pool,
PDModelActor, and fake prefill/decode stages. It shortens the configured timeout to 50 ms, disconnects before the first body chunk, and checks response completion and decode accounting(0, 1)while prefill abort remains gated. It then opens the gate and verifies abort completion, one abort per stage, and no duplicate iterator destruction or slot release.Late-exception coverage checks both timeout and cancellation of an unbounded caller. The final assertions also check that repeated abort calls do not log another timeout. Anthropic and shared-helper timeout coverage checks cleanup while the retained abort is pending, then releases and joins that task.
Other real actor/router paths with fake inference cover sequential/concurrent P/D, released request/handoff state, native/shared sync/async ownership, a queued waiter, setup rejection, and explicit abort/replacement.
Validation
The following suite results cover branch head
087ce714, whose tree matches the Linux-tested tree.Checks ran on Ubuntu 24.04.5 LTS:
| Check | Result |
|---|---|
| Four changed API suites — Python 3.12.3, Transformers 5.23.0 | 180 passed |
| Four changed API suites — Python 3.12.3, Transformers 4.57.6 CI pin | 180 passed |
| Four changed API suites — Python 3.10.22 | 180 passed |
| Consumer suites — Python 3.12 | 318 passed |
| Pre-commit — changed files plus
xinference/types.pyand the touchedengine_family.py| Passed || Fail-before — production at
cad04961, updated tests | Failed as expected |The changed API suites are Responses, LLM request abort, Anthropic request abort, and non-streaming request abort. The consumer suites include Responses, Anthropic messages, authentication, cache salt, model catalog credentials, model recommendations, request overhead, REST metrics, Token Router audit/dispatch, and benchmarks. Their count overlaps the changed API suites.
Windows follow-up suites ran serially, offline and without weights, using:
| Suite | Python 3.10.20 | Python 3.14.6 |
|---|---:|---:|
|
xinference/api/tests/test_openai_responses.py| 50 passed | 50 passed ||
xinference/api/tests/test_llm_request_abort.py| 81 passed | 81 passed ||
xinference/api/tests/test_anthropic_request_abort.py| 21 passed | 21 passed ||
xinference/api/tests/test_non_streaming_request_abort.py| 28 passed | 28 passed ||
xinference/core/tests/test_pd_model.py| 164 passed | 164 passed || Total | 344 passed | 344 passed |
Earlier Windows checks at
b26551d1also passed on both versions:| Suite | Result per Python version |
|---|---:|
|
xinference/core/tests/test_request_tracking.py| 51 passed ||
xinference/core/tests/test_request_priority.py| 55 passed |For the round-3 change, Windows standalone Black 25.1.0, Ruff 0.17.3 including import ordering, whitespace checks, platform coverage, and scoped mypy passed. Windows pre-commit was blocked by its read-only cache database; the subsequent Linux pre-commit run passed.
Focused in-memory checks of the final adjustments passed on Windows Python 3.10.20 and 3.14.6, covering repeated/concurrent abort callers, late exceptions, unbounded-wait cancellation, and all five shared-helper interruption modes. A cooperative event-loop shutdown check also passed.
Earlier validation passed the 11 portable coverage unit tests and Linux-target mypy across 1,171 source files. That earlier Windows-target mypy run reported 35 POSIX-attribute errors in seven unchanged files. A later whole-tree mypy run reported six errors in three unchanged files, identical on
b26551d1. The separate Windows Bash-driven workflow harness failed with 15 failures and 137 subtest errors across 47 tests, with one skipped.Both Windows environments used xoscar 0.11.2, below the declared
>=0.12.2requirement. The Linux report does not record its xoscar version. Native GPU/Metal engines and the broader hardware-dependent suite were not run.AI disclosure: this was prepared with AI assistance (Claude Opus 5.5 and Claude Sonnet 5.5).
🤖 Generated with Claude Code
https://claude.ai/code/session_01JfvcPZyKcKQUG9fQGYfRMw