Repository navigation
fix(core): wait for the caller before a stream's last chunk - #109
Merged
Merged
Conversation
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
One should-fix finding, on the test. The fix itself is correct.
Checked
uv run pytestpasses on the default Python and on 3.10.19 (476 passed, 1 unrelated xfail, on top of main at 6c623a8). Pre-commit anduv run mypy cyclopspass, and CI is green.- The root cause is an AnyIO bug, not misuse.
WorkerThread.runskips a job whose future is already cancelled and never calls_report_result, the only place a worker goes back toidle_workers. I read it in 4.11.0 (locked) and 4.15.1 (latest). Standalone scripts without cyclops leak 200 workers in 200 calls, with 0 jobs run, on both versions and on Python 3.10 and 3.14. That holds for a nativetask.cancel(), and also for AnyIO's own API (run_sync(..., abandon_on_cancel=True)in a task group whose scope is cancelled), which rules out misuse. I found no existing AnyIO issue for it. - LiteLLM always sends a finish chunk before its thread call. Traced on 1.105.1 with
stream_options={"include_usage": True}. A text stream goes text chunks, then afinish_reason="stop"chunk, thenrun_sync(stream_chunk_builder), then the usage chunk, then a secondrun_sync. A streamed tool call goes tool call chunk, then afinish_reason="tool_calls"chunk, then the same two calls. When the provider's last chunk carries content, LiteLLM strips its finish reason. In that case_finalize_completed_streamreturns a separatefinish_reason_handler()chunk first, and only the next call reachesasyncify. So the wait always comes before both thread calls. - The fix works. With a tool call and a short answer, the run is dropped at the first
TextDelta. On main that leaves 7 workers after 500 runs and 12 after 1,000; with this PR, 1 after both (the normal idle worker). This machine leaks fewer than the PR's table, but the growth is the same. With plain text and the PR, no worker is ever created, because the cancel lands on the run's wait before LiteLLM gets that far. - No cost elsewhere. It adds one wait per completion. The #94 bench is identical on main and the PR:
astream_events0.12 iterations per token, sync 2.12, peak memory unchanged. A paced consumer that stops still lets 202 tool call chunks be read, and a sync caller holding the iterator still runs no tool. - Unchanged interactions:
- The wait sits outside the per-chunk idle timeout.
- Retries before the first delta are unaffected: the wait emits nothing.
- On 3.10 an
astream_eventsclosed after one event still closes cleanly.tests/test_retries.pypasses on 3.10.
- The remaining race (an explicit cancel exactly while LiteLLM finishes) is stated in the PR body and is AnyIO's to fix. That is acceptable; an upstream report would close it.
- Confidentiality and prose: nothing in the title, body, commit, added lines or issue #103, and no dashes used as punctuation.
LiteLLM finishes a stream in an AnyIO worker thread, and AnyIO never returns a worker to its pool when the job's future is cancelled before the worker starts it. A paced run that read ahead to the end of its stream while its caller dropped the iterator was cancelled right there, so every abandoned stream could leave a thread until the event loop's main task ended. The run now waits for its caller at the chunk with a finish reason, so a stream whose caller stops reading is cancelled before LiteLLM ends it.
gopaljigaur
force-pushed
the
fix/abandoned-stream-thread
branch
from
October 15, 2026 04:29
5ff78d3 to
95943fa
Compare
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
No findings.
Re-reviewed 95943fa.
git merge-base --is-ancestor origin/main 95943faholds (main at abbed05).git range-diffshows the fix commit unchanged (5ff78d3 = 28bf01b); the test change is its own commit.test_dropped_event_stream_leaves_no_thread_or_taskfails 20 of 20 runs with main'scompletion.pyand passes 20 of 20 with the fix.uv run pytestpasses on the default Python and on 3.10.19 (471 passed, 1 unrelated xfail). Pre-commit anduv run mypy cyclopspass, and CI is green.- Confidentiality and prose: nothing in the title, body, commits, added lines or the reply, and no dashes used as punctuation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Root cause
The thread is not held by the read ahead buffer, the sync bridge or an unclosed LiteLLM stream. The asyncgen hooks already close an abandoned
astream_events()iterator: the loop's finalizer schedulesaclose(), whosefinallycancels the run as before.The leak comes from where that cancellation lands:
_finalize_completed_stream, which runsstream_chunk_builderthroughasyncify, that isanyio.to_thread.run_sync.WorkerThread.runskips a job whose future is already cancelled and never calls_report_result, so that worker never goes back to the idle pool. It stays until the loop's main task ends. This holds on anyio 4.11.0 (locked) and 4.15.1 (latest): a task cancelled right after it queues a job leaks one worker every time.aclose()comes a couple of loop turns after the iterator is dropped and cancels the run inside LiteLLM's thread call. Withanyio.to_thread.run_syncinstrumented, 300 of 300 abandoned runs were cancelled there. Before perf(core): keep un-iterated events short and pace streams by deltas #94 the run waited at a join after every chunk, so the cancellation found it there.An explicit
aclose()right afterbreakcancels the run mid stream, before LiteLLM ends it, which is why it kept one worker.Fix
The run waits for its caller at the chunk that carries a finish reason, the last chunk before LiteLLM ends the stream, instead of reading on. A caller that stopped reading now holds the run before that point, so its cancellation lands on the run's own wait. Read ahead within a completion is unchanged, and so is the wait after the stream for tool calls and the next completion.
A run cancelled while LiteLLM ends a stream can still leak a worker, for example
handle.cancel()timed exactly there. That race was there before #94 and belongs to AnyIO.Measurements
astream_events()with one tool call and a short answer throughlitellm.acompletionwith mock responses, Python 3.14, breaking at the firstTextDeltaand dropping the iterator:Tests
test_dropped_event_stream_leaves_no_thread_or_taskdrops 20 iterators withoutaclose()and checks that no task is left and no AnyIO worker thread was created; it failed 20 of 20 runs on main and passed 20 of 20 with the fix.uv run pytest(471 passed, 1 xfailed for #108),uv run pre-commit run --all-filesanduv run mypy cyclopspass.#96 (soak suite) is not merged yet; it marks
abandoned_generatoras a strictxfail(#103), which this fix turns into an XPASS, so that mark should be removed when #96 merges after this, or in a follow up if it merges first.Closes #103