From ae0071f3e951105a8c32b56c087789b29e665735 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 5 Dec 2026 15:46:14 +0000 Subject: [PATCH] Design note: -mm=own deferred releases - free after the borrow ends instead of refusing (draft for discussion) Co-Authored-By: Claude Opus 5.5 --- .../2026-12-05-own-deferred-release-design.md | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 docs/superpowers/specs/2026-12-05-own-deferred-release-design.md diff --git a/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md b/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md new file mode 100644 index 000000000..9f679e1e7 --- /dev/null +++ b/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md @@ -0,0 +1,177 @@ +# `-mm=own` deferred releases: free after the borrow ends instead of refusing + +Date: 2026-12-05. Status: draft for discussion. No code yet. + +## Intent and why + +Under `-mm=own`, a local that borrows (`let q: L | null = a; ... q = q.next`) is checked against +everything that may release or overwrite what it reads. When the release comes first, the program is +refused. An example (Fable's `r2`, `own_err_walk_const_head_cut`): + +```ts +const a = new L(0); a.next = new L(1); a.next.next = new L(2); +let q: L | null = a; +while (q) { if (q.i == 1) a.next = null; s += q.i; q = q.next; } // gc prints 3 +``` + +`a.next = null` frees nodes 1 and 2 at that point, while `q` is still on node 1. Today this is an error: +`'q' borrows 'q.next' but is used here after it may be released or overwritten`. + +The pass already computes everything needed to accept it soundly: + +- the dry run finds the conflict; +- `rootEnds` / `reachableAfter` give the borrow's extent: up to where `q` is assigned again or dies, and for + a borrow carried round a loop, up to the loop's exit; +- the release that conflicts is an op in the same function. + +The idea: **instead of refusing, move that release to the end of the borrow's extent.** The unlink still +happens where the program says (`a.next` is null at once), but the memory is freed only when nothing can +read it any more. + +Delaying a release can never cause a use after free; it only makes the memory live longer. So the design +is about choosing when the delay is allowed and making sure every delayed value is still released +exactly once. + +## Decisions for the user + +1. **The language rule changes.** `docs/own-memory-model.md` says: "Giving the head up, or cutting the + list, while the walk still reads it is an error." With this design: cutting the list in the same + function is allowed, and what was cut is freed when the walk ends. Giving the head up (a move) is + still refused (see the "not covered" rows of the table below). +2. **Default or opt-in.** Proposed: on by default, because it counts nothing at run time and only + accepts programs that are refused today. Every deferral could be reported by a new remark option (there + is none today) so that a user who cares about peak memory can see where memory is held longer. +3. **Order against the counted fallback.** Where both apply, deferral is used first: it has no + run-time count. `--own-fallback=count` is still what is used where deferral can't be proven. +4. **Consume-as-you-walk loops.** A loop that cuts behind itself every turn (`r3`: + `const p = q; q = q.next; p.next = null`) frees as it goes under rc and gc's collector, in O(1) + memory. Deferred to the loop's exit, everything cut is held until the loop ends: O(n), which on a + long-running loop is a leak in all but name. Options: (a) accept it and say so in the remark; + (b) flush at the end of each turn when the analysis proves no borrow carried into the next turn + reads what was cut that turn; (c) leave this shape to `--own-fallback=count`. Proposed: (b) where + provable, else (c), so that deferral never turns a constant-memory loop into a growing one. + +## Goals + +- Accept a release that conflicts with a live local borrow when the release is in the same function as + the borrow and the borrow's extent is known. +- No reference counting, and no cost on code that has no conflict. +- Release every deferred value exactly once on every way out of the extent: the normal end, `break`, + `continue` out of the loop, `return`, and a thrown exception. + +## Non-goals + +- Releases inside a called function (`clear(a)` that runs `n.next = null`). Deferring them would need a + deferral context passed into the callee. They stay refused, or counted under the fallback. +- Moves of the borrowed object to another owner (`keep(a)`, `h.t = q`). The free then happens wherever + the new owner drops it, which may be another function. Phase 2 below sketches a local subset. +- Borrow-inference gaps where nothing is freed at all (see the "not covered" rows of the table below). + +## Design + +### What may be deferred + +A release R (a `ReleaseSlot` before a store, a `Release` of a temporary, the release of a field's old +value) is deferred to the end of the extent of a local borrow B when all of these hold: + +1. R is in the same function as B and inside B's extent. Today the dry run would report R as an end of B + that a later use of B reaches (`reportPlaceBorrowOutlives`: "borrows ... but is used here after it may + be released or overwritten"). A refusal of another kind, such as "borrows ... and cannot be stored", + is not this condition and is not touched. +2. B's extent is known statically: B's next assignment, its scope's exit, or, for a borrow carried round + a loop, the later of the loop's exit and B's last use after it (`break; print(q.i)` reads past the + exit). These are the ends `rootEnds` computes today. +3. **R waits for every borrow it ends, not only B.** A release may end several live borrows at once: a + second walker, `const e = q`, a call's temporary that lends its argument back. R is deferred to the + latest end among all of them, and only if each one satisfies 1 and 2. +4. No call inside the extent may free what B reads. That check is unchanged: a call that may free stays + an end of B, and stays an error. Only R itself moves. +5. What R releases is held by nothing but the deferral after R. For the old value of a slot, rc's + `ReleaseSlot` + `Store` already says so: the slot gets the new value, so the old one has no other + owner. Ownership moves into the deferral, as it would into a temporary. + +### How a deferred release runs + +- **R runs at most once in B's extent** (not in a loop inside the extent): rc's release becomes a load + of the old value into a function-local temporary, and that temporary is released at each end of the + extent. The machinery that releases a temporary on each way out is already in the pass + (`checkReleasedOnce`, the releases rc puts on exits). +- **R is in a loop inside the extent** (the `r2` / `r3` shape: one cut per turn while the walk goes on): + a function-local deferral list. R pushes the old value; each end of the extent releases everything + pushed and empties the list. The list is a small growable array: two default-library helpers (named as + the default library's runtime helpers are; see the compiler-helper naming ruling), or a stack buffer with + a heap overflow. One list per + function is enough when the extents don't overlap. Overlapping extents flush to the mark they started + with (a stack of marks), as an autorelease pool does. + +A deferred node is released with whatever it holds when the release runs. So cutting a node out of a +node that is itself deferred (`r3`: `p.next = null` each turn) frees each node once: the first node's +deferred release finds `next` already null, and the second node was deferred on its own. + +### Exceptions + +A throw inside the extent must flush, like a temporary's release on the unwind path. **Assumption, not +yet checked in the code:** own releases temporaries on unwinding through the same cleanup rc emits, so a +flush can be added there with no new mechanism. To be confirmed before building; if own has no such +cleanup for temporaries, a deferral inside a `try` region is refused in phase 1. + +### What a user can observe + +- Peak memory: what was cut stays allocated until the walk ends. For a list cut once, that is the cut + part; for a cut per turn, everything cut during the loop. +- `WeakRef.deref()` / FinalizationRegistry see the object a little longer. JavaScript promises nothing + about when that happens, so this is allowed. + +## The scratch cases, classified + +Taken from `fable235/` and `t246/`. "own now" and "gc" are what the PR #1132 build printed on +2026-12-05. The last column was **classified by hand** from the rules above: nothing here has been +built or run. + +| Case | Shape | own now | gc | With deferral | +|---|---|---|---|---| +| `r2` | `a.next = null` inside the walk loop | refused: borrow used after release | 3 | **accepted**: list, flushed at loop exit; prints 3 | +| `r3` | `const p = q; q = q.next; p.next = null` every turn | refused: borrow "stored" | 3 | **unverified**: the refusal is not of the release kind (condition 1), so phase 1 accepts it only if the pass is taught to see `p.next = null` as a release end. Then decision 4 applies | +| `own_err_walk_const_head_cut` | `r2` as a test: `a.next = null` while the walk is on node 1 | refused | 3 | **accepted**: as `r2` | +| `r4`, `own_err_walk_const_head_cleared` | `q = q.next; clear(a); q.i`: the free is inside `clear` | refused | 1 | **still refused**: release in a callee (non-goal) | +| `r1` | `keep(a)` inside the walk: a move of the head | refused | 3 | **still refused**: move, not release | +| `f5` | `keep(a)` then `q!.i` | refused: use after move | 0 | still refused (phase 2 would cover it) | +| `own_err_walk_const_head_moved` | the head moved during the walk | refused | - | still refused | +| `own_err_let_borrows_local_moved` (Example 1) | `h.t = q; h.t = null; print(b.v)` | refused | 1 2 | phase 2 | +| `r5` | `G.push(a)` after the walk has ended | refused | 3 | not a lifetime problem: the borrow is dead by then. A precision fix (`r5_let` already compiles) | +| `t235f`, `t235g` | `a.next = b; b.next = c`: `b` used after moving into `a.next` | refused: use after move | s 3 | phase 2 (a moved local becomes a borrow of its new place) | +| `d12`, `g5`, `v5`, `w2`, `e3`, `bfull_nocall` | walks through `nn(c)` in a method, nested loops with no step | refused: borrow "stored" | runs | **not covered**: nothing is freed; these are gaps in borrow inference, a separate item | + +Phase 1 accepts one confirmed shape of the 18 refused programs: `r2`, which `..._cut` is as a test +(cut the list ahead of the walk, in the same function). `r3` may follow (see its row). Its main value is that the rule becomes simpler to state ("cutting a list you are walking is +fine"), not the count of programs. + +## Phase 2 (sketch, not proposed yet) + +**A moved local becomes a borrow of the place it moved into.** After `h.t = q` (or `a.next = b`), later +uses of `q` (`b`) read the object through its new owner. That is a borrow of the place `h.t`, bounded by +that place's releases and overwrites, which the place-borrow machinery already checks. When those +releases are local (`h.t = null` in the same function), they can be deferred as in phase 1. When the new +owner is a global or escapes (`keep(a)` into `G`), every call that may free anything ends the borrow, as +for any place borrow today. + +This covers Example 1, `t235f`/`t235g`, and `f5` when no call follows the move. It changes what "use after +move" means, so it is a separate user decision. + +## Tests to add with phase 1 + +- Accepted, with output equal to gc and rc: `r2` and `..._cut` (it becomes a positive test), `r3` if + decision 4 allows it; a borrow carried past the loop's exit (`break; print(q.i)`); a release that ends + two walkers at once; a deferred release inside + `try`/`catch` with a throw in the extent; `break` and `return` out of the walk; two overlapping walks. +- Still refused: `r4`/`..._cleared` (callee frees), `r1`/`..._moved` (move). +- Leak check: a 200k-iteration loop over `r2`/`r3` shapes keeps a flat private-memory size, as `leak/lk.ts` + does now. +- mm_fuzz: a generator option for cuts during walks, so the differential fuzzer covers the new path. + +## Left to decide while building + +- Whether the list helpers live in the default library or are emitted inline (a stack array of fixed + size with a heap overflow avoids a library dependency for the common case of one or two cuts). +- How deferral is reported (a new remark option), so that a user can see where memory is held + longer.