Loans as facts: two Mut loans alive at once through branches, loops, lists, fields, listeners and timers; the owner's write while lent #132

Merged
sionzee merged 136 commits from loans-as-facts into main 2026-11-22 17:33:15 +01:00
Owner

Based on field-study (#131), and contains it: the diff shown is this piece alone.

Mut<T> is SAFE-TS's &mut: a parameter declared Mut<T> promises the function that, while it runs, it is the only way to that object. An async function keeps that loan until its promise settles. aliased-mut reported two loans alive at once in three written shapes only (one Promise.all, two statements of one block, .map(async ...)), and stale-across-await leaves a Mut parameter alone on purpose, because "the loan is this call's". So nothing checked the promise the second rule relies on. Given

async function addOne(ledger: Mut<Ledger>): Promise<void> {
  const before = ledger.total;
  await store.flush();
  ledger.total = before + 1;
}

each of these passed tsc strict, safe-ts check --deny-warnings and oxlint, and loses an update at run time:

for (const id of ids) pending.push(addOne(mut(ledger)));  await Promise.all(pending);   // a loop and a list
const p = addOne(mut(ledger));  if (urgent) await p;  await addOne(mut(ledger));        // awaited on one path only
save(): void { this.#saving = addOne(mut(this.ledger)); }                               // kept in a field; the next call overlaps
socket.on("message", async () => { await addOne(mut(ledger)); });                       // the next message overlaps
setInterval(() => { void addOne(mut(state.ledger)); }, 1000);                           // the next tick overlaps
const q = addOne(mut(ledger));  ledger.total = 0;  await q;                             // the owner writes while it is lent

What this adds

A loan is a fact on the control-flow layer. It starts where mut(x) is handed to a call and ends where that call's promise is awaited: directly, through Promise.all and its siblings (over it, or over the list, Set or Map it was put into), through a for...of that awaits each, through the local or field it was kept in. aliased-mut now reports, on some path:

  • x, a part of it, or what holds it, lent again or written by its owner while a loan is alive: a branch that does not await, the loan of the round before in a loop, a promise dropped with void or handed to another call, a map callback (whoever collects the list);
  • runs of the same code that overlap: a listener, an interval, a JSX on... prop that lends state it does not own; a method that returns while such a loan is alive;
  • a loan that outlives the function: a function that returns while a call it lent its own parameter to still holds it. One finding there, instead of one at each of its callers.

Only where the callee really holds the loan across a suspension, which the whole-program pass decides: it writes the loan (or a part, or lends it on) after an await, a write of its own answer included (doc.title = await fetchTitle(id): the older answer may land on the newer one), or it cannot be named and returns a promise. A callee done with the object before its first await, or one that never waits, is no hazard however its calls overlap.

Correct code stays silent: one loan at a time (for...of with await); a chained queue (this.tail = this.tail.then(() => f(mut(this.state)))); an in-flight guard (if (this.saving) return this.saving;) or a flag tested and set before the loan; one object per call; the elements of a list lent one by one; a { once: true } listener. Quick fix Await p first where both loans are in one block.

stale-across-await's page and this one now say who guarantees what: the first takes a Mut parameter to be the call's alone, the second reports every call site it sees that would make that untrue.

Evidence

  • Held-out cases, written before the implementation existed: 18 functions that lose an update at run time. The checker before reported 3; now all 18, and all 22 correct forms next to them are silent. A second set asked which callees make an overlap matter, and found the first version too narrow: it counted only read, wait, write back, and so dropped two findings the old checker had (two calls in one Promise.all that each write their own answer after waiting). Fixed; the callees it now leaves out are the ones that cannot interleave.
  • An adopter's project. Its own tree has no loans written yet, and every finding there is unchanged. On a copy migrated with safe-ts migrate mut: 105 async functions take a Mut, 81 of them write it after a suspension, 267 call sites lend to them, and 32 findings are new, each read:
    • 7 real: two runs of a sign-in flow in flight at once (two places); a cache entry dropped by maintenance that runs during a fill; two writers of one index; packets handled while a handshake is still writing the connection.
    • 23 true overlaps that something the checker does not follow makes harmless: a busy flag that disables the buttons, a generation counter that drops the older run, two loans of one large object that touch different parts of it, tests that overlap on purpose.
    • 2 false: a promise awaited through a flag; a .then that touches another field.
  • Soundness corpus: six classes added and closed (a loop and a list, a branch, a field, a listener, a timer, the owner's write). 20 of 98 escape, the same twenty as before.
  • Nothing else moves: every other rule's findings are identical on the three examples, the adopter's own tree and twelve earlier held-out projects.
  • Cost: a graph only where a path can matter: 20 on the adopter's largest entry as it is, 507 on the migrated copy. Per-file analysis there 202 ms before, 213 ms after (minimum of 21 interleaved runs); the whole-program pass is unchanged. A new count in the work guard (loan_holders).

What turns red on upgrade

aliased-mut is an error, so a project that lends with mut(x) gets the findings above as errors: on that copy, 32 in about 760 files, most of them overlaps that are safe for a reason the code does not show. The way out is to show it: await the first call, test a flag before lending, chain the calls, or lend the part instead of the whole (mut(game.cache) and mut(game.scene) do not overlap).

Two findings the old rule gave are gone on purpose: a Promise.all of calls whose callee is done with the object before it first waits, or never waits.

Decided from the numbers

  • The owner's reads while lent are not reported. They added 34 findings on the copy, and every one read was harmless: a read sees the value as it is; it is the write made from it that loses an update. Writes are reported.
  • "Holds" is "writes after a suspension", not "touches on both sides of an await": the wider one added a cluster where a field is read before the await and a packet sent after, with nothing written back.
  • Updates that commute (count += 1 after the await) stay in: 1 finding of 54 candidate sites rested on one alone, not worth a second definition.

What stays unseen

  • Who calls a function: Promise.all([this.save(), this.save()]), where each save() awaits its own loan, overlaps and is not reported.
  • A callback the checker does not know runs again (a framework's ticker); a promise kept in a reassigned let or an object literal, or awaited through a flag or a helper.
  • Which parts of one object two loans touch; generation counters; flags set inside the callee.
  • State written without a loan: the corpus class out-of-order-responses still escapes because its program writes a captured object. Written as a loan, it is reported.
  • Two parameters that are the same object by value, elements reached by index, workers and shared memory.

Created with Claude Opus 5.5 (implementation and the merge) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.

Based on `field-study` (#131), and contains it: the diff shown is this piece alone. `Mut<T>` is SAFE-TS's `&mut`: a parameter declared `Mut<T>` promises the function that, while it runs, it is the only way to that object. An async function keeps that loan until its promise settles. `aliased-mut` reported two loans alive at once in three written shapes only (one `Promise.all`, two statements of one block, `.map(async ...)`), and `stale-across-await` leaves a `Mut` parameter alone on purpose, because "the loan is this call's". So nothing checked the promise the second rule relies on. Given ```ts async function addOne(ledger: Mut<Ledger>): Promise<void> { const before = ledger.total; await store.flush(); ledger.total = before + 1; } ``` each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint, and loses an update at run time: ```ts for (const id of ids) pending.push(addOne(mut(ledger))); await Promise.all(pending); // a loop and a list const p = addOne(mut(ledger)); if (urgent) await p; await addOne(mut(ledger)); // awaited on one path only save(): void { this.#saving = addOne(mut(this.ledger)); } // kept in a field; the next call overlaps socket.on("message", async () => { await addOne(mut(ledger)); }); // the next message overlaps setInterval(() => { void addOne(mut(state.ledger)); }, 1000); // the next tick overlaps const q = addOne(mut(ledger)); ledger.total = 0; await q; // the owner writes while it is lent ``` ## What this adds **A loan is a fact on the control-flow layer.** It starts where `mut(x)` is handed to a call and ends where that call's promise is awaited: directly, through `Promise.all` and its siblings (over it, or over the list, `Set` or `Map` it was put into), through a `for...of` that awaits each, through the local or field it was kept in. `aliased-mut` now reports, on some path: - `x`, a part of it, or what holds it, lent again or **written by its owner** while a loan is alive: a branch that does not await, the loan of the round before in a loop, a promise dropped with `void` or handed to another call, a `map` callback (whoever collects the list); - **runs of the same code that overlap**: a listener, an interval, a JSX `on...` prop that lends state it does not own; a method that returns while such a loan is alive; - **a loan that outlives the function**: a function that returns while a call it lent its own parameter to still holds it. One finding there, instead of one at each of its callers. **Only where the callee really holds the loan across a suspension**, which the whole-program pass decides: it writes the loan (or a part, or lends it on) after an `await`, a write of its own answer included (`doc.title = await fetchTitle(id)`: the older answer may land on the newer one), or it cannot be named and returns a promise. A callee done with the object before its first `await`, or one that never waits, is no hazard however its calls overlap. **Correct code stays silent**: one loan at a time (`for...of` with `await`); a chained queue (`this.tail = this.tail.then(() => f(mut(this.state)))`); an in-flight guard (`if (this.saving) return this.saving;`) or a flag tested and set before the loan; one object per call; the elements of a list lent one by one; a `{ once: true }` listener. Quick fix *Await `p` first* where both loans are in one block. `stale-across-await`'s page and this one now say who guarantees what: the first takes a `Mut` parameter to be the call's alone, the second reports every call site it sees that would make that untrue. ## Evidence - **Held-out cases**, written before the implementation existed: 18 functions that lose an update at run time. The checker before reported 3; now all 18, and all 22 correct forms next to them are silent. A second set asked which callees make an overlap matter, and found the first version too narrow: it counted only read, wait, write back, and so dropped two findings the old checker had (two calls in one `Promise.all` that each write their own answer after waiting). Fixed; the callees it now leaves out are the ones that cannot interleave. - **An adopter's project.** Its own tree has no loans written yet, and every finding there is unchanged. On a copy migrated with `safe-ts migrate mut`: 105 async functions take a `Mut`, 81 of them write it after a suspension, 267 call sites lend to them, and **32 findings** are new, each read: - **7 real**: two runs of a sign-in flow in flight at once (two places); a cache entry dropped by maintenance that runs during a fill; two writers of one index; packets handled while a handshake is still writing the connection. - **23 true overlaps that something the checker does not follow makes harmless**: a busy flag that disables the buttons, a generation counter that drops the older run, two loans of one large object that touch different parts of it, tests that overlap on purpose. - **2 false**: a promise awaited through a flag; a `.then` that touches another field. - **Soundness corpus:** six classes added and closed (a loop and a list, a branch, a field, a listener, a timer, the owner's write). 20 of 98 escape, the same twenty as before. - **Nothing else moves**: every other rule's findings are identical on the three examples, the adopter's own tree and twelve earlier held-out projects. - **Cost:** a graph only where a path can matter: 20 on the adopter's largest entry as it is, 507 on the migrated copy. Per-file analysis there 202 ms before, 213 ms after (minimum of 21 interleaved runs); the whole-program pass is unchanged. A new count in the work guard (`loan_holders`). ## What turns red on upgrade `aliased-mut` is an error, so a project that lends with `mut(x)` gets the findings above as errors: on that copy, 32 in about 760 files, most of them overlaps that are safe for a reason the code does not show. The way out is to show it: await the first call, test a flag before lending, chain the calls, or lend the part instead of the whole (`mut(game.cache)` and `mut(game.scene)` do not overlap). Two findings the old rule gave are gone on purpose: a `Promise.all` of calls whose callee is done with the object before it first waits, or never waits. ## Decided from the numbers - **The owner's reads while lent are not reported.** They added 34 findings on the copy, and every one read was harmless: a read sees the value as it is; it is the write made from it that loses an update. Writes are reported. - **"Holds" is "writes after a suspension"**, not "touches on both sides of an `await`": the wider one added a cluster where a field is read before the `await` and a packet sent after, with nothing written back. - **Updates that commute** (`count += 1` after the `await`) stay in: 1 finding of 54 candidate sites rested on one alone, not worth a second definition. ## What stays unseen - Who calls a function: `Promise.all([this.save(), this.save()])`, where each `save()` awaits its own loan, overlaps and is not reported. - A callback the checker does not know runs again (a framework's ticker); a promise kept in a reassigned `let` or an object literal, or awaited through a flag or a helper. - Which parts of one object two loans touch; generation counters; flags set inside the callee. - State written without a loan: the corpus class `out-of-order-responses` still escapes because its program writes a captured object. Written as a loan, it is reported. - Two parameters that are the same object by value, elements reached by index, workers and shared memory. Created with Claude Opus 5.5 (implementation and the merge) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Open: `stale-across-await` takes a `Mut` parameter to be the call's alone, but `aliased-mut`
saw two loans alive at once in three written shapes only (one `Promise.all`, a `const` promise
and a second loan in the same block, `.map(async ...)`). A loop that pushes the promises into a
list, a promise awaited on one branch, a promise kept in a field by a method, a listener or an
interval lending state it doesn't own, and the owner writing the object while it is lent all
passed both rules and lost an update at run time.

Closes it with loans carried as facts on the flow layer (`lent.rs`): a `mut(x)` handed to a
call is alive until its promise is awaited (directly, through `Promise.all` over it or the list,
`Set` or `Map` it went into, a `for...of` that awaits each, the local or field it was kept in).
Reported on some path: `x` lent again or written by its owner while a loan of it is alive; runs
that overlap (a callback that runs again, a method or function that returns with the loan
alive); and a function that returns while its own parameter's loan is still held. The
whole-program pass keeps a finding only where the callee holds the loan across an `await` as
`stale-across-await` means it (`stale_await::stale_through`, the parameter taken as shared;
loans lent on, by reachability over the program's loans, memoised per function and parameter,
counted as `loan_holders` in tests/work.rs), or can't be named and its result is shown to be a
promise. The same-block case is now this analysis; `Promise.all` and `.map(async ...)` findings
go through the same callee question. One finding per alive loan names the lines of the others.
Quick fix *Await `p` first*, with its entry in tests/meaning.rs.

Taking turns stays silent: an awaited loop, a chain extended by each call
(`this.tail = this.tail.then(...)`), a guard clause testing where the promise is kept or a flag
set before the loan, each call its own object, elements of a list lent one by one. The owner's
reads aren't reported (measured: they doubled an adopter's findings, none lost an update).

Soundness corpus: six new classes (loop and list, branch, field, listener, timer, the owner's
write), each escaping at the starting commit, are rejected; escaping.txt is unchanged. Fixture
loans_over_time has every shape and its silent twin. Docs: aliased-mut and stale-across-await
pages tell one story; flow guide table and costs; README, CHANGELOG, migration skill, oxlint
message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open (review of 9cb98ca1): "holds" was stale-across-await's read-await-write, so a callee that
writes its own answer after waiting (`doc.title = await fetchTitle(id)`) held nothing, and two of
its calls at once (in one `Promise.all`, a kept promise, a listener) were silent; the starting
binary reported the first two. And `const jobs = ids.map(() => apply(mut(doc)))` was reported
only when `Promise.all` collected the list, though every call starts inside the `map`.

Closes it: a callee holds the loan when it writes it (or a part, or lends it on) after a
suspension on some path (`lent::writes_after`, one fact on the flow layer: suspended since the
start), itself or in an `async` callback that captures it; stale-across-await keeps its own
definition and `stale_await.rs` is back to the base unchanged. A `map` / `forEach` / `flatMap`
callback that returns (or starts with `void`) a call holding a loan of a place it doesn't own is
reported whoever collects the list. A finding needs the first loan's callee to return a promise
(a synchronous function whose callee keeps the loan is reported once, where it lets the loan
outlive the call), and so does the second's in the second-holds case. A graph is skipped where
no path can matter (no loop, nothing else lends or writes the object, nothing awaits the loan).

Fixture: the retitle, map-then-for-of and commuting (`total += 1`) shapes reported; a callee done
before its first `await` and one that never awaits, which the starting binary reported, silent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts, each two additions side by side, both kept: `work.rs` (this branch's `loan_holders`
next to `outside_files_parsed`), `tests/meaning.rs` (the *Await `p` first* program next to
`unused-private`'s), `docs/guide/flow.md` (`aliased-mut` and `unreachable-code` in the list of
analyses and in what each costs). `tests/work-ceilings.json` regenerated on the merged tree:
`loan_holders` new (1 per run), the others moved only by the loans added to the generated
project (`outside_files_parsed` unchanged).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
aliased-mut pages and docs: the callee writes the loan after an await; void-discards-result keeps its own bug
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m26s
Tests / test (pull_request) Successful in 8m35s
b74822a279
Open: the pages, the CHANGELOG, README and the migration skill still described "holds" as
stale-across-await's read-await-write; and on the merged corpus `aliased-mut` rejected the one
program of `void-discards-result` (its `void reload(mut(panel))` lets the loan outlive
`onReset`), though the class's bug, `void` dropping a `Result`, needs no loan.

Closes it: the docs say what is asked now (a write of the loan after an `await`, a call's own
answer included; a callee done before its first `await`, or that never waits, isn't), with the
measurement behind keeping commuting updates in; `stale-across-await`'s page says a write of the
call's own answer is the call's to make, since the loan is its alone, and `aliased-mut` makes
that true. `void-discards-result` gets a second program without a `Mut`, so the class still
measures its own bug (it escapes; escaping.txt unchanged), and the page names
`out-of-order-responses` (captured state, no loan) as unseen, reported once written with `mut`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from field-study to main 2026-11-22 17:32:24 +01:00
Merge main: the piece below has landed
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
adc7712eb6
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch loans-as-facts 2026-11-22 17:33:15 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!132
No description provided.