Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Alexey seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
Greptile SummaryThis PR fixes a fire-and-forget task lifecycle bug in Key changes:
Issues found:
Confidence Score: 4/5
|
| Filename | Overview |
|---|---|
| litellm/llms/custom_httpx/aiohttp_transport.py | Introduces _background_close_tasks ClassVar and _schedule_session_close to retain strong references to close tasks; correctly adds session close scheduling to three replacement paths. Minor concern: tasks from closed event loops that never complete won't be pruned by _prune_background_close_tasks. |
| tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py | Replaces a broad mock-based test with five focused unit tests covering each new code path. Uses mock sessions / monkeypatching; no real network calls. The old session in test_handle_session_closed_during_request has a background close task scheduled but is not awaited in the finally block, which may leave the session unclosed. |
| tests/test_litellm/test_streaming_connection_cleanup.py | Adds one new test (test_get_valid_client_session_closes_old_session_on_loop_mismatch) exercising the loop-mismatch path. Uses a FakeLoop to avoid real session creation with a bad loop; correctly awaits pending tasks and checks _background_close_tasks is empty afterwards. |
Sequence Diagram
sequenceDiagram
participant C as Caller
participant T as LiteLLMAiohttpTransport
participant S as Old ClientSession
participant NS as New ClientSession
participant BG as _background_close_tasks (ClassVar)
participant EL as asyncio Event Loop
C->>T: handle_async_request()
T->>T: _get_valid_client_session()
T->>S: getattr(session, "_loop")
T->>EL: asyncio.get_running_loop()
alt Loop mismatch or closed loop
T->>T: _schedule_session_close(old_session)
T->>S: session.close() → coroutine
T->>EL: asyncio.create_task(close_coro)
EL-->>T: task
T->>BG: _background_close_tasks.add(task)
T->>EL: task.add_done_callback(_discard_background_close_task)
T->>NS: _client_factory() / ClientSession()
T-->>C: new session
EL-->>BG: done callback fires → discard task
else No running loop (RuntimeError)
T->>T: _schedule_session_close(old_session)
Note over T: create_task raises RuntimeError<br/>→ close_coro.close() called<br/>"relying on GC"
T->>NS: _client_factory() / ClientSession()
T-->>C: new session
end
C->>T: handle_async_request() makes request
alt "Session is closed" RuntimeError
T->>T: _schedule_session_close(old_session)
Note over T: If session.closed → no-op<br/>(already closed by aiohttp)
T->>NS: _client_factory() / ClientSession()
T->>NS: retry _make_aiohttp_request()
T-->>C: response
end
Comments Outside Diff (1)
-
litellm/llms/custom_httpx/aiohttp_transport.py, line 354-367 (link)_schedule_session_closeis a no-op in the production "Session is closed" pathWhen aiohttp raises
RuntimeError("Session is closed"), the session is already fully closed —old_session.closedisTrueby the time_schedule_session_closeis called here. That method checksif session.closed: returnand exits immediately, so the call does nothing in the real failure scenario.The new test (
test_handle_session_closed_during_request) simulates this path by raising a fakeRuntimeErrorbefore actually closing the session, which is whyscheduled_sessions[0].closed is Falsepasses. In production,closedwould beTrueand the session would never be added to the background task set.This doesn't break anything (the session is already closed so no leak), but the intent — "ensure the old session is properly closed" — is not achieved on this specific code path. Consider whether this guard is still useful here, or whether it should be removed/documented to avoid confusion.
Last reviewed commit: "fix(aiohttp): reliab..."
| Credit to: https://github.com/karpetrosyan/httpx-aiohttp for this implementation | ||
| """ | ||
|
|
||
| _background_close_tasks: ClassVar[set[asyncio.Task[Any]]] = set() |
There was a problem hiding this comment.
Stale tasks from closed event loops accumulate forever
_background_close_tasks is a ClassVar shared across all instances and all event loops. _prune_background_close_tasks only removes tasks where task.done() is True. However, when an event loop is closed before a scheduled session.close() task has a chance to run, the task state remains PENDING and task.done() returns False. Such tasks are never pruned and will leak memory for the lifetime of the process.
This is particularly relevant in test environments (multiple event loops per process) but could also manifest in server-restart or long-running worker scenarios.
A straightforward mitigation is to also prune tasks whose event loop is closed:
@classmethod
def _prune_background_close_tasks(cls) -> None:
for task in tuple(cls._background_close_tasks):
if task.done():
cls._discard_background_close_task(task)
continue
# Also drop tasks whose loop is already closed; they will never run.
loop = task.get_loop()
if loop.is_closed():
cls._background_close_tasks.discard(task)| call_count["value"] += 1 | ||
| if call_count["value"] == 1: | ||
| raise RuntimeError("Session is closed") | ||
| return await _make_mock_response().__aenter__() | ||
|
|
||
| transport._make_aiohttp_request = tracked_make_request # type: ignore[method-assign] | ||
|
|
||
| try: | ||
| response = await transport.handle_async_request(httpx.Request("GET", "http://example.com")) | ||
|
|
||
| assert call_count["value"] == 2 # First request failed, second succeeded | ||
| assert counts["sessions"] == 2 # Created 2 sessions for retry | ||
| assert response.status_code == 200 | ||
| assert len(scheduled_sessions) == 1 | ||
| assert scheduled_sessions[0].closed is False | ||
| finally: | ||
| if isinstance(transport.client, aiohttp.ClientSession) and not transport.client.closed: |
There was a problem hiding this comment.
Old session not awaited in
finally block
tracked_schedule records the first (old) session and then calls the real _schedule_session_close, which creates a background asyncio.Task to close that session. The finally block only awaits the new transport.client; the background close task for the old session is never awaited. This can produce ResourceWarning: Unclosed client session noise and makes the test non-deterministic if the task happens to outlive the test's event loop teardown.
finally:
# Drain any pending background close tasks first so the old session is
# properly closed before teardown.
pending = list(LiteLLMAiohttpTransport._background_close_tasks)
if pending:
await asyncio.gather(*pending, return_exceptions=True)
LiteLLMAiohttpTransport._background_close_tasks.clear()
if isinstance(transport.client, aiohttp.ClientSession) and not transport.client.closed:
await transport.client.close()|
This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. |
Relevant issues
Fixes #24230
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
tests/test_litellm/directory, Adding at least 1 test is a hard requirement - see detailsmake test-unit@greptileaiand received a Confidence Score of at least 4/5 before requesting a maintainer reviewDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
CI (LiteLLM team)
Branch creation CI run
Link: pending
CI run for the last commit
Link: pending
Merge / cherry-pick CI run
Links: pending
Type
🐛 Bug Fix
Changes
ClientSession.close()tasks inLiteLLMAiohttpTransport, so recycled aiohttp sessions are not dropped on fire-and-forget close paths."Session is closed"retry paths.tests/test_litellm/test_streaming_connection_cleanup.pyandtests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py.poetry run env PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 pytest -q -p pytest_asyncio.plugin tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py -k "not sock_read_timeout_triggers and not streaming_does_not_timeout_on_total_duration" poetry run env PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 pytest -q -p pytest_asyncio.plugin tests/test_litellm/test_streaming_connection_cleanup.py tests/test_litellm/llms/custom_httpx/test_aiohttp_cleanup_closed.py17 passed, 2 deselected11 passed