RuntimeError In _AsyncHttpxClientWrapper.__Del__ When Event Loop Is Closed
langchain-openai and langchain-anthropic's _AsyncHttpxClientWrapper.__del__ calls asyncio.get_running_loop() without checking for a running loop. During interpreter shutdown or after loop closure, this raises RuntimeError, which is swallowed by a broad except Exception, preventing self.aclose() and causing unclosed httpx resource warnings.
The __del__ method unconditionally attempts to obtain a running event loop with asyncio.get_running_loop() and then schedules an async close; when no running loop exists (e.g., after asyncio.run() returns or at interpreter shutdown), get_running_loop() raises RuntimeError, which the current broad except Exception block silently ignores, so self.aclose() is never invoked.
Run the provided minimal example: import asyncio, gc, _AsyncHttpxClientWrapper; define async main that creates client; run with asyncio.run(main()); after loop closes call gc.collect(); __del__ executes, get_running_loop raises RuntimeError, caught and suppressed, httpx emits unclosed resource warning.
Fixing Code Block
def __del__(self) -> None:
try:
loop = asyncio.get_running_loop()
except RuntimeError:
# No running event loop; we cannot safely schedule an async cleanup.
# Attempt to close on a fresh loop only if the interpreter is still sane.
try:
asyncio.run(self.aclose())
except Exception:
pass
return
if loop.is_running():
loop.create_task(self.aclose())
else:
# This branch should be unreachable, but keep as a defensive fallback.
asyncio.run(self.aclose())
Wrap get_running_loop in a dedicated except RuntimeError to distinguish the no-loop case from other exceptions. If no loop is running, attempt a synchronous cleanup via asyncio.run, which creates a temporary loop, but guard with try/except to avoid interpreter shutdown failures. If a running loop exists, schedule the close as a task; otherwise fall back to asyncio.run as a defensive measure.
Edge Case Audit
Calling asyncio.run inside __del__ can be unsafe during interpreter finalization or if the thread already has a closed loop; it may create a new loop that conflicts with shutdown or raise further errors, which are swallowed. This could still leave resources unclosed in rare edge cases. If this hotfix causes new warnings or hangs, revert to simply returning when no running loop is found (accepting the leak) or move cleanup to weakref.finalize with a synchronous close where possible.