If you have ever maintained a nontrivial asyncio codebase, you know the quiet failures. A task is spawned without anyone keeping a reference, and the garbage collector eats it mid-flight. An exception surfaces three layers away from the bug. A timeout fires, but the code it was supposed to protect keeps running anyway because cancellation is opt-in per awaitable. It is widely recognized that these failure modes make large async Python systems hard to reason about, and none of them announce themselves in a profiler.

Trio’s answer is structural rather than cosmetic. Every task must live inside a nursery, every nursery must finish its children before its block exits, and every blocking call is an explicit cancellation point. The design has influenced a generation of Python libraries, and its implementation is remarkably legible once you know where to look: the entire scheduler fits in one file, src/trio/_core/_run.py, which at 3,141 lines is the largest module in the package.

This post is a source tour of the real tree of python-trio/trio on branch main at version 0.35.0+dev, which requires Python 3.10 or newer. We walk it top to bottom: the run loop and its unrolled scheduling generator, the three platform IO backends, the sync primitives, the thread bridge, and the socket layer. Every symbol, path, and line number below was verified against that checkout, so you can follow along in your own clone.

Trio overview architecture: run() driving the Runner scheduler and the three IO backends

Overview of Trio's architecture: the public run() entry point feeds a generator-based scheduler whose Runner parks tasks on epoll, kqueue, or an IOCP completion port depending on the operating system.

Reading the overview from left to right:

  • run(), L2426 — the only way into the library. It takes an async function plus clock, instruments, and strict_exception_groups options, calls setup_runner(), then loops: it sends event batches into a generator until the main task’s outcome is ready.
  • Runner, L1786 — the per-run state object: the runq deque of ready tasks, a Deadlines heap, the task set, the IO manager, the keyboard-interrupt manager, and guest-mode flags.
  • Nursery, L1183 — the structured-concurrency container, built with NoPublicConstructor so users only get one from open_nursery(). Its start_soon() at L1340 schedules children via spawn_impl; exiting the async with waits for every child.
  • CancelScope, L543 — the cancellation unit. Each scope carries a deadline and shielding state; cancel() at L928 marks it effectively cancelled and aborts parked waiters inside it.
  • checkpoint(), L3019 — the schedule point and cancel point in one function. It increments task._cancel_points, gives the scheduler a chance to run other tasks, and raises Cancelled if the current status is effectively cancelled.
  • EpollIOManager, L200 — the Linux backend. One epoll object, waiters keyed by file descriptor, and a get_events(timeout) that hands the scheduler the next batch of readable and writable sockets.
  • to_thread_run_sync, L257 — the escape hatch for blocking calls. It ships the function to a daemon worker thread and parks the calling task; from_thread_run at L531 is the inverse direction for worker threads.
  • CapacityLimiter, L174 — the FIFO token limiter that throttles the thread pool. The default limit lives one floor down: DEFAULT_LIMIT = 40 in _threads.py at L56.
Trio detailed architecture with scheduler internals, IO backends, sync primitives, and the socket layer

The detail view: scheduler internals on the left, the three IO backends, the thread and signal bridge, waiter-based sync primitives, and the socket, subprocess, and helper modules on the right.

The Run Loop Is a Generator, Not a Method

The most surprising fact about Trio’s core is architectural: run() does not contain the scheduler as a method. The scheduling state machine lives in a separate generator, unrolled_run, L2715, and run() simply steps it. Each time the generator yields, it asks for one IO wait with a specific timeout; run() calls runner.io_manager.get_events(timeout) and sends the result back. The while True: loop doing this sits at L2532, wrapped in a try/finally that restores the sniffio library name so other async frameworks can detect which runtime they run under.

Why unroll it into a generator? The generator boundary is a hard isolation line: scheduling machinery runs as plain synchronous Python between waits, and event dispatch happens in exactly one place. It also enables guest mode. start_guest_run, L2550 starts an embedded run whose Runner gets ticked by a host loop through run_sync_soon_threadsafe callbacks — the trick that lets Trio run under Jupyter and other hosts without taking over their main loop.

Cancellation Is a Library Feature, Not a Language One

Python’s CancelledError exists in the language, but Trio treats cancellation as a scheduling problem. A CancelScope is entered with a deadline, optionally shielded, and its cancel() records a structured CancelReason rather than flipping a boolean. The scope tree is consulted at every checkpoint: checkpoint(), L3019 first gives the scheduler a chance to reorder work, then checks task._cancel_status.effectively_cancelled and, if a cancel is pending, enters a throwaway scope with deadline -inf and parks the task so Cancelled is delivered at the right point in the stack.

The same discipline covers Ctrl-C. Trio installs its own SIGINT handling through KIManager, defined at L241 of src/trio/_core/_ki.py. When the signal fires, it marks ki_pending on the runner instead of raising immediately; the pending interrupt is delivered to the main task at its next checkpoint, wrapped in Cancelled, so finally: blocks and context managers run exactly as written. The checkpoint function itself is a few dozen lines — the mechanism is small, which is part of why it is so trusted.

The waiting machinery under all of it is ParkingLot, a private counting primitive at L138 of src/trio/_core/_parking_lot.py. Every higher-level waiter — locks, semaphores, the capacity limiter, condition variables, even memory channels — parks tasks there and wakes them in FIFO order, which makes Trio’s fairness guarantees uniform across the API surface.

One IO Contract, Three OS Backends

The scheduler never talks to the operating system directly. It only requires that the installed IO manager expose a small contract: register waiters per descriptor or handle, get_events(timeout) to block once per scheduling pass, and force_wakeup() to break the wait from outside. Three implementations ship in the tree, and their size reflects platform reality rather than abstraction overhead.

On Linux, EpollIOManager, L200 fills 385 lines including its statistics class. The BSD/macOS KqueueIOManager starts at L35 of _io_kqueue.py (298 lines) and follows the identical shape. Windows is the outlier: WindowsIOManager begins at L428 of _io_windows.py, a 1,036-line module, because sockets there are polled through the internal AFD device whose request structures Trio defines by hand, and completion events are drained from an IOCP port rather than a selector.

Cross-thread wakeups all funnel through one primitive: WakeupSocketpair at L12 of _core/_wakeup_socketpair.py, a self-pipe whose wakeup_thread_and_signal_safe() is the only method a non-Trio thread may call. The epoll and kqueue managers subscribe its read end with force_wakeup(), so a worker thread finishing a blocking call can break the main wait without races. Signal handling reuses the same socket via wakeup_on_signals() at L52, which is how open_signal_receiver (L130 of src/trio/_signals.py) exposes signals as an async iterator without the usual handler-race caveats.

From One Thread to Forty: Build Facts from the Tree

Trio’s engineering shows up in numbers as much as in design. Build facts you can verify in the tree:

  • The blocking-call budget is DEFAULT_LIMIT, L56: DEFAULT_LIMIT = 40, the maximum number of OS threads to_thread_run_sync will occupy by default, enforced through the CapacityLimiter returned by current_default_thread_limiter().
  • The whole public low-level surface is a facade: src/trio/lowlevel.py is only 96 lines, re-exporting curated names from _core with from x import y as y — the comment in the file says that form exists for pyright --verifytypes compatibility.
  • The instrumentation layer is code-generated. src/trio/_core/_generated_run.py, _generated_io_epoll.py, _generated_io_kqueue.py, and _generated_io_windows.py all open with an “AUTOGENERATED! ALL EDITS WILL BE LOST” banner; they wrap every core call with KI protection and instrument hooks.
  • Memory channels default to zero buffering. open_memory_channel at L49 of src/trio/_channel.py (652 lines total) documents that max_buffer_size of 0 is the recommended choice for prompt backpressure, and channel operations are atomic with respect to cancellation.
  • Interface contracts live in one file: src/trio/_abc.py (722 lines) defines Clock, Instrument, AsyncResource, SendStream, ReceiveStream, HalfCloseableStream, Listener, and the channel ABCs that every stream class, including SocketStream at L55 of _highlevel_socket.py, implements.
  • Client sockets connect the smart way: open_tcp_stream at L188 of src/trio/_highlevel_open_tcp_stream.py races candidate addresses and includes a dedicated reorder_for_rfc_6555_section_5_4() helper (L140) implementing the Happy Eyeballs reordering rule.
  • Typing is enforced, not decorative: pyproject.toml carries a strict [tool.mypy] section at L197 and pyright typeCheckingMode = "strict" at L227, and linting runs through [tool.ruff] at L102 with a flake8-pytest-style block at L194.

That item points at the tooling culture in the repo itself. The test suite runs through a custom pytest integration: src/trio/_tests/pytest_plugin.py provides mock_clock (L37) and autojump_clock (L42) fixtures plus a pytest_pyfunc_call hook (L51) that runs each test inside run(), with the project’s pytest addopts wiring that plugin in by name — our pytest tour covers the framework side it plugs into. The same strictness applies to types and linting, which readers of the mypy and ruff tours will recognize.

Subprocess, Signals, and the Long Tail

The remaining modules show how far the “everything is a task” idea stretches. src/trio/_subprocess.py (1,177 lines) builds an async Process class (L103) and run_process (implementation at L465) whose cancellation behavior is deliberately platform-specific: _subprocess_platform/waitid.py imports to_thread_run_sync to watch process exit from a worker thread on Unix, while Windows uses its own wait-for-object machinery. Signals, file I/O, and DNS resolution follow the same pattern of moving blocking work off the run loop.

Even pathlib gets the treatment. src/trio/_path.py (289 lines) subclasses pathlib.PurePath with a Path class at L119 whose blocking methods execute through trio.to_thread.run_sync, with PosixPath and WindowsPath aliases at L275 and L284. Nothing invents a new filesystem API; the module is thin by design, which is the consistent theme of the package: core machinery in _run.py, everything else delegating to it.

Honest Limits

The tree also shows where the abstraction costs you. First, the run loop is single-threaded by design: Runner.runq is a plain deque with no locks, and CPU-bound work must go through to_thread (or processes) to avoid stalling every other task. Second, guest mode carries real constraints — the docstring of start_guest_run warns that stopping the host loop before the guest run finishes can leave internal structures inconsistent. Third, Windows support is heavy to maintain: the 1,036-line _io_windows.py contains hand-rolled AFD constants and cffi definitions precisely because CPython exposes no stable socket-polling API there. Fourth, the public Nursery type is unconstructible and typed as such, which surprises newcomers annotating it. Finally, this tour covers main at 0.35.0+dev; line numbers drift as the code evolves, so treat them as coordinates for this snapshot rather than permanent addresses. None of these caveats undermine the central lesson of the codebase: structured concurrency is mostly discipline, implemented in a few hundred lines of very careful scheduling code.

Watch PyShine on YouTube

Contents