Whole-program pass: 1,120 ms down to 465 ms on a large entry, findings unchanged, with a guard on the work done #126
Loading…
Reference in a new issue
No description provided.
Delete branch "pass-speed"
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?
The whole-program pass is what the editor, the lint plugin and an agent's edit loop wait on, and the README promises it stays "well under a second on a project of a few hundred files". On an adopter's largest entry it had crept to 1,120 ms: a dozen pieces of work each added a few percent, and each was accepted on its own. It is now 465 ms, with every finding unchanged.
About 350 ms of the gain on the entry is work moved onto other cores, not work removed; the one-thread row is the honest measure of what was cut.
Where the time went, and what was cut
sentinel-errorwas more than half the pass. It looks at package files outside the program, and analysed each one lazily, one at a time, once per file that asked. Now each file's tested calls are resolved once per pass (5,977 resolutions became 1,774), package text is read once, and the outside files are analysed in one parallel batch.resolve_callee,resolve_binding, a type lookup at the top level, a global type and a type import are remembered per pass. Call resolutions on the directory run went from 1.06 million to 123 thousand.Two of the nine commits show no measurable gain on their own and are kept because they remove repeated work; the commit messages say which.
Nothing changed in what is reported
Byte-identical output against the previous binary, checked after every commit: 234 invocations, each compared as text with the summary line, as
--json, and as stderr with the exit code. That covers the adopter's entries and its directories, the three example projects and every fixture directory, with and without--idiomatic. I repeated the adopter's directory run and the examples on top of the currentmain: identical again, and two runs of the new binary agree with each other.So it does not creep back
crates/safe_ts_core/tests/work.rschecks a fixed generated project and compares counts of work done from scratch withtests/work-ceilings.json: files analysed and parsed again, calls, names and receivers resolved, types looked up and evaluated, declarations copied, package calls judged, failure chains, filessentinel-errorreads. Counts, not milliseconds, so it holds on a shared CI runner. It fails when a count rises above its ceiling, and also when one falls more than 10% below, so a speed-up has to be written down. Disabling the new memos makes it fail (calls resolved on the entry: 581 → 2,579).What is left
sentinel-errordoes for that entry to go (about 350 ms of CPU): either a lighter analysis for files outside the program, or a narrower name filter in the rule. The second changes what the rule sees, so it is not part of a change that promises identical findings.safe-ts fixon a large project is slow for a different reason: every file is checked with a fresh run, so the cross-file facts of its dependencies are worked out again each time. These cuts help it (fix strict-truthinesson one app: 10.4 s → 7.3 s), but the fix is a run shared across files.For whoever writes rules next:
resolve_callee,resolve_binding, a top-level type lookup and a global type are now remembered per pass. Their answers must not depend on anything that is not part of the key.Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and verification) in Claude Code.
Promise.rejectno longer escapesWhat was open: `no-unchecked-cast` bans `as`, but three constructs hand out a type nobody checked and passed every gate, `tsc` strict included. TypeScript never checks a type predicate's or an assertion signature's body against its claim (`(v: unknown): v is User => true`, `asserts v is User {}` compile), and an overload signature only has to be loosely related to the implementation (`function parse(t: string): User; function parse(t: unknown): unknown`). A predicate could also mint a brand. The only coverage was the opt-in `partial-type-guard`, which looked at field names in guards over `unknown`. The docs recommended the overload and the "complete" guard as the cast-free way. What closes it: - `no-type-predicate` (error): every hand-written `x is T`, `this is T`, `asserts x is T` and `asserts x` on a function, method or arrow with a body. Nothing is verified and allowed: since TypeScript 5.5 a predicate whose body is one test TypeScript narrows by is inferred, and checked, once the annotation is gone. The quick fix "Let TypeScript infer the narrowing from the body" removes it for those bodies (typeof, instanceof, Array.isArray, `in`, literal and constant comparisons, discriminants, `!!x`, std's guards, joined by || or &&); a claim wider than its test then fails to compile where it was used. The message names the form for the rest (validate<T>, `find` for a lookup, std's isJsonObject, filter(isSome)). The one form allowed: `asserts x` whose body is exactly `if (!x) throw`/`panic(...)`. - A predicate that claims a brand is `brand-constructor`. - `no-overload` (error): overloads of the project's functions and methods, once per function. Allowed: overloads that only narrow the implementation (same type parameters and result, each parameter one of its union's members), `.d.ts`, `declare` blocks, interface call signatures. A result the body can't type is `trust<T>(value)`, which `check` counts. - `partial-type-guard` is removed; a config or ignore naming it is told what replaced it. On an adopter's project (346 files) the run adds 99 no-type-predicate and 2 no-overload findings and changes nothing else; 24 of the predicates get the fix, and with it applied 21 compile unchanged and 3 surface a claim their body didn't make. The fix is held back where TypeScript would infer something else: `Array.isArray` on a readonly array, `instanceof` for a claim with type arguments (`Map<any, any>`), `Record<string, unknown>`. The repo's examples are unchanged; the docs, the skill, the fixtures and std's test fixture write `codesOf` with `trust` instead of an overload. Co-Authored-By: Claude Opus 5.5 <[email protected]>The failure rules followed a method call only when the receiver's class was visible at the call: `this`, `super`, `new C()`, a module-level instance, or a binding declared as exactly `C`. Every other receiver was silent, so the most ordinary shape of application code, a service holding its dependencies in fields (`this.repo.load(id)`), propagated nothing anywhere. A receiver is now written down as a value (analyze/receivers.rs) and a call on it as `Callee::Of`; the whole-program pass (project/receivers.rs) follows the declarations, across files, to the method `new Repo().load()` runs: - a field declared with the class: an annotation, `= new Repo()`, a constructor parameter property, `this.repo = new Repo()` in the constructor; inherited; - a property of a declared type (`deps.repo.load()` with `deps: Deps`, an alias, an interface, an object type, `Repo | undefined`), also destructured (`const { repo } = deps`, `function run({ repo }: Deps)`), and `const` copies (`const repo = this.repo`, `const self = this`); - a function or method declared to return the class (`makeRepo().load()`, `T` of an async one's `Promise<T>` once awaited), and chains of these; - a member chain into a module-level object literal (`api.users.load()`); - getters and setters: `x.value` runs `get value()`, `x.value = v` runs `set value(v)`, keyed `C#get value` / `C#set value`. Not followed: a receiver typed as an interface or a union of several types, an override through a value declared as the base class (left to the declared contracts of the next change), generic types, array and Map elements. Two causes of false floating-rejection findings that the newly known rejections exposed are fixed: a promise held in a binding and also stored in an object literal (`{ promise }`) or compared (`p === q`) still settles where every path awaits it, and `return c ? f() : undefined` (also `??`, `||`) returns `f()`'s promise. Following more receivers adds call sites; the failure and propagation passes now take a function's calls from an index (`calls_of`) instead of scanning the file's, and calls by span from another (`call_at`). Receivers are interned per file and resolved once each. Co-Authored-By: Claude Opus 5.5 <[email protected]>this, taken off its object 3d6696055e`queueMicrotask(this.tick)`, `items.forEach(this.tick)`, `return this.tick`, `const f = ticker.tick; f()` and `const { tick } = ticker; tick()` run the method with `this` undefined, and the first `this.x` throws TypeError. tsc, oxlint's preset and `safe-ts check` all passed them (the soundness corpus counted the class `unbound-method-this` as escaping). The places the by-name machinery already visits as a function used as a value (an argument, a return, an object or array literal, an assignment, a field's value, a JSX attribute), and a `const` copy or a destructuring, now record the method they name, through the same receivers the failure rules follow. The whole-program pass reports it (an error) when that method is an instance method of a module-level class whose body uses `this` or `super`: not an arrow-function field, a `static` method, a method that doesn't use `this`, a decorated one, one the constructor binds, `this.tick.bind(this)`, `() => this.tick()`, or `items.forEach(this.tick, this)`. The quick fix binds it (`.bind(<object>)`) where the object is `this`, `super` or a plain name; the meaning test runs it. `unbound-method-this` no longer escapes and comes out of escaping.txt. Co-Authored-By: Claude Opus 5.5 <[email protected]>Three receivers the previous two commits left silent: - `(await makeLater()).load("")` wasn't followed, while `const repo = await makeLater(); repo.load("")` was. The awaited call is now the same value as the local holding it (`Callee::Returned` from `member_target`, `Value::Returned` from `value_of`). - `private readonly api = { load(id) { ... } }` and then `this.api.load()` wasn't followed, while a module-level object literal and a field `= new Repo()` were. A `readonly` field's object literal is now keyed like a module-level one (`Holder#api.load`) and the field resolves to it. - `setTimeout(super.reset, 5)` was silent when the parent's constructor sets `this.reset = this.reset.bind(this)`: the exemption removed the method from the ones that use `this`. That assignment makes an own property of the instance; `super.reset` reads the prototype's method, still unbound. The exemption now applies only to a read through the instance (the constructor of the method's class, or of the object's class or one between). Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: the mark `(value: T) => void` compared whole types, so a value with more properties than asked for (a Tree where Mut<Entity> is asked, a Sprite for Mut<Container>), a writable list where Mut<readonly T[]> is asked and a typed array made with `new` were refused, though the callee can't break any of them: 134 + 27 + 3 of 251 tsc errors on a migrated adopter. And the advice to make such callees generic was unsound: TypeScript lets a generic body write the bound's type into a narrower `T["x"]`. Closes it: the mark lists, per property of T, a slot: invariant where the callee may write it, covariant where it can only read it (`readonly`) or calls it (a method, rebuilt as a plain function type so its parameters count one way, which keeps `Map<string, 1>` out of `Mut<Map<string, number>>`). Every hazard stays refused (Dog[] as Mut<Animal[]>, { x: 0 | 1 } as Mut<{ x: number }>, a Map of a narrower value, Mut<Builder> as Mut<Unit>, a narrower override); width, subclasses, readonly views, typed arrays and narrowed unions are accepted. What it newly accepts (a delete through a Record target, Object.assign through Mut<object>) is reachable under the old mark by a plain assignment first. mut.check.ts pins each case. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: a value put into a place declared Mut<...> without a call (an initializer or assignment, a parameter's default, a field, a `return`, an array literal where readonly Mut<T>[] is asked) wasn't reported or migrated, and a fresh literal at a Mut slot got no fix: 30 + 17 tsc errors after the migration on an adopter, all mechanical. Closes it: `missing-mut` reports those places (per file, as Slot), and its fix, which `safe-ts migrate mut` applies, lends them; a fresh literal is lent with the place's type (`mut<Cost>({ ... })`, `mut<number[]>([])`) where the file can name it, else only `[]`/`{}` are left as notes. Returns count through Promise<Mut<T>> and Generator<Y, Mut<T>, N>. Fixtures, the codemod case (tsc on its output) and meaning.rs cover it. Docs: the state guide's table and "what to write" for the new mark, missing-mut, adoption, README, CHANGELOG, skill. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: the mark compared a `readonly` property one way, as covariant, but `readonly` is shallow. A `{ readonly dogs: Dog[] }` lent as `Mut<{ readonly dogs: Animal[] }>` was accepted and the callee pushed a cat into the list (`Dog[]` as `Animal[]` one property down); also a `{ readonly state: { on: 0 | 1 } }` lent where `on: number` is written, a subclass narrowing a `readonly` field that holds a list, a `Map` of a narrower value in a `readonly` field. And two `Shared<...>` were compared by the variance TypeScript measures for the alias, which ignores `readonly`: a `{ readonly n: number }` was lent where the callee writes `n`. Closes them: each property's slot is `{ w, r }`: `w` whether the callee may replace it (the same type both ways, or never), `r` what it holds, an object lent as a loan of its own (`Lent<X>`: each member of the value lendable as some member asked, so a typed array's `ArrayBuffer` fits `ArrayBufferLike`). `Shared` and the slots are written so TypeScript compares them structurally. Recursive types (nodes with `readonly children`) check, and an adopter's ten projects reach no depth limit; tsc takes 8.3 s and 1,295 MB where the round-3 mark took 8.0 s and 1,210 MB (minimum of three interleaved rounds). Left open, documented on `Mut`, in the guide and as escaping corpus classes: a function in a writable property replaced by one that needs more (compared one way like a method: compared both ways, 97 more of the adopter's errors, subclasses lent as their base and typed arrays), and a write through a member shared by a `readonly` property's union. Corpus: mut-readonly-field-list, -object, -subclass (refused; each escapes with the round-3 mark), mut-function-field-replaced and mut-readonly-union-field-write (escaping.txt). mut.check.ts pins the refusals, the recursive tree and the two open holes. Co-Authored-By: Claude Opus 5.5 <[email protected]>on...member, the same for a name and its arrow.oxlintrc.json, the file that sets themOpen (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]>asynconeConflicts, all kept from both sides: ecmascript-api.json gets both new sections (`callbacks` and `consumes`, merged as JSON: each side only added its own key); package.json takes `test:std` from this side (vue-tsc tools for the TypeScript-versions test) and `test:browsers` from the other (the browsers' consumes test); the soundness class list imports both new groups; the migration skill has both sections ("A promise used as its value", "A value used after it was used up") and census.mjs both pointers; the CHANGELOG's Added and Changed keep every entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open after the merge: - `packages/std/src/mut-loan.ts` (borrow-escapes: the one-value mark of `Mut`) is `// @safe-ts std`, and with escape-hatches-2 a marker counts only in a file its package.json lists: `unlisted-marker` at the marker, and the module checked as project code (its `null`s reported in every fixture importing std's `mut`). Closes: `src/mut-loan.ts` under std's `"trustedFiles"`, as unlisted-marker's page says to write. - null_package_receivers: `copy.put("c", null)` with `copy: Readonly<Store>` is now also `no-param-mutation`. The one opener (return-types) reads `Readonly<Store>` as `Store`, and borrow-escapes follows `Store.put`, which writes the store's private map: `Readonly` makes the fields read-only, not the methods, so the caller's store does change. A finding of the two pieces together, right by the rule's page; the expectation is written, with the reason in the fixture's comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: `returns` (borrow-escapes) says `Array.from` hands back a container of its argument's objects, and the borrow follower took that for every call, while `callbacks` (promise-statics) says its second argument is a callback whose results are collected. So `Array.from(order.lines, (l) => ({ ...l }))` was taken to hold the borrowed lines, and a change to the copies was reported as `no-param-mutation` (borrow-escapes alone reports it). Nothing held the three sections (`consumes`, `callbacks`, `returns`) to each other. Closes: - `Builtins::static_hands(name, args)`: a static whose callback's results are collected and that is given that callback hands back new values, as `map` does; both callers (analyze.rs `call_reach`, borrow.rs `part_in`) pass the call's argument count. `Array.from(xs)` is a container as before. elements fixture: `fromList` (reported) and `fromMapped` (silent), in two functions since one parameter's findings in one function are one finding. - builtins::tests::the_sections_agree: all three sections load; a collected callback means fresh values (a static's optional mapper through `static_hands`); a truthiness callback picks an element or a container, and its iteration of an iterator may stop early (`iterates: some`); an order callback sorts the same items; a static's `returns` and `consumes` are about the same argument. - Receiver table: a slot row for std's `Mut<Port>` lent with `mut<Port>({ ... })`, now that failure-contract reads a `Mut` slot as its type (43 rows). - no-param-mutation's page: `Array.from` with a mapper is with `map` (and an identity mapper is the same gap as `lines.map((l) => l)`). Co-Authored-By: Claude Opus 5.5 <[email protected]>Resultgets one finding, not two