Skip to content

fix: close backend clients and event-loop threads to stop resource leaks - #1648

Merged
psschwei merged 10 commits into
generative-computing:mainfrom
psschwei:noisy-tests
Sep 18, 2026
Merged

psschwei merged 10 commits into
generative-computing:mainfrom
psschwei:noisy-tests

Conversation

@psschwei

Copy link
Copy Markdown
Contributor

Pull Request

Issue

Fixes #349

Description

Fixes the resource leaks behind #349: 50+ ResourceWarnings (unclosed sockets, transports, event loops) across the test suite, all pointing at real cleanup gaps rather than just log noise.

Correction to the issue: the warnings aren't actually visible today — pytest 9 no longer forces always for all warning categories, so ResourceWarning falls back to Python's default-ignore list. Nothing shows up unless you pass -W always::ResourceWarning. The leaks are still there; only the "noise" symptom is gone.

Escalation found while investigating: a separate, worse leak in the same area — _EventLoopHandler spawned a fresh event loop + daemon thread on every nested _run_async_in_thread call and never shut it down. This is reachable from ordinary user code (call_tools() re-enters the handler loop from an async @tool wrapper), so it's fixed here alongside the resource warnings rather than split out.

Root causes fixed

  1. _EventLoopHandler._close_event_loop called loop.stop() from a foreign thread (not thread-safe, often didn't wake the selector), never joined the thread, never called loop.close(). The nested branch in __call__ also built a fresh _EventLoopHandler() per call and dropped it, leaking a thread + loop + fds every time. Rewrote shutdown to cancel tasks on the loop, gather, then call_soon_threadsafe(loop.stop) → thread join → loop.close(), made idempotent, and made teardown deterministic in __call__ instead of relying on __del__.
  2. ClientCache evicted entries without closing them and had no clear(). It now keys on the event loop object itself (not id(loop), which can be reused by a new loop after the old one is GC'd) and takes an optional aclose closer, invoked on eviction and by new clear()/aclear() methods.
  3. Backend had no way to release the clients it holds open. Added default no-op close()/aclose() to the ABC, overridden in OllamaModelBackend, OpenAIBackend, and WatsonxAIBackend to close their sync client and clear their cached async client(s).

Testing

  • Tests added to the respective file if code was changed
  • New code has 100% coverage if code was added
  • Ensure existing tests and github automation passes (a maintainer will kick off the github automation when the rest of the PR is populated)

Added:

  • test/helpers/test_event_loop_helper.py: nested-call thread-leak regression test, _close_event_loop idempotency test.
  • test/helpers/test_async_helpers.py: ClientCache closer-on-eviction and clear()/aclear() tests.
  • test/backends/test_client_close_unit.py (new): close()/aclose() unit tests for Ollama, OpenAI, and Watsonx backends.
  • test/backends/test_ollama_socket_leak.py (new): real-socket e2e regression guard — creates a backend, drives it, closes it, asserts no ResourceWarning survives gc.collect(). This is a targeted stand-in for globally re-enabling -W always::ResourceWarning, scoped to one backend so it doesn't drown in third-party warning noise.
  • Closed backends in the module/function-scoped fixtures the leak census implicated: test/backends/test_ollama.py, test/backends/test_openai_ollama.py, test/backends/test_watsonx.py, test/stdlib/test_session.py.

Verified against a live Ollama server: full suite (pytest test/ -m "not qualitative" -W "always::ResourceWarning") drops from a 54-socket/26-transport baseline to 44/22. ruff format/ruff check/mypy clean; docstring quality gate (Backend gained public methods) at 100% coverage, 0 issues.

Known, accepted residual: the remaining warnings all trace to async def tests whose per-test event loop (pytest-asyncio's default function scope) closes before any fixture teardown runs — structurally the same as an async client stranded on an already-closed asyncio.run() loop, just triggered by pytest-asyncio rather than by test code directly. Fixture-level cleanup can't reach these; closing them would need either inline await backend.aclose() in every affected async test or a broader pytest-asyncio loop-scope change. Neither is in scope here — this PR fixes what fixture-level cleanup can reach and adds a regression test for it, matching the "targeted test over global suppression" approach.

Attribution

  • AI coding assistants used

Adding a new component, requirement, sampling strategy, or tool?

If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.

@psschwei
psschwei requested a review from planetf1 September 14, 2026 21:30
@psschwei
psschwei requested a review from a team as a code owner September 14, 2026 21:30
@github-actions github-actions Bot added the bug Something isn't working label Sep 14, 2026
Signed-off-by: Paul S. Schweigert <[email protected]>
Comment thread test/backends/test_client_close_unit.py Resolved

@planetf1 planetf1 left a comment

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.

Left inline comments — a few gaps in the new close/eviction machinery, mainly around the eviction/close path still being able to block the caller's event loop in some cases.

Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread mellea/backends/watsonx.py Resolved
Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread mellea/core/backend.py Resolved
Signed-off-by: Paul S. Schweigert <[email protected]>

@ajbozarth ajbozarth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some feedback from Claude (reviewed on my behalf):

Solid work — the event-loop shutdown reordering, the nested-handler teardown, and the loop-object rekeying all check out, and the test coverage is thorough. I verified the rekeying is applied consistently across all three backends with no leftover id(...) call site, and that the HF (aLoRA) and LiteLLM backends are correctly out of scope. Not requesting changes; three low-priority notes inline, none blocking.

Comment thread mellea/helpers/async_helpers.py Outdated
# If the cache is full, remove the least recently used item
self.cache.popitem(last=False)
evicted_key, evicted_value = self.cache.popitem(last=False)
self._close_entry(evicted_key, evicted_value, wait=False)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Behavior change worth a sanity check: eviction used to just drop the reference and let GC close the client lazily; now it actively schedules aclose() on the client's loop. If a backend is ever driven by more than 2 concurrent live event loops, an evicted client could have its transport closed mid-request. Very unlikely given the single-background-loop design — just confirming it was a considered tradeoff.

@psschwei psschwei Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Left the behavior as is and wrote the reasoning into ClientCache.put: closing on eviction assumes at most capacity loops drive a backend concurrently (true for the single-background-loop design); past that an evicted transport could close under an in-flight request, and the alternative (drop the reference, wait for GC) is exactly what leaked sockets. Worth noting the hazard is narrower than it looks: an evicted entry whose loop has already closed can't be closed at all, so the risky window needs 3+ live loops on one backend.

Comment thread mellea/helpers/async_helpers.py Outdated
else:
# A loop that is neither running nor closed has no thread to schedule on;
# only `run_until_complete` can drive it.
_close_client_for_loop(client, loop, aclose)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This branch silently no-ops in one case: for a client bound to a loop that's neither running nor closed, reached from async code, delegating to _close_client_for_loop runs loop.run_until_complete(...), which raises RuntimeError inside the already-running caller loop and gets swallowed by the except — so the client falls to GC rather than closing here. Rare degenerate case and consistent with the documented "GC reclaims it" philosophy, but the delegation doesn't actually achieve what the branch comment intends.

@psschwei psschwei Sep 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

mellea/helpers/async_helpers.py:344 delegated the stopped-but-not-closed loop case to _close_client_for_loop, which calls loop.run_until_complete() — that raises inside the caller's already-running loop and got swallowed, so the client fell to GC. Now it goes through asyncio.to_thread(...), where no loop is running, so run_until_complete can actually drive the stopped loop; the coroutine awaits the result. Verified the old path silently no-oped (it also leaked a "coroutine was never awaited" warning); added test_aclear_drives_a_stopped_loop_to_close_its_entry, which fails on the old code.

Comment thread mellea/backends/openai.py
Safe to call more than once; subsequent calls close nothing further.
"""
try:
self._client.close()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Optional/nit: close() closes the sync self._client permanently with no reuse guard, while clearing the async cache lets _async_client rebuild on next access — so after close() the backend is in an asymmetric state (sync calls fail, async calls silently work). Fine for a teardown-only API; flagging in case reuse-after-close should instead raise cleanly. Same asymmetry applies to the Ollama sync client.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a "teardown only, not a reset" paragraph to Backend.close (published API reference) and to the Ollama/OpenAI close() overrides, stating plainly that the sync client can't be reopened while a later async call rebuilds one into the emptied cache, so callers should build a new backend. I did not add a _closed guard that raises: that's a user-facing behavior change to a teardown path, beyond the note's scope. Say the word if you'd rather it raise cleanly, it's a small follow-up.

Signed-off-by: Paul S. Schweigert <[email protected]>
Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread test/stdlib/test_session.py Resolved
Comment thread mellea/helpers/async_helpers.py Resolved
Comment thread mellea/helpers/event_loop_helper.py Resolved
Comment thread mellea/helpers/event_loop_helper.py Resolved
Signed-off-by: Paul S. Schweigert <[email protected]>
Signed-off-by: Paul S. Schweigert <[email protected]>
Signed-off-by: Paul S. Schweigert <[email protected]>
Signed-off-by: Paul S. Schweigert <[email protected]>
Signed-off-by: Paul S. Schweigert <[email protected]>
@planetf1

planetf1 commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Thanks @psschwei — went back through all my points in the code against 0e88f3095. All good, threads resolved.

On Alex's close() one, I lean towards fixing it here — post-close behaviour is a bit worse than I first thought. Ollama's sync client does raise clearly (RuntimeError: Cannot send a request, as the client has been closed), but the OpenAI SDK wraps that same error into APIConnectionError: Connection error., so a closed backend looks just like a server outage. On the async side, a later call quietly rebuilds a client into the emptied cache. To be fair that one isn't orphaned — a further close() does reclaim it — but nobody makes that call having already torn down, so in practice you're back to sockets held for the life of the process, which is the thing this PR is here to stop. Given you already pulled get_or_create in for the same reason, a _closed guard feels in scope rather than a follow-up.

Also, your two replies to Alex look swapped — :424 answers his :344 point and vice versa. Both right, but each reads as a non-answer as filed.

Minor, no change wanted: get_or_create holds the lock across factory(), and watsonx's fetches an IAM token in APIClient.__init__. First-use only, and Watsonx is deprecated anyway — just noting it.

Edited twice for accuracy: the sync path errors clearly on Ollama but not OpenAI (generic connection error there), and the resurrected async client is reclaimable by a second close() rather than orphaned outright.

@psschwei

Copy link
Copy Markdown
Contributor Author

Also, your two replies to Alex look swapped — :424 answers his :344 point and vice versa. Both right, but each reads as a non-answer as filed.

Thanks, should be fixed now

Signed-off-by: Paul S. Schweigert <[email protected]>

@planetf1 planetf1 left a comment

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.

LGTM

@psschwei
psschwei added this pull request to the merge queue Sep 18, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Sep 18, 2026
@psschwei
psschwei added this pull request to the merge queue Sep 18, 2026
Merged via the queue into generative-computing:main with commit 42dc3a0 Sep 18, 2026
12 checks passed
@psschwei
psschwei deleted the noisy-tests branch September 18, 2026 13:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test: Resource warnings - noise in log and may mask library issues

4 participants