Output capture and detachment
A run captures a child’s output by draining its stdout/stderr pipe to
end-of-file, so a process that never closes that pipe is foreground work the run
must wait on to its wall — and spawn is the construct that moves such work off
the run onto a session-owned, byte-bounded worker that lives as long as its
owner. A long-running server is the canonical instance: run inline it stalls
the call to the deadline and is killed with its tree; spawned it returns
instantly and survives until it completes, is cancelled, or the session ends.
The capture frame: a computation’s own bytes
This section names a different mechanism from the drain-to-EOF story
below, though both swap in a Sink::Buffer. The evaluator’s Capture node
is inserted only at a binding: when a let’s right-hand side resolves to
F^w Unit, the checker wraps that computation in cap M to d. decode d (let v = echo hi; see
type-inference and
grades and capture). A command’s value is its output, so the
frame inspects no produced value: capture : F^w Unit → F Bytes.
CompKind::CapturepushesFrame::Capture(core/src/shell/evaluator/machine.rs, evaluator-machine) and swapsshell.io.stdoutto a freshSink::Bufferfor the run of its operand, the frame holding the sink it replaced.- On success,
Frame::Capture’s return rule restores that sink and takes the buffer exactly, asValue::Bytes; the operand’s own value is ignored. The text a value boundary reads comes from thePrim::Decodenode the checker binds over it — no frame of its own, since the kernel’sdecodetakes a value andstep_evalreads it inline: one trailing terminator stripped, thendecode_utf8_strict, the bind’s scope dropped first so the buffer moves into the string rather than being copied. A decode failure names| from-bytesas the route for output that is not valid UTF-8. - On a halt,
Frame::Capture’s halt rule restores the sink it replaced and drops the buffer, as aRedirectaborts its staged writes: a capture that does not become its value commits nothing. AnErrorthat dropped bytes says so once in its hint, never in the recordtryreads;auditis where a command’s output survives. - An operand may contain an external child. That child’s stdout still drains
through the ordinary pump-to-EOF machinery below. It lands in the
Capturebuffer rather than in the terminal.
A discarded statement writes to stdout, wherever that is. A block is a
nesting of Bind and Seq, a; b being Seq(a, b)
(evaluator-machine), and stepping it touches no
sink. Inside a capture stdout is the buffer, and the capture wraps the whole
right-hand side, so everything the block writes is the value unless an inner
let takes it: let x = !{ echo a; echo b } prints nothing and binds
"a\nb", while let x = !{ let y = echo a; echo b } prints nothing and binds
b. A captured stand-in’s every statement is captured.
Capture is a drain to EOF
A captured stream is a Sink::Buffer fed by a pump — see io-process.
io::child::Connectionallocates each drain pipe before spawn. Installation gives its writer to the launch;PendingDrainsowns the reader and sink. Starting drains creates threads without taking any endpoint from the child. Each drain reads to EOF even after destination writes fail, and then flushes its watch tail (core/src/io/child.rs). Shared stdout/stderr destinations have one pipe and one drain on both platforms (a-drain-owns-its-reader).- The pump is joined after the child is waited, and after the kill: the
collector, every external’s one waiter, files the child’s end, and its
settlement then finishes the guest jail, joins the pump handles under the
scope, and only then reads the ending (
drained,core/src/shell/exec/pipeline/collect.rs, runtime). A foreground command returns only once every byte the child wrote has been copied and the pipe has closed. - Every failed start retains its already-started drains in
StartFailureuntil caller settlement, before the error is returned. This does not change audit/surface publication timing. A lone run settles immediately; a pipeline first rolls back and joins, even if no stage registered. A handoff or confinement refusal can follow exec and output:Launch::bornkills an envelope’s named payload group and the fresh group its applied step leads, and no other, before reaping its child; it then restores retained terminal state and releases the jail. A joined child’s descendants remain its enclosing owner’s responsibility, so drain settlement cannot block that owner’s launch rollback. The failed-start join has an empty kill callback; it never addresses a numeric group ID after reap. - The join never delays the terminal: a lone command’s or pipeline’s opaque
TerminalHoldis reclaimed once its tenants are dead, before pumps are joined. An envelope’s restoration-only hold returns modes without attributing a key (the-terminal-returns-before-the-pumps). - A join under a cause in force kills the owned group once, a slice at a time: a survivor holding the pipe ends the join only when its pipe closes. A child cut for a dead write, and a collector dropped by an unwind, detach their pumps instead of joining them, since a descendant the kill missed could hold the pipe for ever (a-teardown-kills-before-it-joins).
- The release condition is EOF, not exit. A pipe closes when its last writer’s descriptor closes — so a child that has itself exited but left a grandchild holding the inherited write end keeps the pump blocked.
A never-closing pipe stalls the foreground to the wall
- A server holds its stdout open for its whole life, so the drain’s read loop never sees EOF and the foreground command blocks indefinitely.
- The release is the foreground deadline. exarch arms a 30 s wall as a
disarmable entry on the shared
process::deadlinescheduler (deadlines-as-data); on expiry the child’s collector, which reads the scope each slice, tears the group down. - A headless exarch external leads a session of its own, and so its own
process group (
Placement::NewSession, chosen byPlacement::commandincore/src/process/terminal/job_control.rsfromShell::group_owner, gated by terminal-foreground-ownership), so the cancel SIGTERMs then unconditionally SIGKILLs the whole group — grandchildren included. Every copy of the write end closes, the pump sees EOF, the drain joins, and the call returns at the wall with exit 124. The server dies with it. - The child’s own report names the cause, not the signal: a death by the
deadline’s own teardown signal is attributed to
TimedOut(cancellation), so the command readstimed outat status 124 rather thankilled by signal 15. - This is correct, not a defect: an inline command that never closes its pipe is genuinely work the run cannot finish, so the run bounds it and tears down its tree. The cancel→drain→collect path is the same one pipelines reap by (pipeline-execution).
spawn moves the work off the run
A worker born in a run hangs off the durable root, not the run (one born inside another worker hangs under that worker): the handle is its evidence (concurrency-detached-vs-structured).
spawn { … }reifies aValue::Handleand runs the body on a worker thread parented at the durable root, not the swappable foreground scope (unify-turn-evaluation). The 30 s wall never reaches it, so the worker survives the run.spawnreturns the handle the instant the thread starts; the run does not wait. A server spawned this way keeps running while the launching run returns in milliseconds.- The worker’s output goes to its own per-handle buffer —
spawn_childwires the child’sstdout/stderrto freshnew_buffer()sinks (core/src/shell/builtins/concurrency/birth.rs), drained into the handle’s result only when the worker settles it. There is no run-owned pipe for it to hold open, so the run cannot stall on it.
A chatty server is bounded, not unbounded
- Ordinary capture and worker buffers are capped at 16 MiB (
SINK_BUFFER_CAP). Past the capCapturedBytes::appendcounts the bytes and drops them, keeping an exact prefix — yet the write still returnsOk(core/src/io/sink.rs). No marker enters the stream. - So the pump keeps reading and discarding after the cap. A server that spews to stdout never fills the kernel pipe — it never blocks on a full pipe — and the worker’s memory stays bounded at ~16 MiB. The worker path has no unbounded-growth failure mode, and no undrained-pipe stall.
- Truncation is reported one way:
takehands back aRetained, the prefix and the total written, whole iff the two agree. The pump is a thread whose failure has no one to raise it to, so the cut cannot be reported on the write path; each reader of theRetaineddecides what it means. Where the bytes are the value —capture—Frame::Capture’s return rule refuses a cut prefix once the writers have joined, keeping none of it (capture). A worker’s replay (await, or a loose worker’s at the end) writes the prefix, then a note on stderr in ral’s voice for each cut stream;pollshows the prefix. A captured run hands its host the totals on the wire (Captured = Streams<Retained>), and exarch says the cut on the model’s stderr. - Audit tees have their own 1 MiB retention cap. They keep exact prefixes without a marker and count every observed byte. Each stream pairs its prefix with its total; a larger total means truncation (audit).
A worker lives as long as its owner
Every concurrent block has exactly one owner, fixed at birth, and only its owner ends it: no policy reaps a running worker for neglect or age (concurrency-detached-vs-structured).
- A gather — a
gather { … }, or a worker’s body — owns everyspawnorwatchborn inside it, and has ended every one before it exits (gather). - The session owns a
spawnorwatchworker born outside any gather, which ends by completing, bycancel, or with the session: dropping the shell cancels every registered worker throughRoster’sDrop. - Nobody owns a
detached process: it files nothing here, because it is not a worker at all — it is meant to outlive the host (exec).
What bounds a forgotten session worker is the session alone: the admission
cap (Mooring::worker_cap; exarch’s is 64) refuses a birth while cap workers
are running, stopping, or reserved at the spawn door, and teardown cancels
the rest.
- Every worker files a
WorkerEntryin its shell’sWorkerRegistrythe instant it starts (core/src/shell/runtime/state/workers.rs): the handle itself and itsOwner— the session, the worker whose body it was born in, or thegatherthat owns it. The handle carries the rest: itsWorkerId, its title, and its clock — a birthStamp(one instant on the monotonic clock durations are measured on and the wall clock a reader is shown), and an endStampset byCompletionPermit::finishonce its thread reaches a terminal state (ReadyorConsumed), before flushing its deferred surface. Every report of time reads those two cells. - Identity is the id; the handle is the capability. A worker’s
Handleis held only in the lexical bindings that received it fromspawnorwatch(pinned against idle pruning bypins_live_workwhile the worker isrunningorstopping); there is no handle-lookup builtin by id or title. - A listing is data.
workers(builtin_workers) returns oneWorkerRowperrunning,stopping, orreadyentry (Consumedentries are omitted): its id, title, owner, state (`running,`stopping, or`ready), birth time, elapsed seconds and settle time (settledis`someiffstateis`ready), all derived from a single consistent snapshot per handle without claiming it. It never holds aValue::Handle, which is not ground, so it crosses the engine protocol as any record does; the row type is the`workersprobe’s, less the host’sretention-left. - A finished worker lingers in the registry in
Readystate,polled or not, until it is claimed (Consumed) or retention expires it — the one policy that removes an entry: 256 idle ral calls under exarch (SETTLED_WORKER_RETENTION), swept byWorkerRegistry::sweep_retentionon the host’s ral-call epoch. The sweep stamps aReadyentry only once any owning parent worker is no longer live (RunningorStopping), so a child whose parent is still running cannot expire before the parent joins it. - A retention reap is atomic with a
ReapNoticerecording what fell and why. The engine drains its ledger at each run’s own ready boundary (Shell::emit_ready_boundary_notices, called fromrun_framedjust before the frame tears down) and pushes it through that run’s surface sink as a`noticevalue, beside the binding-lease’s idle-prune notice; exarch decodes it back (Surface::Notice(Notice::Reap)) into aForensic::Reaprecord that no printer draws. The model’s later “where did my result go?” always has an answer in the log.
Reading a spawned server’s output (the exarch caveat)
- A server never settles, so
await $hwould block to the wall and unwind — sparing the session’s worker, via the cancel-awarefirst_ready. Butpoll $his a pull-based read of a running (or stopping) worker: its`runningand`stoppingarms carry a{stdout, stderr, elapsed}snapshot of the bytes buffered so far and the seconds run, the bytes cloned non-destructively (CapturedBytes::peek, not the completiontake), so the buffer is left intact and a laterawait/`readypollstill sees everything (partial-poll-pending-output). The snapshot is cumulative — each poll of a live worker reports monotonically more — and it is capped bySINK_BUFFER_CAPlike every capture buffer. watch— the one primitive that streams a running worker’s output live — rides the session surface: each line leaves as one`watch [label, line]value through the session-lived deferred sink (Sink::Watch), a batch of one, which the REPL host prints through rustyline’s external printer above the prompt and batch prints to stdout. Only the ral hosts install it (watch-repl-builtin); partialpollis exarch’s substitute: not a live stream, but a poll-driven read exarch can drive from its own runs.- So under exarch a server is fire-and-
poll-and-cancel:spawnit, read its accumulated output withpoll $hon later runs,cancel $hwhen done. Polled or not, it runs untilcancel,/clear, or the host’s own exit — and a server that must still be answering after that exit is not a worker at all, but adetach(below). To keep a full, unbounded log past the 16 MiB cap, still redirect inside the block to a file —spawn "docs server" { python3 -m http.server > srv.log 2>&1 }— and read the file on later runs.
detach leaves the machine, not just the run
Every mechanism above is in-process: the pump, the buffer cap, the registry
all presuppose a thread the session can still reach. detach gives
that up — the thing to escape is not the session but the parent’s observation
of the child’s pgid. It is a first-class value with type
String → String → [String] → F [pid: Int, desc: String], called as
detach desc program [args]. A binding, not a handler, stubs detach.
- Everything up to the birth is the ordinary external-command machinery —
Command::from_name,Command::lookup,Command::admit, and the vetting and launch any external is prepared with, surrendered here (Prepared::detach,core/src/shell/exec/command/detach.rs) — so the grant judges the call exactly as it judges any exec. Program lookup bypasses bindings and the whole handler stack, including base frames, as^programdoes; an intercepted program name is never refused merely for having a handler. Only the last act differs:Prepared::detachmatchesProgramLaunchto the direct or envelopedspawn_detached. The innerLaunch::spawn_detacheddouble-forks. The intermediate exits at once and hands the grandchild’s pid back over a pipe, so no collector ever records the pgid its kills address. Reaching the same lifetime by hiding a worker outside the session’sDurableRootcancel scope was rejected: it defeats the signal but leaves the child holding a pipe that closes at exit, killing anything that logs. - The grandchild severs the rest itself:
setsid()in its own body, since a bare double fork leaves its pgid naming the intermediate’s recycled pid; and fd 0, fd 1, fd 2 all on/dev/null. There is no pump, so none of the drain-to-EOF story above applies, and noSINK_BUFFER_CAP— there is nothing to buffer. - What comes back is a receipt —
{ pid, desc }, anF [pid: Int, desc: String]record rather than aValue::Handle— and nothing is written anywhere. So there is no registry entry, nothing forcancel_allto reach, and no exit status: the session never waited and cannot. The survivor is mute: a program worth outliving a session keeps its own log, and the only way to learn whether it is still alive is to probe what it serves. - A report failure surrenders too. Direct trampoline and enveloped
launches hear the first word after detached birth. A refusal or stop returns
an error without killing the survivor; an envelope asks for no payload pgid.
Launcher attribution applies only to the fork’s own exec error, not to the
payload’s later
unstarted(errno). - A successful spawn means the grandchild exec’d. A later failure to reap
the intermediate or recover the pid is
Survivor::Unnamed: the user is told a program runs that nothing can stop by pid. - The verb is absent, not vetoed, wherever the host omits it. Installation
is Unix-only, where the double fork exists. Whether a given call may use
the verb is asked of the live grant stack
(
GrantStack::permits(Flag::Shell(ShellVerb::Detach))) and answered as a refusal, ashelllist without`detach(detach-under-a-grant). - A survivor born under a projection keeps it for life. Preparation
renders the frame’s confinement into the launch exactly as for a child the
session keeps;
Ownership::Surrendered, which only thedetachbuiltin asks for, drops only the two ties between the session and the envelope — death (--die-with-parent, which against a double fork would kill the survivor moments after birth or never fire at all) and address (--info-fd, there being no session left to address it). The namespaces stay: the envelope’s init outlives the session, so the daemon runs confined until it exits, itsgetpid()namespace-local and its process invisible from inside any later grant. Nothing later can widen what it may touch, because nothing later can name it (the-envelope-is-a-process-namespace). - In a guest, all survivors join one shared
ral-exec/detachedleaf, limited as one command is, and runs as the one guest uid,GUEST_ID. A launch holds no teardown authority over that leaf, even if preparation or exec fails. Engine teardown reaches only its kept commands; machine halt reaches both (io-process). - A detached row has no place in a resident fold even if one wanted the
ledger’s uniformity, because that fold demands
cancel()and every answer is wrong — a no-op lies about the edge, akillre-asserts the ownership the verb exists to renounce (residency).
See also
exec (the detached program and its receipt),
concurrency-detached-vs-structured
(why a handle marks a worker),
unify-turn-evaluation (the root/foreground
split and the reaper), shell-eval (the frame that arms the
wall and captures the bytes), binding-leases (the
scratch-name ledger on the same ral-call clock as retention),
io-process, and docs/SPEC.md §11.2, §11.4, §11.5.