Skip to content

ADR 0006: The CPython FFI

Status: Final Type: Feature Created: 2026-07-27 Consolidated: 2026-08-07 (absorbs 0008 (data operations, keyword call sites) and 0009 (the object annotation; both retired) Amended-By: 0007 (a CPython error is a catchable POST exception; no abort), 0019 (the GIL and thread-state discipline when tasks call CPython) Related-ADRs: 0005 (the conversion builtins), 0024 (handles are a remaining leak-at-exit heap). Provenance comes from arbitrations A13–A15 and A22 and from upstream question U11.

Context

Compiled-Python projects have died with their performance goals met, because compiled code could not call CPython: Flask, SQLAlchemy and even the stdlib were out of reach from the compiled side. The FFI makes the refusal discipline affordable: code that cannot compile gets a diagnostic, since the escape to CPython is expressible and silent deoptimization is unnecessary. The acceptance shape is an application: a compiled binary, libpython embedded, serving real Flask routes through compiled handlers, byte-identical to the same file interpreted.

Decision

The boundary

One visible boundary: from python import X. It is the only construct that produces a CPython value; nothing anywhere else falls back to a Python object. Interpreted, the same line keeps its ordinary meaning through a shipped shim module whose __getattr__ defers to importlib, so an FFI program runs unmodified under CPython and the stdout differential applies to it like any other program.

A handle is opaque. In emitted code it is void *, with a dtype kind of its own, so no numeric path ranks it, no arithmetic table matches it, and a backend without a row for it fails. No emitted translation unit includes Python.h; only the FFI runtime unit and the generated callback glue do. The C backend holds prototypes only for this runtime, the one deviation from its static-copy pattern, because a static copy would drag Python.h into each unit and make --pure impossible.

Call helpers are fixed-arity (__pp_py_call0..4, and keyword variants): a variadic call is the one C shape QBE and LLVM cannot emit uniformly. Calls with more than four positional arguments, and f(**d), are refused.

Conversion

Outward is implicit; inward is explicit and is the CPython builtin. A Str is a str and an Int64 is an int, so arguments convert outward with no ceremony. A handle could hold anything, so inward conversion is always explicit. It is written as the builtin that names it (int(obj), float(obj), str(obj), bool(obj)) and lowers to the exact C function that builtin calls (PyNumber_Long, PyNumber_Float, PyObject_Str, PyObject_IsTrue), so the compiled conversion runs the same code the interpreted one runs.

An annotation is not a conversion, in either direction. x: int = body["n"] is a diagnostic, since letting the annotation drive int(...) would silently coerce or abort at a line the source does not mention. x: object = 3 is the same rule with the arrow turned round: a declaration must not become an implicit heap allocation. The conversion belongs where the type claim is written.

Data operations

A handle supports subscripting, subscript stores, len, membership, iteration, attribute access, calls and keyword call sites, each lowered to the C-API entry point CPython's bytecode uses (PyObject_GetItem, PyObject_SetItem, PyObject_Length, PySequence_Contains, PyObject_GetIter/PyIter_Next), so each operation dispatches through the object's dunders and cannot drift. The choices this forecloses are the content. Iteration is the iterator protocol (a dict, a generator and an .items() view are iterable and none is indexable). Membership is PySequence_Contains (substring semantics on str, which a scan would answer wrongly). An operation yields another handle, equally opaque. Slices and tuple subscripts are refused, since both require CPython to receive a value (a slice, a tuple) that POST cannot build.

The exception check after each next is required. PyIter_Next returns NULL for exhaustion and failure; a raising generator read as an empty sequence is the silently-wrong outcome this compiler exists to prevent.

Keyword arguments at a call site build a CPython dict one entry at a time, in source order (f(a=g(), b=h()) calls g first) and hand it to PyObject_Call. The mapping is never a POST value; it is the argument convention a Python call already has.

The object annotation

A handle is spelled object, valid as a parameter, a return type, and a declared local, meaning the same thing in all three, so handles pass between compiled functions. Four arguments favour the spelling. It is a builtin, so the interpreted program needs no import. It is semantically true (any CPython value is a PyObject). Python's typing already reads object as "hold it, narrow before use", which is the explicit-conversion rule. And it leaves Any unclaimed for a future POST dynamic type, since a foreign opaque handle and a POST value of statically-unknown type are different questions that deserve different names.

The refusals follow from the property "opaque" and never name the type. object(...) is not a call or a cast. Array[object] has no element layout or ownership story. A POST aggregate cannot be returned as one (pointer-to-pointer is what a cast would silently launder). A kernel cannot take or return one (a ufunc loop cannot report errors). A handle cannot cross the stable C ABI: a void * in a C99 header would name a value meaningful only inside a CPython process with the GIL held, which a header cannot say. _-prefixed functions are never exported and hold handles freely. class Foo(object): is not a type position, and isinstance(x, object) is unaffected.

The null handle is the placeholder a -> object function returns while unwinding. It is safe by construction: every FFI helper is a no-op on NULL, so a placeholder that reaches an operation propagates as a second failure and can never be mistaken for data. It has no source spelling and no caller reads it.

Exports: compiled functions as Python callables

A POST function named in a Python call exports as a cached PyCFunction wrapper. The cache is a semantic requirement, since interpreted f is one function object and CPython can observe identity. The wrapper takes keywords with the POST signature's parameter names, because callers rely on it: Flask dispatches URL variables as keywords, and a positional-only wrapper answers 500 where the interpreter answers 200.

Callback arguments convert by CPython's argument convention (PyNumber_Index, PyUnicode_Check, PyFloat_AsDouble, PyObject_IsTrue), which differs from the value conversions above. str(x) written in source requests CPython's str(); a parameter annotated s: str is a claim about the caller, and coercing whatever arrived would silently differ from the interpreted function (greet(1) raises TypeError interpreted; coercion would return "Hi 1"). Errors inside a callback take the C-API convention (return NULL with the exception set) because that is what the interpreted function does. Private (_-prefixed) functions cannot be exported (C internal linkage), nor can one with a defaulted parameter (the wrapper would require what the interpreter defaults). A handle arriving as a callback parameter is increfed on the way in: it arrives borrowed from the argument tuple, but a compiled function can outlive the borrow.

Linking and the driver

--pure is a link-step property, decided over the IR: only a program whose IR touches the FFI compiles the FFI runtime, links libpython and uses the CPython-aware driver. The predicate reads the IR; a callback-only program imports nothing and still needs libpython, and in script mode an unused from python import counts, because CPython would import it too. Discovery is sysconfig plus python3-config --embed --ldflags, with the library directory and a matching rpath added by the compiler. Without the rpath the binary links and does not start.

The driver initialises CPython with the building interpreter baked in as program_name, so the binary sees the same environment (the virtualenv's site-packages included) with no PYTHONPATH. parse_argv is off (argv belongs to the POST program). Stdout is flushed before finalisation, since the POST runtime writes stdio, CPython writes sys.stdout, and finalisation flushes only the second. Script mode runs every from python import eagerly, in source order, so import-time side effects order as CPython orders them.

Handle lifetime

Refcounting v0: owned and never released, the safe end of the trade, because a borrowed reference outliving its owner crashes the process where a leak does not. Handles remain one of the named leak-at-exit heaps in 0024's model; releasing them properly needs the GIL discipline of 0019 and is a slice of its own.

Consequences

  • Heterogeneous data is representable; its representation is "a CPython object across a visible boundary." That is the standing answer to "why no Any": POST's value domain stays closed. The boundary shows where the explicit conversions are written.
  • A compiled binary serves real Flask routes (JSON bodies read, records built with keyword call sites, responses via flask.jsonify), byte-identical with the interpreted run.
  • The perimeter rule was bought with a defect: introducing a non-numeric type into a compiler whose promotion fell back permissively turned on a family of pointer-arithmetic miscompiles at once. The fix is structural and standing: promote answers None for unknown pairings, operator paths reject by the opaque property. Each new position for an opaque value must re-establish the perimeter.

Alternatives considered

  • A topy/frompy conversion vocabulary: rejected: the builtin is the conversion, needs no new names, and is differential-exact by construction.
  • PyObject (or any importable name) as the annotation: rejected: the annotation must mean something interpreted. An importable spelling costs an import that the object builtin does not.
  • Index-loop iteration and hand-rolled membership: rejected: cheaper to write and silently wrong on ordinary data (dicts, generators, substring in).
  • Inferring inward conversions from annotations: rejected: that is the silent deoptimization the language refuses, moved into the type system.