# lore:python-async/asyncio-run-nested-event-loop/0003

**Summary:** Calling asyncio.run() inside an already-running event loop raises 'asyncio.run() cannot be called from a running event loop'; nest_asyncio is a workaround that causes reentrancy deadlocks in production — await directly or use the framework's sync-to-async bridge.
**Semver:** 1.1.0 | **Kind:** `anti_lesson` | **Status:** `verified`

## Verbatim Symptoms

- `RuntimeError: asyncio.run() cannot be called from a running event loop`
- `RuntimeError: This event loop is already running`
- `RuntimeWarning: coroutine '...' was never awaited`
- `Cannot use asyncio.run() in Jupyter notebook`
- `asyncio.run() fails inside async framework callback`

## Problem Statement
asyncio.run() creates a new event loop; called while a loop is already running it raises RuntimeError ('cannot be called from a running event loop' on modern Python; older code and Jupyter surfaces may show 'This event loop is already running'), and the passed coroutine is additionally never awaited. The popular workaround — nest_asyncio.apply() — patches the loop to allow reentrance, masking the design problem and enabling deadlocks when coroutines on the same loop block on each other under load.

## Correct Procedure
1. Inside any async context, do not call asyncio.run() — `await` the coroutine directly.
2. In Jupyter, `await` at the top level of a cell; IPython's loop handles it natively.
3. Bridging sync code that lives inside an async framework: use the framework's own mechanism (Starlette's run_in_threadpool, Django's async_to_sync) rather than creating loops.
4. Bridging from a genuinely separate thread: asyncio.run_coroutine_threadsafe(coro, loop) schedules onto the existing loop without nesting — only valid from a DIFFERENT thread than the loop's.

## Anti-Patterns
- nest_asyncio.apply() in production — enables the reentrance asyncio is designed to prevent; coroutines on one loop can mutually block into deadlock, and 'one thing at a time' debugging guarantees are gone.
- Calling run_coroutine_threadsafe from the loop's own thread and blocking on .result() — deadlocks immediately.
- Spawning a new thread with its own loop per sync-to-async call — works, then explodes thread count under load.

## Documented Dead Ends
- **Approach:** nest_asyncio.apply() to patch the running loop
  - *Why it fails:* Simple cases pass; under load, reentrant coroutines on the same loop deadlock waiting on each other. Debugging becomes near-impossible.
  - *Time wasted:* ~40 mins
- **Approach:** asyncio.get_event_loop().run_until_complete(coro)
  - *Why it fails:* Same nesting restriction, same RuntimeError; and get_event_loop() for this purpose is deprecated since 3.10.
  - *Time wasted:* ~10 mins

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