8000 Session is not fork-safe: both engines are silently corrupted by a fork() · Issue #93 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

Session is not fork-safe: both engines are silently corrupted by a fork() #93

Closed

Description

@Lillecarl

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.Finalize objects do run in an Ansible child. popen_fork._launch calls atexit._clear() (so plain atexit handlers are safe) but then registers util._exit_function, which runs multiprocessing finalizers before os._exit().

inproc.Session

  • NixThreadExecutor pools (inproc/_impl.py:1051,1070) — bounded pool for store work, dedicated thread per evaluator — do not survive fork(). The child awaits futures nothing will ever fulfil: deadlock, not corruption.
  • thread_initializer=nanopynix_expr._enter_evaluator_thread is GC_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_session and 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__ / Finalize become 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 ForkedSessionError from every public method.

Constraints worth knowing:

  • os.unregister_at_fork does not exist. One module-level handler over a registry — never one per Session, 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_fork misses a raw fork(2) via ctypes or a C extension forking itself. An os.getpid() comparison catches those. Its own blind spot is pid namespaces — not hypothetical here, given OverlayNamespace — 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

  1. Lillecarl commented on Aug 4, 2026

    @Lillecarl
    ContributorAuthor

    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: Finalize objects do NOT run in a multiprocessing child

    The original report said:

    multiprocessing.util.Finalize objects do run in the child even though popen_fork._launch calls atexit._clear().

    That is wrong. BaseProcess._bootstrap calls _after_fork(), which does util._finalizer_registry.clear(). Measured:

    parent finalizer_registry size: 1
      child pid 2161251 | finalizer_registry size: 0
    after mp child, marker exists: False
    

    So teardown in an Ansible worker child is not automatic. It happens only when code explicitly closes the session — which async with does, 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 uses multiprocessing, 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.

    Scenario Result
    child inherits a live rpc.Session and merely exits parent unharmed
    child closes the inherited session (fresh event loop, as anyio.run() in a forked plugin would give it) parent gets WorkerDiedError: Protocol error

    The 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_child handler 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 inproc runtime:

    Parent Result
    single-threaded ok, 31 ms
    multithreaded and allocating (as Ansible's is) ok, 52 ms — 60/60 runs, no failures, no hangs
    via multiprocessing.get_context("fork") ok, 31 ms
    after an rpc session was opened and closed ok, 33 ms
    4 concurrent children, own Nix each all ok, 21–50 ms

    "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 _InprocProcessGuard reset lands, since a child legitimately wants its own session.

  2. added
    source: nanopynix
    on Oct 19, 2026
  3. added theissue type on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: nanopynix

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0