State and ownership: emitters that collect subscribers, Mut through callbacks and passes, declared optional keys #65

Merged
sionzee merged 3 commits from evobug/fb3-state into main 2026-11-16 23:58:40 +01:00
Owner

Round 3 of the 0.2.0 adoption feedback, area state and ownership (no-mutable-global, no-param-mutation, stable-shape, no-object-dictionary, listener-cleanup). Real-world numbers are from TwitchRTS: the adopted branch (evobug/adopt-safe-ts-architecture, where the workarounds are) and the upstream commit before adoption (d08e90f1^, where the original shapes are), each copied to /tmp and checked with the old and the new binary.

Per feedback item

  1. Module-level objects that collect subscribers: done. no-mutable-global now reports a module-level emitter that a function subscribes to with a listener written in place (bus.on("x", () => ...), addEventListener without { signal }/{ once: true }, subscribe) or hands to new X(...). What counts as an emitter: EventTarget, EventEmitter (Node's, or any package's class of that name), the platform's event targets, classes the packs' class chains derive from those, the project's own subclasses, and classes listed in the new "safe-ts": { "emitters": ["module Class", "Class"] }. A value built by calls on a new one counts (new GraphicsContext().ellipse(...).stroke(...)); frozen data never does. Vue's reactive() is left out on purpose: a watch made in setup is stopped on unmount, which removes its subscription, so a module-level reactive object doesn't keep components alive (documented). The state guide's context section now says the lifetime's abort handler destroys every third-party object that registered global listeners. RTSS upstream with "emitters": ["pixi.js GraphicsContext"]: 4 findings, exactly the leak's retainers (PIXI_UNIT_RING, PIXI_BUCKET_PAIL/WATER/SPLASH handed to new Graphics(...)). Without the config entry it finds 0 (PixiJS has no pack). On the adopted branch, where the leak is fixed: 0.
  2. A callback parameter gets Mut from its expected type: done. It uses the same contextual-type lookup as q-needs-result-return (qcontext.rs, whose function shapes now record Mut parameters): the parameter of a project function, here or imported; a variable's annotation; and also a function declared inside a function (the variant5((w) => ...) test helper). RTSS adopted, the 19 (x: Mut<T>) => annotations on call arguments removed: 20 findings before, 0 after.
  3. Ownership through local aliases into nested callbacks: done. The variable of a for...of over an owned collection is owned (also through .values(), .entries(), Object.values(...), Array.from(...)), and so are the callbacks inside. A local array, Map or Set filled only with owned values has owned elements. It stops being owned when something that may be the caller's goes in, or when it is handed out. Results of module-level or global functions called with owned arguments count as owned; a primitive parameter (now: number) holds nothing of the caller's. RTSS adopted, the two index-loop workarounds turned back into the feedback's forEach forms (chatter crowd, couples hearts): 11 findings before, 0 after.
  4. Passing a borrowed parameter to a Mut parameter: done. It is reported as no-param-mutation ("Passes parameter cart to applyCoupon, which declares it Mut<...>"), also from closures, with the fix to declare Mut. borrow.rs (#54) records passes for stale-read and unneeded-mut but has no borrowed-to-Mut check. This uses the analyzer's existing borrow tracking (aliases, element callbacks) plus the cross-file Mut parameter table (state.mut_params, the same data FnBorrow.params holds). RTSS adopted: 253 new findings of this kind (after grouping per parameter), e.g. toWorld(game: Game) calling moveCamera(game) (a Mut<Game>), or killUnit(world, u, ...) with a borrowed u. The samples I read are real missing Mut annotations, which the feedback said the rule couldn't find. They are errors, so the adopted branch will need those annotations (each finding offers the fix).
  5. Drawing contexts: done. CanvasRenderingContext2D / OffscreenCanvasRenderingContext2D parameters are owned (also Option<...>). no-param-mutation now gives one finding per parameter: "Changes parameter g, which belongs to the caller: here and in 3 other places (lines 12, 14, 20)". RTSS adopted with the 12 Mut<CanvasRenderingContext2D> removed: 89 findings before, 0 after. With the 8 Mut<Graphics> removed: 6 before, 4 after (one per parameter). Parameters changed only through a package's own methods (g.moveTo) still aren't seen; that limit is now documented.
  6. Test state handed between tests: done. A module-level let in a test file may be assigned in test(...)/it(...) callbacks (and .only/.skip/.todo/.fails/.serial, not .concurrent). It isn't fresh for each test, so changing what it holds is still reported. RTSS upstream: estate ×2, deathCell, scoutedWorld and baseWorld are no longer reported.
  7. stable-shape: done.
    • Several conditional spreads are accepted where the object's type declares every key they may leave out optional. The type comes from a variable's annotation, the return type, satisfies, the parameter it's passed to (here or imported), or the element type of the array it's pushed to. It is followed through aliases, interfaces, Partial/Omit/Pick, intersections, and unions (the member its type: "..." literal picks); anything unresolvable is still reported.
    • Loopholes closed: spreading a const holding a conditional literal, or the result of a function whose returns have different keys (local or imported, e.g. ...buildingEventKind(k)), counts as a conditional spread. A literal with conditional spreads keeps its key list, so o.x = 1 for a key it lacks is reported.
    • The docs present Option<T> as the alternative.
    • Trade-off to flag: N declared-optional keys means up to 2^N shapes, not N+1. The rule now trusts the type's ?:, and the docs give the cost (the guide measures 5× at three keys).
    • RTSS upstream: 122 conditional-spread findings → 89 (33 accepted by declared types). Plus 5 new findings in codec.ts, the "literal with a spread isn't tracked" case the feedback names; they are on the adopted branch too.
    • On the adopted branch, 6 new findings in fire.ts: ...rain and ...buildingEventKind(b.kind) spread into SimEvent.BurntOut({...}), the loophole the feedback names. An Enum constructor's payload type isn't followed as a context yet, so these stay reported even where the payload declares the keys optional. Upstream's pushEvent(world, { type: 'burntOut', ... }) form is accepted through the SimEvent union.
  8. no-object-dictionary: done. A key typed as a union of string literals that Object.prototype doesn't have is accepted: a named type (resolved across files), an inline union, a for...of over such an array, or a string/tuple array literal (as const). The inconsistency the feedback saw came from two places. {} declared with a closed type (skills: Partial<Record<(typeof SKILLS)[number], number>> = {}) was still taken as a dictionary because of the empty literal; it no longer is. And the rule sees bindings, not fields (atlas.textures[id] vs a local textures); that is now documented. RTSS upstream: 107 → 89.
  9. Messages: done; the marker: evaluated, not implemented.
    • Setting globalThis properties in a test file now hints at vi.stubGlobal.
    • A package's registry (extensions.add(...)) and prototype changes (direct writes, Reflect.set, or passing to a Mut parameter) get their own message, and the state guide has a new "Packages: registries and prototypes" section with the module-load pattern. RTSS upstream: both extensions.add sites get the package message.
    • "One sanctioned global per module": not implemented. The marker would exempt exactly the state the rule exists for, without making it less shared, and unlike @cache there's no promise the checker could rely on. The rule page explains this and the alternatives (a module-level handle that reads from a context, vi.stubGlobal, a context passed down).
  10. listener-cleanup on objects the function creates: done. Any new X(...) bound to a const in the function is exempt until the function hands the object out (passes, stores or returns it). RTSS adopted, chat.ts turned back to ws.addEventListener(...): 3 → 0. Upstream unchanged at 35 (those are on parameters, elements, or objects stored first).
  11. @scratch: evaluated, not implemented. It can't be made sound. "Fully written before read" is checkable, but "nothing else uses it in between" isn't: any call between the first write and the last read (a package, a callback, another file) or an await could reach another user. A check strict enough to be sound would reject nearly every real hot path. The state guide documents the context-object (or Mut<T> parameter) alternative and why.

Docs changed

  • docs/rules/no-param-mutation.md: callbacks' Mut, aliases/loops/local collections, passing to Mut, drawing contexts, one finding per parameter, can't-see.
  • docs/rules/no-mutable-global.md: emitters and "emitters", packages, vi.stubGlobal, why no sanctioned-global marker, test lets.
  • docs/rules/stable-shape.md: declared optional keys, Option alternative and cost, variable spreads, literals with spreads.
  • docs/rules/no-object-dictionary.md: literal-union keys, closed declared types, what it sees.
  • docs/rules/listener-cleanup.md: objects the function makes.
  • docs/guide/state.md: the context's lifetime (abort handler destroys third-party objects), scratch space (@scratch evaluation), packages, how-it-decides list.
  • docs/guide/shapes.md: example and the stable-shape summary.
  • docs/guide/testing.md: lets assigned in tests, vi.stubGlobal.
  • README.md: rule table rows.
  • CHANGELOG.md: Unreleased (Added / Changed / Fixed).

Tests

New fixture subscribers (with a fake package and an "emitters" config). New cases in ownership (with session.ts), lints (with sizes.ts), and test_setup. Fixtures cache, ownership and borrow were adjusted for one finding per parameter and for the new transitive finding (selectFirst in borrow). Docs examples cover each new behaviour.

Verification

All pass: npm run build, cargo nextest run --workspace (210/210), cargo clippy -q --workspace --all-targets (no warnings in changed code; the 18 existing ones are untouched lines), npm run test:std, npm run typecheck, npm run typecheck:emit, node scripts/docs-typecheck.mjs (395 examples), npm run test:docs, npm run test:vite, npm run bench:check, node scripts/verify-packages.mjs.

🤖 Generated with Claude Code

Round 3 of the 0.2.0 adoption feedback, area **state and ownership** (`no-mutable-global`, `no-param-mutation`, `stable-shape`, `no-object-dictionary`, `listener-cleanup`). Real-world numbers are from TwitchRTS: the adopted branch (`evobug/adopt-safe-ts-architecture`, where the workarounds are) and the upstream commit before adoption (`d08e90f1^`, where the original shapes are), each copied to /tmp and checked with the old and the new binary. ## Per feedback item 1. **Module-level objects that collect subscribers: done.** `no-mutable-global` now reports a module-level emitter that a function subscribes to with a listener written in place (`bus.on("x", () => ...)`, `addEventListener` without `{ signal }`/`{ once: true }`, `subscribe`) or hands to `new X(...)`. What counts as an emitter: `EventTarget`, `EventEmitter` (Node's, or any package's class of that name), the platform's event targets, classes the packs' class chains derive from those, the project's own subclasses, and classes listed in the new `"safe-ts": { "emitters": ["module Class", "Class"] }`. A value built by calls on a new one counts (`new GraphicsContext().ellipse(...).stroke(...)`); frozen data never does. Vue's `reactive()` is **left out on purpose**: a `watch` made in setup is stopped on unmount, which removes its subscription, so a module-level reactive object doesn't keep components alive (documented). The state guide's context section now says the lifetime's abort handler destroys every third-party object that registered global listeners. RTSS upstream with `"emitters": ["pixi.js GraphicsContext"]`: **4 findings, exactly the leak's retainers** (`PIXI_UNIT_RING`, `PIXI_BUCKET_PAIL/WATER/SPLASH` handed to `new Graphics(...)`). Without the config entry it finds 0 (PixiJS has no pack). On the adopted branch, where the leak is fixed: 0. 2. **A callback parameter gets `Mut` from its expected type: done.** It uses the same contextual-type lookup as `q-needs-result-return` (`qcontext.rs`, whose function shapes now record `Mut` parameters): the parameter of a project function, here or imported; a variable's annotation; and also a function declared inside a function (the `variant5((w) => ...)` test helper). RTSS adopted, the 19 `(x: Mut<T>) =>` annotations on call arguments removed: **20 findings before, 0 after**. 3. **Ownership through local aliases into nested callbacks: done.** The variable of a `for...of` over an owned collection is owned (also through `.values()`, `.entries()`, `Object.values(...)`, `Array.from(...)`), and so are the callbacks inside. A local array, `Map` or `Set` filled only with owned values has owned elements. It stops being owned when something that may be the caller's goes in, or when it is handed out. Results of module-level or global functions called with owned arguments count as owned; a primitive parameter (`now: number`) holds nothing of the caller's. RTSS adopted, the two index-loop workarounds turned back into the feedback's `forEach` forms (chatter `crowd`, couples `hearts`): **11 findings before, 0 after**. 4. **Passing a borrowed parameter to a `Mut` parameter: done.** It is reported as `no-param-mutation` ("Passes parameter `cart` to `applyCoupon`, which declares it `Mut<...>`"), also from closures, with the fix to declare `Mut`. `borrow.rs` (#54) records passes for `stale-read` and `unneeded-mut` but has no borrowed-to-`Mut` check. This uses the analyzer's existing borrow tracking (aliases, element callbacks) plus the cross-file `Mut` parameter table (`state.mut_params`, the same data `FnBorrow.params` holds). RTSS adopted: **253 new findings** of this kind (after grouping per parameter), e.g. `toWorld(game: Game)` calling `moveCamera(game)` (a `Mut<Game>`), or `killUnit(world, u, ...)` with a borrowed `u`. The samples I read are real missing `Mut` annotations, which the feedback said the rule couldn't find. They are errors, so the adopted branch will need those annotations (each finding offers the fix). 5. **Drawing contexts: done.** `CanvasRenderingContext2D` / `OffscreenCanvasRenderingContext2D` parameters are owned (also `Option<...>`). `no-param-mutation` now gives one finding per parameter: "Changes parameter `g`, which belongs to the caller: here and in 3 other places (lines 12, 14, 20)". RTSS adopted with the 12 `Mut<CanvasRenderingContext2D>` removed: **89 findings before, 0 after**. With the 8 `Mut<Graphics>` removed: 6 before, 4 after (one per parameter). Parameters changed only through a package's own methods (`g.moveTo`) still aren't seen; that limit is now documented. 6. **Test state handed between tests: done.** A module-level `let` in a test file may be assigned in `test(...)`/`it(...)` callbacks (and `.only/.skip/.todo/.fails/.serial`, not `.concurrent`). It isn't fresh for each test, so changing what it holds is still reported. RTSS upstream: `estate` ×2, `deathCell`, `scoutedWorld` and `baseWorld` are no longer reported. 7. **`stable-shape`: done.** - Several conditional spreads are accepted where the object's type declares every key they may leave out optional. The type comes from a variable's annotation, the return type, `satisfies`, the parameter it's passed to (here or imported), or the element type of the array it's `push`ed to. It is followed through aliases, interfaces, `Partial`/`Omit`/`Pick`, intersections, and unions (the member its `type: "..."` literal picks); anything unresolvable is still reported. - Loopholes closed: spreading a `const` holding a conditional literal, or the result of a function whose returns have different keys (local or imported, e.g. `...buildingEventKind(k)`), counts as a conditional spread. A literal with conditional spreads keeps its key list, so `o.x = 1` for a key it lacks is reported. - The docs present `Option<T>` as the alternative. - Trade-off to flag: N declared-optional keys means up to 2^N shapes, not N+1. The rule now trusts the type's `?:`, and the docs give the cost (the guide measures 5× at three keys). - RTSS upstream: 122 conditional-spread findings → 89 (33 accepted by declared types). Plus 5 new findings in `codec.ts`, the "literal with a spread isn't tracked" case the feedback names; they are on the adopted branch too. - On the adopted branch, 6 new findings in `fire.ts`: `...rain` and `...buildingEventKind(b.kind)` spread into `SimEvent.BurntOut({...})`, the loophole the feedback names. An Enum constructor's payload type isn't followed as a context yet, so these stay reported even where the payload declares the keys optional. Upstream's `pushEvent(world, { type: 'burntOut', ... })` form is accepted through the `SimEvent` union. 8. **`no-object-dictionary`: done.** A key typed as a union of string literals that `Object.prototype` doesn't have is accepted: a named type (resolved across files), an inline union, a `for...of` over such an array, or a string/tuple array literal (`as const`). The inconsistency the feedback saw came from two places. `{}` declared with a closed type (`skills: Partial<Record<(typeof SKILLS)[number], number>> = {}`) was still taken as a dictionary because of the empty literal; it no longer is. And the rule sees bindings, not fields (`atlas.textures[id]` vs a local `textures`); that is now documented. RTSS upstream: 107 → 89. 9. **Messages: done; the marker: evaluated, not implemented.** - Setting `globalThis` properties in a test file now hints at `vi.stubGlobal`. - A package's registry (`extensions.add(...)`) and prototype changes (direct writes, `Reflect.set`, or passing to a `Mut` parameter) get their own message, and the state guide has a new "Packages: registries and prototypes" section with the module-load pattern. RTSS upstream: both `extensions.add` sites get the package message. - "One sanctioned global per module": not implemented. The marker would exempt exactly the state the rule exists for, without making it less shared, and unlike `@cache` there's no promise the checker could rely on. The rule page explains this and the alternatives (a module-level handle that reads from a context, `vi.stubGlobal`, a context passed down). 10. **`listener-cleanup` on objects the function creates: done.** Any `new X(...)` bound to a `const` in the function is exempt until the function hands the object out (passes, stores or returns it). RTSS adopted, `chat.ts` turned back to `ws.addEventListener(...)`: **3 → 0**. Upstream unchanged at 35 (those are on parameters, elements, or objects stored first). 11. **`@scratch`: evaluated, not implemented.** It can't be made sound. "Fully written before read" is checkable, but "nothing else uses it in between" isn't: any call between the first write and the last read (a package, a callback, another file) or an `await` could reach another user. A check strict enough to be sound would reject nearly every real hot path. The state guide documents the context-object (or `Mut<T>` parameter) alternative and why. ## Docs changed - `docs/rules/no-param-mutation.md`: callbacks' `Mut`, aliases/loops/local collections, passing to `Mut`, drawing contexts, one finding per parameter, can't-see. - `docs/rules/no-mutable-global.md`: emitters and `"emitters"`, packages, `vi.stubGlobal`, why no sanctioned-global marker, test lets. - `docs/rules/stable-shape.md`: declared optional keys, `Option` alternative and cost, variable spreads, literals with spreads. - `docs/rules/no-object-dictionary.md`: literal-union keys, closed declared types, what it sees. - `docs/rules/listener-cleanup.md`: objects the function makes. - `docs/guide/state.md`: the context's lifetime (abort handler destroys third-party objects), scratch space (`@scratch` evaluation), packages, how-it-decides list. - `docs/guide/shapes.md`: example and the stable-shape summary. - `docs/guide/testing.md`: lets assigned in tests, `vi.stubGlobal`. - `README.md`: rule table rows. - `CHANGELOG.md`: Unreleased (Added / Changed / Fixed). ## Tests New fixture `subscribers` (with a fake package and an `"emitters"` config). New cases in `ownership` (with `session.ts`), `lints` (with `sizes.ts`), and `test_setup`. Fixtures `cache`, `ownership` and `borrow` were adjusted for one finding per parameter and for the new transitive finding (`selectFirst` in `borrow`). Docs examples cover each new behaviour. ## Verification All pass: `npm run build`, `cargo nextest run --workspace` (210/210), `cargo clippy -q --workspace --all-targets` (no warnings in changed code; the 18 existing ones are untouched lines), `npm run test:std`, `npm run typecheck`, `npm run typecheck:emit`, `node scripts/docs-typecheck.mjs` (395 examples), `npm run test:docs`, `npm run test:vite`, `npm run bench:check`, `node scripts/verify-packages.mjs`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
State and ownership: emitters, Mut through callbacks and passes, declared optional keys
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m35s
01f34c8ee1
- no-mutable-global: module-level event emitters subscribed to (or handed to `new X`) from a
  function, with `"safe-ts": { "emitters": [...] }`; package registries and prototypes get
  their own message; `vi.stubGlobal` hint in tests; lets assigned in tests are allowed.
- no-param-mutation: a callback's parameter takes `Mut` from its expected type; ownership
  through aliases, for...of and local collections; passing a borrowed parameter to a `Mut`
  one is reported; canvas 2D contexts are owned; one finding per parameter.
- stable-shape: several conditional spreads accepted where the type declares the keys
  optional; spreads of values and results with different keys count; literals with spreads
  keep their keys.
- no-object-dictionary: literal-union keys that aren't Object.prototype names are fine; `{}`
  with a closed declared type isn't a dictionary.
- listener-cleanup: objects a function makes with `new`, before it hands them out.
- Docs: rule pages, state/shapes/testing guides, README, CHANGELOG; `@scratch` and a
  sanctioned-global marker evaluated and documented as not sound / not added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
stable-shape: at most two declared-optional keys
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m15s
b2126788ed
Trusting `?:` in the declared type for any number of conditional spreads
allowed 2^N shapes; three keys make eight, past what V8 keeps fast. Now up to
two keys (four shapes) are accepted where the type declares them optional;
three or more are reported whatever the type says, pointing to Option<T>.
Rule page, shapes guide, CHANGELOG and the lints fixture follow.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge remote-tracking branch 'origin/main' into up-65
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m29s
e6377ee0f3
sionzee deleted branch evobug/fb3-state 2026-11-16 23:58:40 +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!65
No description provided.