Aliasing and duplication
What this document decides
How a value is duplicated, whether its duplicates can observe each other, and which of those duplicates may cross a thread.
It supersedes "Amendment to Finding 3" in memory-model.md, which
reached the right problem and the wrong answer twice. The corrections
are recorded at the end rather than hidden, because two of them were
found by writing corpus against the proposal.
The problem, in one pair of declarations
examples/Buffer is a split-pane editor: two panes share one text, each
keeps its own cursor. Under the original design both are spelled the
same way:
Cursor implements Copy // duplicates are INDEPENDENT
Buffer implements Copy // duplicates ALIAS the same cell
One word, two incompatible guarantees, and nothing at either declaration
site says which you get. memory-model.md Finding 3 called this "one
mechanism (type-level Copy), not two" and counted it as an economy.
It is not an economy; it is a conflation.
Rust is careful at exactly this point: Arc<T> is Clone, not
Copy, and #[derive(Copy)] is refused for any struct holding one. The
restriction is what lets Copy keep meaning "trivially duplicable and
independent".
Three types carry the aliasing
The semantics lives in the type, where a reader meets it, not in a conformance they have to go and look up.
| type | second handle | can two handles observe each other? | crosses a thread? |
|---|---|---|---|
Shared<T> | implicit — it is Copy | no — nothing can write | yes, when T is Sendable |
Confined<T> | explicit — .alias() | yes — writes are mutual | no, ever |
Synchronized<T> | explicit — .alias() | yes — writes are mutual | yes, when T is Sendable |
All three are refcounted handles. Duplicating any of them duplicates a pointer, never the referent.
Shared<T> — immutable sharing
.new(v) and .get(). There is no .set.
An immutable alias is observationally identical to a copy: two
holders have no operation through which either can detect the other. So
it is Copy, for any T — Shared<[string]> is Copy even though
[string] is not.
That is not a new rule. memory-model.md Finding 6 already decided it
for references:
A reference (
&T, for anyT) is unconditionally cheap to copy… so&_belongs in the same "free, no declaration" tier as primitives.
Shared<T> is that rule given an owning form — &T with a refcount
instead of a lifetime. Same tier, same reasoning, no new precedent.
Confined<T> — mutable sharing on one thread
.new(v), .get(), .set(v), .update(fn (&var T) -> R) -> R,
.alias(). The thing a library reaches for when "edit this once, and
every holder sees it" is the actual requirement — examples/Sheet's
styles, examples/Buffer's text.
.update is the late addition and it is the one that matters: without it
a cell's only write is whole-value, so a cell holding a Move aggregate
cannot be written at all. See "The transform closure", below.
Never Sendable, under any T. It is Rc<RefCell<T>>, and it is sound
only because of cell-thread confinement (reactivity.md), which is
where the name comes from.
Synchronized<T> — mutable sharing across threads
The same capability where there is no single thread to confine to:
kind = .Binary server code, background work, examples/Worker's
pool. Arc<Mutex<T>>.
Its surface is two closures, one per direction:
.update(fn (&var T) -> R) -> R // read-modify-write under the lock
.read(fn (&T) -> R) -> R // read under the lock, return a derivation
hits.update(fn (&var n) { n += 1 })
The direction split survives here and not on Confined<T>, and the reason
is the lock rather than symmetry: a Synchronized<T> cannot offer .get()
because a read has to be bounded by the critical section, so read is how
it is read. Confined<T> has .get() and needs neither.
A .get()/.set() pair over a lock is memory-safe and still
logically racy — two writers interleave between the read and the write
and one update is lost. Confined<T> can expose that pair precisely
because the cell thread makes the sequence atomic; off the cell thread
nothing does.
And yield points are invisible (operators.md, "The amendment: a
call ends the turn"). A lock guard object could therefore be held
across a call that yields, and deadlock with nothing in the source
marking the boundary. elp also has no RAII, so there was never a good way
to express a guard anyway.
(This sentence used to add "and no &mut spelling". That is no longer
true — memory-model.md Finding 4's third amendment ratifies &var T —
and it is worth noting that the guard rejection does not depend on it.
The reason is the invisible yield point, which a spelling does not fix.)
Still true after release was designed, and after the construct for it
was deleted. memory-model.md first added with ... as x { } and then
deleted it (2026-11-20): release is defer x.release(), with release
taking &self, and no keyword. Neither version rehabilitates the guard,
and for the same reason both times — a defer releasing a lock, or a
with block's marked boundary, leaves the yield inside invisible, so a
lock held across one deadlocks exactly as before. The line is that release
is for resources, which need release once and in order, not for
locks, which need exclusivity between statements.
update originally took a pure transform, fn (T) -> T, which is
what examples/Pipeline corrected it to and which is what Confined<T>
never received. That shape was chosen because a mutating body needed two
things the language did not have — a &var T parameter spelling and
whole-value assignment through a reference. Both now exist
(memory-model.md Finding 4's third amendment, and self = … in a
method), so the transform has been widened to fn (&var T) -> R and the
two cells have the same shape. The properties that made the transform the
right mechanism are unchanged: it cannot forget to write back, and the
critical section is syntactically total.
The transform closure, ratified
One shape, at three sites, and it is the fix for all nine reports in
memory-model.md's "One hole, reported nine times":
Confined<T>.update(fn (&var T) -> R) -> R
Synchronized<T>.update(fn (&var T) -> R) -> R
Synchronized<T>.read(fn (&T) -> R) -> R
[T].update(at int, fn (&var T) -> R) -> R
Map<K, V>.update(key K, fn (&var V) -> R) -> R
Two constructs were both called with, and one is renamed
Synchronized<T>'s read-under-lock closure is read, not with. It
was with(fn (&T) -> R) -> R and it collided with memory-model.md's
with ... as x { }, which is an unrelated mechanism: one is a method on a
cell that bounds a read by a critical section, the other is a statement
that binds a resource to a block and releases it at the brace.
Caught by the user asking where with came from, having seen .with( six
times in the corpus and the statement once. That is the same defect as
realtime being spelled two ways, and the fix is the same: pick one
meaning per word. read also pairs with update, which is what the two
halves of the surface actually are.
- The payload never leaves. This is the difference from Rust's
RefCell::replace_withand it is what closesexamples/Recalc's GAP 7: there is no moment at which the cell is empty, so a re-entrant read cannot observe a hole. What it can observe is a half-finished value, and that is what rule 3 is about. -> Ris load-bearing, not a convenience.examples/EditorFINDING 3: an undo record needs the line that was replaced, and returning it out of the transform is the only way to get it without a second traversal.- Re-entering a cell inside its own
updatetraps, at runtime, in the same register as an out-of-bounds[](collections.md). The static exclusivity rule covers every path it can see; a second handle reached through a data structure is not statically decidable, so the dynamic check is the floor. A lint catches the visible case — the same cell handle captured by the closure. - The closure is not
pure, and that fork is closed. It was argued thatpure fnwould both forbid the hazards inside aSynchronizedcritical section and prevent a cell cycle being built.examples/InterpreterFINDING 8 falsified the second half:LETRECstores an already-aliased value, so the transform captures a handle and writes it, calling nothing, andgrammar-script-notes.mddefines the rule as being about side-effectful calls.purecannot see it. The first half survives as a real requirement with no mechanism yet — aSynchronizedtransform still must notbackground, receive from a channel, or lock a secondSynchronized— and it is now plainly a restriction on a body by position, which is where it should have been filed. Now ratified asnonsuspending, the third body property (functions.md), and it does two jobs for one marking: the hazards this rule was written for —background, a channel receive, a second lock — are precisely the yield points, so forbidding them also forbids a cancellation unwinding mid-write. The restriction stops being by-position and becomes a type: the transform takes anonsuspending fn (&var T) -> R. - The
&var Tmay not escape. It is a borrow and a field may not hold one, so storing it is already an error; this adds no rule and is stated because the closure makes it look like it might. .set(v)stays. It is the whole-value case, it is shorter, and it is what most writes are.updateis what makes the rest possible.
A defect the widening introduced, and it was not noticed when this was ratified. A transform that fails partway leaves the payload partially mutated, and there is no rollback.
c.update(fn (&var t) -> Either<int, Error> {
t.a = computeA()
t.b = computeB()? // fails here; `t.a` is already written
return Ok(t.a + t.b)
})
The argument for the transform was that "it cannot forget to write back, and
the critical section is syntactically total". Both are still true and
neither is the property wanted here: total means control reaches the end,
not that the value left behind is consistent. Under the original
update(fn (T) -> T) this could not happen — a transform either returned a
new value or it did not, so failure left the cell untouched. Widening to
&var T is what introduced it, and the widening is right for every other
reason.
It also extends the re-entrancy hazard rule 3 already records. That one says a re-entrant reader can see a half-finished value; this says the caller can, after the transform returns, with nothing marking it.
Three candidate answers, none decided — superseded, see "resolved by
commit" below:
- State it and move on. A failing transform leaves a partial write, the same way a failing method leaves a partially mutated receiver, which is already true everywhere in the language. Cheapest, and it gives up the one thing the cell idiom used to have for free.
- Require the transform to be total, so
Rmay not be anEitherand a failure has to be computed before the transform opens. Honest, and it pushes the work to the caller in exactly the case — a read-modify-write that can fail — where the transform was most wanted. - Snapshot and restore on a failing return, which needs
Tto beDuplicateand costs the copy the transform exists to avoid. Available only where the payload is cheap, which is not where this matters.
Raised by an outside review of the corpus, which asked what an early-return
path inside an update does. Nothing in the corpus took one, which is why
neither the probe nor the ratification found it.
RESOLVED for cancellation, by the property this restriction was already
owed. functions.md ratifies nonsuspending as the third body property
and the transform's parameter type carries it, so the closure cannot
background, receive from a channel, acquire a lock or run an effect —
which is the same list rule 4 below was written to forbid for deadlock, and
is exactly the set of yield points. With no yield point there is no
cooperative cancellation to land, and a panic is discarded by
RecoveryBoundary rather than observed.
So the signature is update(nonsuspending fn (&var T) -> R) -> R, and rule
4's "a real requirement with no mechanism yet" now has one. What survives
is the author-written failure path below, which is a smaller problem: it
is visible on the page, and the three candidates still apply to it.
It was worse than a failure path, because cancellation is not one.
examples/Dashboard found the sharper case: reactivity.md makes
cancellation cooperative — it lands at the next yield point and unwinds the
stack — and a transform may call anything, so it may yield. The unwind
leaves the payload half-written with no failure path on the page to see.
All three candidates above are about a failure the author wrote. None covers
an exit the author did not write, and the second one — forbid R from being
an Either — does not help at all here, which is worth knowing because it
was the most promising of the three. The transform's guarantee was that its
critical section is syntactically total, and cancellation is precisely a
non-syntactic exit.
So this is the one pair in the corpus the composability probe classed as
unsound rather than as a gap or a bad program, and it is the entry in
tradeoffs.md with the shortest fuse.
The partial write — resolved by commit, and the vocabulary was C++'s
RESOLVED, 2026-11-20. The three candidates above are superseded, and
what unstuck them was borrowing a vocabulary rather than inventing a
mechanism. error-handling.md now owns the three exception-safety
guarantees Abrahams named — nothrow, strong, basic — because
they describe what a caller may assume after a failure, which is the
question all three candidates were circling.
update(nonsuspending fn (&var T) -> R) -> R gives the basic
guarantee. That is not a defect in the mechanism, it is what &var T is:
the closure writes through a mutable borrow, so on Err those writes are
in the cell. Stating it is the first candidate, and it was right as far as
it went.
The cell surface gains a second form for the strong guarantee:
commit(nonsuspending fn (&var T) -> Either<R, E>) -> Either<R, E>
available when T: Duplicate. It is C++'s copy-and-swap, and elp already
had both halves: Duplicate is the copy, a move into the cell is the
nothrow swap. Take the lock, copy the payload, run the closure against
&var the copy, move it in on Ok and drop it on Err, release.
This is the third candidate — "snapshot and restore on a failing return" —
with the objection removed. It was rejected for costing "the copy the
transform exists to avoid", and that objection was aimed at the wrong
target: the transform exists to avoid a copy on the hot path, and this
copies only where the author asked for atomicity. The call site says which,
which is the thing all three candidates failed to make visible: .update(
means the payload may be half-written, .commit( means it is not.
It also closes the cancellation hole above, which is why this is
resolved rather than narrowed. A cancellation unwinds out of the closure
while the cell still holds the original, so the case with no failure path
on the page needs no rule of its own — for every Duplicate payload. That
is the tradeoffs.md entry with the shortest fuse, defused by a mechanism
that is one conformance and no new concepts.
Costs, in full: a copy inside the critical section, so commit is
forbidden in a realtime body like everything else that allocates (and
a realtime body has no failure path to be atomic about); nothing for a
non-Duplicate payload, where the basic guarantee remains all there is;
and the rule that a fallible transform must say which it wants —
error-handling.md carries the rule and the diagnostic.
Forced by examples/Recovery/internal/outbox.elp, which does the partial
write four times and has no correct handler for it: two items marked
delivered, the third's id unknown, the count advanced by two, and an Err
that says only UNKNOWN_ITEM. No correct handler is the signature of a
missing guarantee rather than of a missing arm.
What it closes. The cell's write surface (so a Confined<Node> holding
a Move aggregate is writable, which is five of the nine reports),
"collections hold values, not places" at the element it was written about,
and the invisible no-op tree-places.elp found in children[i].insert(…).
What it does not close, so the corpus scan can look for them: a Move
resource released out of a cell still needs a consuming .take()
(examples/Playhead GAP 6); Map.get on a Move value still needs a
borrowing read, which runs into Optional<&V> and the no-borrow-in-a-field
rule (tree-places.elp GAP 8); and a transform that captures a Move value
is called exactly once but the function type does not say so (GAP 7).
Atomic<T> — mutable sharing with a deadline
Synchronized<T> is a mutex, and a thread with a hard deadline must not
take one: it blocks on a lower-priority holder, misses the deadline, and
the failure is load-dependent and intermittent. A real-time audio callback
is the forcing case, and examples/VulkanTriangle's foreign-callback work
is what surfaced it.
T is restricted to what fits a machine word — int, bool, the
fixed-width integers, a payload-free enum. Nothing that allocates, so no
string, no [T], no Buffer<T>. Move and Sendable, refcounted like
its siblings.
T may also be a Copy object whose layout fits that word. Probe 11
found real code packing a transport flag and a generation counter into one
integer, because two separate atomics permit a combination that never
existed to be observed and a single load is the fix. That defends the
word-size restriction — packing is what an implementation does anyway — but
the hand-rolled form is an int plus two shifting accessors, which is
exactly the code that goes wrong silently:
export object Transport {
const playing bool,
const generation int32,
}
Transport implements Copy
const stopped = Transport { playing = false, generation = 0 }
const transport = Atomic<Transport>.of(stopped)
The constraint is T implements Copy and T's layout fitting one
machine word, checked at the use site:
Atomic<Transport>requiresTransportto fit in 8 bytes;Transportis 12 bytes.
That needs the compiler to compute a concrete layout for an object, which
is the capability @external struct fields already demand (probe 10,
finding 3) arriving from a third direction — so it is affordable, and the
two should be settled together. Atomic<int> and Atomic<bool> become the
degenerate cases of one rule rather than the whole surface.
The word size is a target property, so an object that fits on a 64-bit target and not on a 32-bit one is a per-target error. That is unpleasant and nothing in the design makes it avoidable: the guarantee being bought is a single-instruction load.
fn Atomic<T>.load(&self) -> T
fn Atomic<T>.store(&self, value T)
fn Atomic<T>.exchange(&self, value T) -> T
fn Atomic<T>.compareExchange(&self, expected T, value T) -> bool
Load and store, deliberately not a transform. The sibling symmetry
argues for update(pure fn(T) -> T), and over a word that is a
compare-and-swap retry loop rather than a lock — the "no external calls"
rule makes a pure transform free of consequence to retry, so the surface
would even be sound. It is still the wrong spelling, because a CAS loop
is unbounded in the worst case and the retry is exactly the part a
real-time programmer needs to see. Whoever wants the loop writes three
visible lines.
A lock-free Synchronized<T> was rejected on the same grounds. Making
that type use CAS whenever T fits a word and a mutex otherwise would be
a performance optimisation applied conditionally, which is the single
worst property for code with a deadline: the failure is silent and
load-dependent. The guarantee has to be static and visible in the type,
which is the same reason Confined<T> and Synchronized<T> are two types
rather than one type with a mode.
Sequential consistency only, with no orderings exposed
No relaxed, acquire, release or seqcst argument. Three reasons:
- Exposing orderings means elp has to specify a memory model, which is a document every language that has one regrets the first draft of.
- Most callers would reach for
relaxedbecause it reads as "faster", and the resulting bug is unreproducible. - Relaxing later is additive; tightening is not.
The cost is real and lands worst on the targets that matter most — a
barrier on every operation, and .iOS and .Android are ARM. It is
affordable because the operations this exists for happen once per buffer
rather than once per sample.
What must not happen on a thread with a deadline
Three are obvious: no lock, no allocation, no blocking call. Two are not, and both bear on decisions already recorded:
- A refcount decrement that reaches zero deallocates. Cloning a handle
is an atomic increment and costs nothing; the last drop calls the
allocator, which takes a lock. So such a body must never hold the last
handle to anything.
memory-model.md's rule that passing a cell asOpaque<T>does not retain already guarantees it — argued there on leak grounds, and load-bearing for this second reason too. - An owned parameter might be the thing that frees. So a real-time
body's parameters may be borrows and
Opaquecells and never ownedMovevalues:&Buffer<T>, neverBuffer<T>.
Where a deadline body's private state lives
A deadline callback needs state that persists between calls and is private to it — a read cursor into an event buffer, the generation it last applied, whether it was playing on the previous call. Probe 11 found all three in production, and found them as plain mutable fields rather than atomics, precisely because exactly one thread ever touches them.
elp has nowhere obvious to put them. A local does not survive the call, and
a package-level variable does not exist — memory-model.md forbids globals
outright. So the state has to arrive through the void*.
And that settles what holds it, before any question of who may touch
it. The boundary table's cell row is Opaque<Cell<T>>, never Opaque<T>
over a bare object, and the out-of-line principle says why: a bare elp
value is in-line and moves, so there is nothing for C to hold the address
of. Only a cell's contents and a Buffer<T>'s elements qualify. So private
deadline state sits in a cell, and the kind is forced rather than
chosen:
Shared<T> | immutable — no |
Synchronized<T> | a lock, forbidden on a deadline thread — no |
Atomic<T> | word-sized, and puts a private value back into shared memory to pay a barrier no other thread wants — no |
Confined<T> | mutable, unsynchronised, out-of-line — yes |
Which answers something that looked like a missing mutability
spelling. A deadline body updating its cursor needs no &var self and no
&var T parameter, because the mutation does not go through the receiver:
it goes through the cell, and .set() takes &self. examples/Sheet had
already written the sentence — “&self, not &var self: the object is
unchanged, the cell it points at is not” — so there was never a gap here.
There was a boundary form written as Opaque<T> over a bare object, which
is not one of the three.
Privacy remains the answer to who may touch it. memory-model.md
scopes private to the type, reached through self, so the cell is
unreachable from anything but the deadline type's own methods. The two
mechanisms answer different questions and both are needed: Confined<T>
for what holds the state, privacy for what may reach it.
The discipline, stated so it can be checked by reading:
- state shared across the boundary is an
Atomic<T>, aRing<T>endpoint or aPublished<T>endpoint, and lives on the shared half; - state private to the deadline body is a
Confined<T>of aCopyobject, held by a type whose own methods are the only way in, and never aliased.
Confined<T> off the cell thread, and the one sanctioned crossing
Confined<T> is Rc<RefCell<T>> and is sound above “only because of
cell-thread confinement”, which is where the name comes from. A deadline
thread is not the cell thread, so that justification is unavailable here —
and the conclusion survives for a narrower reason.
Exactly one holder. examples/Sheet justifies the read/copyWith/write
idiom by cell-thread serialisation, so that a read-modify-write cannot be
interleaved. On a deadline thread the same idiom is atomic because nothing
else holds the cell at all. Move supplies that and .alias() takes it
away, so:
A
Confined<T>that crosses to a foreign thread is moved in once and never aliased.
Confined<T> is never Sendable under any T, and handing one to C to be
called back on another thread is a crossing — so this is an exception and
has to be named as one. Opaque<Confined<T>> in an @abi(.C, realtime)
parameter is the one sanctioned crossing of a non-Sendable cell.
And it is weaker than the parallel it invites. Buffer<T> by value is sound
because the value is gone: the hazard is absent, not checked. Here the
registration must keep holding the cell, since Opaque<T> does not retain
and something has to keep it alive. What is relinquished is access, not
the handle — and privacy is what relinquishes it.
So privacy is load-bearing for soundness at this one boundary rather than for tidiness, which turns the open item below from a style question into a real one.
One consequence the corpus had not met before: a cell holding a Move
aggregate cannot have its fields updated at all. Confined<T>'s only
write is .set(whole), so the idiom needs T to be Copy, and a Move
field cannot be taken out of the &T that .get() returns either. Every
cell in the corpus until now held a Copy payload — examples/Sheet's
StyleValues, examples/Pipeline's Stats — so this is the first place
the restriction bites. It is “collections hold values, not places” reaching
cells rather than a new rule, and it means a registration holding Move
resources and mutable private state needs a nested cell per mutable part,
whose own teardown then has no spelling. Open below.
And this is why Atomic<T> does not get the endpoint split
The obvious reading of probe 11's cursor bug — a seek clobbered by the next
callback's write-back — is that cells want Ring<T>'s two-endpoint
treatment, so that one side writes and the other cannot.
That is the wrong lesson, and the production fix says so. The cursor did not get a constrained writer; it stopped being shared at all. It became private to the deadline body, and what crosses the boundary is a request that the next callback applies. An endpoint split would have fixed the symptom and left a word being written across a thread boundary for no reason.
The decisive argument against it is that multi-writer atomics are the normal case, not an abuse: a CAS on a shared list head, a refcount, a work-stealing index — and in that same probe, the transport word, which both threads compare-exchange. Constraining the general primitive to one writer would break every one of those to fix something privacy already fixes.
So the split stays where it was earned, and the tiers on an endpoint pair are not boilerplate — they state which discipline is being enforced:
| writing end | reading end | what the tiers enforce | |
|---|---|---|---|
Ring<T> | Move | Move | single producer and single consumer |
Published<T> | Move | Copy | single writer, any number of readers |
Atomic<T> | one undivided handle | nothing, deliberately |
Ring<T>'s consumer is Move because a second consumer races on the read
index. Published<T>'s reader is Copy because a seqlock read is
re-entrant by construction, and several components sampling one playhead is
the expected use rather than an abuse of it.
Opaque<T> and the cell kind stay orthogonal
Opaque<T> says how C names a thing; the cell kind says what discipline
governs access to it. Opaque<Atomic<int>> therefore works the day
Atomic<T> exists, with no change to memory-model.md's three boundary
forms — which is the test of whether that table was drawn at the right
level, and it passes. Collapsing the two would mean an Opaque variant
per discipline, and the C side would be carrying information C does not
have.
Ring<T> — and Move turns out to enforce SPSC
A single-producer/single-consumer ring buffer is the pattern a real-time thread actually needs, and in practice the hard part is not the atomics. Three distinct bugs wear the name "invalidation" and they are fixed in three different places:
| symptom | where the fix is | |
|---|---|---|
| payload overwritten | the consumer holds a reference into a slot, the producer wraps, a read is half-old and half-new | the API |
| false sharing | no wrong data — unpredictable latency spikes under load | layout: two cache lines |
| torn read | a payload wider than a word, partially written | falls out of the other two |
The first is answered by a rule chosen for unrelated reasons. A ring
must never hand out its interior: pop moves the value out, and that is
what makes the slot releasable. That is "collections hold values, not
places" (memory-model.md), ratified because an API that forgets a
write-back should be a visible no-op — and forced here by a concurrency
argument that did not exist at the time.
It also bounds what the view design buys, which is worth stating: a borrow is not a synchronisation primitive. Making a view borrow-shaped stops this code from retaining it and does nothing about a producer on another core overwriting the slot. So a ring must not expose one, and "views are borrows" is not a licence to hand one out here.
The two ends are two values
const { producer, consumer } = Ring<Event>.of(capacity = 256)
Each endpoint is Move, so it lives in exactly one place. A thread cannot
push unless it holds the producer, which means the type in hand says
which side of the fence the code is on — not a comment, not a naming
convention.
And the find worth recording: SPSC's precondition is exactly what Move
already means. "Single producer, single consumer" is something every
ring buffer library documents and none can enforce; here a second producer
is unconstructible. The tier system enforces the invariant for free.
That pairs with @abi(.C, realtime): the endpoint says where the code is
locally, and the propagating check says where it is transitively —
naming the chain when an allocation appears nine frames deep. Neither
alone is the answer to "which thread is producing this work".
The binding form needs patterns.md's "Destructuring an owned aggregate",
and the accessor alternative (.producer() / .consumer()) is worse:
"call each exactly once" is unenforceable, which gives back the guarantee
the split exists to provide.
The surface
fn RingProducer<T>.push(&self, value T) -> Optional<T> // nil on success, the value back if full
fn RingConsumer<T>.pop(&self) -> Optional<T> // nil if empty
push returning the value on failure is the honest signature for a
bounded queue that may carry Move payloads: it cannot be dropped on the
floor, and it certainly cannot be freed on a deadline thread.
&self rather than &var self, consistent with examples/Buffer:
mutation goes through the cell.
T needs no constraint. A Copy payload looked necessary to keep
pop allocation-free, and it is not: the ring only ever moves — in on
push, out on pop — and a move never allocates for any tier. So
Ring<Buffer<float>> works, which matters, because that is the
garbage-return channel. A deadline thread swaps in a new allocation and
pushes the old one back; a thread that may block pops it and lets it die
there. That closes the one pattern a deadline thread otherwise cannot
express, since it must not free.
Capacity rounds to a power of two so wraparound is a mask and the counters may wrap freely.
Published<T> is the other half of the same asymmetry
A ring is for events that must not be missed. State where only the
latest value matters — a playhead, a peak meter — wants the opposite
trade, and it gets a different primitive because the two ends are not
symmetric: the deadline side must be wait-free, while the side reading it
may retry, having no deadline. That is a seqlock, and exploiting the
asymmetry lifts the word-size restriction Atomic<T> carries.
| must not miss any | only the latest matters | |
|---|---|---|
Ring<T> | Published<T> | |
| deadline side | push, may fail when full | publish, never fails |
| other side | pop | sample |
| payload | any T, moved in and out | any Copy T |
Both are single-writer and both get that from Move on the writing
endpoint. Published<T>'s reactive read is deliberately not settled
here: it is the only piece that touches reactivity.md, and it deserves
its own pass rather than riding in on a concurrency decision.
All speed on the writer, all policy on the reader
Three of probe 11's findings looked like three problems and are one. The deadline side must be wait-free and unconditional; the reading side has a whole frame, may branch, may retry, and may be wrong without anything dying. So every decision belongs on the reader, and the writer's only job is to be fast.
Staleness is a reader decision. An age measures staleness, not elapsed time: extrapolating a playhead from its age is right while audio flows and wrong the instant it stops, because past some threshold an age stops meaning "this much has happened" and starts meaning "the producer died" — opposite instructions from the same number. The fix is not for the publish to carry a threshold, which was the first instinct. The producer publishes its rate, which it knows; the reader derives a cap from that rate and decides what to do past it. The same information, and no policy on the hot path.
Validity is a reader decision. A position published after playback
restarted mid-buffer is stale and must not replace the new start's. The
instinct is a guarded publish — publish(value, ifEpoch = word) — and it
is wrong twice: the epoch belongs to the transport rather than to the
position, so the primitive would be checking a condition it cannot see, and
it puts a branch and a re-read on the one thread that must have neither.
Put the epoch in the payload instead. The writer publishes a
{ frame, generation } unconditionally; the reader samples the transport
too, and discards a reading whose generation does not match. So publish
genuinely never fails, the table above is right as recorded, and the
finding is about how the primitive is used rather than what it is.
What the reader may not do is act on the producer. A playhead that decided playback was over killed the transport during the release tail, so a loop never survived its first pass. "All policy on the reader" means policy about the value — what to show, what to discard, how far to extrapolate — and never control over the producer.
And there is no language feature for that. A read-only endpoint would not have helped, because the offending call was on a different object entirely; enforcing it needs a capability system, which costs more than every bug of this shape put together. It is recorded as a design rule with its evidence attached, and that is the honest outcome — the corpus exists to find what the language needs, and sometimes the answer is nothing.
Still open
- Whether a deadline body's private state wants enforcement. Privacy
keeps the control thread out of a render cursor, but only as far as the
package boundary; inside a package it is convention. That convention is
now load-bearing for soundness rather than tidiness, which is the argument
for a marker meaning "reachable only from an
@abi(.C, realtime)body". - Releasing a
Moveresource held inside a cell. Wrapping a registration in theConfined<T>the boundary form requires leaves its teardown unexpressible:.get()hands back a borrow, aMovefield cannot leave one, and.set(whole)needsCopy. Three candidates — a consuming.take() -> Ton a uniquely-held cell,releasereaching through a cell it is the last holder of, or keeping theMoveresources beside the cell rather than inside it. The third is probably right and is an architectural claim: what a deadline thread must read and what the program must release are different sets. - Waiting on the non-deadline side. A UI thread wants to sleep until something arrives, and a deadline thread must not signal a condvar — that is a syscall. Polling and a lossy wakeup are the two honest answers and neither is designed.
Weak<T>. Undesigned, and deliberately left so — see "Reference cycles" below for why the shapes that would need it are mostly unconstructible, and for what would reopen the question.- Multi-producer is deliberately out of scope.
Moveenforcing SPSC is a feature, not a limitation worked around; MPSC is a different type with a different cost.
Reference cycles, and why three of the four cells cannot form one
elp reclaims memory by reference counting. There is no tracing
collector anywhere in the design and no destructors, so a cycle of handles is
never collected, and Weak<T> was for a long time not a decision but an
absence.
Corrected — this paragraph twice said "no defer, nothing at scope exit",
and both halves are wrong. reactivity.md designs defer in full and
states that it is "a general language feature rather than an effect
feature"; memory-model.md adds defer x.release() and Scoped. So the
language has three scope-exit constructs and this file was arguing from
having none. The conclusion survives — a defer releases what
you tell it to and a cycle is precisely what nobody tells it about — but the
premise was never checked, and the second instance of it is load-bearing for
an Open item below. examples/Json found it, in a parser that uses defer
to decrement a depth counter.
examples/Recalc was written to find where the corpus leaks one. The answer
is narrower than "refcounting leaks cycles" and wider than "it cannot
happen".
Every cycle must pass through a cell. A plain elp value is owned and ownership is a tree, so shared ownership exists only in the four cell types and they are the only candidate edges in a loop. Taken one at a time:
| can it be an edge in a cycle? | |
|---|---|
Atomic<T> | no — the payload is a word-sized Copy value and cannot be a handle |
Shared<T> | no — .new(v) and .get(), no .set. A cycle must be closed after construction, since neither node exists while the other is built, so an immutable cell can never be the closing edge |
Confined<T> | only awkwardly — its write is .set(whole), needing T to be Copy, and a type holding a Confined is Move field-wise |
Synchronized<T> | same, through .update |
Three are closed off, and two of them by rules argued for on entirely
unrelated grounds. That is why the probe's realistic graph came out acyclic
without trying: the natural handle-per-node graph is unconstructible,
because a cell cannot hold a mutable Move aggregate, and what is left is
an arena keyed by address whose ownership is a tree.
The needle can still be threaded, and the whole leak is this:
export object Knot {
const peer Optional<Shared<Confined<Knot>>>,
}
Knot implements Copy // `Shared<T>` is `Copy` for ANY `T`
const a = Confined<Knot>.new(Knot { peer = nil })
const b = Confined<Knot>.new(Knot { peer = .SOME(.new(a.alias())) })
a.set(Knot { peer = .SOME(.new(b.alias())) }) // closes the loop
It works because Shared<T> is Copy for any T, which was argued above
from "an immutable alias is observationally identical to a copy" — true, and
about observation rather than reachability. So a Copy payload may
transitively own a mutable cell, and Confined<T>'s Copy requirement is
satisfied by exactly the thing it was meant to exclude.
So: a cycle is constructible and leaks silently with no diagnostic; it is not reachable by accident in the shapes the corpus produces; the one route is an odd thing to write and an easy thing to spot; and a program that genuinely needs a back-edge between cells has no spelling for one.
The recommendation is not to add Reversed by
Weak<T> now.examples/Interpreter — see "And an interpreter settles it", below. The
argument above is still the right argument and its evidence was too narrow: a
spreadsheet graph is a program whose ownership is a tree once handles are
dropped, and its arena is free because the arena's lifetime is the program's.
Neither property holds generally. Kept in place rather than rewritten, because
what the reversal turns on is which premise failed.
And the loosening is already indicated, from a different direction
Superseded in its conclusion's favour. Everything below argues for
giving Confined<T> an .update, against the narrower
update(fn (T) -> T) signature that was on the table at the time. It got
one, in the wider fn (&var T) -> R form — see "The transform closure,
ratified", above. The reasoning is kept because the pricing in it is
still the argument, and because the fork it spends most of its length on
turned out not to be a fork.
That last sentence turned out to be a prediction with a date on it.
examples/Recalc/internal/handles.elp re-ran the probe against one proposed
addition and the answer inverts, so the result above must be read as
conditional on a cell's only write being whole-value rather than as settled.
The addition is Confined<T>.update(fn (T) -> T), by symmetry with
Synchronized<T>, and the case for it has nothing to do with cycles.
Pricing a read-modify-write by the payload's tier:
| payload | how it is spelled today | cost per write |
|---|---|---|
Copy | c.set(c.get().copyWith(…)) | one record copy |
Duplicate | c.set(c.get().copy().insert(…)) | deep copy of the whole payload |
Move | — no spelling exists — | impossible |
The middle row is examples/Buffer's self.lines.get().copy().insert(...),
quoted approvingly in the Open item below: a shared mutable text buffer
duplicating every line on every keystroke. The bottom row is the Move
aggregate finding above. Stated as one defect rather than three reports:
mutation of shared state goes through a cell, and a cell's only write is
whole-value, so shared mutable state is either transitively Copy, or costs
a deep copy per write, or is unexpressible. .update closes all three at
O(1), because it moves the payload out and back instead of duplicating it.
The justification for the current asymmetry does not cover this. It is that
"a .get()/.set() pair over a lock is still logically racy… Confined<T>
can expose that pair precisely because the cell thread makes the sequence
atomic" — which argues the pair is permissible on the confined cell, not
that .update is unnecessary there. Two claims, run together.
What that does to the cycle answer. With .update, the handle-per-node
graph is constructible, and the leak stops being a needle:
sheet.link(A1, B1) // A1 = B1, an entirely acyclic formula
A1.precedents == [B1] // A1 holds a handle to B1
B1.dependents == [A1] // B1 holds a handle to A1
A bidirectional graph makes every edge a cycle. Not a circular formula —
any formula naming a second cell, and equally every parent link, observer
registration and doubly-linked list. So Weak<T> goes from unnecessary to
mandatory. The decision not to design Weak<T> and the decision not to
give Confined<T> an .update are one decision, and they were recorded in
two places as if independent.
And the fork looked one word wide. It is not a fork. The proposal is
update(pure fn (T) -> T), so the transform's limits come from a mechanism
that already exists, and closing an edge from inside a transform appears to
need b.alias() in the closure body — making the whole question whether
.alias() is a side-effectful call, which grammar-script-notes.md leaves
to an undesigned effect system:
if pure is observational | if pure is about reachability |
|---|---|
.alias() allowed in a transform | .alias() rejected in a transform |
| every edge leaks | the result above survives intact |
Weak<T> mandatory | Weak<T> stays unnecessary |
Confined<[T]> mutates in O(1) | so does it — a buffer insert captures no handle |
The right-hand column does not exist, and examples/Interpreter FINDING 8
is why. Closing an edge does not need .alias() inside the transform. A
LETREC writes an already-aliased value into a scope:
scope.update(fn (&var e) { e.bindings.set(name, bound) })
bound is a closure whose captured-environment field was aliased several
frames earlier, in a different arm of the evaluator. The transform captures
a handle and stores it; it calls nothing. Captures are settled —
functions.md's own transform closes over frames, and the rule is "pure
functions containing side-effectful calls" — so a bare capture-and-store
is admitted and a pure transform closes the cycle.
Narrowing pure to forbid capturing a cell handle by type would not help:
reading the captured cell is a call and is caught anyway, while merely
storing a handle is all the cycle needs, and a restriction by capture type is
"a restriction by position" in a new costume — the thing pure was reached for
to avoid. So the left column is the only column, and pure was never the
deciding variable.
The observation-versus-reachability conflation is still real and still worth
deciding once: Shared<T> is Copy for any T because "an immutable alias
is observationally identical to a copy", a claim about observation
settling a question about reachability, and it is the reason the Knot
needle exists. What it does not do is decide this.
.update empties the cell — resolved by the signature it was written against
.update empties the cellThe objection was aimed at update(fn (T) -> T), which moves the payload out,
transforms it and moves the result in, so for the transform's duration the
cell holds nothing and a transform reaching its own cell observes a hole
rather than a stale value. handles.elp GAP 7 demonstrates it with an
ordinary graph invalidate holding a borrow across a recursion that comes
back round.
The ratified signature is update(fn (&var T) -> R) -> R, and the payload
never leaves. There is no hole, because nothing is moved. What survives is
the weaker and ordinary hazard: a re-entrant reader sees a half-finished
value, which is the state any mutation passes through, and that is what the
runtime trap in "The transform closure" rule 3 is for. Kept on the page
because the difference between the two signatures is invisible at every call
site and this is the one place it is observable.
And an interpreter settles it — Weak<T> is mandatory
examples/Interpreter is the deciding probe, because an interpreter's cycle is
not an encoding choice. LETREC has to make a bound name visible inside its
own value, so there is exactly one arrangement and every language with
recursive functions uses it: create the scope, evaluate the value in it so the
closure captures it, then write the closure into the scope. The third step
leaves one cell holding a handle to itself through its own contents —
tighter than the two-cell Knot needle, and reached by writing let rec.
No reordering avoids it. The closure must see the binding, which is what
recursion means; the binding must hold the closure, which is what let rec
means. Placeholder-then-patch, which real implementations use, is that third
step renamed.
Four things are now jointly true, and together they overturn the recommendation:
- the cycle is in the semantics, so no spelling avoids it;
- it is a self-cycle through one cell, so "three of the four cells cannot be an edge" does not bound it — only one cell is involved;
pureon the transform does not prevent it (above), so the fork has one column;- the arena escape fails here, and fails differently from how it succeeded
in
examples/Recalc. A spreadsheet'sGraphlives as long as the sheet, so an arena that never shrinks is correct and free. An interpreter's scopes have genuinely dynamic lifetimes, so every scope ever entered stays in the arena forever, and recovering them means walking reachability over the indices — a tracing garbage collector, hand-written, inside the interpreter. That is a worse outcome than designingWeak<T>.
The prior art agrees and it is not a matter of implementation taste: CPython refcounts and ships a cycle collector, which exists for precisely this shape; Lua, Ruby and the JVM trace. No production interpreter refcounts without either a cycle collector or weak references.
And this is not an exotic corpus entry. It is BlogStyle's JSON, a template
engine, a query planner, a build-rule evaluator — anything holding a
user-authored expression.
But the target is narrower than the prior art suggests, which
examples/LruCache establishes by failing to need it. The canonical weak var
site — a doubly-linked list beside a map — needs no Weak<T> here, because
Map being insertion-ordered already is the recency order the list
maintains, so the whole structure evaporates and ownership is a tree again. So:
| shape | cycle? | why |
|---|---|---|
a dependency graph (examples/Recalc) | no | edges are addresses; the arena's lifetime is the program's |
an LRU cache (examples/LruCache) | no | the back-edge is recency order, and an insertion-ordered Map is one |
let rec (examples/Interpreter) | yes | the cycle is in the semantics; the arena escape becomes a hand-written GC |
A data structure's back-edge is an index in disguise and dissolves under a
better primitive. A language's cyclic value does not. Weak<T> is taught
with the first and needed for the second — so it does not have to be ergonomic
enough for everyday graph code, because everyday graph code should not reach
it. Which matters for the cost question: a rarely-used Weak<T> can afford to
be expensive, or be forbidden outright in an @abi(.C, realtime) body
rather than made cheap enough for one.
Weak<T>, ratified — and it does not solve let rec
fn Confined<T>.weak(&self) -> Weak<Confined<T>>
fn Synchronized<T>.weak(&self) -> Weak<Synchronized<T>>
fn Weak<C>.upgrade(&self) -> Optional<C>
- The parameter is the cell, not the payload.
Weak<Confined<T>>, so that upgrading cannot hand back the wrong kind of handle and so thatSendablefalls out of the cell it names rather than needing its own rule.Cis constrained to the two mutable cells, which the compiler knows because it already knows them; this is the first concrete customer forstdlib-boundary.md's unmade decision between a privilege marker and compiler-known types, and it is noted there rather than decided here. Weak<C>isCopy. A weak handle grants no access at all untilupgradeis called, so a second one observes nothing — the same immutability argument asShared<T>, and it joins that table. The consequence is a pleasing one:.alias()costs you a word on a strong handle, and a weak handle is free, because it is not yet a handle to anything.upgradereturnsOptional<C>, and that is the whole cost. Every traversal of a weak edge carries anOptional, which is exactly the visibility wanted — a weak edge is a design decision and it should be legible at the places that depend on it.- Forbidden outright in an
@abi(.C, realtime)body. Not narrowed the waystringandShared<T>are narrowed to "borrow yes, copy no": using aWeakmeans upgrading, and the strong handle that produces is dropped at the end of the expression, which can reach zero and call the allocator. There is no borrow-only use, so there is no rule to narrow. The table above is what makes this affordable — everyday graph code should not be reaching for this. - Which edge is weak is the author's decision, and nothing infers it.
That is the standing cost of refcounting, it is the same cost Rust and
Swift pay, and it is why "A leak has no observable symptom", below, is not
a gap that
Weak<T>closes.
And now the correction, because ratifying is where it has to be said:
Weak<T> is not the answer to let rec. The section above establishes
that an interpreter's cycle is in the semantics and that the arena escape
degenerates into a hand-written collector. Both stand. What does not follow,
and what a reader will take from it, is that a weak edge fixes it — and it
does not, because neither edge may be weakened:
| weaken | what breaks |
|---|---|
| closure → captured scope | a closure returned out of its scope loses its environment |
| scope → bound closure | a sibling binding in a live scope can still reach f, and f is gone |
Which is precisely why CPython ships a cycle collector in addition to
refcounting rather than exposing weakref and calling it done. So the
position elp takes is the one Rust and Swift take and it should be written
down rather than discovered: a let rec cycle leaks, and a leak is safe.
No tracing collector, no cycle detector, no runtime elp does not otherwise
have.
What makes that acceptable rather than a hole is where the escape lives. An
interpreter that cares reclaims scopes itself, by arena and index, and that
is not a workaround — it is what CPython's collector is, written once in a
runtime instead of once per program. The useful move is to make it a
library: an Arena<T> with index handles is plain elp, bucket 3 in
stdlib-boundary.md, and the one program in the corpus that needs it
(examples/Recalc) already has it hand-written. Weak<T> is ratified for
the shapes it does fix — a parent back-edge, an observer list, a cache of
things someone else owns — and let rec is not one of them.
What is now open is Weak<T>'s cost, which is a different problem. The
sharp edge is in the prior-art notes below: weak needs a side table and must
zero every weak reference at deallocation, while @abi(.C, realtime) forbids a
refcount decrement reaching zero because deallocation takes a lock. Weak<T>
makes release strictly more expensive in the one place this language cares
most, and that is the design question to answer.
Prior art — Rust, Go and Swift all solve this, two of the three ways are closed
Recorded because the comparison is cheap to get wrong from memory and the clashes are not obvious.
| mutate shared state in place | reference cycles | |
|---|---|---|
| Rust | RefCell::borrow_mut() -> RefMut<'_, T>, a guard deref'ing to &mut T; runtime borrow flag, panic on conflict. Also replace_with<F: FnOnce(&mut T) -> T> | Rc/Weak, upgrade() -> Option<Rc<T>>. No collection — you leak. For graphs, the idiom is an arena of indices (petgraph, slotmap), because the handle graph is miserable |
| Go | pointers into GC'd memory; node.F = append(...) directly. Sharing is a sync.Mutex in the struct | collected by the tracing GC. Go 1.24 added weak.Pointer[T] and runtime.AddCleanup — for caches, not cycles. Note SetFinalizer never runs for an object in a cycle, which is part of why AddCleanup exists |
| Swift | classes mutate directly through a reference under ARC; structs get mutating methods plus copy-on-write collections. Also inout parameters and _modify accessors. Exclusivity enforced statically where possible, dynamically where not, trapping | weak (optional, side table, zeroed at dealloc) and unowned (non-optional, traps), unowned(unsafe) for UB-with-a-comment. No collection |
All three separate mutating a place from replacing a value, and elp has only the second. There are exactly three mechanisms in the prior art for the first, and elp's position on each is already on record:
| mechanism | who | elp |
|---|---|---|
| a guard | Rust RefMut, Swift's dynamic exclusivity | rejected — invisible yield points, above |
an &mut/inout parameter | Rust, Swift | queued, and memory-model.md leans yes |
| a transform closure | Rust replace_with, Synchronized<T>.update | already in the language |
So the answer needed here is not a new idea; it is the third mechanism
reaching Confined<T>, with Rust's signature rather than the one proposed
above — fn (&var T) -> T keeps the payload in the cell, which is why
replace_with has no hole to re-enter.
Where the prior art would clash:
- Guards are rejected for a good reason that does not extend to closures. A guard's lifetime spans statements, and a yield inside it is invisible. A transform's critical section is syntactically total. That distinction is this document's own argument for the closure form, and it survives.
- Swift's
weakwould collide with the realtime rule, which nobody has noted.weakneeds a side table and must zero every weak reference at deallocation.@abi(.C, realtime)already forbids a refcount decrement reaching zero, because deallocation takes a lock.Weak<T>makes release strictly more expensive — a lock plus a walk of N weak refs — in a language whose sharpest probe is an audio callback. unowned's niche is already covered.examples/PlayheadFINDING 5 is shippedunowned(unsafe)used to dodge refcount traffic on the audio thread, andOpaque<Cell<T>>plus no-retain plus release ordering is the designed replacement. IfWeak<T>ever lands it needs nounownedsibling.==with no===becomes a cost rather than a convergence. All three have reference identity (Rc::ptr_eq,===, pointer==) and all three need it for graph work — visited sets, dedup, cycle detection. AWeak<T>that upgrades but cannot be compared for identity is a strange object.- elp is the only one of the four where a leak is invisible to the
program. Rust has
Drop, Swiftdeinit, GoAddCleanup; all three can assert "this was released" and so all three have a leak testing story. That is what makes their tolerance of leaked cycles survivable, and it is why "A leak has no observable symptom", below, is not a minor note. - The arena is a vindication, not a limitation. What elp's rules force is what a Rust programmer reaches for voluntarily.
Copy-on-write, and whether invisibility can be paid for with a diagnostic
Swift's CoW is the obvious answer to the Duplicate row of the table above,
and the objection to it is that .copy() is explicit here so that the cost
is visible at the call site — CoW makes the explicit call O(1) and moves the
cost to an invisible write. The question is whether that invisibility can be
bought back with a diagnostic instead. Mostly yes, with three refinements and
one hard limit.
1. CoW should be a property of three stdlib types, not of the Duplicate
tier. If .copy() on a Duplicate user type became lazy, the conformance
would be making a claim about when that it cannot keep. Swift does not do
that either — CoW lives in the stdlib collections, not in a protocol. Scoped
to [T], Map and string, the conformance system does not move at all and
explicit-.copy()-shows-the-cost stays true everywhere a user wrote the type.
2. The diagnostic should be gated on the type's computed cost, not on
runtime sharedness. Whether a refcount is 1 is a runtime property, so a
lint claiming "this will copy" cannot be honest. A lint gated on layout can
be: "a copy-on-write of Document may copy 2.4 MB." The machinery already
exists — Atomic<T>'s requirement is enforced with a use-site diagnostic
naming the computed size ("Transport is 12 bytes"), and it is the same
layout pass. This is that diagnostic one tier softer, an error becoming a
named lint, which diagnostics.md's noisy-by-default-and-filtered model is
built for. The honest claim is if this copies it will hurt, which is the
useful one.
Worth noting which of the expensive shapes actually is expensive. Large and contiguous is the bad case. Recursive is the good case — a CoW tree copies one node per write, which is path-copying, i.e. a persistent data structure, and is the reason anyone wants CoW in the first place.
3. One place a lint is not enough, and it is already handled. A CoW write
is a conditional allocation, invisible at the write site and dependent on
a runtime refcount. @abi(.C, realtime) forbids allocation outright, and
diagnostics.md keeps the soundness floor non-configurable — so this cannot
be a lint there, it has to be an error. It does not need a new rule:
memory-model.md deliberately keeps Buffer<T> out of the collections, the
realtime path uses Buffer<int16> rather than [int16], and so a CoW type
never reaches a realtime body. A decision made about storage identity turns
out to be what keeps latent allocation off the audio thread.
And CoW does not replace .update — it complements it. In the cell
idiom, c.set(c.get().copy().insert(…)), the original is still in the cell
during the .copy(), so the refcount is at least two and it copies anyway.
CoW makes collections cheap to pass and assign; it does nothing for mutating
a cell's payload. .update is the load-bearing fix, and CoW is what makes it
cheap everywhere else. Granted both, examples/Buffer stops duplicating
every line per keystroke; granted only CoW, it does not.
Two amendments from examples/Editor, which priced this. First, the lint
above could not be computed: it needs a size, Line holds a string, and
string's tier was unstated. That is now answered — string is Copy
and immutable, so it is not in CoW's domain at all and it contributes a
pointer to the size calculation rather than a buffer. The blocker is gone and
what is left is smaller than it looked: the lint still needs the layout pass
to expose "this Copy type's copy is a memcpy", which is the same gate
@abi(.C, realtime) and Atomic<T> want.
Second, and it narrows the proposal: CoW is not the answer to the
Duplicate row for a value that is deliberately snapshotted. An undo
snapshot is O(1) and shares the buffer — and the next edit then finds the
buffer shared with the history entry and copies it. Snapshot per keystroke,
copy per keystroke; the cost moved one statement right. What fixes that is a
persistent structure whose edit copies only a root-to-leaf path, which is a
rope, which is a recursive value type — so an undo stack needs
examples/QuadTree's GAP 1, now ratified as indirect, whose immutable
box is precisely what path-copying wants. CoW remains worth having for
passing, assigning and reading, where
tree-places.elp FINDING 5 shows it is what keeps a read-only descent
non-quadratic.
One convergence worth flagging. A CoW lint that wants to be more precise
than layout has to ask "can this value be aliased from anywhere else" — which
is a reachability analysis. So is the pure/.alias() fork above. So is
Shared<T> being Copy for any T. Three separate questions now want one
notion of reachability, and the language has none.
A leak has no observable symptom
Worth stating because it bounds every answer above. There are no
destructors, so "was this released?" is not a question a program can ask or
a test can assert. Move giving at-most-once release and never
at-least-once is recorded for FFI handles; the same property holds for a
cycle of elp cells and had not been written down. Leak detection is
undesigned, and that is a tooling question rather than a language one — but
it is the reason the cycle above is worth catching by reading rather than at
runtime.
Three conformances, and only one rule
Copy, Duplicate, Move. There is no Shared interface — see
"What this corrects".
| duplication | independence | examples | |
|---|---|---|---|
Copy | implicit | independent | primitives, string, Cursor, Money, Point, JobId, Value, Shared<T> for any T, a type with an indirect field |
Duplicate | explicit, via .copy() | independent, possibly deep | [T], Row, Sheet, Protected<T> |
Move | exclusive transfer — the source is dead | everything else that opts in, Confined<T>, Synchronized<T> |
Duplicate is the row the first draft missed, and the corpus had been
using it all along:
posts.copy().prepend(post) // SocialFeed/screens/home.velp
state.messages.copy().append(...) // ChatRoom/main.velp
Corrected — neither line ever type-checked, and they were this document's
evidence. collections.md declares fn Array.append(&var self, value T)
returning unit, so .copy().append(x) is not a value and cannot be
assigned. The corpus scan found it (core-language-probes.md §16) and both
sites are now transforms, which are cheaper anyway.
The tier is unaffected — .copy() is still explicit duplication of
something not implicitly Copy, and that is still what Duplicate means.
What is gone is the claim that the corpus had been using it all along,
which is weaker evidence than it read as: what the corpus had been doing was
writing something that did not compile, in two files, quoted in two
documents.
.copy() is explicit duplication of something that is not implicitly
Copy — otherwise nobody would have to call it. It is Rust's Clone.
Separating it from the aliasing types is where elp ends up better
placed than Rust rather than catching up: Rust puts Arc<T> and
Vec<T> in the same trait, so "this type is Clone" tells you nothing
about whether duplicating it aliased. Not retrofittable there, free
here.
.copy() and .alias() are two words on purpose
A mutable handle is Move, not Duplicate, and a second handle
comes from .alias().
The first draft of this document put Confined<T> and
Synchronized<T> in Duplicate and was caught while migrating
examples/Buffer: Duplicate promises independence, and
Confined.copy() would hand back something that aliases. That is the
original Copy bug one tier down — one word, two guarantees, and no
site at which to see which you got.
So the words do not overlap anywhere in the language:
| means | duplicates alias? | |
|---|---|---|
.copy() | Duplicate — a second, independent value | never |
.alias() | a second handle to the same referent | always |
.copy() never aliases and .alias() always does, so neither call site
needs its receiver's type checked to be read correctly. That is worth
one extra method name.
It also means a type wrapping a handle hand-writes its own .alias(),
which is exactly the honest duplication the design wants — the sharing
is stated at the one site that has to think about it:
export fn Buffer.alias(&self) -> Self {
return Self { lines = self.lines.alias(), path = self.path }
}
Shared<T> needs none of this. It is Copy, so a second handle is a
plain assignment — which reflects the reality that immutable sharing is
free and mutable sharing costs you a word.
string is Copy, and immutability is the whole argument
Open since examples/SqliteBinding asked whether Connection { handle, path string } was Copy-eligible, and bigger than it looked: a record of
strings is most of the corpus, so the answer decides the tier of most types
anyone will write.
Decided: string is Copy. It is not a judgement call, because
strings.md already made it — "string is an immutable sequence of
Unicode scalar values". The third tier question in this file resolves
against the same sentence the other two did: an immutable alias is
observationally identical to a copy, so there is no second value to make,
and a copy is a pointer copy and a retain.
The alternative is not merely worse, it is incoherent. Duplicate promises
an independent value, and independence from a value nobody can write is
not a property — .copy() on a string would be a method whose return is
indistinguishable from its receiver by any program. A tier whose guarantee
is unobservable is not a tier.
Four consequences, and the third is the one nobody expects:
- A record of strings is
Copy.Connection'spathwas never the blocker; itshandleis. stringleaves the copy-on-write question entirely. The CoW assessment above is about the cost of duplicating before a write, and there is no write. CoW stays a property of exactly two stdlib types,[T]andMap, which also unblocksexamples/EditorFINDING 1 — that probe could not compute the CoW lint because this tier was unstated, and the answer is thatstringis not in its domain.- Concatenation is not a copy, and that is where the cost went.
a + ballocates and walks both operands, O(n), because the result is a new immutable value. Sostringhas a cheap implicit copy and an expensive explicit build, which is the right way round and is exactly where a program loops without noticing. That is a lint, not an error, and it belongs with the CoW lint rather than here. - A
stringmay be borrowed in a realtime body but not copied into one or dropped there, because the retain's matching release can reach zero and call the allocator. Same rule asShared<T>. See below.
Copy does not mean trivially copyable, and there are now three of them
Worth stating once, because it has been derived separately three times and the third time it should stop being a surprise.
| type | what a copy is | why it is Copy |
|---|---|---|
Shared<T> | pointer copy + retain | the referent is immutable |
string | pointer copy + retain | the value is immutable |
a type with an indirect field | pointer copy + retain | the box is immutable (memory-model.md) |
Weak<C> | pointer copy + weak retain | it grants no access until upgrade |
Copy means implicit and independent, and immutability buys
independence without buying a deep copy. It does not mean a memcpy, and no
decision in this file ever said it did — but the word invites the reading,
and a Point is the example everyone has in mind.
The one place the distinction is load-bearing is @abi(.C, realtime),
which forbids a refcount decrement reaching zero. Under it, these three are
borrowable and not copyable, while a Point is both. So the realtime rule
cannot be phrased as "only Copy types"; it is only Copy types whose
copy is a memcpy, which is a property the layout pass computes and the
type system does not currently name. That is the same gate
examples/Editor's CoW lint needs and Atomic<T>'s eight-byte diagnostic
already has, which makes three customers for one piece of machinery.
The rule: Copy is field-wise
A type is Copy only if every field is Copy. That is the whole
mechanism. There is no propagation rule, no contagion rule, and nothing
to derive.
Because Confined<T> and Synchronized<T> are Move and not Copy,
any type holding one is not Copy either, transitively, all the way up.
examples/Sheet has four levels of it — Style → Cell → Row →
Sheet — and no rule says so four times. One rule applies four times.
Five precisions, because each one catches somebody:
An indirect field is read through to its type. The marker is a layout
instruction, not a type (memory-model.md), so field-wise sees the field's
declared type and nothing else: indirect left Expr is Copy exactly when
Expr is. It is only sound because that file ratified the box as
immutable — a mutable box would be Confined-shaped and would have to
block Copy like any other cell. This is the same argument that makes
Shared<T> Copy for any T, arriving a second time from a different
direction, which is some evidence it is the right argument.
A field may not hold a borrow. &T is unconditionally Copy
(memory-model.md Finding 6), which is harmless inside a call and not
harmless in a field: the field outlives the call and is freely copyable,
so a &T field is a duplication route field-wise approves of without
looking at T at all.
A borrow is bounded by the call that receives it; a field is not, and
there is nothing to bound it against. examples/SqliteBinding had the only
two & fields in the corpus and both were the bug, so the rule costs
nothing today and keeps Finding 6 unconditional rather than caveated.
It blocks only the implicit tier. A type holding a Confined field
is not Copy; it can still be Duplicate. Explicit duplication is fine
because it is explicit — .copy() on a spreadsheet Cell sharing the
style and copying the value is a decision somebody wrote down. What is
refused is silent duplication, not duplication.
A field's const/var marker does not change it. Eligibility comes
from the field's type:
export object Cell {
var value Value,
const style Style, // const field, still not Copy
}
const says you cannot rebind this field. The Confined inside
Style says you can write through it. Two independent axes — which is
what Sheet/types/style.elp already notes: "&self, not &var self:
the object is unchanged, the cell it points at is not."
Closures are field-wise too, so they need no separate treatment.
functions.md already says a closure is Sendable iff every capture is;
it is Copy iff every capture is, by the same reading. Two closures over
one Confined handle therefore need two aliases:
const a = self.lines.alias()
const b = self.lines.alias() // two handles, one cell
Which is examples/Undo's GAP 3 with an answer rather than a gap, and
the .alias() calls are where the sharing gets written down.
Protected<T> — secrecy, and it needs no privilege at all
This document said only what Protected<T> is not: "a compiler-enforced
access restriction, not duplication semantics, and the tables above should
not be read as including it." That was four documents' worth of use resting
on a sentence about what it isn't, and open-questions.md listed it as one
of three load-bearing things with no design.
Its one corpus use is examples/ChatRoom's login form, which holds
var password Protected<string> and passes it to a submit callback typed
fn(string, Protected<string>). The threat is ordinary and the corpus is
the right shape for it: a password that must not end up in a log, a crash
report, a URL, a cache key or an analytics payload.
The finding: it is plain elp
name-resolution.md calls it "compiler-enforced secrecy, not a library
wrapper", and that turns out to be wrong in the useful direction. Go
through what a secret has to survive, and every one is closed by a
conformance that is simply absent:
| leak | what stops it |
|---|---|
log(password), "{password}" | no conformance that renders a value, and no toString method |
encode(credentials) | no Codec/To conformance, so a @CodeGen derive over a record containing one fails at compile time |
map.set(password, …) | no Hashable |
if password == guess | no Equatable — .constantTimeEquals(&Self) -> bool is the method, and it is better anyway |
| silent duplication | not Copy |
None of that needs a compiler. aliasing.md's own rule is that Copy is
declared, with field-wise eligibility as a necessary condition rather
than a sufficient one, so a type that never declares it never gets it. The
rest is a small method surface and a short conformance list.
So Protected<T> is bucket 3 in stdlib-boundary.md's terms: ordinary
elp, writable by anyone, competing with nothing. That is the second time
this session a thing assumed to need privilege did not — indirect was the
first — and it is the file's rule working twice.
The surface
export object Protected<T> {
const value T,
}
fn Protected<T>.of(value T) -> Self
fn Protected<T>.expose(&self) -> &T
fn Protected<T>.constantTimeEquals(&self, other &Self) -> bool
Duplicate, neverCopy, conditional onTbeingCopyorDuplicate. This is.copy()/.alias()'s argument applied to secrecy: "what is refused is silent duplication, not duplication." Every additional copy of a secret is a decision somebody wrote down.SendablewhenTis, andMovewhenTis. Field-wise, no new rule..expose()is the only way out, and it is named to be greppable. Rust'ssecrecycrate reached the same conclusion withexpose_secret(). One name, one audit.expose_protectedis a lint, allow by default, so a package that must never expose can set it todenyin its manifest — which is exactly the configurabilitydiagnostics.mdwas designed for, used for the first time by something real.
What it does not promise
- No zeroing on drop. It is
Duplicate, so copies exist and zeroing one proves nothing; elp has no destructor, andreleaseis called by a block while a secret in a reactive cell is not. A type that genuinely wanted zeroing would beMoveplusScoped, which is a different type with a worse API, and no corpus program has asked for it. - Nothing about a debugger, a core dump or the allocator. Those are outside any language-level mechanism and saying so is better than implying otherwise.
Two dependencies, one of them undocumented
It stays in the prelude, for a different reason than recorded.
name-resolution.md's criterion is "a type is atmospheric if the compiler
can name it in a diagnostic without your help", and the row's stated reason
— compiler-enforced secrecy — is now false. It passes anyway: the compiler
names it in the conformance error it produces for every row of the leak
table. The outcome survives; the justification is replaced.
And the first row of that table rests on something no document states.
The corpus interpolates primitives directly ("task-{i}") and calls
.toString() explicitly for everything else ("{e.toString()}",
"{row.total.toString()}"), consistently, across every file. If
interpolation ever accepts an arbitrary value through a conformance, a
Protected<T> must not satisfy it. Recorded here because this type is the
first thing whose correctness depends on that rule, and strings.md does
not state it.
Sendable, and the premise under conditional conformance
Shared<T: Sendable> implements Sendable
Synchronized<T: Sendable> implements Sendable
Confined<T> declares no such line, for any T, and that is the whole
enforcement — exactly how reactivity.md already handles reactive cells
and Binding<T>: "a reactive cell fails to conform by simply never
declaring it." No bound to propagate, no trait chain to read backwards.
Field-wise conformance then does the propagation for free. Style holds
a Confined → Cell holds a Style → Row → Sheet: none are
Sendable, and the error lands on the capture the developer wrote:
sheetcannot cross intobackground—Sheetholds aConfined<Style>, which is confined to one thread. UseSynchronized<Style>, or send the values it needs and write the result back.
Why Confined<T> is not Sendable when T is
The obvious rule — Confined<T: Sendable> implements Sendable — is
unsound, and the counter-example is one line:
const hits = Confined.new(0)
background(fn {
hits.set(hits.get() + 1) // thread B
})
hits.set(hits.get() + 1) // cell thread
int is as Sendable as a type gets. Both sides hold the same cell,
both read-modify-write, and the update is lost. T: Sendable
constrains what is in the box; the race is the box. The bound checks
the wrong noun.
The premise, stated once so it stops being invisible
Channel<T: Sendable> implements Sendable (generics.md) is sound
because a channel is internally synchronized — its own operations
handle concurrent access, so the contents really are the only open
question. That is a hidden premise in the form, and it is why Channel
looked like a precedent for Confined when it is not one.
Every legal use of the form satisfies the premise for a stated reason:
| why it may conditionally conform | |
|---|---|
Shared<T> | immutable — there are no writers to order |
Synchronized<T> | internally synchronized — the lock is in the type |
Channel<T> | internally synchronized |
Confined<T> | nothing — so it does not conform |
This premise is currently unguarded in the language. Nothing stops a
library author writing MyCache<T: Sendable> implements Sendable over an
unsynchronized cache. That is interfaces.md's problem rather than this
document's, and it is recorded as open there.
Fields spell const or var
memory-model.md originally said const is not accepted on a field
— "two spellings for the default is one more than the language needs."
The corpus writes const on 72 fields and bare on none, so the rule was
both unimplemented and unloved.
Resolved the other way, and more strictly: a field spells const or
var, exactly like a local, and bare is an error. The old rule gave
two spellings for immutable and one for mutable; matching locals gives
one each, costs zero migration, and means a reader never has to decide
whether a missing word meant immutable or meant the author forgot.
| declaration | outside the type |
|---|---|
const field T | not visible |
var field T | not visible |
export const field T | read |
export var field T | read and write — &obj.field is legal |
This replaces the table in memory-model.md, "Fields carry var".
FFI is the one place duplication semantics are declared by hand
unsafe exists in elp only at a boundary to a native shared library
— C, C++, Objective-C — and nowhere else. It is not a general escape
hatch and there is no safe-Rust-style unsafe block for ordinary code.
That decision is what makes everything above inferable. Mutable aliasing
is obtainable only from Confined<T>, Synchronized<T>, a closure that
captured one, or a borrow of a type whose mutators elp cannot see —
and the first three are what field-wise conformance already sees. A user
type cannot invent interior mutability, so the compiler never has to ask.
The fourth is FFI's, and it is worth stating exactly, because an earlier
draft of this document claimed the compiler simply could not see an
external handle's semantics. It sees them; it gets them wrong. &T is
Copy because T's only mutators are elp code honouring the borrow, so
two holders of a &T have nothing to observe about each other. An
@external type's mutators are in C: sqlite3_close(db &Sqlite3)
destroys the pointee through a read-only borrow. The rule that makes
&T free is the rule FFI breaks.
Three parts, and no new vocabulary
1. A field may not hold a borrow — the precision above, which is the general form of the problem rather than an FFI special case.
2. A foreign handle is a value, not a borrow — whatever the library's
own ownership story is. There is no owned Sqlite3 anywhere in the
program for a borrow to borrow from: SQLite owns the pointee and elp
owns the pointer. So the field is handle Sqlite3, and &Sqlite3 has no
referent in elp's model. Borrows stay legal at a parameter, where the
call bounds them.
This holds for the handles elp never releases too, which is the larger class — see "Three kinds of foreign pointer" below. What varies between them is the tier, not whether they are values.
3. An @external type must declare its tier, and silence is an
error. An external type has no fields, so field-wise is vacuously
satisfied and the derivation's answer is Copy — the dangerous one for a
sqlite3*. But no default in the other direction works either: Move
would mis-describe a time_t, a C enum, a POD struct, and most of
Vulkan. The tiers genuinely differ per handle, which is the whole argument
for making the declaration mandatory rather than picking a side.
@external(.C, library = "sqlite3") {
export type Sqlite3
export type Sqlite3Stmt
}
Sqlite3 implements Move
Sqlite3Stmt implements Move
And then nothing above it needs extending. Connection holds a
Move field, so field-wise forces Connection implements Move — a
conclusion, exactly as Style implements Move is a conclusion from
holding a Confined<StyleValues>. One type at the boundary whose
semantics the compiler is told, everything above it derived, which is
the same shape stdlib already uses.
That is also what makes it legitimate rather than a hole. stdlib declares
Confined<T> implements Move and the compiler trusts it; @external is
the one place a user gets the same privilege. Not an exception to the
rules — the same trust, scoped to the marked surface.
The three questions, answered by conformances that exist
| answer | |
|---|---|
| is duplicating the handle independent, aliasing, or illegal? | the conformance: Copy, Duplicate, Move already mean exactly those three |
| may it cross a thread? | Sendable, declared rather than derived |
| who releases it, and is exactly-once guaranteed? | open — but not for the reason first given; see below |
So two of the three need no new syntax, which retires a strawman
examples/SqliteBinding was carrying:
@external(.C, library = "sqlite3", duplication = .aliasing, threads = .confined)
That invented .aliasing/.independent/.illegal for precisely what
Move/Copy/Duplicate say. A parallel vocabulary for a distinction the
language already draws is worth deleting rather than designing.
The thread question is answered in form and still blocked in fact:
SQLite's discipline is a runtime value (sqlite3_threadsafe()) against a
static conformance, which no part of this language covers.
Three kinds of foreign pointer, and only one is a handle you release
sqlite3* is the easy case and generalising from it alone would be a
mistake. GLFW and Vulkan hand back pointers to resources they own and
never expect back, and they are the common shape rather than the exotic
one:
| you release it? | tier | examples | |
|---|---|---|---|
| owned handle | yes, exactly once | Move | sqlite3*, sqlite3_stmt*, GLFWwindow*, VkInstance, VkDevice |
| borrowed handle | no — it dies with its parent | Copy | VkQueue, VkPhysicalDevice, GLFWmonitor* |
| transient view | no — invalidated by the next call | none — it is a borrow, not a value | const char* from sqlite3_column_text, const GLFWvidmode*, float *out in an audio callback |
The first two are both handled by rule 3 with no further machinery, and
they land on different tiers — which is the clearest evidence that a
mandatory declaration beats a default. Move is right for a VkDevice
because you call vkDestroyDevice once; Copy is right for a VkQueue
because you never destroy it, duplicating it is free, and two copies of it
have nothing to observe about each other that matters.
The third row is answered, and not by a tier. It was recorded as
having no tier that fits, and the reason is that it is not a value at all:
a transient pointer is a borrow, so it may not be a field, may not be
captured, and dies with the call. memory-model.md settles that under
Buffer<T>, where the forcing case is a foreign callback's float *out
parameter. Two things then need no declaration: such a view is never
Sendable, because it cannot be captured and so cannot cross; and it
cannot outlive the call that delivered it, because borrows already cannot
escape.
What the second row does not get is validity. A VkQueue is valid
only while its VkDevice lives, and nothing in the tier says so.
Copy/Duplicate/Move answer may I duplicate this, and how?; they do
not answer is this still alive?. Those are orthogonal, and elp has a
mechanism for the first and none for the second.
That gap was already recorded from Statement/Connection, and Vulkan
makes it much worse than one pair suggested: its handles form a strict
ownership tree — instance → physical device → device → queue, buffer,
image → view — and every edge is a constraint elp cannot express. Rust
cannot either without a hand-written lifetime, and ash declines to,
making its handle types Copy and leaving use-after-free to the
programmer. So the honest statement is that elp's binding would be exactly
as unsound as Rust's here, and the tier is not the thing that fixes it.
Two things the table does not capture, both from
examples/VulkanTriangle.
A borrowed handle may be Copy and not Sendable. A VkQueue is a
pointer you never release, so Copy is right; Vulkan queues are not
thread-safe, so it must not cross into background. Everywhere else in
the corpus a Copy type is trivially Sendable because it is plain data,
and this is the first type that needs to decline — legal, since the two
are unrelated conformances, and worth stating because the pairing has
always been free until now.
And a field can outlive a sibling field. Renderer holds a Move
VkDevice and a Copy VkQueue that points into it, so the object
cannot be duplicated while that field can be read out and copied anywhere.
Field-wise Copy protects the aggregate, not the members — which is
correct for Confined<T>, because reading a handle out keeps the cell
alive, and wrong for a foreign handle, which keeps nothing alive. That
difference is the whole reason the validity gap is FFI's and not the
language's.
The third row is the one nothing covers. A transient view is not a
handle: its validity is measured in calls, not in the lifetime of a
parent. No tier can express "you may read this and may not keep it",
because Move still permits storing. What every real binding does instead
is copy at the boundary and never expose the pointer — which is what
Statement.textAt returning Optional<string> does — and that is a
discipline at the wrapper rather than a guarantee from the language. It is
also why the @external declarations belong in internal/.
The mechanism already exists and is not a keyword. @external(.OBJC)
is in the corpus (BlogStyle/internal/api.elp) and the parser already
accepts body-less declarations for it; name-resolution.md adds links
on @Package as the allow-list bounding what it may reach. There is no
unsafe marker and no extern keyword, because @external is the
marker and reactivity.md rejects new lowercase intrinsic keywords as a
matter of policy. examples/SqliteBinding is the probe.
And @external carries no duplication arguments at all, which is
where the three parts above land. A macro receives the AST of what follows
it, and that may be a block of declarations (macros.md), so one
@external(...) header covers a library's handles — but what each handle
means is an ordinary conformance written under the block, not an
argument inside it. The attribute says where the symbol comes from; the
conformance says how the value behaves. Those were conflated in the first
draft and they are different questions.
A C callback runs on a thread elp never created
A library that calls into elp — an audio driver, a sort comparator, a
sqlite3_exec row handler — raises a question the three aliasing types were
not written for: whose thread is this? Confined<T> is confined to one
logical thread, and on the client targets that thread is the platform UI
thread. An audio thread is categorically not it, and elp never saw the
thread created.
A foreign callback body is checked exactly as a background body is.
Everything it reaches must be Sendable, Confined<T> is refused, and a
value elp also reads must be Synchronized<T>. No new rule, and the
diagnostic already exists — examples/Pipeline/main.elp writes it out.
Two constraints then fall out rather than being imposed:
- A foreign callback is a top-level
fn, never a closure. A C function pointer carries no environment, so there is nowhere for a capture to live. State arrives through thevoid*parameter and nowhere else, which isOpaque<Cell<T>>inmemory-model.md's table. - A value that drives UI must hop. The callback writes a
Synchronized<T>; the cell thread reads it and writes theBinding<T>.Binding<T>is tied to the cell thread, so the hop is mandatory and the language should say so rather than let it look like an optimisation.
Thread safety for storage, in one rule
C and elp never touch one extent concurrently, because the only way C gets an extent is for elp to give it up.
Buffer<T> is Sendable when T: Sendable, and it is safe for precisely the
reason Confined<T> is not. The premise above — T: Sendable constrains
what is in the box; the race is the box — does not apply, because
Buffer<T> is not a box: it is Move, so there is exactly one holder and
no alias to race through.
There is deliberately no Shared<Buffer<T>> and no aliasing form for
storage. Two elp threads that need one extent use
Synchronized<Buffer<T>>, access goes through the lock, and C cannot
participate in that at all — which is the honest statement, not a
limitation worked around.
Two residuals a callback cannot discharge
Both are irreducible rather than gaps, and both are discharged by the
Scoped registration pattern rather than by the type system:
- The type claim. elp cannot verify that the
void*C returns is the one it was given.Opaque<T>is a claim, and C may hand back anything. - The retention window. elp cannot see that C kept the pointer past the call that delivered it. A borrow's rules cannot express it, because the escape happens in C.
This is the same posture already taken above, where a tier answers may I
duplicate this and says nothing about is this still alive. Any language
accepting C callbacks has exactly these two; Rust spells them unsafe and
documents them.
What this corrects
Four drafts were rejected on the way here, and each was killed by corpus rather than by argument. Recorded because the reasoning is the load-bearing part.
1. "Copy is two things, and the second one is Shared" — a fourth
conformance named Shared. Rejected: once the aliasing lives in
Shared<T>/Confined<T>/Synchronized<T>, field-wise Copy does
everything the conformance did, and a user cannot construct aliasing
without one of those types (see FFI, above, for the exception). The
conformance was only ever needed because there was no type to put the
semantics in.
2. "Shared is not contagious" — a dedicated rule saying a type with
a Shared field is not implicitly duplicable, plus a @Duplicate derive
to make it bearable. Rejected: that is field-wise Copy restated as a
special case. "Non-contagion" and "poisoning" both named a consequence as
if it were a mechanism, which is why the next question was how to
mitigate it.
The observation behind the derive survives and is still wanted.
examples/Sheet forces four duplication functions and three of them
contain no decision at all — they map a collection and forward. That is
boilerplate, and boilerplate is how a safety rule gets worked around. A
@Duplicate derive generating field-wise duplication is the fix, and it
is honest precisely because each field's type declares which it is.
3. "A field's type may not hide a mutable alias" — proposed so a
reader of const style Style could tell that writes through it are
visible to others. Rejected while migrating examples/Buffer: it cannot
be stated without forbidding abstraction. Buffer holds a
Confined<[string]>, so View { const buffer Buffer } would be illegal,
and so would every type that wraps a shared resource — which is most of
what a library is for.
What answers the objection instead is field-wise Copy itself. Because
Buffer is not Copy, View is not Copy, so duplicating a View must
be written by hand — and that is where the sharing gets stated, at the
one site that has to think about it. The declaration site stays silent;
the duplication site cannot. All five of examples/Buffer's findings
close on this alone, with Style.setBold surviving as a method, which
proposal 3 would have killed.
4. Confined<T>/Synchronized<T> as Duplicate — so that one
.copy() covered both independent duplication and a second handle.
Rejected while migrating examples/Buffer, because Duplicate promises
independence and a Confined.copy() would hand back something that
aliases. That is the original Copy conflation one tier down, and it
would have been worse there: Copy at least had no call site to inspect,
while .copy() would have had one that looked identical in both cases.
.alias() is the fix — see "two words on purpose", above.
Open
- What
.get()returns, and how long it lives. It returns&T— anything else would move the referent out of the cell and leave every other holder pointing at nothing, andexamples/Pipelinehit that on the first type it wrote. The shape is already legal (memory-model.mdFinding 5 allows borrow-returns) and already assumed (examples/Bufferwritesself.lines.get().copy().insert(...), which reads correctly under&T). Undecided is the lifetime: a&Tout of aConfined<T>is invalidated by any.set()on the same cell, andoperators.md's amendment says any call may yield, so the "a call ends the turn" reasoning that governs narrowing has to govern this too. It currently does not. A cell's write surface, andBoth ratified, and they were one decision:Weak<T>, are one decision.update(fn (&var T) -> R) -> Rmakes the handle-per-node graph constructible, which is what makesWeak<T>necessary rather than optional. The sub-question — whether.alias()counts as a side-effectful call — turned out not to be a fork at all (examples/InterpreterFINDING 8), sopureis not on the transform. What is left open is not in this bullet's shape: alet reccycle leaks and nothing in the language detects it, which is a documented limit rather than an undecided question.Decided:string's tier is not stated anywhere.Copy, by the same immutability argument asShared<T>— see "stringisCopy, and immutability is the whole argument", above. What it leaves behind is a smaller, sharper item: the layout pass needs to expose "thisCopytype's copy is a memcpy", which@abi(.C, realtime), the CoW lint andAtomic<T>all want and none of them can currently ask for.- Exactly-once release for a foreign handle.
Movegives at most once and never at least once, so a dropped handle leaks with nothing to notice. The premise has been corrected: this item used to rest on elp having "no destructors, nodefer, nothing at scope exit", and it has three scope-exit constructs — and is now down to one,defer(reactivity.md), sincewith ... as x { }was deleted andScopedis a marker rather than a mechanism (memory-model.md). It does not close the item, because all three are at-most-once-if-you-write-it, which is whatMovealready gives. What the correction changes is the shape of the question: it is not "elp needs a scope-exit mechanism", it is "elp has three and none of them is mandatory", and whether a fourth should be or one of the three should become so. The candidates are aDrop-shaped interface, a scopedwith ... as x { }form, or lint-only. Narrowed from the old "what arguments@externalcarries", the rest of which is now answered by ordinary conformances. Worse, SQLite's thread discipline is a runtime value (sqlite3_threadsafe()) whileConfined/Synchronizedis a static distinction — a capability that is real but not statically known, which nothing in this language covers.examples/SqliteBindingputs the cases on the page; none are decided. - Does
Confined<T>unify with a reactive cell? A componentvarlowers to a cell,Binding<T>is a handle to one, andConfined<T>is a handle to one — three names for what may be one mechanism. If aConfined<T>read inside a component body subscribed like a cell, the reactive system and library sharing would be the same thing. Attractive and unproven. - How deep is
.copy()? Conditional conformance gives the rule ([T]isDuplicatewhenTisCopyorDuplicate), but whether a nested structure duplicates at every level or one needs stating. One case is now answered: anindirectfield copies the pointer and stops, becausememory-model.mdratified the box as immutable and an immutable alias is observationally identical to a copy — the same argument that makesShared<T>Copyfor anyT. That is the whole of the recursive case, which was the hard one. - Can a type be
CopyandDuplicateboth? It should not need to be, and overlapping tiers should be a diagnostic rather than a silent precedence rule. It is still not a peer — it is an access restriction rather than duplication semantics — but it is designed now, above, and the "compiler-enforced" half of the old sentence was wrong: it is ordinary elp, and its secrecy is a short conformance list rather than a compiler rule. It does have a tier,Protected<T>is not a peer of these three.Duplicate, which is the one thing the tables above should include.