State and ownership: emitters that collect subscribers, Mut through callbacks and passes, declared optional keys #65
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/fb3-state"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
no-mutable-globalnow reports a module-level emitter that a function subscribes to with a listener written in place (bus.on("x", () => ...),addEventListenerwithout{ signal }/{ once: true },subscribe) or hands tonew 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'sreactive()is left out on purpose: awatchmade 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/SPLASHhanded tonew Graphics(...)). Without the config entry it finds 0 (PixiJS has no pack). On the adopted branch, where the leak is fixed: 0.Mutfrom its expected type: done. It uses the same contextual-type lookup asq-needs-result-return(qcontext.rs, whose function shapes now recordMutparameters): the parameter of a project function, here or imported; a variable's annotation; and also a function declared inside a function (thevariant5((w) => ...)test helper). RTSS adopted, the 19(x: Mut<T>) =>annotations on call arguments removed: 20 findings before, 0 after.for...ofover an owned collection is owned (also through.values(),.entries(),Object.values(...),Array.from(...)), and so are the callbacks inside. A local array,MaporSetfilled 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'sforEachforms (chattercrowd, coupleshearts): 11 findings before, 0 after.Mutparameter: done. It is reported asno-param-mutation("Passes parametercarttoapplyCoupon, which declares itMut<...>"), also from closures, with the fix to declareMut.borrow.rs(#54) records passes forstale-readandunneeded-mutbut has no borrowed-to-Mutcheck. This uses the analyzer's existing borrow tracking (aliases, element callbacks) plus the cross-fileMutparameter table (state.mut_params, the same dataFnBorrow.paramsholds). RTSS adopted: 253 new findings of this kind (after grouping per parameter), e.g.toWorld(game: Game)callingmoveCamera(game)(aMut<Game>), orkillUnit(world, u, ...)with a borrowedu. The samples I read are real missingMutannotations, 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).CanvasRenderingContext2D/OffscreenCanvasRenderingContext2Dparameters are owned (alsoOption<...>).no-param-mutationnow gives one finding per parameter: "Changes parameterg, which belongs to the caller: here and in 3 other places (lines 12, 14, 20)". RTSS adopted with the 12Mut<CanvasRenderingContext2D>removed: 89 findings before, 0 after. With the 8Mut<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.letin a test file may be assigned intest(...)/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,scoutedWorldandbaseWorldare no longer reported.stable-shape: done.satisfies, the parameter it's passed to (here or imported), or the element type of the array it'spushed to. It is followed through aliases, interfaces,Partial/Omit/Pick, intersections, and unions (the member itstype: "..."literal picks); anything unresolvable is still reported.constholding 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, soo.x = 1for a key it lacks is reported.Option<T>as the alternative.?:, and the docs give the cost (the guide measures 5× at three keys).codec.ts, the "literal with a spread isn't tracked" case the feedback names; they are on the adopted branch too.fire.ts:...rainand...buildingEventKind(b.kind)spread intoSimEvent.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'spushEvent(world, { type: 'burntOut', ... })form is accepted through theSimEventunion.no-object-dictionary: done. A key typed as a union of string literals thatObject.prototypedoesn't have is accepted: a named type (resolved across files), an inline union, afor...ofover 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 localtextures); that is now documented. RTSS upstream: 107 → 89.globalThisproperties in a test file now hints atvi.stubGlobal.extensions.add(...)) and prototype changes (direct writes,Reflect.set, or passing to aMutparameter) get their own message, and the state guide has a new "Packages: registries and prototypes" section with the module-load pattern. RTSS upstream: bothextensions.addsites get the package message.@cachethere'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).listener-cleanupon objects the function creates: done. Anynew X(...)bound to aconstin the function is exempt until the function hands the object out (passes, stores or returns it). RTSS adopted,chat.tsturned back tows.addEventListener(...): 3 → 0. Upstream unchanged at 35 (those are on parameters, elements, or objects stored first).@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 anawaitcould reach another user. A check strict enough to be sound would reject nearly every real hot path. The state guide documents the context-object (orMut<T>parameter) alternative and why.Docs changed
docs/rules/no-param-mutation.md: callbacks'Mut, aliases/loops/local collections, passing toMut, 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,Optionalternative 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 (@scratchevaluation), 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 inownership(withsession.ts),lints(withsizes.ts), andtest_setup. Fixturescache,ownershipandborrowwere adjusted for one finding per parameter and for the new transitive finding (selectFirstinborrow). 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
- 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]>