# Runtime ABI The contract between C emitted by `louise` and the Rust runtime `louise_rt`. It covers value representation, heap layout, the execution context, calling conventions, unwinding, and what the runtime does for actors, handlers and the standard library. - **Normative source:** [`runtime/louise_rt/include/louise_rt.h`](../runtime/louise_rt/include/louise_rt.h). This document explains it. The header says which part C bindings may use; the rest is for generated code. - **Names:** the header was `tilrt.h` before the language was renamed Louise ([ADR 0021](adr/0021-the-name-louise.md)). Its declarations kept their `tl_`/`TL_` names: bindings need only the new include. - **Rust mirror:** `runtime/louise_rt/src/abi.rs` mirrors the layouts. Both sides assert them at compile time. - **Version:** `TL_ABI_VERSION` is **11**. Generated `main` calls `tl_abi_check(TL_ABI_VERSION)` first, and a runtime built for another version stops with a message. - **Change rule:** change the header and `abi.rs` together, and bump `TL_ABI_VERSION` when a layout or a calling convention changes. - **Targets:** 64-bit only (x86_64 and aarch64 Linux first). The sections below describe the ABI as the code implements it. How it got there, and which decisions superseded which, is in [History](#history). Rationale lives in the ADRs. ## Status The ADRs are the source of truth for statuses ([`docs/adr/README.md`](adr/README.md)); where this document and an ADR differ, the ADR wins. | Part | Decided in | Status | |---|---|---| | Values, heap blocks, the context, reference counting, yield-bubbling unwinding, preemption | ABI v0 and Revision 1; ADRs 0002–0004 | Accepted 2026-10-08 (issue #2) | | Unwinding by yield checks rather than tables | ADR 0003, Revision 2 | Accepted by the project owner; needs engineering review (#44) | | `ctl` handlers on fibers, the runtime's context switch | ADRs 0010, 0011 | Accepted by the project owner; needs engineering review (#44) | | Multi-threaded scheduler, sending, timers, real time with sockets | ADR 0004, Revisions 1–5 | Accepted by the project owner; needs engineering review (#2, #44) | | Extern convention, blocking pool, resources | ADR 0005, Revision 1 | Accepted by the project owner; needs engineering review (#44) | | Blocking pools (`cpu`, `io`) and their statistics | ADR 0005, Revision 2 | Proposed; needs engineering review (#44) | | OS signals, `Shutdown`, draining | ADR 0060; ADR 0004, Revision 7 | Proposed; needs engineering review (#44) | | Perceus optimisations | ADR 0002, Implementation (v1) | Accepted by the project owner; needs engineering review (#44) | | `Bytes`, builders, HTTP | ADR 0012 and its Revision 1 | Accepted by the project owner; needs engineering review (#44) | | Arrays, owned externs, big integers (ABI version 2) | ADR 0014 | Accepted by the project owner; needs engineering review (#44) | | Bit operations, `U64` (ABI version 5) | ADR 0035 | Proposed; needs engineering review (#44) | | `Dec` (`TL_TAG_DEC`, ABI version 11) | ADR 0070 | Proposed; needs engineering review (#44) | | Root capabilities for `clock` and `random` (ABI version 6) | ADR 0036 | Proposed; needs engineering review (#44) | | Contexts of tail recursion modulo cons (ABI version 7) | ADR 0039 | Proposed; needs engineering review (#44) | | Reuse tokens' kept fields (`TL_FLAG_TOKEN`, ABI version 8) | ADR 0040, Revision 2 | Proposed; needs engineering review (#44) | | Borrowed closures (ABI version 10) | ADR 0068 | Proposed; needs engineering review (#44) | | TLS clients and servers (`tls.rs`, no layout change) | ADR 0038 | Proposed; needs security and engineering review (#44) | | Callbacks from C | ADR 0015 | Accepted by the project owner; needs engineering review (#44) | | `defer`, multi-shot continuations | ADRs 0016, 0017 | Accepted by the project owner; needs engineering review (#44) | | Console output on a writer thread | ADR 0022 | Accepted by the project owner (PR #90); needs engineering review (#44) | | `#line` directives in generated C | issue #35 | Accepted by the project owner; needs engineering review (#44) | ## Values A `tl_value` is one machine word: | Low bit | Meaning | |---|---| | `1` | 63-bit signed small int: `n << 1 \| 1`. Also used for `Bool` (0/1), `()` (0), and **nullary constructors**, which are encoded as their constructor index. | | `0` | Pointer to an 8-byte aligned heap block. | **An `Int` is a small int or a `TL_TAG_BIGINT` block.** A value in the 63-bit range is always small (canonical form), so word equality decides every comparison with a small int, and a `switch` on an integer literal needs no special case. See [Big integers](#big-integers). ## Heap blocks ``` +-----------------------------+--------------------------------+-------------+ | header (8 bytes) | scanned fields: tl_value[n] | raw bytes | | rc:i32 tag:u16 scan:u8 fl:u8| | (by tag) | +-----------------------------+--------------------------------+-------------+ ``` **`rc`, the reference count:** - `> 0` means a local count, with `1` meaning unique. - `< 0` means *shared*: reachable from more than one actor. The count is `-rc` and is updated atomically. - `0` means *immortal*: a static literal (strings, floats) or a constant dictionary. `tl_dup`, `tl_drop`, `send` and the runtime leave it alone, and nothing may write to it (it may live in read-only memory). - An object only ever moves from local to shared, never back. That makes a plain load enough to test the sign. - **A count saturates instead of overflowing** (issue #217). A local count stops at `TL_RC_STUCK` (`INT32_MAX`): `tl_dup` and `tl_drop` leave it there, and the block is never freed. A shared count that reaches −2^29 is held at −2^30: every atomic dup or drop that sees it there puts it back, so the dups and drops other threads have in flight never bring it to −1 nor wrap it, without a compare-and-swap loop. Either way a bounded leak replaces a use after free, and the runtime says so once on stderr. A saturated block is not made immortal: immortal blocks are shared between actors as they are, and this one may hold counted children. The check costs one instruction in `tl_dup` and `tl_drop`: on 2026-10-27, `tests/bench`'s reference-counting programs ran 0.6% (`lists`) to 3.9% (`records`) more instructions, and their cycles stayed within run-to-run noise (±2%). **`tag`:** - Values below `0xFF00` are user constructor indices. User constructors have **no raw area**; every field is a `tl_value`. - Values from `0xFF00` up are runtime kinds. Each kind defines the size of its raw area: | Kind | Scanned fields | Raw area | |---|---|---| | `STRING` | 0 | `i64 len`, `len` UTF-8 bytes, NUL | | `BYTES` | 0 | `i64 len`, `len` bytes | | `FLOAT` | 0 | `double` | | `CLOSURE` | captured env | code pointer (`tl_closure_fn`) | | `REF` | 1 (the cell) | — | | `REGION` | 0 | runtime-private: the references made in the region | | `FRAME` | 0 | runtime-private: a running `ctl` handler | | `RESOURCE` | 0 | `void *ptr`, then its finalizer | | `CAP` | a handler's clauses, then its marker | — | | `ARRAY` | `TL_SCAN_LARGE`: the count, then the elements | `i64 spare`, then `spare` unused slots ([Arrays](#arrays-and-owned-externs)) | | `BIGINT` | 0 | `i64 len` (`\|len\|` limbs, the sign of the number), then `uint64` limbs, least significant first | | `BUILDER` | 0 | `i64 len`, `i64 cap`, then `cap` bytes (the first `len` used): `bytes.Builder` | | `U64` | 0 | `uint64` (`std/u64`, ADR 0035) | | `DEC` | 0 | `uint64` × 2: a `Dec`'s `i128` limbs, lo first (8-byte alignment), 10^18-scaled (`std/dec`, ADR 0070) | **`scan_fsize`:** the number of scanned fields. `0xFF` (`TL_SCAN_LARGE`) is reserved for arrays: `fields[0]` then holds the count. Only the runtime allocates such blocks; `tl_alloc` refuses it. **Why blocks describe themselves:** drop, the move/share/copy walk of `send` and debugging can walk any value without type information. **`flags`:** `PINNED` marks a value that must not be copied to another actor, such as a resource that is not thread-safe. **Allocation** (`runtime/louise_rt/src/heap.rs`): every block is allocated by `tl_alloc` (or by the runtime, the same way) and freed by `tl_free` or the drop worklist. - Blocks come from **mimalloc**, called directly, when `louise_rt` is built with its `mimalloc` feature (the default). Without it they come from the system allocator. Only blocks change allocator; the runtime's own Rust allocations use Rust's global allocator either way. - A block may be freed on another thread than the one that allocated it: actors move between scheduler threads, and messages move between actors. Both allocators allow this. - **Sanitizers:** ASan only sees memory from `malloc`, so a program built with `-fsanitize=address` must link a runtime built without mimalloc: `cargo build -p louise_rt --no-default-features --features stats,tls,crypto --target-dir target/sanitize`, then `LOUISE_LIB_DIR=target/sanitize/debug`. The asan workflow (`.toboggan/workflows/asan.yml`) does this (and `scripts/spike.sh --asan` for the spike, which needs neither TLS nor crypto). With mimalloc, ASan misses errors on blocks (a use-after-free of a block goes unreported) instead of reporting false ones. ThreadSanitizer needs an instrumented runtime and standard library (nightly `-Zbuild-std`), and C built without TSan's function entry/exit hooks, which `musttail` loops overflow: `scripts/tsan.sh` does both (ADR 0004, Revision 5). ## Execution context ```c typedef struct tl_ctx { int32_t yielding; // tl_yield_kind int32_t reductions; // preemption budget uint64_t yield_marker; // FINAL: target handler tl_value yield_value; // owned payload / reason void *evv; // unused (null): handlers are values (ADR 0010) void *rt; // runtime-private: the owning actor tl_value *xargs; // call arguments after the sixth (123 slots) } tl_ctx; ``` **Ownership and placement:** - There is **one context per actor**, passed as the first argument of every generated function. - It is never stored in thread-local storage. An actor may resume on another OS thread after any suspension, and C compilers may cache TLS addresses across calls, which breaks when a fiber resumes on another thread. The runtime's own thread-locals follow the same rule (`Fiber` in `louise_rt/src/sched.rs`). ## Calling convention **One signature.** Every generated function is a `tl_fn`: `tl_value f(tl_ctx *ctx, tl_value a0, ..., tl_value a5)`. Arguments after the sixth go to `ctx->xargs` (123 slots), and the callee copies them on entry. One signature is what allows `musttail` on every tail call. A function takes up to 128 parameters: a call through a closure passes the closure first, so the slots hold one value more (ABI 12, issue #434). **Unboxed-float workers** (ADR 0045, issue #190). A function whose parameters and result are known `Float` (lowering records which, in `FnDecl::unbox_sig`) gets a second emission next to its wrapper: a worker `f$uf` taking the marked parameters and returning the result as raw `double`s, the body's float arithmetic raw. A boxed operand is unboxed in place (`tl_float_get`); a raw value escaping into data or an unknown call is boxed at the boundary (`tl_float_from`); a worker's self-recursion stays raw. Direct callers cross the boundary once per call; closures and unknown callers use the wrapper. Workers are internal to generated code — the runtime's value representation is unchanged — so the ABI version does not change. `LOUISE_NO_FLOAT_UNBOX` turns them off. **Unboxed-int workers** (ADR 0045, Revision 2). The same for known `Int`: a worker `f$ui` on raw `int64_t`s. Because a raw result can leave the 63-bit small range (where Louise promotes to a big integer), the worker checks each add/subtract/multiply and returns `TL_INT_BAIL` on overflow — division and remainder also bail where the boxed path would panic or promote — and the direct caller recomputes the whole call with the boxed wrapper. Only functions safe to re-run (fusion's purity gate) get one, and the boundary calls the worker only for immediate or range-proven-small arguments (a boxed `Int` may be a big integer). `LOUISE_NO_UNBOX_INTS` turns them off. **Record workers** (ADR 0069, issue #337). The same split for a monomorphic function whose parameters or result have a single known constructor (a record, a one-constructor type, a tuple): the worker `f$ur` takes the marked constructors' *fields* as one C parameter each (bounded at 32 values, the convention's bound before ABI 12; wider stays boxed) and returns a small result's fields as a bare `tl_value` (one) or a `tl_pair{n}` struct (two to four). Every field of a user constructor is a `tl_value`, so this is placement, not representation: the runtime's value encoding and the ABI version are unchanged. A construction that never escapes is never allocated (its fields are locals); an escape rebuilds the box (`tl_alloc`); a consumed box's fields are moved out with `tl_unbox_fields` (prelude). A flat value's `release` moves the bound fields and makes a unit token, so the FBIP release/rebuild loop flattens to field moves. `LOUISE_NO_UNBOX_RECORDS` turns them off. **`xargs` belongs to the thread** (ABI 3, ADR 0028). The scheduler points `ctx->xargs` at the running thread's 123 slots each time an actor resumes. This is safe because nothing suspends, and no generated code runs, between a caller's stores and the callee's copy: generated functions copy before their preemption check, and the runtime's callers (`call_closure`, effect clauses, callbacks) call straight into generated code. The one exception, a `ctl` clause's call (`handlers.rs`), drops the operation's payload in between: freeing runs no Louise code (a suspended handler fiber is leaked, not resumed, and a resource's finalizer is C that must not touch Louise values). Checked builds verify it: the runtime poisons the slots at each slice, and a callee that copies a poisoned slot aborts (`TL_XARG`, issue #217). Until ABI 2 the slots were part of the context: 208 of the 336 bytes of every actor. **Ownership:** - Every function returns a `tl_value`, owned by the caller. - Parameters are **owned** by default. The callee must consume them: drop them, store them, or pass them on. - For *direct* calls only, Perceus may make a parameter *borrowed* ([Borrowed parameters](#borrowed-parameters)). - **Externs borrow.** Functions declared `@extern`, and the runtime functions generated code calls, borrow their arguments and return owned results, unless declared `owned` ([Arrays and owned externs](#arrays-and-owned-externs)). **Closures:** - A closure block carries **two code pointers** (ABI 10, [ADR 0068](adr/0068-borrowed-closures.md)): the owned entry and the borrowed entry (`tl_closure_code_borrowed` reads the second). `tl_closure_alloc` takes both. - The **owned entry** is called with owned arguments, **including `self`**, which closure code receives as its first value. The runtime's own calls (`call_closure`: spawns, `defer` cleanups, handler bodies, C callbacks) always use it. - The **borrowed entry** neither drops nor consumes `self` or the arguments — the caller keeps its references and drops them when the call returns (on the unwinding path included). Generated non-tail closure calls use it, as do `fn` operations on user handlers and `final ctl` clauses (`tl_call_payload_borrowed`). Tail calls consume, as before: a `musttail` cannot drop after itself. - Runtime-made closures (root-capability clauses, a `multi ctl` `resume`) fill the borrowed slot with a per-arity adapter (`tl_borrowed0`/`1`/`2`) that dups `self` and the arguments for the owned entry. - The code pointer is cast to its exact arity first, e.g. `tl_value (*)(tl_ctx*, tl_value self, tl_value a)`. A variadic pointer type is never used. **Tail calls:** a self tail call is a `goto`; every other tail call is emitted with `musttail`. **Entry functions** (`main`, a test) receive the actor's root `proc` capability, then the unit argument: `fn() -> T` is `fn(()) -> T` at every ABI (ADR 0062), and a parameterless function, lambda, handler body or `defer` cleanup takes one. A zero-parameter `@extern`'s C shim is the exception: it sees its declared arguments only; when an entry function borrows it, `tl_entry` drops it after the call. `tl_entry` selects the entry by `tl_which`, which generated `main` reads from the environment variable `LOUISE_ENTRY` (unset means 0). Only `louise test --native` sets it, to pick the test; an environment variable cannot collide with the program's own arguments (issue #287). Generated code never reads argv: the process's arguments are entirely the program's own, and `os.args` (std/os) reports all of them. ## Reference counting `tl_dup` and `tl_drop` are inline, and leave immortal blocks (`rc == 0`) alone without a call. Only the following go out of line: | Function | When it is called | |---|---| | `tl_drop_slow` | The count reaches zero, or the block is shared. | | `tl_dup_shared` | A block is shared. | | `tl_free` | Perceus has moved a unique cell's children out (drop specialisation). | **Freeing is iterative.** Dead blocks go onto a per-actor worklist, so dropping a million-element list never recurses. This is essential on fiber stacks. **It is also done in steps** (issue #158, ADR 0002): a drop frees at most 4,096 blocks and sets `reductions` to 0, so the actor's next function entry calls `tl_preempt`. Freeing continues each time the actor is preempted or woken, and before it ends. Arrays of more than 4,096 elements are released from their end, 65,536 elements per step. Code that needs every block freed (the leak oracle mid-program, as the spike does) yields until `tl_stats_live_blocks()` is back to what it expects. **Leak oracle:** with the `stats` feature (on by default), `tl_stats_live_blocks()` counts live blocks, and `LOUISE_LEAKS` makes `tl_report_leaks` print it at exit. Tests require 0. The `fast` and `lto` runtimes that release builds link (ADR 0031, ADR 0032) are built without `stats`: `tl_stats_live_blocks()` returns −1, and `LOUISE_LEAKS` prints `live blocks: unknown` with a pointer to `LOUISE_RUNTIME=checked`. **Allocation counter:** the same per-thread counts give the blocks ever allocated: `tl_stats_allocations()` sums them, and `LOUISE_STATS` makes `tl_report_leaks` print `louise: allocs: N` at exit (−1, printed as `unknown`, without `stats`). It is how a change's allocations per request are measured: run with the checked runtime and divide by the requests served. ### Perceus optimisations (v1, issue #34; proposed, needs engineering review) These change what generated code does with counts, not the layouts. Rationale and measurements: [ADR 0002, Implementation (v1)](adr/0002-memory-model.md#implementation-v1--2026-10-09). #### Borrowed parameters - A function called only directly (never made into a closure) may *borrow* some parameters: `FnDecl::borrowed` in Core, decided by `louise_perceus` and printed `^v` in Core printed after Perceus (its test snapshots; `louise core` prints Core before Perceus runs, so without it). - The caller keeps its reference across the call and releases it as usual afterwards. The callee must neither drop nor consume a borrowed parameter: to store it, return it or pass it to an owned position it takes a `dup` first. - A borrowed parameter is not one of the frame's references: unwinding (preemption, panics, exit signals, `final ctl`) does not drop it. - The C signature is unchanged (`tl_fn`); only the ownership of the argument differs. A self tail call (`goto entry`) passes borrowed arguments in borrowed parameters. - Closures, effect clauses, externs and runtime functions keep their conventions (owned for closures and clauses, borrowed for externs). - **Projections borrow.** In Core after Perceus, `let a = x.i` reads the field without a `dup` (C: `a = tl_as_block(x)->fields[i]`); a `dup a` follows when `a` must be owned. A projection of a borrowed value stays borrowed, so a borrowed structure is walked without counting. #### Drop specialisation and reuse `release x [i: a, ...]` (Core `Expr::Release`) ends `x`'s reference after its fields `a`, ... were projected: ```c if (tl_is_unique(x)) { tl_as_block(x)->fields[i] = TL_UNIT; /* moved out to a, ... */ tl_free_moved(ctx, tl_as_block(x), moved); /* tl_free, or tl_drop_slow if other fields remain */ } else { tl_dup(a); ... tl_drop(ctx, x); } ``` With reuse (`release x [...] reuse as t`), the unique branch keeps the cell instead, `t = tl_reuse_token(ctx, b)`: its remaining fields are dropped and every field is unit, so a token is an ordinary owned value (a unique block of units, or `TL_UNIT`) and dropping it is safe. A later `reuse t in C(...)` (Core `Value::Reuse`) writes the cell in place when `t` is a block with as many fields as `C`, rewriting its header in one 8-byte store (`tl_reuse_header`: unique, `C`'s tag and size, no flags); otherwise it drops `t` and allocates. A `reuse t sized in C(...)` skips the size test: Core knows the matched cell has exactly `C`'s fields (ADR 0040), so only uniqueness is tested. Tokens are only taken from values a `switch` matched (user constructor cells: no raw area, flags 0); `tl_reuse_token` frees a runtime block instead. `tl_free_moved` and `tl_reuse_token` are inline helpers in the generated prelude. **Kept fields** (ADR 0040, Revision 2; issue #193; runtime ABI 8): a sized reuse whose field `i` receives the value the release moved out of slot `i` neither clears the slot at the release nor rewrites it at the reuse (a record update writes one field, not all of them). The release then prepares the token with `tl_reuse_token_kept(ctx, b, keep0, keep1)` (a prelude inline: drops the rest, sets the mask's bits) and flags the cell `TL_FLAG_TOKEN`; a token dropped unused is freed by `tl_drop_slow`/`free_block` without touching its fields — they are dead: the values are owned by the bindings they were moved to. `tl_reuse_header`'s whole-header store clears the flag, so a reused cell is ordinary. `LOUISE_NO_KEPT_REUSE` turns it off. #### Constant dictionaries A trait dictionary without constraints (`Num`) is emitted as `static const` immortal blocks: a tuple (`tag` 0) of closures without captures (`TL_TAG_CLOSURE`, `scan_fsize` 0, the code pointer in the raw area). Since issue #61, the C backend calls the methods of such dictionaries directly, or inlines them, and specialises functions for them ([ADR 0013](adr/0013-numeric-code.md)); the dictionaries remain for the calls it cannot resolve. ## Unwinding Several things abort part of an actor's stack. All of them use **yield-bubbling** (ADR 0003, Revision 2): no unwind tables, no `-fexceptions`. | `yielding` | Cause | Stopped by | |---|---|---| | `FINAL` | a `final ctl` op (`tl_yield_final`) | the handler frame whose marker matches (`tl_catch_final`) | | `PANIC` | a division by zero, a failed match, or `panic` (`tl_panic`, `tl_panic_str`) | the actor root, where the actor crashes | | `KILL` | an exit signal delivered at a safe point | the actor root | | `CANCEL` | a suspended `ctl` handler body that will never be resumed | the handler (`tl_handle_ctl`) | Two more values are passes over a suspended `multi ctl` continuation, not unwindings the program can observe ([Multi-shot continuations](#multi-shot-continuations)): `CLONE` and `DISCARD`. **Protocol:** 1. The operation sets `ctx->yielding` (and the payload), then returns `TL_UNIT`. 2. After every call that may unwind, generated code tests `TL_YIELDING(ctx)`. If it is set, the code drops its owned references (with `TL_UNWIND_DROP`) and returns `TL_UNIT`. 3. A handler frame calls `tl_catch_final(ctx, marker, &payload)` after its body. If that returns true, unwinding stops there and the clause runs. A handler capability stores the handler's marker after its clauses; `final ctl` yields a payload (the operation's index, then its arguments) to that marker. 4. Return values produced while unwinding are always `TL_UNIT`, so dropping them is a no-op. 5. `tl_main_program` reports a panic of `main` as `error: panic: `, with exit code 101. **Which calls need the check.** Panics and kills unwind through *any* frame, so the check is needed after every call except to a callee proven never to unwind. A callee qualifies only if all three hold: - it has no `TL_ENTER`, - it has no operation that can panic, - every call it makes is itself to a never-unwinding function. In practice that means small leaf functions, which are inlining candidates anyway. Since issue #61 the C backend finds them (`louise_codegen_c/src/unwind.rs`, ADR 0003's implementation note): their calls have no check, and they have no preemption point. Effect rows alone cannot drop the check. **Externs.** The backend checks `yielding` after every extern outside the runtime, so a binding's shim may panic with `tl_panic_str` (not in a `blocking` extern). The prefix `tl_` is reserved for the runtime, whose functions are listed, with whether they may unwind, in `louise_core::externs` ([Adding a runtime extern](#adding-a-runtime-extern)). **Cost of the check:** one load, one compare and one predicted branch per call. The drop paths add code size, not time. The compiler emits the checks in Core *before* Perceus runs ([ADR 0003](adr/0003-effect-lowering.md)), so Perceus computes the drops on the unwinding path the same way as on any other path. **Cleanups (`defer`, [ADR 0016](adr/0016-defer.md)).** Generated code calls the body closure, then `tl_defer(ctx, result, cleanup)`, which consumes both: - it saves `yielding`, `yield_marker` and `yield_value`, clears them, and calls the cleanup; - if the cleanup unwinds (a panic, or a kill at one of its safe points), that unwinding continues: the saved payload and `result` are dropped, and it returns unit; - otherwise it restores the saved state and returns `result`. The yield check after the call continues any unwinding. Cancelling a `ctl` body follows the same rule: if the cancelled code ends with a panic or a kill instead of `CANCEL`, that unwinding replaces the caller's, and `tl_handle_ctl` returns unit. ## Preemption and exit signals `TL_ENTER(ctx, label)` appears at the entries of functions that can reach themselves (ADR 0046, piece 2: alone or through a recursive group — that is, at every loop, since a loop is a self tail call re-entering through `goto entry`): 1. It decrements `ctx->reductions`. 2. When the budget is spent, it calls `tl_preempt`, which suspends the actor's fiber back to the scheduler. The budget is 2,000 entries (`REDUCTIONS`), refreshed whenever the actor is scheduled and at every `proc` operation. 3. A pending exit signal is turned into `yielding = KILL` on resume, and the code jumps to `label`, which drops the owned locals. The yielding test sits on the slow path, so the fast path is a decrement and a branch. A loop that makes no calls is therefore still preemptible and killable. ## Effect handlers - **Handler capabilities** ([ADR 0010](adr/0010-lexical-handlers.md)) are ordinary `CAP` blocks holding the clause closures, then the handler's marker. A `fn` operation calls its clause directly. - **`ctl` handlers** (`louise_rt/src/handlers.rs`) use stack switching: - `tl_handle_ctl` runs the body on a fiber of its own (a lazily committed 16 MiB stack); - a scheduler `Shared` keeps a separate pool of returned handler mappings, nominally 16 warm and 64 total. Entries beyond the warm threshold are cold-released with `MADV_DONTNEED`; over-cap entries are dropped and unmapped. Because checking length and inserting are separate, a no-acquisition drain on T scheduler threads is bounded by 64 + T - 1 total and 16 + T - 1 warm. Dropping a non-process `Shared` unmaps the whole vector; true program shutdown deliberately leaves the mappings to process exit; - these are virtual mappings, not equally sized resident allocations. Warm entries retain touched RSS and cold ones retain VA only. On 4 KiB-page Linux the full map for one 16 MiB request is 19,011,584 bytes including guard/colour/alignment (18.131 MiB); 64 use about 1.133 GiB of VA. The exact extent changes with aarch64 page size. Actor hibernation neither ages nor releases retained handler entries; - `tl_perform_ctl` suspends the fiber with `(op, args)` for the handler's marker, and handlers in between forward the request; - `resume` is a runtime closure, valid once per suspension; - a body that is never resumed is cancelled with `CANCEL`, so generated code unwinds it and every reference is dropped; - preemption inside a fiber is forwarded up to the actor's own stack. - **Context switch** ([ADR 0011](adr/0011-context-switch.md)): the runtime's own assembly, on Linux for x86_64 and aarch64, the only supported targets. aarch64 is tested under qemu (`scripts/aarch64.sh`). - **Regions** (ADR 0002, Revision 1): `tl_region_new`, `tl_ref_new`, `tl_ref_get`, `tl_ref_set` and `tl_region_end`. A region holds a count on each of its references until it ends; ending it clears them, which breaks cycles through them. ### Multi-shot continuations [ADR 0017](adr/0017-multishot.md). `tl_handle_multi` is `tl_handle_ctl` for an effect with `multi ctl` operations, with one more argument: a mask whose bit `i` is set if operation `i` is one (operations are still performed with `tl_perform_ctl`). Copying a continuation needs generated code to: - release what a frame holds on its unwinding paths with `TL_UNWIND_DROP(ctx, v)`, which dups instead when `yielding == TL_YIELD_CLONE` (a *copying pass*), including a `fn` or `final ctl` handler's capability when the handler is left; - leave a region with `tl_region_exit(ctx, region)` (consumes it), which ends the region only when its last copy leaves; - reuse a token only if it is unique (`tl_is_unique`), since copies share tokens. `TL_YIELD_DISCARD` releases a continuation whose copies ran: frames unwind as usual, and `tl_defer` drops the cleanup without running it. Neither mode is an unwinding the program can observe: no handler catches it, and the runtime restores the previous state afterwards. ## Actors The native scheduler (`louise_rt/src/sched.rs`, [ADR 0004](adr/0004-actor-model.md)) implements `std/process` with the interpreter's semantics. **Fibers:** - Each actor runs on its own fiber with a guard page: the root actor on a lazily committed 1 GiB stack, other actors of compiled programs on 64 MiB ones (committed lazily, and reused), so native recursion depth matches the interpreter's. The M0 spike's actors (`tl_spawn`) get 256 KiB. - A fiber is **never dropped while suspended**: its frames would never release what they hold. A killed actor exits logically at once (links and monitors are notified), then its fiber runs once more to unwind, which releases everything it owns. **Root capabilities** (ADR 0036). The runtime handles `std/process.proc`, `std/time.clock` and `std/random.random` around `main`, each test and every actor. Each is a capability block whose clauses are runtime closures, one per operation in declaration order, then the marker. `tl_root_cap(ctx, kind, ops)` builds one: `kind` is `TL_ROOT_PROC`, `TL_ROOT_CLOCK` or `TL_ROOT_RANDOM`, `ops` the number of operations the program was compiled for; the runtime stops on an unknown kind or a mismatch. - Every root capability is built once, outside the counted heap, and is immortal (rc 0), as are its clauses (`louise_rt/src/clock.rs`): none holds state. `proc`'s was fresh for each actor until ADR 0036, Revision 1. - The native `main` passes an entry function one capability per parameter, of the kinds lowering recorded (`Program::root_caps`, in the order of its row). - Every actor body takes the kinds `tl_main_program(entry, actor_caps, n)` lists, in order: lowering derives them from `std/process.spawn`'s parameter type (`Program::actor_caps`). - `clock` and `random` operations are not scheduling points. `monotonic_ns` is the scheduler's clock in nanoseconds: virtual milliseconds, then, in real time, the clock when it switched plus the real time since. - Only these clauses read the system's clock and the kernel's generator: no extern does. **Sending: move, share or copy** (`louise_rt/src/send.rs`). `send` and `spawn` walk the message (or the spawned closure) once, iteratively: - a unique block (`rc` 1) is moved and its fields are walked; - a block the sender also reaches (`rc` > 1) is copied, with a forwarding table so sharing inside the message is kept. It is promoted to shared instead when it reaches more than 64 blocks, holds a string, `Bytes`, builder or array over 4 KiB, or is a resource: its whole subgraph gets negative counts; - immortal and shared blocks are kept; - `Ref`, regions, handler capabilities and frames, and `PINNED` resources stop the walk, and the sender panics (`cannot send a mutable reference`, ...). The interpreter refuses the same values. This makes every message safe to own on another thread. **Sendability is checked twice, on purpose** (issue #335). Statically, the compiler decides `Send` from the type's structure (`Solver::send`, ADR 0004 Revision 6): a `Ref` never is, a `Resource` only of a `@thread_safe` kind is, a closure only with sendable captures is — so `process.send` requires `Send` and a spawned body is a `send fn`, and a bad send does not compile. Dynamically, the walk's `check_sendable` (`send.rs`) is the backstop for what types cannot see — chiefly `@extern` bindings, whose Louise signature may hide a `Ref` or a pinned resource behind a sendable one. A backstop failure is a Louise panic in the *sending* actor (`handover`, `louise_rt/src/process.rs`): the message is dropped, the sender unwinds, the receiver simply never gets it — never a process abort. One exception by design: `tl_spawn`, the M0 spike's own entry point, does not walk its closure. Compiled programs never call it (they spawn through `op_spawn*`, which does), and the spike only spawns env-less closures (`tl_closure_alloc(ctx, code, 0)`), so there is nothing a walk could reject. Audited for issue #335: intended, not a hole. **Threads** (ADR 0004, Revisions 2, 4 and 8): - `LOUISE_THREADS` scheduler threads (default: one per core) each have a FIFO run queue, a next slot and an inbound queue. A message's receiver runs next on the sender's thread; an actor woken by a socket, a timer or a blocking call is queued on its home (the thread it last ran on), which alone is woken. Each thread parks on its own parker; at most half the threads awake search others' queues, and take work only from a thread with more than one actor queued. An actor may resume on another thread after a suspension, when its own is busy. With `LOUISE_THREADS=1` there is one queue, the order is the interpreter's and outputs match it exactly; the differential tests run that way, and check that 4 threads end the same way without leaks. - What other actors touch (mailbox, links, monitors, wait state) is behind the actor's own lock; sockets and blocking calls behind one control lock. No lock is held while actor code runs. - A wake-up queues an actor only if it is suspended. If it is still on its way to parking, the thread running it queues it when it yields (`handoff::RunState`, checked with loom). - When nothing can run, one thread waits on the reactor for sockets, finished blocking calls and OS signals (they signal a `mio::Waker`) or the next deadline. It gives up as soon as an actor is queued elsewhere, and only declares a deadlock when, under one lock, nothing runs, nothing is queued and nothing outside can wake an actor (a live `os.signals` subscriber can still be woken, ADR 0060). - Mailboxes are indexed by subject tag, so receiving from one subject does not scan the others' messages. **Time and timers** (ADR 0004, Revisions 3 and 5). Time is virtual: when no actor can run, the clock jumps to the next deadline. Once the program opens a socket, the clock follows real time instead: it is counted between slices, and due timers fire then, even if no thread ever idles. Timers are in a heap per scheduler thread, with a lock-free bound on the earliest deadline (`louise_rt/src/timers.rs`). `LOUISE_VIRTUAL_TIME=1` keeps the clock virtual even with sockets open ([ADR 0055](adr/0055-virtual-time-opt-in.md)); a testing aid, never for production. Semantics: the one-way switch to real time is disabled (`real_start` is never set); when no actor can run and no blocking FFI call is in flight, the idle thread polls the reactor with a zero timeout and, only if no socket is ready, jumps the clock to the next timer deadline and fires it — even while actors are parked on sockets (socket readiness does not depend on the clock, so a ready socket is always delivered first). It never sleeps in the poll waiting for a virtual deadline (it jumps instead), never jumps while a blocking call runs, and with no timers pending it waits on the reactor as before, so deadlock detection is unchanged. **Exits** follow Erlang: an abnormal exit stops linked actors, or sends them an `ExitSignal` if they trap exits; monitors receive `Down`. When the root actor returns, every remaining actor is killed and driven to completion. **Remote pids** ([ADR 0072](adr/0072-distribution.md), `louise_rt/src/dist.rs`). A local pid is 0 or more; a remote one is negative, `-1 - (node << 46 | serial)`: a node-table index and the pid on that node. `send` to a `Remote` subject (`std/process`, constructor 1: `owner`, `tag`, `wire`), `link`, `monitor`, `kill` and `stop` on a remote pid go to the transport's hooks; until distribution starts there are none, and a remote pid behaves as a dead one (a send is dropped, `monitor` answers `Down(pid, Crashed("noproc"))`). The transport delivers messages, exit signals and `Down`s from its own thread, and the links and monitors a remote pid makes to a local actor, which keeps them with its others: its exit sends their exit and `Down` back through the hooks. A lost node ends every link and monitor across it with `Crashed("noconnection")`. A scheduler thread takes from the shared run queue, where actors woken from outside the scheduler are queued, before its own one time in 61 that it finds actors there. ## Native dependencies [ADR 0005](adr/0005-ffi.md), Revision 1. - **Extern convention.** A C function bound with `@extern(c, "sym")` has the convention of `louise_rt.h`: `tl_value sym(tl_ctx *ctx, tl_value a, ...)`, with borrowed arguments and an owned result, built with the functions the header lists for bindings. - **Blocking externs** (`@extern c "sym" (blocking)`, `blocking cpu` or `blocking io`) are called through a generated thunk on their pool (`tl_call_blocking(ctx, TL_BLOCKING_CPU or TL_BLOCKING_IO, thunk, argc, args)`, `louise_rt/src/blocking.rs`) while the actor is parked. They must not panic, perform operations or drop values. The pool is the symbol's: declaring one symbol on two pools keeps one of them. The pools' sizes are `LOUISE_BLOCKING_CPU_THREADS` (or `LOUISE_BLOCKING_THREADS`; default half the cores, 1 to 4) and `LOUISE_BLOCKING_IO_THREADS` (default 16), checked by `tl_main` and `tl_main_program` before anything runs: an invalid one prints why and exits with status 2 (ADR 0005, Revision 2). - **Resources** (`tl_resource_new`, `tl_resource_get`) wrap a foreign pointer with a finalizer, called when the last reference is dropped. A resource that is not thread-safe is `PINNED`. **Callbacks from C** ([ADR 0015](adr/0015-c-callbacks-and-bindings.md), `louise_rt/src/callback.rs`): - **`tl_callback`** (24 bytes: the actor's `ctx`, the closure, a runtime-private thread token) is the `void *` environment a shim passes C with its trampoline, for one extern call. `tl_callback_begin(ctx, &cb, f)` sets it up; `tl_callback_call(&cb, argc, args)` calls `f` (borrowed by the extern, duplicated per call) with owned arguments and returns an owned result; `tl_callback_end(&cb, result)` returns `result`, or drops it and returns unit after a panic. `tl_callback_failed` (inline) tells whether one happened. - **Panics:** a callback's panic unwinds to `tl_callback_call` and stays pending in `ctx->yielding`. Further calls return unit without running anything; once the extern returns, the generated code unwinds. - **No suspension inside the call:** the actor counts its calls in progress. Meanwhile `tl_preempt` only refills the budget, so exit signals wait; `tl_call_blocking` runs the thunk inline; parking aborts. - **Guards** (abort): a call on another thread or after `tl_callback_end`, `tl_callback_begin` on the blocking pool, more than 128 arguments. ## The standard library in the runtime Like every extern, these borrow their arguments unless declared `owned`, and must behave like the interpreter's (`louise_interp`): the differential tests compare both. Their pure kernels (hashes, `split`, `html_escape`, `url_decode`, random numbers) are shared with it in `runtime/louise_rt_prims`. **Constructors the runtime builds** follow the declaration order in `std/`: `Ok`/`Error` (0/1), `Nil`/`Cons` (the small int 0, then tag 1), `None`/`Some`, `Lt`/`Eq`/`Gt` (0/1/2), tuples (tag 0), and the types of `std/process` and `std/http` (`Head`, `Chunk`). `louise_core/tests/runtime_constructors.rs` checks their tags against the analysed std. ### `Bytes` and builders [ADR 0012](adr/0012-bytes-and-http.md). - `Bytes` blocks (`TL_TAG_BYTES`: an `i64` length, then the bytes, no NUL) are made by `louise_rt/src/bytes.rs`. Each operation returns a fresh block; slices are copies. - **C bindings** read a `Bytes` with `tl_bytes_ptr` and `tl_bytes_len` (borrowed, no NUL: zeros are data) and make one with `tl_bytes_from`, a copy of `len` bytes (`louise-ffi`: `bytes_of`, `bytes`). - A `bytes.Builder` is a `TL_TAG_BUILDER` block (`louise_rt/src/builder.rs`). Its appends and `build` are owned externs: a unique builder grows in place, and `build` turns it into a `TL_TAG_BYTES` block in place (moving the bytes over the capacity word, then shrinking the block). A shared builder is copied first. - `tl_string_join` joins a `List` in one allocation. ### Console output [ADR 0022](adr/0022-console-output.md). `tl_println`, `tl_print` and `tl_eprintln` queue their text for one writer thread (`louise_rt/src/console.rs`), which writes stdout and stderr in the order they were queued. Up to 64 KiB may be queued; past that, the actor parks as in a blocking call until the writer makes room, so a console nobody reads parks the actors that print, never a scheduler thread. Because they may park, the three are `unwinds()` in the extern table. Where an actor cannot park (in a callback from C, on the blocking pool) the text is queued past the budget. `tl_main` and `tl_main_program` wait for the queue to empty once every actor has stopped, as does an `atexit` handler; the runtime's crash reports are queued like `io.eprintln`. ### Standard input [ADR 0086](adr/0086-reading-standard-input.md). `tl_io_read_line` and `tl_io_read_bytes` (`louise_rt/src/stdin.rs`) take from a read-ahead buffer (`louise_rt_prims/src/stdin.rs`, shared with the interpreter) that a `louise-stdin` thread fills with blocking `read`s of descriptor 0, started by the first read: - **Bounded.** The thread reads while less than 64 KiB wait, or while a line reader waits for the end of a longer line (up to 16 MiB), then waits for a take to make room. - **Parking.** Each scheduler that reads registers an eventfd with its reactor under its own token (`Shared::stdin_token`); the thread writes to each after every `read`. An actor with nothing to take parks on the token as on a socket (`net::wait_for`): a kill wakes it, nothing taken; the scheduler sees no deadlock while it waits; the token switches the clock to real time. Where an actor cannot park, the read waits on its thread. - **Values.** Each takes an `Int` (the maximum) and returns `(kind, Bytes)`: 0 data, 1 the end of input, 2 a line too long (skipped to its newline), 3 a read error (its message, once, then the end). `std/io` makes its `Result`s from them, and checks UTF-8 itself. Both may park, so both are `unwinds()`. - **The interpreter** fills the same buffer from `RunOptions::stdin` on its own thread, flushing output first, and blocks the run while it waits. ### Sockets and HTTP - **Sockets** (`louise_rt/src/net.rs`) are non-blocking, registered once, edge-triggered, with a mio reactor owned by the scheduler. An operation that would block parks the actor on the socket's token; a spurious wake-up only retries it. Every actor parked on a socket is woken by its events, and an event that comes between an operation's `WouldBlock` and its parking makes it retry instead of park (the reactor counts its events; ADR 0004's note of 2026-10-15). Host names are resolved on the blocking pool (`tl_net_resolve`), never on a scheduler thread. The network reads and writes `Bytes` (`tl_net_write_string` sends a string). - **HTTP framing** (`louise_rt/src/http.rs`): `tl_http_parse_request` and `tl_http_parse_chunk` take a buffer and an offset, and return offsets, parsed by `httparse` (Rust's port of picohttpparser). A `Content-Length` that is not a decimal number, or two that differ, make a request invalid; `std/http` answers 400 to a request with both `Content-Length` and `Transfer-Encoding`, 501 to a coding other than `chunked`, and 413 to a body over its limit, and closes the connection after each. ### Open files [ADR 0087](adr/0087-streaming-file-handles.md). `std/file/stream`'s externs (`tl_file_open_read`, `tl_file_open_write`, `tl_file_handle_*`, in `louise_rt/src/fs.rs`) wrap the kernel the interpreter shares, `louise_rt_prims::file::Handle` (a `File` behind a lock, emptied by `close`): - **Resource.** An open file is a `Resource` made with `thread_safe = false`, so it is `PINNED`: `send` refuses it, statically (`OpenFile` is not `@thread_safe`) and dynamically. Its finalizer drops the `Handle`, which closes the descriptor if `close` did not. The interpreter holds the same `Handle` in a `Val::File` (an `Rc`), refused by its send check too. - **Pool.** Every extern is `blocking io`: it runs on the pool with the resource borrowed while the actor is parked. One actor owns the file, so calls on it never overlap; the lock only makes the handle `Sync`. - **Actor ends.** An exit is logical first: `Down` and exit signals go out, then the fiber unwinds the next time it runs (after a blocking call in progress returns) and drops its values, which closes its files. A result that arrives for a killed actor is dropped by `park`, so a file opened meanwhile is closed too. - **Values.** `mode` is `Mode`'s constructor index (0 `Truncate`, 1 `CreateNew`, 2 `Append`); reads return `Bytes` (empty at the end), other calls `Ok(())` or `Ok(Int)`; errors are `Error(message)`. After `close`, every call is `Error("the file is closed")`. - **Files.** New files request mode `0600`; descriptors are close-on-exec. A read fills up to `max` bytes (fewer only at the end of the file), allocating at most 1 MiB until the file proves to have more. `tl_file_sync_dir` opens a directory and `fsync`s it. ### Child processes [ADR 0085](adr/0085-running-external-programs.md). `tl_command_run` (`louise_rt/src/command.rs`) starts a program with the driver in `louise_rt_prims/src/command.rs`, shared with the interpreter: - **Spawn.** `posix_spawn` with an empty signal mask (the runtime blocks SIGTERM, SIGINT and SIGHUP in its threads, and a child would inherit that), default dispositions and a process group of the child's own. Its pipes are close-on-exec until they become the child's 0, 1 and 2. A pidfd follows its exit. - **Waiting.** The pipes, the pidfd and a timerfd for the next deadline are registered with the reactor under one token, edge-triggered, and the actor parks on it as on a socket. Each wake-up drains, feeds, checks the pidfd and sends the signal due; never on the blocking pool, whose waits a kill cannot end. The interpreter waits with `poll(2)`. - **Ends.** At the timeout the group gets SIGTERM, after the grace SIGKILL; when the child ends, the rest of its group gets SIGKILL before it is reaped. A killed actor drops the run: the group is killed and the child reaped, by the `louise-reaper` thread if it does not die at once. An `atexit` handler kills the groups still running when the program exits. - **Values.** Arguments are plain values and the result a tuple of `Int`s, `Bytes` and `Bool`s (`Error((code, message))` on failure); `std/command` makes its own types from them. ### Arrays and owned externs [ADR 0014](adr/0014-arrays-and-bigint.md). - **`TL_TAG_ARRAY` blocks** have `scan_fsize = TL_SCAN_LARGE`: `fields[0]` is `tl_int(n)`, `fields[1..=n]` the elements. The raw area is the spare capacity: an `i64` count, then that many zeroed slots, so a block of capacity `cap` is `2 + cap` words and still describes itself. Drop and `send` need nothing specific. The functions of `std/array` live in `louise_rt/src/array.rs`. - **Fast paths** (ABI 4, issue #128): `tl_array_length`, `tl_array_get` and `tl_array_at` are inline in the header, so generated code reads this layout directly. Only `at` out of range calls the runtime, `tl_array_at_slow`, which panics. An index that is a big integer is out of range. - **Owned externs.** An extern declared `@extern(c, "sym", owned)` takes its arguments *owned*: it must consume each (store, return or drop it), like a closure. Perceus moves a variable's last use into the call and `dup`s other uses. With an owned argument, `rc == 1` means the caller kept no reference, so the runtime may update the block in place: `tl_array_set` and `tl_array_push` do, and copy a block whose count is not 1. An owned extern that panics drops its arguments first. ### Contexts (tail recursion modulo cons) A context (ADR 0039) is unit when empty, or a 3-field block (tag 0): - the root cell, owned; - `tl_int` of the last cell's address, and `tl_int` of the field that is its hole. Each cell owns the next through its hole field; the last cell's hole is unit. The two int fields are immediates, so dropping, sending or copying a context treats it as an ordinary value. - `tl_ctx_extend(ctx, k, cell, hole)` puts `cell` in the hole of a unique context, in place, and `tl_ctx_apply(ctx, k, value)` fills it and returns the root. Both are inline in `louise_rt.h` and consume their arguments. - A context that is not unique (a multi-shot resumption kept a copy, ADR 0017) goes to `tl_ctx_extend_slow`/`tl_ctx_apply_slow` (`louise_rt/src/ctx.rs`). These copy the path from the root to the last cell, following the hole field, which is the same for every cell of one function's contexts. ### TLS `tls.rs` (ADR 0038, the `tls` feature): rustls over the sockets of `net.rs`, clients (`tl_tls_connect`) and servers (`tl_tls_accept`, Revision 1). A TLS stream, either side, takes a TCP connection's socket and token. The connection is then marked upgraded (an atomic flag; the socket itself never changes) and refuses reads and writes, but still shuts the socket down on `net.close`. Errors are `Error((code, message))`. Without the feature, the externs exist and fail. ### Big integers [ADR 0014](adr/0014-arrays-and-bigint.md). - **Fast paths:** `tl_int_add`, `tl_int_sub`, `tl_int_mul`, `tl_int_div`, `tl_int_rem`, `tl_int_eq` and `tl_int_compare` are inline. When both arguments are small and the result is small, they compute it inline; otherwise they call the `_slow` function of the same name (`louise_rt/src/int.rs`), which returns a canonical result. Addition, subtraction and multiplication never unwind, so generated code has no yield check after them; division and remainder panic on zero. - `tl_int_show` and `tl_hash_int` take big integers too. - **Bit operations** (ADR 0035): `tl_int_and`, `tl_int_or`, `tl_int_xor`, `tl_int_not`, `tl_int_shift_left` and `tl_int_shift_right` are inline for two small ints, two's complement with infinite sign extension; the `_slow` functions take the rest (num-bigint). A shift by a negative amount panics. - **Runtime functions that take an `Int` as an index, a count, a size or a duration** read a big integer as the nearest `i64` (saturating). - **C bindings:** `tl_int_get` reads small ints only. `tl_int_to_i64` reads any `Int` that fits in 64 bits, and `tl_int_from_i64` makes one (`louise-ffi`: `int_i64`, `int_from_i64`). ### Adding a runtime extern - The runtime's externs are listed once, in `crates/louise_core/src/externs.rs`, with whether each may unwind (panic or park the actor), is `blocking` or is `owned`. Codegen decides from it which calls get a yield check and which symbols `louise_rt.h` declares; the interpreter must implement every one. - Adding `tl_foo` therefore touches: its `@extern` in `std/.lse`; the `#[unsafe(no_mangle)] pub unsafe extern "C"` function in `louise_rt`, with a `# Safety` section (or a `static inline` one in `louise_rt.h`); its prototype in `louise_rt.h`; the interpreter (`louise_interp`, `externs.rs`); and the table. `crates/louise_codegen_c/tests/externs.rs` fails if any of them is missing or disagrees (options, interpreter, `liblouise_rt.a` exports, header), so the one mistake it cannot see is a wrong `may_unwind`: mark it whenever the function can reach `tl_panic_str` or park. Checked builds catch a wrong mark when a test reaches it: each call of an extern marked as never unwinding is wrapped in `TL_NO_UNWIND`, and a panic or a park inside it aborts, naming the extern (issue #217). - A new `proc` operation is added to `PROC_OPS` (`runtime/louise_rt_prims`), which both codegen and the runtime's clause table read, and to the interpreter's scheduler (`louise_interp`, `sched.rs`). - A pure kernel the interpreter needs too (a hash, a string or byte transformation) goes in `runtime/louise_rt_prims`, which both call. ## Source lines in generated C Issue #35. Generated C carries `#line` directives, so C compiler errors, sanitizer reports and debuggers show `.lse` files and lines (debug builds compile with `-g1`: line tables, no variables; `LOUISE_CFLAGS=-g` adds them, issue #116) instead of the generated file's. This changes no layout or convention. - **Where lines come from.** Core keeps a source span on each `let` (the innermost expression it was lowered for; a `let` pattern's bindings are at the pattern) and on each function (its definition, or the lambda or call site it was made for). Dictionaries and derived methods have none. The C backend turns a span into a line with the file's line index (`louise_span`), and points at the file by the path the compiler was given (`` for the embedded standard library). - **Shape of the file.** Glue comes first and keeps its own C line numbers: the prelude, literals, prototypes, constant dictionaries, closure entries, `tl_entry` and `main`, then functions without a span. Functions with a span come last, each starting with `#line N "file"`, so no directive ever points back into the generated file. - **One source line per statement.** C numbers the lines after `#line N` as `N`, `N + 1`, and so on, but all the C of one Core `let` (a call, its yield check, the unwinding path) belongs to one source line. So every further C line gets its own `#line N` (without the file). A directive is only written between whole lines: `TL_MUSTTAIL return f(...);` stays on one line, so no directive separates the attribute from its statement, and self tail calls (`goto entry`) are unaffected. The `dup`s, `drop`s and `release`s Perceus puts before a `let` are at its line (a `release` after a `match`'s projections is at the first line of the arm's code; a `reuse` is a `let`, at the construction's line); other code without a span (a `switch`, a `return`) keeps the line of the enclosing `let` or function, which is restored after a nested block. - **Cost.** The C file grows (about +75% lines and +25% bytes for `tests/bench/html.lse`); no difference in C compile time was measurable. - **Turning it off.** Setting `LOUISE_NO_LINE_DIRECTIVES` (to any value) leaves the directives out, to read, grep or debug the generated C by its own lines. The library API takes the source files as an option (`louise_codegen_c::generate(program, entry, Some(sources))`); `None` also leaves them out. - **Tests.** `crates/louise_codegen_c/tests/lines.rs` checks where the C lines of a function point (its prologue, a call and the yield check after it, a `musttail` call, a `release` and a `reuse`), a C compiler error pointing at the `.lse` call, and (with clang) a UBSan report from generated code pointing at the `.lse` line. ## Validation - **The M0 spike.** `runtime/spike/spike.c` is hand-written C in the shape `louise` emits. `scripts/spike.sh` (also run by `scripts/ci.sh`) links it against `liblouise_rt.a` in debug, release, and clang ASan+UBSan builds. It checks that 1M-element lists are summed, consumed and dropped on a fiber stack (iterative drop); FBIP (a unique list is updated in place, a shared one copied); that a `final ctl` op unwinds 500 frames, each owning a list, to its handler, with live blocks back to 0; that 1,000 actors are preempted round-robin, one panics on a division by zero and crashes alone, and 500 are killed mid-loop and release their lists; that an overflow promotes to a big integer and subtracting back gives the small int; and that the process ends with 0 live blocks and 0 actors. - **Differential tests.** `crates/louise_codegen_c/tests/native.rs` runs every `tests/run` program natively, and requires the interpreter's output and zero live blocks. - **Sanitizers and models.** CI runs native programs under ASan and UBSan (nightly, and on pull requests that touch them), and loom models of the scheduler's hand-offs, timers and mailbox; `LOUISE_CI_TSAN=1` adds ThreadSanitizer. - **Checked builds.** Debug builds of generated code (`-DTL_CHECKED`, as `tests/run`'s native runs are) check two invariants nothing else verifies, and abort with a message when one fails: an extern marked as never unwinding that panics or parks (`TL_NO_UNWIND`), and an argument slot read after a suspension (`TL_XARG`) (`louise_rt/src/checked.rs`, issue #217). Release builds are unchanged. - **Extern table.** `crates/louise_codegen_c/tests/externs.rs` checks the runtime's externs across the table, std, the interpreter, `liblouise_rt.a` and `louise_rt.h`. - **Runtime unit tests** (`cargo test -p louise_rt -p louise_rt_prims`) cover the pure kernels and HTTP framing, and run small scenarios as a root actor under the leak oracle. ## Known limitations - A cycle through `Ref`s lives until its region ends, which clears the region's references (ADR 0002, Revision 1); reference counting alone cannot reclaim it. - A block with more than 2^31 local references, or 2^29 shared ones, is never freed: its count saturates (above) rather than overflow. - A saved or live multi-shot capture pins its handler mapping until final handler finish; no resume closure is safe merely because the coroutine returned. Pooling that mapping earlier could let a later snapshot overwrite another handler's frames (issue #329). Handlers whose operations are all `final ctl` (early `return`, exceptions) run no fiber and do not use this pool. - A Rust panic inside an `extern "C"` entry point aborts the process. That is acceptable for runtime bugs (`expect("louise: ...")`), but not for user errors, which use `tl_panic`. ## History What changed, in order. Each step's rationale is in the ADR it names. - **ABI v0 (M0)**, validated by the M0 spike and accepted on 2026-10-08 (issue #2): the values, blocks, context, reference counting, yield-bubbling unwinding and preemption above, with a single scheduler thread and corosensei fibers. - **Revision 1** (ADRs 0002–0004, Revision 1; accepted with v0, implemented in M5), `TL_ABI_VERSION` 1: - one C signature for every generated function, with `ctx->xargs`, so every tail call can be `musttail`; - externs borrow; immortal blocks; regions; handler capabilities; - the runtime's own context switch (implemented on x86_64 Linux: ADR 0011); - sending by move, share or copy, and threads (M6). - Revision 1 also replaced yield checks with table-driven unwinding (`-fexceptions`, `_Unwind_ForcedUnwind`). That part was never implemented: ADR 0003, Revision 2 keeps yield checks, which [Unwinding](#unwinding) describes. - **M7, M8:** the extern convention, the blocking pool and resources (ADR 0005, Revision 1); sockets on a mio reactor, and real time once a socket opens (ADR 0004, Revision 3). - **Issue #36:** `Bytes`, keep-alive HTTP framing on buffers and offsets, `tl_string_join` (ADR 0012). - **Issue #34:** the Perceus optimisations (borrowed parameters, drop specialisation and reuse, constant dictionaries); `tl_dup` and `tl_drop` test `rc != 0` inline. - **Issue #47, `TL_ABI_VERSION` 2:** arrays and owned externs, big integers (overflow promotes instead of panicking; `tl_int_overflow` is gone), builders, `tl_abi_check` (ADR 0014; ADR 0012, Revision 1). - **Issue #48:** callbacks from C and generated bindings (ADR 0015). No layout change. - **Issue #35:** `#line` directives in generated C. - **v1 effects:** `defer` (`tl_defer`, ADR 0016) and multi-shot continuations (`tl_handle_multi`, `TL_YIELD_CLONE`, `TL_YIELD_DISCARD`, `tl_region_exit`, ADR 0017). - **Issues #61 and #45:** never-unwinding calls lose their yield check, constant dictionaries are called directly, fewer wake-ups (ADR 0004, Revision 4), per-thread timers and ThreadSanitizer (Revision 5). - **Issue #72:** console output goes through a writer thread, and a full stdout parks the printing actor instead of blocking its scheduler thread; `tl_println`, `tl_print` and `tl_eprintln` may park (ADR 0022). No layout change. - **Issue #220 (ABI unchanged):** `tl_http_parse_head_end` finds where a request head ends, so `std/http` scans a head arriving in pieces once instead of parsing it again on every read; `tl_http_parse_request` refuses more than one `Transfer-Encoding` (ADR 0012, Revision 2). - **Issue #222 (ABI unchanged):** `tl_net_resolve`, a `blocking` extern, resolves a host on the pool; `std/net`'s `connect` and `listen` resolve first and give `tl_net_connect` and `tl_net_listen` addresses, which need no lookup. Those two refuse a port outside 0 to 65535 instead of truncating it (ADR 0012, Revision 2). - **Issue #221 (ABI unchanged):** several actors may wait on one socket, each woken by its events; readiness that arrives before an actor parks is a count of the reactor's events instead of a flag per socket (ADR 0004, note of 2026-10-15). - **Issue #146 (ABI unchanged):** TLS clients: `tl_tls_*` externs (`tl_tls_config` is the first `blocking` runtime extern), and TCP connections that can be upgraded (ADR 0038). - **Issue #154, `TL_ABI_VERSION` 7:** `tl_ctx_extend` and `tl_ctx_apply` are inline (unique contexts change in place), with `tl_ctx_new` and the `_slow` paths, which copy a shared context first (ADR 0039). - **Issue #193, `TL_ABI_VERSION` 8:** kept fields for sized reuses — `TL_FLAG_TOKEN` marks a token whose kept fields are dead, and `tl_drop_slow`/`free_block` frees it without touching them (ADR 0040, Revision 2). - **Issue #305, `TL_ABI_VERSION` 9:** two blocking pools (ADR 0005, Revision 2): `tl_call_blocking` takes the pool, `TL_BLOCKING_CPU` or `TL_BLOCKING_IO`, after the context; `tl_runtime_blocking_stats` reports both pools' sizes, running and queued calls (`std/runtime`). - **Issue #336, `TL_ABI_VERSION` 10:** borrowed closures (ADR 0068): the closure block's raw area is two code pointers (owned and borrowed entries); `tl_closure_alloc` takes both; `tl_closure_code_borrowed` reads the second; runtime-made closures fill the borrowed slot with a per-arity adapter (`tl_borrowed0`/`1`/`2`). - **Issue #308 (ABI unchanged):** `tl_net_peer`: a connection's peer, recorded when it was accepted or made (ADR 0012, Revision 4). - **Issue #404 (ABI unchanged):** TLS servers and mutual TLS: `tl_tls_server_config` (`blocking`), `tl_tls_accept`, `tl_tls_peer_names` (ADR 0038, Revision 1). - **Issue #414 (ABI unchanged):** `std/process.proc` has a sixteenth operation, `demonitor` (`PROC_OPS`); `tl_root_cap` refuses a program compiled for another count. An exiting actor's local watchers get their `Down` under its lock, and a remote `Down` is delivered under the watcher's lock, so that none comes after `demonitor` (ADR 0072, wire op `16`). - **Issue #423 (ABI unchanged):** `tl_dist_spawn` answers a linked or monitored spawn to a node whose hello does not set that op's capability flag with failure code 10, `std/dist`'s `Unsupported`, at once (ADR 0072; `docs/wire-format.md`, *Capability flags*). - **Issue #422 (ABI unchanged):** `std/process.proc` has a seventeenth operation, `unlink` (`PROC_OPS`); `tl_root_cap` refuses a program compiled for another count. An exit through a link counts only through a half its receiver still has, local exits included, and its effect (the `ExitSignal` in the inbox, or the receiver's exit) happens under the receiver's lock, so that none comes after `unlink`. So `link` makes the linking actor's half first, and `spawn_link` the parent's, before the child is in the actor table (ADR 0072, wire ops `17` and `18`). - **Issue #404 (ABI unchanged):** distribution's externs (ADR 0072): `tl_dist_start` starts the node (the transport thread, the type registry, the hooks of remote `proc` operations), `tl_dist_register` names a local subject, `tl_dist_whereis` asks a node for one, its answer arriving as a message on the caller's subject (the `tl_os_signals` pattern), and `tl_dist_spawn` asks a node to start a `@remote` function, answered the same way, and `tl_dist_monitor_node` follows a node's connection, its `NodeUp` / `NodeDown` events arriving the same way; `tl_dist_spawn_for` is the node's spawner starting the body the dispatcher gave (or refusing) and answering, the new actor linked to the asker for `spawn_link_on` (#415: it replaced `tl_dist_spawned`, and `tl_dist_spawn` gained `link`) or monitored by it for `spawn_monitor_on` (#421: `link` became `tie`, a `std/dist.Tie`, and both gained `down`, the monitor's tag); `tl_dist_spawn_abandon` gives up a monitored spawn whose wait timed out, so its actor is not monitored (#421); `tl_dist_peers` reads the transport's statistics of every known node (a `List`, built at once); `tl_dist_connect` gives the transport a node to stay connected to, as a seed (#417). `tl_dist_start` also takes the program's `@remote` entries and the spawner's subject, and (#417) the address the node advertises and its discovery. A send to a remote subject may park the sending actor while the peer's outbound queue is full (back-pressure, item 10). The interpreter's fail with "distribution needs --native". - **Issue #306 (in `TL_ABI_VERSION` 9):** `tl_os_signals` subscribes the running actor to SIGTERM, SIGINT or SIGHUP, which `tl_main` and `tl_main_program` now block in every runtime thread and take on a signal thread; `tl_net_close_listener`; `std/process.proc` has a fifteenth operation, `stop` (`PROC_OPS`), and `ExitReason` a fourth constructor, `Shutdown` (3) (ADR 0060; ADR 0004, Revision 7). - **Issue #142, `TL_ABI_VERSION` 6:** `tl_root_cap` takes a kind (`TL_ROOT_PROC`, `TL_ROOT_CLOCK`, `TL_ROOT_RANDOM`) and `tl_main_program` the kinds of every actor body's capabilities; `clock` and `random` capabilities are immortal. `tl_random_int` and `tl_random_token` are removed: randomness goes through the `random` effect (ADR 0036). - **Issue #143, `TL_ABI_VERSION` 5:** bit operations on `Int` (`tl_int_and`, `or`, `xor`, `not`, `shift_left`, `shift_right`) are inline for small ints, with `_slow` paths; `TL_TAG_U64` boxes a `U64` (ADR 0035). - **`Bytes` for C bindings (ABI unchanged):** `tl_bytes_from`, `tl_bytes_len` and `tl_bytes_ptr`, the accessors the known limitations listed as planned. New entry points only: no layout or calling convention changes. - **Issue #434, `TL_ABI_VERSION` 12:** `TL_XARGS` is 123: native functions take up to 128 parameters (a row of many effects, a lambda capturing many values), and a call through a closure, which passes the closure first, still fits. The slots are the running thread's (ABI 3), so it costs about 1 KB per scheduler thread. - **Issue #340, `TL_ABI_VERSION` 11:** `TL_TAG_DEC` boxes a `Dec`: an `i128` counting 10^-18 units, as two raw `u64` limbs (a raw area is 8-byte aligned, an `i128` wants 16), with the `tl_dec_*` externs (ADR 0070). A leaf kind: drop, send and copy need nothing new. - **Issue #128, `TL_ABI_VERSION` 4:** `tl_array_length`, `tl_array_get` and `tl_array_at` are inline (`tl_array_at_slow` panics out of range); generated code reads the array layout. - **Issues #136 and #137, `TL_ABI_VERSION` 3:** `ctx->xargs` points at the running thread's slots; the context shrinks from 248 to 48 bytes (ADR 0028). Senders put messages in a lock-free inbox, and idle actors' stacks hibernate; neither changes the ABI. - **Issue #380 (ABI unchanged):** `tl_string_find` — `string.find`, the byte index of a substring or `None`, and `tl_string_contains` share the one substring-search kernel (`louise_rt_prims::find`, which the interpreter calls too): memchr's two-byte filter (SSE2 on x86-64, SWAR elsewhere), dispatched by needle length. No layout change.