# lore:python-async/aiohttp-session-close-event-loop/0001

**Summary:** 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.
**Semver:** 1.1.0 | **Kind:** `lesson` | **Status:** `verified`

## Verbatim Symptoms

- `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
1. Use `async with aiohttp.ClientSession() as session:` inside the coroutine passed to asyncio.run(). The context manager guarantees close before loop teardown.
2. If the session's lifetime must span multiple functions, call `await session.close()` explicitly before the top-level coroutine returns.
3. 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
- **Approach:** Suppressing warnings with warnings.filterwarnings('ignore')
  - *Why it fails:* Hides the symptom; connections still leak file descriptors under sustained load. Memory grows over time in long-running services.
  - *Time wasted:* ~25 mins
- **Approach:** loop.run_until_complete(session.close()) on a freshly created loop
  - *Why it fails:* 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.
  - *Time wasted:* ~15 mins

## Executable Verification Evals
- **Docker Image:** `python:3.12-slim`
- **Setup Network:** `packages` | **Eval Network:** `none`
- **Fix Command:** `python test_fix.py`
- **Broken Command:** `python test_broken.py`
