Runtime memory

How radlang stores managed values, how unreachable values are reclaimed, how memory limits work and how to observe usage. Managed strings, lists, structs, closures, Maps and asynchronous values live in one traced heap. A tracing collector keeps values reachable from program roots and reclaims unreachable objects, including cycles. Managed values do not use reference counting, arena rewinds or return-time compaction, and there is no alternate RC mode.

The heap uses a thread-private nursery for young allocations. A young collection traces only the calling thread’s nursery and roots; a full collection traces the whole heap while mutators are stopped. Values reachable from roots survive, and publication into older, global or cross-thread storage promotes the referenced graph before it is exposed. See gc_trace.c and the runtime’s store and transfer barriers for implementation details.

Collection is a memory safety mechanism, not deterministic resource disposal. Use using (Resource value = ...) { ... } or close() when a native resource must be released at a specific point. A finalizer or collector cleanup is a safety net, not a substitute for explicit disposal.

Current execution evidence is incomplete: Windows is unsupported; Linux, Intel macOS, iOS and Android execution gates remain unverified. This guide describes the intended traced-heap model and makes no release-acceptance claim. After the memory-model cutover, rebuild every .rlc and .rlp library with a matching compiler/runtime; stale RC or trace revisions are not compatible.

Accounting classes

Every byte the runtime accounts belongs to a memory class. sys.memory() and the memory report show live and peak bytes per class.

Class sys.memory() fields What it holds Accounted
scope arenaBytes, arenaPeakBytes Committed nursery storage in the traced heap. This is a storage category, not a lexical lifetime. Nursery storage; disjoint from managedBytes
value managedBytes, managedPeakBytes Other value storage in the traced heap, including reusable reserve. Value storage outside the nursery; disjoint from arenaBytes
transfer transferBytes, transferPeakBytes Storage accounted to the transfer class. Separately accounted runtime transfer storage
conn connectionBytes, connectionPeakBytes Memory that lives as long as a connection, stream or handle. Allocations made through the front door
process registryBytes, registryPeakBytes Registries and configuration that live for the process. Allocations made through the front door
temp tempBytes, tempPeakBytes Buffers freed before the allocating function returns. Allocations made through the front door
meta metaBytes, metaPeakBytes Collector, scheduler and runtime bookkeeping. Allocations made through the front door
stack stackBytes, stackPeakBytes Coroutine stacks (8 MB each by default) and the 64 KB signal stack of each thread. Mapped size
foreign foreignBytes, foreignPeakBytes Memory owned by SQLite, curl, BearSSL and platform frameworks. Not yet accounted

Heap storage is accounted separately for nursery and other value storage; these categories must not overlap. Runtime allocations outside the traced heap may be reported in their own classes or in process resident memory. Exact accounting for all native subsystems is still being completed.

Reachability and collection

The collector traces roots in mutator stacks and registers, globals, registered runtime roots, and live coroutine stacks. An exception handler’s saved state is also rooted while it can be resumed. A pending coroutine and its Future keep their reachable values alive; after completion, a result remains alive for as long as a program or runtime owner can reach it. Unreachable cycles are reclaimable.

Roots are conservative in some native and stack regions. A stale word that looks like a pointer can keep an otherwise unreachable object alive longer; this may increase memory use, but does not make the object unsafe to access. Use explicit collection only for diagnostics or memory-pressure handling, not as a substitute for keeping a live value reachable.

Completed async owners

As of 1.38.5, an empty async owner no longer waits for its caller to end merely because an unknown callback might have published data. Once completion leaves no arena data or resources and no runnable callbacks or borrowing children, its conservative lifetime record can be removed. If a callback can still run, the runtime waits and checks again after the final hold ends. Cleanup append and cancellation use constant-time list operations; ordinary bump allocations gain no extra scan.

The compiler also proves some global callback slots in sealed programs, where all assignments are visible. A uniquely named slot whose targets are synchronous and preserve escaping stores can release private temporary arenas at completion. This proof is separate from purity, parallel safety and return aliasing, and requires no new ownership syntax or runtime lookup. Ambiguous names, unsupported signatures and unknown stores remain conservative.

Source-less or public library callbacks can still retain nonempty producer arenas for their caller’s lifetime. Replacing that whole-owner retention needs callback-effect and argument-flow evidence across library boundaries; it is not yet a guarantee of bounded memory for every repeated async workload. Compare live scope/transfer/metadata with resident memory and stack reservations separately.

Out of memory

Every way of running out of memory ends in one error:

  • Code 507 (e.code), catchable with catch (Error e) wherever the current thread has a handler, including inside an async fn (the awaiting caller receives it).
  • Message in one format: out of memory: <what> requested <n> bytes (class <c>, in use <x> of limit <y>, process <rss>) at <function>:<line>. Fields that are unknown are left out (of limit without a limit, the location outside generated code). A size that overflows reads out of memory: <what> size overflow (class <c>, ...).
  • Without a handler: one report on stderr, the memory report below, and exit status 71.
fn main() {
    try {
        string big = "x".repeat(100000000)
    } catch (Error e) {
        if (e.code == 507) { sys.error("not enough memory: " + e.message) }
    }
}
$ RADLANG_MEM_LIMIT_MB=64 ./app
radlang: uncaught exception (code 507): out of memory: value allocation requested 198952017 bytes (class value, in use 2.0 MB of limit 64.0 MB, process 1.3 MB) at main:17
[mem] memory report (out of memory)
...

After catching the error, the program can continue when the failed operation left its state valid. Collection may reclaim unreachable values and make storage reusable; the exact amount and timing are not deterministic.

What the catching function still holds stays live until that function returns: the collector scans each frame conservatively, so a half-built list in the same function as the catch keeps the heap at the limit, and an allocation inside the catch can fail again. The compiler may inline a plain function into its caller, so its locals can live in the caller’s frame; a function that contains a try is never inlined, and a catch clears the stack its throw abandoned. Put the try that catches the failure in a function of its own, return what you need from it, and do work that allocates after it has returned. To drop a global that holds the failed value from inside the catch, assign a value made beforehand (an empty list created at startup): assigning [] allocates, and the heap is still full.

Errors raised in a callback of a parallel list call (xs.map(fn, 4)) run on a worker thread with no handler: like any error there, an out-of-memory error ends the program even inside a try.

Limits

Limits are off by default. Without them, the program can grow until the operating system or configured heap reservation prevents another allocation.

Variable Limit
RADLANG_MEM_LIMIT_MB Total accounted bytes of every class except stack
RADLANG_MEM_SCOPE_MB Legacy scope limit; no scope allocator remains
RADLANG_MEM_VALUE_MB All accounted value storage, including nursery and old storage
RADLANG_MEM_TRANSFER_MB, RADLANG_MEM_CONN_MB, RADLANG_MEM_PROCESS_MB, RADLANG_MEM_TEMP_MB, RADLANG_MEM_META_MB, RADLANG_MEM_FOREIGN_MB The class’s bytes
RADLANG_MEM_STACK_MB Coroutine and signal stacks (not part of the total)

Limits are read once, at startup. An allocation that would exceed one raises the out-of-memory error above. Limits can also be set per project in config.yaml.

config.yaml memory:

The limits and supported heap/stack sizes can be set for a project in its config.yaml. Values are baked into the program when it is built; the environment variable for a setting, when supported and set to a positive number, overrides the file at run time. Unknown keys are reported as warnings when the program is built.

memory:
  limitMB: 512              # RADLANG_MEM_LIMIT_MB
  limits:                   # RADLANG_MEM_<CLASS>_MB
    value: 256
  heapReserveMB: 4096       # RADLANG_HEAP_RESERVE_MB
  coroutineStackKB: 1024    # RADLANG_CORO_STACK_KB
  report: true              # RADLANG_MEM_REPORT
Key Default (desktop / phones) Meaning
limitMB none Total accounted bytes of every class except stack, in MB
limits.<class> none One supported memory class’s limit in MB
heapReserveMB target-dependent Traced heap address-space reservation
coroutineStackKB 8192 Stack of each coroutine (minimum 64)
report false Print the memory report at exit (RADLANG_MEM_REPORT=0 turns it off again)

Heap reservation is address space, not committed memory. Settings apply to programs and tests built with the project’s config.yaml.

Observing memory

sys.memory()

Returns a MemoryStats value (all fields long, bytes unless noted):

Field Meaning
residentBytes, residentPeakBytes The process’s resident memory now and at its peak (macOS and iOS: physical footprint)
arenaBytes … foreignPeakBytes Live and peak bytes per class (table above); the existing 26-field prefix is retained
arenaOverflowBytes, arenaOverflowPeakBytes Legacy fields in the API prefix; zero after removal of scope overflow
totalBytes, totalPeakBytes All classes except stack
limitBytes RADLANG_MEM_LIMIT_MB in bytes, 0 when unlimited
failures Out-of-memory failures so far (a count)
fn main() {
    MemoryStats m = sys.memory()
    sys.output("resident " + (m.residentBytes / 1048576).toString() + " MB")
}

The original 26 fields keep their order. Three fields follow them:

Field Meaning
gcFullCollections Completed whole-heap collections
gcYoungCollections Completed nursery collections
gcLongestPauseNs Largest observed collection interval, in nanoseconds

arenaBytes is committed storage assigned to nursery spans. managedBytes is the remainder of value storage: old spans, reusable committed reserve and native storage charged to the value class. The two are disjoint. A nursery span that contains promoted slots stays nursery storage until the span leaves the nursery; these counters describe storage, not the exact payload of live young objects. Their peaks are independent, monotonic high-water marks recorded at allocation and span transitions. They need not have occurred at the same time and must not be added to estimate a historical peak. Accounted totals are unchanged and exclude reserved coroutine stack storage, which has its own fields.

The interval counter measures private nursery collection work or the stopped-world collection proper. It excludes the whole-heap stop handshake and finalizers; a private collection can include waiting for a collector lock. It is neither a whole-program stall measurement nor a pause-time guarantee. Reporting uses allocation-free atomic snapshots, including on an allocation-failure path.

Memory in tests

The rtest namespace of the standard library turns a memory measurement into an assertion:

Function Meaning
rtest.memoryBytes() Memory in use now (sys.memory().totalBytes), a long
rtest.memoryPeakBytes() The most the process has held so far
rtest.assertMemoryBelow(bytes, "msg") Fails when the memory in use is bytes or more
rtest.assertPeakMemoryBelow(bytes, "msg") Fails when the peak so far is bytes or more
rtest.memoryAssertsActive() False under RADLANG_MEM_POISON, when both assertions pass without checking
import { rtest } from stdlib

test "building labels leaves nothing behind" {
    long before = rtest.memoryBytes()
    int total = 0
    for (int i = 0; i < 200000; i++) {
        string s = "x".repeat(200) + i.toString()
        total += s.length()
    }
    rtest.assertMemoryBelow(before + 4 * 1048576, "workload stays within its memory budget")
}

Collection and reuse are nondeterministic, so leave a workload-appropriate allowance or collect explicitly before a diagnostic measurement. Poison mode keeps reclaimed storage poisoned to catch stale reads, which is why these assertions are switched off there. Example: tests/regression/tests/memory/assert-memory.test.rad.

The memory report

RADLANG_MEM_REPORT=1 (any value but 0) prints the report when any program exits, and the report is always printed with an uncaught out-of-memory error. HTTP servers additionally keep their one line per request (see HTTP).

Report rows and collector counters can vary by runtime version. Use sys.memory() for the programmatic fields documented above.

Environment variables

Each variable below that has a config.yaml memory: key overrides it.

Variable Effect
RADLANG_MEM_LIMIT_MB, RADLANG_MEM_<CLASS>_MB Limits (above)
RADLANG_MEM_REPORT The memory report at exit; per request in HTTP servers
RADLANG_CORO_STACK_KB Stack of each coroutine (default 8192, minimum 64)
RADLANG_HEAP_RESERVE_MB Traced heap address-space reservation, where supported
RADLANG_MEM_POISON Any value but 0: poison reclaimed managed storage to help detect stale reads
RADLANG_GC_VERIFY Enable traced-heap verification diagnostics where supported
RADLANG_GC_QUARANTINE_MB With RADLANG_GC_VERIFY: MB of freed slots the verifier holds back to catch late reads (default 32, 2 under RADLANG_GC=stress); they count toward the process RSS
RADLANG_GC_STATS Print collector statistics where supported; exact counters are runtime-version dependent
RADLANG_GC_MARKERS Threads that mark during a full collection, the collecting thread included (default: the number of cores, at most 4; 1 marks serially; at most 8)
RADLANG_GC_CYCLES (runtime.gcCycles) Cycle collector of the reference-counting model (collect, stress, report, off). The traced heap (the default since 1.39) frees cycles itself and ignores it

Platform status

Windows is unsupported for this memory model. Linux, Intel macOS, iOS and Android execution gates remain unverified. A successful cross-link or host build is not target execution evidence.