ADR 0134: Errors in No-Reply Handlers Crash the Actor

Status

Implemented (2026-10-21). Accepted 2026-10-19. Amends ADR 0065 § "Error contract" for handleInfo:; decides cast error semantics, which ADR 0054 left undecided.

Context

The problem

A Beamtalk actor receives three kinds of message:

KindSyntaxReply channelWhat happens when the handler raises today
Sync callcounter incrementyes — gen_server:callerror is returned to the caller as a value; actor continues
Async castrunner go!nonelogged at warning, discarded; actor continues with pre-call state
Raw messagehandleInfo: on a Servernonelogged at warning, discarded; actor continues with pre-call state

Sync semantics are right and are not touched by this ADR: the error has somewhere to go, and the caller decides. The other two rows are the subject of this ADR. Both are generated by the same noreply_error_arms in crates/beamtalk-codegen/src/core_erlang/gen_server/callbacks.rs — a logger:warning call followed by {'noreply', State}.

ADR 0065 chose log-and-continue for handleInfo: deliberately:

Beamtalk bakes this best practice in: errors in handleInfo: are logged and the server continues.

The "best practice" cited is the Elixir idiom of ending handle_info/2 with a catch-all clause:

def handle_info(_msg, state), do: {:noreply, state}

But that clause tolerates unmatched messages — a stale timer tick after a hot reload, a monitor DOWN the author forgot about. It does not, and was never meant to, swallow an error raised while handling a matched message. In Erlang and Elixir, a handle_info clause that matches and then raises crashes the process, exactly like handle_call and handle_cast. ADR 0065 conflated the two cases and, by swallowing both, bought stray-message tolerance at the price of let-it-crash.

For casts nothing was ever decided. ADR 0054 says the cast result is discarded (there is no caller to return it to), and the implementation extended that to the error.

Why it matters now

While planning the Thousand Island port (beamtalk-catalina/PLAN.md), the failure mode became concrete. A connection handler is a Server:

Server subclass: EchoConnection
  state: sock = nil

  handleInfo: msg =>
    msg match: [
      {#tcp, s, data} -> self onData: data socket: s;
      {#tcp_closed, _} -> self stop;
      _ -> nil
    ]

  onData: data socket: s =>
    self process: data                                         // raises on bad input
    (Erlang inet) setopts: s with: #(Tuple withAll: #(#active, #once))

Note (BT-4024): the examples here were corrected after acceptance. A match: arm body of the form pattern -> [ ... ] is a Block value that never runs (and fails to compile when it writes a field or sends to self), so multi-statement arms now call a method.

If process: raises, today the actor survives with its pre-call state — but the socket's {active, once} was consumed by the message that arrived and is never re-armed. The connection hangs forever: no close, no crash report, no supervisor restart, nothing for the operator to see beyond one warning line. The same shape applies to any Server that drives an external resource from handleInfo:: a GenStage-style producer that stops producing, a monitor that never re-monitors, a timer loop that never re-schedules.

A library author can work around it by wrapping every callback in on:do: and stopping the actor by hand — which is the universal boilerplate ADR 0065 set out to eliminate, reappearing in every serious Server.

Current state

Constraints

Decision

A message with no reply channel whose handler raises crashes the actor. This applies to handleInfo: on Server subclasses and to async ! casts on any actor. Sync calls are unchanged.

Concretely, the generated handle_info/2 and handle_cast/2 re-raise the caught error with its original class, reason and stacktrace instead of logging it. OTP then does what it always does: gen_server calls terminate/2 with the error as the reason, emits a standard crash report, exits the process, and the supervisor applies its restart policy. onExit: observers receive the error reason. Nothing in the runtime needs to know the message kind; the behaviour is the gen_server's own.

Unmatched messages remain tolerated, by two existing or cheap mechanisms rather than by swallowing errors:

  1. Server>>handleInfo: keeps its default no-op body. A Server that does not override it ignores everything, as today.
  2. A new lint, handleinfo-no-catch-all, warns when a handleInfo: body's outermost expression is a match: with no catch-all arm (_ -> or a variable pattern). This is the one place where "unexpected message" and "raise" meet, and the fix is one line.

What it looks like

Server subclass: PeriodicWorker
  state: count = 0

  initialize =>
    Erlang erlang send_after: 1000 dest: (self pid) msg: #tick

  handleInfo: msg =>
    msg match: [
      #tick -> self tick;
      _ -> nil
    ]

  tick =>
    self.count := self.count + 1
    Erlang erlang send_after: 1000 dest: (self pid) msg: #tick

Nothing changes for this class: unknown messages hit _ -> nil. If self.count + 1 could raise, the worker would now crash and be restarted by its supervisor, instead of silently never scheduling the next tick.

Server subclass: Fragile
  handleInfo: msg =>
    msg match: [
      #tick -> self tick
    ]
// ⚠ Warning (handleinfo-no-catch-all): `handleInfo:` matches on `msg` with no
//   catch-all arm; any other message will raise `#pattern_mismatch` and crash
//   this server. Add `_ -> nil` to ignore unexpected messages.

REPL session

worker := FailingServer spawn
worker onExit: [:reason | Transcript show: "exited: ", reason displayString]
Erlang erlang send: worker pid msg: #crash
// Transcript: exited: Error: deliberate handleInfo: error
worker isAlive                                               // => false

A supervised instance is restarted:

sup := WorkerSupervisor supervise
Erlang erlang send: (sup which: FailingServer) pid msg: #crash
// (gen_server crash report in the log, selector handleInfo:, with stacktrace)
(sup which: FailingServer) isAlive                           // => true  (new pid)

Error examples

A cast whose handler raises:

runner go!                 // method `go` raises
// crash report: ** Generic server <0.213.0> terminating
// ** Last message in was {cast, go, []}
// ** Reason for termination == error: #beamtalk_error{kind = runtime_error, selector = go, ...}

The crash report names the selector and carries the Beamtalk stacktrace, which is what the warning line carried before; the only difference is that the process is gone and the supervisor knows.

terminate: still runs when the class overrides it (which also makes it trap exits, BT-3596), with the wrapped error as reason:

Server subclass: Connection
  terminate: reason =>
    self.sock isNil ifFalse: [(Erlang gen_tcp) close: self.sock]

Single source of truth

The re-raise replaces noreply_error_arms in one place; handle_info/2 and handle_cast/2 keep sharing it, so the two paths cannot drift. No Erlang-side change is needed: beamtalk_actor:handle_info/2's handle_linked_exit already stops the actor on a non-normal 'EXIT', and a raised error reaches terminate/2 through gen_server itself.

Prior Art

PlatformError raised while handling a no-reply messageUnmatched message
Erlang gen_serverprocess exits with the error; terminate/2 runs; crash report; supervisor restartsfunction_clause crash unless a catch-all clause exists
Elixir GenServersame as Erlangsame; the community idiom is a trailing handle_info(_, state) clause, and use GenServer injects a default handle_info that logs and continues
Gleam OTP actorthe actor crashes (a panic is an Erlang error)impossible by construction: the message type is closed, Subject(msg) only carries that type
Akka (classic/typed)exception escapes receive → supervision strategy, default Restartunhandled(msg) → published to the event stream as UnhandledMessage; actor continues
Ponybehaviours cannot raise; partial functions must be handled at the call siteimpossible by construction (typed behaviours)
Pharoan unhandled error in a forked Process opens a debugger; the process is suspended, not continuedn/a — no mailbox

What we adopt: OTP's error semantics unchanged, which is what Gleam and Akka also converge on (crash → supervision). What we adapt: Elixir's unmatched-message tolerance, delivered as a default no-op and a lint rather than as error swallowing. What we reject: Akka's unhandled event-stream channel — Beamtalk has no event bus for it to go to, and a no-op default serves the same purpose.

User Impact

Steelman Analysis

Keep log-and-continue (status quo, ADR 0065)

Crash in handleInfo: only; defer casts

Opt-in class-side policy (class infoErrorPolicy => #crash)

Tension points

Alternatives Considered

Crash in handleInfo: only

Smallest change, zero users affected. Rejected because it leaves ! with the same silent-hang failure mode for exactly the same reason ("no caller to return to"), and the inconsistency would need its own ADR within months. Everything in the Implementation section applies to both paths through one shared helper, so the extra cost is the cast audit, not code.

Opt-in per class

Server subclass: Connection
  class infoErrorPolicy -> Symbol => #crash

Non-breaking, but keeps the trap as the default: every library wanting OTP semantics must remember to opt in, and a Server from a package you did not write cannot be trusted to crash. Policy knobs also multiply (one for info, one for cast?). Rejected.

Keep as-is; libraries wrap and self-stop

This is the Catalina workaround. It is on:do: + self stop around every callback — the boilerplate ADR 0065 was written to eliminate. Rejected.

Treat #pattern_mismatch from the outermost match: as "unmatched message" and ignore it, crash on everything else

Preserves stray-message tolerance without a lint. Rejected as too magical: it makes the top-level expression form change semantics, hides a real class of bugs (match: over a tuple you mis-shaped), and is invisible in tooling. A lint says the same thing at compile time.

Consequences

Positive

Negative

Neutral

Implementation

  1. Codegen (crates/beamtalk-codegen/src/core_erlang/gen_server/callbacks.rs): replace the body of noreply_error_arms with a re-raise of {Type, Reason, Stacktrace} (erlang:raise/3) so class and stacktrace are preserved; keep the arm shared by handle_info/2 and handle_cast/2. Update the doc comments on generate_handle_info / generate_handle_cast and the Core Erlang snapshot tests.
  2. Lint (crates/beamtalk-core/src/semantic_analysis/validators/): add handleinfo_catch_all_validators.rs with DiagnosticCategory::HandleInfoNoCatchAll: for each method named handleInfo: whose outermost expression is a match: send, warn unless some arm pattern is a wildcard or bare variable. Register in validators/mod.rs.
  3. Tests: in stdlib/test/server_handle_info_test.bt replace the two BT-1457 tests with testHandleInfoErrorCrashesServer (uses onExit: to observe the reason) and testSupervisedServerRestartsAfterHandleInfoError; add stdlib/test/actor_cast_error_test.bt for the cast path; a lint test over a fixture with and without _ ->.
  4. Docs: docs/beamtalk-language-features.md § "handleInfo: Semantics" and § "Unguarded late-slot reads in lifecycle hooks"; docs/ADR/0065-*.md Status line gains "Error contract amended by ADR 0134"; docs/ADR/README.md index row.
  5. Cast audit (Migration Path).

Affected components: codegen, semantic analysis (lint), stdlib tests, docs. No parser, runtime or REPL changes. Size: M (BT-3953).

Migration Path

Implementation Tracking

Epic: BT-3953 (under BT-3957, Catalina stdlib work) Issues: BT-3958 (codegen re-raise), BT-3959 (handleinfo-no-catch-all lint), BT-3960 (docs + REPL e2e), BT-3961 (package cast audit) Status: Implemented. Phase 1 (BT-3958, codegen and runtime re-raise), Phase 2 (BT-3959, handleinfo-no-catch-all lint) and Phase 3 (BT-3960, docs and the REPL e2e test tests/repl-protocol/cases/server_handle_info_crash.btscript) are done. Phase 4 (BT-3961) audits the ! cast sites in the downstream packages and changes no Beamtalk behaviour. Phase 1 covers compiled actors (noreply_error_arms) and for the runtime-path actor (beamtalk_actor:dispatch_cast/3, which also runs runtime-path continuations), so runtime and compiled actors agree. Both raise the error as a wrapped Exception object (beamtalk_exception_handler:ensure_wrapped/3 / reraise/1), always as an error-class raise. This differs from the plain re-raise described above in two ways. First, terminate: and onExit: see {Exception, Stacktrace} whatever was raised (a Beamtalk error, a raw Erlang badarith, an exit or a throw). Second, a throw cannot be taken by gen_server as the callback's return value. The compiled triple arm keeps the original stacktrace with primop 'raw_raise', because the caught trace is a raw trace that erlang:raise/3 rejects. continueWith: steps (BT-3968) share the cast error arms, so a raising continuation also crashes the actor. That includes a continuation requested in initialize: it runs after spawn has returned (BT-3992), so its error is not a spawn failure. A cast that calls self stopWith: and then raises crashes with the error rather than stopping with the requested reason.

Amendment (BT-4057): exit: #normal / #shutdown stop the actor normally

The "always an error-class raise" rule above has one exception. In the compiled triple-format arm, an exit whose reason is exactly normal or shutdown is a control signal, not a crash, so it is re-raised as exit with the original raw reason. terminate: and onExit: then see #normal / #shutdown instead of {Exception, Stacktrace}, the actor stops normally, and a transient child is not restarted. This applies to every such exit raised in a cast, handleInfo: or continueWith: step, including one raised deep in FFI or library code, not only one re-raised with Exception>>pass. Every other failure, including every throw, every abnormal exit and {shutdown, Term} (deliberately excluded), keeps the behaviour above. Runtime-path (hand-written Erlang) actors still normalise through beamtalk_exception_handler:reraise/1. See the CHANGELOG entry "Exception>>pass re-raises a caught exception unchanged (BT-4057)".

References