Repository navigation
fix: close backend clients and event-loop threads to stop resource leaks - #1648
Conversation
Signed-off-by: Paul S. Schweigert <[email protected]>
Signed-off-by: Paul S. Schweigert <[email protected]>
planetf1
left a comment
There was a problem hiding this comment.
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.
Signed-off-by: Paul S. Schweigert <[email protected]>
ajbozarth
left a comment
There was a problem hiding this comment.
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.
| # 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| Safe to call more than once; subsequent calls close nothing further. | ||
| """ | ||
| try: | ||
| self._client.close() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
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]>
|
Thanks @psschwei — went back through all my points in the code against On Alex's Also, your two replies to Alex look swapped — Minor, no change wanted: 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 |
Thanks, should be fixed now |
Signed-off-by: Paul S. Schweigert <[email protected]>
42dc3a0
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
alwaysfor all warning categories, soResourceWarningfalls 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 —
_EventLoopHandlerspawned a fresh event loop + daemon thread on every nested_run_async_in_threadcall and never shut it down. This is reachable from ordinary user code (call_tools()re-enters the handler loop from an async@toolwrapper), so it's fixed here alongside the resource warnings rather than split out.Root causes fixed
_EventLoopHandler._close_event_loopcalledloop.stop()from a foreign thread (not thread-safe, often didn't wake the selector), never joined the thread, never calledloop.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, thencall_soon_threadsafe(loop.stop)→ thread join →loop.close(), made idempotent, and made teardown deterministic in__call__instead of relying on__del__.ClientCacheevicted entries without closing them and had noclear(). It now keys on the event loop object itself (notid(loop), which can be reused by a new loop after the old one is GC'd) and takes an optionalaclosecloser, invoked on eviction and by newclear()/aclear()methods.Backendhad no way to release the clients it holds open. Added default no-opclose()/aclose()to the ABC, overridden inOllamaModelBackend,OpenAIBackend, andWatsonxAIBackendto close their sync client and clear their cached async client(s).Testing
Added:
test/helpers/test_event_loop_helper.py: nested-call thread-leak regression test,_close_event_loopidempotency test.test/helpers/test_async_helpers.py:ClientCachecloser-on-eviction andclear()/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 noResourceWarningsurvivesgc.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.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/mypyclean; docstring quality gate (Backendgained public methods) at 100% coverage, 0 issues.Known, accepted residual: the remaining warnings all trace to
async deftests 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-closedasyncio.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 inlineawait 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
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.
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.