A shared control-flow layer; values used after they were consumed; a Result kept in a local #120

Merged
sionzee merged 47 commits from flow-consumed into main 2026-11-21 23:29:42 +01:00
Owner

Based on escape-hatches-2 (#119), and contains it: the diff shown is this piece alone. The open pieces above #118 form one chain, each branch containing the ones below it: #119, #120, #121, #123, then #116 and #122. Merge them in that order.

Combined with the pieces below. analyze_file_with takes both this piece's consumes table and #119's marker permission; nothing else overlapped.

Several rules ask "on some path, did A happen before B?", and each had its own walker with its own idea of branches, loops and early exits: eight of them, listed below. The next bug classes on the roadmap all need that question answered properly. These passed tsc strict, safe-ts check --deny-warnings and oxlint, and are wrong at run time:

const g = nums();                        // a generator object
for (const n of g) first += n;
for (const n of g) second += n;          // sees nothing: second is 0

worker.postMessage({ pixels }, [pixels.buffer]);
return pixels.length;                    // 0: the buffer went to the worker

const text = await res.text();
await res.text();                        // TypeError: body stream already read

const r = save(order);                   // Result<void, SaveError>
console.log(r);                          // logging is not looking: the failure is gone

What this adds

A shared control-flow layer (flow.rs). One graph per function, built only when an analysis asks: if / ?: / && / || / ?? (branching straight to their targets inside a test), optional chains, every loop with its back edge, switch fall-through, labelled break / continue, return, throw, and try / catch / finally with the finally copied for each way out. await and yield end their block, so the analyses that come next can ask what happens across them. On top, one forward data-flow driver for "on some path" and "on every path". oxc's own graph was measured and not used: it is built eagerly for every function (+21 to 26% on semantic analysis), marks statements only, and does not mark await.

number-parse-nan moved onto it, with identical findings on an adopter's project. Three cases the old source-order walker got wrong are now right: a check in the other branch no longer covers a use, a use on the next round of a loop is after the parse, and let n = Number(s); n = 0; is no longer reported.

New rule use-after-consume (error). A value that an operation uses up, used again on a path where the operation ran: a transferred ArrayBuffer (also through a view's .buffer, and a second name for the same object), a generator or one-shot iterator run twice, a Response / Request body read twice, a stream with two readers, and use after close() on sockets, ports, workers, file handles and readline. Which operations consume is data, a consumes section in the ECMAScript map and in each pack's manifest, so a third-party pack can declare its own; every entry is demonstrated on Node, and the worker ones in Chromium, Firefox and WebKit.

must-use-result sees a Result kept in a local and never looked at on some path to the function's end: also behind ?: / ?? / await, and each element of const [a, b] = await Promise.all([...]). Logging and string conversion are not looking; returning it, storing it, handing it on or capturing it is.

Evidence

  • Paths. I ran 25 shapes with known answers through the layer (labelled break out of two loops, do...while, a loop's update clause, continue inside try / finally, default in the middle of a switch, an exception path into catch). All are answered correctly. The repository now has its own table of 39 shapes that tests the layer without any rule.
  • No false positives found. Reading res.ok after the body, a fresh response per retry, an array iterator's rest after break, listeners removed after close(), and try / finally around a file handle are all silent.
  • An adopter's project: findings byte-identical before and after. The first version of the kept-Result check reported six places there; four were an early return (a cancellation) before the code that checks the Result, which is deliberate. The rule now counts only a function end that comes after every look.
  • Cost. A graph is built only for a function that has something to ask about: 40 on that project's largest entry, down from 3,119 in the first version. Whole-program pass there: 990 ms before, 1010 ms after.
  • Soundness corpus: one-shot-generator-reused and use-after-consume-arraybuffer are closed; response-body-read-twice and result-kept-only-logged were added and closed. 10 of 33 classes escape.

The walkers that have not moved

Walker Rules What it can't express
search_index.rs not-found-index source order, with a special case for a for update clause
borrow.rs reaches stale-read no loop back edges; any switch counts as "not reached"
holders.rs a promise held in a local its own idea of exits
bounds.rs divide-by-length, sparse-array-write, a[i]! proofs facts only from guards earlier in the same block
shape.rs narrowing truthiness and compare-with-undefined only if (...) exit in the same statement list
lints.rs stable-shape "every path" means top-level statements
vue.rs vue-setup-after-await "after an await" in source order

They move one at a time, as decided. The three analyses planned next (state read before an await and written after it, a resource released on every exit, a new Promise with a path that never settles) are written up in docs/guide/flow.md with what the layer still lacks for each.

What stays unseen

  • An operation inside a callee or a callback: only what the function itself writes counts.
  • A value whose kind is not written: an imported generator function's result, a field, a reassigned let.
  • A kept Result abandoned by an early return before the code that checks it, and one behind const { result } = pair().
  • A project whose installed packs predate this release gets only the language's entries until it upgrades them.
  • A new imprecision in number-parse-nan: if (text !== "" && Number.isNaN(n)) return; leaves the empty-text path unchecked, so it is reported although Number("") is 0.

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

Based on `escape-hatches-2` (#119), and contains it: the diff shown is this piece alone. The open pieces above #118 form one chain, each branch containing the ones below it: #119, #120, #121, #123, then #116 and #122. Merge them in that order. **Combined with the pieces below.** `analyze_file_with` takes both this piece's `consumes` table and #119's marker permission; nothing else overlapped. Several rules ask "on some path, did A happen before B?", and each had its own walker with its own idea of branches, loops and early exits: eight of them, listed below. The next bug classes on the roadmap all need that question answered properly. These passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint, and are wrong at run time: ```ts const g = nums(); // a generator object for (const n of g) first += n; for (const n of g) second += n; // sees nothing: second is 0 worker.postMessage({ pixels }, [pixels.buffer]); return pixels.length; // 0: the buffer went to the worker const text = await res.text(); await res.text(); // TypeError: body stream already read const r = save(order); // Result<void, SaveError> console.log(r); // logging is not looking: the failure is gone ``` ## What this adds **A shared control-flow layer** (`flow.rs`). One graph per function, built only when an analysis asks: `if` / `?:` / `&&` / `||` / `??` (branching straight to their targets inside a test), optional chains, every loop with its back edge, `switch` fall-through, labelled `break` / `continue`, `return`, `throw`, and `try` / `catch` / `finally` with the `finally` copied for each way out. `await` and `yield` end their block, so the analyses that come next can ask what happens across them. On top, one forward data-flow driver for "on some path" and "on every path". oxc's own graph was measured and not used: it is built eagerly for every function (+21 to 26% on semantic analysis), marks statements only, and does not mark `await`. **`number-parse-nan` moved onto it**, with identical findings on an adopter's project. Three cases the old source-order walker got wrong are now right: a check in the other branch no longer covers a use, a use on the next round of a loop is after the parse, and `let n = Number(s); n = 0;` is no longer reported. **New rule `use-after-consume`** (error). A value that an operation uses up, used again on a path where the operation ran: a transferred `ArrayBuffer` (also through a view's `.buffer`, and a second name for the same object), a generator or one-shot iterator run twice, a `Response` / `Request` body read twice, a stream with two readers, and use after `close()` on sockets, ports, workers, file handles and `readline`. Which operations consume is data, a `consumes` section in the ECMAScript map and in each pack's manifest, so a third-party pack can declare its own; every entry is demonstrated on Node, and the worker ones in Chromium, Firefox and WebKit. **`must-use-result` sees a `Result` kept in a local** and never looked at on some path to the function's end: also behind `?:` / `??` / `await`, and each element of `const [a, b] = await Promise.all([...])`. Logging and string conversion are not looking; returning it, storing it, handing it on or capturing it is. ## Evidence - **Paths.** I ran 25 shapes with known answers through the layer (labelled `break` out of two loops, `do...while`, a loop's update clause, `continue` inside `try` / `finally`, `default` in the middle of a `switch`, an exception path into `catch`). All are answered correctly. The repository now has its own table of 39 shapes that tests the layer without any rule. - **No false positives found.** Reading `res.ok` after the body, a fresh response per retry, an array iterator's rest after `break`, listeners removed after `close()`, and `try` / `finally` around a file handle are all silent. - **An adopter's project:** findings byte-identical before and after. The first version of the kept-`Result` check reported six places there; four were an early `return` (a cancellation) before the code that checks the `Result`, which is deliberate. The rule now counts only a function end that comes after every look. - **Cost.** A graph is built only for a function that has something to ask about: 40 on that project's largest entry, down from 3,119 in the first version. Whole-program pass there: 990 ms before, 1010 ms after. - **Soundness corpus:** `one-shot-generator-reused` and `use-after-consume-arraybuffer` are closed; `response-body-read-twice` and `result-kept-only-logged` were added and closed. 10 of 33 classes escape. ## The walkers that have not moved | Walker | Rules | What it can't express | |---|---|---| | `search_index.rs` | `not-found-index` | source order, with a special case for a `for` update clause | | `borrow.rs` `reaches` | `stale-read` | no loop back edges; any `switch` counts as "not reached" | | `holders.rs` | a promise held in a local | its own idea of exits | | `bounds.rs` | `divide-by-length`, `sparse-array-write`, `a[i]!` proofs | facts only from guards earlier in the same block | | `shape.rs` narrowing | truthiness and compare-with-undefined | only `if (...) exit` in the same statement list | | `lints.rs` | `stable-shape` | "every path" means top-level statements | | `vue.rs` | `vue-setup-after-await` | "after an `await`" in source order | They move one at a time, as decided. The three analyses planned next (state read before an `await` and written after it, a resource released on every exit, a `new Promise` with a path that never settles) are written up in `docs/guide/flow.md` with what the layer still lacks for each. ## What stays unseen - An operation inside a callee or a callback: only what the function itself writes counts. - A value whose kind is not written: an imported generator function's result, a field, a reassigned `let`. - A kept `Result` abandoned by an early `return` before the code that checks it, and one behind `const { result } = pair()`. - A project whose installed packs predate this release gets only the language's entries until it upgrades them. - A new imprecision in `number-parse-nan`: `if (text !== "" && Number.isNaN(n)) return;` leaves the empty-text path unchecked, so it is reported although `Number("")` is `0`. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Open: each rule that asks "did A happen before B on some path" had its own walker with
its own idea of branches, loops and exits (number-parse-nan and not-found-index took source
order, stale-read an ancestor walk, holders and bounds their own exits).

Closes the first step: flow.rs builds a graph per function body on request (if, ?:, &&/||/??
as jumping code, optional chains, loops with back edges, switch fall-through, labelled
break/continue, return/throw, try/catch/finally with a finally copy per way out; nested
functions are one point; await/yield end their block) and a bitset forward data-flow driver
(Meet::Any / Meet::Every, replay). number-parse-nan decides "used before a check" on it:
identical on the adopter; three fixture cases the source-order walk got wrong (a check in the
other branch, a use on the next loop round, a new value assigned).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: a value used again after an operation used it up passed every gate (a generator or an
array's iterator iterated twice, an ArrayBuffer used after transfer() or a transfer list, a
Response body read twice, a locked stream, a closed WebSocket, MessagePort, FileHandle or
readline interface), and must-use-result only saw a Result dropped as a statement, not one kept
in a local and only logged.

Closes:
- use-after-consume (an error, on by default), on the flow layer: a fact per operation site,
  set where it runs, cleared by a new value or releaseLock(); a second solve on every path
  words "on one path". Which operations consume, what state they leave and which uses fail is
  data: a `consumes` section in ecmascript-api.json, browser-api.json and node-api.json
  (compiled in; a platform's findings kept where its pack is on), demonstrated on Node
  (ecmascript/consumes.test.ts, packages/feature-*/test/consumes.test.ts) and, for Worker and
  the global postMessage, in Chromium, Firefox and WebKit (test:browsers). The packs' safe
  versions count as the member they stand for. A view made on a buffer before the transfer
  reads the detached buffer (reported); one made after throws where it is made.
- must-use-result: a call kept in a local (kept.rs) that, on some path to an end after the
  last code that looks at it, nothing looks at, or that a new value replaces first; the
  whole-program pass reports the ones whose function returns a Result. Logging and string
  conversion aren't looking; handing it on, storing it, capturing it, returning it are. An
  exception and an early return before the look aren't drops; a short-circuit test of several
  counts for each.
- Soundness corpus: one-shot-generator-reused and use-after-consume-arraybuffer come off
  escaping.txt; new classes response-body-read-twice and result-kept-only-logged (both escape
  at the starting commit, both rejected now).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: the new rule, the kept-Result part of must-use-result, the consumes format and the paths
number-parse-nan now follows were undocumented, and two pages said number-parse-nan takes source
order.

Closes: docs/rules/use-after-consume.md (idiomatic forms first, what it can't see),
must-use-result's "A Result kept in a local", docs/guide/flow.md, the `consumes` format in the
libraries guide (and a pointer from the built-ins guide), number-parse-nan's and
not-found-index's pages, README (rules table, known gaps), docs index and sidebar, the errors
guide, CHANGELOG (Added: the rule and the flow layer; Changed: must-use-result and
number-parse-nan, with what to write instead), and the migration skill's patterns and tool gaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: npm run typecheck failed on packages/pack-kit/consumes.ts (a DOM-only type name, and a
check TypeScript took for always true). Closes: a structural type for the read result, and the
demonstration typed as possibly missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open (review): a buffer transferred through its view (`[pixels.buffer]`, `pixels.buffer.transfer()`)
left the views unreported; `maybe?.transfer()` wasn't seen; `const same = buf` was a stranger;
and the browser and Node `consumes` were compiled into the checker, so a third-party pack (or a
project's own) couldn't declare one, and a pack's version could disagree with the checker's.

Closes:
- A pack's `consumes` is read from its safe-ts.json with the rest of the pack (Manifest::consumes;
  the browser and Node packs copy theirs from their API maps when safe-ts.json is generated, and
  the manifest tests keep the two equal). Only the language's map stays compiled in. A pack's
  safe versions come from its manifest's `safe` refs. What a pack gets wrong (an entry described
  differently from an earlier pack, an operation on a state nobody describes, a section that
  isn't one) is a setup warning and that entry is left out (consumed::for_packs, unit tests).
  Fixture consume_pack: a tiny third-party pack with a one-shot cursor.
- Groups (Cx::group): a second name (`const same = buf`, neither reassigned) is the same value;
  a typed array or DataView is a view on a buffer (the one it was made on, `x.buffer`, or its
  own); `x.buffer` in a transfer list or `x.buffer.transfer()` uses up every view of the group.
  `x.buffer.detached` is asking, not using. A reassigned `let`, a property or a destructuring
  isn't followed.
- The flow layer keyed points by span alone, so a call inside an optional chain shared its key
  with the chain (`a?.b()`), and an expression statement without `;` with its expression: points
  are keyed by span and kind now (flow::PointKey). That is what hid `maybe?.transfer()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kept Results beyond a bare call; the cheap test before any graph; the layer's path table
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m57s
Tests / test (pull_request) Successful in 8m6s
9a540ef57e
Open (review): `const r = flag ? save(1) : save(2)` and `const [a, b] = await Promise.all([...])`
weren't seen as kept Results; the kept-Result analysis built a graph for one function in five on
the adopter's largest entry (2,561 of ~10,500) and use-after-consume for 539, mostly for calls
that can't matter; and the layer was held only by ten unit tests and the rules' fixtures.

Closes:
- Kept: each call of a `?:` / `??` / `||` / `&&` / parenthesised / awaited initialiser, and each
  element of an array destructuring of `Promise.all` / `allSettled` over a list written in
  place, in the binding at its place (fixtures). `const { result } = pair()` isn't (only
  `pair`'s return type says what `result` is).
- The cheap test first. Kept Results: the local pass only lists the kept calls (no graph),
  after two syntactic tests (a const looked at unconditionally by the very next statement; a
  call whose callee the file shows returns a plain type, or a method of a value declared with
  one); the whole-program pass keeps those whose function returns a Result and only then
  parses the file again and builds graphs for them (`unsafe(...)` / `parseJson` stay local).
  use-after-consume: a function gets a graph only if an operation there would use a binding
  up (`Array.from(list)` of an array doesn't); the generator walk runs only in a file with a
  `function*`. On the adopter's `apps/client/src/start.ts`: 3,119 graphs before (2,561 kept,
  539 consumed, 19 number-parse-nan), 40 after (21, 0, 19).
- flow::tests::path_cases: 39 shapes with their answers on some / every path, independent of
  any rule (labelled break and continue, do...while, a loop's update clause, for await,
  continue in try/finally, finally after a return, nested finally, switch with default in the
  middle and falling into it, && / || in a statement and a test, ?:, ??, ||=, optional calls,
  yield and await between, reset, an exception into catch, nested functions, unreachable code).
- Docs: the libraries guide says a pack's `consumes` is read from its safe-ts.json (and the
  manifest example shows it); use-after-consume's page covers views, second names and optional
  calls; must-use-result's covers branches and Promise.all; README gaps, CHANGELOG, tool gaps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open: each of these passed tsc strict, `safe-ts check --idiomatic --deny-warnings`
and oxlint with the preset, and none was counted or ratcheted.

- `// @safe-ts std` / `// @safe-ts legacy`: one comment turned every rule off for a file (and
  `std` made its functions count as never failing for callers), and nothing said who may write
  it. Now a marker counts only in files the nearest "safe-ts" package.json lists under
  "trustedFiles" / "legacyFiles" (patterns as in "overrides", relative to it). Anywhere else it
  is an `unlisted-marker` error at the marker and the file is checked, transformed and followed
  as if it weren't there: check, the editor, the oxlint plugin, the Vite plugin and the loader
  all go through `Project::markers_allowed` (part of the analysis cache key). Library code in
  node_modules keeps its markers. `safe-ts check` prints, per package.json, the lines that list
  every marked file it found. The repository's packages, the demo, the fixtures and the docs
  examples list theirs.
- `eslint-disable*` / `oxlint-disable*` comments were counted nowhere, and silenced the oxlint
  plugin. Now all are counted; a blanket one or one naming a `safe-ts/` rule is reported by the
  new `no-lint-suppression`, on the directive's name inside the comment, where oxlint's own
  directive ranges don't reach (measured: a block directive applies from its comment's end, a
  `-line` one to the code before the comment). A named rule of another linter is only counted.
- `declare const | let | var | function | class | enum | namespace`, `declare global`,
  `declare module "..."` and the project's own .d.ts files were casts with no `as`. Now they
  are counted, the CLI checks the .d.ts files under the entries' directories (as the editor and
  oxlint already did), and the new `no-unchecked-declare` reports what asserts a value nothing
  checks (a type other than `unknown` or one admitting `undefined`, functions, classes, enums,
  required members added to a built-in or in a package augmentation, values added to a project
  module, `declare module "x";` with no body).
- `defineSanitizer(...)` was not counted; now it is, also through `export *` and renamed
  re-exports in project modules (and so are re-exported `trust()` and `panic()`).

The three counts are in the summary line, `--json --summary` and the baseline, and a test holds
the three together. An old baseline without the new keys loads; a missing count is 0, so the
gate fails once with a note until it is written again.

Soundness corpus: four new classes (unlisted std marker, unlisted legacy marker, a declared
value, a member declared on Array) that escaped before and are rejected now; the corpus project
lists no marker files.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open after 25d3ef37, and what closes it:

- A hatch was counted only when called by its imported name: `r.trust(x)`, `const t = trust;
  t(x)`, `(0, trust)(x)`, `trust.call(...)`, `r.unsafe(...)`, `stop = panic` counted nothing, so
  `export const forged = r.trust<T>("no")` passed the baseline uncounted. Now one pass over the
  semantic references of every binding that may hold one (named and namespace imports,
  destructuring, dynamic `import()`, prelude names; hatch_refs.rs) classifies each use: a call,
  `.call` / `.apply` / `.bind`, a copy followed to its own uses (an exported copy counts once),
  and any other use counted (handed on, re-exported, a std namespace used whole: fail closed).
  Types (`typeof trust`) don't count. The whole program decides which imports are hatches,
  through re-exports, and counts `export { x as y } from` of one.
- With std or the Vue package linked into a workspace, `defineSanitizer` counted 0: the
  resolver calls those files the project's. Now the package.json that owns the defining file
  says what it is, and a SAFE-TS package's own files aren't counted as uses.
- vue-tsc's `<!-- @vue-ignore -->`, `<!-- @vue-skip -->` and `<!-- @vue-expect-error -->` were
  neither reported nor counted. Now `no-ts-suppression` reports ignore, skip and a reasonless
  expect-error; ignore counts with @ts-ignore, expect-error with @ts-expect-error, skip as the
  new `vueSkips`.
- A disable of an oxlint rule the preset makes an error (`no-eval`, `no-proto`, ...) passed
  silently: those rules are how SAFE-TS bans the constructs. Now one without `-- reason` is
  reported by `no-lint-suppression`. The same at config level: `.oxlintrc.json` next to the
  package.json (JSON with comments) is read, and a config not extending the preset, a preset
  rule turned off or down in "rules" or "overrides", and "ignorePatterns" are named as weakened
  settings, which the baseline ratchets.
- `declare value: string` in a class was silent while `value!: string` is a cast. Now it is
  reported by `no-unchecked-declare` and counted with the ambient declarations.
- Docs that teach a `declare` form are checked with the rule on (`declares` fence word), and
  say what the rule asks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Weakened lint settings are named by .oxlintrc.json, the file that sets them
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m54s
Tests / test (pull_request) Successful in 7m48s
6577df1a9a
The check listed `oxlint.rules no-eval off (package.json)`: the setting lives in the
`.oxlintrc.json` beside it, and that is where a reader has to look.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Conflicts, all kept from both sides: `analyze_file_with` / `analyze_vue_with` / `analyze`
take both the `consumes` table and the `MarkerPermission`; `Project::analyze_text` passes
both; `FeatureSet` has `consumes` and the marker lists / oxlint weakenings; the rule list,
the sidebar (no-lint-suppression, unlisted-marker and no-unchecked-declare under Ignore
comments, use-after-consume under Correctness), the module list and the CHANGELOG's Added
and Changed entries hold both pieces'. `kept_results` and the hatch-counting functions of
project.rs sit side by side.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ambient declarations test: a neutral member name in the sample
All checks were successful
Benchmarks / bench (pull_request) Successful in 4m9s
Tests / test (pull_request) Successful in 9m13s
6e1cc600bc
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Merge the chain below: a neutral member name in the ambient declarations test
All checks were successful
Benchmarks / bench (pull_request) Successful in 4m19s
Tests / test (pull_request) Successful in 9m56s
259c12be10
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from sentinel-values to escape-hatches-2 2026-11-21 20:38:47 +01:00
sionzee changed target branch from escape-hatches-2 to main 2026-11-21 23:28:33 +01:00
Merge main
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m14s
Tests / test (pull_request) Successful in 8m59s
6f50907135
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch flow-consumed 2026-11-21 23:29:42 +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!120
No description provided.