Skip to content

fix(core): wait for the caller before a stream's last chunk - #109

Merged
gopaljigaur merged 2 commits into
mainfrom
fix/abandoned-stream-thread
Oct 15, 2026
Merged

gopaljigaur merged 2 commits into
mainfrom
fix/abandoned-stream-thread

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

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 schedules aclose(), whose finally cancels the run as before.

The leak comes from where that cancellation lands:

  1. LiteLLM finishes a stream in _finalize_completed_stream, which runs stream_chunk_builder through asyncify, that is anyio.to_thread.run_sync.
  2. AnyIO's WorkerThread.run skips 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.
  3. Since perf(core): keep un-iterated events short and pace streams by deltas #94 a paced run reads up to 16 deltas ahead, so with a short answer it reaches the end of the stream while its caller holds the first delta. The finalizer's aclose() comes a couple of loop turns after the iterator is dropped and cancels the run inside LiteLLM's thread call. With anyio.to_thread.run_sync instrumented, 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 after break cancels 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 through litellm.acompletion with mock responses, Python 3.14, breaking at the first TextDelta and dropping the iterator:

Runs AnyIO workers, main AnyIO workers, this PR
500 34 1
1,000 84 1
1,500 139 1

Tests

test_dropped_event_stream_leaves_no_thread_or_task drops 20 iterators without aclose() 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-files and uv run mypy cyclops pass.

#96 (soak suite) is not merged yet; it marks abandoned_generator as a strict xfail(#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

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One should-fix finding, on the test. The fix itself is correct.

Checked

  • uv run pytest passes on the default Python and on 3.10.19 (476 passed, 1 unrelated xfail, on top of main at 6c623a8). Pre-commit and uv run mypy cyclops pass, and CI is green.
  • The root cause is an AnyIO bug, not misuse. WorkerThread.run skips a job whose future is already cancelled and never calls _report_result, the only place a worker goes back to idle_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 native task.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 a finish_reason="stop" chunk, then run_sync(stream_chunk_builder), then the usage chunk, then a second run_sync. A streamed tool call goes tool call chunk, then a finish_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_stream returns a separate finish_reason_handler() chunk first, and only the next call reaches asyncify. 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_events 0.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_events closed after one event still closes cleanly. tests/test_retries.py passes 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.

Comment thread tests/test_agent.py Resolved
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
gopaljigaur force-pushed the fix/abandoned-stream-thread branch from 5ff78d3 to 95943fa Compare October 15, 2026 04:29

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

Re-reviewed 95943fa.

  • git merge-base --is-ancestor origin/main 95943fa holds (main at abbed05). git range-diff shows the fix commit unchanged (5ff78d3 = 28bf01b); the test change is its own commit.
  • test_dropped_event_stream_leaves_no_thread_or_task fails 20 of 20 runs with main's completion.py and passes 20 of 20 with the fix.
  • uv run pytest passes on the default Python and on 3.10.19 (471 passed, 1 unrelated xfail). Pre-commit and uv run mypy cyclops pass, and CI is green.
  • Confidentiality and prose: nothing in the title, body, commits, added lines or the reply, and no dashes used as punctuation.

@gopaljigaur
gopaljigaur merged commit bf4f5d4 into main Oct 15, 2026
9 checks passed
@gopaljigaur
gopaljigaur deleted the fix/abandoned-stream-thread branch October 15, 2026 04:43
gopaljigaur added a commit that referenced this pull request Oct 15, 2026
…plainly

The sessions scenario now gives its agent the store, so every run saves
its session in the background as main does since autosave, instead of
saving by hand. #109 fixed #103, so the abandoned generator scenario is a
plain one.
gopaljigaur added a commit that referenced this pull request Oct 15, 2026
…plainly

The sessions scenario now gives its agent the store, so every run saves
its session in the background as main does since autosave, instead of
saving by hand. #109 fixed #103, so the abandoned generator scenario is a
plain one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An abandoned event stream leaves an AnyIO worker thread behind

1 participant