# ADR 0002: Memory model — Perceus reference counting, no GC **Status:** Accepted — 2026-10-08, reviewed and accepted by the project owner (issue #2), including Revision 1. ## Context The language must have **no tracing garbage collector**, and it must support: - effect handlers whose resumptions capture stack frames, - OTP actors that crash and restart freely. Rust-style lifetimes and borrow checking conflict with resumable handlers, because a continuation can capture live borrows. Combining the two is still a research problem. ## Decision **Perceus reference counting** (as in Koka) is the only memory management. The compiler inserts the counting: 1. It analyses ownership in Core: every value has one owner, and parameters are owned unless inferred to be borrowed. 2. It inserts `dup`/`drop` precisely, at last use rather than end of scope. 3. It applies **reuse analysis** (FBIP: a unique cell being matched is updated in place) and **drop specialisation**. **Resumptions are one-shot (affine).** This keeps ownership linear through handlers, and v0 never copies a continuation. (v1: `multi ctl` operations copy theirs, taking a reference per copy; [ADR 0017](0017-multishot.md), proposed.) **Each value stays inside one actor:** - Counts are non-atomic. - Values that cross actors are deep-copied ([ADR 0004](0004-actor-model.md)). - A value becomes *shared* (negative count, atomic updates) only by explicit promotion: large binaries and thread-safe FFI resources. **Allocation:** - Allocation goes through `tl_alloc`/`tl_free`. - v0 uses the system allocator, then switches to **mimalloc**. There are no per-actor heaps. - When an actor dies, its stack is *unwound* ([runtime ABI](../runtime-abi.md#unwinding)), which drops everything the actor owns. **Freeing is iterative**, using a per-actor worklist, because fiber stacks are small. **User syntax:** programmers write no lifetime or borrow annotations in v0. ## Consequences **Benefits:** - Deallocation is deterministic. - There are no pauses. - Functional code is fast when data is unique (FBIP). **Costs:** - **Cycles leak.** They can only form through mutable `Ref`s; immutable data is acyclic. This is documented, and a cycle detector may come later. - The compiler must get ownership exactly right. The safety net is: - the `tl_stats_live_blocks()` leak oracle, which must read 0 at exit, - ASan in CI, - a differential test against the reference interpreter. - Uniform boxed values (no monomorphization in v0) cost speed on numeric code. This can be revisited after v0. ## Alternatives considered - **Rust-style lifetimes and a borrow checker.** Research-level when combined with effect handlers, and roughly doubles the type-system work. Optional `borrow` annotations may come later as a performance tool only. - **Per-actor heaps or arenas** (BEAM style). Destroying a dead actor wholesale is attractive, but deep-copy `send` would then need cross-thread allocation into the receiver's heap (Erlang's "heap fragments"). They would also still need lists of external references for shared binaries. Not worth it for v0. - **Tracing GC.** Ruled out by the requirements. ## Revision 1 — 2026-10-09: scoped references; how values are sent **Status:** Accepted — 2026-10-08, with the rest of this ADR (issue #2). Decided by the project owner. ### Mutable references are scoped to regions This supersedes "cycles through mutable `Ref`s leak". - **Why only `Ref` matters:** immutable constructors can only point at values that already exist, so every reference cycle goes through a `Ref`. - **The rule:** `Ref`s may only be created inside a **region**: ``` region { let r = ref.new(0) ref.set(r, ref.get(r) + 1) ref.get(r) } ``` - **Typing:** - Each region gets a fresh, rigid region type `h`. - A reference has type `Ref`. Creating one performs `alloc`; reading or writing it performs `st`. The region handles both. - **Nested regions**, settled by lexical handlers ([ADR 0010](0010-lexical-handlers.md)): - The region `h` is the *instance* of its `alloc` and `st` labels, so every operation goes to the region its reference belongs to. - Reads and writes of an enclosing region's reference therefore reach that region. - `ref.new` without a known region allocates in the innermost one. Allocating in an outer region requires a helper whose signature names that region's `alloc`. - Only `region` may handle `alloc` and `st` (E0702). - Neither the region's result nor anything outside it may mention `h`, so no `Ref` can escape. This is Haskell's `runST`, checked at a dedicated construct instead of through rank-2 types. - **Reclamation:** - When a region ends, normally or by unwinding, the runtime clears every reference created in it. That breaks every cycle, and reference counting frees the rest. - Clearing can't be observed, because nothing outside the region can reach those references. - **Consequence:** reference cycles never outlive their region. Long-lived mutable state belongs in an actor's state (message passing) or in a region that lives as long as the actor; actor exit unwinds it. - **Alternatives considered:** - Breaking cycles only when an actor exits; leaks would still be bounded by actor lifetime. - A trial-deletion cycle collector, restricted to `Ref` cells. - Weak references. Regions make leaks impossible by construction instead of collecting them. ### Sending: move, share or copy, decided per part of the message This replaces "send deep-copies". All values that can be sent are immutable (`Ref` cannot leave its region, nor be sent), so moving, sharing and copying are indistinguishable to programs. `send` walks the message once: | Part of the message | What happens | Cost | |---|---|---| | Uniquely owned (reference count 1) | **moved:** the pointer changes owner | no copy, no allocation | | Shared and large | **promoted to shared** once (atomic counts; negative `rc` in the ABI) | no copy | | Shared and small | **copied** | keeps each actor's memory local | | `Bytes` above a threshold | always shared (off-heap, as in Erlang) | no copy | A message built for the send (`send(s, Ctor(...))`) has count 1, so the runtime moves its outermost block without copying it. (This said the compiler skips the walk for it; it never did, and measured on `tests/bench/records` the visit costs under 1%, so it won't: issue #155.) Freeing memory on a different thread than allocated it is supported by the allocator (mimalloc). **Note — 2026-10-15** (Proposed; needs engineering review, #44): with `Send` as an auto trait and capture rows in function types ([ADR 0004](0004-actor-model.md), Revision 6, issue #233), the walk's refusals (pinned blocks, captured capabilities) are no longer reachable from well-typed code. The walk keeps them as a backstop for `@extern` code. ## Implementation (v1) — 2026-10-09 **Status:** Accepted by the project owner on 2026-10-12 (issue #34); the decisions marked *for review* had been accepted on 2026-10-09 (PRs #54–#59); needs engineering review (#44). The v0 backend inserted `dup`/`drop` precisely but did none of the optimisations planned in the Decision above. They now run in `louise_perceus` after dup/drop insertion, and `louise_perceus::verify` checks every program they produce. What generated code does is in the [runtime ABI](../runtime-abi.md#perceus-optimisations-v1-issue-34-proposed-needs-engineering-review). ### Borrow inference (`louise_perceus/src/borrow.rs`) - Lean 4's inference ("Counting Immutable Beans"): each parameter of a function that is never made into a closure starts *borrowed*; it becomes owned when the body consumes it (returns it, stores it, passes it to an owned position), or when a tail call to the same recursive group passes it a value the caller owns (dropping that value after the call would break the tail call). A fixed point over all functions. - Closures, effect clauses and externs keep their conventions: closure entries tail-call the lifted function with owned arguments, so a function used as a closure borrows nothing. - Projections borrow from the value they read (no `dup`); one that must be owned gets an explicit `dup`. A projection of a borrowed value stays borrowed, so walking a borrowed structure does no counting. - *For review:* **a parameter the function matches (`switch`) stays owned.** Lean borrows it if it is only read. Measured on the benchmarks, borrowing walked structures kept temporaries alive until the call returned: `lists` was about 15% slower (the list is freed in a separate pass instead of as it is folded), and `html` became about half again as slow, because glibc then trimmed and re-faulted its heap around the quadratic `string.join` (314k minor page faults instead of 1.4k). Owned, drop specialisation frees (or reuse rebuilds) each unique cell as it is matched. The cost is the other case: a lookup in a persistent structure (`dict.get`) takes its map owned, so its caller dups the map and each level takes the shared path. On the `dict` benchmark the two choices measured the same. Borrowing still applies to dictionaries, strings and other parameters passed along unchanged. ### Drop specialisation (`louise_perceus/src/specialise.rs`) `let a = x.0; dup a; let b = x.1; dup b; drop x` becomes `release x [0: a, 1: b]`: if `x` is unique its fields move to `a` and `b` and the cell is freed without touching their counts; otherwise the fields are dup'd and `x` dropped. Only the statements just before the drop are rewritten (projections, `dup`s, `drop`s: nothing that can unwind), so no code moves across a call. A value whose fields are projected before a nested `switch` and dropped inside it (`[a, b, ..rest]`) is not specialised. ### Reuse (FBIP) - A release of a value matched by a `switch` keeps its cell as a *token* when a constructor or tuple at least as large as the fields read is built later on some path: that construction writes the cell in place. Every path consumes the token once: the first suitable construction on it, or a `drop` on entry to a branch without one. The token is an ordinary owned value (a unique cell whose fields are all unit, or unit), so unwinding drops it like any other reference. - *For review:* Core has no types, so the size of a matched cell is not known statically. A construction checks at run time that the token has as many fields as it needs (it may change the tag), and otherwise frees the token and allocates. Carrying constructor arities in Core would make the choice static. *Done by [ADR 0040](0040-perceus-v2.md) (issue #157): Core carries arities, and a reuse of known size has no check.* - Tuples and dictionaries are projected without a `switch` and give no token (a constant dictionary is immortal, never unique). ### Constant dictionaries A dictionary without constraints (`Num`) was built at every use: six closures and a tuple allocated and freed per `+`. The C backend now emits it as `static const` immortal blocks (count 0, like literals), and `tl_dup`/`tl_drop` skip immortal blocks inline. Because the blocks are read-only constants, the C compiler can fold a method lookup on them into a direct call. Calling methods of known instances directly in Core (devirtualisation) would also help the interpreter; it is not done. ### Results Release builds, best of 7 interleaved runs, on a shared machine (load average around 8, so about ±10%): v0 is the base branch (`v1-bench`), v1 this implementation. | Benchmark | v0 (ms) | v1 (ms) | Change | |---|---|---|---| | `arith` | 1178 | 236 | −80% | | `dict` | 3043 | 727 | −77% | | `effects` | 1722 | 188 | −90% | | `html` | 1157 | 1179 | +1% (noise) | | `lists` | 4542 | 1024 | −78% | | `messages` | 2797 | 2534 | −10% | Constant dictionaries account for most of it: an arithmetic operation on `Int` allocated and freed seven blocks for `Num`. Each step alone, from a separate series of interleaved runs (best of 5, ms): | Benchmark | v0 | + constant dictionaries | + borrowing | + drop specialisation | + reuse | |---|---|---|---|---|---| | `arith` | 1130 | 222 | 226 | 214 | 224 | | `dict` | 3306 | 823 | 682 | 705 | 738 | | `effects` | 1893 | 203 | 210 | 204 | 206 | | `lists` | 4708 | 1332 | 1368 | 1237 | 1053 | `html` is bound by copying in the quadratic `string.join` and varied between 1.1 and 1.9 s for the same binary; its page faults are unchanged. All `tests/run` programs give the same output on both backends with no leaked block, with 1 and 4 scheduler threads and under ASan+UBSan; `tests/run/reuse.lse` and `tests/run/reuse_unwinding.lse` cover reuse of unique and shared cells, size and tag changes, borrowed parameters whose fields escape, and reuse while `final ctl` unwinds, while a `ctl` body is suspended or cancelled, and in a panicking actor. ## Note — 2026-10-12: borrowing does not slow `arith` or `effects` (issue #102) **Status:** for review with the section above (#44). The step table above shows `arith` +2% and `effects` +3% from "+ borrowing". That was noise: the same section puts these runs at about ±10%, and its "+ reuse" column moves `arith` by +5%, which reuse cannot affect. **Measured again by instruction counts**, which are exact (`perf stat --no-scale -e instructions:u`, one scheduler thread, release builds, the cpu_core and cpu_atom rows summed). `LOUISE_NO_BORROW=1` turns borrow inference off, so every parameter is owned: | Benchmark | Borrowing (instructions) | All owned | Change | |---|---|---|---| | `arith` | 233,534,658 | 233,534,657 | 0 | | `effects` | 219,129,049 | 219,129,064 | 0 | | `dict` | 1,701,324,920 | 1,702,216,065 | −0.05% | | `lists` | 1,974,737,231 | 1,974,737,218 | 0 | **Why nothing moves:** in the hot loops (`sum_to`, `fib`, `ticks`, `count`), borrowing only changes parameters passed along unchanged. Owned, they are moved through the self tail call (a `goto`) at no cost; borrowed, they are not counted either. What changes is outside the loops: fewer drops on exit and smaller unwinding paths. **One real cost, kept on purpose:** a tail call to a function of *another* recursive group that borrows a variable the caller owns becomes a call, a yield check and a drop. In `effects`, the handler bodies' calls of `ticks` and `count` show it. Borrow inference keeps such calls tail calls within a group, where a loop would otherwise grow the stack. Across groups, the chain of calls is bounded by the call graph, and the cost is paid once per call, not per iteration. `louise_perceus`'s module documentation now says so; it claimed drops never come after a tail call. **Targets for the remaining Perceus work** (instructions, one thread), set before doing it: - borrowing is never more than 0.5% worse than all-owned on any benchmark (`LOUISE_NO_BORROW=1` measures it); - borrowing the map of a lookup (`dict.get`) without slowing `lists` or `html`: `dict` −5%; - reuse sizes known statically (arities in Core), and drop specialisation of nested matches (`[a, b, ..rest]`): `lists` −5%. **Perceus runs on reachable functions only** (2026-10-12, issue #114). The specialiser and Perceus work on the functions the program's entries reach, as emission always did. On hello, Perceus took 4.0 ms instead of 0.1, almost all on std. Borrow inference sees only live closure targets: a function that dead code alone makes into a closure may now borrow. That is sound, since no live code calls it through a closure. The generated C of `tests/run` is unchanged up to function numbering, except in 3 programs where such a function now borrows; the native tests, with the leak oracle, pass. ## Implementation note — 2026-10-09: mimalloc for blocks (issue #35) **Status:** Accepted by the project owner on 2026-10-09 (PRs #54–#59); needs engineering review (#44). mimalloc stays on by default. "The system allocator, then mimalloc" is now done, in `runtime/louise_rt/src/heap.rs`: - **Only blocks use mimalloc, called directly** (through its `GlobalAlloc` implementation, without registering it as `#[global_allocator]`). The runtime's own Rust allocations (run queues, mailboxes, the drop worklist) keep Rust's global allocator: they are not on the hot path. This also keeps the global allocator of `liblouise_rt.a` the same as that of a native Rust dependency, which is a separate static library with its own copy of the standard library, linked into the same program ([ADR 0005](0005-ffi.md)). (The compiler, `louise`, is a separate program: it does register mimalloc as its global allocator, issue #120.) - **A cargo feature, `mimalloc`, on by default.** Without it, blocks come from the system allocator, as before. - **Freeing on another thread** than the allocating one (actors migrate between scheduler threads; messages move between actors) is supported by mimalloc: such a free goes to the page's thread-free list. - **Sanitizers.** ASan intercepts `malloc` and `free` only, so it does not see blocks allocated by mimalloc: a use-after-free of a block goes unreported (checked by hand: reported with the system allocator, silent with mimalloc). Sanitizer builds therefore link a runtime built without the feature (`--no-default-features --features stats`, in `target/sanitize`): `scripts/ci.sh` does it for the native programs under ASan+UBSan, and `scripts/spike.sh --asan` for the spike. The leak oracle (`stats`) does not depend on the allocator. - **What it bought** (mimalloc v3, through the `mimalloc` crate 0.1.52; `tests/bench`, one scheduler thread, pinned to performance cores, user-space counts of a perf counter): the benchmarks run 2–10% fewer instructions (`lists` −9.8%) but the cycles barely move (−3% to +3%, within the noise of a shared machine). mimalloc v2 gave the same picture. The benchmarks are not bound by the allocator: `html` is bound by copying strings, and the leak oracle's shared atomic counter costs more than the allocator itself (21–32% of the cycles of `arith`, `dict`, `effects` and `lists`, against a runtime without it; see the next note). Wall-clock timings of `scripts/bench.sh` on the shared machine vary by ±15% between identical runs, more than the difference. - **Cost:** a C library built by the `cc` crate (a few seconds on a clean build), and a second runtime build for sanitizer runs. After the leak-oracle change below, the comparison is the same: cycles −2% to +2% on one thread, and wall time within ±3% with all threads (`messages`, `lists`, `dict`, interleaved runs). Keeping mimalloc is therefore a bet on allocation-heavy, multi-threaded programs (where glibc's arenas are known to be weaker), not a measured win on the current benchmarks. The feature makes going back a one-line change. ## Implementation note — 2026-10-09: per-thread leak-oracle counts (issue #35) **Status:** Accepted by the project owner on 2026-10-09 (PRs #54–#59); needs engineering review (#44). The leak oracle (`tl_stats_live_blocks`, the `stats` feature, on by default) counted live blocks in one global atomic, so every allocation and free was an atomic read-modify-write on a shared cache line. That cost 21–27% of the cycles of `arith`, `dict`, `effects` and `lists` on one thread (+6% instructions, measured as above), far more than the choice of allocator. Each thread now keeps its own count, written with a plain load and store (only its thread writes it), and `tl_stats_live_blocks` sums them. A block freed on another thread lowers that thread's count, so a single count can be negative; the sum is exact once the other threads are idle, as at exit, where the oracle is read. The counts are registered on a thread's first block and never freed (one word per thread), so a count outlives its thread. With `stats` on by default, the oracle stays available in every build at a small cost (`lists`: 5.9G cycles, against 5.4G without `stats` and 7.9G with the shared counter). ## Implementation note — 2026-10-09: the allocator's fast paths (issue #61) **Status:** Accepted by the project owner on 2026-10-12; needs engineering review (#44). It changes how the mimalloc note above calls mimalloc, not the choice. - **mimalloc is called directly** (`libmimalloc-sys`: `mi_malloc`, `mi_free`), no longer through the `mimalloc` crate's `GlobalAlloc`. That implementation always takes mimalloc's *aligned* allocation path, and its `dealloc` needs a `Layout`, which the runtime computed from the block's tag for every free and mimalloc then ignored. Every mimalloc allocation is 16-byte aligned, more than blocks need (8). Without the `mimalloc` feature (sanitizer builds), blocks still come from the system allocator through `GlobalAlloc`. - **A unique block without children or finalizer is freed at once.** `tl_drop_slow` used to push every dying block on the actor's drop worklist and drain it; a `Float` or a `String` (no scanned fields, an ordinary tag) is now freed directly. - **Measured** (user-space cycles, best of 5 interleaved, one thread): `floats` −39% (a new benchmark: boxed `Float` arithmetic, ADR 0013), `dict` −17%, `messages` −4%, `html` −3%, `lists` −1%, `arith` and `effects` unchanged. ## Revision — 2026-10-12: the leak oracle only in the checked runtime (issue #130) **Status:** Proposed (epic #135); needs engineering review (#44). The per-thread counts above stay, but no longer in every build. Release programs link the `fast` runtime (ADR 0031), built without `stats`. In it, `tl_stats_live_blocks()` returns −1, and `LOUISE_LEAKS=1` prints `live blocks: unknown` with the way to get the count (`LOUISE_RUNTIME=checked`). Debug builds, `run`, `test --native`, the stress and sanitizer runs, and the demo's load test keep the oracle, and every test that requires 0 live blocks still runs with it. With LTO and one codegen unit as well, `floats` is 16% faster, `arrays` 10% and `dict` 7% (ADR 0031's table). ## Note — 2026-10-12: large drops are freed in steps (issue #158) **Status:** Proposed (epic #135); needs engineering review (#44). **The problem:** freeing a large structure ran to the end without yielding. A list of 10 million cells took about 97 ms to free, and other actors on that thread waited all that time. With one thread, a ping-pong pair running beside the drop made 1 round trip while it lasted. **The change:** - **A step at a time.** A drop frees at most 4,096 blocks (about 45 µs for list cells), then leaves the rest in the actor's worklist and sets `reductions` to 0. The actor's next function entry then yields, and it continues freeing when it runs again. - **Large arrays from their end.** A block with more than 4,096 fields is set aside and released 65,536 fields per step, with a cursor beside it. Its count isn't rewritten: without mimalloc, freeing a block computes its size from that count. - **Where freeing continues:** - the next drop; - each time the actor is preempted or woken (`preempt_root`, which receives and sleeps go through too); - when its body returns: in steps, yielding between them, before its exit is recorded; - after that, what releasing its mailbox drops is freed at once. The `DropStack` checks it's empty when the actor is freed (debug builds). - **The hot path is unchanged.** A leaf block (a `Float`, a `String`) is still freed inline in `tl_drop_slow`. The worklist is out of line (`drop_queued`), and the stepping is in `#[cold]` functions. Inlined, the worklist cost up to 10% in instructions across the benchmarks, through the inlining decisions it changed. **Measured:** - **10 million cells, one thread:** the ping-pong pair makes 611 round trips during the drop, against 1. `tests/fixtures/large_drop.lse` checks more than 10 for a million cells, plus an actor killed while freeing and one waiting with cells left, with 0 live blocks. - **The benchmarks,** against the stack's previous PR (user cycles, one thread, best of 9–15): - `floats` −7.6% (the leaf case now inlines into programs); - `fanin` −3.7%; - `idle` +2.5% (+5.3% instructions, at each actor's end); - `html` +5.0–6.6%, with +1.1% instructions; - every other benchmark within ±4%. **Trade-offs, for review:** - **An actor that waits** with blocks left keeps them until it's woken or ends. A server that frees a large request and waits for the next keeps that garbage until then. - **Finalizers run later.** A resource inside a large structure is finalized when its step comes, not at the drop. A file may close a little later. - **Exits are seen later.** An actor that ends with a large structure is seen as exited (by links, monitors and `main`) once it has freed it. - **Frees outside an actor** (`drop_detached`, the scheduler freeing a message whose receiver is gone) still run to the end. ## Note — 2026-10-12: no free lists in front of mimalloc (issue #132) **Status:** Proposed (epic #135); needs engineering review (#44). #132 asked whether a free list per scheduler thread in front of mimalloc would speed up allocation-heavy programs. The plan was to ship it only if it gained at least 5% on `floats`, `dict` or `lists` without slowing anything else by more than 5%. Two prototypes were measured against the stack's last PR, with the `lto` runtime (ADR 0032), which inlines mimalloc's fast paths into programs (user cycles, one thread, best of 11): | Benchmark | Free lists (16–64 bytes, 256 each) | `mi_malloc_small` | |---|---|---| | `floats` | +26.7% | −0.6% | | `dict` | −8.3% | −1.6% | | `lists` | −0.1% | −0.7% | | `arrays` | +14.6% | +12.3% | | `html` | −2.7% | −4.7% | | `records` | +4.9% | +1.6% | - **Free lists:** a freed block's size has to be computed from its header to find its list, which costs more than mimalloc's own free. With ThinLTO, `mi_malloc` and `mi_free` are about a dozen instructions inlined into the program. - **`mi_malloc_small`:** it skips one size check, and changes nothing measurable but `arrays`, which gets slower. Neither is kept. A prototype reached through a thread-local was enough to measure; one to ship would have to reach its lists through `ctx`, because a program function can resume on another thread (ADR 0032).