tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

98 lignes · 13421 octetsBrut · Historique

ADR 0017: Multi-shot resumptions

Status: Accepted by the project owner on 2026-10-12; proposed 2026-10-09 (issue #49, v1 milestone M5); needs engineering review (#44).

Context

Resumptions are one-shot (ADR 0002): a ctl clause calls resume at most once. Natively, a ctl handler's body runs on a fiber of its own (ADR 0003 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.

Three things make this hard:

  • 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.
  • 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.
  • The interpreter ran handle bodies on corosensei fibers too. A Rust stack cannot be copied either: its frames own heap memory.

Decision

Declared per operation: multi ctl

effect amb {
  multi ctl choose() -> Bool
  final ctl fail() -> Never
}

fn all(action: fn() -> a / <amb | e>) -> List<a> / <e> {
  handle { [action()] } with {
    choose() -> list.append(resume(True), resume(False)),
    fail() -> [],
  }
}
  • 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.
  • 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.
  • The kind is part of the effect's declaration, which the checker already reads at every handler and operation. Rows do not change.

Semantics

  • Each resume runs a copy of the rest of the handled computation, up to the handler (deep handlers, as for ctl).
  • 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.
  • Cleanups (defer, ADR 0016) 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.
  • Limits, checked on both backends with the same panics:
    • 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);
    • 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;
    • after the handler finished, as for ctl.

Native: stack snapshots at the same address, and a copying pass

  • tl_handle_multi runs the body on a fiber as tl_handle_ctl does; it is also given which operations are multi ctl (a mask), and tl_perform_ctl suspends the body as before. Each suspension is a capture.
  • 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.
  • 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.
  • 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.
    • 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).
    • 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.
    • 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.
    • 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.
  • 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).
  • Snapshot-safe stack reclamation. Finished coroutines' mappings may be pooled by size. A one-shot mapping is reusable only after normal or cancellation-driven Return (a suspended body must first be run out). A normally returned multi-shot coroutine is not immediately reusable: saved captures can still restore its old addresses. Its mapping leaves the frame only at the final finish, once the occupant is gone, every capture is Gone (dropping every saved snapshot), every cancel/discard drive has returned, and cancelled excludes future resume access. Generic frame destruction does not pool mappings: escaped resume closures may retain that frame, and its suspended-fiber leak fallback remains unchanged. A returned coroutine alone therefore never proves mapping reuse safe.
    • Each scheduler Shared has one handler-only pool, separate from the actor size class. Its nominal policy is 16 warm + 48 cold = 64 retained 16 MiB mappings. Cold insertion runs MADV_DONTNEED; insertion past the cap drops and unmaps. Length checks and insertion are separate so madvise/munmap never run under the pool lock. Consequently, a drain with no acquisitions on T scheduler threads has the loose bounds 64 + T - 1 total and 16 + T - 1 warm, not an exact 64/16 under every schedule. Ordinary non-process Shared drop unmaps every retained entry; the existing whole-program exit path intentionally leaves teardown to process exit.
    • Parked-actor hibernation does not age or release pool entries. The pool's VmSize contribution is committed-lazily address space, not host-sized allocation or resident memory. On 4 KiB-page Linux, one 16 MiB request's guard, colouring and alignment make its exact Stack::new map 19,011,584 bytes (18.131 MiB), so 64 entries account for about 1.133 GiB of VA. This byte count is not portable to aarch64 kernels configured for 16 or 64 KiB pages. Warm entries keep touched pages in RSS; cold entries retain VA but release their pages/page tables. Evidence for issue #329 must therefore inspect a specific process's live maps and per-mapping RSS at rendezvous points, including an in-process drain/refill, rather than infer either number from syscall counts or whole-process VmSize alone.
  • 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:
    • unwinding paths release references through a call (tl_unwind_drop) instead of an inline drop: smaller code, slower only while unwinding;
    • the same call when a fn or final ctl handler is left (its capability);
    • one comparison when a reuse token is used.
  • One-shot ctl keeps its path. Its operations are performed with tl_perform_ctl as before (tl_handle_multi gets a mask of the multi ctl operations instead). While at it, a resume that returns into its clause (x + resume(())) now nests less stack per operation: resume_code, drive and call_clause end in tail calls (208 bytes per level instead of 272).
  • Other targets: snapshots need the runtime's own context switch (ADR 0011), 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.

The interpreter: an explicit continuation stack

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/louise_interp/src/lib.rs).

  • 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).
  • 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.
  • Nothing recurses on the Rust stack, and the scheduler drives machines instead of corosensei fibers: louise_core no longer depends on corosensei.
  • 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.

Consequences

  • tests/run/multishot.lse 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.lse and multishot_running.lse check the limits.
  • 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.
  • Native and interpreter agree on every observable difference between copying and moving (cleanups run max(n, 1) times), so the differential tests stay exact.
  • 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).
  • Benchmarks: no regression (see Results).

Alternatives considered

  • 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.
  • Copying stacks to another address. Breaks pointers into the stack.
  • Conservative scanning for references. Not exact: a stale word that looks like a pointer would be counted.
  • 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.
  • 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.
  • 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.

Results

tests/bench, release builds, CPU time (user + system), best of 21 runs interleaved between main (f2b02b7) and this branch, one scheduler thread, on a shared machine (load around 8; differences within ±3% are noise). effects is also split into its two halves.

Benchmarkmain (ms)this branch (ms)Change
arith54.555.1+1.0%
dict178.5181.7+1.8%
effects57.248.7−14.9%
effects, fn operations only31.229.9−4.1%
effects, ctl generator only26.818.3−31.7%
html305.2285.9−6.3%
lists231.4221.7−4.2%
messages64.163.6−0.8%

With 4 threads: messages −1.5%, lists −2.0%. The generator's gain is the shallower nesting of resume (less stack touched: 47 MB instead of 69 MB of peak memory for 200,000 nested resumptions). scripts/bench.sh (wall time, all threads) gave the same picture, with ±20% noise between identical runs.