8000 anyio, not asyncio · Issue #572 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

anyio, not asyncio #572

Closed
Closed

Description

@Lillecarl

DONE. The suite runs under anyio, and so does the library. Every
asyncio name outside payload/runtime.py is gone, and the four that
stay there are the one measured exception. Originally: the suite ran
under anyio; the runtime did not, and payload/runtime.py's four
loop.run_in_executor calls were the half this file called movable.
They are not movable, and the 2026-09-05 section says why.

Carl, 2026-08-25: "We should use anyio instead of asyncio where
possible, this includes anyio's test runner instead of pytest-asyncio.
This is what my other related projects do and what we should continue
doing. You don't have to migrate all code to anyio primitives straight
away but pytest-asyncio is to be removed in favour of anyio, it's more
correct."

Done: the suites

The test harness is anyio throughout - the runner, the subprocess, the
port probe, the timeouts, the sleeps. pytest-asyncio is gone.

Two things about anyio's plugin worth knowing before touching it:

  • anyio_mode = "auto" runs every async test under it without a
    marker, the same way asyncio_mode did. (I first wrote that anyio
    had no auto mode and marked every suite by hand; Carl corrected it.
    anyio has had the setting since 4.x.)
  • the runner is cached at the anyio_backend fixture's scope. That
    fixture is session-scoped here on purpose, because that is what lets
    a server fixture outlive one test. A client belongs to the loop it
    connected on, and reconnecting is what several of these tests are
    about.

Structured concurrency changed one thing for the better. The server
fixture's log drain used to be a fire-and-forget task; it is now a
task group whose scope encloses the yield, so the reader cannot
outlive the fixture. That is the same class of bug as the reaper task
asyncio could collect before it ran (fixed in the server earlier), and
anyio makes it unrepresentable rather than merely fixed.

Not done: the library

remote.py, server.py and the generated _runtime.py are still
asyncio, and one of them cannot move on its own: grpclib is an asyncio
library. So the migration splits in two.

Movable now, because none of it touches the transport:

  • _runtime.py. run_in_executor becomes anyio.to_thread.run_sync,
    which also gets a limiter rather than a hand-rolled pool - though
    the AFFINE runner needs its own dedicated thread and anyio's thread
    pool does not offer thread affinity, so that one stays a
    concurrent.futures executor either way.
  • the client's ping loop, which is a bare asyncio.sleep in a task
    that has to be cancelled by hand. A task group ends it by scope.

Blocked on the transport: anything that touches grpclib. Either it
keeps an asyncio loop underneath (anyio's asyncio backend runs on one,
so this works today and is what the suites already prove), or the
transport itself changes. That is a bigger decision than a primitive
swap and it belongs with #551, which already asks what the
transport should be.

The honest order is: move the runtime and the ping loop, leave grpclib
alone, and revisit when 014 does.

2026-09-05: Carl asked again, and the library moved

We should be using anyio primitives instead of asyncio to the
greatest extent possible (preferably only), record this in
CLAUDE.md and work on it. anyio's structured async model is good at
preventing bugs.

The rule is now in CLAUDE.md, which is what this file lacked - it
sat open for eleven days as a task nobody was steering by.

This section was written as #629 first, which was a
duplicate of the file it is now part of.
Nothing looked for an
existing task before opening a new one, and tasks/README.md names
this file on its own line. The number 092 is retired; every citation
in the code points here.

What 035 got right, and the one thing it got wrong

Right, and worth saying because it was written from reading rather
than from running: "the AFFINE runner needs its own dedicated thread
and anyio's thread pool does not offer thread affinity". Confirmed
below against anyio 4.14.2's source.

WRONG: "the client's ping loop, which is a bare asyncio.sleep in a
task that has to be cancelled by hand. A task group ends it by
scope." The sleep moved; the task did not. A task group is a scope
somebody holds open, and a NixClient has none - see the last
section.

Also wrong in the other direction: "run_in_executor becomes
anyio.to_thread.run_sync, which also gets a limiter rather than a
hand-rolled pool". That is true only of the SHARED pool, and it is
not done - the reason is below.

What is there today

Every asyncio name outside the tests, by file.

server.py     Lock, sleep x2, ensure_future x2, create_task,
              Task[None], CancelledError x2, run
remote.py     create_task, sleep, wait_for x2, Task[None]
watch.py      Lock
runtime.py    get_running_loop x4, run_in_executor x4
smoke_test.py gather x4, get_running_loop x2, run
notify.py     named in a comment only

The exception, and it is measured

runtime.py keeps loop.run_in_executor. Read
anyio/_backends/_asyncio.py, run_sync_in_worker_thread:

if not idle_workers:
    worker = WorkerThread(root_task, workers, idle_workers)
    ...
else:
    worker = idle_workers.pop()
    # Prune any other workers that have been idle for
    # MAX_IDLE_TIME seconds or longer

A SHARED pool, LIFO, with expiry. run_sync takes a limiter and no
thread. So there is no way to say "this call, on that thread".

Two things depend on exactly that:

  • An EvalState is AFFINE. AffineRunner gives each one a
    ThreadPoolExecutor(max_workers=1), and thread_queue in
    logging.hpp is a thread_local that assumes it.
  • _refuse_foreign compares callee._executor() is arg._executor().
    That identity check IS the isolation Carl ruled on: values from one
    EvalState are not valid for another.

The anyio-native shape that was rejected

It is constructible. One long-lived
to_thread.run_sync(worker_loop, limiter=CapacityLimiter(1)) per
state, consuming a job queue, gives an affine thread with an anyio
spelling.

Rejected. It rebuilds run_in_executor by hand, it replaces the
executor identity that _refuse_foreign reads with something else to
compare, and it buys NO structure - an affine thread already has one
owner and one lifetime, which is the whole thing a task group would
have added.

The shared pool stays too, for a weaker reason

_shared_pool needs no affinity, so to_thread.run_sync with a
CapacityLimiter(_POOL_SIZE) would work. It is not done because it
buys nothing and it is not free: the pool would churn where it does
not today, and this repo has already aborted a process over thread
churn under Boehm (gc.hpp, "verified by reproducing the abort
first"). The thread_local destructor makes churn CORRECT rather than
leaky, so this is a preference and not a defect - recorded so the next
reader does not re-derive it.

What the conversion buys, per site

server.py   _detach + the retained `self._closing` set + the
            "asyncio holds only a weak reference to a running
            task" comment ALL die. A task group holds its
            children. This is the concrete instance of Carl's
            point.
server.py   `_Fanout` stops holding a Task and cancelling it.
remote.py   the ping loop stops being a task the client has to
            remember to cancel.
both        `wait_for` -> `fail_after`, which is a cancel scope
            and composes.

Three traps, named before they are hit

  1. A task group WAITS for its children; it does not cancel them.
    sweeper() and _Fanout._run loop forever, so a task group around
    serve() hangs on shutdown unless the exit cancels the scope.
  2. start_soon hands back no task. _Fanout.leave cancels the
    drain and awaits it before unsubscribing, and that ordering is
    GATED (test_the_last_reader_out_unsubscribes). It has to become a
    CancelScope stored on the fan-out plus an anyio.Event the drain
    sets in its finally.
  3. Never swallow the cancellation exception.
    contextlib.suppress(asyncio.CancelledError, Exception) in
    _Fanout.leave is hostile under anyio's contract. Where one must
    be named, anyio.get_cancelled_exc_class() is the spelling.

Order

  1. This file and the CLAUDE.md rule.
  2. The mechanical swaps: Lock, sleep, wait_for, gather, run.
  3. server.py's task groups, which is the structural one.
  4. remote.py's ping loop.

Done, 2026-09-05, except one spawn

Every asyncio name outside runtime.py is gone but one.

watch.py       Lock            -> anyio.Lock
server.py      Lock, sleep     -> anyio
server.py      ensure_future   -> two task groups
server.py      create_task     -> loops.start_soon
server.py      run             -> anyio.run
smoke_test.py  gather x4       -> `_all` / `_all_errors`
smoke_test.py  loop().time()   -> anyio.current_time
smoke_test.py  run             -> anyio.run
remote.py      sleep, wait_for -> anyio.sleep, anyio.fail_after
remote.py      create_task     -> STILL asyncio, see below

The two task groups in serve

work is outer and AWAITED. It holds the runner shutdowns _on_drop
starts, and each of those releases an affine thread from the
collector's list - work that must finish rather than be cancelled.

loops is inner and CANCELLED. It holds the sweeper and the log
drains, which never return on their own.

Being inner is what orders them: the loops stop first, and anything
they started is still awaited by work afterwards. This is trap 1
above, answered.

_detach, the retained self._closing set, and the comment
explaining that "asyncio holds only a weak reference to a running
task" are all GONE. That is the concrete thing Carl's point buys
here: the workaround existed because nothing owned the task, and a
task group owns it.

start_soon is a plain method rather than a coroutine, which is what
lets _on_drop - a callback the sweep calls synchronously - still
start one.

The bug the conversion caused, and the suite caught

_Fanout._run set self._stopped after its cancel scope exited, and
leave clears that attribute before the drain notices the cancel. So
the first run died at startup:

File "huggorm/server.py", line 385, in _run
AttributeError: 'NoneType' object has no attribute 'set'

The server never listened and 11 tests failed with
ConnectionRefusedError. Both sub and stopped are parameters
now, for the same reason sub already was.

The teardown ORDER is argued, not gated

leave cancels the drain, waits for it, and only then unsubscribes.
Two perturbations were tried and NEITHER produced a failing test:

drop `await stopped.wait()`     ruff refuses it - F841, `stopped`
                                assigned and never used. So the
                                linter holds the shape, and no
                                test was reached.
wait AFTER the unsubscribe      396 passed. The ordering is not
                                gated.

The second one is the honest finding. sub.close() empties the queue
anyway, so a late drain finds a closed queue and the binding tolerates
the race. The wait stays because it makes the sequence say what it
means, not because a test proves it must.

Recorded rather than left implied: the three fan-out gates from
#622 still hold, and they are what proves the CancelScope and
Event replace the Task correctly.

The tests, and one more thing not gated

The first survey in this file excluded tests/, which the rule does
not. One hit: test_lifecycle.py used asyncio.wait_for to bound one
iteration of the real ping loop. Converted. conftest.py names
asyncio twice and both are correct - it pins the anyio BACKEND, which
grpclib fixes.

serve's two-group exit ordering is also argued rather than gated.
The suite stops a server with SIGTERM, so nothing here ever runs the
finally that cancels loops and lets work drain. Stated beside
the teardown-order finding above for the same reason.

The one spawn left, and why it was held for Carl

NixClient._ping_loop started with asyncio.create_task.

anyio starts a task only inside a task group, and a task group is a
scope somebody holds open. A NixClient had none: connect() built
it and a synchronous stop_pinging() stopped it, so there was no
async with to own the loop.

Giving the client one is a BREAKING change to a published surface,
and CLAUDE.md called that the expensive kind - so it was written up
as Carl's call rather than made.

Carl answered by deleting the rule.

Breaking compatibility is not frowned upon in this repo, it's
encouraged if it helps improve the codebase. This repo is an
elaborate spike, backwards compatibility is not in our terminology,
the best possible thing forwards is the only goal.

The sentence that made this a question - "the third is what makes a
breaking change expensive" - is gone from CLAUDE.md, and the
section that replaces it says to take the break.

The break, 2026-09-05

connect() is an async context manager. NixClient owns a task
group, opened in __aenter__ and closed in __aexit__.

client = await remote.connect(host, port)     # before
...
client.stop_pinging()

async with remote.connect(host, port) as client:   # now
    ...

What a caller written against the old shape sees is Python's own:

TypeError: object _AsyncGeneratorContextManager can't be used in
'await' expression

Not gated, because it is the interpreter's sentence rather than ours
and a test on it would assert CPython's wording. It names the type,
which is enough to find this file.

bind() REFUSES outside the context, with a message that names the
fix. That refusal reaches the OTHER migration - a caller that builds
a NixClient by hand - because the await above fires first for
anyone who used connect. It is the one place a caller could still start a loop nothing
owns, and letting it would put back exactly what this removed.

stop_pinging() stays public. It is no longer cleanup - the context
does that - but it is still how a test makes a connection go silent so
the sweeper reaps it, which the swept fixture does three times.

Two shapes that do not work, both measured

An AsyncExitStack in a pytest fixture, clients added by tests.
It would have kept every call site as it was. anyio needs ONE task to
enter and leave a cancel scope, and a fixture is not the task its
tests run in:

ERROR at teardown of test_probe_task_identity
ExceptionGroup: errors during test teardown (2 sub-exceptions)

A fixture body IS one task across its own yield, which is why the
client fixture and the swept fixture can each hold clients open -
they enter and leave them themselves.

A fail_after around the enter. The client fixture had one, to
report a server that never answers. Entering a client leaves a cancel
scope OPEN, so the timeout's scope then tries to close inside it:

RuntimeError: Attempted to exit a cancel scope that isn't the
current tasks's current cancel scope

Eleven tests failed on it. A guard on the connect would have to close
after the client does, which is the opposite of what it is for, so it
is gone and the suite's own timeouts cover that case.

Two gates, and what breaking one shows

bind() outside the context refuses
leaving the context stops the loop

Dropping stop_pinging() from __aexit__ hangs EVERY client test,
not just the second gate: a task group waits for its children and the
ping loop never returns. The first test to reach a client died on
pytest-timeout at 180 seconds.

That is the change stated as a cost: a forgotten stop_pinging() used
to leak a task quietly, and now the equivalent mistake stops the
program. Loud beats quiet, and this repo's named failure mode is the
quiet one.

Migrated from tasks/035-anyio-not-asyncio.md.done.


Assisted-By: Opus 5

Activity

  1. added
    source: huggorm
    on Oct 19, 2026
  2. transferred this issue fromnixidae/huggormon Oct 19, 2026
  3. added theissue type on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: huggorm

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0