0278. In-place unique updates for long-lived state
- Status: Accepted (maintainer, 2026-11-22; recommended defaults for all open questions; frozen-file edits listed here approved)
- Date: 2026-11-22
- Plan: D6 (map.remove is independent and not designed here); amends 0040, 0043, 0053
- Review: Design Critic #5
Context
v.set(i, x) and m.set(k, v) copy the
whole buffer/table (O(n)) unless regions.rs
unique_sets proves the target a named local built
fresh in the same function (VecNew/MapNew), never snapshotted,
captured, passed or field-read; then it rewrites to
VecSetUnique / MapSetUnique (0040/0053).
Parameters start non-unique and Field reads reject.
Long-lived state is exactly that shape: TUI
impl App for M { fn update(self, e: Event) -> Step<Self> }
and agent transitions do
self with { items: self.items.set(k, v) }, so every
event copies the table and a session of n updates costs O(n²).
--report=copies (0043) already counts these as
set/map-set sites. Agent state is
promoted out of the transition arena after each step (0115, 0037);
trt_transition_colour copies only data owned by
transient arenas. with is shallow (0021): it copies a
struct of handles, O(fields), not O(n). The interpreter mutates in
place on *Unique ops
(Rc<RefCell<…>>) and clones otherwise,
trusting the proof.
Decision
Extend the static proof; add no syntax, no refcounts, no new container. A set reuses storage when its base is provably the last use of a uniquely held value. Three extensions:
- Field take. A record/union local is unique
when every heap field it holds is unique (built from fresh or
unique values, or a consumed parameter). In
s = s with { f: s.f.set(k, v) }(any depth:s with { a: s.a with { m: s.a.m.set(…) } }) the reads.fis a take, not an alias, iffsis unique and its old value is dead after thewith(only the new record survives). The set then rewrites to*SetUnique. Liveness is per IR block, as in 0037 placement; anything else (a snapshotlet old = s, a capture, a second read ofs.flive later) keeps today's copy. - Consumed parameters. Compute a per-function
summary
consumable[i]: the body would make parameteriunique (only takes/self-updates, never retains it). At a call site where the argument is a unique local at its last use (not captured, not passed toPar, not read after), the call targets a mono clonef$ownwhose consumable parameters start unique. One clone per function (all consumable parameters owned); a site that cannot own them all calls the shared original. Summaries converge on the existing BTreeSet worklist; recursion anddyn/indirect calls (ADR-0275) use the shared version. - Unique returns. Summary
ret_unique: the result is fresh or built only from owned parameters. A unique result (and its fields, e.g.step.app) seeds uniqueness at the call site, sovar model = init(); … model = model.update(ev).appstays unique across the loop, as do therun_tools_loopsingle-rootvar state(0212) and TUIStepdriver loops.
Arenas. An in-place set on a container whose
storage is outside the current scratch region places the inserted
key and value in the container's home region at insertion (0053
already copies keys on insertion), so an old-region container
never points into younger arenas. Transition promotion (0107/0115)
then stops at handles trt_transition_colour reports
as non-transient: an untouched or in-place-updated table costs
nothing per step. Growth reallocates geometrically in the home
region (0041 tip rule unchanged). Slice 1 verifies the promote
helpers do not recurse into non-transient containers; if they do,
it fixes that.
Visibility for agents.
--report=copies gains a reason per remaining
set/map-set site:
alias <var> live at L:C,
param not consumed (caller <f> L:C),
captured, indirect call. Fixtures pin
zero copy sites for the canonical TUI and agent update loops. No
consuming keyword now: if inference proves
insufficient after measuring, a copyfree fn marker
(mirroring checkfree, E07xx allocate at
implementation) can fail the build when a copy site remains; that
is open question 2, not part of this decision.
Semantics are unchanged: every rewrite is unobservable; copying
is always a legal result. Fuel charges are unchanged (no new
calls). map.remove lands separately; when it does,
the same proof rewrites it to a unique variant with one extra
match arm.
Prior art
- Swift
consuming/borrowingparameters and CoW uniqueness: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0377-parameter-ownership-modifiers.md, https://developer.apple.com/documentation/swift/isknownuniquelyreferenced(_:) - Perceus / FBIP reuse (Koka): https://www.microsoft.com/en-us/research/publication/perceus-garbage-free-reference-counting-with-reuse/
- Lean 4 "Counting Immutable Beans" (borrow inference, destructive updates): https://arxiv.org/abs/1908.05647
- Roc opportunistic in-place mutation: https://www.roc-lang.org/functional
- Persistent HAMT maps (Bagwell; im-rs): https://docs.rs/im/latest/im/
Alternatives considered
- (a) Explicit
consuming self/ owned parameters (Swift, Rust move) — new grammar and a rule agents must apply by hand on everyupdate; inference covers the same programs and the report shows misses. Kept as a fallback (copyfree) only. - (b) Runtime refcount + copy-on-write (Swift, Perceus, Lean, Roc) — arenas have no counts; adding them touches every handle, both backends, FFI and promotion, and makes cost depend on runtime sharing an agent cannot see in source.
- (c) Persistent structures (HAMT, Clojure, im-rs) — O(log n) every update even when unique, more memory, and breaks 0053's insertion-ordered dense layout; better as a later plugin type for genuinely shared snapshots.
- (d′) Whole-program alias analysis without
clones — a parameter unique at one caller and shared at
another would need runtime flags; one
$ownclone keeps it static and bounded.
Consequences
- UX: long TUI sessions and agents stay O(1) amortized per
update; no growing frame times. DX: idiomatic
with/setcode becomes fast without rewrites. AX (0009): no new syntax; the copies report names why a copy happened, so an agent's fix is local and checkable. - Code size: at most one clone per function with consumable
parameters; reported by
--report=copiesasclones: N. - Soundness rests on regions.rs (the interpreter trusts
*Uniqueops). Each extension adds positive and rejecting unit tests besideunique_set_rejects_every_container_escape_and_incoming_alias(in-memory compact source, milliseconds). - Verification:
bench/unique-state/drives a TUI-styleupdateand an agent transition with n = 10³, 10⁴, 10⁵ map insertions; time(10n)/time(n) ≤ 13 and runtime copied bytes stay O(n), output byte-identical across C andtenon interp. - LANGUAGE.md: +1 line (~40 tokens) under
Records/
withstating that last-use updates reuse storage and pointing at--report=copies; trims the "copies the table" caveat. IDIOMS.md: replace any copy-avoidance workaround with the plainwithform. - Frozen files: none expected. The interpreter already mutates
on
VecSetUnique/MapSetUnique(crates/tenon/src/interp.rs, crates/tenon/src/interp/heap.rs) and runs$ownclones as ordinary functions; a parity bug there would need the maintainer's OK.
Implementation slices
- Arena invariant. Confirm/fix that transition and carry promotion skip non-transient containers and that unique inserts place in the home region. runtime/trt_mem.h, runtime/trt_map.h, cgen_carry.rs, regions.rs. Frozen: no. Claude Opus.
- Field take + liveness. regions.rs
unique_setsper-block liveness, record uniqueness, tests. Frozen: no. Claude Opus. - Consumed parameters, unique returns,
$ownclones. regions.rs summaries, mono.rs clone emission, ir.rs verify. Frozen: no. Claude Opus. - Copies report reasons + fixtures. regions.rs reporting, main.rs flags, diagnostics.md check-reports, zero-copy fixtures for tui and agent loops. Frozen: no. Claude Sonnet.
- Bench + spec.
bench/unique-state/, LANGUAGE.md line, IDIOMS.md. Frozen: no. Gemini (agy Argon Low).
Open questions (resolved)
Resolved by maintainer on 2026-11-22: every question takes its stated default.
- Clone policy: one
$ownclone per function (default) / per ownership mask (more precise, more code)? - Fallback syntax: none until the bench shows misses (default) /
add
copyfree fnnow? - Extend field take to vec elements
(
v.set(i, v[i] with {…})with inner sets): later (default) / in slice 2? - Bench gate: on-demand
bench/only, per AGENTS.md (default) / also a CI job?