louise
The Louise language: compiler, runtime, std, tooling
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
ADR 0028: Mailboxes under contention, and memory per actor
Status: Proposed — 2026-10-11 (issue gabla108/louise#98); needs engineering review (gabla108/louise#44).
Context
- ADR 0004 Revision 1 planned lock-free mailboxes and an atomic actor state. Revision 2 chose per-actor locks instead: everything other actors touch (
Proc: the mailbox, the wait state, links, monitors, the run state) is behind the actor's ownstd::sync::Mutex. It said the choice would be revisited if profiling showed a hot actor's lock. No benchmark had a hot actor: intests/bench/messages.lse(a ring) each actor has one sender. - The goal is many cheap actors: 100,000 and more, in close to no memory each.
- Issue gabla108/louise#98 asked for a loom model of the mailbox, and for a measurement of the lock on many threads. The model is in
runtime/louise_rt/src/otp.rs. It found a bug (an actor killed while it ran could then park for good, fixed in the same change).
How other runtimes do it
- BEAM splits the queue. Senders append to an outer queue under the receiver's
msgqlock. The owner moves the whole outer queue into a private inner queue, which selective receive scans without a lock. The split dates from the first multi-threaded emulator (R13): senders never touch what the owner scans. The outer queue stayed locked. OTP 25 measured many senders to one receiver collapsing on that lock, and adds 64 lock-protected buffers to a receiver once its lock is found taken often (per-sender order is kept by hashing the sender), and removes them when contention ends. The run state is one atomic word (ACTIVE,IN_RUNQ,MSG_SIG_IN_Q...): a sender sets a flag and schedules the process if it was inactive. Any message wakes the receiver; the sender does not look at what it waits for. Since OTP 21, links and monitors are signals in the same queue, so a process has no link lock. A process takes 327–338 words (about 2.6 KB) when spawned, its 233-word heap and stack included. - Pony: a lock-free intrusive MPSC queue per actor (one atomic swap per push). The sender that finds the queue empty schedules the actor. No selective receive; behaviours run on the scheduler thread's stack, so an actor has no stack of its own (about 270 B).
- CAF: one atomic word per inbox, an intrusive LIFO pushed with a CAS. Tag values mark it empty, closed, or with its reader blocked, and the push that replaces "blocked" schedules the reader. The owner takes the whole stack at once into private queues. This is BEAM's split, lock-free, and the CAS lets a closed inbox refuse messages.
- Akka: a lock-free queue and an atomic status word, whose CAS decides which sender schedules the mailbox. Tokio: one atomic word per task (
RUNNING,NOTIFIED...); a notification to a running task only sets a bit, and the thread running it queues it again, asRunStatedoes. Go: channels are locked.
Sources: OTP's erl_proc_sig_queue.h/.c, erl_process.h, erl_process_lock.h; the Erlang blog post "Parallel signal sending optimization" (OTP-16982); OTP 21 release notes (OTP-14589); the efficiency guide (processes, memory); ponyc's messageq.c and actor.h; CAF's lifo_inbox.hpp; Akka's Mailbox.scala; Tokio's task/state.rs; Go's runtime/chan.go.
Measurements
A release build (clang, mimalloc), a 22-thread laptop shared with other work (load average 2–3), best of 5. Contention is counted with --features lock-stats (below), in a separate run.
| Benchmark | Threads: 1 | 2 | 4 | 8 | 22 | Locks found taken |
|---|---|---|---|---|---|---|
messages (a ring, 1 sender per actor) | 60 ms | 60 | 60 | 62 | 61 | 0 |
parallel (64 actors computing) | 1052 ms | 546 | 300 | 172 | 122 | 0 |
fanin (64 senders, one collector, 1.28M messages) | 112 ms | 316 | 469 | 479 | 539 | 28–41% |
idle (spawn 100k actors that wait) | 1200 ms | 1045 | 1148 | 1186 | 1244 | 0.03% |
The lock is not the cost of sending, but it collapses under fan-in. With one sender per receiver, no acquisition in a million found the lock taken. With 64 senders to one actor, a third did, and 22 threads ran 4.8 times slower than one: about 210 ns per message, against 44 on one thread.
To separate the lock from the rest of the scheduler, runtime/louise_rt/examples/inbox_fanin.rs pushes 2.56M messages from P threads into one inbox that one thread drains (ns per message, best of 5):
| Producers | Lock per push and per take (today) | Locked outer queue, swapped out whole (BEAM before OTP 25) | Lock-free MPSC (one swap per push) |
|---|---|---|---|
| 1 | 124 | 62 | 101 |
| 2 | 129 | 95 | 61 |
| 4 | 159 | 126 | 69 |
| 8 | 164 | 147 | 62 |
| 21 | 197 | 201 | 66 |
The lock alone accounts for the 200 ns fanin reaches. A locked outer queue only helps with few senders; this is what OTP 25 had to fix. A lock-free inbox stays flat, about 3 times cheaper than a lock from 8 senders. One consumer still bounds the throughput: no design makes fan-in faster on 22 threads than on one.
Where fanin's time goes on 22 threads (perf record -g, kernel included). It takes 9.2 s of CPU for 0.55 s of wall time, and 7.5 s of that CPU time is in the kernel. One thread takes 0.1 s, all of it in user space. It makes 347,277 voluntary context switches (3 on one thread), about one for every 4 messages.
Two thirds of all cycles (66–70%) are in the kernel's native_queued_spin_lock_slowpath, under the lock of the futex hash bucket. 40% come through futex_wait, called from the actor lock in deliver: senders parking on the collector's lock. Another 26–28% come through futex_wake, as each unlock wakes a parked sender. Every sender waits on the same futex word, so they queue on one kernel lock as well. The user-space part, out of user time only:
| Function | Share |
|---|---|
Mutex::lock_contended (the actor lock, spinning) | 47% |
Shared::with_proc for deliver (the lock's fast path, inlined) | 28% |
Shared::cell (finding the receiver in the actor table) | 15% |
Proc::deliver | 3% |
Shared::cell takes the table's RwLock for reading and clones the receiver's Arc. Both are atomic writes to lines every sender shares, so even without the actor lock, each send would still write twice to contended lines.
Memory per idle actor (idle.lse, 100,000 against 1,000 actors, sampled while they wait):
| Per actor | |
|---|---|
| Resident memory | 5.2 KiB |
| Page tables (not counted as resident) | 4.3 KiB |
| Memory mappings | 2 |
That is about 9.5 KiB per actor, 0.95 GB for 100,000, against about 2.6 KB per BEAM process. The mailbox's share is a few words: the mutex is 8 bytes, an empty map allocates nothing, and a lock-free inbox would take 8 to 16 bytes. Stacks dominate. Each compiled actor reserves 64 MiB (PROGRAM_STACK_SIZE, committed lazily) above a guard page: at least one touched 4 KiB page, a page-table page of its own (each reservation spans its own 2 MiB regions), and two mappings, since the guard page splits it. idle takes about 12 µs per actor, from its spawn to its unwinding at exit. 70% of it is kernel time (0.84 s of 1.18 on one thread), with 1.3 page faults per actor. Of all its cycles:
- 40–43% are in
munmap: as each actor unwinds at exit, its stack is unmapped (the pool keeps 256), in a tree of 200,000 mappings; - 16% are page faults: the first touch of each stack, with its page table;
- 5.5% are in
mprotect, for the guard pages;mmapitself is negligible (the pages are committed lazily).
In user space, the time is spread over the scheduler loop, fiber switches and frees.
Decision
- Keep the per-actor lock for links, monitors and exits. They are rare, and their ordering with exits is simplest under one lock.
- Replace the mailbox's lock by a lock-free inbox with an owner-private mailbox (to implement and measure: issue gabla108/louise#136):
- A send no longer looks the receiver up in the actor table under its
RwLock, cloning anArc: a subject carries what finds the receiver's inbox without a shared write (for example a reference kept alive by the table until the actor finishes, asActor::with_procalready relies on for the running actor). - The inbox is one atomic word, CAF's design: an intrusive LIFO of message nodes, pushed with a CAS, with tag values for "empty", "closed" (the actor exited: a push fails and the message goes back to its sender, as now) and "owner waiting".
- The push that replaces "owner waiting" schedules the actor. This replaces the sender's look at
waiting_tagsandRunState.queuedfor messages. - The owner takes the whole list with one swap, reverses it (push order), and files it into the tag map it already has (
Mailbox), which only it touches. Arrival numbers are assigned then. Per-sender order is kept. - Before parking, the owner swaps "empty" for "owner waiting"; if the swap fails, messages arrived and it files them first. That swap happens on the scheduler side, after the fiber is suspended (as
RunState::stopdoes today), so no thread resumes a fiber still on its way out. - A message on a tag the owner does not wait for wakes it, as in BEAM; it files the message and parks again.
- Timers and kills wake a waiting owner the same way, by pushing a signal node: a timeout carries its wait number, so the owner drops a stale one, as
Proc::time_outdoes now. A kill still sets the kill flag and marks the actor exited under its lock first.
- A send no longer looks the receiver up in the actor table under its
- Make memory per actor its own work, with a budget of 2 KiB per idle actor (issue gabla108/louise#137). The candidates are smaller, packed stack reservations, which share page tables; giving back the pages of parked and pooled stacks; and moving an idle actor's stack out of its own mapping. Each changes how deep a compiled actor can recurse, which ADR 0004 matched to the interpreter, and needs its own ADR.
--features lock-stats (off by default) counts, per scheduler thread, actor-lock acquisitions and those that found the lock taken, and prints them at exit with LOUISE_LEAKS. It is how the contention above was measured, and how the change in point 2 is checked.
Consequences
- Until point 2 is implemented, an actor many others send to (a logger, a registry, a shared cache) serialises them, and gets slower with more threads.
- Point 2's targets:
faninon 22 threads within 2 times its time on one thread (4.8 times today);messagesandparallelwithin 5% of their times now; no more memory per idle actor. The loom models inotp.rsare rewritten for the inbox first: they already cover sends racing receives, timeouts and kills. - Each message costs a node (about 24 bytes) until it is filed, against a slot in the tag map today.
- Senders no longer read what the receiver waits for, so a selective receive can wake for nothing. The cost is a wake-up per message the receiver does not want at that moment, such as requests arriving while a server waits for a reply. Measured with the change.
- The models' first finding, an actor killed while it ran parking for good, is fixed.
Proc::park_asleaves an exited actor ready, except in a blocking call, so it is queued again and unwinds.
Alternatives rejected
- Keep the lock for messages too. It costs nothing with one sender per receiver, the common case, but it collapses under fan-in, which OTP designs produce on purpose (a server many clients call).
- BEAM's split with a locked outer queue. The microbenchmark matches what OTP 25 measured: with 16 senders or more, it is no better than one lock.
- BEAM's OTP 25 buffers, added under contention. They make a locked queue scale, at the price of 64 buffers per contended actor and a protocol to install and remove them. A lock-free inbox scales without them, and they could still be added later if one inbox line becomes the bottleneck.
- Vyukov's MPSC queue (Pony's). One swap per push, cheaper than a CAS loop under contention, but a push cannot fail, so an exited actor cannot refuse messages. They would need another way to reach their sender for freeing.
- Links and monitors as signals in the inbox (OTP 21). It would remove the last lock, but exits, links and monitors would have to be argued again in terms of signal order. They are rare enough that their lock is not where the time goes.
Revision 1 — 2026-10-12: implemented (issues gabla108/louise#136, gabla108/louise#137)
Status: Proposed; needs engineering review (gabla108/louise#44). It also changes the runtime ABI (version 3, below).
The inbox (issue gabla108/louise#136)
Implemented as decided in point 2 (runtime/louise_rt/src/inbox.rs, otp.rs), with these differences:
- Finding the receiver: a per-thread cache of cells (
sched::SendCache, 64 slots), not a reference carried by subjects, which would have changed what a subject is. A cached cell may outlive its actor, but its inbox is closed then and a send to it is refused, as one to an unknown pid is; pids are never reused. A pid is cached on its second miss in a row in its slot. Otherwise a thread sending to many actors in turn (the 1,000-actor ring) evicts an entry on every send, which mademessages4% slower than having no cache at all. Without the cache,faninon 22 threads took 303 ms (2.6 times one thread), against 149 ms with it. - Timers and kills wake a receive under the actor's lock, not through signal nodes: they take that lock anyway.
WAITINGmay then outlive the wait it was set for. A push that clears it tries a wake-up, andProc::woken_by_messagerefuses it unless the actor waits in a receive, so it is harmless (a message never wakes a sleep). - Handing a message over: a sender that finds the receiver waiting, with an empty inbox and its lock free (
try_lock, so it never waits), hands the message over if the receiver waits for its tag. That costs no node and nothing for the receiver to take: a ring, or a call's reply. Without it,messageswas 8.5% slower on one thread. Under fan-in the lock is often taken, and senders push. - A message the receive waits for skips the tag map (
otp::take_wanted). Nodes come from mimalloc. A resumed receive takes one lock, not two. - Spurious wake-ups: a message on a tag the receive does not wait for wakes it, at most once per wait. The new
tests/bench/selective.lsemakes 50,000 calls, each waiting on its own reply subject while 4 actors flood its other subject. It is faster than before at every thread count (below).
Memory per idle actor (issue gabla108/louise#137)
None of these changes how deep a compiled actor can recurse, so point 3's condition (an ADR of their own for changes to recursion depth) does not apply.
- Hibernation. An actor parked in a receive or a sleep for 400 to 600 ms of wall time has its stack saved and given back, and written back in place before it next runs, whatever wakes it. An idle actor's stack holds 688 bytes, against the 4 KiB page and the 4 KiB page table it kept resident.
- Each scheduler thread lists the actors that park on it, and looks at them again two epochs (200 ms each) later.
- Blocking calls are excluded, since they run on the actor's values. So are socket waits, which are meant to be short.
- It uses wall time, not the scheduler's clock, so it changes no behaviour, only memory.
LOUISE_PARKED_EPOCH_MS=0hibernates every parked actor at once. CI runs every native test program that way, and they pass under ASan and TSan too.- An epoch of 50 ms made
timers10% slower on one thread: its 2,001 servers are idle longer than that between calls.
- Stacks:
- Stack tops are aligned on 2 MiB, so a hibernated stack's page tables are freed as well: Linux's
CONFIG_PT_RECLAIMfrees one only when the whole range it maps is released. - Stacks start a varying distance below that top, in steps of a page and a cache line. Aligned alike, every stack's top frames fell in the same cache sets, which cost the ring 5%.
- The pool keeps up to 16,384 finished stacks, given back beyond the first 256.
- At exit, stacks are no longer unmapped one by one; unwinding and
defers still run.
- Stack tops are aligned on 2 MiB, so a hibernated stack's page tables are freed as well: Linux's
- Fewer and smaller allocations:
- A fiber's channel and result share one allocation.
- A receive keeps one tag inline.
- Links, monitors and exit-signal settings are allocated on first use.
- Runtime ABI 3:
ctx->xargspoints at the running thread's slots. The 26 slots for call arguments beyond the sixth were part of every actor's context: 208 of anActor's 336 bytes.run_slicepointsctx->xargsat the resuming thread's slots.- It is safe because nothing suspends between a caller's stores and the callee's copy (
docs/runtime-abi.md). - Generated C is unchanged.
- The new
tests/run/many_arguments.lsecovers it. With a deliberately stale pointer, it fails in 10 runs of 10.
- The budget's mapping item was wrong.
MADV_GUARD_INSTALLguards would make a stack one mapping instead of two. But their markers live in page tables: 4.26 KiB per stack, against about 230 bytes of kernel memory per mapping. Two mappings per actor stay.
Measurements
Memory: idle.lse with 100,000 against 1,000 actors, sampled 3.5 s after spawning, so after hibernation.
| Per idle actor | Before | After |
|---|---|---|
| Resident memory | 5.2 KiB | 1.59 KiB |
| Page tables | 4.3 KiB | 0.26 KiB |
| Total | 9.5 KiB | 1.85 KiB (budget: 2 KiB) |
| Mappings | 2 | 2 (and about 0.45 KiB of kernel memory for them) |
- Where the memory goes:
- 688 bytes of saved stack;
- the
Actor(136 bytes) and itsCell; - the program's own values;
- one page of upper-level page tables per GiB of stack address space, shared by about 15 stacks.
- Possible next steps:
- Smaller stack reservations would share those upper-level pages, but they change recursion depth (ADR 0004).
- Until actors hibernate, spawning 100k actors on one thread peaks at about 530 MB.
Time: release builds, the runtime before this revision (gabla108/louise#138) against after, interleaved, best of 9 to 15, pinned to the performance cores. On this hybrid CPU, the same build's best time varies by 3–5% from one batch of runs to the next.
| Benchmark | 1 thread | 11 threads | 22 threads |
|---|---|---|---|
fanin | 107 → 89 ms (−17%) | 508 → 90 ms (−82%) | 546 → 144 ms (−74%) |
selective | 41 → 39 ms (−6%) | 101 → 44 ms (−56%) | 102 → 48 ms (−53%) |
messages | +3 to +8% (55 → 58 ms) | +3% | −2% |
parallel | +3% | 0% | not measured |
idle (spawning) | 1211 → 732 ms (−40%) | 1169 → 1023 ms (−12%) | not measured |
timers | +0 to +10% | −11% | not measured |
- The targets:
faninon 22 threads takes 1.6 times its one-thread time, within the 2 times aimed for (4.8 times before).messagesis at the 5% limit on one thread, and within it on more.- Memory per idle actor fell rather than grew.
- Instructions, one thread, exact:
messagesruns 13% more user-space instructions,timers11%: the inbox's atomic operations and the hibernation bookkeeping.- Kernel instructions fall by 18–47% in
messages,timersandidle, mostly because stacks are no longer unmapped one by one.fanin's grow by 56%; that was not investigated (it runs 17–82% faster).
Verification
- loom:
- The
otpmodels run the inbox andProctogether on a model scheduler. They pass bounded to 3 preemptions (in CI) and unbounded (9 minutes). - Bounded, they still find each of these, introduced on purpose: a sender that does not wake a waiting receiver, whether it pushed or handed over;
stopparking without re-checking the inbox; an exit that does not interrupt a receive; a hand-over that does not wake.
- The
- Tests and CI:
- The full
scripts/ci.shpasses, withLOUISE_CI_TSAN=1. - That includes ASan and UBSan, the native programs on several threads, the native programs with immediate hibernation, the stress tests, the demo, and the demo under load with the leak oracle.
- The full