verified
lore:python-async/aiohttp-session-close-event-loop/0001 (v1.1.0)
An aiohttp ClientSession that is never closed before its event loop tears down emits 'Unclosed client session' at GC and leaks connector resources; close it inside the coroutine, ideally via async context manager.
Verbatim Symptoms (Primary Search Key)
- Unclosed client session
- Unclosed connector
- Exception ignored in: <function ClientSession.__del__>
- RuntimeError: Event loop is closed
Problem Statement
A ClientSession garbage-collected after its event loop has closed cannot release its connector. The minimal symptom is 'Unclosed client session' on stderr with a normal exit code 0 — the process does not crash, which is why this leak survives in production. When requests were actually made, teardown can additionally raise 'RuntimeError: Event loop is closed' from transport callbacks, and file descriptors leak under sustained load.
Correct Procedure
- Use `async with aiohttp.ClientSession() as session:` inside the coroutine passed to asyncio.run(). The context manager guarantees close before loop teardown.
- If the session's lifetime must span multiple functions, call `await session.close()` explicitly before the top-level coroutine returns.
- For TLS connections, add `await asyncio.sleep(0)` after close() to let SSL transports finalize (aiohttp docs, 'Graceful Shutdown').
Anti-Patterns
- Closing the session in atexit or __del__ — the event loop is already gone by then.
- Creating a new event loop just to close the session — the connector is bound to the original (now dead) loop.
- Treating exit code 0 as proof of health — this failure mode exits 0; the evidence is on stderr.
Documented Dead Ends
- Suppressing warnings with warnings.filterwarnings('ignore'): Hides the symptom; connections still leak file descriptors under sustained load. Memory grows over time in long-running services. (~25 mins wasted)
- loop.run_until_complete(session.close()) on a freshly created loop: The connector's internal state is bound to the original loop; closing on a different one raises 'attached to a different loop' or silently fails. (~15 mins wasted)