Repository navigation
Description
Both rpc.Session and inproc.Session are silently unsafe to hold across a fork(). Neither notices, and each fails in a way that points somewhere other than the fork.
I hit this building ansinix, an Ansible collection that evaluates Nix and ships closures to managed hosts. Ansible's execution model makes this unavoidable rather than exotic — details below, because they explain why "just don't fork" isn't available to a library consumer.
Why a consumer can't simply avoid it
ansible-core forks once per (host, task) pair, using an explicitly pinned fork start method:
# ansible/utils/multiprocessing.py — identical in 2.21.1 and devel @ 2d8c74aa7a
context = multiprocessing.get_context('fork')WorkerProcess(multiprocessing_context.Process) is constructed in exactly one place (plugins/strategy/__init__.py:396) and started immediately. There is no non-forking execution path — forks: 1 still forks, it just gives the pool one slot. Workers are never reused, so a 10-task play across 200 hosts is ~2000 forks. The forking parent is also multithreaded (a results thread), and Ansible carries a # FUTURE: this lock can be removed once a more generalized pre-fork thread pause is in place around the start() call.
Ansible's own comment on the situation, in WorkerProcess._hard_exit:
There is no safe exception to return to higher level code that does not risk an innocent try/except finding itself executing in the wrong process. All code executing above
WorkerProcess.run()on the stack conceptually belongs to another program.
So any nanopynix session that happens to be open when a plugin returns gets inherited by thousands of children.
What goes wrong
rpc.Session
- The transport is a
multiprocessing_pipe_pair(grpclib-transports), so parent and child hold the same pipe fds and both write to one serial worker. Interleaved requests, protocol desync. - The child inherits the worker's pid. A teardown path running there can terminate the parent's worker — silent, and it looks like a random worker death.
multiprocessing.util.Finalizeobjects do run in an Ansible child.popen_fork._launchcallsatexit._clear()(so plainatexithandlers are safe) but then registersutil._exit_function, which runs multiprocessing finalizers beforeos._exit().
inproc.Session
NixThreadExecutorpools (inproc/_impl.py:1051,1070) — bounded pool for store work, dedicated thread per evaluator — do not survivefork(). The child awaits futures nothing will ever fulfil: deadlock, not corruption.thread_initializer=nanopynix_expr._enter_evaluator_threadisGC_register_my_thread; Boehm's thread table in the child lists threads that no longer exist._InprocProcessGuard(inproc/_impl.py:118-155) is a module global, so a child inherits_active_sessionand reports "only one nanopynix.inproc.Session may be open per process" about a session in a different process. It also inherits_initialization_signature, so a fresh child believes Nix is already initialized with the parent's settings.
Suggested remediation
A module-level os.register_at_fork(after_in_child=...) over a WeakSet registry. I verified the hook fires for both paths that matter:
in mp child: hook fired = True # multiprocessing 'fork' context, i.e. Ansible
in os.fork child: hook fired = True
parent: unaffected
In the child the handler should neuter teardown, not just flag, because the dangerous paths run without anyone calling a guarded method:
- mark the session forked;
- drop the worker pid, so nothing can signal the parent's worker;
- poison the channel so
close()/__aexit__/Finalizebecome no-ops; - reset
_process_guard(_active_session = None), so a child that legitimately wants its own inproc session can have one; - then raise a named
ForkedSessionErrorfrom every public method.
Constraints worth knowing:
os.unregister_at_forkdoes not exist. One module-level handler over a registry — never one perSession, or you leak a handler per session for the process's lifetime.- The handler runs in the child with one surviving thread; locks held by threads that no longer exist stay held forever. Set flags only — no logging, no I/O, no lock acquisition.
os.register_at_forkmisses a rawfork(2)viactypesor a C extension forking itself. Anos.getpid()comparison catches those. Its own blind spot is pid namespaces — not hypothetical here, givenOverlayNamespace— so the two mechanisms are complementary rather than redundant.
Workaround in ansinix meanwhile
A PidGuard that refuses to hand out a session whose creating pid differs from os.getpid(), plus a role-based backend split: rpc.Session only in Ansible's unforked main process (it keeps init_libstore/init_libexpr in the worker subprocess, so the forking process stays Nix-free), and inproc.Session only inside an already-forked task worker. That works, but it is a rule enforced by convention on our side rather than a guarantee on yours — hence this issue.
Happy to send a PR if the approach looks right.
Activity
Lillecarl commentedon Aug 4, 2026
Measured this properly instead of leaving it argued. One correction to the original report, and one confirmation.
Scenarios and harness:
tests/smoke/in ansinix — each runs in its own subprocess under a timeout, because the failure being tested for is deadlock. Environment: nanopynix @ current checkout, CPython 3.14.6, Nix 2.34-era stable.Correction:
Finalizeobjects do NOT run in a multiprocessing childThe original report said:
That is wrong.
BaseProcess._bootstrapcalls_after_fork(), which doesutil._finalizer_registry.clear(). Measured:So teardown in an Ansible worker child is not automatic. It happens only when code explicitly closes the session — which
async withdoes, so the hazard is still reachable, just not ambient. Sorry for the noise; the remediation is unaffected but the risk profile is narrower than I described.(Note the asymmetry: a bare
os.fork()child does not get_after_fork(), so there the parent's finalizers do survive. Ansible usesmultiprocessing, so the above is what applies to it.)Confirmed: a child's teardown kills the parent's worker
This was the serious claim and it reproduces exactly.
rpc.Sessionand merely exitsanyio.run()in a forked plugin would give it)WorkerDiedError: Protocol errorThe parent's session answered
store_dir()correctly immediately before the fork, and is dead immediately after the child's teardown.The useful refinement: inheritance alone is harmless — teardown is the hazard. So an
after_in_childhandler that only sets a "raise on use" flag is not sufficient; it has to neuter the teardown path itself (drop the worker pid, make close/__aexit__a no-op in the child), which is what the original report suggested and this now justifies concretely.Also measured: initialising Nix fresh in a forked child is fine
Relevant because it is the workaround ansinix relies on, and because it bounds how much the fix has to cover. Parent holds no Nix, forks, child builds its own
inprocruntime:multiprocessing.get_context("fork")"ok" = session open + store call to nix-daemon + evaluator call (
1 + 1→2), so Boehm GC on a dedicated Nix thread is exercised, not just libstore.Worth knowing for the fix's scope: a fresh runtime in a forked child is not the problem even under a multithreaded parent, despite CPython's
DeprecationWarning: This process is multi-threaded, use of fork() may lead to deadlocks in the child. The problem is specifically the inherited one. A guard that invalidates inherited sessions without blocking fresh ones in a child would cover the real hazard without breaking that workaround — worth keeping in mind if the_InprocProcessGuardreset lands, since a child legitimately wants its own session.fix(tests): keep a fork test out of a lane, and name the new class on…
fix(nanopynix): give the evaluator a collector, and fork a contract p…
fix(nanopynix): refuse a session that crossed a fork, on both engines
fix(tests): keep a fork test out of a lane, and name the new class on…
fix(nanopynix): give the evaluator a collector, and fork a contract p…