State across an await, promises that never settle, resources not released on every way out #127

Merged
sionzee merged 112 commits from flow-analyses into main 2026-11-22 01:53:17 +01:00
Owner

Based on pass-speed (#126), and contains it: the diff shown is this piece alone.

The control-flow layer was built so that three questions could be asked properly. Each of these passed tsc strict, safe-ts check --deny-warnings and oxlint:

async add(id: string) { this.total += await price(id); }     // two concurrent calls: one update is lost

if (this.stopping) return;
await this.drain();
this.stopping = true;                                         // tested before the await, set after it: two callers both pass

return new Promise((resolve) => { if (flag) resolve(1); });   // the other path hangs every caller forever

const handle = await open(path, "r");
const stat = await handle.stat();                             // if this rejects, the handle is never closed
await handle.close();

Three rules

stale-across-await (warning). JavaScript has one thread, so nothing else runs between two suspension points; across one, anything can. The rule reports a write to shared state (a field of this, module state, a local captured by a callback that may run more than once) on a path where the same place was read before the last await and not again, and where either the write is made from that read (a lost update, also a position: this.items[at] = value) or the read was the test of a guard that exits (check, await, act). Fine: reading again after the await, a flag or an in-flight promise set before the first await, a write of the call's own answer ("latest run wins"). A Mut parameter is not shared state: the loan is exclusive while the call runs, and two loans at once are aliased-mut's. Quick fix: Await first.

promise-never-settles (error). On every path through a new Promise executor, resolve or reject is called, or handed to something that will call it (a timer, a listener, a function, a field), or the executor throws. A callback that runs once is asked the same question; a named settle function counts where its name goes. new Promise(() => {}) is taken as written on purpose.

unreleased-resource (warning). Something acquired (a file handle, a stream reader's lock, an object URL, an observer, an interval, a socket) and not released on some way out of the function, including the way out where an await in between rejects. An await is a way out only when the failure rules say the awaited call can fail, so awaiting a function that returns a Result does not count. A value that is returned, stored, passed on or captured by a closure has left the function's hands. What acquires and what releases is data in the packs (acquires), demonstrated on Node and in Chromium, Firefox and WebKit; a third-party pack can declare its own. The fix is try / finally, or using / await using where the value is disposable.

What the layer gained

Exception edges as an option (from every call, or only from await / yield), so an analysis says what can throw; q(...) as an early return that runs the open finally blocks; an identity for member paths (this.a.b); "this callback runs once later, repeatedly, or unknown"; two hooks, at a suspension and at the origin of an exception edge. The existing analyses keep the default model. Each extension has rows in the layer's path table.

Evidence, on an adopter's project

Rule First version After reading every finding Verdicts on what remains
stale-across-await 15 3 2 real: a stopping flag set after the await, so two stop() calls both shut down; a save that can delete a world loaded again in the meantime. 1 harmless: a fake clock in tests
promise-never-settles 3, all wrong 0 the three settled through a named done / finish, which the rule now follows
unreleased-resource 45 5 2 real: when an await rejects, an interval keeps the test runner hanging instead of failing. 3 harmless: awaits of promises the checker cannot look up

The unreleased-resource numbers are from a mirror of that project wired to this branch's packs: its installed packs predate acquires, so on its own install the rule is silent until it upgrades them. Nothing else changes there, and the three example projects are unchanged.

Review

Two defects came out of my held-out cases and are fixed. A handle closed by its own finally inside another try was reported, which is the form the rule's own help recommends: an exception from the inner block reached the outer handler without running the inner finally. And a rejecting call whose receiver the packs cannot settle (stream.getReader().read()) was treated as one that cannot fail; unknown now counts as a possible failure.

Soundness corpus: four classes added and closed (a lost update, check-then-act, a promise that never settles, a resource not released). The harness learned two oracles for them: run() never settling, and resources still held after it returns. 2 of 62 classes escape.

Cost: graphs are built only where there is something to ask: 11, 46 and 5 on that project's largest entry for the three rules. Per-file analysis there: 168 ms before, 170 ms after; the whole-program pass is unchanged.

What stays unseen

  • stale-across-await: who calls a function (one that is only ever awaited in sequence is still reported), local aliases of shared state, a lock class the project wrote itself.
  • promise-never-settles: whoever receives resolve is trusted to call it.
  • unreleased-resource: a resource captured by a closure that never releases it; one reached through a field (this.timer = setInterval(...)); two closes in one finally are reported, because the second is skipped when the first rejects.
  • Loans alive at once in loops and listeners still wait for this analysis to carry loans as facts.

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

Based on `pass-speed` (#126), and contains it: the diff shown is this piece alone. The control-flow layer was built so that three questions could be asked properly. Each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint: ```ts async add(id: string) { this.total += await price(id); } // two concurrent calls: one update is lost if (this.stopping) return; await this.drain(); this.stopping = true; // tested before the await, set after it: two callers both pass return new Promise((resolve) => { if (flag) resolve(1); }); // the other path hangs every caller forever const handle = await open(path, "r"); const stat = await handle.stat(); // if this rejects, the handle is never closed await handle.close(); ``` ## Three rules **`stale-across-await`** (warning). JavaScript has one thread, so nothing else runs between two suspension points; across one, anything can. The rule reports a write to shared state (a field of `this`, module state, a local captured by a callback that may run more than once) on a path where the same place was read before the last `await` and not again, and where either the write is made from that read (a lost update, also a position: `this.items[at] = value`) or the read was the test of a guard that exits (check, await, act). Fine: reading again after the `await`, a flag or an in-flight promise set before the first `await`, a write of the call's own answer ("latest run wins"). A `Mut` parameter is not shared state: the loan is exclusive while the call runs, and two loans at once are `aliased-mut`'s. Quick fix: *Await first*. **`promise-never-settles`** (error). On every path through a `new Promise` executor, `resolve` or `reject` is called, or handed to something that will call it (a timer, a listener, a function, a field), or the executor throws. A callback that runs once is asked the same question; a named settle function counts where its name goes. `new Promise(() => {})` is taken as written on purpose. **`unreleased-resource`** (warning). Something acquired (a file handle, a stream reader's lock, an object URL, an observer, an interval, a socket) and not released on some way out of the function, including the way out where an `await` in between rejects. An `await` is a way out only when the failure rules say the awaited call can fail, so awaiting a function that returns a `Result` does not count. A value that is returned, stored, passed on or captured by a closure has left the function's hands. What acquires and what releases is data in the packs (`acquires`), demonstrated on Node and in Chromium, Firefox and WebKit; a third-party pack can declare its own. The fix is `try` / `finally`, or `using` / `await using` where the value is disposable. ## What the layer gained Exception edges as an option (from every call, or only from `await` / `yield`), so an analysis says what can throw; `q(...)` as an early return that runs the open `finally` blocks; an identity for member paths (`this.a.b`); "this callback runs once later, repeatedly, or unknown"; two hooks, at a suspension and at the origin of an exception edge. The existing analyses keep the default model. Each extension has rows in the layer's path table. ## Evidence, on an adopter's project | Rule | First version | After reading every finding | Verdicts on what remains | |---|---|---|---| | `stale-across-await` | 15 | 3 | 2 real: a `stopping` flag set after the `await`, so two `stop()` calls both shut down; a save that can delete a world loaded again in the meantime. 1 harmless: a fake clock in tests | | `promise-never-settles` | 3, all wrong | 0 | the three settled through a named `done` / `finish`, which the rule now follows | | `unreleased-resource` | 45 | 5 | 2 real: when an `await` rejects, an interval keeps the test runner hanging instead of failing. 3 harmless: awaits of promises the checker cannot look up | The `unreleased-resource` numbers are from a mirror of that project wired to this branch's packs: its installed packs predate `acquires`, so on its own install the rule is silent until it upgrades them. Nothing else changes there, and the three example projects are unchanged. ## Review Two defects came out of my held-out cases and are fixed. A handle closed by its own `finally` inside another `try` was reported, which is the form the rule's own help recommends: an exception from the inner block reached the outer handler without running the inner `finally`. And a rejecting call whose receiver the packs cannot settle (`stream.getReader().read()`) was treated as one that cannot fail; unknown now counts as a possible failure. **Soundness corpus:** four classes added and closed (a lost update, check-then-act, a promise that never settles, a resource not released). The harness learned two oracles for them: `run()` never settling, and resources still held after it returns. 2 of 62 classes escape. **Cost:** graphs are built only where there is something to ask: 11, 46 and 5 on that project's largest entry for the three rules. Per-file analysis there: 168 ms before, 170 ms after; the whole-program pass is unchanged. ## What stays unseen - `stale-across-await`: who calls a function (one that is only ever awaited in sequence is still reported), local aliases of shared state, a lock class the project wrote itself. - `promise-never-settles`: whoever receives `resolve` is trusted to call it. - `unreleased-resource`: a resource captured by a closure that never releases it; one reached through a field (`this.timer = setInterval(...)`); two closes in one `finally` are reported, because the second is skipped when the first rejects. - Loans alive at once in loops and listeners still wait for this analysis to carry loans as facts. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Open: the flow layer marked await and yield but nothing read them, had no
identity for member paths, and ended an exception outside a try only at a
throw statement; nothing reported shared state read before an await and
written after it (a lost update, or check-then-act loading twice).

Closes: Options::calls_throw (an edge to thrown after each call, new, await,
yield and tagged template outside a try), Transfer::suspend (run at the end
of each block that suspends), Place (a root and static property names, with
within()), callback_runs (later once / later repeatedly / unknown), each with
rows in the layer's tables. stale-across-await follows reads and writes of
shared places (this in a method, a binding outside the function unless the
function is called in place, a Mut parameter) and reports a write on a path
where the place was read before the last suspension and not since: checked by
a guard clause (check-then-act), or with the written value made from the read
(a lost update). A guard tested and set before the first await holds until it
is written again. borrow_escapes: addOne is the lost-update shape itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: nothing asked whether a new Promise executor settles the promise on
every path; an if without an else, or a catch that only logs, left every
caller awaiting forever, and every gate passed.

Closes: an every-path question on the executor's graph: resolve or reject
called, or handed on (an argument, stored, returned), or a function using
one handed to a call. A callback the layer knows runs once (setTimeout,
.then, once, { once: true }) is asked the same question; one that runs
repeatedly counts when it uses a resolver; an unknown call is trusted. A
path ending in a throw rejects. new Promise(() => {}) is on purpose.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: nothing followed a file handle, an interval, a listening server or an
observer from where a function acquires it to where it ends: an early return
or a rejected await between left it held, and every gate passed.

Closes: an acquires section in the Node and browser maps (what acquires a
resource, what arms it, what releases it, whether it is often meant to live
as long as the program, and the declaration that disposes it), copied into
each pack's safe-ts.json, demonstrated on Node and in Chromium, Firefox and
WebKit (acquires.test.ts), read like consumes and carried in consumed::Table
so it reaches every file. The analysis asks the flow layer with a new builder
option, Options::awaits_throw (a rejection from any await outside a try), and
a new Transfer::throw_from hook (an await of Promise.resolve, a pack's safe
version or unsafeAsync can't reject). A resource leaves the function's hands
when it is returned, stored, handed to a call or captured by a closure.
Quick fix: Release it in a finally.

stale-across-await no longer treats a Mut parameter as shared: the loan is
the callee's alone while the call runs, and two at once are aliased-mut's.
Fixtures: three existing ones keep a handle or a reader they never release;
the meaning harness's project enables the Node pack so a resource is known.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: the corpus had no class for state read before an await and written after
it, for a new Promise that never settles (the runner printed no outcome when
the process ran out of work with run() pending, and the harness called that a
mistake in the corpus), or for a resource still held after run() returns.

Closes: four classes, each escaping every gate at the starting commit and
rejected now: lost-update-across-await (three spellings),
check-then-act-across-await (a cache, a stop flag), promise-never-settles (an
if without else, an early return, a timer settling on one path),
resource-not-released (an interval, a listening server). Two oracles: settles
(the runner reports { pending: true } when the process exits with run()
unsettled) and released (resources held after run() returned that weren't
before, from process.getActiveResourcesInfo(); the runner then exits).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: idiomatic code calls the packs' safe versions and q(...): open from the
Node pack returned a Result the rule didn't know as a file handle, close(handle)
didn't release it, fileHandleStat(handle) read as handing it on, and q's early
return (the transform writes one) wasn't a way out. The three rules had no
pages, and the guides didn't say what the layer now models.

Closes: the packs' safe versions stand for what they wrap (from each
manifest's safe entries), std's isErr(x) on its true edge holds nothing, q(...)
acquires what it unwraps, and Options::q_returns gives q an edge to the exit
through the open finally blocks (opt-in, with rows in the layer's table). Rule
pages, the README's rules, quick fixes and known gaps, the docs index and
sidebar, flow.md (exceptions, callbacks, places, cost), async.md (state across
an await; a promise that settles, a resource released), libraries.md (the
acquires format), quick-fixes.md, CHANGELOG, the migration skill and census.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: setTimeout(() => { if (ok) resolve(); }, ms) was reported, the same
callback declared as function onTimeout() and passed by name was not: the
declaration itself counted as handing resolve on.

Closes: a function of the executor bound to a name is judged at each use of
the name: called now (it must settle on every path), handed to a call that
runs it once (the same), handed on another way (trusted). Fixture rows for
the by-name and arrow forms of all three rules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: an executor that settles through a named function its callbacks call
(const done = (ok) => { clearTimeout(timer); resolve(ok); }, then
setTimeout(() => done(false), ms)) was reported on an adopter three times:
the callbacks use done, not resolve.

Closes: the functions of an executor bound to a name settle for whatever uses
them, asked in turn (taken to settle while asked, so a check that settles or
runs itself again later counts), and passed down to the callbacks inside.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: every await outside a try was taken to reject, so an await of a project
function returning a Result, of one that propagates nothing, or of std's
mapLimit counted as a way out: on an adopter two of the seven findings came
only from those.

Closes: the file's analysis records, per resource, which awaits an exception
that leaves with it held may have started from (a fact per resource and
await, set in Transfer::throw_from). A leak at a return or the end is reported
at once; one only on the way out by an exception from awaited calls goes to
the whole-program pass as a candidate (LocalAnalysis::release_candidates, as
kept Results do), which keeps it when one of the calls can fail (a project
function that propagates, a library member a pack or automatic mode marks as
failing, or a call it can't resolve) and names that one. A throw, a yield or
an await of something it can't look up (a promise in a property) stays a
finding. The SAFE_TS_FLOW_STATS knob is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: const at = this.items.length; await quiet(); this.items[at] = value was
silent: the written value isn't made from the read, the written position is,
and an assignment to a computed member wasn't a write of any place.

Closes: an assignment to object[key] is a write of what the object holds, made
from what the key and the value read; so the position counts like the value.
splice(at, ...) and map.set(keyFromRead, ...) already counted their arguments.
Fixture rows for each, and for a position read after the await and one that
isn't made from the list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: the pages of the older rules the three new ones relate to didn't say
which of the two reports what, and docs/guide/flow.md described what the layer
models but not which options and hooks each analysis uses.

Closes: a sentence on vue-async-race, react-async-race, latest-wins-counter,
stale-read, listener-cleanup, unbounded-poll, pending-without-close and
fetch-signal linking the new page; a table in flow.md of every analysis on the
layer (what a fact is, some or every path, the options and hooks), with the
graphs each builds on an adopter's entries. The pages, README, CHANGELOG and
the skill say what this round changed: an await is a way out only when the
awaited call can fail, and a position computed before an await is stale.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: a handle closed by its own finally inside another try was reported: under
awaits_throw, every point inside a try still had an exception edge, so the
inner finally copy run for an exception (built with the outer try's handler)
left from its first point, the read of the handle, before the close ran, and
the exception reached the outer handler with the handle held. And an awaited
reader.read() was taken as one that can't fail: no pack's creates says what
ReadableStream#getReader hands back, so the receiver's class wasn't settled,
lib_effect gave nothing, and the global module was taken as 'known not to
fail' before the member was found.

Closes: with calls_throw or awaits_throw, the points they name are the only
ones that throw inside a try as well, and the edge for an exception before
anything in the block runs goes too (nothing has run); rows in the layer's
table for nested try / finally, and the row whose answer this corrects. A
method whose receiver class the packs can't settle can fail. Fixture rows:
both nested shapes silent; a rejecting read() reached through a call's
result, a field and a value of a type no pack names, each reported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge the control-flow analyses onto main and the pass's speed work
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m5s
Tests / test (pull_request) Successful in 7m22s
2ca4d9e8ec
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from pass-speed to main 2026-11-22 00:57:13 +01:00
sionzee deleted branch flow-analyses 2026-11-22 01:53:17 +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!127
No description provided.