Skip to content

ADR 0024: The heap memory model

Status: Final Type: Architecture Created: 2026-07-29 Consolidated: 2026-08-07, absorbing 0034, 0036, 0037 (retired) and the lifetime parts of 0023 and 0026 Amends: 0014 (appends IR18), 0023 (an instance is counted and released), 0027 (the element kind is a character of the descriptor alphabet; instance elements and container fields) Amended-By: 0061 (a temporary is released where its statement ends), 0065 (the header holds the instance's class), 0078 (a loop variable that meets its conditions borrows its element and is not a slot) Related-ADRs: 0023 (the class model), 0026 (Str's ownership specifics, which extend the slot rule), 0027 (list values), 0029 (union boxes), 0035 (the slot descriptor in detail), 0021, 0022. Provenance: arbitrations A57–A114.

Context

POST heap values (instances, strings, lists, dicts, sets, union boxes) are reclaimed by per-task, non-atomic reference counting. Two facts drive the rules below. First, the sendability rule (pygo D15) refuses mutable heap values at task boundaries. No counted value is reachable from two tasks at once, so the counts need no locking; admitting a shared instance would reopen this decision. Second, the project's primary oracle is a byte-identical stdout differential, yet a leak has no stdout. The memory model therefore includes an instrument that is part of the decision.

Decision

The slot rule

All references a frame holds live in slots; each slot owns exactly one reference to what it holds and holds the type's null when it holds nothing. The slot kinds are: a named local, a parameter, a construction site, a producing call site, a conditional expression's join, the finally return stash, and a loop variable. There are no borrowed temporaries: a borrowed temporary's release point is a dominance question; a slot's release point is fixed in the entry block and live at all exits, in one list.

Three emission rules follow, each ordered for correctness:

  • Adopt (a producer's +1 arrives): decref(slot); slot = value. This is safe when old and new are one object, because the adopted +1 keeps it alive.
  • Alias (a second reference to something a slot holds): incref(value); decref(slot); slot = value. Incref comes before decref, always, since p = p reaches this code.
  • Statement end: a construction site's or a producing call site's slot is released and nulled where its statement ends, which is when CPython drops the temporary (0061). A statement that leaves early (a raise, a return) leaves the slot to the epilogue, and the next adoption releases whatever it still holds.
  • Prologue and epilogue: the prologue (an incref per counted parameter, a null store per other slot) is spliced into the entry block; the epilogue is appended to each block whose terminator is a Return (which includes the fallthrough, the finally machinery's return block, and the exception-propagate block), with the returned value increfed first, so returning the last owner does not free the answer on its way out.

A slot is declared in the entry block regardless of where the name is first bound, so the declaration dominates each release. A value that is already a slot passes through a use untouched; an argument is borrowed for the duration of the call and the callee's own prologue counts it.

The representation

A heap value points at its payload; its header sits at a negative offset. An instance's header is a reference count, a pointer to a static per-class descriptor string, and the instance's class number (0065). The descriptor has one character per slot, saying what releasing that slot owes:

-  nothing      s  Str       y  bytes      o  instance      u  union box
l / d / e  list / dict / set      w  an int word that may hold a big int      F  a file's stream

The descriptor is emitted through the Str literal table all backends already share: interned, immortal, and crossing as const char * literals already cross. A new kind therefore costs the backends nothing. NUL terminates it (no kind is the zero byte), so the release walk needs no slot count. The generated C shows "-so", and the layout reads straight off it.

A container records the same thing as one character in its header, since its elements are homogeneous where a class's fields are heterogeneous. One shared function answers both shapes, so a kind added once reaches both. The value 0 lies outside the alphabet: an unconverted caller trips the runtime's abort and never reads "scalar". A parameterised type's parameter always lives on the slot that holds the value: the frontend's slot record for locals, the container header for elements, per-class records for fields. The result is a bounded product of small closed sets and never a property of the bare dtype.

Provenance

Every runtime helper that returns a counted value is classified owning (the caller adopts a +1) or borrowing (someone else holds the reference: a field read, a record's message, a list element). Borrowing is the default direction: an unclassified producer leaks, which the retention counter reports on the next run; the opposite default is a use-after-free that nothing sees. Completeness is derived from the source: per counted type, a guard parses the helper signatures out of the runtime's own C and requires each producer to be classified exactly once. void *, the one overloaded return type (instance, CPython handle, exception record), has an explicit not-an-instance list. A borrowed value is increfed at the moment it lands in a real slot, which keeps it = c.it valid after c.it = Item(2).

Release

decref aborts on a count that is already zero, in both build modes. No POST program can cause it; it is a defect in the emitted release sequence, so a check active only in debug would leave the release build open to a use-after-free. incref/decref return void, so a release sequence can only ever be a statement; the C signature enforces it and the ABI check holds each call to the parsed definition.

Cascading frees run through an intrusive, allocation-free destruction queue: a dead block's count field is the link (it has no references left to count). The outermost decref drains and inner ones enqueue, so the C depth is bounded by a constant whatever the shape of the graph: an instance holding a list holding instances releases in four frames, not a frame per node. The queue lives on the instance, the only node type a cycle can pass through.

A reference cycle leaks and is reported. That is the shipped behaviour: the exit report states the leak. The reopen trigger is standing: a program that ends with live != 0 under a balanced ownership discipline is a cycle, by elimination. Three refusals keep the future options open and must stay refused meanwhile: __del__, is, and id(). A later collector reclaims at a time no one can predict, so nothing may observe finalization or identity.

Linkage

The counted-heap runtime units (object, list, map, union) reference each other behind branches particular programs can never take, and a branch nothing can take still needs its symbol at link time. They are therefore one linkage decision: a single closure predicate computed from the raw per-type scans. Per-unit disjunctions kept in step by hand failed twice before it was centralised.

The instrument

The runtime maintains two counters per counted type, per task: live (allocated minus reclaimed; zero at exit is the property that matters) and allocated (monotonic, never read by the program). Guards assert both, exactly: live == 0 alone is satisfied identically by "reclaimed everything" and by "the optimiser deleted the allocation". A guard that can be satisfied by deleting the thing it measures is not a guard. The report goes to stderr only (the oracle compares stdout) and the counters are always on in both modes with only the report gated; a debug-only counter would make the measured build and the shipped build different programs. To keep the allocation opaque to the optimiser, the object runtime is a separate translation unit for every backend, the C backend included (the one deviation from the C backend's static-copy pattern), which is why all three backends allocate, reclaim, and agree on allocated.

Consequences

  • A program with no counted heap emits no slots, prologues, epilogues or linked runtime units: it is the IR it was before this model existed.
  • A counted type's placeholder is its null, which makes a raising function returning any counted type lowerable: the only operations a placeholder can meet before the caller's exception check diverts are incref and decref, no-ops on null. (Str's null is the immortal empty string, because a Str placeholder is readable; see 0026.)
  • What remains at frame exit is bounded by the source: one value per static producing site, whatever the input.
  • The remaining leak-at-exit heaps are CPython handles (0006) and the exception records 0007 leaves unreleased (one that reaches the top of the program, one a C unit keeps); the cycle policy above is the only unbounded class, reported at exit.

Alternatives considered

  • A type tag in the header, for the release walk: rejected twice, once at the class model and once when instance-valued fields were predicted to force it. A tag answers what class is this?; a release walk asks which of my slots are references?, which the descriptor answers without naming a class. The class number the header holds since 0065 serves method dispatch, and no release path reads it.
  • Per-kind bitmaps: the road actually travelled (one mask for Str, a second for instances), abandoned at the third kind: a word per kind grows the header forever and caps the field count at the word width, where one descriptor pointer answers for every kind that will ever exist and retires the 64-field limit with the mechanism that needed it.
  • Atomic counts: rejected; they would buy shared heap values at the price of atomic updates on every count, abandoning the bargain the sendability rule already paid for. Str crosses task boundaries by copy-on-send (0026), the price of keeping every count non-atomic.
  • Garbage collection: out of scope by design; the counters, the queue and the reported cycle leak are the refcounting answer. The standing refusals (__del__, is, id()) keep a future collector implementable.