| @@ -0,0 +1,74 @@ |
| 1 | +# ADR 0016: User-level cleanups: `defer` |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44). |
| 4 | + |
| 5 | +## Context |
| 6 | +[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): |
| 7 | +- a `final ctl` operation, unwinding to its handler; |
| 8 | +- a panic, unwinding to the actor's root; |
| 9 | +- a kill, delivered at the actor's next safe point; |
| 10 | +- the cancellation of a `ctl` handler body that is never resumed (the handler finished first). |
| 11 | + |
| 12 | +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. |
| 13 | + |
| 14 | +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). |
| 15 | + |
| 16 | +## Decision |
| 17 | + |
| 18 | +### Syntax: a `defer` statement |
| 19 | +``` |
| 20 | +fn serve(conn) -> () / <io> { |
| 21 | + defer net.close(conn) |
| 22 | + handle_requests(conn) |
| 23 | +} |
| 24 | +``` |
| 25 | +- `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`. |
| 26 | +- Several `defer`s in a block run in reverse order: each protects the statements after it. |
| 27 | +- 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. |
| 28 | +- `defer` is a new keyword. It follows Go, Swift and Zig, and the existing `use` statement, which also takes the rest of the block. |
| 29 | + |
| 30 | +### A cleanup's effects: only those that cannot unwind or suspend |
| 31 | +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: |
| 32 | +- an effect without operations: `io`, `ffi`; |
| 33 | +- or a region's `st` or `alloc`, whose operations are handled by the runtime and never unwind. |
| 34 | + |
| 35 | +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. |
| 36 | + |
| 37 | +**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. |
| 38 | + |
| 39 | +**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. |
| 40 | + |
| 41 | +**Panics stay possible.** Arithmetic can overflow anywhere, so a cleanup can always panic. |
| 42 | + |
| 43 | +### What happens while a cleanup runs |
| 44 | +- 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. |
| 45 | +- **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. |
| 46 | +- **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. |
| 47 | +- **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. |
| 48 | + |
| 49 | +### Native lowering |
| 50 | +- Core gets `Defer { body, cleanup }`: two closures. HIR lowering turns `defer c; rest` into it, with `rest` as the body. |
| 51 | +- 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. |
| 52 | +- `tilrt`'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. |
| 53 | +- Cost: one closure for the rest of the block and one for the cleanup, and two calls. Code without `defer` is unchanged. |
| 54 | + |
| 55 | +### The interpreter unwinds like the native backend |
| 56 | +- 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`. |
| 57 | +- 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``. |
| 58 | +- 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. |
| 59 | +- **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. |
| 60 | + |
| 61 | +## Consequences |
| 62 | +- Cleanups run on normal exit, `final ctl`, panics, kills and cancellation, on both backends, with the leak oracle at 0 (`tests/run/defer.til`, `defer_panic.til`). |
| 63 | +- `resume` after its handler finished panics in the interpreter too (`tests/run/resume_escaped.til`). |
| 64 | +- The interpreter's scheduling of killed actors now matches the native one more closely: their cleanups print in the same order. |
| 65 | +- Logging through a user `log` effect in a cleanup is not possible; cleanups use `io` directly. |
| 66 | +- A cleanup that must run to completion should be short and must not block. A kill cuts it short at its next safe point. |
| 67 | +- When `main` finishes, the order in which remaining actors run their cleanups is not specified (pid order in the interpreter, run-queue order natively). |
| 68 | + |
| 69 | +## Alternatives considered |
| 70 | +- **`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. |
| 71 | +- **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"). |
| 72 | +- **Total cleanups.** Too weak: no logging, no closing sockets (see above). |
| 73 | +- **Cleanups with any effect.** Too many interacting cases for the control flow they would add (see above). |
| 74 | +- **Deferring kills until cleanups finish.** A cleanup that loops or blocks would make an actor unkillable. |