Browse documentation

Garbage Collector

Unified mark-and-sweep garbage collector shared by the bytecode VM, the built-ins and the runtime.

Executive Summary

  • Mark-and-sweep — Two-phase tracing GC (Goccia.GarbageCollector.pas) for every GocciaScript value: each TGocciaValue registers via AfterConstruction and overrides TraceReferences to mark what it owns; generation-counter marking (AdvanceMark) clears marks in O(1), and explicit collections are serialized across worker threads because some intrinsic objects are shared
  • Marking does not recurse per object — A trace nests at most 64 objects deep on the native stack and puts the rest on an explicit mark stack, so a collection marks a chain of any depth (ADR 0147)
  • Weak references and finalization — WeakMap, WeakSet, WeakRef and FinalizationRegistry use post-mark weak tracing and sweeping hooks, so weak targets never become strong roots; WeakRef construction and deref() keep targets until the next host job checkpoint, and FinalizationRegistry cleanup jobs run after the normal microtask queue
  • Pinned singletons — undefined, null, true, false, NaN, Infinity are pinned once at engine startup; built-in prototypes are pinned per-engine via realm slots and released atomically when the realm is destroyed
  • Collection under memory pressure — Script execution collects only at the VM's pressure checkpoints, when either the tracked bytes or the heap manager's in-use total nears the --max-memory ceiling (ADR 0129); both triggers back off above what a collection cannot reclaim (ADR 0141); the heap trigger also fires once the heap has grown to four times what the last collection left (ADR 0145), and there is no allocation-count collection while a script runs
  • Two refusal contracts — the --max-memory ceiling refuses a charged allocation with a catchable RangeError and a gated growth point with the script-opaque MemoryLimitError. Both force a collection and re-test before refusing; they differ in what the guest can do about the answer, not in how it is reached (ADR 0110)

Value Integration

Every TGocciaValue participates in the garbage collector:

var
GCCurrentMark: Cardinal; // Shared generation counter
​
TGCManagedObject = class
private
FGCMark: Cardinal; // Per-object mark — matches GCCurrentMark when alive
FGCIndex: Integer; // Index in FManagedObjects for O(1) unregistration
public
procedure BeforeDestruction; override;
class procedure AdvanceMark; static; inline;
procedure MarkReferences; // Marks, then traces or pushes
procedure TraceReferences; virtual; // protected: marks what it holds
function TraceWeakReferences: Boolean; virtual;
procedure SweepWeakReferences; virtual;
property GCMarked: Boolean read GetGCMarked write SetGCMarked;
property GCIndex: Integer read FGCIndex write FGCIndex;
end;
​
TGocciaValue = class(TGCManagedObject)
procedure AfterConstruction; override; // Auto-registers with GC
function RuntimeCopy: TGocciaValue; virtual; // Create a GC-managed copy
end;
  • AfterConstruction / BeforeDestruction — Every value auto-registers with the thread-local TGarbageCollector.Instance upon creation and unregisters before destruction so root sets cannot retain stale object pointers. A value the memory limit refuses in AfterConstruction is unregistered there, unless its constructor has no implicit exception frame (a number box in a production build; see Managed Locals on Hot Paths): FPC then does not destroy it, and it stays registered until a collection frees it.
  • MarkReferences / TraceReferences — MarkReferences is not virtual: it sets FGCMark := GCCurrentMark (marking the object as alive for the current collection) and returns at once when the object is already marked, so a cycle ends at the mark. AdvanceMark increments the shared GCCurrentMark while the collector lock is held. A newly marked object's TraceReferences runs once per collection, and again only during an overflow rescan, so it must be idempotent: subclasses override it to mark the values they reference (e.g., TGocciaObjectValue marks its prototype and property values, TGocciaBytecodeFunctionValue marks its closure's home object and upvalue cells, TGocciaArrayValue marks its elements) by calling MarkReferences on each. See Mark stack for where that call runs.
  • TraceWeakReferences / SweepWeakReferences — Optional hooks for weak containers and weak references. The default implementations do nothing. WeakMap uses TraceWeakReferences as an ephemeron pass: if a key is already marked by normal roots, its value is marked, but the key is never marked by the map. WeakMap and WeakSet use SweepWeakReferences to remove entries whose keys/values remain unmarked. WeakRef clears an unmarked target, and FinalizationRegistry removes dead cells while enqueueing cleanup jobs for their held values.
  • RuntimeCopy — Creates a fresh GC-managed copy of the value. The default implementation returns Self (for singletons and complex values). Primitives override this: numbers reuse the special-value singletons (0, 1, NaN, ±Infinity, -0) and otherwise create a fresh instance, booleans return singletons, strings create new instances (cheap due to copy-on-write).

Contributor Rules

When working with the GC, follow these rules:

  • Override TraceReferences in every value type that holds TGocciaValue references. Call inherited first, then call MarkReferences on each owned reference. Do not test GCMarked at the top: the object is already marked when its TraceReferences runs, so that guard would skip the whole body. Do not call TraceReferences on another object either; MarkReferences decides whether it is traced now or later. This includes host objects a builtin defines for its own bookkeeping — a matcher, a per-call state record, a handler cell — whenever they stash a value in a native field instead of a property. The inherited walk only sees properties, so an unmarked native field is invisible to the collector even while the object holding it is plainly alive, and the value dies mid-operation as soon as the builtin re-enters user code.
  • Pin singletons — UndefinedValue, TrueValue, NaNValue, etc. are pinned via PinObject during engine initialization (consolidated in PinPrimitiveSingletons). Built-in prototype singletons are stored per-engine in realm slots (see next bullet); the realm pins them on SetSlot and releases them on Destroy, so contributors do not need to call PinObject from InitializePrototype themselves.
  • Realm-owned pinning — Built-in prototypes are stored in per-engine realm slots. TGocciaRealm.SetSlot pins the stored object via PinObject; the realm tracks every pin it took and releases all of them in Destroy via UnpinObject. Owned-slot helpers (TGocciaSharedPrototype instances) are Freed before the pin-release pass, so their destructors can still call UnpinObject on objects they own. This means engine tear-down releases the entire intrinsic prototype graph atomically — embedders should not pin or unpin built-in prototypes manually.
  • Protect stack-held values — Values held only by Pascal code (not in any GocciaScript scope) must be protected. Use TGocciaActiveRootFrame for stack-local groups of roots, especially nested native paths where the same object may be rooted more than once; use AddTempRoot/RemoveTempRoot for simple one-off temporary ownership.
  • Use CollectIfNeeded(AProtect) or CollectForMemoryPressure(AProtect) when holding a TGCManagedObject on the stack. The no-arg CollectIfNeeded is only safe when all live values are already rooted.
  • Anything a native path re-reads after guest code runs is a root. Gate-side rooting covers the store itself, so what is left are the values a native Pascal path holds across a guest call; values the VM holds in registers are roots already. A key list is the recurring shape: CopyDataProperties in Goccia.VM.pas builds a plain Pascal array of freshly created strings and calls a getter between one key and the next, so the keys not yet reached are reachable from nowhere at that instant unless the list is rooted.
  • A scope's own bindings are not the only way its objects stay reachable. The VM has no with scope: a with object and a function's hidden variable object for sloppy direct eval (ADR 0134) live in a register or a captured cell, which the frame or the closures holding the cell mark.
  • The property-store path is rooted at the growth gate, not at the store entry points. TGocciaShapedPropertyMap.RequireStorageBytes raises a TGocciaActiveRootFrame covering the map's owning value and the descriptor the in-flight Add has not stored yet (via TGocciaPropertyDescriptor.PushRoots), then consults the budget inside that window through the virtual ConsultStorageBudget. Those two are what the collection taken at the gated growth point would otherwise reclaim: the owner may be held only by a native local, and the pending descriptor is a plain class the collector does not trace, so the value it carries is reachable from nowhere at all. This is not a hypothetical window — RequireNativeBytes collects and re-tests before refusing, so a store that grows a map under memory pressure runs a full mark-and-sweep between deciding to grow and having grown. TOrderedStringMap.Add threads the pending value down through Grow/Compact/GateStorageGrowth for exactly this reason. Do not add a frame to DefineProperty, TryDefineProperty, AssignProperty, or any other store entry point to cover this: the gate is consulted O(log Count) times per map while those run once per store, and measuring the entry-point variant against the store-hot-path benchmark shapes put it at +2.4%..+4.0%. Rooting at the map also needs no per-call-site work at all — every store that bypasses the DefineProperty family is covered by construction: the intrinsic length/name seeding in Goccia.Values.FunctionBase.pas, the native-method and constant registration in Goccia.Values.ObjectValue.pas, the array index-key store in Goccia.Values.ArrayValue.pas, the class prototype store in Goccia.Values.ClassValue.pas, and the object-literal builders in Goccia.VM.pas.
  • The element-store path is rooted at its growth gate too, on the same shape. TGocciaElementList (Goccia.Values.HoleValue.pas) is the element-side twin of the shaped property map: RequireStorageBytes raises a TGocciaActiveRootFrame over the array that owns the list — a backref set at the array's single construction site — and over the value the in-flight store has not written into a slot yet, then consults the budget inside that window through the virtual ConsultStorageBudget. ExtendElementsWithHoles takes the list type and the pending value, so no list without an owner to root can reach the gate — the rooting is covered by construction (budget coverage is a separate question: the list's own Add/Capacity growth never consults the gate, which only bounds bulk extension). The frame closes when the consult returns, before the hole fill and the caller's post-gate store; that is safe because the gate is the only prospective collection point in the extension window — allocation registers but never collects. That invariant was re-audited when the gate learned to collect, since it stopped being a precaution and became the thing the store's safety rests on, and it holds unchanged in shape: the collection the gate now takes happens inside this frame, in ConsultStorageBudget, with the owner and the pending value already pushed, and every step after the frame closes only allocates — the fill appends the pinned hole singleton and grows a plain dynamic array, the timeout poll raises but never collects, and TGocciaValue.AfterConstruction registers and may raise but never collects. If that ever changes — a collecting allocator, or hole construction that can collect — the window must widen to cover the whole extension. The owner push is not a theoretical case: InitializeNativeFromArguments extends the element list while the array is still inside its own constructor, so new Array(n) reaches the gate with the array reachable from nothing at all. The pending push is what makes the descriptor read safe — ArrayDefineOwnProperty's dense-create arm reads the descriptor's value into the new slot after the extension, and a descriptor is a plain class the collector does not trace, so without the push a collection at the gate would leave a freed pointer stored in the element list rather than merely dropped. Reading the field before the gate is not a fix for that; the hazard is the object's lifetime, not when the field is loaded. The dense-append fast path — a store at exactly the element count — never enters this unit and pays nothing.
  • An unrooted temporary fails as an integrity fault, and those are never the guest's to catch. A virtual call through a collected value raises EObjectCheck in a development build ($OBJECTCHECKS ON) and reads freed memory in a production one. Goccia.EngineFault.IsEngineIntegrityFault classifies that family, and every boundary that converts a Pascal exception into a script value re-raises it ahead of the generic arm — the same convention TGocciaMemoryLimitError follows, for a stronger reason: a ceiling the guest can catch is one it can ignore, and a use-after-free the guest can catch is one it keeps running on top of. See ADR 0109.
  • Every reservation is a collecting safe point, not only a guest call. Making a string, a buffer or a SuppressedError, and a gated growth, reserve bytes, and a reservation that would cross the ceiling collects first (below). So native code that has made an object and not yet stored it anywhere a root reaches (a result object it is filling, an error, a key list, a prototype it will put in a realm slot) roots it before it makes the next value: in a TGocciaActiveRootFrame, or by attaching it to its owner first. A constructor counts too: the object under construction is not registered until AfterConstruction, so nothing marks what its constructor has made so far, and a constructor that makes two such values roots Self. Two shapes recur. An open-array argument list (TGocciaArgumentsCollection.Create([A, B])) evaluates every element before the collection exists, so it is built with Add, which roots each element as it lands. And a builtin's own fields are marked by its MarkBuiltinReferences override, and a TGocciaMemberCollection is a root source for the values it holds. Goccia.GCStress.Test runs engine creation, the lazy initialisers and these paths with a collection at every reservation (GC stress at every reservation, issue #1816).
  • A native builder roots what it is holding across the next guest call, not across its own store — except where there is no store to gate. Gate-side rooting covers the store when the receiver has a property map. A proxy receiver has none, and its [[DefineOwnProperty]] is three guest-code safe points in a row: GetTrap reads the trap off the handler, InvokeTrap runs it, and the invariant check afterwards re-reads the caller's descriptor across ProxyTargetIsExtensible and a target [[GetOwnProperty]] — each another trap when the target is itself a proxy. TGocciaProxyValue.PushDefineTrapRoots therefore roots the proxy, its handler, its target and the descriptor across the whole dispatch, and [[GetOwnProperty]] does the same for the completed descriptor it hands back, which is the sole holder of the trap's value while the extensibility check runs. Getting that one wrong does not crash: the guest is handed a recycled object, which is worse. So what is left for a builder — JSON.parse's visitor, a reviver or replacer walk, Object.defineProperties' staged batch — is everything it will read again after the next accessor, Proxy trap or callback runs. Three more shapes recur. A staged batch is the sharpest: Object.defineProperties collects every descriptor before it defines any (§20.1.2.3.1), and both the array and the TGocciaPropertyDescriptors in it are plain natives the collector does not trace, so the value captured for the first key is reachable from nowhere while the second key's getter runs. AppendPendingDefineProperty therefore pushes each descriptor's roots into one shared frame that spans the capture and the apply loop, alongside the key list a Proxy ownKeys handed back. Field-by-field extraction is the same shape one level down: ToPropertyDescriptor reads six fields in spec order, and each read can run guest code while the already-extracted value, get and set sit in Pascal locals — so it holds its own frame over the descriptor object and every field it has taken. A frame and not per-value temp roots, in both cases, because one function used as both get and set would collapse into a single temp-root entry whose first release unroots it for the other. And a detached side table outlives the value tree it describes: JSON.parse's parse records keep raw pointers so the walk can ask whether the value at a position is still the one the text produced, and it asks that after earlier revivers have run, by which time an overwritten primitive is reachable from the record and nothing else — TGocciaJSONParseRecordRoots covers the released tree for the length of the walk. The builder's own tree is covered by TGocciaJSONVisitorRoots, which marks the open-container stack, the finished result, the record tree, and the one value an in-flight emit has popped off the stack and not yet handed to its parent.
  • Push into a frame inside the try that clears it. A frame is a stack record, so an exception escaping between Add and the guarding try is not a recoverable leak: nothing downstream ever releases those entries, the collector's active-root stack stays permanently deeper, and the objects they name are pinned for the life of the thread. Initialize is safe to call before the try — it only records the floor — but every Add belongs after it, including the allocation of whatever the frame was raised to protect. Goccia.GarbageCollector.Test.pas pins both halves of this by asserting ActiveRootDepth rather than a sweep count, which is why the check needs no collection to see the imbalance.
  • A live TGocciaArgumentsCollection roots its elements. It descends from TGCRootSource, registers with the thread-local collector in AfterConstruction, unregisters in BeforeDestruction, and MarkRoots marks every registered source. Builtins therefore do not root their own AArgs elements. Array callback dispatch relies on the enclosing builtin arguments for callback and receiver roots; its hoisted callback arguments own the element, index, array, and reduce accumulator roots. Nested dispatch borrows a different argument collection, so it cannot clear those live slots. The contract stops at the container: anything a builtin copies into its own native state — a path intermediate, a traversal stack, a partially built result — is still unrooted across any call that can run user code, and still needs AddTempRootIfNeeded or TGocciaActiveRootFrame. A subclass that hands out values not present in FArgs must override MarkRootReferences to mark them (see Goccia.Arguments.Callbacks). See ADR 0105.
  • A native call roots a number receiver. The VM boxes a number receiver out of a scalar register into a fresh TGocciaNumberLiteralValue that only the call holds, so TGocciaNativeFunctionValue.Call pushes a receiver of that class into a TGocciaActiveRootFrame for the call (CallWithRootedReceiver); other receivers are held by the caller's register or arguments and pay nothing. A wrapper a builtin makes from its receiver with ToObject, and every value it coerces from its arguments, are still the builtin's to root.
  • A live thrown-value exception roots its value. A guest throw crosses native code as TGocciaThrowValue or EGocciaBytecodeThrow, and the exception may be the only reference to the thrown value while a native handler runs guest code before it rejects with or rethrows it, as closing an iterator after an abrupt completion does (ES2026 §7.4.11). Both classes hold the value in a thread-local root slot (HoldThrownValue in Goccia.Values.Error.pas) from construction to destruction, so a handler does not root it itself. A value copied out of the exception into a native local before the exception is freed is not covered. See #1629.
  • A live TGocciaModule roots the values it holds directly. Its TGocciaModuleRoots root source marks the value-bound exports (AddExportValue, UpdateExportValue), the export table (ExportsTable, which data modules also write directly) and the evaluation promise for as long as the module exists. Local exports stay rooted through the environment scope SetEnvironment registers, and forwarded exports through their source module. The module re-registers its root source when the thread's collector has been replaced. A host module therefore does not need to root what it exports, and must not rely on the namespace object to do it: that object exists only once something asks for the namespace. See ADR 0133.
  • A live builtin roots its object. TGocciaBuiltin.Create links the builtin into its thread's list of live builtins as soon as it has made FBuiltinObject, before the subclass constructor runs, because that constructor may load a shim (below); Destroy unlinks it. One TGCRootSource per thread walks the list and calls each builtin's MarkBuiltinReferences, which marks FBuiltinObject. A builtin need not bind its object anywhere to keep it, and several do not: the engine and runtime extensions read it later through BuiltinObject (static members, the goccia:test namespace). A builtin that keeps other values only in its own fields overrides MarkBuiltinReferences to mark them, as TGocciaConsole does for its count and timer tables.
  • Touching a lazily installed member can run bytecode. No shim loads at boot (Shimmed Legacy Globals), so the first read, write, delete or reflection of a shim global on globalThis (Date, parseInt, ...) or a shim member of Object.prototype, Number.prototype or Array.prototype loads its shim through the VM, and the VM's memory-pressure checkpoint can collect there. That includes the TGocciaObjectValue operations that materialize lazy members as a side effect: GetOwnPropertyKeys, GetAllPropertyNames, GetOwnPropertyDescriptor, HasOwnProperty, DefineProperty and DeleteProperty on those objects. Native code holding a fresh object across such an operation roots it, exactly as across a getter: Object.getOwnPropertyDescriptors keeps its result in a frame, and %TypedArray%.prototype.toLocaleString roots each element across its toLocaleString lookup. A store is the sharpest case, because the value it carries was often boxed out of a VM register a moment earlier and is held by nothing else. o.__defineGetter__ = 1.5 finds the lazy member while walking for a setter, and { ["__proto__"]: 42 } while checking whether the literal may take its fast path. So the store paths of Goccia.Values.ObjectValue.pas do not materialize through the bare MaterializeOwnLazyProperty. The [[Set]] walks (AssignProperty, AssignPropertyWithReceiver and TGocciaInstanceValue.AssignProperty) look descriptors up through GetOwnPropertyDescriptorHolding, which materializes a lazy entry with the value, the receiver and the owner rooted. DefineProperty and TryDefineProperty root the pending descriptor's values the same way before they materialize the entry they replace. A walk that only needs to know whether a member exists asks the property map and never materializes it. The literal fast path, TGocciaVMLiteralObjectValue.TrySetLiteralDataPropertyFast, checks the prototype chain that way.
  • A native object whose methods back native functions is a managed value. When a builtin hosts a native function's callback on a Pascal object of its own (a decorator context's access.get, import.meta.resolve), that object is a TGocciaObjectValue subclass, marks what it holds, and is set as the function's CapturedRoot. The collector then keeps it exactly as long as the function and frees it with it. A TGCManagedObject subclass that does not register itself, as TGocciaValue, TGocciaScope and TGocciaBytecodeCell do, is never freed by a collector.
  • Weak containers and weak references must not mark weak targets during TraceReferences. Put weak-value propagation in TraceWeakReferences and dead-target pruning or cleanup scheduling in SweepWeakReferences; otherwise weak semantics collapse into strong references.
  • Queued jobs must root their callback payloads. Promise reactions, queueMicrotask callbacks, and FinalizationRegistry cleanup jobs use queued roots so callback functions, held values, and result promises survive collections until the job runs.
  • Clear kept objects at host job boundaries. Engine idle checkpoints and the shared microtask/fetch drain helper clear the kept-objects set before and after draining; individual microtask/finalization jobs clear it after they complete. Clearing an empty set does nothing, and a set grown past 1,024 slots is replaced by a new one rather than cleared slot by slot, so one job that keeps many objects does not make every later job pay for that capacity.
  • Scopes register with the GC in their constructor and unregister through BeforeDestruction. Active call scopes are tracked via PushActiveRoot/PopActiveRoot.
  • VM register rooting uses a bytecode VM stack root and only traverses object-bearing register slots.
  • A bytecode closure cell is a managed object. TGocciaBytecodeCell (Goccia.VM.Upvalue.pas) holds a binding a closure, a direct eval or a mapped arguments object has captured. The frame that opened it, every closure that captured it (a closure's upvalue slots hold the cells themselves, and nested closures and generator clones share them), a suspended generator's continuation and a mapped arguments object can all hold one cell at once, so none of them frees it: each marks it, and the sweep frees a cell nothing marked. A new holder of a cell must mark it, or the cell is freed under it. Its InstanceSize is charged like a value's, so --max-memory counts captured bindings. Before #1618 cells and a per-capture upvalue box were plain native objects that nothing freed, about 64 bytes per capture.
  • The execution-context stacks are deliberately unrooted, and that is a contract on their push sites. Goccia.ExecutionContext.pas keeps a raw thread-local array of GC-managed scopes and function values that no root source marks. What keeps an entry's objects alive is the push site, which must name objects a root the collector already walks holds for at least as long as the entry — a VM frame's closure, the engine global scope, a module scope its module registers as a root, or a temp-rooted shim scope or eval activation. The per-site rooting arguments live next to the array they justify (the threadvar comment in that unit) rather than here; read those before adding a push site. One that cannot name such a root makes the array the last reference to a collectible object and needs a real TGCRootSource — TGocciaAsyncContextRoots in Goccia.AsyncContext.pas is the shape to copy. tests/language/execution-context-gc-roots.js is the regression guard.
  • The Enabled flag (threshold collection through CollectIfNeeded) is off during bytecode execution; the pressure checkpoints ignore it and still collect. CLI hosts may still call Collect explicitly between files; the benchmark runner does this after each benchmark file, the test runner after each test file, and GocciaRunner after each file or --multifile section, on the main thread and on every parallel worker. Explicit Goccia.gc() is still available in worker threads and is serialized by the collector lock.

Mark Stack

A collection marks without one native frame per object (ADR 0147). Before it, MarkReferences was the virtual method and each override called it on its children, so marking recursed once per link: a collection taken while a chain of 30,000 classes, or of a few hundred thousand nested objects, was alive ran out of native stack (a stack overflow in a development build, a segmentation fault in a production one).

  • Bounded nesting. While a trace runs, MarkReferences marks the object and calls its TraceReferences in place as long as fewer than 64 calls are nested (MARK_RECURSION_LIMIT). Most objects are leaves or sit a few links from one, and tracing in place costs one call where the stack costs a push, a pop and the same call.
  • Spill to the mark stack. At the limit the object goes on the mark stack, a process-wide array used only under the collect lock, like the mark epoch. The trace drains it before it returns. An object is marked when it is pushed, so it is pushed at most once per collection, and the stack never holds more entries than the collection marks objects: one pointer per live object at worst (an array whose elements are all unmarked). Like the collector's object list it is not charged to BytesAllocated. It keeps 4,096 entries (32 KiB on 64-bit) for the life of the process and gives back whatever a trace grew it to when the collection ends.
  • When the stack cannot grow. A push that finds the stack full doubles it. When the heap manager refuses that, the object is already marked but not traced, so dropping it would let the sweep free what only it references. An object the thread's collector manages is left for a rescan: before the trace ends it calls TraceReferences again on every marked object in the collector's list, draining the stack after each, and repeats while a pass overflowed. Each pass marks at least the objects that overflowed in the one before, so the passes end. An object the rescan cannot find (a shared intrinsic another thread's collector manages, or one no collector manages) is traced where its push failed instead. That is the only recursion left: it nests once per such object along a chain of them, and only while the heap manager is refusing memory.
  • Roots and weak hooks. A MarkReferences call outside a running trace (a root, a root source, a weak container's TraceWeakReferences) starts a trace and returns once everything reachable from the object is marked, as the recursive walk did. The stack and the flags are process-wide, like the mark epoch, so marking runs only inside a collection on the collecting thread, or on a thread while no other thread collects (a unit test); outside a collection the trace takes the collect lock itself.

TGarbageCollector.LimitMarkStackForTesting caps the stack and turns off tracing in place, so the unit tests drive both overflow paths; MarkStackOverflows counts the pushes that found no room.

Design Rationale

Why Not Manual Memory Management?

  • Aliased references — A value assigned to multiple variables, captured in a closure, and stored in an array has no single owner. Determining when to free it requires tracking all references.
  • Shared prototype singletons — String, Number, Array, Set, Map, Function, Symbol, and other built-in prototype objects are per-engine singletons stored in realm slots and shared across all instances of their type within the same engine. Each type's InitializePrototype creates the singleton once (guarded by checking the realm slot) and stores it via TGocciaRealm.SetSlot / SetOwnedSlot, which pins it with the GC. Manual lifetime tracking would be fragile; the realm releases all of its pins atomically in Destroy.
  • Closure captures — Arrow functions capture their enclosing scope, creating non-obvious reference chains between scopes and values.

Why Not Reference Counting?

TGocciaValue inherits from TGCManagedObject, which is a plain TObject descendant — there is no reference counting. Values are stored as class references (TGocciaValue), and lifetime is managed entirely by the mark-and-sweep GC. Using interface-based reference counting would require a large-scale refactor and introduce circular reference issues (objects referencing their prototypes and vice versa).

Why Mark-and-Sweep?

  • Simplicity — Two phases (mark reachable, sweep unreachable) with straightforward implementation.
  • Handles cycles — Circular references between objects, closures, and scopes are collected correctly.
  • O(1) membership checks — Pinned objects, temp roots, and root objects are stored in THashMap<TGCManagedObject, Boolean> (TGCObjectSet) for O(1) PinObject, AddRootObject, AddTempRoot, and RemoveTempRoot operations, avoiding O(n) linear scans on every allocation.
  • Generation-counter mark tracking — Instead of clearing the GCMarked flag on every object at the start of each collection (an O(n) pass), the GC uses a generation counter. AdvanceMark increments the counter in O(1), and an object is considered "marked" when its FGCMark matches the current generation. This eliminates a full pass over the managed objects list per collection. The counter is shared across threads, and full/young collection holds a global collector lock so shared intrinsic objects cannot race on mark state.
  • O(1) UnregisterObject — Each managed object stores its index in the managed objects list (GCIndex). Unregistration nils the slot at the known index instead of performing an O(n) linear scan. The sweep phase compacts nil slots during its existing pass.
  • Pressure-triggered, not count-triggered — While a script runs, collections happen only at the pressure checkpoints and at the forced collection before a refusal, both described under Memory Ceiling. The allocation-count threshold behind CollectIfNeeded (rescaled after each collection to max(DEFAULT_GC_THRESHOLD, surviving_count)) is consulted only by the benchmark runner between measurements; the VM does not call it, because a collection at an arbitrary allocation would sweep temporaries held only in Pascal locals.
  • Weak fixed-point tracing — After normal root marking, the collector repeatedly visits marked objects' weak hooks until no hook marks anything new. This handles ephemeron chains such as a live WeakMap key exposing a value that then keeps another WeakMap key alive. After the fixed point, marked weak containers sweep entries whose weak keys or values are still unmarked, WeakRefs clear dead targets, FinalizationRegistries enqueue cleanup jobs for dead cells, and then the normal object sweep frees unreachable objects. Because the weak hooks are inert on every object except a live weak container, the collector tracks live weak containers and skips both weak passes entirely while none are tracked — the common case for code that uses no weak collections. A container joins the set on its first weak-data insertion and leaves only when it is itself collected; it is not removed when it merely becomes empty again (via delete, unregister, or having its weak keys/targets swept). So the set means "live containers that have ever held weak data": an emptied-but-still-live container keeps both full-heap passes running. That residual cost is bounded — such code already opted into weak semantics — and removing it would mean iterating the tracked set itself (O(live weak containers)) rather than the whole managed-objects list.
  • Recycle virtual method — Sweep calls Obj.Recycle instead of Obj.Free. The default calls Free, but subclasses can override to return objects to a pool.
  • Measurable impact — Both the GocciaBenchmarkRunner and GocciaTestRunner call Collect after each file to reclaim memory between script executions.

Memory Ceiling

The GC tracks approximate heap usage via InstanceSize per registered object, and samples the heap manager's real in-use total alongside it. A byte ceiling is always active:

  • Default: half of physical memory, capped at 8 GB on 64-bit or 700 MB on 32-bit. Falls back to 512 MB when OS detection fails.
  • Override: --max-memory=<bytes> sets an explicit limit.

An allocation that pushes BytesAllocated above MaxBytes is refused, and how it is refused depends on which path it took. A charged allocation — one with an owner that can release it again — raises a JavaScript RangeError. That error is catchable with try/catch; after catching, the script can call Goccia.gc() to free unreachable objects and retry. A gated growth point (below) raises TGocciaMemoryLimitError, which is opaque to the script and ends the run. Both paths force a collection and re-test the request before refusing, through the same TGarbageCollector.TryCollectForLimitedBytes; what differs is whether the guest can observe and retry.

The VM has checkpoints that call CollectForMemoryPressure every 1,025 dispatched instructions. Apart from the forced collection a refused request takes (below), these are the only places automatic collection happens while a script runs. A checkpoint collects when one of these triggers has fired:

  • Tracked bytes. BytesAllocated has come within the pressure reserve (MaxBytes / 8, clamped to 16 KiB…16 MiB) of the ceiling. A charged reservation that lands there asks the next checkpoint to collect at once. When the last full collection could not get BytesAllocated below that line, because the live set itself sits in the reserve, the trigger backs off to halfway between what survived and the ceiling, so collections follow allocated bytes instead of repeating at every checkpoint and after every charged reservation. Releasing tracked bytes lowers the recorded level to the total the release reached, and a collection that gets back under the line resets it, so either brings the trigger back down. The backed-off trigger never rises above the ceiling, because a plain value allocation over the ceiling is refused with the RangeError without collecting first, so only a checkpoint collection clears the garbage in front of it. The trade-off: while the live set sits inside the reserve, a collection is due only once garbage fills half the remaining headroom, and it runs at the next checkpoint, so half the headroom or more can hold garbage when a burst starts, so a burst between two checkpoints that would have fit in the whole headroom can be refused; catching the error, calling Goccia.gc() and retrying succeeds. ADR 0141 records the decision and its measurements.
  • External allocation volume. Charged external allocations (string payloads, buffer backing stores) have added up to 256 MiB since the last collection (EXTERNAL_MEMORY_PRESSURE_ALLOCATION_INTERVAL), whatever the ceiling.
  • Heap in use. Every 1,024 object registrations, and whenever the gated growth points (element and property storage, below) have reported 1 MiB of growth or a pressure reserve if that is smaller, the collector reads the heap manager's in-use total (GetFPCHeapStatus.CurrHeapUsed, per thread, matching the thread-local collector). The growth reports matter because a registration can carry far more heap than an object: new Array(100000) registers about two objects for 800 KB of element storage. At or above the heap trigger it latches the same pending flag an external reservation uses, so the next checkpoint collects. The heap trigger is the same reserve below the ceiling, except when what the last full collection left in use already sits within a reserve of it — survivors plus everything the collector does not own, such as source text, ASTs and bytecode. Then the trigger backs off to the larger of a reserve and half that level above it, so collection work stays proportional to growth instead of repeating at every checkpoint. A sample that finds the heap below that recorded level lowers it, so freeing memory the collector does not own brings the trigger back down without waiting for a collection.
  • Heap growth. The heap trigger is lowered to four times what the last full collection left in use (HEAP_GROWTH_TRIGGER_FACTOR), and at least 64 MiB above it (HEAP_GROWTH_TRIGGER_MIN_BYTES), when that is below the ceiling's trigger. Under a large ceiling, including the default, a script that keeps little alive would otherwise grow towards the ceiling before its first collection. It never raises the trigger and always sits at least the floor above what survived, so a heap that a collection cannot shrink does not collect more often. ADR 0145 records the decision and its measurements.

The heap trigger exists because BytesAllocated sees only part of the heap (see What BytesAllocated tracks). With tracked bytes alone, a script that keeps little alive grew to five or six times the ceiling in resident memory before its first collection; with the heap trigger its peak resident memory stays near max(ceiling, 1.5 × what survives a collection), and with the growth trigger near max(4 × what survives, survivors + 64 MiB) when that is lower. ADR 0129 records the decision and the before/after measurements. The heap trigger needs the FPC heap manager; a Delphi build reports no heap total and keeps the tracked trigger only.

Refusal does not change with the heap trigger: an allocation is refused only by BytesAllocated, as described above. A script whose live data costs more heap than the ceiling but less than the ceiling in tracked bytes therefore runs on, collecting once per growth step, rather than being refused. If a collection cannot bring tracked usage below the ceiling, the next allocation still raises RangeError.

Neither path depends on those checkpoints having fired. When a request would push BytesAllocated past the ceiling, TGarbageCollector.TryCollectForLimitedBytes forces a collection — the pressure heuristic alone would decline, because it only triggers once the live set is within a fixed reserve (MaxBytes / 8, clamped to 16 KiB…16 MiB) of the ceiling — and then re-tests the request once. A request is therefore refused only when the post-collection heap genuinely cannot fit it. The forcing does not apply while a collection is already running or while the memory limit is firing, since both mean the caller is already inside the collector's own re-entrant path.

Two shapes are still refused without walking the heap, because for them no collection could change the answer: a request larger than MaxBytes itself, and a repeat of a request a forced collection has already refused at the current live level. The second is what keeps a script that catches the RangeError and retries at near-constant cost per attempt rather than paying a full mark-and-sweep each time; the record is per request size, so a smaller request the record does not rule out still forces its collection. The record cannot see a script drop what it held, because unreachable objects move no counter, so it does not answer every retry: the first retry after a refusal collects, and each retry collection that makes no room doubles the interval before the next one (up to 65,536 retries). Only that first retry is guaranteed a collection: when it makes no room the interval is 2, and the next retry can be refused from the record even after another drop, so Goccia.gc() stays the fallback. A script that fills the heap, drops it and retries is therefore served without Goccia.gc(), and a loop that retries while holding everything walks the heap a logarithmic number of times. The record is cleared by any collection — threshold, young-generation, pressure checkpoint, or an explicit Goccia.gc() — and by the heap dropping below the recorded level, not by allocation as such. ADR 0173 records the decision and its cost.

That record is deliberately shared by both refusal paths rather than kept per path. It states a fact about the heap — the level the last forced collection could not get below — not about the caller, and both paths force the same full collection and apply the same fit test, so a level that defeated one defeats the other at the same request size. A second, gate-private record would only buy each path the right to re-learn what the other just proved.

What still separates the two paths is what the guest can do about the answer, not how it is reached: the gate's TGocciaMemoryLimitError is opaque to the script rather than catchable, so the same byte count can be survivable on a charged path — a string payload, an ArrayBuffer — and end the run on the element-storage or property-storage path. ADR 0110 records why the gate could not collect until the store paths rooted their temporaries, and what that changed: the same 4 MiB-ceiling property-growth loop, which bytecode used to refuse at a 1,179,552-byte doubling, now reaches the arithmetic crossing at 4,718,496, with or without the guest collecting for itself.

From JavaScript, Goccia.gc.bytesAllocated and Goccia.gc.maxBytes are read-only getters. The ceiling can only be changed from the engine level (CLI option or Pascal API: TGarbageCollector.Instance.MaxBytes).

Physical memory detection

PlatformAPINotes
macOS/Darwinsysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE)Declared as external 'c' inline
Linuxsysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE)Same API, different constant values
WindowsGlobalMemoryStatusEx (kernel32.dll)Declared inline because the standard FPC 3.2.2 Windows unit only provides the older GlobalMemoryStatus, which Microsoft documents as capping dwTotalPhys at 2 GB on x86 systems with 2-4 GB of RAM. GlobalMemoryStatusEx uses 64-bit DWORDLONG fields (ullTotalPhys) that report correctly on all systems.

Scaling constants

ConstantValuePurpose
DEFAULT_MAX_BYTES512 MBFallback when OS memory detection fails
MAX_BYTES_CAP_64BIT8 GBUpper bound on 64-bit targets
MAX_BYTES_CAP_32BIT700 MBUpper bound on 32-bit targets

The formula is min(physicalMemory / 2, platformCap).

What BytesAllocated tracks

BytesAllocated sums InstanceSize of each TGCManagedObject registered with the GC. This covers the Delphi/FPC object instance (vtable, fields, padding). Backing storage allocated separately by an object splits into two cases. Storage with a clear owner and a release hook is charged to BytesAllocated through the TryReserveExternalBytes contract — string payloads (TGocciaStringLiteralValue), ArrayBuffer/SharedArrayBuffer backing stores and Response bodies reserve on allocation and release when the owner is destroyed (a Response body also when it is consumed; see Fetch — Response bodies and the memory limit). An ArrayBuffer additionally releases the freed bytes when a resize shrinks its backing store (SetData/SetDataLength release -Delta whenever Delta < 0), so its charge tracks the live payload rather than the peak. A SharedArrayBuffer allocates its backing store once, at construction (AllocateBlock): a growable one allocates and is charged maxByteLength bytes, a fixed-length one its byte length, and grow changes neither the store nor the charge (Binary Data). Either way they do count. Storage that is only gated (checked before allocation, never charged) does not — dynamic array element buffers in TGocciaArrayValue are bounded per-allocation by the growth gate below, not summed into BytesAllocated.

Several other costs are not charged at all. Each object's TGocciaShapedPropertyMap instance and its bucket and entry arrays, each property's TGocciaPropertyDescriptor, each scope's binding map, the collector's own object list, and the heap manager's rounding (on 64-bit FPC a block is InstanceSize + 8 rounded up to 32 bytes) all sit outside BytesAllocated. Measured on Linux x64 with nothing collected, the heap manager held 2.4 to 3.6 bytes for every tracked byte across a loop of short-lived objects and arrays and a Promise micro-benchmark (4.8 to 6.7 before an object's symbol-keyed storage became lazy). BytesAllocated is therefore an approximate measure of collector-owned bytes, not of the process's memory; the heap trigger is what keeps collectable garbage near the ceiling.

Deferred string prefixes reserve their eventual flat buffer plus their retained suffix when created. TraceReferences marks the prefix, with at most 32 links. Materialization consumes that reservation without collecting and releases the suffix charge; destruction releases the remaining reservation. When an append needs a collection to fit, it first materializes its prefix so the collection can reclaim unaliased intermediate nodes and their reservations. This accounting is deliberately conservative: a deferred string's charged capacity can exceed its currently allocated native buffer. It preserves non-collecting primitive reads while reducing physical copying; see ADR 0116.

The bytecode VM's stacks are charged as well: the register, local-cell, argument, frame, closed-numeric-frame and handler stacks, and the thread's call stack and execution-context stack, which the VM grows for every call it makes. Each is charged for the capacity it has past its initial capacity. A stack shrinks back at an instruction boundary once the recursion that grew it has returned, and the VM releases the rest when it is destroyed. The thread's two stacks give back no more than the VM charged for them, since other code can grow them too. A generator or async function charges the frame it suspends: its registers, local cells, arguments and handler entries. The charge covers the largest frame that generator has held, and is released when the generator finishes or is destroyed. With --max-stack=0 this charge is all that stops a bytecode recursion. Deep stacks grow only up to the memory-pressure reserve below the ceiling. Stacks smaller than that reserve may use it, so a program whose heap fills the ceiling can still make calls. The refusal is the catchable RangeError: Maximum call stack size exceeded. SetLength holds a stack's old and new blocks together while it copies one into the other, so a growth must also leave room under the ceiling itself to copy the largest stack once more.

A stack grows inside call setup, which can neither collect nor throw. So a growth that does not fit is made uncharged, and the next instruction boundary settles it: it collects, then charges the growth or throws. TGarbageCollector.TryChargeExternalBytes is the non-collecting charge both sites use. Unlike TryReserveExternalBytes, it does not latch memory pressure. Everything a bytecode recursion holds per frame is therefore charged, and the refused error's stack trace lists at most 100 frames (Stack Traces), so a recursion's peak resident memory stays close to the ceiling. What still exceeds it is garbage, which BytesAllocated counts at its InstanceSize rather than at what the heap holds for it, and memory a shrunk stack has given back, which stays resident in the heap manager. See ADR 0130 and ADR 0132, which records the measurements.

Gated growth points

Backing storage sized by the running script is checked against the ceiling before it is allocated, without being charged to it (Goccia.MemoryLimit: CanAllocateNativeBytes / RequireNativeBytes, raising the host-catchable TGocciaMemoryLimitError). Two growth points are gated: array element extension (ExtendElementsWithHoles) and object property storage, where the map's entry and bucket arrays grow past a small-block threshold. Both belong to containers with no hook to release a reservation, so a charge would leak budget the engine could never give back; a gate bounds the peak instead. What is reported to the gate is the transient footprint — the block being allocated plus the block still live while it is — because SetLength may allocate and copy rather than extend in place, and compaction holds both entry arrays at once by construction.

A granted request is still uncharged, but RequireNativeBytes reports its size to TGarbageCollector.NoteNativeGrowth, which samples the heap once enough such growth has built up, counting the request as in use because it is reported before the store allocates it, so the heap trigger sees storage that no registration accounts for (ADR 0145). The report never collects. Element storage that grows by appending (push, literal construction) does not pass the gate and is not reported, so the heap sees it only at the registration-count samples.

RequireNativeBytes forces one collection and re-tests before it refuses, on the same terms as the charged path above. That makes the gate a collecting safe point inside a store, which is why the two RequireStorageBytes overrides open their rooting window before consulting the budget rather than after — see the two store-path contributor rules above, and ADR 0110. Anything that calls RequireNativeBytes from a new site takes on the same obligation: make live temporaries reachable first. CanAllocateNativeBytes carries no such obligation — it reads the counter and never collects.

What the gate does not bound. It bounds the size of any one gated allocation; it does not bound resident memory. Two limits stack up. Property storage below GATED_GROWTH_MIN_BYTES is not reported at all, so an object that never exceeds 62 properties (64-bit, SizeOf(TEntry) = 24) is never checked. More importantly, BytesAllocated omits the dominant per-property cost — TGocciaPropertyDescriptor is a plain class, not a TGCManagedObject, and the shape's property-key strings are likewise unmanaged — so the remaining budget the gate compares against barely moves as properties accumulate, and no number of these uncharged small objects ever sums to a refusal. (Charged allocations — string payloads, ArrayBuffer backing stores — still count against BytesAllocated and can exhaust it; the aggregate gap is specific to the uncharged descriptors and keys, and closing it would narrow the gap rather than turn the budget into a resident-memory ceiling.) Measured at a 64 MiB budget: 40,000 objects of 120 properties each completes at 978 MB resident, while the same total properties on a single object is refused at 324 MB. ADR 0106, Amendment 1 records the full measurements. Those objects are live, so the heap trigger of ADR 0129 changes neither outcome: it collects as the heap grows, finds little to free, backs off, and refuses nothing. It bounds collectable garbage, not live data. A host that needs a real ceiling on live data must impose one outside the process.

Teardown

A collector that is freed destroys every object it still manages (TGarbageCollector.ReleaseAllManagedObjects, called from Destroy). It drops its pins, temp roots, queued and kept objects and root objects, then sweeps with nothing marked, as a collection does, and sweeps again while destructors register new objects. Each worker frees its collector in ShutdownThreadRuntime when it exits, after draining the thread-cleanup registry, and TGocciaApplication.RunApplication calls the same procedure on the main thread once the application has finished (ShutdownMainThreadRuntime, skipped when a thread pool abandoned a stalled worker, which still reads the main thread's values). A process therefore ends with nothing its collectors managed still allocated (ADR 0143).

The sweep runs destructors in list order, as every sweep does. So a value's destructor frees only what the value owns natively and never calls into another managed object, which may already be gone; at teardown this includes the prototypes, realm values and singletons that an ordinary sweep never frees. No engine may be alive on a thread when its runtime shuts down, and nothing may use a managed value after that.

Threading model

Each worker thread creates its own TGarbageCollector instance via threadvar. The --max-memory ceiling is propagated from the main thread's GC to each worker via TGocciaThreadPool.MaxBytes → InitThreadRuntime(AMaxBytes).

Two kinds of lock coordinate the collectors, with a strict order between them:

  • The global collect lock serializes Collect/CollectYoung across all collectors — the mark epoch (GCCurrentMark) is process-global and some intrinsic objects are shared, so two concurrent collections advancing the epoch mid-mark would unmark each other's live sets.
  • A per-collector accounting lock is a short-lived leaf lock for the byte counters a foreign thread can drive (BytesAllocated, the external-byte total, the forced-collect floor, the peak). The one cross-thread entry point into a collector is ReleaseExternalBytes through an error object's reserving-collector pointer (an error charged on collector A can be destroyed on worker thread B); everything else reaches a collector through the thread-local Instance, so the managed-object list and root sets are owner-thread-confined and unlocked. Keeping the counters on their own per-collector lock means one worker's full mark-and-sweep does not stall any other worker's per-allocation register/unregister — and workers never contend with each other on the allocation path at all, only with the rare cross-thread release aimed at their own collector.

Readers of those counters do not take the accounting lock on 64-bit targets: every write goes through the lock, and an aligned Int64 load cannot tear there, so BytesAllocated stays a bare field read on the per-allocation path. On 32-bit targets a cross-thread ReleaseExternalBytes splits its write into two stores, so the BytesAllocated accessor takes the lock for the load — no 64-bit interlocked read is available, since FPC 3.2.2 declares those only under CPU64 and CI also builds i386-win32. The peak and lifetime totals are written only by the owning thread and need neither treatment.

The order is collect lock → accounting lock, never the reverse (and never two accounting locks at once): a sweep settles its freed bytes — and a swept error destructor releases its cross-collector charge — under an accounting lock while the collect lock is held, and the reservation path drops the accounting lock before it collects. The accounting lock lives and dies with its collector; a cross-thread release entering it is safe on the same terms as the counter fields it guards, per the lifecycle invariant that a charged object is freed before its reserving collector shuts down.

Key behavior on worker threads:

  • Automatic GC collection is disabled (Enabled := False) so worker execution does not collect between ordinary allocations. Explicit Collect calls still run under the global collector lock; Goccia.gc() therefore has the same observable behavior in worker threads as on the main thread. GocciaTestRunner collects at the end of every file a worker runs. Without that, a worker holds every object it allocated until it exits, so the workers together hold the garbage of the whole run. On four 64-bit workers that raised the suite's peak, measured with the tree-walk interpreter before 0.15.0, from 0.70 GB to 1.27 GB resident, and a 32-bit process has 2 GB of address space.
  • BytesAllocated still increments on every allocation, even with automatic collection disabled. A host that runs many files on one worker without collecting between them sees the counter grow across all of them.
  • The memory ceiling check still fires. The limit check in TGocciaValue.AfterConstruction does not depend on GC.Enabled — it checks MaxBytes > 0 and BytesAllocated > MaxBytes regardless. This is the sole protection against unbounded memory growth on workers.
  • No pre-allocation. MaxBytes is a threshold, not a reservation. Memory is allocated on demand by the FPC heap manager; the GC only checks whether the running total exceeds the ceiling.
  • Each worker gets the same ceiling as the main thread. The limit is per-thread, not divided across workers. With N workers, the theoretical maximum total allocation is N × MaxBytes, though in practice worker allocations are far below the ceiling.

CLI JSON reports aggregate worker GC memory once per worker thread. Live and peak values are summed across worker thread-local GC instances, while the limit is the per-worker ceiling. The report deliberately avoids summing per-file live snapshots, because a worker may process many files using the same GC instance.

The separate memory.heap JSON object comes from FreePascal's GetHeapStatus, not from the GocciaScript GC. It describes allocator state for the process/thread scope being measured. Free-space deltas can be negative when the allocator has less reusable free space at the end of a run; this is not itself evidence of a GocciaScript GC leak.

JavaScript API

Goccia.gc() manually triggers a full mark-and-sweep collection, bypassing the automatic collection threshold. The VM's registers are treated as roots while collection runs. Collections are serialized by a global collector lock so explicit calls are safe in parallel test workers even though intrinsic prototype objects can be shared. It is safe to call repeatedly and returns undefined.

PropertyTypeDescription
Goccia.gc()functionForce a full garbage collection
Goccia.gc.bytesAllocatednumberApproximate bytes currently tracked by the GC (read-only)
Goccia.gc.maxBytesnumberActive byte ceiling (read-only; set via --max-memory or auto-detected from OS memory)

AST Literal Ownership

The parser creates TGocciaValue instances (numbers, strings, booleans) and stores them inside TGocciaLiteralExpression AST nodes. These values are owned by the AST, not the GC. TGocciaLiteralExpression.Create calls TGarbageCollector.Instance.UnregisterObject to remove the value from GC tracking, and TGocciaLiteralExpression.Destroy frees the value. A primitive singleton (UndefinedValue, TrueValue, ZeroValue, ...; IsPrimitiveSingleton) is neither unregistered nor freed: it stays with the collector it was created in, which frees it when the main thread's runtime shuts down. The node itself belongs to the arena of the parse that created it, which its program frees with the whole tree (ADR 0143).

The compiler never hands an AST-owned literal value to running code: it compiles each literal to a load instruction (OP_LOAD_NULL, OP_LOAD_TRUE, OP_LOAD_INT, …) or to an entry in the function template's constant pool. This cleanly separates compile-time constants (owned by the AST) from runtime values (managed by the GC).