| @@ -0,0 +1,81 @@ |
| 1 | +# ADR 0017: Multi-shot resumptions |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44). |
| 4 | + |
| 5 | +## Context |
| 6 | +Resumptions are one-shot ([ADR 0002](0002-memory-model.md)): a `ctl` clause calls `resume` at most once. Natively, a `ctl` handler's body runs on a fiber of its own ([ADR 0003](0003-effect-lowering.md) Revisions 1 and 2), and the continuation *is* that suspended fiber, so a second `resume` has nothing to continue. Nondeterminism and backtracking need several: collecting every result of a `choose` effect resumes each choice once per answer. |
| 7 | + |
| 8 | +Three things make this hard: |
| 9 | +- **C stacks cannot move.** Frames hold pointers into their own stack (saved frame pointers, addresses of locals), so a copy of a stack only works at the address it was taken from. |
| 10 | +- **Perceus ownership.** Every reference a suspended frame holds is owned once. Two copies of a stack own it twice, so each copy needs a reference of its own. Without stack maps, the runtime cannot find those references in a C stack. |
| 11 | +- **The interpreter** ran `handle` bodies on corosensei fibers too. A Rust stack cannot be copied either: its frames own heap memory. |
| 12 | + |
| 13 | +## Decision |
| 14 | + |
| 15 | +### Declared per operation: `multi ctl` |
| 16 | +``` |
| 17 | +effect amb { |
| 18 | + multi ctl choose() -> Bool |
| 19 | + final ctl fail() -> Never |
| 20 | +} |
| 21 | + |
| 22 | +fn all(action: fn() -> a / <amb | e>) -> List<a> / <e> { |
| 23 | + handle { [action()] } with { |
| 24 | + choose() -> list.append(resume(True), resume(False)), |
| 25 | + fail() -> [], |
| 26 | + } |
| 27 | +} |
| 28 | +``` |
| 29 | +- `multi` is a new keyword, in front of `ctl` like `final`. Its clause is typed like a `ctl` clause; its `resume` may be called any number of times. |
| 30 | +- Plain `ctl` stays one-shot, and stays the default: handlers whose effect has no `multi ctl` operation compile exactly as before. `fn` and `final ctl` operations are unchanged. |
| 31 | +- The kind is part of the effect's declaration, which the checker already reads at every handler and operation. Rows do not change. |
| 32 | + |
| 33 | +### Semantics |
| 34 | +- **Each `resume` runs a copy** of the rest of the handled computation, up to the handler (deep handlers, as for `ctl`). |
| 35 | +- **Values are immutable, so copies share them.** References (`Ref`) are shared too: a branch sees what an earlier branch wrote, as with any state outside the handler. A region the continuation is inside ends when the last copy leaves it. |
| 36 | +- **Cleanups** (`defer`, [ADR 0016](0016-defer.md)) run once per copy that leaves their scope. A continuation never resumed is cancelled when its handler finishes, so its cleanups run once, as for `ctl`. One resumed at least once is released then without running them: its copies did. A cleanup therefore runs `max(n, 1)` times for `n` resumes, on both backends, whatever the reference counts. |
| 37 | +- **Limits, checked on both backends with the same panics:** |
| 38 | + - a continuation that holds the body of another handler with `ctl` (or `multi ctl`) operations cannot be resumed: natively that body is a fiber of its own, which is not copied (`` a `multi ctl` continuation holding a `ctl` handler cannot be resumed ``); |
| 39 | + - `resume` panics while the handler's body runs (or waits on another handler's operation), because natively its stack is in use: `` `resume` called while its handler's body is running ``; |
| 40 | + - after the handler finished, as for `ctl`. |
| 41 | + |
| 42 | +### Native: stack snapshots at the same address, and a copying pass |
| 43 | +- `tl_handle_multi` runs the body on a fiber as `tl_handle_ctl` does, and `tl_perform_multi` suspends it. Each suspension is a *capture*. |
| 44 | +- **One stack, swapped in place.** The fiber's stack holds at most one capture, its *occupant*. Resuming another one first saves the occupant (copying the used part of the stack and the stack pointer), then writes the other back at the same addresses. Pointers into the stack stay valid. Saving and restoring move a capture; they do not change who owns its references. |
| 45 | +- **The last use runs the capture itself.** Perceus knows when `resume` is called for the last time: the closure is unique. Then the capture runs as it is, with no copy. `resume(a) ++ resume(b)` copies once, not twice. |
| 46 | +- **Otherwise, a copying pass.** The capture is saved, then resumed with `yielding = CLONE`. Generated code takes the same path as when it unwinds, frame by frame, but every release becomes a `dup` (`TL_UNWIND_DROP`). Each frame thus takes one more reference to everything it holds, then returns, and the fiber finishes. Writing the saved stack back gives a copy that owns those references and runs; the saved capture keeps its own. |
| 47 | + - **Why it is exact:** the unwinding paths release exactly what each frame holds; that is what makes unwinding leak-free today (ADR 0003 Revision 2, the leak oracle). |
| 48 | + - What else runs on that path is copy-aware: `tl_defer` takes a reference to the cleanup instead of running it, `tl_region_exit` counts the copy (the region ends when its last copy leaves), and a handler's capability is released through `TL_UNWIND_DROP`. |
| 49 | + - A reuse token (FBIP) held across the operation is now shared by the copies. A construction reuses a token only if it is still unique, which costs one comparison on the same header word. |
| 50 | + - Another handler fiber on the stack cannot take part: hence the limit above. The runtime counts the `ctl` handlers installed on each fiber, and refuses before anything is copied. |
| 51 | +- **When the handler finishes,** each capture left is materialised in turn and run in *cancel* mode (never resumed: cleanups run) or *discard* mode (`yielding = DISCARD`: references dropped, cleanups not run). |
| 52 | +- **Costs, paid only by multi-shot programs:** a copy costs two copies of the used stack (words, not `memcpy`, so AddressSanitizer does not check them against the frames' redzones) and one pass through the frames' unwinding code. The rest of the program pays: |
| 53 | + - one comparison per reference released on an unwinding path (`TL_UNWIND_DROP`), which only runs when unwinding; |
| 54 | + - one comparison when a `fn` or `final ctl` handler is left; |
| 55 | + - one comparison when a reuse token is used. |
| 56 | +- **Other targets:** snapshots need the runtime's own context switch ([ADR 0011](0011-context-switch.md)), x86_64 Linux for now. Elsewhere, a `resume` that needs to copy or restore a capture panics (`multi-shot resumptions are not supported on this target yet`); a single `resume` of each capture works. |
| 57 | + |
| 58 | +### The interpreter: an explicit continuation stack |
| 59 | +The interpreter becomes a CEK machine: the code being evaluated, the current function's variables, and a stack of frames for the rest of the computation (`crates/tilc_core/src/interp.rs`). |
| 60 | +- `handle` pushes a delimiter. A `ctl` operation moves the frames above its handler's into a continuation, and `resume` pushes them back; a `multi ctl` one copies them (`Vec::clone`: values are shared, as natively). |
| 61 | +- Unwinding pops frames, running cleanups and ending regions (ADR 0016's rules are unchanged). Region frames share a guard that ends the region when its last copy is gone. |
| 62 | +- Nothing recurses on the Rust stack, and the scheduler drives machines instead of corosensei fibers: `tilc_core` no longer depends on corosensei. |
| 63 | +- The limits above are checked from the frames (a delimiter of a handler with `ctl` operations inside the continuation; whether the handler's body is in use), with the native runtime's messages. |
| 64 | + |
| 65 | +## Consequences |
| 66 | +- `tests/run/multishot.til` collects every result of `choose`/`fail`, solves N-queens (4 and 6), and checks cleanups, shared references and cancellation, on both backends, with the leak oracle at 0, under ASan and UBSan too. `multishot_nested.til` and `multishot_running.til` check the limits. |
| 67 | +- Multi-shot cost is proportional to the depth of the stack between the handler and the operation, per copy: fine for search, expensive for deep recursion inside the handler. |
| 68 | +- Native and interpreter agree on every observable difference between copying and moving (cleanups run `max(n, 1)` times), so the differential tests stay exact. |
| 69 | +- A program that resumes captures in an order other than last-in first-out swaps stacks; AddressSanitizer may then report false positives, because the shadow state of the stack is not swapped (the tests resume in LIFO order). |
| 70 | +- Benchmarks: see the Results section (`scripts/bench.sh`). |
| 71 | + |
| 72 | +## Alternatives considered |
| 73 | +- **Re-execution (replay).** Run the body again from the start, answering its operations from a log, to recreate a continuation. Simple with Perceus (nothing is copied), but anything the body did outside its handler (`io`, `ffi`, references, messages) runs again unless it is logged, and natively externs cannot be intercepted. Rejected. |
| 74 | +- **Copying stacks to another address.** Breaks pointers into the stack. |
| 75 | +- **Conservative scanning for references.** Not exact: a stale word that looks like a pointer would be counted. |
| 76 | +- **Koka-style continuation capture** (each frame builds a closure of its live variables when an operation yields), ADR 0003's planned path for wasm and JS (M6). It supports multi-shot naturally, but every function that can be in a continuation needs the extra code: a large change to the C backend. The copying pass reuses the unwinding code that exists. M6 can still choose capture for the client target; the semantics above (copies, shared references, `max(n, 1)` cleanups) do not depend on the mechanism. |
| 77 | +- **Inferring multi-shot instead of declaring it.** It would need effect-kind polymorphism in rows, and would make one-shot handlers pay for a possibility. |
| 78 | +- **An interpreter that replays, keeping corosensei fibers.** Less change, but its correctness rests on the body being deterministic given a log of everything it observes. The machine is the textbook semantics and needs no such argument. |
| 79 | + |
| 80 | +## Results |
| 81 | +See below (filled in with `scripts/bench.sh`). |