Failure contracts: a function type says whether it can fail (Throws, Throwing, failure-contract) #115

Merged
sionzee merged 24 commits from failure-contracts into main 2026-11-21 23:24:46 +01:00
Owner

Based on fail-closed-integration, which is main plus the six open PRs (#109 to #114) merged together. Review the diff as it stands; once those six are in, I'll rebase this onto main and retarget it.

SAFE-TS finds out which PropagateError kinds a function can throw by following calls. The previous PR taught it to follow a method through a field or a declared type to a class. What it still could not follow is a call whose target is only known at run time:

interface Loader { readonly load: (id: string) => string }
function use(loader: Loader): string { return loader.load(""); }   // which load? nothing was reported, whatever the implementer did

The same held for an override reached through its base class, and for a callback kept in a field or a collection and called later.

The rule

A function type says whether it can fail, as a trait signature does in Rust. A slot that declares nothing cannot propagate; one that can says what:

interface Store { readonly get: (id: string) => Throws<string, NotFound> }
abstract class Task { abstract run(): Throws<void, NotFound> }
private readonly jobs: Throwing<[id: string], string, NotFound>[] = [];
  • Whatever goes into a slot is checked against it (new rule failure-contract, an error): a class that implements an interface, an object literal typed as one, a visible class handed over as one, an override against the method it overrides, an implementation of an abstract method, a function put into a typed member, field or collection. The message names the two ways out: catch it there, or declare it on the slot.
  • A call through a slot propagates what the slot declares, with the same findings a direct call gets.
  • Inference stays where it works. A callback handed to a function that calls it right away needs no declaration. A function's own Throws return type is a claim, and its body is checked against it.

Throws<R, E> and Throwing<Args, R, E> are in std's result module and the prelude. To TypeScript Throws<R, E> is R: the checker reads it, as it does Mut<T> today. Whether a function value fails is not in its TypeScript type, so the conformance check is the checker's in any design; a nominal wrapper would have changed every call site and ruled out implementing an interface with ordinary methods.

For async, Promise<Throws<T, E>> declares what the promise rejects with.

What an adopter will notice

On an adopter's project: 78 new failure-contract findings (69 from its entries), and nothing else changes. All 78 are implementations that throw a PropagateError their slot does not declare; 61 are in one package whose interface doc comment already says "methods throw". 41 slots need a declaration.

The implementer read 23 sites and found no false positives. It then declared 35 of the slots in a private copy: every caller the checker follows already catches the failure, so no unhandled failure surfaced. What the project gains is that the contracts are now written down and checked.

One behaviour change: a failing callback kept in a collection or field whose function type is written is now failure-contract, where it was uncaught-propagation, because the fix differs (declare it on the slot).

The whole-program pass on that project's largest app goes from 864 ms to 923 ms.

How it was checked

  • The Rust suite (334 tests), test:std, typecheck, the docs examples (870 compile), test:vite, the docs site build and the soundness corpus pass.
  • Eight places given to the implementation are reported, and ten more it had not seen: an implementer in another file than its interface, an object literal returned as the interface, a failing function by name in an alias-typed member, an assignment to a typed field, an async implementer rejecting outside its contract, a function whose own claim its body exceeds, a declared rejection nobody awaits.
  • Legitimate code stays clean: a subclass of a declared kind, a Result (a value, not a propagation), callers that catch, Throws<T, never>, callbacks that are called right away.

Where the principle could not be carried through

Listed with examples on the rule page. The main ones:

  • A value of inferred type, or from a package, entering a slot.
  • Slots reached through Map.get, a computed key or a Record.
  • Members of mapped types.
  • A collection whose type is only in its initializer (new Set<Handler>()), not in an annotation.
  • Whether an implementer throws or rejects is not compared with its slot.

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

Based on `fail-closed-integration`, which is `main` plus the six open PRs (#109 to #114) merged together. Review the diff as it stands; once those six are in, I'll rebase this onto `main` and retarget it. SAFE-TS finds out which `PropagateError` kinds a function can throw by following calls. The previous PR taught it to follow a method through a field or a declared type to a class. What it still could not follow is a call whose target is only known at run time: ```ts interface Loader { readonly load: (id: string) => string } function use(loader: Loader): string { return loader.load(""); } // which load? nothing was reported, whatever the implementer did ``` The same held for an override reached through its base class, and for a callback kept in a field or a collection and called later. ## The rule A function type says whether it can fail, as a trait signature does in Rust. A slot that declares nothing cannot propagate; one that can says what: ```ts interface Store { readonly get: (id: string) => Throws<string, NotFound> } abstract class Task { abstract run(): Throws<void, NotFound> } private readonly jobs: Throwing<[id: string], string, NotFound>[] = []; ``` - **Whatever goes into a slot is checked against it** (new rule `failure-contract`, an error): a class that `implements` an interface, an object literal typed as one, a visible class handed over as one, an override against the method it overrides, an implementation of an abstract method, a function put into a typed member, field or collection. The message names the two ways out: catch it there, or declare it on the slot. - **A call through a slot propagates what the slot declares**, with the same findings a direct call gets. - **Inference stays where it works.** A callback handed to a function that calls it right away needs no declaration. A function's own `Throws` return type is a claim, and its body is checked against it. `Throws<R, E>` and `Throwing<Args, R, E>` are in std's result module and the prelude. To TypeScript `Throws<R, E>` is `R`: the checker reads it, as it does `Mut<T>` today. Whether a function value fails is not in its TypeScript type, so the conformance check is the checker's in any design; a nominal wrapper would have changed every call site and ruled out implementing an interface with ordinary methods. For `async`, `Promise<Throws<T, E>>` declares what the promise rejects with. ## What an adopter will notice On an adopter's project: 78 new `failure-contract` findings (69 from its entries), and nothing else changes. All 78 are implementations that throw a `PropagateError` their slot does not declare; 61 are in one package whose interface doc comment already says "methods throw". 41 slots need a declaration. The implementer read 23 sites and found no false positives. It then declared 35 of the slots in a private copy: every caller the checker follows already catches the failure, so no unhandled failure surfaced. What the project gains is that the contracts are now written down and checked. One behaviour change: a failing callback kept in a collection or field whose function type is written is now `failure-contract`, where it was `uncaught-propagation`, because the fix differs (declare it on the slot). The whole-program pass on that project's largest app goes from 864 ms to 923 ms. ## How it was checked - The Rust suite (334 tests), `test:std`, `typecheck`, the docs examples (870 compile), `test:vite`, the docs site build and the soundness corpus pass. - Eight places given to the implementation are reported, and ten more it had not seen: an implementer in another file than its interface, an object literal returned as the interface, a failing function by name in an alias-typed member, an assignment to a typed field, an `async` implementer rejecting outside its contract, a function whose own claim its body exceeds, a declared rejection nobody awaits. - Legitimate code stays clean: a subclass of a declared kind, a `Result` (a value, not a propagation), callers that catch, `Throws<T, never>`, callbacks that are called right away. ## Where the principle could not be carried through Listed with examples on the rule page. The main ones: - A value of inferred type, or from a package, entering a slot. - Slots reached through `Map.get`, a computed key or a `Record`. - Members of mapped types. - A collection whose type is only in its initializer (`new Set<Handler>()`), not in an annotation. - Whether an implementer throws or rejects is not compared with its slot. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Failure contracts: a function type says whether it can fail (Throws, Throwing, failure-contract)
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m13s
Tests / test (pull_request) Successful in 9m26s
78603babc0
Open: the failure rules followed a call only into a body. A call through an
interface member, an abstract method, a base class's method that a subclass
overrides, or a callback kept in a field or a list runs whatever was put
there, so nothing was propagated through it and nothing put into it was
checked: an implementation's PropagateError reached callers that were never
asked to handle it, silently.

Closed: like a trait method's signature, a function type now declares what it
may throw. std's result module (and the prelude) gains `Throws<R, E>` (R to
TypeScript) and `Throwing<Args, R, E>`; an async slot declares what it rejects
with as `Promise<Throws<T, E>>`. A function type that says nothing declares no
failure.

- analyze/contracts.rs reads every function type where inference ends
  (interface and type-literal members, abstract methods, type aliases,
  parameters', fields' and locals' types, a function's own return type) and
  records the values put into declared types: object literals, instances,
  functions written in place or by name, array literals.
- A call through a declared type propagates what it declares (`store.get()`,
  `task.run()`, `job()`, items of declared collections, members taken off one,
  fields declared with a function type); a method called on an item of a
  declared array of a class is followed to that class.
- New rule `failure-contract`: a class's methods against the interfaces it
  implements, object literals and visible instances against the interface they
  go into, overrides against the method they override (declared or inferred),
  abstract implementations, a body against its own Throws, and a callback kept
  for later against the type it is kept as. A kept callback whose type is a
  function type written in the project was uncaught-propagation and is now
  failure-contract; a Throwing type that declares the failure allows it.
- Callbacks a function calls right away stay inference, with no declaration.

Fixture expectations changed from uncaught-propagation to failure-contract
where the kept callback has a declared function type (passed_callbacks,
spellings, test_runners/shadowed.ts); test_runners/fakes.ts now expects the
fake that throws under an undeclaring type, with a declared variant that
passes. The fixture harness takes several annotations on one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Contracts: name the span helper so it can't collide with another module's
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m30s
Tests / test (pull_request) Successful in 7m0s
db642660f6
Two branches each added an inherent method `text_of` to the analyzer, with
different signatures. Each compiles alone; together they are a duplicate
definition. This one reads a span's source text: `span_text`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
failure-contract: one finding for a declared on... member, the same for a name and its arrow
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m15s
Tests / test (pull_request) Successful in 7m35s
ebcc2e07c8
Open: `port.onmessage = find` with `port` of a type the project declares was
reported twice, as a runtime handler (uncaught-propagation) and as a function
put into a typed slot (failure-contract), while `port.onmessage = (id) =>
find(id)` got only uncaught-propagation. A field initializer by name
(`handler: Plain = find`) was checked against the field's type while its arrow
twin was left to inference.

Closed: an `on...` member of an object whose type the project declares is a
slot like any other. A function assigned to it, by name or written in place,
is checked against the member's type (failure-contract) and nothing else; a
platform or package object's handler (`worker.onmessage = ...`) has no slot
and stays uncaught-propagation. Calls and throws now record where the callback
that runs them later starts, so the arrow's inner failures find the member.
A field's function initializer is followed by inference in both forms, and
held to the field's type in both forms when that type declares failures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from fail-closed-integration to main 2026-11-21 23:24:44 +01:00
Merge main
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m36s
Tests / test (pull_request) Successful in 9m9s
15352b9dc6
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch failure-contracts 2026-11-21 23:24:46 +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!115
No description provided.