Skip to content

fix(aiohttp): reliably close recycled client sessions - #24231

Closed
alilxxey wants to merge 1 commit into
BerriAI:mainfrom
alilxxey:fix/aiohttp-session-cleanup
Closed

alilxxey wants to merge 1 commit into
BerriAI:mainfrom
alilxxey:fix/aiohttp-session-cleanup

Conversation

@alilxxey

@alilxxey alilxxey commented Mar 20, 2026 •

Copy link
Copy Markdown

Relevant issues

Fixes #24230

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have Added testing in the tests/test_litellm/ directory, Adding at least 1 test is a hard requirement - see details
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible, it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review

Delays 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)

CI status guideline:

  • 50-55 passing tests: main is stable with minor issues.
  • 45-49 passing tests: acceptable but needs attention
  • <= 40 passing tests: unstable; be careful with your merges and assess the risk.
  • 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

  • Retain strong references to background ClientSession.close() tasks in LiteLLMAiohttpTransport, so recycled aiohttp sessions are not dropped on fire-and-forget close paths.
  • Close replaced sessions across loop-mismatch, loop-inspection-error, and "Session is closed" retry paths.
  • Prune completed background close tasks and log failed background closes.
  • Add regression coverage in tests/test_litellm/test_streaming_connection_cleanup.py and tests/test_litellm/llms/custom_httpx/test_aiohttp_transport.py.
  • Targeted verification run:
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.py
  • Observed results:
    • 17 passed, 2 deselected
    • 11 passed

@vercel

vercel Bot commented Mar 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
litellm Ready Ready Preview, Comment Mar 20, 2026 6:08pm

Request Review

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


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.

@alilxxey

Copy link
Copy Markdown
Author

@greptileai

@codspeed

codspeed Bot commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 16 untouched benchmarks


Comparing alilxxey:fix/aiohttp-session-cleanup (2627bd0) with main (d7c419b)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a fire-and-forget task lifecycle bug in LiteLLMAiohttpTransport where recycled aiohttp.ClientSession close coroutines were wrapped in asyncio.create_task but the resulting Task object was immediately discarded, making it eligible for garbage collection before the session was actually closed (see CPython docs on task GC).

Key changes:

  • Introduces _background_close_tasks: ClassVar[set[asyncio.Task]] to hold strong references to in-flight close tasks, preventing premature GC.
  • Adds _schedule_session_close() which centralises session close scheduling, handles the cross-loop RuntimeError path by discarding the coroutine, and prunes already-complete tasks on each invocation.
  • Adds _discard_background_close_task() as a done-callback to remove completed tasks from the set and surface close errors via verbose_logger.debug.
  • Applies _schedule_session_close consistently across the loop-mismatch, loop-inspection-error, and "Session is closed" retry paths.
  • Regression coverage added across two test files with real aiohttp.ClientSession objects and monkeypatched control points.

Issues found:

  • _background_close_tasks can accumulate permanently-pending tasks from event loops that are closed before the close task gets a chance to run; _prune_background_close_tasks only removes done() tasks and will miss these.
  • In test_handle_session_closed_during_request, the background close task scheduled for the old session is never awaited in the finally block, which may surface ResourceWarning noise.
  • The _schedule_session_close call in the "Session is closed" retry path of handle_async_request is a no-op in production because aiohttp sets session.closed = True before raising the error; the intent is good but the effect doesn't materialise on that path.

Confidence Score: 4/5

  • Safe to merge; the fix is a net improvement with no regressions introduced.
  • The core mechanism (ClassVar set + done-callback pruning) is sound and directly addresses the GC-drop bug. Three minor concerns prevent a 5: (1) tasks from closed event loops can accumulate indefinitely in the ClassVar set; (2) the "Session is closed" retry path's new _schedule_session_close call is effectively a no-op in production; (3) a test's finally block doesn't drain background close tasks, risking unclosed-session warnings. None of these are regressions or correctness bugs in the hot path.
  • litellm/llms/custom_httpx/aiohttp_transport.py — specifically _prune_background_close_tasks (stale task accumulation) and the "Session is closed" retry block (no-op close call).

Important Files Changed

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
Loading

Comments Outside Diff (1)

  1. litellm/llms/custom_httpx/aiohttp_transport.py, line 354-367 (link)

    P2 _schedule_session_close is a no-op in the production "Session is closed" path

    When aiohttp raises RuntimeError("Session is closed"), the session is already fully closed — old_session.closed is True by the time _schedule_session_close is called here. That method checks if session.closed: return and 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 fake RuntimeError before actually closing the session, which is why scheduled_sessions[0].closed is False passes. In production, closed would be True and 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 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)

Comment on lines +672 to +688
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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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()

@github-actions

Copy link
Copy Markdown
Contributor

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.

@anmolg1997

Copy link
Copy Markdown
Contributor

Picked this up in #32003 since this one went stale - kept the strong-reference task registry idea (credited in the PR) and extended it to cover the fallback branch and the cross-loop lifecycles. Thanks for the groundwork @alilxxey.

This branch was successfully deployed

1 active deployment
Preview — 2627bd03 Deployed Mar 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: LiteLLMAiohttpTransport can leak recycled aiohttp ClientSession instances

3 participants