ADR 0148: Checked Narrowing Casts and the Trusted-Type Comparison Hole

Status

Deferred (2026-11-14). Tracking: BT-4772.

The owner deferred this ADR on 2026-11-14. Part 1 (the correctness bug) is implemented separately as BT-4823, receiver side only; the owner chose BT-4823's option 3 for the guard-return rewrite, which keeps the fast form for typed-parameter guard clauses. Parts 2 (an explicit checkedAs: cast) and 3 (no implicit guard on :: locals) are ergonomics, not correctness, and are deferred. What would bring them back: a real FFI or JSON boundary bug where a wrong value travels far before failing, or demand for a cast-site error. The open questions stay as listed below: String vs Binary, dead actors, the selector name, and a runtime Object>>checkedAs:. BT-4823 (PR #5284) measured the cost: reductions and heap words are unchanged on the benchmark rows and the ns differences are inside run-to-run noise, so the ~1 ns estimates below were not contradicted (docs/development/benchmarks.md § BT-4823).

Scope amendment (2026-11-14): part 1 is being done as BT-4823

The owner fast-tracked part 1 as a separate bug, BT-4823 ("Typed comparison fast path answers wrong when the declared type is violated"), implemented ahead of this ADR. Consequences for this document:

Context

Problem statement

A narrowing local annotation is a cast the type checker cannot prove:

n :: Integer := opts at: #max     // RHS is Object or Dynamic: accepted silently (BT-2015)

Nothing checks it at run time. BT-4719 made these casts visible (their own type-coverage category and an opt-in narrowing-cast lint). This ADR decides whether to make them checked, and what the evidence says about how urgent that is.

The issue raised one open fact that decides urgency: codegen trusts declared types (row 11b of just bench-vs-elixir: a + 1 with a :: Integer is a bare erlang:'+'), so can a wrong cast give a silently wrong answer rather than a crash?

Finding: yes, but not where the issue looked

A wrong value can produce a silently wrong answer today. The test stdlib/test/narrowing_cast_wrong_value_test.bt (with fixtures narrowing_cast_probe.bt and narrowing_cast_limit.bt) feeds non-Integer values through a narrowing cast and records what happens:

Where the wrong value is usednil < 10nil > 10nil + 1
The cast local (n :: Integer := opts at: #v, then n > 10)does_not_understanddoes_not_understanddoes_not_understand
A typed parameter it is passed to (paramGreater: n :: Integer)falsetruetype_error (raw badarith)
A typed field it is stored in (field: limit :: Integer)–true–

#foo and true behave like nil in the parameter and field rows. A real Integer or Float answers correctly everywhere.

Three facts follow from the table:

  1. The silent answer comes from the comparison fast path, not from the annotated local. Codegen trusts the declared type of a parameter or field (trusted_param_types, field_types.rs) and emits a bare erlang:'<' / '>' for it. Erlang's comparison is a total term order that never raises, so nil > 10 is true (atoms sort above numbers). An annotated local is not trusted by the operator path, so the same value fails loudly there. Arithmetic fails loudly everywhere (badarith), only with the wrong error kind.
  2. A guard at narrowing casts would not close it. The last test in the file passes d at: #v straight to the typed parameter with no annotation anywhere, and gets the same wrong answer. A wrong value reaches a typed parameter or field through a cast, a Dynamic argument, an untyped caller or an FFI result. The cast is one route of several.
  3. It contradicts a rule already on the books. ADR 0025's amendment (BT-4118) says types "may choose code, never results" and that a lying annotation "simply misses the guard and gets the dynamic answer". BT-3924 already decided that a silent term-order answer is unacceptable for untyped receivers and Nil unions (ADR 0116, last paragraph of the field-types section). The typed Integer/String parameter and field are the one remaining exception.

BT-1944's typed_param_erasure_test.bt states the intent ("adding :: Integer | Nil should NOT change runtime behavior"). For comparisons it does change it: paramLess: nil answers false while the same expression on an untyped receiver raises.

Current state

Constraints

Decision

Two parts, in this order. Part 1 is independent of part 2 and is the actual fix for the silent wrong answer. Part 1 is implemented as BT-4823 (see the scope amendment above); the open decision is part 2.

1. Make the comparison fast path obey "never results" (BT-4823)

Drop the bare-BIF path for <, >, <=, >= on a typed parameter or field. Every comparison whose receiver is not a numeric/string literal (or self in a numeric class) takes the existing inline OperatorGuard::Comparison test (is_number or is_binary). nil > 10 then raises does_not_understand for a typed parameter exactly as it does for an untyped one. Only the receiver is tested; the argument stays unchecked (BT-3928), so 5 < nil is still true. Only declared types are guarded: a receiver whose kind the compiler proves (a literal, integer arithmetic) keeps the bare BIF. Annotated locals already take the guard today (the evidence table), so the sites that change are typed parameters and typed fields.

Arithmetic keeps its bare path: its BIF raises, so a lying annotation fails loudly, and row 11b keeps its zero-guard fast path. It still reports type_error where an untyped receiver would dispatch to a user-defined +; that remaining gap is listed under Open Questions.

2. An explicit checked cast; no implicit guard on :: locals

Add a checked sibling of asType:, spelled here checkedAs: (name to be settled; as: is ruled out by ADR 0025):

n := opts at: #max checkedAs: Integer      // answers Integer, raises on a mismatch
n :: Integer := opts at: #max              // unchanged: unchecked, still lintable
n := (opts at: #max) asType: Integer       // unchanged: unchecked, erased

asType: stays the unchecked escape hatch (question 2). A narrowing :: local stays unchecked, which keeps ADR 0025's erasure rule intact for annotations. The narrowing-cast lint message gains a hint pointing at checkedAs:.

Semantics of checkedAs: C:

> (#{#max => "ten"} at: #max) checkedAs: Integer
=> type_error: expected Integer, got String (at the checkedAs: on line 1)

(Proposed output; nothing here is implemented.)

3. Not now: an implicit guard on narrowing :: locals

Recorded as the alternative the issue proposed, with the conditions that would reopen it (see Recommendation changes).

Answers to the five questions

1. Where the guard applies. The explicit form applies wherever it is written, in any class, typed or not; it is opt-in per site, so there is no class-level switch and no REPL/build divergence. For the implicit variant (not adopted), the answer would be typed classes only, since typed already means "opts into thorough checking" and untyped exploratory code stays erased.

2. Unchecked escape hatch. asType: already is one and needs no new spelling. Under an implicit guard it would be the way to opt a hot site out.

3. Migration. Part 2 has none: no existing program changes meaning. Part 1 changes only programs where a comparison receiver on a typed parameter or field holds a non-number/string, which today answer by atom/number term order; those are bugs. Measured narrowing-cast counts (command below):

TreeNarrowing castsNotes
stdlib/src3all :: String from Dynamic, system_navigation.bt lines 907, 2241, 2489
examples/0
stdlib/test41 (+9 added by this ADR's fixture):: SomeActor from Object: spawn results and supervisor child lookups; no built-in-typed casts
tests/1:: E2EInitChildA from Object
benchmarks/1vs-elixir row 13b (s :: String := Erlang erlang integer_to_binary: a)
mint, buccaneer, catalinanot measuredrepos are not reachable from this session

Run in each satellite repo root, then add the totals to this table:

beamtalk type-coverage src --format json | python3 -c 'import sys,json; j=json.load(sys.stdin); print(j["narrowing_casts"])'
beamtalk type-coverage src --detail | sed -n '/^Narrowing casts:/,/^$/p'

For scale only: ADR 0147's survey counted literal-key at: reads (buccaneer 89, beamtalk-http 11, catalina 16). That is a proxy for dictionary casts, not a count of them, and BT-4736 has since moved the option aliases to shapes.

4. Map-shape types. ADR 0147 deletes the typed option-map reads, which were the largest cast family in the libraries, so a checked form would have had to fire there mostly for casts that no longer exist. What remains is where untyped data enters: decoded JSON/YAML (string keys, outside ADR 0147), FFI results, spawn results and the one shape assertion at a config boundary. Those are few and deliberate, which suits an explicit per-site form better than a blanket guard. A shape cast checks only "is a map" in v1; key and value checks would cost O(size) and are left to a validator.

5. Measured cost. See below. The short version: a built-in-class guard is about one is_* test; a user-class guard costs far more until BT-4769 lands; and part 1 costs about the same as the untyped guard.

Measured cost

Measured here (the committed benchmarks/vs-elixir/README.md figures):

RowWhatns/opReading
11ba + 1, a :: Integer (bare erlang:'+')0.23the only row whose speed depends on a trusted declared type
11ca + 1, a untyped (is_number guard + BIF)1.31guard delta is ~1.1 ns, 0 reductions
12bp isKindOf: VbPoint (user class, hierarchy path)6814what a user-class guard costs today if routed through isKindOf:

Re-running rows 11a-c, 12b and 14a in this cloud container was too noisy to use (11c came out at 8.0 ns against 1.3 committed); I rely on the committed figures and did not change them.

Rows that depend on a trusted declared type: only 11b (and the guarded typed-send rows 1a and 14a, which already stand behind a guard and are unaffected). Row 13b is the only vs-elixir row containing a narrowing cast, so it is the only row an implicit :: guard would slow. No row measures a comparison on a typed parameter, so part 1 has no row today; BT-4823 adds 11e (a < 1, a :: Integer). BT-3928 rejected an argument check partly because the stdlib sort and max: hot paths compare typed values with no benchmark to measure the cost; BT-4823 adds a receiver branch on those same paths, so its before/after numbers for them, not the 11b/11c delta, are the figure to trust.

Estimates, not measurements:

Prior Art

User Impact

Steelman Analysis

OptionStrongest case
Lint onlyLanguage designer: erasure is the contract; a guard that raises makes annotations load-bearing and splits "typed" from "untyped" semantics. Operator: zero cost, zero migration risk.
Guard every narrowing localNewcomer: "if I wrote :: Integer and it is not one, tell me now." Operator: the cast line is where the data entered; every later error is misleading. Tooling: one rule, no new selector.
Explicit checkedAs:Smalltalk purist: it is a message, like asType:. Erlang veteran: mirrors a function-head guard written where you want it. Operator: no behaviour change to ship.
Fix the comparison hole only (part 1)Language designer: it removes the one place where the contract is actually broken, for every route, at ~1 ns.

Tension: newcomers and operators want the implicit guard; the language designer and the satellite maintainers (unmeasured migration cost) want erasure kept. The no-cast route in the finding is why the explicit form does not give up much: the implicit guard would close only one of several routes into the same hole.

Alternatives Considered

Lint only (BT-4719 as shipped)

Cheapest, no semantic change. Rejected as the whole answer because it leaves the comparison hole open: a lint cannot see the Dynamic-argument route. Part 1 closes the hole for every route, so lint-only remains acceptable for the cast itself.

Guard every narrowing site, in all classes

The issue's proposal. Rejected for now: it closes only one route, makes annotations load-bearing in untyped code and the REPL, forces a migration that is unmeasured for three libraries, and a user-class guard is expensive today. It becomes attractive again under the conditions below.

Guard narrowing sites in typed classes only, warn first

The staged variant: a lint level narrowing-cast = "check", off by default, per package in beamtalk.toml. Keeps untyped code erased. Rejected for now because it makes generated code depend on a manifest setting, which sits badly with the no-image-mechanics rule for the REPL (no package) and because the explicit form delivers the same diagnostics site by site.

Explicit checked form (checkedAs:)

Adopted as part 2.

Checked narrowing with existing match: (not in the draft)

x match: [n :: Integer -> n; _ -> self error: ...] already narrows with a run-time check and needs no new selector. Weakness: verbose, and the _ arm is easy to omit or fill with a silent default. A stdlib helper built on match: would give checkedAs:'s call-site brevity without a new special form. Added at review; the owner should weigh it against part 2.

Ship part 1 only, defer part 2 (not in the draft)

With BT-4823 landing, the measured cast population (3 stdlib String casts, 0 in examples, actor casts in tests) shows no built-in-typed cast that needs a checked form. Deferring part 2 until the satellite counts exist costs nothing now and avoids adding a selector with unspecified actor/String semantics.

Recommendation, and what would change it

Adopt part 1 first; it is the real fix and does not depend on any decision about casts. Adopt part 2 as the cast story, and keep the lint. Defer the implicit guard.

I would move to a typed-class implicit guard (the staged variant) if:

I would drop part 2 and keep lint only if part 1 lands and the satellite counts show casts concentrated in code that already validates its input.

Consequences

Positive

Negative

Neutral

Open Questions

Implementation

Part 1 is BT-4823 (in progress, separate PR). Part 2 is not started, and no implementation issues are filed until this ADR is accepted.

Part 1 (BT-4823, not this ADR's work) touches receiver_is_statically_comparable / operator_guard (core_erlang/operators.rs) and the comparison half of field_types.rs (BareOperator::Comparison, trusted_param_types for comparisons); it flips the pinned assertions in narrowing_cast_wrong_value_test.bt. Part 2 touches the type checker (inference/send/receiver.rs, next to asType:), the dispatch lowering (dispatch_codegen/mod.rs), the shared routing::type_test renderer (one rendering, no copy), the narrowing-cast lint hint, and docs/beamtalk-language-features.md § Local Variable Type Annotations.

Migration Path

Part 1 (BT-4823): one release note; no source change expected. Part 2: none.

References