8000 inproc: a hung Nix operation cannot be stopped; use Nix's per-thread interrupt hook · Issue #66 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

inproc: a hung Nix operation cannot be stopped; use Nix's per-thread interrupt hook #66

Closed

Description

@Lillecarl

TL;DR

An inproc operation that hangs cannot be stopped. anyio.fail_after cancels
the await, not the work, so the caller gets an exception and the evaluator
thread stays occupied for ever. Because an EvalState is confined to that one
thread, every later operation on that evaluator queues behind the hung one.

Nix has a per-thread interrupt hook that this project does not use. Install it
on the evaluator thread and a store operation, a fetch or a build becomes
interruptible. A pure evaluation does not, and this issue does not claim
otherwise.

The problem, measured

NixThreadExecutor._submit runs the work on a dedicated thread and awaits it:

future = self._pool.submit(func, *args)
return await asyncio.wrap_future(future, loop=loop)

concurrent.futures.Future.cancel() does nothing once the work starts. So a
cancel scope around this call unblocks the caller and abandons the thread. The
executor keeps the thread, the EvalState stays bound to it, and the evaluator
is unusable from that point.

inproc has no operation timeout at all today. The two timeouts that exist,
executor.drain(timeout=...) and capture_logs(wait_timeout=...), bound
teardown and log collection. Neither bounds a Nix call.

The RPC engine does recover, because it owns a process that it can kill. That
is process isolation working as designed. inproc has no such lever, and this
issue gives it the only one Nix offers.

The mechanism

src/libutil/unix/include/nix/util/signals-impl.hh:

extern std::atomic<bool> _isInterrupted;                   // process-global
extern thread_local std::function<bool()> interruptCheck;  // per-thread

static inline bool isInterrupted() {
    return _isInterrupted || (interruptCheck && interruptCheck());
}

interruptCheck is thread_local. Set it on the evaluator thread and only
that evaluator stops. The global flag is not used, so one evaluator's deadline
does not touch another. No watchdog thread is necessary: the predicate runs on
the Nix thread, and it reads a deadline that the submitting code sets.

Nix throws nix::Interrupted at the next checkInterrupt(). The bindings
already catch it, at nanopynix-bindings/src/nix_errors.cpp:161.

The API is the same on all three supported versions, so no #if is needed:

version interruptCheck checkInterrupt in libexpr in libstore
2.31 yes 5 34
2.34 yes 4 33
2.35 yes 4 33

What this can and cannot interrupt

library checkInterrupt call sites
libstore 33
libutil 32
libfetchers 9
libexpr 4

The four in libexpr are in print.cc, print-ambiguous.cc,
value-to-json.cc and value-to-xml.cc. They serialise a value. eval.cc
calls checkInterrupt nowhere.

So:

  • A hung fetc 8000 h, a hung store operation, a hung build, and a long
    value-to-JSON conversion stop.
  • A runaway evaluation such as let x = x + 1; in x does not stop. Nix
    bounds that case with max-call-depth, and not with an interrupt.

State this limit in the docstring of whatever setting this adds. A timeout that
silently fails to fire on the case a user most fears is worse than no timeout.

Three decisions this needs

1. A timeout must not look like Ctrl-C

nix_errors.cpp maps nix::Interrupted to KeyboardInterrupt, and the
comment says why: KeyboardInterrupt derives from BaseException, so
except Exception does not swallow it, and pynix's repl and the RPC worker
both expect that.

A deadline is not a user interrupt. If a timeout arrives as KeyboardInterrupt,
pynix's repl reads a slow fetch as the user pressing Ctrl-C. The interrupt
state must therefore carry a reason, and the binding must raise TimeoutError
for a deadline and keep KeyboardInterrupt for a real interrupt.

2. Do not overwrite an interruptCheck that Nix installs

src/libutil/thread-pool.cc assigns interruptCheck on its own worker
threads:

unix::interruptCheck = [&]() { return (bool) quit; };

If a Nix operation runs a ThreadPool on the calling thread, an assignment
would drop Nix's own predicate. Compose instead: keep the previous value and
call it, and restore it with an RAII guard when the operation finishes.

3. Decide whether an evaluator survives an interrupt

nix::Interrupted unwinds through Nix's C++ stack. Whether the EvalState is
usable afterwards is not known, and it decides the API:

  • If the evaluator survives, a timeout is an ordinary recoverable error.
  • If it does not, a timeout must close the evaluator, and the API must say so.

Answer this with a test before the API is designed, not after.

Acceptance criteria

  1. An operation on an inproc evaluator accepts a deadline.
  2. A deadline that expires during a store operation, a fetch or a build raises
    TimeoutError in the caller, and the evaluator thread becomes free again.
    A test proves the thread is free, and not merely that the caller returned.
  3. A real interrupt still raises KeyboardInterrupt. A test proves that a
    timeout and an interrupt are distinguishable.
  4. The predicate composes with any interruptCheck already installed, and
    restores it. A test covers a Nix operation that uses a ThreadPool.
  5. A test records what happens to the EvalState after an interrupt, and the
    documented behaviour matches it.
  6. The documentation states that a pure evaluation is not interruptible, and
    names max-call-depth as what bounds that case.
  7. The feature works on 2.31, 2.34 and 2.35 with no version gate.

Not in scope

  • A synchronous API. This issue is about the async engine, which has the
    same defect. Cancellation is not a property of the colour of the function.
  • Interrupting a pure evaluation. That needs checkInterrupt calls in
    eval.cc, which is an upstream change.
  • RPC. The RPC engine recovers by killing its worker, and already has
    rpc_timeout.

Activity

  1. Lillecarl commented on Jul 31, 2026

    @Lillecarl
    ContributorAuthor

    Implementation decisions, and what the work found

    The cancel model: signal, bounded wait, then poison

    A cancelled call sets a per-thread interrupt token and then waits up to
    DEFAULT_INTERRUPT_GRACE_SECONDS (2.0s) for the work to really stop.

    • Work that stops inside the grace leaves the evaluator healthy and usable.
    • Work that does not is abandoned. The executor is poisoned, and every later
      call raises EvaluatorAbandonedError at once instead of queueing.

    Scope: both engines, in one change

    NixThreadExecutor is shared, so the mechanism landed once. Only the trigger
    differs: a cancel scope for inproc, gRPC handler cancellation for the worker.

    RPC's stronger lever stays internal

    Both engines answer a cancellation identically: same class, same permanence.
    No public method kills or replaces a worker, because one worker hosts many
    evaluators and killing it would destroy every sibling. The worker does call
    os._exit at teardown when abandoned work is still running, and a host
    application does not, but that is not an API difference.

    Three findings the work produced

    1. interruptCheck only helps where Nix polls. A blocking wait inside
    Nix is unreachable. filetransfer.cc waits on a condition variable and
    registers a createInterruptCallback, and those fire from
    unix::triggerInterrupt() on the signal handler thread, which this process
    never starts. So the honest statement is narrower than this issue first
    assumed: a polling operation stops, a blocking one does not.

    2. Nix does not collide with the scope, but composing is still right.
    ThreadPool::doWork assigns unix::interruptCheck only if (!mainThread),
    so a pool never writes the slot of the thread that called process().
    Composing keeps a nested scope correct and survives that guard being dropped.
    Restoring on exit matters for its own reason: Nix's predicate captures &quit
    by reference, so a slot left holding it after the pool dies reads freed memory.

    3. An abandoned thread is a load, not a free resource. Two separate Boehm
    aborts were hit and diagnosed from core dumps while building this:

    • pthread_kill failed at suspend — a real defect in the first draft.
      Skipping the thread finalizer on a poisoned shutdown() let the thread reach
      the pool's stop marker and exit while Boehm still listed it. The next
      collection then signalled a dead thread. Fixed: shutdown() still queues the
      finalizer behind the runaway operation and only drops the wait.
    • Signals delivery fails constantly — not a defect, but a real limit worth
      recording. Boehm stops the world by signalling every registered thread and
      waits about 0.45s in total (150 retries, 3ms apart). An abandoned thread
      keeps allocating, and a machine that swaps under the extra heap can miss that
      budget. Sizing the grace is a real decision.

    Both are written up in docs/nanopynix/architecture-principles.md.

    One divergence found by the parity test, and kept

    The engines reach the abandoned state at different moments. On inproc the grace
    runs inside the cancelled caller, so EvaluatorAbandonedError is in force the
    instant the cancel returns. On rpc the cancel only closes the gRPC stream and
    the worker runs its own grace in its own process, so a client call made during
    that window is served rather than refused. Same class, just as permanent, one
    round trip later. Forced by process isolation, so recorded in the parity
    contract rather than fixed.

    The parity test also found a genuine bug: CloseEval on a poisoned worker
    executor raised, which left the worker's EvalState open and made the owning
    store unclosable. Closing an abandoned evaluator now always succeeds on both
    engines, and the native resources leak with the thread that owns them.

    Verification

    • full suite, dev shell: 1872 passed, 3 skipped
    • packaged runner (nanopynix-tests-nix_2_34), which is what CI runs: 1872
      passed, 3 skipped
    • cancellation tests on --nix-test-backends local,daemon: 112 passed
    • cancellation tests on Nix 2.31 and 2.35: 26 passed each, no version gate
    • check-lint, check-lint-strict, check-format, check-types all build

    Still to do by hand: start a slow fetch in the pynix REPL, press Ctrl-C, and
    confirm the prompt returns and the next expression evaluates.

  2. Lillecarl commented on Jul 31, 2026

    @Lillecarl
    ContributorAuthor

    The manual REPL check is now automated. tmux drives a real pynix REPL on a real
    tty, and it found two defects that the unit tests could not.

    A terminal Ctrl-C killed the rpc worker. A worker is a child of its client,
    so it shares the foreground process group. asyncio.Runner installs a SIGINT
    handler that cancels the main task and re-raises KeyboardInterrupt. The REPL
    cancelled the evaluation and returned to its prompt exactly as intended, and its
    worker died at the same moment, over a grpclib traceback. A worker now ignores
    SIGINT. WorkerClient is the only thing that may stop a worker, and
    cancellation still reaches the worker over the wire.

    An abandoned evaluator killed the REPL. EvaluatorAbandonedError is an
    ObjectMisuseError, and _run_repl_loop catches NixError and ReplRunError.
    The first expression after an uninterruptible Ctrl-C therefore ended pynix with
    a traceback. The loop now prints the error, says that the evaluator cannot serve
    another expression, and leaves with status 0.

    A test that uses a double finds neither one. The first needs a true process
    group, and the second needs the real exception class.

    Both cases now behave in the real REPL:

    pynix> builtins.genList (x: x) 40000000
    ^C
    pynix> 1 + 1
    2
    pynix> builtins.foldl' (a: b: a + b) 0 (builtins.genList (x: x) 40000000)
    ^C
    pynix> a Nix operation did not answer an interrupt within 2.0s; abandoning the
    Nix thread. It keeps its 62914560-byte stack until the process ends.
    pynix> 1 + 1
    error: a Nix operation did not answer an interrupt within 2.0s
    this evaluator cannot be used again; start pynix again
    

    Verification, all green: the full suite (1873 passed); the cancellation tests
    with --nix-test-backends local,daemon; the same tests under the 2.31 and 2.35
    dev shells (99 passed each), which confirms that no version gate is needed; the
    four sandboxed check gates; and the packaged runner that CI executes (1834
    passed).

  3. added
    source: nanopynix
    on Oct 19, 2026
  4. 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