# ADR 0016: User-level cleanups: `defer` **Status:** Accepted by the project owner on 2026-10-12; proposed 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44). ## Context [ADR 0003](0003-effect-lowering.md) rule 5 left user `finally` out of v0: unwinding runs only drops, never user code that could perform operations. Programs still need cleanups that run however a scope is left: closing a socket, logging that a request ended, restoring a reference. Four things leave a scope early, and each already unwinds exactly (Perceus drops on the unwind paths, ADR 0003 Revision 2): - a `final ctl` operation, unwinding to its handler; - a panic, unwinding to the actor's root; - a kill, delivered at the actor's next safe point; - the cancellation of a `ctl` handler body that is never resumed (the handler finished first). Running user code in the middle of an unwinding raises two questions: which effects that code may perform, and what happens if it unwinds itself. The interpreter did not unwind the way the native backend does. It abandoned a body left by `final ctl`, and killed actors, by dropping their corosensei fibers, which runs Rust destructors only. It also never cancelled a `ctl` body whose handler finished, so a `resume` called later still ran it, where the native runtime panics (issue #49: escaped continuations). ## Decision ### Syntax: a `defer` statement ``` fn serve(conn) -> () / { defer net.close(conn) handle_requests(conn) } ``` - `defer expr` is a statement. `expr` (the *cleanup*) runs when the rest of the enclosing block is left, normally or by unwinding. The block's value is the value of the statements after the `defer`. - Several `defer`s in a block run in reverse order: each protects the statements after it. - The cleanup has type `()`. It reads variables when it runs, not when the `defer` is reached; values are immutable, so this only shows with references. - `defer` is a new keyword. It follows Go, Swift and Zig, and the existing `use` statement, which also takes the rest of the block. ### A cleanup's effects: only those that cannot unwind or suspend The cleanup is checked like the body of a closure `fn() -> () / r` called at the `defer`, with `r` **closed**. Every label of `r` must be: - an effect without operations: `io`, `ffi`; - or a region's `st` or `alloc`, whose operations are handled by the runtime and never unwind. Anything else is error **E0506**: `fn` operations of user effects (their clauses may do anything, including `final ctl` to an outer handler), `ctl` and `final ctl` operations, and `proc` (`receive` and `sleep` suspend the actor). A callback with an inferred row becomes total; one with a declared row variable is rejected (E0502), as in a lambda. **Why not total cleanups.** A total cleanup could not print or close a socket, which are the main uses. `io` and `ffi` have no operations, so allowing them adds no control flow. **Why not every effect.** An operation that unwinds or suspends inside a cleanup starts a second control transfer during the first. Each combination would need a rule: `final ctl` to a handler *inside* the one being unwound to, a `ctl` that captures a continuation of half-unwound frames, a `receive` in an actor being killed, or a never-resumed continuation cancelled during a cancellation. Koka allows effects in `finally`, but it unwinds by its handlers' own machinery. Here, unwinding is a flag that every frame tests, and a second transfer would have to save and restore it at every handler. The restriction can be relaxed later without breaking programs. **Panics stay possible.** Arithmetic can overflow anywhere, so a cleanup can always panic. ### What happens while a cleanup runs - The unwinding in progress, if any, is **set aside** while the cleanup runs (`yielding`, the marker and the payload are saved, then cleared), and **resumed** afterwards. - **A cleanup that unwinds itself replaces the unwinding in progress**, whose payload is dropped. That is a panic, or a kill. This is the rule `tl_panic_str` already applies to a panic during a `final ctl` unwind; Java's and C#'s `finally` behave the same way. - **Kills are not deferred.** A killed actor runs its cleanups as it unwinds, but the kill is delivered again at the actor's next safe point (a preemption, or a wait). A cleanup that runs longer than the actor's time slice, or that blocks, is cut short there, and the cleanups outside it still run. As in Erlang, a kill cannot be trapped; a cleanup that could delay a kill indefinitely would make it trappable. - **Cancellation.** When a `ctl` handler finishes while its body waits for a `resume`, the body is cancelled: its cleanups run then, after the handler's clause returned. A panic in such a cleanup continues past the handler, replacing its result. ### Native lowering - Core gets `Defer { body, cleanup }`: two closures. HIR lowering turns `defer c; rest` into it, with `rest` as the body. - The C backend calls the body, then the runtime's `tl_defer(ctx, result, cleanup)`, which implements the rules above. The usual yield check after it continues any unwinding. Perceus treats both closures as consumed; nothing else changes. - `louise_rt`'s cancellation (`handlers::cancel`) lets an unwinding started by a cleanup win over the one it was preserving, and `tl_handle_ctl` returns unit in that case. - Cost: one closure for the rest of the block and one for the cleanup, and two calls. Code without `defer` is unchanged. ### The interpreter unwinds like the native backend - Unwinding is an `Err` returned through the interpreter's Rust frames, so a `Defer` runs its cleanup on the way. Two internal errors join panics: `Cancelled` and `Killed`. - A suspended fiber is never dropped. A body left by `final ctl` is resumed with `Cancelled` and unwinds before the clause runs. A body whose `ctl` handler finished is cancelled then, and a later `resume` panics with the native message: `` `resume` called after its handler finished``. - An error that answers a forwarded request (the code around the handler is unwinding), or that a `fn` clause returns (natively, the clause runs on top of the body's stack), is delivered into the body first. Inner frames therefore unwind first, as natively. - **Actors.** A killed actor exits at once and keeps its fiber, which is resumed with `Killed` at its next turn, and again at each safe point, until it finishes. A failed `proc` operation (an unsendable message, `receive` on another actor's subject) panics in the actor, which unwinds and then exits. When `main` finishes, the remaining actors are unwound in pid order. The native runtime does the same, in the order of its run queue. ## Consequences - Cleanups run on normal exit, `final ctl`, panics, kills and cancellation, on both backends, with the leak oracle at 0 (`tests/run/defer.lse`, `defer_panic.lse`). - `resume` after its handler finished panics in the interpreter too (`tests/run/resume_escaped.lse`). - The interpreter's scheduling of killed actors now matches the native one more closely: their cleanups print in the same order. - Logging through a user `log` effect in a cleanup is not possible; cleanups use `io` directly. - A cleanup that must run to completion should be short and must not block. A kill cuts it short at its next safe point. - When `main` finishes, the order in which remaining actors run their cleanups is not specified (pid order in the interpreter, run-queue order natively). ## Alternatives considered - **`try { body } finally { cleanup }`.** It needs two keywords, `try` suggests a `catch` the language does not have, and it nests the protected code one level deeper. - **A library function `finally(cleanup, body)`** (Koka). The restriction on the cleanup's effects cannot be written in a signature without row constraints ("`e` lacks `ctl` effects"). - **Total cleanups.** Too weak: no logging, no closing sockets (see above). - **Cleanups with any effect.** Too many interacting cases for the control flow they would add (see above). - **Deferring kills until cleanups finish.** A cleanup that loops or blocks would make an actor unkillable.