Under the Hood

Two systems do most of the runtime's work: a multithreaded event loop that powers async/await, and the reference-counting allocator that manages every heap value. This page walks through both with architecture diagrams, then compares marina's approach with Swift, Go and Rust.

The event loop & async threads

Marina compiles async functions ahead of time into state machines — there is no VM, no interpreter, and no green-thread scheduler. The compiled binary links libmarina_runtime.a, which starts a small thread pool and a timer thread. Every blocking operation (fs, net, sql, http) runs as a task on the pool; continuations after await are tasks too.

  • Worker pool — min(hardware_concurrency, 8) threads pulling from a shared task deque under one mutex + condition variable.
  • Timer thread — a binary min-heap of setTimeout entries ordered by (due, seq); a due timer becomes an ordinary task.
  • Quiescence — the main thread blocks in marina_event_loop_run() until no queued tasks, no running tasks, no pending timers, no unresolved promises, and no listening HTTP servers remain, then the process exits.
flowchart TB
    subgraph MAIN["Main thread"]
        M1["compiled main()"] --> M2["async main() state machine
kicked off with resume(frame, 0, null)"] M2 --> M3["marina_event_loop_start()
spawns worker pool + timer thread"] M3 --> M4["marina_event_loop_run()
waits on condition variable"] end subgraph POOL["Worker pool — min(cores, 8) threads"] W1["worker 0"] W2["worker 1"] W3["worker n"] end subgraph TIMER["Timer thread"] T1["min-heap of timers
ordered by (due, seq)"] end Q[("Task deque
std::function<void()>")] M3 --> POOL M3 --> TIMER W1 & W2 & W3 -- "pop task
running += 1" --> Q T1 -- "timer due:
push callback task" --> Q W1 & W2 & W3 -- "task done
running -= 1
notify_all" --> M4 M4 -. "quiescent when tasks are empty,
running == 0, timers empty,
pending_promises == 0,
pending_listeners == 0" .-> EXIT["process exits (0)"] LISTEN["HTTP server listening"] -. "never quiescent
(Ctrl-C to stop)" .-> M4

What await actually does

The compiler splits every async function at each await into segments. Each segment is a case in a generated resume(frame, state, value) function — the frame is a plain heap block holding the locals. await promise compiles to marina_await(promise, resume, frame, next_state): the frame is parked and the worker thread moves on immediately. When the promise resolves, a waiter task runs the continuation on some worker thread — the value crosses threads by reference-counted ownership, never by shared mutable state.

sequenceDiagram
    participant A as async fn (segment N)
    participant P as Promise
    participant Q as Task deque
    participant B as Worker (blocking work)
    participant C as Worker (continuation)

    A->>P: marina_await(promise, resume,
frame, state N+1) alt not resolved yet P->>P: waiters.push({resume, frame, state})
(await consumes the caller's +1 ref) Note over A: frame parked —
thread is free immediately else already resolved P->>Q: waiter task (same semantics) end Note over B: e.g. fs.readFile body —
blocking syscalls are fine here B->>B: run blocking work B->>P: marina_promise_resolve(promise, value)
(first resolve wins) P->>Q: schedule one waiter task per waiter
(task retains a copy of the value) Q->>C: run_waiter C->>A: resume(frame, N+1, &value) Note over A: execution continues after await,
on whichever worker picked it up C->>P: release the waiter's promise ref
async function load(path: String): String {
    let text = await fs.readFile(path)   // parks the frame here
    return crypto.sha256(text)          // runs in a continuation segment
}

The same machinery backs setTimeout (timer → task) and promise executors (new Promise runs synchronously, JS semantics). Promises are ARC-managed too: creating one registers it as pending so the loop can't exit while work is outstanding.

The HTTP accept loop

Blocking servers (http.listen) occupy one listener thread, but the express-style server.listen(host, port) uses a poll(2)-multiplexed accept loop — a single thread watches every connection's file descriptor, so thousands of idle keep-alive connections cost nothing until they have data. Handlers are async: each request becomes a task on the worker pool.

flowchart LR
    L["listener thread"] --> P["poll(2) over all
registered fds"] P -- "listening fd readable" --> ACC["accept() →
register new fd"] P -- "connection fd readable" --> REQ["read request →
run async handler
as a task"] ACC --> P REQ --> RES["res.json / res.send
(write when ready)"] RES --> P

Memory management: ARC

Every heap value — strings, arrays, objects, promises — carries a 16-byte header with a lock-free atomic reference count. The compiler inserts retain/release calls during codegen: a value assigned into a variable, array slot or object field takes a +1; overwriting or leaving scope drops it. When a count hits zero the object is freed immediately and deterministically — there is no garbage collector, no tracing, no pauses.

flowchart TD
    LIT["String literal —
interned at first use"] --> IMM["rc = -1 (immortal):
retain/release are no-ops"] NEW["Alloc: string / array /
object / promise"] --> RC1["header.rc = 1
(creator owns it)"] RC1 -- "assign, pass, store
in array/object field" --> RET["retain: rc.fetch_add(1)
lock-free atomic"] RET --> LIVE["value alive"] LIVE -- "overwrite, leave scope,
frame dropped" --> REL["release: rc.fetch_sub(1)
acq_rel ordering"] REL -- "old value was 1" --> FREE["free_obj:
release elements (deep drop),
return block to the heap"] REL -- "other owners remain" --> LIVE
flowchart LR
    subgraph OBJ["Any ARC object (StrObj, ArrayObj, ObjectObj, Promise)"]
        direction LR
        H["Header — 16 bytes:
atomic<i64> rc · kind · pad"] --> PAY["payload:
e.g. len + UTF-8 bytes,
vector<MValue> elements,
class fields"] end subgraph FRAME["Compiler-managed blocks (not refcounted)"] F1["async frame — locals,
state, owned values
dropped by generated code"] F2["closure env — captured refs
released by an env_drop fn"] end

A few rules make this safe across threads: counts are atomic (a value can be retained on one worker and released on another), element drops are deep (freeing an array releases every element), and background tasks record an Owns list of retained payloads that is released when the task finishes — so an I/O task can't outlive its arguments.

ARC vs Go GC vs Rust ownership

Marina / Swift (ARC)Go (GC)Rust (ownership)
When is memory freed?The instant the last reference dropsSome time after it becomes unreachable, in a GC cycleThe instant the owner's scope ends (compile-time inserts the frees)
Runtime costAtomic increment/decrement per assignmentConcurrent mark & sweep; write barriers, GC assists, larger heapsZero — everything is decided at compile time
Pause timesNone (destruction is incremental)Very short stop-the-world pauses, plus CPU stolen by the collectorNone
Reference cyclesLeak (Swift: break with weak/unowned; marina: none of these yet)Collected automatically — cycles are fineCompile error unless you opt in (Rc<RefCell<_>> + Weak)
Programmer burdenAlmost none; mind cyclesNoneHigh — fight the borrow checker for shared mutation
Deterministic destructionYes (RAII-style drops)No (finalizers are not prompts)Yes
flowchart LR
    subgraph ARC["Marina & Swift — reference counting"]
        A1["assign: +1"] --> A2["last release: 0"] --> A3["freed immediately"]
    end
    subgraph GC["Go — concurrent mark & sweep"]
        G1["object becomes
unreachable"] --> G2["next GC cycle:
mark reachable set"] --> G3["sweep frees it later"] end subgraph OWN["Rust — compile-time ownership"] R1["move transfers ownership"] --> R2["scope end"] --> R3["freed immediately,
no runtime bookkeeping"] end

Swift — ARC with escape hatches

Swift is marina's closest cousin: the compiler also inserts retain/release. Swift additionally has weak/unowned references and autorelease pools; marina currently has neither (cycles leak, same as a Swift cycle you forgot to break).

class Node {
    var next: Node?          // strong reference
}
var a = Node()
var b = Node()
a.next = b
b.next = a        // cycle: both stay at rc = 1 forever → leak

class Parent {
    weak var child: Child?   // weak: does not bump the refcount
}

Go — the runtime decides

In Go you never think about ownership: objects live as long as they are reachable, and the concurrent collector (tri-color mark & sweep with write barriers) reclaims them — cycles included — in background cycles with very short stop-the-world phases. The price is a bigger heap and CPU time you don't control.

type Node struct {
    next *Node
}

func main() {
    a := &Node{}
    b := &Node{}
    a.next = b
    b.next = a
    a, b = nil, nil   // cycle is unreachable — the GC collects it
    runtime.GC()      // ...at some point like this (or on its own)
}

Rust — the borrow checker decides

Rust enforces a single owner per value at compile time. Assignment moves; borrows (&/&mut) are checked so no aliasing mutation can exist. Nothing runs at runtime — which is why there are no refcount atomics and no GC pauses — but shared mutation needs explicit opt-in (Rc, RefCell, Arc, Mutex).

struct Node {
    next: Option<Box<Node>>,   // Box: single owner, freed on drop
}

let a = Node { next: None };
let b = a;              // move — `a` is no longer usable
// println!("{}", a.next.is_none()); // compile error: value moved
let r = &b;             // borrow — checked at compile time

use std::rc::Rc;
let shared = Rc::new(Node { next: None });  // opt-in refcounting
let also = Rc::clone(&shared);              // rc: 2

Marina — ARC in an AOT C++ runtime

Marina programs read like Swift: plain assignment, no annotations, deterministic destruction. The counting happens in the generated LLVM IR calling the C runtime — marina_retain / marina_release — so it behaves exactly like the diagram above: freeing is immediate, cycles leak, and there is no collector to tune.

class Node {
    public name: String
}

let a = new Node()       // rc = 1 (a owns it)
let b = a               // same object — retain (+1)
b.name = "shared"

let list = ["a", "b"]   // array owns its element strings
let copy = list         // retain the array (+1), elements untouched

// when a, b, list, copy leave scope the compiler emits:
//   call void @marina_release(ptr %b)
//   ...
//   call void @marina_release(ptr %list) ; frees when the count hits 0
// (a reference cycle would keep both counts above 0 — same as Swift)
Design rule of thumb: Swift's ergonomics + Rust's determinism, without Rust's type-system burden. The trade-off accepted for v0.2 is that reference cycles leak — same as Swift with strong references — while Go would have collected them.