Issue #1626: Cycles of handles: the compiler refuses them unless it proves a back edge (inference, summaries, Weak[T], indices)

Open and answer this issue on GitHub.

views, note · opened 2026-11-15 · updated 2026-11-22 · 1 comment

Status: decided by the owner 2026-11-15 (section 8: questions 1 and 2; question 3 fell away with G). Nothing in the repository waits on it today (section 2). Rewritten 2026-11-15 after the owner’s feedback: the compiler, not the user, should find the edges that close a cycle; every static way found is listed below as an option, so that whatever is left out is left out on purpose.

1. The feature, from zero

A value in Nikaia has one owner. When several parts of a program need the same value, the program writes a handle explicitly: Shared[T] for a value that is only read, SharedMut[T] for one that changes through its doors get, set, update and access (Part I §6.2, Part II §12). A handle is duplicated, never moved, and every duplicate raises an owner count; when the last handle goes, the value is freed (ADR-312). In the runtime a handle is an Rc, or an Arc where the value crosses threads, around a lock (crates/nikaia-std/src/lock.rs, the Door for Rc<D> impl).

That is reference counting, and reference counting has one known hole: a cycle. A tree whose nodes know their parent, a doubly linked list, a graph whose nodes point at each other, an observer that knows its subject and the other way round: in each, two values hold handles on each other, neither count reaches zero, and neither is freed.

struct Node { name: String, next: SharedMut[Node]? }

fn main() throws {
    let a = SharedMut(Node { name: "a", next: null })
    let b = SharedMut(Node { name: "b", next: a })
    a.update(fn(mut v) { v.next = b })
    println("built")
}

What the user sees today (measured, 2026-11-15, develop at 735d61ed): the program compiles without a warning, runs and prints built. a and b hold each other, so both stay in memory until the program ends. Nothing in the language, the compiler or the messages says so. Not measured: the bytes lost per cycle with valgrind.

The guide says this in one place (guide/ownership.md, Where the model ends): an owner count does not free a cycle of handles, there is no weak handle yet, and a graph or a tree whose nodes know their parent is better written with indices into a list.

The question: how does Nikaia close this hole, and how much of it can the compiler do without the user writing anything?

2. Where the question comes from

Does anything need the answer now? No. The compiler, the prover and the tools are built with indices into lists, and no issue is blocked. The cost of waiting: every user who writes a parent link today gets a silent leak.

3. What is already decided, and what it already proves

What follows from this, and is not yet written anywhere: a cycle of handles can only be closed by a write after construction: a handle that already exists is stored into a value that the handle’s target already reaches. In Nikaia only two things write into a value behind a handle: the doors of SharedMut[T] and a Locked[T] field inside a Shared (Part I, around line 2463). A Shared[T] value is complete when the handle is made and can only point at values that already existed, and Nikaia has no recursive value construction (no let rec). So:

  1. An immutable value is never part of a cycle. The keyword already excludes every type that could close one. The answer to does immutable help is yes, exactly: what is declared immutable needs no cycle handling at all, by proof, and the runtime can skip every check for it.
  2. A type that reaches no SharedMut and no Locked (directly, through fields, collections or closure captures) is never part of a cycle either, immutable or not.
  3. Only types that can reach themselves through a SharedMut/Locked path can be in a cycle. That set is computable at compile time over the type graph (its strongly connected components) and is, in our own code, expected to be small (measurement 3).

Points 1 and 2 cost nothing and belong in the specification whatever else is chosen. They also bound every option below: whatever cycle handling is chosen, it is paid only by the types of point 3.

To search for a static way, it helps to say what the human reasoning is. A programmer writing a tree with parent links makes parent weak because the parent owns the child: the tree is held from its root, every child is reached from the root through children, and the edge child → parent points back to a value that already keeps the child alive. In graph terms: in the graph of handles, rooted at the program’s live variables, the parent dominates the child (every path from a root to the child goes through the parent), and an edge to a dominator is a back edge. Making back edges weak frees exactly what a tracing collector would free.

That is a property of the program’s reachable states, not of a type and not of the order of stores, and that is what a static analysis has to establish. Two consequences:

So the claim of the first version, that a person has to say which link is weak because the compiler cannot, was wrong in both directions.

5. The options

A to D are the forms other languages use. E to I are the static and runtime ways found for the compiler to do it. They combine; section 8 proposes a combination.

A. Do nothing

B. Indices are the way for graphs, and the compiler says so

The specification writes that a structure with back links is built with indices into a list (later a std arena with generations). The compiler warns where a type is in a self-reaching component (point 3 of section 3) and points to the index form.

C. Weak[T], written explicitly

handle.weak() gives a Weak[T] that does not keep the value alive; w.upgrade() gives SharedMut[T]? (or Shared[T]?): null once the value is gone.

D. A tracing cycle collector for everything

Python’s approach: a collector periodically walks all counted values and frees unreachable cycles.

E. The store that closes a cycle is found at compile time (write-site check)

At every write through a door (a.update(fn(mut v) { v.next = b })), the compiler asks whether the stored handle’s target can already reach the value written into. The compiler already tracks aliasing and handle identity for the sharing check; extending it to “b reaches a” within a function is local reachability over the stores it can see.

F. The compiler infers the back fields (owners-as-dominators shape analysis)

The compiler proves, over all the stores into a field of a self-reaching type, the invariant of section 4: for every value x, the value in x.f dominates x (parent points to a value from which x is reached by the other fields). A field with that proof is lowered as a non-owning link; the user writes the ordinary parent: SharedMut[Node]?. Prior art: ownership types with the owners-as-dominators discipline (Clarke, Potter, Noble 1998) and its inference work; shape analysis (Sagiv, Reps, Wilhelm, TVLA) and bi-abduction in separation logic (Facebook Infer), which infer tree and list shapes with back pointers.

Two strengths, by how much is proved:

G. Synchronous trial deletion, only for the self-reaching types

Excluded now, kept as a possible later stage (owner, 2026-11-15, section 8).

The runtime way of finding cycles without a tracing collector (Bacon and Rajan, 2001; PHP’s cycle collector uses it): when a count of a value of a self-reaching type drops but not to zero, the value may have become the entry of an orphaned cycle; a local scan from it subtracts the counts the values hold on each other, and whatever ends at zero is unreachable from outside and freed. The compiler restricts it to the types of section 3, point 3, so every other value pays nothing, and every immutable value pays nothing by proof.

H. Inferred regions for cyclic structures

Region inference (Tofte and Talpin, ML Kit): the compiler infers a region whose lifetime covers all values of a cyclic structure, allocates them there and frees the region as a whole, cycles included.

I. Freeze after building

Build a structure with SharedMut, then turn it into an immutable one so it is provably free of cycles.

6. How other languages solve it

Language Answer What we learn
Rust Rc/Weak, Arc/Weak; graphs with indices (petgraph, slotmap with generations) Weak for parent links and observers, indices for graphs. No warning on a cycle.
Swift weak / unowned under ARC unowned is F1 trusted instead of proved; cycles through closures ([weak self]) are the most common bug in practice. No warning.
C++ shared_ptr / weak_ptr lock() returns a pointer that can be ignored; our optional forces the check.
Koka precise counting with reuse (Perceus) Values are immutable, so cycles arise only through mutable refs; those leak, without a warning. Same position as Nikaia’s section 3, without the check.
Lean 4 counting with destructive update when unique Same as Koka: pure values cannot form cycles; IO.Ref cycles leak.
Python, PHP counting plus a cycle collector (PHP’s is Bacon-Rajan trial deletion) Option G’s mechanism, there run for every value and batched; we would run it only for self-reaching types, synchronously.
Go, Java, C# tracing collector No hole, no predictable destruction.
ML Kit inferred regions, later plus a collector Option H, and why it is excluded.
Zig, Odin indices and arenas Works for systems code, leaves stale indices to the user.

No mainstream language infers the weak edge or warns about a cycle at compile time. Koka and Lean are where section 3 comes from: immutability rules cycles out, and only the mutable part needs an answer.

7. How it meets the existing model

8. Decision (owner, 2026-11-15)

The user writes nothing for cycles, and the compiler guarantees at compile time that a program never builds a cycle of handles. The one exception is a cycle where the compiler has proved a back edge and lowered that edge as non-owning. There is no runtime cycle detection.

  1. Now, free: write section 3 into the specification: immutable values and types that reach no SharedMut/Locked are free of cycles by proof. The checker computes the self-reaching types (point 3), and every later step applies only to them.
  2. The rule (E as a refusal): a store through a door of SharedMut[T], or into a Locked[T] field, is refused at compile time if it can close a cycle among self-reaching types and layer 3 has not proved a back edge on that cycle. The check is sound: it may refuse a correct program, but it never lets a cycle through. The message names the line, the cycle, and the index form.
  3. What makes the rule mild (F): owners-as-dominators inference proves back fields. A proved field is lowered as non-owning (F1) or as weak with null (F2, an optional field only), and the store that closes the cycle is accepted. Parent links, doubly linked lists and observer pairs are the shapes it must pass. F decides how much the rule allows, so it is a main build, not a later optimisation. Until F lands, these shapes are refused and written with indices, which is the guide’s advice today.
  4. Reach across boundaries: first function summaries (what a parameter and a result can reach, and which fields a function stores into), then package summaries carried in a package’s interface. With them, a store is judged across functions and packages without reading their bodies. Where no summary decides, the store is refused, because soundness comes first. Generic code and trait objects get conservative summaries.
  5. Weak[T] (C) only for intent, not for cycles: caches and observer lists that should not keep a value alive. A separate, small decision; it can wait.
  6. Indices for general graphs (B), where no edge is a back edge: the refusal’s message points to them, and later to a std arena with generations.

Why, in the owner’s words, condensed:

Consciously excluded:

The risk, named honestly: until F and the summaries reach far enough, the rule refuses correct programs (measurements 5, 6). It is a breaking change for programs like the probe of section 1, which compile today and leak. In pre-alpha that is accepted, and measurement 3 shows how much of our own code it touches.

The owner’s decisions:

  1. Decided (2026-11-15): the user writes nothing for cycles; no weak handle the user places. Where the rule cannot allow a shape, the compiler points to indices. The reasons: complexity goes into the compiler, not to the user; immutable values pay nothing by proof; and a Weak[T] for caches and observers can still be added later.
  2. Decided (2026-11-15): a compile-time refusal of stores that close cycles (layers 2-4), not runtime trial deletion. The reasons are given above.
  3. Dropped: whether G’s runtime falls under the #1214 exception. G is not built.

Next:

9. Measurements still owed

  1. valgrind on the probe: bytes lost per two-node cycle.
  2. Size of a handle’s allocation with and without a weak count (Rc in Rust always carries it).
  3. How many types in crates/nikaia-std/src/tools/, packages/ and examples/ are self-reaching through SharedMut/Locked, and how many of those values are immutable already.
  4. callgrind for F’s lowering: a tree with parent links built, walked and torn down with F1/F2 links, against the same tree through indices and against a hand-placed Rc/Weak in Rust.
  5. For the rule: how many stores in our code it refuses, how many of those are correct, and how many function and package summaries remove.
  6. For F: on trees with parent links, doubly linked lists and observer pairs, how many back fields a first owners-as-dominators analysis proves, and what it costs in compile time.

Comments

keywan-ghadami, 2026-11-15

Decided (owner, 2026-11-15): the user writes nothing for cycles. The compiler refuses a store that closes a cycle of shared handles unless it proved a back edge, across functions and packages. There is no runtime detection; trial deletion (G) stays a possible later loosening.

Status changes from decision to note. This issue stays the reference for the decision paper and §9.


Generated by Claude Code

Back to Open Issues