Cancellation
Stopping in-flight work is one delivery mechanism — a cooperative,
cause-bearing scope tree that asks the evaluator to unwind at its next poll
point — backed by an escalation ladder that forces an exit when a user
insists. A signal handler holds neither a Shell nor a scope, so it raises
one of two process-lifetime ambient causes, and no scope folds either: the
host forwards it into scope cancellation, directly for exarch’s fleet or
as Control for a ral engine, which strikes the tree like any other cancel
(signals-are-causes). The host is the
identity front-end — REPL, batch, exarch — or, for a wire engine, the engine
process itself. Both live in core/src/process/signal.rs (see
io-process); the gestures that drive them differ per
host.
The two pieces answer different questions:
- The scope tree (
Scope,ScopeNode) answers “which subtree should unwind, and why?” — a structured-concurrency primitive that names a cause and reaches exactly the workers owned under the cancelled scope. It is the only thingShell::pollreads, and what it raises is a stop: an escape naming its owner, which notrycatches (delimiters-are-handlers-for-poll). - The ladder (
ESCALATION: AtomicU8) answers “is the user escalating toward kill?” — the third delivery forces_exitwith the signal’s cause’s status (SIGINT 130, SIGTERM and SIGHUP 143). It is a blunt, host-agnostic floor for a process whose cooperative delivery is wedged, never a delivery mechanism itself.
The escalation ladder
The Disposition::Shutdown handler fetch_adds the ladder on every
delivered signal; the third hit calls libc::_exit with the code of the
cause the signal asks (asked(sig).cause().failure_code()) — bypassing atexit so a
wedged process always dies. Nothing else reads it for control flow: clear()
resets it at acknowledgment boundaries (a fresh prompt, a run compile, a
session reboot), and escalation_pending() exposes it for observability only.
Being process-global and cleared by every run compile, it is nothing a test
can assert on beside a test that runs source.
Windows’ console handler has the same shape: the first two console events
raise the interrupt, the third ExitProcesses with its status. Neither
ladder signals a process: a child hears ral’s teardown only from the scope
that owns it, so nothing fans out around the tree.
The force-exit floor is reachable only in non-interactive paths. The ral
batch launcher gives SIGINT Disposition::Shutdown (batch.rs,
install_handlers); the interactive REPL gives it the non-escalating
Disposition::Interrupt (below; on Windows, install_interrupt_handler),
which never touches the ladder. So repeated Ctrl-C at an interactive prompt is cooperative, never a
hard kill — the escalation belongs to batch scripts and to external
SIGTERM/SIGHUP.
This is the esc-non-escalating-interrupt discipline taken to its end state: the user-facing interrupt writes a cause, and only a real delivered signal walks the ladder.
The scope tree and its cause lattice
A scope node is { flag, cancelled_at, parent, shield } in a tree of
Arc-linked nodes. Its cancellation is a join:
j(s) = ⨆ over chain(s) of flag(n)
-
cancel(cause)setscancelled_at(once) and thenfetch_maxes the flag — cancellation is one-way and monotone: a later, weaker cause can never mask a stronger one already in force. The instant is written first, by the same writer in the same act, so a reader that sees the flag sees it. -
One private
resolvefolds the chain root-first;in_force,cause,is_cancelledandpollare its readers, and every part it reads is private tocancel.rs. It mutates nothing. No mutex, no allocation beyond the chain walk. -
The name.
in_forcereturns oneCancellation: the join andν, the outermost node whose own flag attains it (it words itself byCancelCause::message, so apollis anErras it stands) — a declared tie-break, not a record of who struck first. AScopeId(pointer identity) is that name; a stop carries it for its owner. A cause the collector writes on a stage that an ancestor already carries therefore renames nothing. -
Evaluator minting points, each a frame or a base: the session root (
DurableRoot::new); the session anchor (the root’s child, minted once byShell::constructand shared by an aside); a worker’s node, minted under its shell’s cradle (Cradle) — the session root in a run outside any gather, else the gather’s entry scope: the parent worker’s own node inside a worker, the current scope when agatheropens; a host’s dispatch scope (run_cancel_handle, the anchor’s child); a run’s node (dispatch, the base of a run); a stage’s node (launch_thread_stage, a child of the current scope, so a pipeline inside acquisition or release is masked with it); a guard’s shields (Frame::Acquire,Frame::Cleanup,shielded(grace)). -
One writer per node. The root by SIGTERM/SIGHUP/Ctrl-
\; the dispatch scope by the host’s interrupt or enclosing exarch exchange; a run’s node by its wall and by the key its terminal tenant heard; a worker’s bycancel, araceloss, its parent’s gather’s halt rule (Brood), the session wipe; a stage’s by its collector alone, with the cause of whatever teardown it runs (ReaderGonefor a reader that left,Abortedfor a panic,Cancelledfor a sibling’sexit,Terminatedfor the anchor’s death or the collector’s own drop, the cause it is tearing down for otherwise); a shield by nobody. -
The cause is an escalation order,
CancelCause:cause value meaning who raises it ReaderGone1 a pipeline stage’s reader has ended the pipeline collector Interrupted2 user asked the foreground to stop Ctrl-C / Esc / batch SIGINT Cancelled3 a targeted worker teardown cancel <handle>,raceloser, a gather’s halt ruleTimedOut4 a wall-clock deadline expired process::deadlineTerminated5 the process was asked to shut down SIGTERM / SIGHUP; also a pipeline teardown of unobserved stages Aborted6 the session root is being reaped Ctrl- \
Scope::poll returns domain data: Result<(), Cancellation>, carrying the
cause and its owner. The process module knows no runtime control flow.
From<Cancellation> for Break (shell/runtime/flow.rs) preserves both as
Break::stopped(cause, Some(owner)); Shell::poll uses that conversion, so no
try can catch the stop. Its message is CancelCause::message, the one
vocabulary every poll point shares. Non-runtime readers may report the same
cause without constructing a shell escape.
Three types name the capabilities
The tree’s capabilities are spelled in the type system, not left to
discipline (unify-turn-evaluation):
Scope reads (poll, cause, child, shielded) and has no write;
ScopeNode writes (cancel) and derefs to its view.
DurableRoot(shell.session.root) is minted once perShell; exarch also holds one per fleet. It never yields its own node, so every node descends from a durable root and none is installed as a home. A loose worker born in a run —spawn,watch— hangs under it, so a foreground cancel never reaches it (concurrency-detached-vs-structured).- The session anchor is the one child of the root minted at construction, beside a run’s own extent; nothing writes it. A run’s frame nests under the anchor, so cancelling it never reaches a session worker, while cancelling the root reaches both.
- A gather is a scope over its births. A shell’s
LocalState::cradlesays where a birth hangs and who settles it: a run’s is loose under the root and answers for nothing; inside a gather — a worker’s body, or agather { … }(Frame::Gather, which swaps the cradle for its body’s extent) — it is the gather’s entry scope and itsBrood, owned by a uniqueBroodGuardthat holds the handles of everyspawnorwatchborn inside it; a stage shares its parent’s. When a gather begins exiting, it closes membership first (BroodGuard::close), so any late birth from a pipeline stage thread still unwinding against that cradle is immediately cancelled and rejected before it can start. One exit rule,exit_brood, settles the gather for both: on return it closes membership and claims and awaits each unclaimed child in birth order, the first failure being the gather’s; on a halt (BroodGuard::end) it closes membership and claims and cancels every such child; on an unwinding panic or frame drop (BroodGuard::stop, run by the guard’s ownDrop) it closes membership and cancels every remaining child without waiting. On every normal or halting exit it then waits, up to one shared cleanup grace and without polling, for every child accepted into the gather to reach a terminal state (ReadyorConsumed) (BroodGuard::drain), including children cancelled earlier bycancel $hinside the body (Stopping), since its own scope may be the one cancelled. Claiming is one transition under the handle’s lock, so a child claimed elsewhere first is skipped, and the join and that claimer never both replay it.racedrains its losers — and any argument already inStopping— within one shared grace by the same claim-and-stop. Socancel $hreaches everything$hstarted, and nothing a gather started outlives it by more than the grace (a-worker-ends-with-its-children). - The tree is the runs’ dynamic extent.
Shell::dispatchnests each entry under the frame the run door displaces, not beside it under the root, so a nested run observes what encloses it — its outer run’s interrupt, and its outer run’s wall elapsing (cancel-is-a-join). A pipeline mints one node per thread stage, under the current scope, which its collector alone writes;CollectState::dropwritesTerminatedon every live thread stage in one sweep, then kills whatever it still holds unobserved: the owned pgid, or each live external by pid (see pipeline-execution).
The ambient causes
A signal handler must not lock and cannot hold a ScopeNode by value, so it
raises a cause on a process-lifetime static, and a host thread hears it off
signal context. The two are different kinds of proposition.
- Shutdown is absolute.
request_root_cancel(cause)is onefetch_maxonREQUESTED_ROOT. Once raised it holds for every listener forever, so a SIGTERM delivered before a host listens still reaches it. - An interrupt is temporal.
request_interrupt()ticksINTERRUPTS; a listener hears only the interrupts raised after it registered, having been aimed at the run in flight then. - No scope folds either.
process::forward_ambienthands a host thread each cause as it lands (Ambient::Interrupt,Ambient::Root(cause), aRootCause), the handlers staying async-signal-safe and the reaper’s wake running the scan.RootCauseis closed,Cancelled | Terminated | Aborted, each encoded as itsCancelCause, soREQUESTED_ROOT’sfetch_maxkeeps the strongest.ControlSender::hear, also used byforward_signals, maps a root cause toControl::End(cause), which cancels the durable root with it, and an interrupt toControl::Strike(id, Interrupted), naming the dispatch its front-end has in flight. The REPL and batch hold one for the session; exarch’ssignals::faceinstead interrupts root exchanges or cancels the fleet root, letting active dispatchers observe their scopes. A wire engine hears only its own process’s shutdown, since an interrupt is aimed by the front-end that sent the dispatch. So a process hosting many engines — exarch, a test binary — never has one signal reach them all. - A dispatch is born at an instant. Forwarding lags the key by two thread
hops, so the dispatch in flight when an interrupt arrives need not be the
one in flight when it was struck: a Ctrl-C at an idle minimal prompt, where
the canonical tty raises a real SIGINT, would land on the next line.
dispatch_to_reportaims its front-end’sControlSenderat each dispatch it sends (aim), samplinginterrupt_epochunder the lockhearreads it by, andhearsendsStrike(id, Interrupted)only if the epoch has moved since. This is the birth instant the move toControlhad dropped, kept now per dispatch at the front-end rather than per frame. A key-driveninterrupt()names whatever is in flight now. The engine strikes only the id named and foretells one not yet arrived, as it does aCancel, so a lateInterruptfinds a stale id and strikes nothing. - An idle Unix REPL is woken after its root is cancelled. Its ambient
forwarder calls
hearbeforeShutdown::end: both readers are interrupted with thread-directed SIGINT until their exclusive registration ends. The minimal reader leaves stdin’s shared flags untouched and checks shutdown afterEINTR, which no ral disposition restarts (below). A user interrupt instead changes the logical prompt’s epoch: the reader returnsInterruptedand the frontend discards primary or continuation input immediately. This admits a fresh prompt without ending the session or consuming its root. Repeated delivery covers cancellation just before a blocking syscall or before rustyline installs its handler. A new read refuses a standing shutdown. The loop checks the root again after input returns, preserving its cause’s status and the ordinary history, worker, and terminal cleanup (frontend). - Sharing, not shadowing. A nested run nests under the frame the interrupt strikes, so a Ctrl-C mid-nest unwinds the whole nest, as a POSIX shell’s does.
- A loose worker in a run hears the root; a worker inside a worker hears
its parent; a call child hears the call.
Terminatedreaches every one; an interrupt or a wall, striking a run’s frame, reaches the run’s call children and no session worker. - A child session (
Shell::marshalandShell::child_of) does not independently subscribe to the host process’s interrupts. Exarch supplies its exchange scope to each dispatch: identity parents beneath it; wire dispatchers translate its cause to an addressedControl. Engine drop ends the session and its loose workers. - An aside is inside the session. A second
Shellthe engine runs beside its session — a hook whose registered policy saysaside, as the REPL’s buffer-change hooks do while readline runs — shares the session’sDurableRoot(Shell::join_session), so acancel_handlecancel reaches it. It shares the session’s anchor too, so its frames are siblings of the struck run’s, off its chain: it can neither absorb an interrupt that struck the run it was called from nor keep it from that run.
This is the seam the unify-turn-evaluation ADR calls “cancel translation”: the semantic collapse is onto the scope tree, never into the signal handler.
Where cancellation is observed
A cancel is a request: it flips a flag, and nothing stops until a reader samples its chain. There are two kinds of reading, and nothing is ever delivered, so nothing can be lost.
Step boundaries. Shell::poll reads the current scope and raises the stop
in force, at:
- the machine’s step arms (
shell/evaluator/machine.rs) — the β-step,Bind,Seq,App,Rec, guard entry and the exec step each poll, so any loop ofralcalls is preemptible (the original hot-path-cancellation insight); a?chain’s advance from one arm to the next is nestedtryapplying a handler thunk, so it polls at the same β-step; - the iterating builtins (
shell/builtins/collections.rs,shell/builtins/concurrency.rs) —map/filter/each/rangeand the worker-join sweep poll between elements; - pipeline launch (
shell/exec/pipeline.rs,shell/exec/pipeline/launch.rs) — before and between stage spawns; - a base’s closing poll (
final_poll), the first half of its return clause: a run, a worker and a stage read their node once more after the body settled, so a stop that landed after the last poll is not lost. The join supersedes the body’s ending unless that outranks it in the one order of endings (Break::rank, the pipeline fold’s), or is the join itself, located; anexithas already left. So a reader-gone join, which a collector above consumes, supersedes only a value: a stage whose cleanup halted keeps the halt as its verdict. The run’s wall is disarmed first, and a firing already claimed is waited for on its ownfiredflag, so nothing fires after this poll.
Settlement is not a new cancellation boundary. Machine state is a
computation closure or Err(Break) only. settle passes a produced value
through frames immediately; resume and unwind retain their existing poll
and scope-restoration sites. In particular the successful acquiring guard
restores scope and installs release before its body’s β-poll
(runtime-values-are-value-closures).
One base frame. Shell::base(home, body) -> End is every base: the body
under catch_unwind, the closing poll on home, and an unlocated failure or
stop claimed for the last call site, so a stop that passes a worker keeps its
caret as an error does. A thread’s ending then leaves its shell
(End::leaving, run by the worker’s and the stage’s thread, not the run’s,
whose report is read against the session’s own registry); the worker adds only
its switch (convert_own_stop, on the End). A run’s base-caught panic and
one caught outside it fold to one report, the checkpoint restored and no ready
boundary held. A thread that never reported (its permit dropped unfinished,
its SettleOnDrop dropped armed, a stage the fold finds unfiled) is
End::unreported, a panic with one wording, which a collector re-raises as it
does a panicked stage. The one thread-spawn primitive words a refused thread
once (could not start a worker thread, … a pipeline stage thread).
Sliced waits. Every blocked operation of ral’s own is a sequence of (read
the scope; wait at most POLL_SLICE, 10 ms), the read first so an
always-ready stream still polls once per chunk: a pipe write
(Sink::write_under) and read (read_interruptible), a child’s wait (the
collector’s recv, every external’s one waiter) and its pumps’ drain
(Drains::join_under), the enquiry park, and the
await/race/first-settled sweep (first_ready, which polls the caller’s
scope at the start of the sweep before inspecting any handle, so a pending
cancellation is never lost to an already-ready worker). The slice is the sampling period, not an end-to-end bound: the
latency to a stop is the slice plus the step in progress plus the scheduler.
Teardown waits read no scope, since the waiter’s own may be what was
cancelled: cancel::wait_ended(deadline, ended) re-reads its witness each
POLL_SLICE. Two witnesses, both needed. A brood’s drain, its halt
(BroodGuard::end: stop, then drain) and race’s losers (stop_and_drain) wait on
published handles (Ready or Consumed): what a gather owes is its
children’s endings in hand. The registry’s cancel_all, the session’s end,
waits on live-thread tickets: one per thread spawn_thread starts, worker
and stage alike, dropped only after the thread’s done flush and its shell’s
drop, so a stage thread (which has no handle) and a worker’s tail after its
publish are covered; a ticket outlives its handle’s publish, so the tickets
cover the handles too.
There is no watch table and no wake. Windows pipes cannot be waited on with a
timeout, so there a blocked thread stage or pump is interrupted
(CancelSynchronousIo) instead, and the aborted call re-reads its scope. An
aborted read took nothing and is retried; an aborted write may have delivered
a prefix it cannot report, so it is never retried: under the scope’s cause it
is that stop, under a shield an error naming the unknown delivery
(delimiters-are-handlers-for-poll).
A computation that never reaches either (a tight Rust loop inside one
builtin, a host wait outside the sliced rule: a stopped tty, an inherited
terminal stdin, ask, a file read) is not interruptible by the scope path —
the contract is cooperative.
The two cells
The owner’s node is the base of a machine’s tree — a run’s, a worker’s, a
stage’s — and is run-invariant, so it lives on Mooring::home, a ScopeNode. It is what
writes aim at: the key a terminal tenant heard, a stage’s group membership,
and a cancel. The current scope is a descendant swapped by
frames; it lives on Shell::scope, a Scope, which has no write, and is what reads consult: poll, every
sliced wait, a child’s attribution, the collector’s loop. At a base the two
coincide; inside acquisition or release the scope is a shield under the node. A write never
aims at the current scope. A shield is minted as a Scope alone, so no
ScopeNode of it exists and nothing can write it.
A collector consumes a stop iff it names one of its stages’ nodes
(pipeline-execution). A worker consumes every Cancelled or TimedOut stop whose owner is a
node of the session other than its root — its own, an ancestor worker’s, the
call it is a child of — into the handle’s Reason::Cancelled or
Reason::TimedOut error, preserving Stop.at, so a cancel
made inside the session is the awaiter’s failure, never a foreign stop that
ends its run (convert_own_stop). The root’s causes (Terminated,
Aborted), Interrupted and an unnamed stop pass every base and reach the
top uninterpreted as End::Stopped(Stop { cause, owner, at }); the wire’s
Ending::Stopped carries only the cause
(await-is-the-block-run-here).
The shield
A guard shields acquisition and release within one budget from the
strike. Both use Shell::shield(mooring.cleanup_grace): the current scope
becomes scope.shielded(grace) for that phase’s extent. Frame::Acquire and
Frame::Cleanup restore it on return, halt and abandon, as Frame::Capture
restores io.stdout.
The shield covers owned work, not every birth inside it. Pipeline stages
hang under the current scope; external children and nested machines read it.
Workers hang under cradle.under, their owner’s scope: an enclosing gather,
a worker’s body or the session is not moved under a shield merely because a
worker is spawned during acquisition or release. A gather opened inside
either phase captures the shield as its cradle and owns masked children.
Delegate acquisition through that owner:
guard { gather { let h = spawn { … }; await $h } } { |r| … } { |r _| … }.
Awaiting an outside owner’s worker can halt acquisition on that worker’s stop
and run no release; the awaiter’s mask does not mask the worker.
Entry polls before acquisition, so a pending stop holds nothing. If a stop
lands during acquisition, it may finish within the grace; Acquire restores
scope and installs Guard without a poll, so the body’s first β-poll can
stop it only after release is secured. A halting acquisition runs no release.
One exceeding the grace can leak what it held; one finishing just inside it
can leave release stopped at its first command. The release has only the
remaining budget, not another grace
(a-guard-acquires).
A shielded node’s fold admits from its ancestors only Aborted and, once since + grace has
passed, everything; since is the earliest cancelled_at on the chain above
it, and the grace is capped by the nearest enclosing shield’s. It exists
only as a Scope, so its own flag is never written and a descendant’s own
cause stays visible. Every cleanup of
one unwinding therefore ends by one instant, and a run ends within wall + grace + TEARDOWN_GRACE. The shield is cooperative: a signal the tty or the
collector sends to the group still reaches acquisition or release children,
and a child that dies of it is a process failure, since the current scope
carries no cause to attribute it to. In acquisition that failure can halt
before any release is installed
(a-cleanup-is-shielded-within-its-grace).
The collector honours it in its teardown: cancel_all writes its cause on
every thread stage, waits for live thread stages, bounded by the grace, before
the group kill; a panic or a stronger cause mid-teardown escalates over the
survivors; an abort grants no grace and cuts the waits short; the teardown’s
cause is a candidate verdict at the fold, the collector’s own closing
observation.
External children: teardown by cause
The process-wide reaper (io-process) posts a child’s
exit onto its collector’s channel, a lone command’s too (Started::collect), and the
collector receives a slice at a time, reading the current scope between
slices: a cause in force starts the
teardown, and the grace wait inside it is sliced too, ending at once under
Aborted. The teardown is cause-directed,
and grace_signal(cause) (process/signal/unix.rs, and its Windows twin)
is the one table that directs it — read by the collector’s cancel_all,
every external’s one teardown:
Interrupted→ SIGINT-first, a boundedTEARDOWN_GRACE(500 ms), then a group (or, ungrouped, pid-Watch) SIGKILL — a child that traps SIGINT still dies, and its grandchildren with it.Cancelled/TimedOut/Terminated→ SIGTERM-first with the same grace then the same kill — decisive, without pretending to be a user keystroke; aTerminatedhands the tree the very signal the supervisor sent ral.ReaderGone/Aborted→None, an immediate kill with no grace. A reader-gone cut must not hand the verdict back to the producer’s own disposition, and an abort has no grace to offer.- On Windows every graceful cause opens with Ctrl-Break, named by the
STATUS_CONTROL_C_EXITit leaves, and only an owned console group takes it (break_pipeline_group: oneCTRL_BREAK_EVENTper pid on the job’s member list — every stage is spawnedCREATE_NEW_PROCESS_GROUP, so each is its own console-group root, and a nested member is on the outermost owner’s list); a pid is killed at once in the grace’s place, the WindowsWatchhaving no signal, and anInheritchild sits in ral’s own console group, where no event reaches it without reaching ral. The pipeline anchor swallows every console event, so a group’s grace never ends the process holding it open.
A collector signals only the group it owns. It addresses a child by where it landed, and every other child by pid (a-process-group-is-its-owners-to-signal). A teardown kills before it joins, and a collector dropped mid-flight joins no pump (a-teardown-kills-before-it-joins).
Every external wait goes through this one recv/cancel_all shape, a lone
command’s included (it is a pipeline of one, Started::collect), the interactive
REPL foreground included. ral does not suspend: a stop never reaches this
channel, and is never itself a cause for teardown
(pipeline-execution). A foreground external
still gets its Ctrl-C from the kernel directly — it holds the lent terminal —
and the key is heard back by the loan when the terminal returns
(§Attribution); a SIGTERM delivered to
ral preempts even that wait through the root cause, read at the next
slice.
One status per fact
A run’s ending is a function of its cause, never of where the cancel
landed. A cancel that lands before a spawn meets a poll point; one that
lands after meets a torn-down child. Both doors mint the one constructor
Break::stopped(cause, owner), so the two cannot disagree. Two traits
project status. FailureCode::failure_code() -> NonZeroU8 belongs to what can
only fail: a cause, a Stop, a Reason, an Error, an ErrorFact, an ErrorRecord.
ExitCode::code() -> u8 belongs to what can also succeed: an ending (Ok is
0, an exit n is n, a panic 101, the rest delegate) and a Break. Stop
holds cause, owner and Option<Prov>; End = Ending<ValClos, Error, Stop>
holds the ending. Runtime error and wire fact share the one Reason:
Reason = Process(program, Failure) | Cancelled | TimedOut | Raised(Claim)
Failure = Exited(i32) | Signaled(i32) | NotFound | NotRunnable(detail)
Reason::describe is the one wording; the one FailureCode for Reason
table supplies failure codes (Process delegating to Failure), with errors,
facts and process-layer failures delegating; an ErrorRecord stores the
projected status. Reason::stopped is
the one conversion from a cause (Cancelled, TimedOut); its words and
codes come from CancelCause.
A worker completes otherwise unlocated errors from its inherited register
before publication, so done, poll and await agree on name and site.
The two command-audit observers read Break’s code; fact::Command.status
is u8, since a command can succeed.
An in-session worker stop becomes an error: a worker’s boundary
converts a Cancelled or TimedOut stop owned inside the session, and
await/poll report it as the awaiter’s failure. Signal handlers call
failure_code, which allocates and locks nothing, widening only at
_exit/ExitProcess. Failure::Signaled projects 128 + n through
failure_byte; Signal::of_status decodes an envelope’s raw status.
External raw exits remain in
Failure::Exited for messages and hints until the failure-code projection
clamps through failure_byte into 1..=255. A negative Windows NTSTATUS
must not become success. exit refuses outside 0..=255; fail takes text,
yielding code 1. raise takes any record as a Claim, refusing status 0 and
above 255. A Reason
stores no status, except a claim’s own. Host Static/Faulted statuses stay NonZeroU8
(endings,
the error record):
| break | code |
|---|---|
Raised(Claim) | the claim’s status (1 for fail) |
exit n | n |
ExitCode(n) | n clamped into 1..=255 |
Signal(s) | 128 + s, clamped into 1..=255 |
| spawn: not found | 127 |
| spawn: any other | 126 |
stop Interrupted | 130 (128 + SIGINT) |
stop Cancelled, Reason::Cancelled | 143 (128 + SIGTERM, what kill sends) |
stop TimedOut, Reason::TimedOut | 124 (as timeout(1)) |
stop Terminated | 143 (128 + SIGTERM) |
stop Aborted | 131 (128 + SIGQUIT) |
stop ReaderGone | 141 (128 + SIGPIPE) |
Panic(_) | 101 |
Errors reach ral code as [frame, message, status, site]. Reason lives in
fact/error.rs; the message and status are its projections. `cancelled and
`timed-out are the two converted worker-stop facts. A stop has no
record: no try sees it.
Attribution
A child’s death passes through command::ending, which asks
WaitOutcome::cancelled_by(cause) whether it was a cancellation; if so
Break::cancelled makes it a stop carrying the join of the current scope,
exactly as a poll point does, and otherwise it is the child’s own failure. cause is the strongest in force on the current scope when the
death is observed, not only what ral sent: under a shield a key the tenant
heard is no cause, and the death is a failure.
A death is a cancellation iff it is by a signal of a cause in force.
WaitOutcome::death is the one reader of a death, a signal
death’s signal, and the death is
cause’s iff that signal lies in signals_of(cause): the cause’s
grace_signal, its key gesture_signal, and the kill that ends every
teardown — one function over the platform’s three tables. With no cause in
force, no death mints one: every signal death is the child’s own Signal, a
key’s included, and an exit is never a signal — exit 130 is a choice. A
SIGSEGV under any cause stays Signal.
| cause | signals_of (Unix) | signals_of (Windows) |
|---|---|---|
ReaderGone | SIGKILL | KILL_EXIT_CODE |
Aborted | SIGKILL, SIGQUIT | KILL_EXIT_CODE |
Interrupted | SIGINT, SIGKILL | KILL_EXIT_CODE, STATUS_CONTROL_C_EXIT |
Cancelled, TimedOut | SIGTERM, SIGKILL | KILL_EXIT_CODE, STATUS_CONTROL_C_EXIT |
Terminated | SIGTERM, SIGHUP, SIGKILL | KILL_EXIT_CODE, STATUS_CONTROL_C_EXIT |
Only a terminal ral lent can report a key pressed on it. A key is what a
terminal sends: the GESTURES table in process/signal/unix.rs — SIGINT →
Interrupted, SIGQUIT → Aborted, SIGHUP → Terminated; no terminal sends
SIGTERM. KeyAttribution (process/terminal/keys.rs) reads gesture inside
the private terminal module. Only an established loan owns this attribution;
callers carry an opaque TerminalHold and invoke hear or consuming
reclaim, never extracting saved state or the key state. While lent, the key
reaches the tenant’s group and never ral, so the loan hears it back and
strikes it on the node it was lent for (Mooring::home) as it hears:
- a lone command is heard at
reclaim, the instant it is dead and before its pumps are joined (the-terminal-returns-before-the-pumps), from its owndeath, no anchor having reported a key; its collector then reads the current scope once, so Ctrl-C ends the command stopped withInterruptedand the run is stopped — unless a shield masks it, when the death is the command’s own`process [.., failure: `signaled 2]and the stop follows at the cleanup’s first poll after the grace; - a pipeline’s loan is held by its collector: the anchor reports each
signal it swallowed raw as
Event::Heard(signal), which strikes the node and recordspressed; the teardown follows from the scope read at the next slice, which is what lets a shield hold it off.pressedis read only to skip a duplicate grace signal, never to attribute a death.foldopens withCollectState::vacate, which strikes the last reports and returns the terminal once no stage is live, before any pump is joined, as a lone command does; the reclaim itself strikes nothing.
The node the loan strikes is always the run’s own, never the current scope:
neither a stage’s child nor a stage’s pipeline is lent, so the strike reaches
every stage through the chain and the run’s closing poll alike. What the loan
cannot settle is an external inside a stage body: a Joins member whose
collector reads its scope as the reaper posts its death, racing the strike.
Lose the race and the stage reads `signaled 2 — a failure ranking under
the stop the run’s own poll then raises, so the run stops either way.
An enveloped tenant holds only restoration responsibility, not an established
loan: its TerminalHold restores modes without hearing or attributing keys.
Without a loan — exarch, a capture without explicit access, a stage thread,
a worker’s pipeline — a heard signal is inert, so try stays total over
everything else a child can do, a child that kills itself with SIGINT included.
Two shapes were rejected (the-lent-terminal-returns-the-gesture): ral keeping its own pgid for lone children, which would make ral the ear of a program that reads Ctrl-C itself; and a seat enum recording where a child sits, a fact nobody holds.
The escalation ladder’s forced exit status is its handler’s own cause’s —
130 for SIGINT, 143 for SIGTERM and SIGHUP. Windows has no signals to read,
so ral ends every process it tears down — TerminateProcess and
TerminateJobObject alike — with one KILL_EXIT_CODE; death there reads
that and the console’s STATUS_CONTROL_C_EXIT and nothing else. The latter
is what Ctrl-C and Ctrl-Break both leave, so it is every graceful cause’s —
a TimedOut teardown reads timed out, never an exit status — and with no
such cause in force it is displayed as “ended by Ctrl-C”. A console is never
transferred: a Windows loan saves available console modes and restores them
on drop, but gesture returns None, because ral already hears Ctrl-C itself.
gesture_signal(Interrupted) still names the console death status; the two
functions are not inverses on Windows. A cancelled child carries no hint.
The gestures, per host
The same two mechanisms are driven by different keys on different surfaces.
| gesture | surface | what fires | effect |
|---|---|---|---|
| Ctrl-C | ral REPL, mid-eval | SIGINT → Interrupt | request_interrupt(), forwarded as Control::Strike(_, Interrupted) — a pipeline’s externals hear it through the collector; counter untouched |
| Ctrl-C | ral REPL, idle prompt | line editor reads it as a byte | abandons the partial buffer; nothing is in flight, so nothing is sent; no signal |
| Ctrl-C | ral REPL, idle minimal prompt | canonical tty → SIGINT → Interrupt | the tty drops the partial line; the changed prompt epoch wakes a fresh prompt immediately and discards continuation input too; request_interrupt() is forwarded, but every later dispatch is born after it, so it strikes none |
Ctrl-\ | ral REPL, terminal not lent | SIGQUIT → Abort | request_root_cancel(Aborted), forwarded as Control::End(Aborted) — reaps foreground and every worker, latching if idle; the REPL loop observes the sticky root and exits |
Ctrl-C / Ctrl-\ / hangup | any ral host, terminal lent to a command or pipeline | tty → the tenant’s group (a hangup also reaches ral, as session leader) | the lent TerminalHold hears it from the tenant — its death, or the anchor’s Heard — and strikes Interrupted / Aborted / Terminated on the run’s node as it hears: the job is stopped, try never sees it, the session lives |
| Ctrl-C | ral batch / -c | SIGINT → Shutdown | request_interrupt(), forwarded as Control::Strike(_, Interrupted), + ladder +1; third press _exits |
| SIGTERM / SIGHUP | any ral host | Shutdown | request_root_cancel(Terminated), forwarded as Control::End(Terminated) — foreground and workers unwind, externals torn down SIGTERM-first, exit 143; ladder +1, third delivery _exits |
| Ctrl-C / Ctrl-Break | ral on a Windows console | console event → the ctrlc handler | request_interrupt(), forwarded as Control::Strike(_, Interrupted), + ladder +1; third event ExitProcesses with 130. No console event is sent to any group: the struck run’s teardown breaks the groups it owns, and a worker’s are never reached |
| Ctrl-C / Esc | exarch TUI, open job | AgentHandle::stop(JobId) on the focused address | cancels latest exchange with Interrupted, recalls queued human text losslessly ahead of the draft; helpers survive |
| Stop / Esc | synod, open job | AgentHandle::stop(JobId) under the mailbox lock | matching job is marked stopped, latest exchange cancelled with Interrupted, human text recalled; helpers continue and reports can resume the root within the job |
reply / /clear | exarch owner | owner-thread transition | reply reports and clears schedules; clear prepares first, joins helpers and replaces the engine, retaining queued human text/messages/commands |
end / /close / dismiss / owner drop | exarch | home cancellation | ends subtree with Cancelled; helpers join before engine retirement |
| first failed record append | exarch | home cancellation | the writer’s Fatal ends its bound home with Cancelled; the owner announces the failure at its end |
| engine severance | exarch | home cancellation | the transport’s Fatal ends its bound home with Cancelled from the severing thread; the owner names the loss at its end |
| helper idle timeout | exarch helper | home cancellation | TimedOut under the mailbox lock after resting idle with no admissible input |
/quit / Host::end / host drop | exarch host | fleet-root cancellation | Cancelled reaches all lives; host joins all root threads |
| Ctrl-C / Ctrl-Break | exarch on a Windows console | console event → console_ctrl_handler, ahead of ral’s | request_interrupt(), reported handled so ral’s ladder never sees it; face forwards it to every live root’s AgentHandle::stop_current |
| Ctrl-C / Ctrl-D | exarch TUI, idle prompt | key table → quit | drops the TUI guard; no cancellation |
| Ctrl-C / Ctrl-D / Esc | exarch TUI overlay | key table → close overlay | returns to the underlying prompt / exchange; no root cancel |
| async SIGINT | exarch | ral’s non-escalating Interrupt | forwarded by signals::face to every live root’s AgentHandle::stop_current |
| async SIGTERM / SIGHUP | exarch | ral’s Shutdown | forwarded as Fleet::end(Terminated); dispatchers observe exchange ancestry; ladder +1 |
ral interactive signal dispositions
boot::setup_signals (ral/src/repl/session/boot.rs)
fixes the interactive dispositions, each through core’s
process::install(sig, Disposition) — the only door a disposition changes
by, and the one that snapshots the inherited SIG_IGNs (once, before the
first change) so every child gets them back in reset_child_signals. A
handler’s cause is read from GESTURES, the key table that also names a lent
terminal’s keys: SIGINT asks an interrupt, SIGQUIT the root’s Aborted,
SIGHUP its Terminated; SIGTERM, no key’s, asks what a hangup does.
- SIGINT →
Interrupt. It raises the interrupt and does nothing else — no delivery of its own. The session forwards it asControl::Strike(_, Interrupted), and ral’s own delivery to a pipeline’s processes is the cancel tree alone: the collector’srecvreads the struck scope between slices, mintsEvent::Cancelled, and tears the group down with exactly one grace signal per process (pipeline-execution, one-delivery-path). A foreground pipeline’s externals usually hear the kernel’s own copy first, delivered by the tty to the pgid the terminal is lent to; the anchor reports it and the pipeline’s loan hears it as the key, so teardown does not re-send it. Raised while idle, it strikes only the settled run’s dead scope, so the next run never sees it — and a session worker, off every run’s chain, is spared outright. - SIGQUIT →
Abort, the louder “reap everything” gesture: cancellation of running work, never deletion of bindings. It is a cooperativerequest_root_cancel, not the default core-dump — so it satisfies “Ctrl-\must not core-dump the shell” by reaping, not by ignoring. - SIGTERM/SIGHUP →
Shutdown— translates to a rootTerminated(the whole session unwinds, the REPL loop exits 143) and walks the escalation ladder; SIGTSTP/SIGTTOU/SIGTTIN/SIGPIPE →Ignore— the shell is never stopped itself, a stop reaching one of its own children is the reaper’s to answer, and it rewrites terminal state without being stopped (ral-does-not-suspend).
No disposition restarts a call it cuts. Every handler ral installs (the
three dispositions, the pipeline anchor’s report, the Linux supervisor’s
no-op, the reaper’s SIGCHLD) omits SA_RESTART: signal::set is the one
sigaction the dispositions go through. A signal lands on whichever thread
does not block it, so any blocked call in the process may return EINTR, a
child’s exit included, and every blocked call ral makes retries it:
poll_slice against its slice’s deadline; a sliced read or write after
readiness by ending its slice unlanded (io/source.rs, io/sink.rs); std’s
read_exact, write_all and io::copy; retry_on_intr around reap’s
waitpid, the jail’s flock on its sequence file and a lent terminal’s
restoring tcsetpgrp and tcsetattr(Drain); exarch’s
Scanned::read, since grep-searcher does not retry; the minimal REPL
reader, which relies on EINTR to hear a SIGINT at all. What is left cannot
see one: waitid and waitpid with WNOHANG, a write to cgroupfs or a
one-byte pipe write in a forked child that has no children of its own, and a
non-blocking socket whose caller already treats Interrupted as pending.
exarch: life contains exchange
Every agent owns one life, with exchanges and helper lives beneath it. An exchange is one input through local nudge continuations; a job is its recorded busy period, not a scope (an-agent-is-a-thread).
- Stop cancels only the current exchange with
Interrupted. Human gestures recall queued text; desk Stop and SIGINT retain it. Helpers, schedules, messages and loose shell workers survive. End cancels life; helper rest timeout usesTimedOut; writer failure and engine severance latch life cancellation. No scope resets. AgentMailbox::nextmints the exchange lease at pop.beginopens a job only after the owner accepts input; Stop at rest, including before that opening, does nothing. Mid-job Stop sees the newly minted exchange.JobOpenedand registration,JobSettledand clearing, and Stop’s mark share the mailbox lock. New input may continue a stopped job; settlement waits for the empty queue, pending helpers and returning-agent schedules.- A helper is pending while it owes its parent. Reporting queues
Childbefore clearing the debt;Gonelater joins it quietly, even at rest. A helper ending after reporting does not hold settlement open; teardown failures can arrive later. - Provider waits poll exchange; parks poll life every condvar wake or
PARK_POLL. Own end, Stop and posts notify. Factory, attach, probe and protocol writes retain independent deadlines. dispatch_to_report(..., Some(exchange))owns the strike for its own dispatch id, before sending and after each nonterminal event or slice. Identity parents beneath exchange; wire uses addressed controls. A strike cannot hit a later dispatch, and cancelling threads never write transport.Scopes::endends engine root and current dispatch, even externally parented.- Engine-owned loose workers survive exchange cancellation. Deferred batches carry generation; clear advances it. Clear prepares first, joins helpers, commits and replaces the engine; failed preparation changes nothing. Failed commit ends life and retires the prepared engine.
- Timers use weak shared addresses. Scheduled firing checks coalescing, updates/retires the registry and posts under one mailbox transaction, ordered mailbox → registry. Epochs invalidate wakeups across clear/report.
- Teardown ends life, reports owed failure, joins helpers, then takes and
retires
Option<Engine>once.Joineddrop and owner field order preserve helper-before-engine destruction on unwind.Hostend/drop joins roots. Uncertified engine end isTeardownFailed, propagated through join results.
Synod and TUI observe Stop
Stop preserves the agent and its helpers, not a frozen job boundary.
- Synod uses gated admission. Baseline and each closing folder walk precede
release of the next job. Human text, messages, wakeups and worker batches
may then open it. A stopped helper’s report can wake the root in the same
job; a stopped mark is carried by the eventual
JobSettled. - Settlement waits for helper debts, not shutdown of resting engines.
A resting helper ending during a walk can report teardown failure later;
Synod treats
TeardownFailedas terminal. Engine end requires the wireDetach → Endedacknowledgment, not EOF.Guest::endjoins all agents throughHost::endbefore recovering its machine factory. - TUI tabs use recorded job ids for Stop. Recalled text is prepended to the
draft even during history browsing or non-insert mode; Up recall remains
guarded. Synod serializes withdrawals in gesture order and binds them to
the attempt/job captured at the gesture. Backend
JobDone.stoppedalone draws “Stopped.” after in-flight output. signals::faceforwards SIGINT to rootstop_current, shutdown to the fleet. Raw keys stay local, and overlays/search/copy own their gestures first.Chrome::Cancelleddistinguishes cancellation from failure.
Why interactive Ctrl-C cannot force-exit
A deliberate asymmetry worth stating plainly: the third-signal _exit floor is
unreachable from an interactive prompt. Interactive SIGINT goes to
Disposition::Interrupt, which never ticks the ladder; the TUI’s active-exchange
Ctrl-C goes to
AgentHandle::stop, which never touches the ladder. Repeated presses re-write the same cause
(fetch_max), never escalate. The hard
floor exists for batch scripts (Shutdown) and for external SIGTERM/SIGHUP. Interactive cancellation is cooperative
by construction; the root-reap gesture is REPL Ctrl-\, not a TUI key.
See also
- delimiters-are-handlers-for-poll — a stop is an escape with an owner; the two cells, sliced waits, the collector as the owner of its stages’ nodes.
- a-cleanup-is-shielded-within-its-grace — the shield and its budget from the strike.
- signals-are-causes — the collapse of
signal delivery onto the scope tree:
Terminated, the scope-onlycheck, the one wait loop. - unify-turn-evaluation — the
root/foreground split and the
CancelCauseorder. - esc-non-escalating-interrupt — why the user interrupt writes a flag, not a counter.
- an-agent-is-a-thread — life/exchange scopes, observed jobs, reports and structured teardown.
- hot-path-cancellation — the original cooperative-poll insight.
- cancel-is-a-join — why the handler
contributes an element instead of aliasing one; the folding it introduced has
since given way to forwarding as
Control. - output-capture-and-detachment and pipeline-execution — the foreground-deadline and group-teardown paths that read the scope.
- io-process (signals, process groups),
ral-does-not-suspend,
one-delivery-path (one signal per
process, through the collector),
agent (the owner loop whose scopes evaluation shares),
and
core/src/process/signal.rsitself.