MoxyMoxy
Docs contents

Memory model design

Status: proposal, 2026-11-30. M1, M2 and M3's gates are built (M3: what was built); the cycle collector (the last item under Cycles) shipped 2026-12-01 as --cycles. The user-facing rules live in docs/book/memory.md; this page is about where they go next and why.

Goal

Memory management that is easy to use and still holds up on four costs: run time, compile time, stability, and memory footprint. Dropping automatic memory management entirely (C, Zig) was on the table.

Where 0.3.1 stands

Measured on an M1 Max (arm64), macOS, cc -O2, moxy build --release.

Measurement Result
binary-trees, depth 18 × 20 (10.5M nodes): C, malloc/free 171 ms, 18.6 MB peak
same: Moxy ref struct 216 ms, 35.5 MB peak
same: C, bump arena 34 ms
atomic retain+release pair (uncontended) 13.3 ns
plain increment+decrement pair 2.5 ns
release of a 1,000,000-node ref struct chain crash, exit 139 (stack overflow)
1,000,000 two-node ref struct cycles 130 MB leaked, no warning
100,000 single-character s = s + "x" 175 ms (quadratic)

What those numbers say:

  • Reference counting is not the main cost. Moxy is 1.26x C's malloc version on the most allocation-heavy benchmark there is. The real gap is malloc itself: an arena is 5x faster than malloc in either language.
  • The header is too big. Every ref struct carries 40 bytes (strong count, weak count, drop, fmt, name). The node is 16 bytes. That's why peak memory is double C's.
  • Atomics are paid everywhere even though only values passed to a Future ever cross a thread.
  • Release recurses, so a long chain kills the program.
  • Collections go through a witness table: every element copy, drop, compare and hash is an indirect call (runtime/list.h, runtime/map.h). Since fixed: the hot list, slice and map operations are generated per element type with direct calls (src/gen/listops.mxy, mapops.mxy); the witness remains for sorting, printing and the other rare paths.
  • Cycles leak silently. weak exists, but nothing tells you that you needed it.

All of these are fixable without changing what users write.

Options

Option Run time Compile time Stability Footprint Ease Verdict
Manual (C, Zig) best best worst: leaks, double frees, use-after-free best worst no
Manual with explicit allocators (Zig) best best poor best poor for strings and collections no
Tracing GC (Go, Boehm) good throughput, pauses good good 2–3x heap best no: C can't hold GC pointers, no deterministic cleanup
Ownership and borrowing (Rust) best worst best best worst no: rejects ordinary C patterns
ARC as today (Swift) fair good fair fair good the base
ARC + compile-time elision + reuse (Perceus, Lobster) good good good good good adopt
Regions, here called gates (Cyclone, Vale, Verona) best for batch work good good if checked best fair adopt, opt-in
Generational references (Vale) good good good +8 bytes per object good no: costs a check on every dereference, nothing in it Moxy needs

Why not drop it and go manual

It would make Moxy a slower-to-write Zig with fewer features, in a space Zig, Odin and C3 already hold. Moxy's strings, lists, maps, closures, Result and futures only work because their memory is managed; manual memory means every one of them needs an allocator argument and a deinit, which is the busywork Moxy exists to remove. The measurements show the cost being paid for automation is small and mostly fixable. Manual memory stays available, as it is now: it's C.

The design

Four layers. Users write the same code they write today; each layer makes it cheaper.

1. Lean objects

  • One 64-bit word for counts: strong in the low 32 bits, weak in the high 32. Immortal values keep a reserved pattern.
  • One pointer to a static per-type descriptor: drop, fmt, name, size.
  • Header goes from 40 bytes to 16.
  • Release uses an explicit worklist, so depth never touches the C stack.

2. Count only across threads

Every count starts non-atomic. When a value is handed to another thread (a Future's arguments, its result, its captures), the compiler emits a call that marks it and everything reachable from it as shared, flipping a bit in the count word. Retain and release check that bit and use atomics only when it's set. Koka does this; Moxy can do it more cheaply because Future is the only way values cross threads, so the compiler sees every crossing.

Cost: one predictable branch per count operation on unshared values, saving about 10 ns per pair on arm64.

3. Remove counting at compile time

Moxy's values are already value-semantic and its ownership conventions (owned +1, borrowed +0) are already explicit in the code generator (src/gen/own.mxy). On top of that:

  • Last use moves. If a variable is never read again, passing or storing it transfers the reference instead of retaining a copy and releasing the original.
  • Drop specialization. A release followed by an allocation of the same size in the same function reuses the memory in place (Perceus "reuse"). Functional updates on uniquely owned lists and structs become in-place mutation.
  • Borrowing across calls. Parameters the callee only reads are never retained (extends the current rule).
  • Monomorphized collections. Once generics land, T[] and map[K, V] copy and drop elements with direct calls, and trivially copyable element types skip copy and drop entirely.

Each is a linear pass over a function, so compile time stays flat. Target: 90% of retain/release calls gone from the compiler's own generated C.

4. Gates: checked regions (the new part)

string[] summary(string path) {
    gate {
        Doc d = parse(read_file(path).unwrap());   // thousands of allocations, all bump-allocated
        return d.headings.map((Heading h) => h.title);   // copied out to the heap on return
    }   // the whole arena is freed here in one step
}

A gate is shaped like Objective-C's @autoreleasepool { }, a scoped block that bounds the life of what's made inside it, but the semantics differ on purpose. An autorelease pool still reference counts everything and only postpones some releases, which Objective-C needs because it can't always tell who owns a returned object. Moxy's compiler already tracks ownership, so postponing releases would add work. A gate removes it instead.

gate is a contextual word: it means this only directly before {, so C code using gate as a name keeps compiling.

Inside gate { }:

  • Every managed allocation comes from a bump arena owned by the block.
  • Objects in the arena have no reference counting: retain and release on them compile to nothing.
  • At the closing brace the arena is freed whole, with no per-object work.

What makes it safe is escape checking, done by the compiler:

  • A value that leaves the gate (returned, assigned to something declared outside, stored into an outside collection, passed to a Future) is deep-copied to the normal heap at that point. Strings, lists, maps, structs and enums can always be copied, so this is automatic.
  • A ref struct has identity and can't be copied silently. Letting one escape is a compile error that names the line and suggests moving the allocation out of the gate.
  • Raw C pointers into gate memory are the user's responsibility, as with any C pointer.

Arenas exist in Zig, Odin and C, but unchecked: a pointer out of the arena dangles. Cyclone and Rust check region lifetimes, but by making you annotate them. Vale has designed regions but not shipped them. Regions that are checked, need no annotations, and handle escapes by copying values out automatically haven't been done in a C-family language. They fit Moxy because Moxy's values can always be copied, and that's what makes automatic escape handling possible.

The C arena result (34 ms against 171 ms for malloc) is roughly the ceiling for parse-transform-discard work: request handlers, compilers, game frames, batch jobs.

What was built (M3, 2026-12-01)

Gate blocks, escape checking, debug poisoning, the explain and lint output, in gate functions and arenas as values are in. The user-facing rules are in docs/book/memory.md. Where the build differs from the proposal above, and why:

Counting is not switched off. The proposal had retain and release on gate objects compile to nothing. That doesn't hold up: a list, map or string decides whether it may change in place from its count (copy-on-write), so a gate list without counts can't tell it is shared; and a gate object may hold values from outside the gate (a string read from a parameter, an object from a global), whose counts only its drop gives back. So counts on gate values work as on the heap, and what goes is the rest:

  • No gate block is ever freed one at a time: free of gate memory does nothing, and the arena goes at the closing brace.
  • While a gate holds nothing from outside itself (it is clean), the last release of one of its values doesn't drop what the value holds either: it is all the gate's and goes with it. The drop is logged instead. The first time something older may reach the gate's values, the gate turns dirty and replays the log, so every count is exact again, and from then on drops run as usual. What may bring something older in: a retain of an older value while the gate is the allocation target (checked in the retain functions, behind one global flag that says whether any clean gate is open), a keep of an older value into the gate, a pop or slice of an older list, a move out of a variable or field declared outside the gate, a weak load, a receive, and the values that are always made on the heap (channels, futures, shared ref struct, and objects under --gate-stress). Immortal values (string literals, static closures) don't count. A program with a Drop impl never skips, so user code runs when it always did. At close, a clean gate's log is dropped in release builds and replayed in debug builds, where the leak report needs every object to go.

Binary-trees, the case gates are for, never turns dirty: 79 ms with drops walked, 47 to 48 ms with them skipped (C: 134 ms with malloc, 31 ms with an arena; Moxy without the gate: 158 ms; medians of 25 interleaved runs at load average 19). A gate that turns dirty early pays the checks and gets nothing from skipping: gated jsonroundtrip went from 96 to 101 ms when skipping went in (C: 101 ms with malloc, 45 ms with an arena; Moxy without the gate: 124 ms). Its rounds turn dirty at once because parse stores the heap string it is given into a global, and the retain for that store can't tell the holder is the heap; its output pieces are copied to the heap because they go into a global list. Later the same day the retain for a store into a global or a static was made with the heap as the allocation target (it is the global's reference, not the gate's), so src = s no longer turns the round dirty: all 40 rounds now stay clean, and gated jsonroundtrip went from 108.6 to 105.7 ms against 108.4 ms for C malloc and 53.4 ms for a C arena (medians of 21 interleaved runs, load average 25 to 30).

What a gate costs the rest of the program. A program that has a gate anywhere compiles its runtime with gates in: allocation goes through mxy_valloc, frees check the span, retains and drops check whether a clean gate is open, and stores check regions. That costs code that never runs in a gate. Measured by adding an empty gate { } at the end of main (medians of 15 interleaved runs, load average 13 to 19): listchurn 110 to 132 ms, binarytrees 165 to 191 ms, jsonroundtrip 131 to 154 ms, about 15 to 20%. Allocation outside every gate now goes straight to malloc/calloc instead of through the cold mxy_gate_heap call, which brings those to 130, 182 and 147 ms; it costs gated binarytrees about 2 ms (55.7 to 57.8 ms), since the in-gate path is no longer the predicted one, which is the better trade for programs whose gates are a small part of their running time. Taking the remaining checks out one at a time on binarytrees, most of what is left is the clean-gate check in mxy_drop_deep and the one in the retains (a relaxed load of a global and a branch each, on paths that run hundreds of millions of times); the store checks (keep) are a small part, since stores into fields and globals outside a gate are rare in these programs.

Store checks only where a gate can reach (not done). Generating keep only in functions the call graph can reach from a gate would be sound only with every indirect call counted: closures, function pointers, dyn and interface methods, the Drop, Format, Eq and Hash impls the runtime calls, sort comparators, and C code calling back into Moxy, which the compiler can't see at all. A conservative graph would reach most of a program that uses any of those, and the measurement above says the store checks aren't where the cost is. Not built; the per-thread gate state already makes every check outside a gate a single compare.

Regions. All arenas live in one span of address space reserved at start-up (64 GB on 64-bit systems, nothing committed until used), cut into 16 KB slots, and a table maps each slot to the gate that owns it. Finding the gate of any pointer, interior pointers included, is a subtraction, a compare and a load, so the run-time checks below are cheap, and outside a gate they are a compare. Each gate has a chain of chunks that double from 16 KB up to 4 MB; closed chunks go to a per-thread cache (8 MB) and then to a shared free list. Values allocate through mxy_valloc and friends, which follow a thread-local allocation target; the runtime's own memory (task queues, channels, fibers) always uses the heap.

Where values go. Gates nest per thread, and a gate's depth is one more than the gate open around it; the heap is depth 0. A value may be stored only where it lives at least as long: in its own region or a deeper one. Storing it somewhere older copies it there (keep): to the heap, or into an enclosing gate. Keep is deep, but stops at anything old enough, which by the same rule holds nothing younger.

The rule across calls. Functions called inside a gate allocate in it, without being compiled for it. That makes escape checking a question about every store in the program, not just the gate's block. A static answer was the first option: summarize which functions store into memory they didn't make, and run those with the gate switched off. It fails the common case of handing a parser state object made in the gate to helper functions that fill it in, since nothing static says the object is the gate's, and objects reachable from it may not be. So the check is dynamic where it has to be:

  • in the gate's own block, a store into a variable declared outside the gate copies into that variable's region, known statically (__g1.prev), and so does a return (the caller's region);
  • in every function of a program that uses gates, a store into a field, an element, a global or through a pointer is checked when it runs, against the region of the memory being written; outside a gate this is a compare;
  • a store into a field of an object the function made itself, at the current depth, and never replaced, is not checked: it lives where the function's values do (binary-trees' make() has no checks);
  • list and map operations on a place outside the current region (outer.push(x), a copy-on-write of a list held in an older object) run with the allocation target switched to that region, and what they store is kept for the region of the list or map itself;
  • x = T{...} reuses the object x holds only when it is in the region a new one would go to.

What this doesn't cover is C: a pointer into gate memory, or a Moxy value that C code keeps. Those are the program's own business, as with any C pointer.

ref struct escapes. An object can't be copied, so it can't leave. In the gate's own block the compiler rejects a return or an outside store of a value that may hold one, unless it is read straight from something declared outside the gate: deliberately conservative, since a call's result counts as made inside. Everywhere else the run-time check panics with the gate's location and the store's.

Futures and threads. Starting a future inside a gate is allowed: its arguments, and what a closure passed to it captures, are copied to the heap at the launch, as channel sends are. A task never allocates in a gate, not even one an await runs in place inside a gate. A task may open gates of its own; a fiber switch carries the gate state with the task, so a task that parks inside a gate gets it back on resume while other tasks run on its worker. Results come back on the heap.

Async calls (merged 2026-12-01, after gates). An async call is a fiber on the calling thread, but its Future can outlive the gate it was made in, so it is treated like a task, not bound to the gate: its body runs with no gate open (mxy_async_exec leaves the caller's gate state and restores it after the body, which matters where the body runs inside the call: without fibers, under a lock), its arguments and an async lambda's closure and arguments are kept for the heap at the launch, and a ref struct from inside the gate passed to one is a compile error. Binding the call to the gate instead (allocating in it, and requiring the future be awaited before the gate closes) was rejected: it needs the future's lifetime checked against the gate, which nothing else in the language does. await inside a gate already worked: the fiber switch carries the gate state, so the caller resumes in its gate and other contexts on the thread see none.

Cycles (merged 2026-12-01, after gates). Under --cycles, a gate object is never one of the thread's possible roots and is never walked by its collections: nothing older holds a gate value, so no heap cycle runs through one, and a gate object holding a heap object is a reference from outside. A gate keeps its own buffer of possible roots instead, collected as it closes with only that gate's objects walked, so the Drops of cycles made in the gate run and what they held from outside is released. A gate that is still clean at close in a release build skips it (its cycles hold only its memory, and its drops are skipped anyway). Garbage is freed through mxy_vfree, so arena memory never reaches free().

in gate functions. The proposal had functions called inside a gate allocate on the heap unless declared T f(...) in gate. The build made the allocation target follow the thread instead (above), so every function called inside a gate already allocates in it and returns without a copy, and in gate had nothing left to switch on. It is kept as a checked contract: the body is checked as if it were inside its caller's gate with its parameters counted as the caller's (a ref struct it makes can't be stored into a global; stores into globals are listed as copy-outs), a return from inside one of its own gates is an error since it would copy out, and async and Future functions can't be in gate. Code generation is unchanged apart from the --explain-gates note. If that contract turns out not to be worth a keyword, it can go without changing what any program does.

Arenas as values. std/arena.mxy wraps a runtime mxy_arena (a mxy_gate whose chunks outlive its blocks) in a shared ref struct Arena with a Drop, so it lives on the heap and may be held anywhere. gate (a) { ... } enters it: the arena's gate is pushed as the allocation target with the depth of a gate opened there, and every copy-out rule applies unchanged; the closing brace pops it without freeing and sets its depth to a value younger than any open gate, so a stray pointer into it is copied, never stored, if anything finds one. reset() and free() release the chunks (buried in debug builds, as at a gate's close); free() also marks it dead. One block at a time (an atomic flag), so nested or concurrent entry panics, as do reset()/free() inside a block and any use after free(). An arena never puts drops off: a log of skipped drops would have to live until the reset, and the arena's blocks are where it would grow. Since the escape rules hold, nothing a block makes is reachable from the next one; an arena chooses when memory is released, not what survives. Holding data in an arena across blocks would need variables typed by the arena they live in and a check against reset(), which is not designed. A shared type's Drop no longer forces MXY_GATE_NOSKIP on the program: shared objects are made on the heap, and a gate that comes to hold one turns dirty, so its drop is never put off (std/arena.mxy would otherwise have switched skipping off for every program that includes it).

Debug poisoning. A closed gate's chunks are made inaccessible (mprotect, VirtualProtect) and their slots point at a record of the gate; the most recent 256 MB stay that way before the memory is reused. A read through an escaped pointer faults, and the fault handler reports the gate's location and the current statement. Keeps and frees of such a pointer are caught too. Loads are not otherwise checked: page protection is the check. Release builds reuse closed memory at once.

Shaking out missed escapes. --gate-stress makes every function body a gate (with ref struct objects on the heap, so returning one stays legal), and runs the program in debug, so any value that escapes without being copied reads protected memory. make test runs tests/memory and tests/collections that way; the whole suite passes except tests/memory/sharedreuse (it checks that a list handed to a future becomes shared, and under stress the future gets a copy) and the gate tests themselves (whose expectations are about their own gates). Drop skipping was checked by building the suite in release with stress, with and without skipping, and comparing macOS leaks reports; that found two missed cases (objects made on the heap under stress, pops from outer lists), both fixed, but leaks treats any stale pointer as a reference, so it can miss more.

Cycles

No collector by default. Instead:

  • Static warning: the compiler builds the graph of ref struct types and their strong fields. A type that can reach itself through strong fields only gets a warning with a fix-it pointing at the field to make weak. Swift doesn't do this; it's cheap and catches the common case before it ships.

  • Debug leak report: debug builds track live ref structs and print any still alive at exit, with their allocation sites.

  • unowned: a back-pointer with no weak-count bookkeeping, checked in debug builds.

  • Collector last: an opt-in trial-deletion pass over ref structs only (--cycles), built only if real programs still need it after the warning.

    Built (runtime/cycle.h). Decisions, and why:

    • Zero cost without the flag. The collector is appended to the runtime only under --cycles; the hooks elsewhere in the runtime are #ifdef MXY_CYCLES. Without the flag every program compiles to the same object code as before (checked on the benchmarks and 87 test programs, -O0 and -O2).
    • Header unchanged. The 16-byte header has no free bits, and the debugger reads it. Per-object state (colour, buffered) is a word after the fields, and after the allocation site in debug builds, present only on types that can be in a cycle. A side table would cost a hash lookup on every buffered release.
    • Candidates. A type is one when it can reach itself through strong fields (one-way recursion counts: a Node with a Node? next can form a ring) or holds a closure or dyn value anywhere, since what those capture is out of sight. The descriptor gets a pointer to a mxy_cyc (field release and Drop apart); other types are never buffered.
    • Children come from the share helpers. Marking a value shared already walks every value shape (lists, maps, optionals, enums, value structs, closures, dyn). Under --cycles those helpers are generated even without threads, and a thread-local visitor turns marking into looking: mxy_rc_mark reports instead of marking, mxy_obj_share hands the object to the collector, weak and unowned fields are skipped. A container held more than once is not looked into (it may be held from outside); the root is kept for the next collection.
    • When. Never inside a release: between a release and the store after it a field can name an object it no longer counts. At a ref struct allocation once the buffer passes its limit (10,000, raised to the live objects the last collection walked), when main returns, when a pool task ends, and on cycles::collect().
    • Freeing. Garbage is held, its internal counts restored, then every Drop runs with all fields intact, then every field is released, then memory is freed (or tombstoned for weak references). Weak loads of garbage return null from the moment it is found. A Drop that resurrects garbage panics.
    • Threads. Only unshared objects are candidates, buffers are thread-local, and a shared object counts as an outside reference. Shared cycles are not collected.

    Measured (release, M1 Max, load average 10 to 16): binary-trees 158 to 183 ms (+16%), list churn 102 to 125 ms (+23%), peak memory +42% and +29% (the extra word); a million two-node cycles 63 MB leaked without, 3.9 MB peak with.

Order and checkpoints

  1. Lean objects and iterative release. No language change, fixes the crash and halves ref struct memory.
  2. Bench suite in CI with C baselines (bench/).
  3. Thread-shared bit and non-atomic counts.
  4. Ownership inference and reuse, after generics.
  5. Checkpoint: allocation-heavy benchmarks within 1.5x of C malloc. If not, stop and rethink before gates.
  6. Gates and escape checking.
  7. Cycle warning, leak report, unowned.

Risks

  • Escape checking misses a path. A missed escape is a use-after-free. Mitigation: debug builds make closed gates' memory inaccessible, so a read through an escaped pointer faults and is reported with the gate; --gate-stress runs code with every function body a gate (in make test for the memory and collection tests). Not checked on every load in software: page protection is the check.
  • Skipping drops misses an older reference. A gate that stays clean while one of its values holds something older leaks that value's count (a leak, not a use-after-free). Mitigation: the triggers are listed above; checked by comparing leak reports with skipping on and off.
  • Deep copies on escape are a hidden cost. Mitigation: moxy lint reports every copy-out with its size class, and --explain-gates prints them.
  • The shared bit is set too eagerly. Marking a large structure shared walks all of it. Mitigation: mark lazily, at the first retain from the other thread.
  • Compile time. All analyses are per function and linear. The self-compile budget (under 100 ms) is checked in CI.

Edit this page on GitHub