interpreter_pool runs pure functions in Python 3.14's subinterpreters, each with its own GIL: parallel CPU work on the GIL build without separate processes.
concurrent.interpreters is new in Python 3.14: on 3.13, building the layer dies with
InterpretersUnavailableError.
On the GIL build, Python code in fx.blocking takes turns with every other thread. Python 3.14's
concurrent.interpreters runs code in subinterpreters: interpreters in the same process, each with
its own GIL and its own modules, so pure-Python work in them runs on several cores at once without
the start-up, memory and pipes of a ProcessWorker. pyfect.interpreter_pool runs functions in
them from effects.
Provide a pool with interpreter_pool.layer(size=...) (one interpreter per CPU by default; each
starts on first need and closes when the layer is released) and call a function with
interpreter_pool.call(f, *args). A raised exception is a defect; try_call fails with an
UnknownError around it instead, or with what catch= makes of it, as fx.try_blocking does.
"""Pure functions a subinterpreter imports and runs: this module imports nothing
heavy, so starting it there is quick."""
def checksum(data: bytes) -> int:
# Stands in for CPU-heavy pure-Python work: parsing, scoring, a model.
total = 0
for byte in data:
total = (total * 31 + byte) % 1_000_000_007
return total
def parse_port(text: str) -> int:
port = int(text)
if not 0 < port < 65536:
raise ValueError(f"port out of range: {port}")
return portimport sys
import pytest
from checksums import checksum, parse_port
import pyfect as fx
from pyfect import interpreter_pool
from pyfect.errors import UnknownError
pytestmark = pytest.mark.skipif(
sys.version_info < (3, 14), reason="needs Python 3.14's concurrent.interpreters"
)
def test_checksums_run_in_subinterpreters() -> None:
blobs = [bytes([i]) * 100_000 for i in range(4)]
program = fx.all(*[interpreter_pool.call(checksum, blob) for blob in blobs], concurrency=4)
sums = fx.run_blocking(program.pipe(fx.provide(interpreter_pool.layer(size=4))))
assert list(sums) == [checksum(blob) for blob in blobs]
def test_a_raised_exception_comes_back() -> None:
parsed = interpreter_pool.try_call(parse_port, "70000").pipe(
fx.catch_tag(UnknownError, lambda e: fx.succeed(str(e.cause)))
)
message = fx.run_blocking(parsed.pipe(fx.provide(interpreter_pool.layer(size=1))))
assert message == "port out of range: 70000"What crosses#
A subinterpreter shares no objects with yours. The function, its arguments, its result and a raised exception are copied across:
- A function that reads no globals and closes over nothing, a lambda included, crosses as its code, wherever it is defined. It may import what it needs inside its body.
- Any other function crosses by reference: the subinterpreter imports its module, the first time
it runs something from it, and looks it up by name. Each subinterpreter starts with your
program's
sys.path. Keep these functions in a module that imports little: importingpyfectthere takes up to a second. A lambda or a nested function that reads globals or captured variables has no name to look up, so the call dies withNotShareableError. - Arguments and results must pickle. Objects the function changes are copies, so return what you need instead.
- An exception comes back as itself when it pickles, with the
concurrent.interpreters.ExecutionFailedthat describes it (traceback included) as its__cause__. One that doesn't pickle comes back as thatExecutionFailed.
import sys
from typing import Never
import pytest
import pyfect as fx
from pyfect import interpreter_pool
from pyfect.cause import Die
from pyfect.exit import Failure
pytestmark = pytest.mark.skipif(
sys.version_info < (3, 14), reason="needs Python 3.14's concurrent.interpreters"
)
RATE = 3
def run[A](eff: fx.Effect[A, Never, interpreter_pool.InterpreterPool]) -> A:
return fx.run_blocking(eff.pipe(fx.provide(interpreter_pool.layer(size=1))))
def word_count(text: str) -> int:
# Reads no globals: its code is copied across, wherever it is defined.
import re
return len(re.findall(r"\w+", text))
def test_a_function_reading_no_globals_crosses() -> None:
assert run(interpreter_pool.call(word_count, "one two three")) == 3
def test_a_lambda_reading_no_globals_crosses() -> None:
assert run(interpreter_pool.call(lambda x: x * 2, 21)) == 42
def test_a_lambda_reading_a_global_does_not() -> None:
priced = interpreter_pool.call(lambda x: x * RATE, 14)
ex = fx.run_blocking_exit(priced.pipe(fx.provide(interpreter_pool.layer(size=1))))
assert isinstance(ex, Failure)
[reason] = ex.cause.reasons
assert isinstance(reason, Die)
assert type(reason.defect).__name__ == "NotShareableError"A function that reads globals of the script you ran (python app.py, so its module is
__main__) is found by running the whole script again inside the subinterpreter. With its
top-level code under if __name__ == "__main__":, that re-run only defines the functions, and
the call works. Without the guard, the re-run reaches the script's own fx.run_blocking (or any
other run), which dies there at once; the call then dies with
interpreter_pool.MainScriptRerunError, which says to add the guard or move the function into an
importable module. Everything the script does before that run happens a second time, in the
subinterpreter: a file it writes is written twice, a message it prints is printed twice. That
re-run is CPython's, so the guard is the fix.
Interruption#
Python can't stop a call that has started. Interrupting the fiber abandons it, as fx.blocking
does: a call still waiting for a free interpreter is withdrawn and never runs, while a running
one goes on until it returns and its result is dropped. Releasing the layer fails calls still
waiting with InterpreterPoolClosedError and returns once every interpreter has closed, so it
waits for an abandoned call to return: no interpreter outlives its pool, and a call that never
returns keeps the release waiting.
Memory on the free-threaded build#
On CPython 3.14t, creating many short-lived interpreters raises peak memory to a few GB, in CPython itself rather than in pyfect. Creating 1,000 interpreters, calling each one once and closing it, with no pyfect involved, took the process to 2.9 GB peak RSS (3.14.7t on macOS), where the GIL build stayed at 37 MB. The same churn through 250 short-lived pools reached 3.8 GB. Keep one long-lived pool, provided once near the top of the program, rather than a layer per task.
What it measured#
benchmarks/interpreter_pool.py
runs 8 calls of the same pure-Python function (about 80 ms alone) with concurrency=8, on an
18-core Apple M-series machine other jobs were also using. The rate is 8 times one call's time
over the fan-out's:
| 3.14 | 3.14t | |
|---|---|---|
inline (fx.sync) | 1.01x | 1.02x |
fx.blocking | 1.02x | 5.60x |
interpreter_pool.call | 7.05x | 6.41x |
The round trip of a call that does nothing, p50 / p95, unloaded:
| 3.14 | 3.14t | |
|---|---|---|
fx.blocking | 0.024 / 0.032 ms | 0.017 / 0.031 ms |
interpreter_pool.call | 0.036 / 0.049 ms | 0.354 / 0.391 ms |
So on the GIL build a pool of subinterpreters is the way to spread pure-Python work over cores
inside one process. On free-threaded 3.14t, fx.blocking does it too, with no copying and a
tenth of the round trip, so the pool only pays there for isolation. With a pure-Python loop
spinning on a thread per core, either round trip waits on the OS for a core (3.14t, p95 21 ms
for the pool, 29 ms for fx.blocking), and on the GIL build behind every busy thread for the
GIL, hundreds of milliseconds.