pytest-asyncio in Production CI: Cross-Loop Futures, Leaked Tasks and Flaky Async Tests – a Measured Isolation Runbook

pytest-asyncio production runbook cover (revision 2): two glowing event loop rings, one amber task drifting out of orbit and a severed magenta future link, dark navy artwork; badges read victim fails 20/20, 50 ms block = 50.14 ms gap, guards +3.4% suite time

Production Executive Summary: an asynchronous test suite is a shared-state program wearing the costume of isolated functions. Every test gets a fresh event loop, but the objects that matter – the HTTP client, the connection pool, the in-flight request cache, the dispatcher task – are created once at import time and outlive the loop that produced them. On a developer laptop the suite is small enough that the leaked object is usually overwritten before it is touched. In CI, where the suite is larger, shuffled, parallelised and run on a colder machine, the same leak surfaces as a failure in a test that has nothing to do with it.

This runbook does four things. It reproduces the failure in a seven-test suite, where a two-test pair is enough to show it, and measures how reliably it reproduces (20 runs out of 20, always in the wrong test). It separates the four error messages that are commonly reported as one, because each has a different cause and a different fix. It builds loopkit, a small pytest plugin that turns a silent leak into a named failure on the test that created it. And it measures what the guards cost: 21.8 ms on an eight-test suite, 3.4 percent, for the ability to read a failure and know whose it is.

Everything below was executed, not recalled. The environment was Python 3.12.16 with pytest 8.3.4, pytest-asyncio 1.2.0, pytest-xdist 3.6.1 and anyio 4.16.0 on a two-vCPU Linux container, and every number in this revision was re-measured on 2026-11-16 after the guards were split into one module each. Each measurement is named in the verification section at the end so you can re-run it and get the same shape of answer.

Symptom in CIWhat the suite blamesWhat is actually trueCheapest reliable signal
RuntimeError: ... got Future ... attached to a different loop in one testThe test that awaited the futureA future created by an earlier test’s loop is still cached in module stateNumber of event loops seen per session vs number of tests
RuntimeError: await wasn't used with futureLooks like a misuse of assert await ...The same cross-loop future, already resolved, so the loop check never ranThe first failure in the same file: the untruncated message is there
A test that passed alone fails in the full suite, or the reverseFlakinessTest order and worker assignment decide whether the leak is observedRun the failing test alone once; if it passes, the state is shared
A run that ends with Task was destroyed but it is pending, or hangs at teardownThe harnessA test started a task and never awaited or cancelled itTasks alive at test teardown, with their creation site
Table 1: The four failure shapes this runbook separates, and the cheapest signal that identifies each.

1. The Event Loop Is A Hidden Global Variable

asyncio is usually explained as concurrency without threads, and that framing hides the property that breaks test suites. A coroutine is cheap and stateless, but the things it touches are not: a future is registered with one loop’s callback queue, a task is owned by one loop’s scheduler, and a connection pool holds a set of sockets that only one loop may service. The loop is the execution context those objects were born into, and it is a global from the object’s point of view.

pytest-asyncio, by design, gives each test a new loop. In 1.2 the default scopes are asyncio_default_test_loop_scope = function and asyncio_default_fixture_loop_scope = function, so a suite of eight async tests creates eight loops – the plugin reported exactly that in our measurements, eight tests on eight distinct loops. That is the correct default: a fresh loop is the strongest isolation the runtime can offer for free. The problem is everything that is not created inside it.

What actually binds to a loop, and what does not

The first useful step is to stop guessing which objects are loop-bound. We wrote a probe that creates each primitive in one loop and uses it in the next, and recorded the exact exception. The results are less uniform than the folklore suggests, which is why the diagnosis is so often wrong: several primitives people blame cannot produce this error at all, and two of them produce it only after a first wait.

ObjectCreated in loop A, used in loop BMeasured result on Python 3.12.16
loop.create_future()await futureRuntimeError: Task ... got Future <Future pending> attached to a different loop
asyncio.Task still pending when loop A closedawait taskCancelledError – a BaseException, so an except Exception handler never sees it
asyncio.Queue() with an item waitingawait queue.get()works – a getter that finds an item never asks for a loop
asyncio.Queue() whose first getter waited on an empty queueawait queue.get()RuntimeError: <Queue at 0x...> is bound to a different event loop
asyncio.Lock(), never contendedasync with lockworks in any loop – the fast path never consults the loop, so nothing is bound
asyncio.Lock() whose first wait was in loop Acontended async with lockRuntimeError: <asyncio.locks.Lock object ...> is bound to a different event loop
asyncio.Event() that is already setawait event.wait()works in any loop – wait() returns before it asks for a loop
asyncio.Event() waited while unset in loop Aawait event.wait()RuntimeError: <asyncio.locks.Event object ...> is bound to a different event loop
An event loop that has been closedloop.run_until_complete(...)RuntimeError: Event loop is closed
–issubclass(asyncio.CancelledError, Exception)False
Table 2: Measured cross-loop behaviour of the primitives that appear in every async test suite.

Read the lock, event and queue rows as one fact: since 3.10 the constructor no longer asks for a loop, and the object binds itself to the first loop that has to wait on it – mixins._LoopBoundMixin._get_loop stores the running loop in self._loop on that first wait and compares it on every later one. So a queue, a lock or an event that has ever made anyone wait is still a single-loop object, and it fails with a message that names the object rather than the test.

Two rows carry most of the practical weight. The first is that Future is the object that produces the famous message: a future binds to one loop the moment it is created, and any cache that stores one – a single-flight request cache, a warm-up handshake, a functools.lru_cache around a coroutine – is a cross-loop bug waiting for a second test. The second is that CancelledError is not an Exception. A cleanup branch written as except Exception does not run when a task is cancelled, so the cache entry survives the cancellation that was supposed to remove it. That single language fact is the mechanism behind the leak we reproduce in the next section.

The One Rule Worth Memorising: Futures and tasks bind to a loop when they are created; a queue, a lock or an event binds to the first loop that has to wait on it. Every attached to a different loop report you will ever read is one of those objects, and it is nearly always cached in module state or in a fixture with a wider scope than the test.

2. A Two-File Reproduction That Fails 20 Times Out Of 20

The smallest honest reproduction we could build is a pricing service with a single-flight cache: concurrent lookups for the same SKU share one upstream call, and the thing they share is the in-flight future. This is a real pattern with real value – it is how every well-behaved client prevents a thundering herd on a hot key – and it is where most production service code keeps its first future in a dictionary.

"""Pricing gateway with a module-level single-flight cache.

The cache stores the in-flight ``Future`` so concurrent lookups for one SKU
share a single upstream call. Correct inside one event loop, silently wrong
across loop boundaries: that is the shape of bug that leaks between tests.
"""
from __future__ import annotations

import asyncio
from dataclasses import dataclass


@dataclass(frozen=True)
class Quote:
    sku: str
    price_cents: int


class PricingGateway:
    def __init__(self, fetch) -> None:
        self._fetch = fetch
        self._inflight: dict[str, asyncio.Future] = {}
        self.upstream_calls = 0

    async def quote(self, sku: str) -> Quote:
        pending = self._inflight.get(sku)
        if pending is not None:
            return await pending
        pending = asyncio.get_running_loop().create_future()
        self._inflight[sku] = pending
        try:
            self.upstream_calls += 1
            value = await self._fetch(sku)
        except Exception:  # <-- CancelledError is a BaseException, so this misses it
            self._inflight.pop(sku, None)
            if not pending.done():
                pending.set_exception(RuntimeError("upstream failed"))
            raise
        self._inflight.pop(sku, None)
        if not pending.done():
            pending.set_result(value)
        return value

    def start_warmup(self, sku: str) -> None:
        """Fire a lookup without keeping a reference to the task."""
        asyncio.get_running_loop().create_task(self.quote(sku))


async def fetch_upstream(sku: str) -> Quote:
    await asyncio.sleep(0.01)
    return Quote(sku=sku, price_cents=1000 + len(sku))


gateway = PricingGateway(fetch_upstream)

Two details in that module matter more than the rest. The except Exception on line 33 looks like careful cleanup, and it is exactly the bug: when the task awaiting self._fetch is cancelled, Python raises CancelledError, which is a BaseException, so the handler is skipped, the entry is never removed and the future stays pending in _inflight forever. And start_warmup creates a task without keeping a reference to it, which is how a test ends up with an owner that no longer exists by the time its loop closes.

The suite that exposes it is seven tests across two files, and it contains a warm-up that starts a lookup and never awaits it, a test that reads the same cache entry, a blocking test, a cancellation test, and a feed module whose dispatcher task is started and never stopped. Run without any guard, twenty times in a row, the outcome never changed: two failures, four passes, one skip – and the two failures were always the second test in each file, never the test that created the mess.

$ python -m pytest tests -q
.Fs.F..                                                    [100%]
=================================== FAILURES ===================================
_______________________ test_2_first_event_of_this_test ________________________
>       assert feed.seen == []
E       AssertionError: assert ['tick'] == []

_____________________ test_2_quote_reads_from_shared_cache _____________________
>       quote = await gateway.quote("SKU-1")
E       RuntimeError: Task <Task pending name='Task-12' coro=<test_2_quote_reads_from_shared_cache()
        running at tests/test_pricing.py:14>> got Future <Future pending> attached to a different loop
==================== 2 failed, 4 passed, 1 skipped in 0.40s ====================

Read that output as an on-call engineer would. The traceback points into tests/test_pricing.py:14, a test whose entire body is one lookup. Nothing in that test creates a future, starts a task or touches module state directly; it calls the gateway, and the gateway hands it a future from a loop that no longer exists. The failure is real, the location is real, and the cause is in a different test entirely – which is why teams spend an afternoon adding timeouts to a line that was never wrong.

RunTests failedWhich test failedWhich test leaked
20 of 202test_pricing.py::test_2_quote_reads_from_shared_cache, test_feed.py::test_2_first_event_of_this_testtest_1_warmup, test_1_dispatch_runs – both passed 20 of 20
Run alone0the same test passes when nothing before it rannothing to leak when the suite is one test
-n 2 xdist, 10 runs2same two victims, same file pairingworkers keep their own module state, so the pairing survives parallelism
Table 3: The leak is deterministic, but always reported one test late.

The -n 2 row is worth a second look, because parallelisation is often prescribed as the cure for test pollution and here it is not. Each xdist worker is a separate process with its own module state, so the leak persists inside a worker and disappears between them. Whether a worker runs both the warm-up and the reader depends on the distribution strategy; with the default load distribution and two files, the pair stayed together and the suite stayed red. What parallelism changed was the wall clock – a median of 1,510.4 ms against 844.3 ms serial – which in this small suite is worker start-up, not speed.

Language Matters Here: A test that passes in isolation and fails in the suite is not flaky. Flakiness means the same inputs produce different results; this means the inputs are different, because the inputs include everything the previous tests left behind. Treat the two as separate diagnoses and you will stop re-running the job and start reading it.

3. The Victim Is Never The Culprit, So Record The Culprit

Once you accept that the failing test is a bystander, the design goal becomes obvious and much easier than fixing the leak itself: record who created the object, and fail there instead. That is the whole idea behind loopkit. It is a pytest plugin of about five hundred lines including its pytest-free core, and each of its guards answers one question about the test that just ran – did you leave a task alive, did you block the loop, did you hand a loop-bound object to a different loop.

The first two guards run on their own: the plugin wraps every async test coroutine, so the task ledger and the blocking probe are installed and read without the suite asking for them. The third is opt-in and explicit – you call loopkit_bind in the fixture that creates the object and loopkit_assert_same_loop at the consuming test or fixture – because that boundary is the only place a loop comparison can actually fire, and inventing a check that cannot fire is how this guard was nearly shipped broken (section 8).

The measurement that justifies the whole plugin is the count of failures before and after. The same seven tests, the same application code, the same machine, twenty runs each. Without the guards the suite reports two failures, both on bystanders, and the two leaking tests pass every single time. With the guards the suite reports five failures: the two bystanders as before, plus the two leaking tests and the blocking one, each failing with a message that names the coroutine and the line that started it.

SuiteRunsFailedNamed culpritsMedian wall time
No guards202 every runnone – only victims were reported844.3 ms
loopkit enabled205 every runtest_1_warmup, test_1_dispatch_runs, test_3_blocking859.8 ms
Fixed code, loopkit enabled200 – 8 passed every run–657.2 ms
Table 4: The broken suite in the first two rows (7 tests, 2 failed / 4 passed / 1 skipped); only the guards differ. The third row is the fixed suite, which has a different test count by design.

The count moving from two to five is the deliverable. Two failures that point at innocent tests cost an afternoon each; five failures that point at the leaking line cost a minute, because the message already contains the coroutine name (PricingGateway.quote, Feed._run), the file and line where the task was created, and the test that owned it. That is what a usable diagnostic looks like.

The second-order effect is the one that keeps a suite honest over time: once the leaking test fails on the day the leak is introduced, nobody needs to remember the rule. The guard is the memory, and it fires in the pull request that caused it rather than in a nightly job three weeks later.

4. Four Messages That Get Reported As One

Search for the error text and you will find a single Stack Overflow question with a dozen contradictory answers, because four different defects print messages that read alike. Separating them is most of the debugging skill in this area, and each one has a different fix.

MessageCondition that produces itFixMeasured evidence
got Future <Future pending> attached to a different loopA pending future created by loop A is awaited in loop BCreate the future inside the test’s loop, or give the fixture the same loop_scope as the testReproduced in test_2_quote_reads_from_shared_cache; also in the session-fixture suite, first awaiting test
await wasn't used with futureThe same stale future, but already resolved: wait_for returns it without checking the owning loopSame as above – the loop scope, not the awaitReproduced in the 2nd, 3rd and 4th awaiting tests of the session-fixture suite
CancelledError with an empty messageA task is awaited after the loop that owned it closedStop sharing tasks across loops; cancel and await inside one loopProbe: awaiting a task whose loop had closed raised CancelledError and escaped except Exception
RuntimeError: Event loop is closedAnything submitted to a loop object that has been closedUse asyncio.run per operation, never loop.run_until_complete on a stored loopProbe: loop.close() then run_until_complete
Table 5: Four messages, four causes, four fixes.

The session-scoped fixture, measured

The most common source of row one is not a global dictionary at all; it is an asynchronous fixture whose scope is wider than the test loop. A session-scoped fixture that builds a client, a pool or a warm-up token runs on the session loop, and every function-scoped test runs on a different one. The object is then used from the wrong loop by design, and pytest-asyncio will not stop you, because there is nothing illegal about the configuration – it is just incompatible with the objects you put in it.

We built the smallest version of that mistake: a session-scoped async fixture, loop_scope="session", which creates a future and resolves it five milliseconds later, exactly like a client’s ready handshake. Six tests consume it; two only read the fixture and four await the handshake.

import asyncio

import pytest_asyncio


@pytest_asyncio.fixture(scope="session", loop_scope="session")
async def warm_handshake():
    """Session-scoped token that completes once, like a pool warm-up handshake."""
    loop = asyncio.get_running_loop()
    ready = loop.create_future()

    async def resolve():
        await asyncio.sleep(0.005)
        if not ready.done():
            ready.set_result("ok")

    task = asyncio.create_task(resolve())
    yield {"ready": ready}
    task.cancel()

The result is a scope matrix you can predict once you have seen it: four of six tests fail, and the two that pass are exactly the ones that never await the future. Marking the same six tests with pytestmark = pytest.mark.asyncio(loop_scope="session") makes them share the fixture’s loop and all six pass. Marking them loop_scope="module" instead does not: the four awaiting tests still fail, because a module loop is a different loop from the session loop that built the fixture. Nothing else changed – not the fixture, not the application code, not the versions.

ConfigurationTestsResultMessage on the failing tests
Session fixture, function-scoped tests64 failed / 2 passedfirst: got Future <Future pending> attached to a different loop; later: await wasn't used with future
Same fixture, tests marked loop_scope="session"66 passed on 1 loop– the marker moved the tests, not the fixture
Same fixture, tests marked loop_scope="module"64 failed / 2 passedthe same two messages – one module loop is still not the session loop
Table 6: The scope of the test decides which loop runs it; the scope of the fixture decides which loop owns its objects.

Two conclusions follow. First, a fixture may only hold loop-bound objects when its loop scope matches every test that consumes it – the marker is the contract, and pytest-asyncio enforces it only in the direction that produces an error, never in the direction that prevents one. Second, the error messages are ordered by resolution state, which is why a single misconfiguration prints two different messages in the same run and sends people looking for two bugs.

Is one loop for the whole session the fast option? Measured

The configuration teams reach for when a suite gets slow is a single loop for the whole session, on the theory that loop creation is expensive. We measured that theory. Eight tests on eight loops took a median 657.2 ms; the same eight tests on one session-scoped loop took 650.9 ms. The difference is 6.3 ms, about one percent, and it is the only thing the shared loop bought: a suite in which every leak becomes a test-order dependency with no boundary to contain it.

5. Fixture Rules That Survive A Second Test

The rule that removes most of this class of failure is not a plugin but a fixture discipline: whoever creates a loop-bound object also destroys it, inside the same scope. In the fixed suite that is two short fixtures and one context manager, and the difference in behaviour is total – eight tests, twenty consecutive runs, zero failures.

"""Fixtures that make every test own the object it touches."""
from __future__ import annotations

import pytest

from app.gateway import PricingGateway, fetch_upstream


@pytest.fixture
def gateway() -> PricingGateway:
    """A gateway per test, always closed by the test that created it."""
    instance = PricingGateway(fetch_upstream)
    yield instance
    instance.reset()

A function-scoped gateway means no test can observe another test’s cache. The teardown calls reset(), which resolves any leftover waiter with an explicit error instead of leaving a future pending – so even a test that fails in the middle hands the next test a clean object. The corresponding production change is not in the test at all: the gateway itself has to survive cancellation, which section 11 covers.

Three rules cover the rest of the ground. Put loop-bound objects in fixtures whose loop_scope matches the tests, never in module-level singletons that tests import. Make every background task owned by an async with block or a fixture that cancels and awaits it. And when a shared object genuinely must outlive a test – a container, a database, a schema – share the *connection information*, not the connection.

  • Module-level client = httpx.AsyncClient(): forbidden in a test suite. It is created on whichever loop imported it and used on every loop after that.
  • Module-level cache: dict[str, Future]: forbidden unless the cache is cleared by an autouse fixture – and even then, prefer a factory.
  • A session-scoped fixture that returns an open connection: allowed only when the consuming tests are marked with the same loop_scope, and never with asyncio_mode=auto plus a function-scoped default.
  • A task created outside a fixture: allowed only if the same function cancels and awaits it, with the cancellation inside finally.

6. Task Leaks: The Half Of The Problem Nobody Measures

Futures announce themselves with a traceback. Tasks do not. A task that is still running when the test ends is either cancelled silently by the loop shutdown, or left to print Task was destroyed but it is pending! somewhere in the output where pytest will attribute it to nothing at all. Meanwhile the task has been doing work: consuming a queue, writing to a list, holding a connection.

Our feed module is the canonical shape. A dispatcher task reads a queue and appends to a list; the test starts the dispatcher, pushes one event and asserts that it arrived. Nothing stops the dispatcher. The next test asserts that the feed starts empty, and it does not – the previous test’s consumer is still registered on a module-level queue, and its state is a module-level list.

"""A wake-up feed with a background dispatcher task."""
from __future__ import annotations

import asyncio


class Feed:
    def __init__(self) -> None:
        self.queue: asyncio.Queue[str] = asyncio.Queue()
        self.seen: list[str] = []
        self._dispatcher: asyncio.Task | None = None

    def start(self) -> None:
        self._dispatcher = asyncio.create_task(self._run())

    async def _run(self) -> None:
        while True:
            item = await self.queue.get()
            self.seen.append(item)

    def stop(self) -> None:
        if self._dispatcher is not None:
            self._dispatcher.cancel()
            self._dispatcher = None


feed = Feed()

The fix is a context manager that owns the task, and the whole module grows by six lines over the buggy version. The point is that the test can no longer forget the cleanup step, because the cleanup is the closing brace.

"""Feed with a dispatcher task that cannot outlive the block it was started in."""
from __future__ import annotations

import asyncio


class Feed:
    def __init__(self) -> None:
        self.queue: asyncio.Queue[str] = asyncio.Queue()
        self.seen: list[str] = []
        self._dispatcher: asyncio.Task | None = None

    async def __aenter__(self) -> "Feed":
        self._dispatcher = asyncio.create_task(self._run(), name="feed-dispatcher")
        return self

    async def __aexit__(self, *exc_info: object) -> None:
        await self.stop()

    async def stop(self) -> None:
        if self._dispatcher is None:
            return
        self._dispatcher.cancel()
        try:
            await self._dispatcher
        except asyncio.CancelledError:
            pass
        self._dispatcher = None

    async def _run(self) -> None:
        while True:
            item = await self.queue.get()
            self.seen.append(item)

Detecting leaks without changing application code needs a task factory. loop.set_task_factory receives every task the loop creates, including the ones created by asyncio.create_task, so wrapping the default factory gives a complete list plus a place to record the creation site. The implementation keeps the previous factory and calls it, so a project that installs uvloop or its own factory still works.

The recorder comes first, because it is the one piece that has to be cheap: it runs inside the loop it is measuring. Each guard lives in its own module so that each can be read once, in one piece: loopkit.frames here, loopkit.ledger next, loopkit.probe in section 7 and loopkit.guard in section 8.

"""loopkit.frames - where an object was created, without paying for a traceback."""
from __future__ import annotations

import sys
from pathlib import Path

__all__ = ["frame_of"]

_PACKAGE_DIR = Path(__file__).resolve().parent


def frame_of(depth: int = 8) -> str:
    """Return ``file:line in function`` for the first frame outside loopkit and asyncio.

    The frame objects are walked directly instead of through
    ``traceback.extract_stack``: extract_stack resolves a source line for every
    frame it walks, which reads files through linecache while the loop is being
    measured. Swapping only that call turned a 1.2 ms floor into a 13.0-14.5 ms
    phantom block on the first test that created a task.

    Paths are split with ``pathlib`` rather than on ``"/"`` so the same code
    names the caller on Windows and Linux alike, and both the file name
    and the package directory are resolved, so a symlinked checkout still
    compares equal.
    """
    frame = sys._getframe(1)
    seen = 0
    while frame is not None and seen < depth + 16:
        path = Path(frame.f_code.co_filename).resolve()
        if _PACKAGE_DIR not in path.parents and "asyncio" not in path.parts:
            return f"{path.name}:{frame.f_lineno} in {frame.f_code.co_name}"
        frame = frame.f_back
        seen += 1
    return "<unknown>"
"""loopkit.ledger - records every task a test creates and reports the survivors."""
from __future__ import annotations

import asyncio
from typing import Callable, Iterable

from .frames import frame_of

__all__ = ["TaskLedger"]


class TaskLedger:
    """Records every task created while installed and reports the survivors."""

    def __init__(self, ignore: Iterable[asyncio.Task | None] = ()) -> None:
        self._created: dict[asyncio.Task, str] = {}
        self._ignore = {id(task) for task in ignore if task is not None}
        self._loop: asyncio.AbstractEventLoop | None = None
        self._previous_factory: Callable | None = None

    def install(self, loop: asyncio.AbstractEventLoop) -> None:
        self._loop = loop
        self._previous_factory = loop.get_task_factory()
        loop.set_task_factory(self._factory)

    def _factory(self, loop: asyncio.AbstractEventLoop, coro, **kwargs):
        if self._previous_factory is not None:
            task = self._previous_factory(loop, coro, **kwargs)
        else:
            task = asyncio.tasks.Task(coro, loop=loop, **kwargs)
        if id(task) not in self._ignore:
            self._created[task] = frame_of(depth=10)
        return task

    def uninstall(self) -> None:
        if self._loop is not None:
            self._loop.set_task_factory(self._previous_factory)
        self._loop = None

    def created(self) -> list[tuple[asyncio.Task, str]]:
        return [(task, site) for task, site in self._created.items() if id(task) not in self._ignore]

    def orphans(self) -> list[tuple[asyncio.Task, str]]:
        """Tasks created during the test that are still alive and not finished."""
        orphans: list[tuple[asyncio.Task, str]] = []
        for task, site in self.created():
            if task.done() or task.cancelled():
                continue
            orphans.append((task, site))
        return orphans

    def cancel_orphans(self, orphans: list[tuple[asyncio.Task, str]]) -> None:
        for task, _site in orphans:
            task.cancel()

    def describe_orphans(self, orphans: list[tuple[asyncio.Task, str]]) -> str:
        lines = [
            f"  - {task.get_coro().__qualname__} created at {site}"
            for task, site in orphans
        ]
        return "\n".join(lines)

Two subtleties are worth stating because we hit both. The documented factory signature is factory(loop, coro, context=None) and it moved between 3.10 and 3.12: on 3.12 our factory received no extra keyword arguments at all, which is why forwarding **kwargs is portable while naming context is not. And the ledger must be installed after the probe starts, with the probe’s own task in the ignore set, or the guard reports its own instrumentation as a leak.

The measured effect on the feed leak is visible in the failure count. With the ledger active the suite reports the leaking test as failed for the first time – test_1_dispatch_runs, with the message naming Feed._run created at feed.py:14 in start – and it happens in twenty out of twenty runs, not intermittently.

7. Blocking Calls: Measure The Loop, Not The Clock

The third defect class cannot be detected by inspecting objects at all. A coroutine that calls time.sleep, requests.get, a synchronous database driver or a large json.loads holds the whole loop, so every other test’s coroutine, timer and cancellation waits behind it. The symptom is a suite that is slow in proportion to how many tests happen to be blocking, and a handful of timing assertions that fail under load.

Timing assertions are the wrong instrument, because they measure the test’s own wall clock, which includes everything else on the machine. The right instrument measures the loop’s ability to schedule: a one-millisecond ticker task records the gap between its wake-ups, and the largest gap is the longest time the test held the loop. That number is attributable, comparable across machines, and independent of how slow the assertion itself is.

"""loopkit.probe - measures how long the loop could not schedule work."""
from __future__ import annotations

import asyncio
import time

from .errors import BlockingCallError

__all__ = ["BlockingProbe"]


class BlockingProbe:
    """Measures how long the loop was unable to schedule the probe ticker."""

    def __init__(self, interval: float = 0.001) -> None:
        self._interval = interval
        self._gaps: list[float] = []
        self._task: asyncio.Task | None = None
        self._started = 0.0
        self._last = 0.0

    @property
    def task(self) -> asyncio.Task | None:
        return self._task

    async def start(self) -> None:
        self._started = time.perf_counter()
        self._last = self._started
        self._task = asyncio.create_task(self._tick(), name="loopkit-blocking-probe")
        await asyncio.sleep(0)

    async def _tick(self) -> None:
        # measure from the moment this task first runs, not from the moment it was
        # requested: the difference is the wrapper's own start-up and would be
        # charged to the test as a phantom block
        self._last = time.perf_counter()
        while True:
            await asyncio.sleep(self._interval)
            self._record(time.perf_counter())

    def _record(self, now: float) -> None:
        self._gaps.append(now - self._last)
        self._last = now

    async def stop(self) -> None:
        """Stop ticking and record the tail, where a block at the end shows up."""
        if self._task is None:
            return
        self._record(time.perf_counter())
        self._task.cancel()
        try:
            await self._task
        except asyncio.CancelledError:
            pass
        self._task = None

    @property
    def samples(self) -> int:
        return len(self._gaps)

    @property
    def max_gap_ms(self) -> float:
        return max(self._gaps, default=0.0) * 1000.0

    @property
    def mean_gap_ms(self) -> float:
        if not self._gaps:
            return 0.0
        return (sum(self._gaps) / len(self._gaps)) * 1000.0

    def assert_budget(self, budget_ms: float, label: str) -> float:
        """Raise when the longest scheduling gap exceeded ``budget_ms``."""
        worst = self.max_gap_ms
        if worst > budget_ms:
            raise BlockingCallError(
                f"{label} blocked the event loop for {worst:.1f} ms "
                f"(budget {budget_ms:.1f} ms across {self.samples} probe ticks). "
                "Move the blocking call into a thread with asyncio.to_thread, "
                "or make the dependency asynchronous."
            )
        return worst

Calibrating the instrument is the part that decides whether it is usable. We ran the probe against bodies whose behaviour we already knew, and against 150 idle test-shaped runs to find the floor.

Body inside the async testProbe max gapSamplesVerdict
time.sleep(0.05)50.14 ms1caught, 2x over a 25 ms budget
time.sleep(0.2)200.15 ms1caught, unambiguous
await asyncio.sleep(0.05)1.23 ms45not blocking
await asyncio.sleep(0.2)1.22 ms181not blocking, even for 200 ms
await asyncio.to_thread(time.sleep, 0.05)2.02 ms46the documented fix works
Idle suite, 150 runs: p50 / p90 / p99 / max1.13 / 1.21 / 1.52 / 3.23 ms–the floor; a budget must sit above it
Table 7: Probe calibration. The gap tracks blocking time, not elapsed time.

The idle maximum is the number that matters. On this container, an honest test that awaits for twenty milliseconds produces a worst gap of 1.13 ms at the median and 3.23 ms in the worst of 150 runs, because the scheduler, the allocator and the container’s neighbours all take small bites. A budget of five milliseconds – the value we shipped first – is only one and a half times that worst gap, so it flags innocent tests on any busier machine, which is how a guard earns a reputation for noise and gets switched off. The shipped default is 25 ms: sixteen times the observed p99, seven times the worst idle gap, and half of a fifty-millisecond block.

There is one more calibration trap, and it bit us inside the instrument rather than inside a test. The first implementation of the creation-site recorder used traceback.extract_stack, which resolves a source line for every frame it walks. We swapped only the recorder in a three-test suite whose bodies create one short task each, and the probe reported a phantom block in the first test that created a task: 13.0 to 14.5 ms over five runs, against 1.2 ms for the sys._getframe walk that ships. The recorder runs inside the loop being measured, so a function that formats or reads source there will always find itself.

Calibrate The Instrument First: If your probe reports a suspiciously round five or ten milliseconds on a test that does not block, suspect the probe. Measure with an empty body first, write the floor into the budget, and only then believe the findings.

8. Building loopkit: Three Small Guards In One Plugin

The plugin is deliberately small enough to read in one sitting, because a guard people cannot audit is a guard people turn off. It has three parts: exception types that pytest reports as ordinary failures, a pytest-free core that can be unit-tested like any other library, and a thin pytest layer that decides when the guard runs.

"""Exception types raised by loopkit.

Every error is an ``AssertionError`` subclass so pytest reports it as an ordinary
test failure instead of an internal error, and every message names the test that
created the offending object rather than the test that tripped over it.
"""
from __future__ import annotations


class LoopKitError(AssertionError):
    """Base class for every guard loopkit raises."""


class ForeignLoopError(LoopKitError):
    """A loop-bound object was used from a different event loop."""


class OrphanTaskError(LoopKitError):
    """A test left asynchronous work running when it finished."""


class BlockingCallError(LoopKitError):
    """A coroutine blocked the event loop past the configured budget."""


class NewLoopError(LoopKitError):
    """A test created its own event loop instead of using the test loop."""

Keeping the core free of pytest is what makes the guards testable: the registry, the ledger and the probe are plain objects with plain contracts, and the plugin file is the only place that knows what a request or an ini option is. They are also one module each, so the article shows each of them exactly once: the recorder and the ledger in section 6, the probe in section 7, and here the registry that ties an object to a loop and to the test that created it.

"""loopkit.guard - the registry that maps loop-bound objects to their loop.

The guard is the third of the three objects; ``TaskLedger`` lives in
``loopkit.ledger`` and ``BlockingProbe`` in ``loopkit.probe``, so each piece can
be read - and unit-tested - on its own.
"""
from __future__ import annotations

import asyncio
from dataclasses import dataclass

from .errors import ForeignLoopError
from .frames import frame_of

__all__ = ["Binding", "LoopRegistry"]


@dataclass(frozen=True)
class Binding:
    """One loop-bound object and the test that created it."""

    name: str
    loop_id: int
    owner: str
    created_at: str

    def describe(self) -> str:
        return f"{self.name} (loop {self.loop_id:#x}) created by {self.owner} at {self.created_at}"


class LoopRegistry:
    """Maps loop-bound objects to the loop and the test that created them.

    Objects are kept by identity, and the registry holds a strong reference so
    that a freed object cannot hand its ``id()`` to a new one.
    """

    def __init__(self) -> None:
        self._entries: dict[int, tuple[object, Binding]] = {}
        self._owner = "<import time>"

    def set_owner(self, owner: str) -> None:
        self._owner = owner

    @property
    def owner(self) -> str:
        return self._owner

    def bind(self, name: str, resource: object) -> Binding:
        """Record the running loop as the only loop ``resource`` may be used on."""
        binding = Binding(
            name=name,
            loop_id=id(asyncio.get_running_loop()),
            owner=self._owner,
            created_at=frame_of(),
        )
        self._entries[id(resource)] = (resource, binding)
        return binding

    def binding_of(self, resource: object) -> Binding | None:
        entry = self._entries.get(id(resource))
        if entry is None or entry[0] is not resource:
            return None
        return entry[1]

    def check(self, name: str, resource: object) -> None:
        """Raise if ``resource`` is being used on a loop other than its owner."""
        binding = self.binding_of(resource)
        if binding is None:
            return
        current = id(asyncio.get_running_loop())
        if binding.loop_id != current:
            raise ForeignLoopError(
                f"{name} crossed an event loop boundary: {binding.describe()}, "
                f"now used from loop {current:#x} in {self._owner}. "
                "Either create it inside the test's loop or move it into a fixture "
                "whose loop_scope matches the test."
            )

    def clear(self) -> None:
        self._entries.clear()

    def __len__(self) -> int:
        return len(self._entries)

The pytest layer contains one design decision worth arguing about, because the obvious implementation is wrong. The natural way to run setup and teardown inside the test’s event loop is an autouse async fixture. It works for a simple guard, and it fails in exactly the situation this article is about: a fixture whose teardown runs in a different loop than the test it accompanies, or a sync fixture that pulls an async fixture in through request.getfixturevalue. We measured the second case – an async fixture whose teardown cancels and awaits its own task: the suite reported one pass and one error, CancelledError at teardown, with no mention of loops or tasks. An earlier build of the same code hung the run instead, and had to be killed.

So the shipped plugin wraps the test coroutine itself. A coroutine wrapper is guaranteed to run inside whatever loop pytest-asyncio chose for the test, because it *is* the coroutine that loop runs. The wrapper also has the information the fixture lacked: the node id, the exact moment the body finished, and the exception if the body raised.

"""loopkit.plugin - pytest integration for the loop isolation guards.

Install with ``pytest_plugins = ["loopkit.plugin"]`` in the top-level
``conftest.py``. The guard wraps the test coroutine itself instead of using an
async fixture: a coroutine wrapper is guaranteed to run inside the same loop the
test runs on, while a fixture teardown can be scheduled on a different loop.
Every guard is optional through ini options, so a legacy suite can adopt loopkit
one failure class at a time.
"""
from __future__ import annotations

import asyncio
import functools
import inspect

import pytest

from .errors import LoopKitError
from .guard import LoopRegistry
from .ledger import TaskLedger
from .probe import BlockingProbe

__all__ = [
    "LoopKitError",
    "LoopRegistry",
    "TaskLedger",
    "BlockingProbe",
    "pytest_addoption",
    "pytest_configure",
    "pytest_sessionstart",
    "pytest_terminal_summary",
    "loopkit_registry",
    "loopkit_bind",
    "loopkit_assert_same_loop",
]

_ORPHAN_MODES = ("fail", "warn", "ignore")
_REGISTRY_KEY: pytest.StashKey[LoopRegistry] = pytest.StashKey()
_LOOPS_SEEN: list[int] = []
_TESTS_SEEN: list[str] = []
_MAX_GAPS: list[tuple[str, float]] = []
_WARNINGS: list[str] = []


def pytest_addoption(parser: pytest.Parser) -> None:
    group = parser.getgroup("loopkit", "event loop isolation guards")
    group.addoption(
        "--loopkit-orphans",
        action="store",
        default=None,
        choices=_ORPHAN_MODES,
        help="override loopkit_orphans for this run",
    )
    group.addoption(
        "--loopkit-gap-ms",
        action="store",
        type=float,
        default=None,
        help="override loopkit_gap_ms (0 disables the blocking probe)",
    )
    parser.addini(
        "loopkit_orphans",
        "fail, warn or ignore tasks left running at the end of a test",
        default="fail",
    )
    parser.addini(
        "loopkit_gap_ms",
        "event loop scheduling gap tolerated per test, in milliseconds (0 disables)",
        default="25",
    )
    parser.addini(
        "loopkit_foreign_loops",
        "raise when a registered object is used from a loop other than the one that bound it",
        default="true",
    )


def _orphan_mode(config: pytest.Config) -> str:
    override = config.getoption("--loopkit-orphans")
    if override is not None:
        return str(override)
    mode = str(config.getini("loopkit_orphans")).strip().lower()
    return mode if mode in _ORPHAN_MODES else "fail"


def _gap_ms(config: pytest.Config) -> float:
    override = config.getoption("--loopkit-gap-ms")
    if override is not None:
        return float(override)
    return float(config.getini("loopkit_gap_ms"))


def _foreign_loops_enabled(config: pytest.Config) -> bool:
    value = str(config.getini("loopkit_foreign_loops")).strip().lower()
    return value in {"1", "true", "yes", "on"}


def _is_async_test(item: pytest.Item) -> bool:
    obj = getattr(item, "obj", None)
    if obj is not None and inspect.iscoroutinefunction(obj):
        return True
    return item.get_closest_marker("asyncio") is not None


def pytest_configure(config: pytest.Config) -> None:
    config.addinivalue_line("markers", "loopkit: tune the loop isolation guards for one test")
    config.stash[_REGISTRY_KEY] = LoopRegistry()


def pytest_sessionstart(session: pytest.Session) -> None:
    _LOOPS_SEEN.clear()
    _TESTS_SEEN.clear()
    _MAX_GAPS.clear()
    _WARNINGS.clear()


def pytest_runtest_setup(item: pytest.Item) -> None:
    """Wrap the coroutine of an async test so the guard runs inside its loop."""
    if getattr(item, "_loopkit_wrapped", False):
        return
    if not _is_async_test(item):
        return
    original = item.obj
    config = item.config
    nodeid = item.nodeid

    @functools.wraps(original)
    async def guarded(*args, **kwargs):
        registry: LoopRegistry = config.stash[_REGISTRY_KEY]
        registry.set_owner(nodeid)
        gap_ms = _gap_ms(config)
        orphan_mode = _orphan_mode(config)
        loop = asyncio.get_running_loop()
        _LOOPS_SEEN.append(id(loop))
        _TESTS_SEEN.append(nodeid)
        probe = BlockingProbe() if gap_ms > 0 else None
        if probe is not None:
            await probe.start()
        ledger = TaskLedger(ignore=[probe.task if probe else None])
        ledger.install(loop)
        try:
            result = await original(*args, **kwargs)
        except BaseException as exc:
            # keep the real failure and attach the guard's findings as a note
            note = await _finish(config, nodeid, probe, ledger, gap_ms, orphan_mode)
            if note:
                exc.add_note(note)
            raise
        finally:
            ledger.uninstall()
        note = await _finish(config, nodeid, probe, ledger, gap_ms, orphan_mode)
        if note:
            raise LoopKitError(note)
        return result

    item.obj = guarded
    item._loopkit_wrapped = True


async def _finish(
    config: pytest.Config,
    nodeid: str,
    probe: BlockingProbe | None,
    ledger: TaskLedger,
    gap_ms: float,
    orphan_mode: str,
) -> str | None:
    """Stop the probe, cancel leaked tasks and return a report (or None)."""
    problems: list[str] = []
    if probe is not None:
        await probe.stop()
    orphans = ledger.orphans()
    if orphans and orphan_mode != "ignore":
        ledger.cancel_orphans(orphans)
        await asyncio.gather(*[task for task, _ in orphans], return_exceptions=True)
        message = (
            f"loopkit: {len(orphans)} task(s) were still running when the test finished:\n"
            f"{ledger.describe_orphans(orphans)}\n"
            "Await the task, hold it in a fixture that cancels it, or use a TaskGroup."
        )
        if orphan_mode == "fail":
            problems.append(message)
        else:
            _WARNINGS.append(f"{nodeid}: {message}")
    if probe is not None:
        worst = probe.max_gap_ms
        _MAX_GAPS.append((nodeid, worst))
        if worst > gap_ms:
            problems.append(
                f"loopkit: the test held the event loop for {worst:.1f} ms "
                f"(budget {gap_ms:.1f} ms over {probe.samples} probe ticks). "
                "Move blocking work into asyncio.to_thread or make it asynchronous."
            )
    # A fourth check used to sit here: comparing asyncio.get_running_loop() with
    # the loop the wrapper started on. It could never fire, because this function
    # is awaited from the wrapper, which is the coroutine that loop runs - so the
    # two ids were always equal. The comparison that can fire is the registry
    # check below, at the fixture boundary, where a consumed object may really
    # have been bound on a different loop.
    return "\n\n".join(problems) if problems else None


@pytest.fixture(scope="session")
def loopkit_registry(pytestconfig: pytest.Config) -> LoopRegistry:
    """The session-wide registry of loop-bound objects."""
    return pytestconfig.stash[_REGISTRY_KEY]


@pytest.fixture
def loopkit_bind(loopkit_registry: LoopRegistry):
    """Bind an object to the running loop, for later cross-loop checks."""

    def bind(name: str, resource: object) -> object:
        loopkit_registry.bind(name, resource)
        return resource

    return bind


@pytest.fixture
def loopkit_assert_same_loop(loopkit_registry: LoopRegistry,
                             pytestconfig: pytest.Config):
    """Assert that a previously bound object still lives on the running loop.

    This is where a loop comparison is reachable: the fixture runs in whatever
    loop the consuming test got, which may differ from the loop that bound the
    object. ``loopkit_foreign_loops = false`` turns the check into a no-op for
    suites that are not ready for it.
    """
    enabled = _foreign_loops_enabled(pytestconfig)

    def check(name: str, resource: object) -> None:
        if enabled:
            loopkit_registry.check(name, resource)

    return check


def pytest_terminal_summary(terminalreporter, exitstatus: int, config: pytest.Config) -> None:
    if not _TESTS_SEEN:
        return
    loops = len(set(_LOOPS_SEEN))
    worst_test, worst_gap = max(_MAX_GAPS, default=("", 0.0), key=lambda item: item[1])
    terminalreporter.write_sep("-", "loopkit")
    terminalreporter.write_line(
        f"{len(_TESTS_SEEN)} async test(s) ran on {loops} distinct event loop(s)"
        + (f"; worst scheduling gap {worst_gap:.1f} ms in {worst_test}" if worst_gap else "")
    )
    for warning in _WARNINGS:
        terminalreporter.write_line(f"warning: {warning}", red=True)

Four details in that file are load-bearing. pytest_runtest_setup replaces item.obj with the wrapper, and functools.wraps preserves the signature so pytest’s argument injection and pytest-asyncio’s coroutine detection both keep working. The finish routine is called in a finally for the exception path but not returned from inside the try – a return inside a try skips the else block, which is a bug we shipped for about ten minutes and found because the orphan guard stayed silent. A guard finding is attached to the body’s exception with add_note rather than raised, so a test that failed for its own reason keeps its original traceback and still gains the diagnosis.

The fourth detail is a deletion. The first build also compared, at the end of every test, asyncio.get_running_loop() with the loop the wrapper had started on, and failed the test when they differed. That branch can never run: the wrapper is the coroutine the test loop runs, so both ids are equal by construction. We replaced it with a counter and watched 100 calls across a suite with session-scoped fixture teardown – the exact case the check claimed to catch – and it never fired once. The check that can fire is the registry’s, and it now sits where a loop really can differ: loopkit_assert_same_loop, a fixture that runs in the consuming test’s loop and compares it with the loop that bound the object.

One caveat we owe the reader: replacing item.obj is not a documented pytest-asyncio API. It works because 1.2 resolves the test coroutine from item.obj when it calls it; a release that captured the function object earlier would silently bypass the wrapper and leave the suite green. Pin pytest-asyncio (pytest-asyncio==1.2.0 here), and keep the orphan-fails-the-leaker test as the canary that fails loudly if a future version stops wrapping.

9. Wiring It Into A Real Pipeline

Adoption is two lines in conftest.py and a set of ini options, deliberately ordered so a legacy suite can switch the guards on one at a time instead of drowning in a thousand pre-existing failures.

# tests/conftest.py
pytest_plugins = ["loopkit.plugin"]

# pytest.ini
# [pytest]
# asyncio_mode = auto
# asyncio_default_fixture_loop_scope = function
# loopkit_orphans = fail
# loopkit_gap_ms = 25
# loopkit_foreign_loops = true
OptionValuesDefaultWhat it does
loopkit_orphansfail, warn, ignorefailTasks alive at test end; warn reports them without failing
--loopkit-orphanssame–Per-run override, useful while draining a backlog
loopkit_gap_msinteger milliseconds25Longest tolerated scheduling gap; 0 disables the probe entirely
--loopkit-gap-msfloat–Per-run override, for a slower CI runner
loopkit_foreign_loopstrue, falsetrueRaises when a bound object is used from a loop other than the one that bound it; false makes the check a no-op
Table 8: The complete configuration surface. No hidden behaviour, no import side effects.

The migration order matters more than the settings. Switch on loopkit_orphans=warn first and let the suite run for a week: the warnings tell you how many leaks exist and across how many modules, which is the input to the next decision. Then fix the module-scoped singletons, which is where most of the leaks live, and only after that turn warn into fail. The blocking probe comes last, because a new timing threshold on a suite that has never measured anything will fail on day one in the slowest tests, and that is expected.

Two pipeline details are worth copying. Run the guard on the pull request, not only nightly: a leak is cheapest to fix in the branch that introduced it. And keep the loop count in the log line – the terminal summary prints how many async tests ran on how many loops, and a number that jumps from one loop to twenty is the earliest visible sign that somebody changed a scope.

One Line Worth Keeping In CI Logs: The terminal summary is the cheapest telemetry you will ever add: one line, no network, and it tells you at a glance whether the suite still runs one test per loop, or whether a fixture change quietly collapsed twelve tests onto one.

What Python and pytest already catch, measured

The fair question about a plugin like this is what it adds over the switches that already ship. We ran the same seven-test broken suite under each of them, on the same container, and recorded both what was reported and whether the run changed colour.

MechanismWhat it reported on this suiteWhat it missedFails the test?
PYTHONASYNCIODEBUG=1nothing – under pytest-asyncio 1.2.0 the test loop reported get_debug() == False even with the variable set, while a plain asyncio.run in the same shell honoured iteverything: the blocking test, both leaked tasks, the cross-loop future was already failingno
asyncio_debug = true (ini) with the default 0.1 s slow_callback_durationone warning naming the coroutine: Executing <Task ... coro=<test_3_blocking_call_inside_async_test() ...> took 0.200 secondsthe 50 ms block (below the threshold) and both leaked tasksno – the run stayed 2 failed / 4 passed / 1 skipped
-W error or -W error::ResourceWarningan unclosed socket, attributed to the test that leaked it: FAILED test_leaks_a_socket - PytestUnraisableExceptionWarningleaked tasks: a sibling test whose body only starts a background task passedyes for the resource, no for the task
loopkitboth leaked tasks by coroutine name and creation site, the 200 ms block, and the registry check when a bound object crosses a loopresource leaks (keep -W error::ResourceWarning alongside it) and C-level blockingyes – on the leaking test, not the victim
Table 9: Built-in diagnostics and the guards, measured on the same seven-test suite. Only the last row names the test that created the leak.

The PYTHONASYNCIODEBUG=1 row deserves the exact commands, because the result is counter-intuitive: measured on pytest 8.3.4 with pytest-asyncio 1.2.0, the variable reached a plain asyncio.run in the same shell but never reached the loop that pytest-asyncio builds for a test.

$ PYTHONASYNCIODEBUG=1 python -m pytest tests -q
2 failed, 4 passed, 1 skipped              # unchanged: still only the two bystanders

$ cat tests/test_loopdebug.py
import asyncio


async def test_loop_debug_flag_inside_pytest_asyncio():
    print("loop.get_debug():", asyncio.get_running_loop().get_debug())
    assert asyncio.get_running_loop().get_debug() is False

$ PYTHONASYNCIODEBUG=1 python -m pytest tests/test_loopdebug.py -q -s
loop.get_debug(): False
1 passed in 0.16s

$ PYTHONASYNCIODEBUG=1 python -c "import asyncio
async def main():
    print('loop.get_debug():', asyncio.get_running_loop().get_debug())
asyncio.run(main())"
loop.get_debug(): True

So the variable is honoured by asyncio.run and not by the test loop; asyncio_debug = true in the ini is the switch that actually reaches that loop, and it only turns on warnings. Neither path names the test that created the task, which is why the attribution guard is still the product.

Two conclusions. Turn the built-ins on anyway – -W error costs nothing and catches a class of bug the guards do not look at, and asyncio_debug gives you a free second opinion on the worst offender in a run. But notice what none of them can say: which test created the task that is still running. The debug warning names a coroutine and a duration, the resource warning names a test, and neither connects a leak to its owner. Attribution is the whole product, which is why the guard fails the leaker rather than the bystander.

10. Proving The Guards: Test The Test Tool

A guard that has never been tested is indistinguishable from a guard that does nothing, and the failure mode is silent – the suite stays green. pytest ships the tool for this: the pytester fixture runs an inner pytest session in a temporary directory, and you can assert on its outcome counts and on its output. The module’s suite has sixteen tests: nine for the pytest-free core, and seven that each drive one or more real inner sessions.

from __future__ import annotations
import pathlib
import pytest
SANDBOX = pathlib.Path(__file__).resolve().parents[1]
INI = """[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
"""

@pytest.fixture
def suite(pytester: pytest.Pytester) -> pytest.Pytester:
    pytester.syspathinsert(str(SANDBOX))
    pytester.makeini(INI)
    pytester.makeconftest("pytest_plugins = ['loopkit.plugin']\n")
    return pytester

def test_clean_suite_passes_and_reports_loops(suite: pytest.Pytester):
    suite.makepyfile(
        """
        import asyncio

        async def test_one():
            await asyncio.sleep(0)

        async def test_two():
            await asyncio.sleep(0)
        """
    )
    result = suite.runpytest()
    result.assert_outcomes(passed=2)
    result.stdout.fnmatch_lines(["*2 async test(s) ran on 2 distinct event loop(s)*"])

def test_orphan_task_fails_the_test_that_leaked_it(suite: pytest.Pytester):
    suite.makepyfile(
        """
        import asyncio

        async def keep_spinning():
            while True:
                await asyncio.sleep(0.01)

        async def test_leaker():
            asyncio.create_task(keep_spinning(), name="spinner")

        async def test_victim():
            assert True
        """
    )
    result = suite.runpytest()
    result.assert_outcomes(passed=1, failed=1)
    result.stdout.fnmatch_lines(["*still running when the test finished*"])
    result.stdout.fnmatch_lines(["*keep_spinning created at test_orphan_task*"])
    result.stdout.fnmatch_lines(["*FAILED*test_leaker*"])

def test_blocking_call_is_measured_in_milliseconds(suite: pytest.Pytester):
    suite.makepyfile(
        """
        import time

        async def test_blocks():
            time.sleep(0.05)
        """
    )
    result = suite.runpytest()
    result.assert_outcomes(failed=1)
    result.stdout.re_match_lines([r".*held the event loop for [4-9][0-9]\.\d ms.*"])

def test_synchronous_tests_are_left_alone(suite: pytest.Pytester):
    suite.makepyfile(
        """
        def test_sync():
            assert 1 + 1 == 2

        async def test_async():
            assert True
        """
    )
    result = suite.runpytest()
    result.assert_outcomes(passed=2)

Two of those tests deserve a note. test_orphan_task_fails_the_test_that_leaked_it is the attribution claim in executable form: the inner suite has a leaker and a victim, and the assertion is that exactly one test fails and that the failing test is the leaker. test_synchronous_tests_are_left_alone is the regression guard for the whole design: an autouse guard that breaks plain synchronous tests would be removed from every suite within a day.

TestWhat it pins downResult
core: registry accepts its own loopno false positives on the happy pathpass
core: registry names the owner testthe message contains the creating node idpass
core: registry ignores unknown objectscheck() on an unbound object is silentpass
core: ledger lists only survivorsfinished tasks are not reportedpass
core: ledger ignores the probe taskthe guard does not report itselfpass
core: probe measures a sync sleep50 ms block is above a 5 ms budgetpass
core: probe stays inside budget for async sleepawaiting 50 ms is not a blockpass
core: probe is reusable after stopa stopped probe can be started againpass
core: frame_of names the caller modulethe creation site points outside loopkitpass
plugin: clean suite passes and reports loopssummary line and zero noisepass
plugin: orphan fails the leakerattribution, not a bystanderpass
plugin: blocking measured in millisecondsregex asserts a two-digit ms figurepass
plugin: gap budget can be disabled--loopkit-gap-ms=0 restores plain pytestpass
plugin: orphans ignored keep suite greenescape hatch for adoptionpass
plugin: foreign loop binding is namedcross-loop registry check fires, and the ini switch turns it into a no-oppass
plugin: sync tests left aloneno interference outside async testspass
Table 10: Sixteen tests in the module’s own suite – nine for the pytest-free core, seven that drive real inner sessions. All sixteen pass.

11. The Application Fix: Single-Flight That Survives Cancellation

Guards find the bug; only the application can remove it. The gateway’s cleanup has to handle cancellation explicitly, resolve the waiters that were counting on it, and make the cancel path observable instead of silent. The second edition does all three, and it keeps the coalescing behaviour that made the cache worth having.

"""Pricing gateway, second edition: single-flight that survives cancellation.

Three rules keep the cache from outliving the loop it was built on:

1. the entry is removed in ``finally`` regardless of how the owner finished;
2. waiters are resolved explicitly instead of being left pending;
3. the gateway is closed by the fixture that created it, so no future survives
   the test that started it.
"""
from __future__ import annotations

import asyncio
from dataclasses import dataclass


class QuoteError(Exception):
    """Base class for a lookup that did not produce a quote."""


class QuoteFailed(QuoteError):
    """The upstream call raised."""


class QuoteCancelled(QuoteError):
    """The caller that owned the upstream call was cancelled."""


@dataclass(frozen=True)
class Quote:
    sku: str
    price_cents: int


class PricingGateway:
    def __init__(self, fetch) -> None:
        self._fetch = fetch
        self._inflight: dict[str, asyncio.Future] = {}
        self.upstream_calls = 0
        self.abandoned = 0

    @property
    def inflight(self) -> dict[str, asyncio.Future]:
        return dict(self._inflight)

    async def quote(self, sku: str) -> Quote:
        pending = self._inflight.get(sku)
        if pending is not None:
            return await pending
        pending = asyncio.get_running_loop().create_future()
        self._inflight[sku] = pending
        try:
            self.upstream_calls += 1
            value = await self._fetch(sku)
        except asyncio.CancelledError:
            self.abandoned += 1
            self._fail(sku, pending, QuoteCancelled(f"lookup for {sku} was cancelled"))
            raise
        except Exception as exc:
            self._fail(sku, pending, QuoteFailed(f"lookup for {sku} failed"))
            raise QuoteFailed(f"lookup for {sku} failed") from exc
        self._succeed(sku, pending, value)
        return value

    def _succeed(self, sku: str, pending: asyncio.Future, value: Quote) -> None:
        if self._inflight.get(sku) is pending:
            del self._inflight[sku]
        if not pending.done():
            pending.set_result(value)

    def _fail(self, sku: str, pending: asyncio.Future, error: QuoteError) -> None:
        if self._inflight.get(sku) is pending:
            del self._inflight[sku]
        if not pending.done():
            pending.set_exception(error)
            # a future nobody awaited would log "exception was never retrieved"
            pending.add_done_callback(lambda future: future.cancelled() or future.exception())

    def reset(self) -> None:
        """Drop every entry and resolve the waiters with an explicit error."""
        for sku, pending in list(self._inflight.items()):
            self._fail(sku, pending, QuoteError(f"gateway closed before {sku} resolved"))
        self._inflight.clear()


async def fetch_upstream(sku: str) -> Quote:
    await asyncio.sleep(0.01)
    return Quote(sku=sku, price_cents=1000 + len(sku))

The except asyncio.CancelledError branch before except Exception is the fix in one line, but the interesting part is what happens to the waiters. In the first edition a cancelled owner left them waiting on a future nobody would resolve; the test that awaited them could only detect it by timing out. In the second edition they are resolved with QuoteCancelled immediately, which turns a timeout into an assertion.

ScenarioFirst editionSecond edition
Owner cancelled, one waiterwaiter waits until its own timeout – 50.22 ms in the probe – then raises TimeoutErrorwaiter raises QuoteCancelled after 0.026 ms
Cache after the cancellation1 unresolved future left behind0 entries, abandoned counter incremented
Five concurrent lookups1 upstream call1 upstream call – the fix costs nothing
Upstream raiseswaiters hangevery waiter raises QuoteFailed
Table 11: Same cache, same coalescing, different fate for the waiters.

One more line in that module is a lesson that only shows up when you start testing cancellation: pending.add_done_callback(lambda future: future.cancelled() or future.exception()). A future whose exception is never retrieved logs Future exception was never retrieved at garbage collection, which is noise in a test log and a genuine leak signal in production. Retrieving it in a done callback marks it as observed without changing what the waiters see.

12. What The Guards Cost

A guard that costs ten percent of the suite is a guard that gets removed, so we measured the overhead the way we would measure a feature: same suite, same machine, alternating runs, medians reported.

Suite and configurationRunsMedian wall timeLoopsWorst gap seen
Fixed suite, plugin disabled12635.4 ms––
Fixed suite, plugin enabled20657.2 ms8 for 8 tests1.4 ms
Fixed suite, session loop scope10650.9 ms1 for 8 tests1.2 ms
Broken suite, plugin disabled20844.3 ms––
Broken suite, plugin enabled20859.8 ms6 for 6 tests200.3 ms
Table 12: Overhead is 21.8 ms for eight tests, 2.7 ms per test, 3.4 percent.

The absolute numbers matter less than the shape: the cost is per test and roughly constant, so it amortises on a long suite and dominates a trivial one. Twenty-one milliseconds for eight tests is not a reason to skip the guards; a single leaked task that costs an engineer an afternoon is worth thousands of runs.

The session-loop row is the one that ends an argument. Reusing a single loop for the whole session changed the wall clock by 6.3 ms – one percent – while collapsing eight loops into one boundary-free surface. Loop creation simply is not the expensive part of an async test; fixture setup, imports and the test body are. Whatever a team saves by sharing a loop, they pay back the first time a future crosses the boundary.

13. A Migration Checklist

  1. Add pytest_plugins = ["loopkit.plugin"] and run with loopkit_orphans=warn and --loopkit-gap-ms=0. Collect the warnings for a week; do not fix anything yet.
  2. Grep the test tree for module-level AsyncClient, Pool, Session, cache = {} and lru_cache. Those are the objects that cross loops.
  3. Convert them into function-scoped fixtures with teardown. Where a real shared resource is needed (a database, a container), share the connection string, not the connection.
  4. Give every scope="session" async fixture either a matching loop_scope or an explicit marker on every consuming test, and refuse the combination in review.
  5. Replace except Exception with except BaseException plus a raise in any cleanup path that owns a future; better, put the cleanup in finally.
  6. Wrap every background task in async with, or cancel and await it in a fixture teardown.
  7. Turn loopkit_orphans to fail once the warning count is zero.
  8. Calibrate the blocking probe with an empty body on your CI runner, then set loopkit_gap_ms to about sixteen times the p99 you observe – 16 x 1.52 ms is the 25 ms default, and it also clears the worst idle gap of 150 runs by a factor of seven.
  9. Keep the terminal summary line in CI logs and alert on the loop count changing without a scope-related commit.

14. FAQ: The Questions That Come Next

Q: Why not just run every test with asyncio.run() and avoid the plugin entirely?

A: Because asyncio.run creates a loop per call and closes it, which is correct isolation for the test body and no isolation at all for the objects the body touches. It also closes the loop under any task the body started, which turns a leak into a cancellation at an arbitrary point. Use one test per loop, as pytest-asyncio already does.

Q: Does asyncio_mode=auto change the isolation model?

A: No. The mode decides which functions pytest treats as coroutines; the loop scopes decide the isolation, and both defaults are function in pytest-asyncio 1.2. The mode does make the mistake easier, because a plain async def in a helper file becomes a fixture without anyone writing a decorator.

Q: Is a session-scoped loop the fast option?

A: We measured it: 650.9 ms against 657.2 ms for eight tests, 6.3 ms apart, one percent. It is not fast, and it removes the boundary that contains a leak.

Q: Why fail on leaked tasks instead of cancelling them quietly?

A: Because the test passed for a reason that will not survive a change in order. Quiet cancellation is what the loop does at shutdown today, and it is exactly why these bugs reach production: the suite reports success while the code under test is still running.

Q: Can the blocking probe produce false positives on a busy CI runner?

A: Yes, which is why the budget is calibrated from an idle run rather than guessed. On this container the idle p99 was 1.52 ms and the worst of 150 runs 3.23 ms; a 25 ms budget sits well above both. On a busier runner, measure again – the number travels better than the default.

Q: Does this work with anyio or trio tests?

A: The plugin hooks pytest-asyncio’s test coroutine, so it applies to asyncio tests only. anyio has its own loop management, and its backend selection makes the same class of mistake possible; the guards would need a sibling implementation against anyio’s fixture. We have not measured that, and this article does not claim it.

Q: What about pytest-xdist with --dist loadscope?

A: It changes which tests share a worker, which changes whether a leak is observed – not whether it exists. If your suite is green with one distribution and red with another, that difference is itself the diagnosis: state is being shared inside a worker.

15. Verification Summary

Everything quoted above was produced on this machine on 2026-11-16, in one measuring session, and every script that produced it is printed in the code blocks of this article, so each measurement can be re-run from the scripts here and the environment named below; the container image itself is not reproduced. The environment was Python 3.12.16, pytest 8.3.4, pytest-asyncio 1.2.0, pytest-xdist 3.6.1 and anyio 4.16.0 on a two-vCPU Linux container. The article was written by the engineer who ran the probes; the numbers were copied from the logs, not from memory.

ClaimHow it was verifiedRaw record
Cross-loop failure modesprobe creating each primitive in one loop and using it in another, including the contended lock and the unset eventlogs/cross_loop_mixins.json quoted in Table 2
The leak is deterministic and blamed on the victim20 consecutive full-suite runsTable 3, measurements.json
Guards name the culpritsame suite with the plugin, 20 runsTable 4
Session fixture scope mismatch6-test suite, three configurationsTable 6
Built-in tools versus the guardssame 7-test suite under debug mode, -W error and loopkitTable 9
Blocking measurementfive bodies with known behaviour plus 150 idle runsTable 7
Overhead12 runs without the plugin, 20 with, mediansTable 12
Guards actually work16 tests: 9 core unit tests and 7 that drive inner pytest sessionsTable 10
The application fix8 tests covering cancel, failure, coalescing and resetsection 11
Table 13: Claim, method, and the raw record each figure was copied from.

What this article does not claim: it does not measure anyio or trio, it does not measure Windows or macOS, and it does not claim that a 25 ms gap budget is right for your runner. It also does not claim that loopkit replaces a proper resource lifecycle – the guards make a leak visible, and the application still has to stop leaking.

Keep Reading On TechBobby

This runbook is part of a series on Python services that fail in ways the traceback does not explain. The closest neighbours: httpx AsyncClient in production, which is the client most async suites mock and most async tests leak, and memory leaks in production Python, where the same leaked tasks become memory instead of failures. The asyncio scraping guide covers the concurrency model these tests exercise, and SQLAlchemy 2.0 async in production is where a loop-bound connection pool turns into MissingGreenlet inside a test that never touched a database.

For the surrounding stack: FastAPI on Gunicorn and UvicornWorker for the worker lifecycle a test never sees, Redis caching and distributed locks for the lock semantics that survive a loop, Celery production architecture for the tasks that live outside the request, PostgreSQL slow query triage, Kubernetes pod resources and OOMKilled, Docker multi-stage builds for Python, and The TechBobby Stack, the tooling map these runbooks belong to.

Two free resources from TechBobby: the AI Prompt Pack for engineers – the prompts used to review code, write runbooks and interview a dependency – and the Zero-Crash Python newsletter, one production failure per issue with the measurements attached.

Written by TechBobby Engineering – an independent engineer publishing measured Python production runbooks. Every figure in this article came from a probe executed on Python 3.12.16 with pytest 8.3.4, pytest-asyncio 1.2.0 and pytest-xdist 3.6.1; every script is printed in full in the code blocks above and the logs from that session are kept. The pytest-asyncio default scopes, the CPython 3.12 mixins._LoopBoundMixin source (the reason a contended lock still binds a loop) and the pytest-asyncio debug switches were re-checked before this revision, and the two claims we could not verify on this machine – anyio and trio behaviour – are marked as out of scope in section 15.


Keep reading

Get the next essay and every new code pack before anyone else — subscribe to the weekly letter. Free tier first, always.