cycle-init-read, no-foreign-prototype-patch, pending-without-close, unbounded-poll; listener-cleanup: once isn't enough on page-lived targets #98

Merged
sionzee merged 1 commit from load-order-and-lifetime into main 2026-11-20 16:37:23 +01:00
Owner

An adopter's agent audited about 50 old bug fixes in their game (TypeScript, Vue, PixiJS, Node ws). Several of the bugs were about load order and about things that kept the program alive or waiting, and no rule caught them:

  • an import cycle where module initialisation read a binding of the other module (a TDZ ReferenceError at startup, depending on which module was imported first);
  • a { once: true } listener on a matchMedia list whose event never fired, which kept the previous page alive in tests (~150 MB per boot, issue #64). listener-cleanup accepted once;
  • PixiJS prototype patches behind a let installed guard that stacked on every boot;
  • an RPC peer whose pending calls hung forever when the worker port closed;
  • a while (!cond) await tick() loop that hung a test suite.

Solution

Four new rules and one change, each wired end to end (rule list, oxlint plugin and recommended.json, rule page with ✅/❌ examples, README and docs tables, sidebar, CHANGELOG):

  • cycle-init-read (error, whole program). cycles.rs keeps a per-file summary: the imports read at load (top-level code, extends, decorators, computed keys, static fields and blocks, IIFEs and sync callbacks such as map and new Promise), the module-level functions called at load and followed through the module's own calls (an async one up to and including its first await's operand), the bindings that aren't initialised until the module has run, and what each function reads of them. The whole-program pass finds the strongly connected components of the runtime import graph lazily (iterative Tarjan over runtime_imports, so import type doesn't count), follows re-exports to the declaring module, and reports a read whose import sits in the same component. It also reports calling another module's function that reads that module's own uninitialised bindings. The message names the cycle (renderer.ts → islands.ts → renderer.ts). In Vue, <script setup> and the template don't count as load time.
  • no-foreign-prototype-patch (warn). Assignment, compound assignment and delete on a member of X.prototype, plus Object.defineProperty/defineProperties/assign/setPrototypeOf and Reflect.defineProperty/set/deleteProperty, also through a binding (const proto = X.prototype as T), at module level too. X is an import, a member of one, or a global. Own classes: not reported, and documented why: the class is recreated with its module, so a patch doesn't pile up. no-extend-native: oxlint's rule covers only the ECMAScript built-ins written out directly. This rule leaves those direct forms to it and covers imported classes, DOM and other platform classes, and prototypes held in a binding (built-ins included there).
  • pending-without-close (warn). In one unit (a class; else the outermost function; else the module): a collection store (set/push/add/unshift/x[k] =) of a promise executor's resolve/reject, a Promise.withResolvers() result or a binding made from one, together with a message/data listener (on, once, addEventListener, onmessage =, ...), and no close/error/exit/end/disconnect/abort listener anywhere in the unit.
  • unbounded-poll (warn). A while / do / for(;;) whose own body awaits a delay (known names such as sleep and tick, a new Promise starting a timer, Promise.resolve(), or a function of the file that returns a timer promise). It is reported unless an exit test reads one of these: the clock, a clock-derived binding computed inside the loop, a counter, state the loop drives itself (passed to a call, assigned, or a mutating method), or a limit-like name. A signal anywhere in the loop also silences it. assert.fail(...), panic(...) and the like count as exits.
  • listener-cleanup: { once: true } without a signal no longer counts on window, document, globalThis, self, navigator.*, screen, visualViewport, a matchMedia(...) list (direct or bound to a const), or a module-level value (not in Vue <script setup>). This applies to inline handlers in lints.rs, and through a shared helper also to named handlers in Vue components and React effects.

Checked against the adopter's history

I exported trees with git archive and git show into /tmp; their repo wasn't touched. Each rule fires at the parent of the fix commit and is silent at the fix:

Bug Parent Fix
499b09e3 (top-level pixiInit() reads WAR_FOG_COLOR before its first await) pixi-renderer.ts:981 silent there
2d13a8b6 (PIXI_STRIDE const reads clips through a 3+ file cycle) pixi-gore.ts:871, 872 silent there
d8e80f11 (RPC peer over a worker port, no close) rpc.ts:63 silent
126c3e73 / #64 (prototype patches) 7 findings in pixi-batch.ts 1 left: BatcherPipe.prototype.upload is still replaced directly (it no longer stacks, but it is still a foreign patch)
#64 (matchMedia(...) once listener) pixi-renderer.ts:1332 (126c3e73^) — (removed by a test harness change, not in the source)
9b1455db (hung pixi test) tests/pixi.ts:244, 248 still fires: the fix passed the seed differently, but the loops are still unbounded, so these are correct findings

cycle-init-read also finds 13 more load-time reads through cycles at those commits (pixi-sounds.ts reads VILLAGER_WALK the same way pixi-gore.ts did, and archipelago.ts:53 calls svgTemplate(), which reads a const of core.ts, inside a cycle). They are the same hazard.

Precision sweep over the adopter's client and server at HEAD (src + tests): 13 cycle-init-read, 1 no-foreign-prototype-patch (a test stub patching HTMLElement.prototype), 1 unbounded-poll (a test loop with sleep(20) and no deadline), and nothing from pending-without-close or the new once check. The first sweep had 3 unbounded-poll false positives: a loop that advances its own state, a deadline in const left = end - Date.now(), and assert.fail as the exit. All three are fixed, and the fixture covers them. The repo's own examples and std/vue/react sources get no findings from the new rules.

Tests

  • cargo nextest run --workspace: 280 passed (after npm run build; without the built addon safe_ts_cli::emit fails to load it, which is an environment issue)
  • npm run test:std: 367 passed
  • node scripts/docs-typecheck.mjs: 613 documentation examples compile; docs.rs checks the new ✅/❌ blocks
  • npm run docs:build: builds
  • New fixtures: tests/fixtures/import_cycles (direct const, top-level call into an async function, sync callback, namespace member, extends, static field, imported function reading its own const, a 3-file cycle, and silent cases for type-only cycles, function declarations, reads after await and handlers) and tests/fixtures/lifetime (prototype patches incl. alias, defineProperty, delete, module level, own class and built-in; RPC class and closure, withResolvers, close and abort cleanup; poll loops and their bounded forms). Also new once cases in lints, react and vue_sfc.

Left out, and what the rules miss

  • Overlap with no-mutable-global: that rule already reports a package's prototype changed from a function ("Mutates module-level Batcher"), so those lines now get both findings (subscribers fixture updated). I didn't touch no-mutable-global, since another lane owns it. Its "patch once at module load" advice is what this new rule says isn't enough when the module runs again. The two should probably be reconciled there, for example by dropping its finding where no-foreign-prototype-patch reports.
  • cycle-init-read doesn't follow a called function of another module into a third module, functions passed as values, Object.getPrototypeOf-style indirection, dynamic import() or workers (they load later), or cycles through node_modules. It reports load-time reads that work with today's entry order on purpose; the docs explain why. Its examples span files, so the rule page uses unchecked blocks and points to the fixture.
  • pending-without-close doesn't check that the end listener actually settles the pending entries, or that it listens on the same object; any end listener in the unit counts. It misses a store and listener split across classes, callbacks other than promise resolvers (callbacks.set(id, done)), and per-call timeouts. A cleanup method called from elsewhere (as in the adopter's code, where nothing called it) is still reported.
  • unbounded-poll relies on names: delay names, limit names (deadline, max, ...), and any call argument counts as "driving" the state (log(scene)). It misses delays imported under unknown names and timeouts enforced inside the awaited call.
  • no-foreign-prototype-patch misses a prototype passed to a helper that patches it. The adopter's fix uses exactly that shape (pixiPatch(proto, name, make)).
  • listener-cleanup: a page-lived target behind a parameter (target: EventTarget) isn't recognised.

Created with Claude Opus 5.5 in Claude Code.

An adopter's agent audited about 50 old bug fixes in their game (TypeScript, Vue, PixiJS, Node `ws`). Several of the bugs were about load order and about things that kept the program alive or waiting, and no rule caught them: - an import cycle where module initialisation read a binding of the other module (a TDZ `ReferenceError` at startup, depending on which module was imported first); - a `{ once: true }` listener on a `matchMedia` list whose event never fired, which kept the previous page alive in tests (~150 MB per boot, issue #64). `listener-cleanup` accepted `once`; - PixiJS prototype patches behind a `let installed` guard that stacked on every boot; - an RPC peer whose pending calls hung forever when the worker port closed; - a `while (!cond) await tick()` loop that hung a test suite. ## Solution Four new rules and one change, each wired end to end (rule list, oxlint plugin and `recommended.json`, rule page with ✅/❌ examples, README and docs tables, sidebar, CHANGELOG): - **`cycle-init-read`** (error, whole program). `cycles.rs` keeps a per-file summary: the imports read at load (top-level code, `extends`, decorators, computed keys, static fields and blocks, IIFEs and sync callbacks such as `map` and `new Promise`), the module-level functions called at load and followed through the module's own calls (an `async` one up to and including its first `await`'s operand), the bindings that aren't initialised until the module has run, and what each function reads of them. The whole-program pass finds the strongly connected components of the runtime import graph lazily (iterative Tarjan over `runtime_imports`, so `import type` doesn't count), follows re-exports to the declaring module, and reports a read whose import sits in the same component. It also reports calling another module's function that reads that module's own uninitialised bindings. The message names the cycle (`renderer.ts → islands.ts → renderer.ts`). In Vue, `<script setup>` and the template don't count as load time. - **`no-foreign-prototype-patch`** (warn). Assignment, compound assignment and `delete` on a member of `X.prototype`, plus `Object.defineProperty/defineProperties/assign/setPrototypeOf` and `Reflect.defineProperty/set/deleteProperty`, also through a binding (`const proto = X.prototype as T`), at module level too. X is an import, a member of one, or a global. **Own classes**: not reported, and documented why: the class is recreated with its module, so a patch doesn't pile up. **`no-extend-native`**: oxlint's rule covers only the ECMAScript built-ins written out directly. This rule leaves those direct forms to it and covers imported classes, DOM and other platform classes, and prototypes held in a binding (built-ins included there). - **`pending-without-close`** (warn). In one unit (a class; else the outermost function; else the module): a collection store (`set`/`push`/`add`/`unshift`/`x[k] =`) of a promise executor's `resolve`/`reject`, a `Promise.withResolvers()` result or a binding made from one, together with a `message`/`data` listener (`on`, `once`, `addEventListener`, `onmessage =`, ...), and no `close`/`error`/`exit`/`end`/`disconnect`/`abort` listener anywhere in the unit. - **`unbounded-poll`** (warn). A `while` / `do` / `for(;;)` whose own body awaits a delay (known names such as `sleep` and `tick`, a `new Promise` starting a timer, `Promise.resolve()`, or a function of the file that returns a timer promise). It is reported unless an exit test reads one of these: the clock, a clock-derived binding computed inside the loop, a counter, state the loop drives itself (passed to a call, assigned, or a mutating method), or a limit-like name. A `signal` anywhere in the loop also silences it. `assert.fail(...)`, `panic(...)` and the like count as exits. - **`listener-cleanup`**: `{ once: true }` without a `signal` no longer counts on `window`, `document`, `globalThis`, `self`, `navigator.*`, `screen`, `visualViewport`, a `matchMedia(...)` list (direct or bound to a `const`), or a module-level value (not in Vue `<script setup>`). This applies to inline handlers in lints.rs, and through a shared helper also to named handlers in Vue components and React effects. ## Checked against the adopter's history I exported trees with `git archive` and `git show` into `/tmp`; their repo wasn't touched. Each rule fires at the parent of the fix commit and is silent at the fix: | Bug | Parent | Fix | |---|---|---| | `499b09e3` (top-level `pixiInit()` reads `WAR_FOG_COLOR` before its first `await`) | `pixi-renderer.ts:981` | silent there | | `2d13a8b6` (`PIXI_STRIDE` const reads clips through a 3+ file cycle) | `pixi-gore.ts:871, 872` | silent there | | `d8e80f11` (RPC peer over a worker port, no `close`) | `rpc.ts:63` | silent | | `126c3e73` / #64 (prototype patches) | 7 findings in `pixi-batch.ts` | 1 left: `BatcherPipe.prototype.upload` is still replaced directly (it no longer stacks, but it is still a foreign patch) | | #64 (`matchMedia(...)` `once` listener) | `pixi-renderer.ts:1332` (`126c3e73^`) | — (removed by a test harness change, not in the source) | | `9b1455db` (hung pixi test) | `tests/pixi.ts:244, 248` | **still fires**: the fix passed the seed differently, but the loops are still unbounded, so these are correct findings | `cycle-init-read` also finds 13 more load-time reads through cycles at those commits (`pixi-sounds.ts` reads `VILLAGER_WALK` the same way `pixi-gore.ts` did, and `archipelago.ts:53` calls `svgTemplate()`, which reads a `const` of `core.ts`, inside a cycle). They are the same hazard. Precision sweep over the adopter's client and server at HEAD (src + tests): 13 `cycle-init-read`, 1 `no-foreign-prototype-patch` (a test stub patching `HTMLElement.prototype`), 1 `unbounded-poll` (a test loop with `sleep(20)` and no deadline), and nothing from `pending-without-close` or the new `once` check. The first sweep had 3 `unbounded-poll` false positives: a loop that advances its own state, a deadline in `const left = end - Date.now()`, and `assert.fail` as the exit. All three are fixed, and the fixture covers them. The repo's own examples and std/vue/react sources get no findings from the new rules. ## Tests - `cargo nextest run --workspace`: 280 passed (after `npm run build`; without the built addon `safe_ts_cli::emit` fails to load it, which is an environment issue) - `npm run test:std`: 367 passed - `node scripts/docs-typecheck.mjs`: 613 documentation examples compile; `docs.rs` checks the new ✅/❌ blocks - `npm run docs:build`: builds - New fixtures: `tests/fixtures/import_cycles` (direct const, top-level call into an async function, sync callback, namespace member, `extends`, static field, imported function reading its own const, a 3-file cycle, and silent cases for type-only cycles, function declarations, reads after `await` and handlers) and `tests/fixtures/lifetime` (prototype patches incl. alias, `defineProperty`, `delete`, module level, own class and built-in; RPC class and closure, `withResolvers`, `close` and `abort` cleanup; poll loops and their bounded forms). Also new `once` cases in `lints`, `react` and `vue_sfc`. ## Left out, and what the rules miss - **Overlap with `no-mutable-global`**: that rule already reports a package's prototype changed *from a function* ("Mutates module-level `Batcher`"), so those lines now get both findings (`subscribers` fixture updated). I didn't touch `no-mutable-global`, since another lane owns it. Its "patch once at module load" advice is what this new rule says isn't enough when the module runs again. The two should probably be reconciled there, for example by dropping its finding where `no-foreign-prototype-patch` reports. - **`cycle-init-read`** doesn't follow a called function of another module into a third module, functions passed as values, `Object.getPrototypeOf`-style indirection, dynamic `import()` or workers (they load later), or cycles through `node_modules`. It reports load-time reads that work with today's entry order on purpose; the docs explain why. Its examples span files, so the rule page uses unchecked blocks and points to the fixture. - **`pending-without-close`** doesn't check that the end listener actually settles the pending entries, or that it listens on the same object; any end listener in the unit counts. It misses a store and listener split across classes, callbacks other than promise resolvers (`callbacks.set(id, done)`), and per-call timeouts. A cleanup method called from elsewhere (as in the adopter's code, where nothing called it) is still reported. - **`unbounded-poll`** relies on names: delay names, limit names (`deadline`, `max`, ...), and any call argument counts as "driving" the state (`log(scene)`). It misses delays imported under unknown names and timeouts enforced inside the awaited call. - **`no-foreign-prototype-patch`** misses a prototype passed to a helper that patches it. The adopter's fix uses exactly that shape (`pixiPatch(proto, name, make)`). - **`listener-cleanup`**: a page-lived target behind a parameter (`target: EventTarget`) isn't recognised. Created with Claude Opus 5.5 in Claude Code.
Rules for load order and for what keeps a program alive or waiting, from an
adopter's audit of old bug fixes:

- cycle-init-read (whole program): load-time code (top-level initializers and
  calls, extends, static fields, the module's functions they call, an async
  one up to its first await) reading a binding imported through a runtime
  import cycle. Names the cycle. Per-file summary in cycles.rs, SCCs found
  lazily in the whole-program pass.
- no-foreign-prototype-patch: assigning to the prototype of an imported or
  global class, also through an alias and Object.defineProperty / assign.
  ECMAScript built-ins written out are left to oxlint's no-extend-native.
- pending-without-close: resolvers stored in a collection, settled from
  `message`, with no close / error / exit / abort listener in the class or
  closure.
- unbounded-poll: a loop awaiting a delay that ends only when polled state
  changes, without a deadline, attempt limit or AbortSignal.
- listener-cleanup: `{ once: true }` alone no longer counts on window,
  document, navigator.*, matchMedia(...) lists or module-level targets (also
  for named handlers in Vue components and React effects).

Rule pages, tables, sidebar, CHANGELOG and the skill's tool-gaps updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee force-pushed load-order-and-lifetime from 55720686b5
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m35s
to 30edfdd727
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m49s
2026-11-20 16:36:41 +01:00
Compare
sionzee deleted branch load-order-and-lifetime 2026-11-20 16:37: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!98
No description provided.