Skip to content

ADR 0019: Compiled code and CPython, across threads

Status: Final Type: Feature Created: 2026-07-28 Consolidated: 2026-08-07: absorbs 0017 (the handle-crossing rule) and 0018 (a compiled handler on a thread CPython owns), both retired Amends: 0006 (the GIL and thread-state discipline when tasks call CPython), 0010 (a task may reach CPython) Related-ADRs: 0006 (the FFI this disciplines), 0011, 0022. Provenance comes from arbitrations A24, A28, A35, A51, A54.

Context

The FFI and the concurrency runtime meet in both directions. A pygo task under Scheduler A is an OS thread CPython has never heard of, with no thread state and no GIL, so a task's first FFI call was once a segfault with an unflushed stdout buffer. In the other direction, a compiled handler runs on threads CPython created (a threaded web server). The pygo runtime caches its task context per OS thread, so what one request leaves behind is what the next request inherits. This ADR is the discipline that makes both directions work, plus the rule for the one kind of value allowed to cross between tasks.

Decision

What may cross a task boundary: classified at run time, at the crossing

A CPython immutable (str, bytes, int, float, bool, None, and tuples/frozensets transitively of those) is val in the sendability rule's own sense: no observer can tell whether tasks share one or each holds a copy; a data race needs a mutation. All handles are spelled object, so no static rule can separate a str handle from a dict handle. The classification is therefore at run time, at the crossing. A static rule with an explicit escape was rejected because an explicit escape is an unchecked assertion whose broken promise is exactly the outcome that must be impossible.

Three properties support the safety argument:

  • It is a call: the helper returns the handle it was given, so no path from a handle into a task bypasses it, on any backend.
  • It runs on the spawning task, where the GIL is held and both the object and the argument's name are in hand.
  • A refusal does not return. Sharing a mutable between tasks is a rule violation: it raises no exception, so a try: cannot swallow it, and --release cannot compile it out.

The predicate is CheckExact: a str subclass has an instance __dict__, hence a possible mutation, hence a race. Recursion into tuples/frozensets is depth-bounded; over the bound the answer is no. The refusal names the offending type transitively: a tuple holding a list reports the list. The interpreted program does not refuse; the compiled side is stricter than CPython happens to be and exactly as strict as a conforming program is required to be. The byte-identity contract covers conforming programs.

A pygo task calls CPython: the GIL discipline

  1. PyGILState_Ensure/Release at every FFI entry point, generated from the signatures that are already there. A rule about a list of hand-written functions is one merge away from having a member missing, so the bracket is emitted mechanically, with the do-nothing helpers (null, iterator-validity) exempt by name in one place. The runtime's own GIL assertion stays in place behind the generated bracket: a call graph shows direct calls only and misses callbacks CPython invokes and future indirect calls, so the boundary keeps its own guard even where generation makes it unreachable.

  2. Blocking pygo calls release the GIL around themselves, via a macro over a statement. A site that forgot the release half would be the hang this exists to prevent: a handler holding the GIL joins a task whose first CPython call waits for that GIL. The release is compile-time conditional on the program embedding CPython at all, so the pygo wrapper unit compiles unchanged, with no Python.h, in a --pure program. On a free-threaded build the release is still required: a thread staying attached across a long block stalls the next stop-the-world pause, the same deadlock in a different hat.

  3. A task takes its CPython thread state once, in the trampoline (Ensure, then immediately SaveThread). Without the cache, Ensure/Release on an unknown thread creates and destroys a thread state per call; destroying one runs a heap collect on free-threaded builds, which turned four tasks doing CPython work into ten times slower than one. Later FFI calls find the cached state, so their Ensure is a counter increment that never destroys anything. The bracket is emitted only for tasks the call graph shows reaching CPython. That walk is now an optimisation: a conservative answer costs one needless bracket; a wrong answer costs nothing, where the old refusal (PG209, withdrawn) had to be right or the program crashed.

  4. The compiled-function accessor cache takes a lock: function identity is observable from CPython, so two wrappers would be a wrong answer. On a free-threaded build the GIL is not mutual exclusion, so the check-then-create sits under a PyMutex.

A CPython thread calls compiled code: the attach bracket

Exported callbacks bracket their bodies with pygo_attach/pygo_detach as a two-function split: an inner function holding the body exactly as it was and an outer that is nothing but the bracket. The body has several return NULL paths; a bracket with several exits is that many chances to forget one. The bracket is gated on the program using pygo at all, so a callback-only program links what it always linked.

pygo_detach checks that the scope stack is balanced. The depth is recorded at attach, so a non-empty stack at entry is fine. The check matters because the task context is cached per OS thread (the context is the thread under Scheduler A). A scope leaked on it becomes the parent of the next scope that thread enters. The next request on that worker is born with someone else's deadline, silently cancelled. Resetting the stack at that point was refused: it hides the caller's bug. The hazard is not reachable from POST source (the compiler refuses every path that skips a scope's join); it is an ABI contract whose consumers are other compilers and hand-written C.

The ABI version rule this bought: the compiler refuses a runtime older than the MINOR that added the detach check. A MINOR that adds symbols is caught by the linker; a MINOR that adds a check must be refused explicitly, because an older runtime links, runs, and silently does not make the check.

Free-threaded CPython

Free-threaded 3.14t is a supported embed target: the full suite, the web service, and a compiled binary serving HTTP on worker threads with free-threaded libpython inside all pass. The measured shape: concurrent task CPython work anti-scales on a GIL build and scales on a free-threaded one, so free-threading is the difference between negative and positive scaling, bounded by CPython's own stop-the-world pauses. A generated extension module declares Py_MOD_GIL_NOT_USED, so importing one keeps the GIL off; the declaration is a claim about every linked runtime unit, and 0022 holds the audit behind it.

Consequences

  • A compiled handler on a CPython-owned thread can open a TaskGroup; a compiled task can make and read handles; a handler that does CPython work and then joins tasks doing CPython work (the canonical deadlock) works, on three backends, byte-identical to the interpreted run.
  • Two non-optimisations are logged: a task attaches and detaches per FFI call (staying attached is cheaper free-threaded and catastrophic under a GIL, so the right shape is build-dependent, which makes it a design question), and module lookups are not cached per program.
  • The old task-reaches-CPython refusal is withdrawn with its cost: a helper called from both a task and the dispatching thread no longer needs to be split.

Alternatives considered

  • A static crossing rule with an escape hatch: rejected, because the escape is an unchecked promise whose failure mode is the one outcome that must be impossible.
  • Check as the predicate: rejected, since subclasses are mutable through their instance dict; exactness is the immutability argument.
  • Resetting the scope stack at detach: rejected, since it hides the caller's unjoined scope.
  • Keeping the task-to-CPython refusal (PG209): rejected once the discipline existed, because a capability with a fallback beats a refusal that had to be exactly right.