Repository navigation
Description
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 xdoes not stop. Nix
bounds that case withmax-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
- An operation on an inproc evaluator accepts a deadline.
- A deadline that expires during a store operation, a fetch or a build raises
TimeoutErrorin the caller, and the evaluator thread becomes free again.
A test proves the thread is free, and not merely that the caller returned. - A real interrupt still raises
KeyboardInterrupt. A test proves that a
timeout and an interrupt are distinguishable. - The predicate composes with any
interruptCheckalready installed, and
restores it. A test covers a Nix operation that uses aThreadPool. - A test records what happens to the
EvalStateafter an interrupt, and the
documented behaviour matches it. - The documentation states that a pure evaluation is not interruptible, and
namesmax-call-depthas what bounds that case. - 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
checkInterruptcalls in
eval.cc, which is an upstream change. - RPC. The RPC engine recovers by killing its worker, and already has
rpc_timeout.
Activity
Lillecarl commentedon Jul 31, 2026
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.call raises
EvaluatorAbandonedErrorat once instead of queueing.Scope: both engines, in one change
NixThreadExecutoris shared, so the mechanism landed once. Only the triggerdiffers: 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._exitat teardown when abandoned work is still running, and a hostapplication does not, but that is not an API difference.
Three findings the work produced
1.
interruptCheckonly helps where Nix polls. A blocking wait insideNix is unreachable.
filetransfer.ccwaits on a condition variable andregisters a
createInterruptCallback, and those fire fromunix::triggerInterrupt()on the signal handler thread, which this processnever 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::doWorkassignsunix::interruptCheckonlyif (!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
&quitby 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 reachthe pool's stop marker and exit while Boehm still listed it. The next
collection then signalled a dead thread. Fixed:
shutdown()still queues thefinalizer behind the runaway operation and only drops the wait.
Signals delivery fails constantly— not a defect, but a real limit worthrecording. 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
EvaluatorAbandonedErroris in force theinstant 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:
CloseEvalon a poisoned workerexecutor raised, which left the worker's
EvalStateopen and made the owningstore unclosable. Closing an abandoned evaluator now always succeeds on both
engines, and the native resources leak with the thread that owns them.
Verification
nanopynix-tests-nix_2_34), which is what CI runs: 1872passed, 3 skipped
--nix-test-backends local,daemon: 112 passedcheck-lint,check-lint-strict,check-format,check-typesall buildStill 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.
Lillecarl commentedon Jul 31, 2026
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.Runnerinstalls a SIGINThandler that cancels the main task and re-raises
KeyboardInterrupt. The REPLcancelled 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.
WorkerClientis the only thing that may stop a worker, andcancellation still reaches the worker over the wire.
An abandoned evaluator killed the REPL.
EvaluatorAbandonedErroris anObjectMisuseError, and_run_repl_loopcatchesNixErrorandReplRunError.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:
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.35dev 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).
fix(tests): cancel inside the work, and prove that a cancel happened
feat(bindings): give Nix work an interrupt token and a composing scope
feat(core): let a cancel scope stop the Nix work
fix(tests): cancel inside the work, and prove that a cancel happened