0277. Per-agent trap domains
- Status: Accepted (maintainer, 2026-11-22; recommended defaults for all open questions; frozen-file edits listed here approved)
- Date: 2026-11-22
- Plan: backlog D5 (proposal P5); follow-ups in M14 agent runner, procman (ADR-0267)
- Review: Design Critic #4; amends 0102, 0107
Context
Every trap (LANGUAGE.md "Runtime traps": overflow, bounds,
fuel exhausted, deadline exceeded,
io error, file closed,
out of memory) ends in trt_trap
(runtime/tenon_rt.h): flush stdout, print
trap: <kind> at <file>:<line>:<col>,
exit(101). The interpreter propagates
Stop::Trap(kind, pos) to run_prepared*
and the driver maps it to 101. One bad agent step, TUI widget or
procman job therefore kills every agent, the UI and the daemon.
The C runtime already has half the mechanism: under
TN_PAR a thread-local trt_worker_trap
(jmp_buf + kind/site) lets
trt_par_execute (runtime/trt_par.h)
catch a worker trap, drop the worker arenas and re-raise the
lowest-index trap after join (ADR-0102). Values are immutable
(0007/0036), there is no global mutable state, and agent steps are
pure
Agent.step(self, event) -> Transition<Self>
calls (0010/0107), so a trapped call has no partially updated
value to repair; only arenas and in-flight effects need
cleanup.
Decision
- Kernel mechanism. A trap domain is a
thread-local stack of
trt_trap_context(generalisingtrt_worker_trap).trt_traplongjmps to the innermost domain; with none open it keeps today's print-and-exit-101. The interpreter mirrors it: a domain frame catchesStop::Trapand restores heap marks. Both backends return the same value:struct Trapped { kind: str, file: str, line: i64, col: i64 },kindusing the exact spellings already in LANGUAGE.md. - No new syntax (0006, 0009). Domains open only
through platform methods (policy in plugins, 0004). The cli
platform adds a
Trapscapability (cli.traps, ceilingtraps):traps.contain(job) -> result<J, Trapped>forJ: Contained, whereinterface Contained { fn run(self) -> Self }(a job is a value holding its input and, afterrun, its output). The agent platform's runner wraps eachAgent.stepin a domain and turns a trap into a per-taskTrappedoutcome. Surviving a trap is an authority: a library cannot swallow traps unlessmainhanded itTraps(0050/0095). After ADR-0275 (D3) acontain(f, x)form over function values may replaceContained. - Entry and unwind (C).
setjmplives only in one runtime helper,trt_domain_call(fn, env, out), shaped liketrt_par_execute; generated function bodies never containsetjmp, so no generated local needsvolatileand-O2stays correct. The helper's own state is set beforesetjmpand not modified after it. On entry it recordstrt_markof every scratch colour and oftrt_persistent; on a trap ittrt_resets to those marks, so the transition arena (0107) and anything promoted inside is discarded. Nothing allocated inside a trapped domain is reachable afterwards (its result is dropped). - Effects in flight. The domain owns a resource
ledger:
File/Listener/Conndescriptors, capability slots and child process groups created inside it are closed or killed-and-reaped on unwind. Effects already performed stay done: bytes written to stdout (buffered or flushed), files written, requests sent. The trap does not flush or truncate stdout; a partial line may remain, and platforms print their own marker. Locks held by the runtime (trt_par_io_lock) are released astrt_par_executedoes today. - Nesting, workers, budgets. Domains nest; a
trap goes to the innermost one. A data- parallel worker trap
(0100/0102) is re-raised at join in the caller's thread and so
lands in the caller's innermost domain. Fuel and deadline stay
process ceilings (0017/0074): a domain may carry a tighter budget
(
traps.limit(fuel, deadline_ms) -> Traps, attenuation only); exhausting the domain budget traps into that domain, exhausting the process budget still ends the process once the domain returns. - Not catchable. Native crashes in FFI code
(0152), including SIGSEGV in a shim; in the interpreter a dead
ffi-hostchild stays fatal, matching C. Stack overflow is out of scope (sigaltstack + guard-page recovery is not cheap or portable to get right; a separate ADR may add it). The SIGBUS mmap path (0055) never traps, so it is unaffected; no signal handler ever longjmps into a domain.cli.exitis not a trap and still exits. - Journals and replay. The runner journals a
trapped transition as a result record (kind + site). Replay
re-executes deterministic kinds and requires the same kind and
site (a mismatch is a replay divergence);
deadline exceededandio errorare replayed from the record. Retry, restart and supervision are plugin policy: the agent runner defaults to no retry (deterministic traps repeat); procman and the TUI shell choose their own.
UX: one failing agent or widget degrades to a
visible error, not a dead app or daemon. DX: a
structured Trapped with the same site as today's
message; no exceptions to learn. AX: no new
grammar; one capability method, one result type, explicit
authority.
Prior art
- Go
recover(unwinds only to deferred calls in the panicking goroutine): https://go.dev/blog/defer-panic-and-recover - Rust
catch_unwindandUnwindSafe: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html - Erlang/OTP isolated processes and supervisors ("let it crash"): https://www.erlang.org/doc/system/sup_princ.html
- Swift does not recover from traps ("universal errors" are fatal): https://github.com/swiftlang/swift/blob/main/docs/ErrorHandlingRationale.md
- Zig: panics are not recoverable: https://ziglang.org/documentation/master/#Panic-Handler
Alternatives considered
- Process per agent (Erlang-style by OS
process) — full isolation, but agents are values sharing one arena
runtime and journal; fork/IPC per step costs far more than a
setjmp. - User-level
try/catchsyntax — new grammar and an exception-like form agents would overuse; contradicts 0009 and "Absent: exceptions". - Catch traps everywhere (ambient) — any library could hide bugs; capability gating keeps it explicit and auditable.
- Keep exit-101, let procman restart — loses every other agent's state on each trap.
Consequences
Traps become values at a few platform-chosen boundaries;
elsewhere behaviour is unchanged. LANGUAGE.md: +2 lines (~70
tokens) under "Runtime traps"; trim by moving trap kind list
details to diagnostics.md. No new compile-time codes are needed;
misuse of Traps outside a cli program is the existing
capability error. JSON trap events gain
contained: true. Frozen files: listed below;
Maintainer approves them before slices 2-4.
Frozen files that would change
crates/tenon/src/interp.rs: domain frame catchingStop::Trap,Traps.contain/limit.crates/tenon/src/interp/heap.rs: heap mark/reset for the domain.crates/tenon/src/interp/platform.rs:Trapscapability methods and the per-step domain.crates/tenon/src/interp/trap_report.rs:containedflag on captured reports.crates/tenon/src/interp_fs.rs,interp_net.rs,interp_process.rs: ledger close/kill-and-reap on unwind.plugins/cli/platform.toml,plugins/cli/DOCS.md:Trapscapability and ceiling.plugins/cli/native/trt_cli.h: capability-slot ledger;trt_io.h,trt_net.h,trt_proc.h: register descriptors and process groups with the current domain.plugins/agent/run.tn,plugins/agent/journal.tn,plugins/agent/recover.tn,plugins/agent/DOCS.md,plugins/agent/native/trt_agent.h: per-step domain,Trappedtask outcome, journal record and replay rule.- Not frozen:
runtime/tenon_rt.h,runtime/trt_par.h,runtime/trt_mem.h, cgen.
Implementation slices
- Runtime domain stack +
trt_domain_call+ arena mark/reset; porttrt_par_executeonto it; unit tests on generated C text. Files:runtime/tenon_rt.h,trt_par.h,trt_mem.h,crates/tenon/src/cgen_par.rs. Frozen: no. Agent: Claude Opus. Trapscapability,Contained,contain/limitin both backends; interp domain frame. Files:plugins/cli/*,crates/tenon/src/{lower_platform,cgen}.rs,interp.rs,interp/{heap,platform,trap_report}.rs, LANGUAGE.md. Frozen: yes. Agent: Claude Opus.- Resource ledger for files, sockets, processes. Files:
plugins/cli/native/trt_{cli,io, net,proc}.h,interp_{fs,net,process}.rs. Frozen: yes. Agent: Claude Sonnet. - Agent runner per-step domain,
Trappedoutcome, journal + replay. Files:plugins/agent/{run,journal,recover}.tn,DOCS.md,native/trt_agent.h. Frozen: yes. Agent: Claude Opus. - Policies: procman job restart on
Trapped, TUI shell widget placeholder. Files:plugins/procman_core/*,plugins/tui_shell/*. Frozen: no. Agent: Claude Sonnet.
Open questions (resolved)
Resolved by maintainer on 2026-11-22: every question takes its stated default.
Trapped.kind: stablestrspellings or a closedTrapKindenum? Default:strnow, enum when generated codecs need it.- User-facing
Traps.containin slice 2, or runner-only until D3 function values land? Default: shipcontain(procman and TUI need it). - Agent runner retry on
Trapped? Default: none; report to the parent asChildDone. - Stack overflow recovery: separate ADR later, or never? Default: separate ADR, deferred.