After an await: a listener added too late, a superseded task that still writes; event rules find their receiver through every written form #133

Merged
sionzee merged 139 commits from after-await into main 2026-11-22 17:33:23 +01:00
Owner

Based on loans-as-facts (#132), and contains it: the diff shown is this piece alone.

The study in #131 found that today's checker is silent on 72% of the bugs a reader could have seen in an adopter's code, and listed the kinds. This closes two of them. Both are one mistake seen from two sides: the world moved on during an await, and the code after it acts as if it had not. Each of these passed tsc strict, safe-ts check --deny-warnings and oxlint:

async function stream(req: IncomingMessage, subscribers: Mut<Set<string>>): Promise<void> {
  subscribers.add(topic);
  await firstPage();
  req.once("close", () => subscribers.delete(topic));   // the client left during the await: never runs
}

async function work(signal: AbortSignal): Promise<void> {
  await prepare();
  signal.addEventListener("abort", cancel);              // aborted during the await: never runs
}

const task = useTask(async (_signal, name: string): Promise<void> => {
  viewer.open = await readFile(name);                    // an older run finishes later and overwrites the newer one's
});

Two rules, both errors

late-listener. Some events happen at most once in an object's life, and a listener added afterwards waits for ever. The rule reports a listener for such an event added to an object the function already had before a suspension on that path (also in a callback that runs later: a timer, another listener, a .then), unless the state that says "it already happened" is tested on the way or right after. ws.onopen = f and the other handler properties count as listeners.

Which events those are is data in the packs (events.once), each with the test that says it has happened (signal.aborted, stream.closed, document.readyState === "complete"): 15 entries for Node (abort; a stream's close / end / finish; a child process's exit / close / spawn; a worker's exit / online; ...), 9 for the browser (abort; a WebSocket's open / close; load, DOMContentLoaded; IndexedDB's request and transaction events). Each entry is demonstrated by a test that makes the event happen, on Node and in Chromium, Firefox and WebKit: it fires once, a listener added afterwards never runs, and the test is false before and true after. Left out, with the reason in the guide: a server's listening and a socket's connect (the object can do it again), a stream's error (Node throws when nothing listens), image and XHR loads (they fire again).

Silent: a listener added before the first await; an object made after it; a state test (if (signal.aborted) return;, throwIfAborted()); an awaited call that was given the object and listens for the same event itself; a signal from a controller the function made and has not handed out.

superseded-task-write. A useTask or latest callback that changes state outliving the run (a captured object, a ref, a Mut it lends) after an await, on a path where its signal was not tested since and was not handed to the awaited call. Returning the value is fine: the task drops a superseded run's answer. unused-task-signal once reported every callback that ignored its signal and was narrowed to those with something to pass it to; this is the case the narrowing lost, as a rule of its own because it is a run-time defect and that one is idiomatic.

The event rules now find their receiver

Reviewing this piece showed a gap in #130: unknown-event knew the class of a listener's receiver only when it was a parameter or local typed with the class. Of ten ways to write a Socket receiver it resolved one. The class now comes from the receiver resolution the call rules use: a loop variable, an element by index, a destructured parameter, a member of a parameter, a # field, a parameter property, a forEach callback's parameter, a Map's entries, byId.get(id)?.on(...), net.Socket through a namespace, and a member of a platform object (controller.signal). All ten forms are reported now, by all three event rules. On an adopter, listener sites with a known class went from 82 to 103 of 254, with no new finding.

Also fixed on the way: unused-task-signal reported any task that calls mut(...), as if mut could take a signal.

Evidence

  • Held-out cases. Listeners: 16 of mine that miss their event are reported (a request, a signal, a socket in a loop, a WebSocket made before the await, a field, a child process, one branch only, a test made before the await instead of after, a destructured parameter, an element taken by index, a timer) and every correct form is silent. The first round reported 10 of those 16 and one false positive (the function's own controller); both causes are fixed. Tasks: five bugs reported (a captured object, a ref, a test before the await only, a second await that takes no signal, a finally that clears the newer run's flag), six correct forms silent.
  • An adopter's project: 2 new findings, both read and both real: an abort listener on a lifetime signal added after an awaited start-up, so stopping during it leaves an observer running; and a request's end listener added inside the response's finish listener. Its two earlier fixes of these kinds are reported before the fix and silent after. Nothing else changes.
  • Code not written for the rule: 1,124 files of two open-source projects (a DOM implementation and an authentication library): no finding from either rule, and every other rule identical to before.
  • Soundness corpus: listener-after-await and superseded-task-applies-late come off the list, each rejected by its rule alone. 18 of 98 escape.
  • Cost: 20 graphs on that project's entries for the listener rule, none for the task rule. The whole-program pass on its largest entry: 521 ms before, 528 ms after (minimum of 25 interleaved runs), from every listener's receiver now being resolved.

What turns red on upgrade

  • Both new rules are errors. Add the listener before the first await, or test the state after it; in a task, return the value, test signal.aborted after the await, or hand the signal to the awaited call.
  • A misspelt event name on a receiver the event rules could not type before is now an unknown-event.

What stays unseen

  • The program's own emitters: the packs describe platform classes, so a project cannot yet say which of its events happen once. Other libraries' sockets (ws) have no event data.
  • An object that arrives already finished (a function called with an aborted signal) and gets its listener at once.
  • A request a platform method returns without a written type (store.put(...)), for handler properties.
  • A task callback passed by name; a write two calls down; a state test made through a local.

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

Based on `loans-as-facts` (#132), and contains it: the diff shown is this piece alone. The study in #131 found that today's checker is silent on 72% of the bugs a reader could have seen in an adopter's code, and listed the kinds. This closes two of them. Both are one mistake seen from two sides: **the world moved on during an `await`, and the code after it acts as if it had not.** Each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint: ```ts async function stream(req: IncomingMessage, subscribers: Mut<Set<string>>): Promise<void> { subscribers.add(topic); await firstPage(); req.once("close", () => subscribers.delete(topic)); // the client left during the await: never runs } async function work(signal: AbortSignal): Promise<void> { await prepare(); signal.addEventListener("abort", cancel); // aborted during the await: never runs } const task = useTask(async (_signal, name: string): Promise<void> => { viewer.open = await readFile(name); // an older run finishes later and overwrites the newer one's }); ``` ## Two rules, both errors **`late-listener`.** Some events happen at most once in an object's life, and a listener added afterwards waits for ever. The rule reports a listener for such an event added to an object the function already had before a suspension on that path (also in a callback that runs later: a timer, another listener, a `.then`), unless the state that says "it already happened" is tested on the way or right after. `ws.onopen = f` and the other handler properties count as listeners. Which events those are is **data in the packs** (`events.once`), each with the test that says it has happened (`signal.aborted`, `stream.closed`, `document.readyState === "complete"`): 15 entries for Node (`abort`; a stream's `close` / `end` / `finish`; a child process's `exit` / `close` / `spawn`; a worker's `exit` / `online`; ...), 9 for the browser (`abort`; a WebSocket's `open` / `close`; `load`, `DOMContentLoaded`; IndexedDB's request and transaction events). Each entry is demonstrated by a test that makes the event happen, on Node and in Chromium, Firefox and WebKit: it fires once, a listener added afterwards never runs, and the test is false before and true after. Left out, with the reason in the guide: a server's `listening` and a socket's `connect` (the object can do it again), a stream's `error` (Node throws when nothing listens), image and XHR loads (they fire again). Silent: a listener added before the first `await`; an object made after it; a state test (`if (signal.aborted) return;`, `throwIfAborted()`); an awaited call that was given the object and listens for the same event itself; a signal from a controller the function made and has not handed out. **`superseded-task-write`.** A `useTask` or `latest` callback that changes state outliving the run (a captured object, a `ref`, a `Mut` it lends) after an `await`, on a path where its signal was not tested since and was not handed to the awaited call. Returning the value is fine: the task drops a superseded run's answer. `unused-task-signal` once reported every callback that ignored its signal and was narrowed to those with something to pass it to; this is the case the narrowing lost, as a rule of its own because it is a run-time defect and that one is idiomatic. ## The event rules now find their receiver Reviewing this piece showed a gap in #130: `unknown-event` knew the class of a listener's receiver only when it was a parameter or local typed with the class. Of ten ways to write a `Socket` receiver it resolved one. The class now comes from the receiver resolution the call rules use: a loop variable, an element by index, a destructured parameter, a member of a parameter, a `#` field, a parameter property, a `forEach` callback's parameter, a `Map`'s entries, `byId.get(id)?.on(...)`, `net.Socket` through a namespace, and a member of a platform object (`controller.signal`). All ten forms are reported now, by all three event rules. On an adopter, listener sites with a known class went from 82 to 103 of 254, with no new finding. Also fixed on the way: `unused-task-signal` reported any task that calls `mut(...)`, as if `mut` could take a signal. ## Evidence - **Held-out cases.** Listeners: 16 of mine that miss their event are reported (a request, a signal, a socket in a loop, a WebSocket made before the `await`, a field, a child process, one branch only, a test made before the `await` instead of after, a destructured parameter, an element taken by index, a timer) and every correct form is silent. The first round reported 10 of those 16 and one false positive (the function's own controller); both causes are fixed. Tasks: five bugs reported (a captured object, a `ref`, a test before the `await` only, a second `await` that takes no signal, a `finally` that clears the newer run's flag), six correct forms silent. - **An adopter's project:** 2 new findings, both read and both real: an `abort` listener on a lifetime signal added after an awaited start-up, so stopping during it leaves an observer running; and a request's `end` listener added inside the response's `finish` listener. Its two earlier fixes of these kinds are reported before the fix and silent after. Nothing else changes. - **Code not written for the rule:** 1,124 files of two open-source projects (a DOM implementation and an authentication library): no finding from either rule, and every other rule identical to before. - **Soundness corpus:** `listener-after-await` and `superseded-task-applies-late` come off the list, each rejected by its rule alone. 18 of 98 escape. - **Cost:** 20 graphs on that project's entries for the listener rule, none for the task rule. The whole-program pass on its largest entry: 521 ms before, 528 ms after (minimum of 25 interleaved runs), from every listener's receiver now being resolved. ## What turns red on upgrade - Both new rules are errors. Add the listener before the first `await`, or test the state after it; in a task, return the value, test `signal.aborted` after the `await`, or hand the signal to the awaited call. - A misspelt event name on a receiver the event rules could not type before is now an `unknown-event`. ## What stays unseen - The program's own emitters: the packs describe platform classes, so a project cannot yet say which of its events happen once. Other libraries' sockets (`ws`) have no event data. - An object that arrives already finished (a function called with an aborted signal) and gets its listener at once. - A request a platform method returns without a written type (`store.put(...)`), for handler properties. - A task callback passed by name; a write two calls down; a state test made through a local. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review, acceptance tests and the merge) in Claude Code.
Two classes of the soundness corpus escaped every gate, both the world moving on during an
`await` while the code after it acts as if it had not:

- `listener-after-await`: a listener for an event that happens once (a socket's `close`, a
  signal's `abort`, a page's `load`) added after an `await`, to an object the function already
  had. If the event came during the `await`, the listener never runs.
- `superseded-task-applies-late`: a `useTask` callback whose calls take no signal (so
  `unused-task-signal`, narrowed, says nothing) changes state after an `await`; an older run
  finishes later and overwrites the newer one's.

`late-listener` (an error) asks the flow layer, at each listener, whether on some path the
function waited while it had the receiver and didn't test it since (a property read in a
condition, the receiver passed to a function in a condition, `throwIfAborted()`), or right
after adding it. An object made after the `await` is new; a callback that runs later counts as
having waited, for what it captured; an `await` of a function given the object that itself
listens for the same event on it watches it. Which events happen once, and the test that says
one already happened, is pack data: `events.once` in the Node and browser packs, each entry made
to happen by test/once.test.ts on Node and test/browsers/once.test.ts in Chromium, Firefox and
WebKit.

`superseded-task-write` (an error) follows a `useTask` / `latest` callback written in place:
a change of state that outlives the run after an `await` not handed the signal, with no test of
the signal since; and a call the run waits for that lends such state to an `async` function
using its `Mut<T>` parameter after an `await` of its own, without the signal (the whole-program
pass reads the callee). Returning the value stays fine: both task packages and `latest` drop a
superseded run's answer.

Both corpus classes come off escaping.txt, each program rejected by the new rule alone. The
listener class's program had a plain EventEmitter (no platform data); it now has a Node stream,
as the bug it was reduced from had, and an AbortSignal variant; both escape the starting commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open after review: the event rules decided a listener's class with their own narrow reading of
the receiver. Of ten ways to write a `Socket` receiver, `unknown-event` knew one (a parameter
declared with the class); `late-listener` inherited that and missed seven held-out bugs.

- The receivers' resolution (`written_ty`) ends a walk at a type the program doesn't declare
  (`Socket` from `node:net`, a global `AbortSignal`) as that written type instead of "unknown";
  no call resolves through it, so the call rules are unchanged. `project/events.rs` names the
  packs' class from it once (`written_class`), and a member of a platform object by the packs'
  `creates` (`AbortController#signal`), for `unknown-event`, `unmatched-event` and
  `late-listener` alike. A destructured parameter of any written type is followed (it was for a
  named one only). On an adopter, listeners with a class: 82 to 103 of 254, no new finding.
- `late-listener`'s file pass reads the same forms: a loop variable is the iterable's item (not
  made here), an expression through members and method calls (`byId.get(id)`) keeps its place,
  a `forEach` / `map` / ... callback's listeners are added where the call is, a test inside an
  optional chain counts on the nullish path too.
- Handler properties (`ws.onopen = f`, `signal.onabort = f`, `request.onsuccess = f`) are
  listeners: recorded apart from the sites `unknown-event` reads.
- A controller made here (`new AbortController()`) and reached by nothing before the listener
  can't have been aborted: not reported.
- `unused-task-signal` no longer reports a task calling std's `mut(...)`: trusted and legacy
  files now get their summary of what their functions take.
- Names that came from the adopter's code are replaced in the docs, the changelog and comments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge origin/loans-as-facts: aliased-mut on the function's paths
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m48s
Tests / test (pull_request) Successful in 6m44s
759633669d
Three conflicts, all two pieces describing themselves in the same place: the CHANGELOG's Changed
list, the README's rules table and the cost section of docs/guide/flow.md. Both kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from loans-as-facts to main 2026-11-22 17:32:25 +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
04d2baa675
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch after-await 2026-11-22 17:33:23 +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!133
No description provided.