What this thread does
RuntimeError: Task attached to a different loop — create loop-bound clients within the async test lifecycle and keep their consumers on that loop.
A FastAPI request or database await fails because the resource belongs to another event loop.
First action — use httpx.AsyncClient(transport=ASGITransport(app=app), base_url="http://test") inside an async test instead of sharing loop-bound resources with a synchronous TestClient.
The official guides establish lifecycle and scope requirements; the particular application and test suite have not been reproduced.
Not for: pytest's fixture 'event_loop' not found; see the fixture-removal thread.
What changed
- This is a test-lifecycle diagnosis, not proof that a particular FastAPI release introduced a regression. The async-testing guide, checked 2026-10-28, documents the exact error and says to instantiate loop-dependent objects inside async functions.
- As of November 2026, pytest-asyncio 1.5.0 (released 2026-11-12; checked 2026-11-15) separates fixture caching
scopefrom executionloop_scopein its fixture API. A fixture's loop scope must be at least as broad as its caching scope.
How to migrate
1. Find where the failing client or pooled connection is first created and first used. Move loop-bound initialization out of module-level globals into an async fixture or the application's lifespan. Close it during that same lifecycle. FastAPI recommends lifespan handlers for startup and shutdown (checked 2026-10-28). 2. Pick one async test runner. For pytest-asyncio, start with function-scoped resources and tests. If sharing is necessary, apply matching module scopes as in its loop-scope example, checked 2026-10-28:
import pytest
import pytest_asyncio
@pytest_asyncio.fixture(scope="module", loop_scope="module")
async def resource():
# Create and close the application's async resource here.
yield
@pytest.mark.asyncio(loop_scope="module")
async def test_request(resource):
# Await the request and resource operations here.
pass
This illustrates scope declarations only; replace the empty resource and test with the application's real setup and assertions. 3. Use the HTTPX AsyncClient and ASGITransport form above for requests that must share the test's async context. The FastAPI guide warns that AsyncClient does not trigger lifespan itself; wrap the application with LifespanManager from asgi-lifespan when startup initializes the resource. 4. For SQLAlchemy's pooled AsyncEngine, follow its multiple-loop guidance, checked 2026-10-28. Do not share an engine with its default pool across loops. Dispose it before reuse on another loop; if cross-loop sharing is intentional, poolclass=NullPool prevents connection reuse. Prefer fixing ownership before changing pooling.
What breaks
Diagnostic: RuntimeError: Task attached to a different loop
FastAPI documents this wording. SQLAlchemy also documents a longer variant containing got Future attached to a different loop; task representations vary. A broad fixture can retain a connection while later tests get a fresh loop. The exception alone does not prove which fixture is responsible.
What to test
Run the original failing test alone, then alongside the test that first initializes the client, then the full module. Assert an actual response and resource operation, with startup and shutdown included. During diagnosis compare asyncio.get_running_loop() at resource initialization and use. Confirm cleanup occurs before the owning loop closes.
Pitfalls
Do not add nested asyncio.run(), restore a custom event_loop fixture from an old answer, or change all tests to session scope without checking resource lifetimes. Do not combine AnyIO and pytest-asyncio ownership accidentally. NullPool does not repair arbitrary client reuse.
Community evidence
In FastAPI discussion 8415, a commenter reports finding separate loops with TestClient and recovering with AsyncClient and aligned scopes. Issue 4473 contains another Motor-related test failure and maintainer discussion. These are individual reports, not evidence that every cross-loop error has the same fix; checked 2026-10-28.
A prompt to give your agent
Your training data predates the current APIs. Read the linked FastAPI async-testing, lifespan, pytest-asyncio scope and SQLAlchemy pages before editing; do not guess. Trace creation, first use and teardown of the failing resource. Choose one runner, align its loop scopes, and preserve lifespan. Make one change and run the failing test alone and in its original suite order. Report the traceback and assertions, not just whether collection succeeds.
Limits
No application, resource operation or test suite was run. Community evidence is historical and does not establish prevalence. WebSocket testing, Trio clients and concurrent production workers are outside this repair. There is no universal FastAPI version pin for this symptom.
Started from a post by @FastAPI community, packaged by the editor. Original post