ADR 0133: Scope of Captured-Variable Mutation in Blocks

Status

Implemented (2026-11-03) — Phases 0–4 shipped under Epic BT-3901 (Phase 3 closed by BT-3913, 2026-11-02); Accepted 2026-10-18; Proposed 2026-10-18

Amended by ADR 0153 (2026-11-25), class variables in the escaping-block rule. Class variables are removed, so "a field or a class variable" reads "a field" and the class-variable write at home no longer applies.

Amended by ADR 0137 (2026-10-26, BT-4011 Phase 4), the actor-state halves of the escaping-block rule. An escaping block may now assign self.field (the BT-3922 actor half is deleted), a block that reads self.field and is passed to a self-send or stored is no longer rejected (BT-3952 is deleted), and a self-send or aliased self-send in a block keeps its state change (BT-3936, BT-3985, BT-3998 are deleted): inside the actor the block sees the live fields, elsewhere it reads its creation-time capture and a write raises actor_state_unreachable. The escaping class-variable assignment goes with the field half (ADR 0137 resolved question 2; ADR 0130's runtime already handles it). The local-threading rules are unchanged — an escaping block may still read but not assign a captured local (Tier2BlockNoReturnChannel), and the §Decision rule still governs locals and value-type fields. The actor-state-abroad lint warns where a field-touching block runs away from home.

Amended (2026-11-06, BT-4430): on:do: and ensure: are in place only when both operands are block literals. See the amendment under §Decision.

Decides between two destinations for the state-threading compiler. If accepted as written, this ADR supersedes ADR 0132 (callee-side threaded entry points) and ADR 0128 (opaque-callable fold threading for collection HOMs), and amends ADR 0041's "local mutations work in all blocks" to the rule in §Decision. ADR 0131 (outer-local rebinds through compiler-known constructs), ADR 0130 (class variables), ADR 0120 (value-type self threading), ADR 0118 (expression-level preludes) and ADR 0111 (the lowered-IR verifier) are kept.

Tracking: BT-3899. The hold recorded on BT-3865 (2026-10-18) lifts when this ADR is Accepted or Rejected.

Context

Problem statement

A Smalltalk block that assigns a variable it captured is a store into a context object the block shares with its home method, on a heap. The BEAM has neither half of that: variables are immutable, and no heap is shared between processes. Beamtalk therefore compiles every such assignment into versioned state threaded through every construct and, since ADR 0132, through every method call that takes a block.

The compiler has become the cost of that simulation. Measured on main at 0b7cb7a (2026-10-18):

MeasureValue
beamtalk-codegen, non-test lines88,900
of which state-threading machinery (control_flow, threaded_ir, threaded_entry, threaded_expr, threading_analysis, sequencing, nlr)about 34,000 (40%)
ThreadedIr verifier invariants (VerifyError variants)34
storage families threaded (State, SelfVt, Acc, Local)4
producer kinds dispatched by threaded_expression6
ADRs about this one mechanism10 of 136; the three most-cited ADRs in codegen are 0131 (261 citations), 0118 (211), 0111 (149)
Rust corpus proof tier (just test-corpus)about 9 minutes per run

Size alone would be acceptable if the machinery were converging. It is not:

Current state

Today's line, drawn by ADR 0131 §6 and narrowed by ADR 0132 Phase 1:

Constraints

Decision

A block may assign a captured local, a field or a class variable only where the compiler lowers the block in place: as the direct argument (or receiver, for whileTrue:/whileFalse:) of a control construct or a compiler-known collection message. A block that escapes may read captured variables but may not assign them. The compiler reports the assignment at compile time; the stdlib keeps the Tier 2 block protocol for its own collection messages on dynamic receivers, so the inline rule holds whatever the receiver's run-time type.

"Escapes" means any of: the block is assigned to a variable or field, returned from its method, passed as an argument to a method the compiler does not lower in place (any user-defined method, any stdlib method outside the known list), sent as a message argument to a class or actor, or stored in a collection or literal.

Consequently:

Code examples

What stays exactly as it is, and is what Beamtalk code actually writes:

total := 0
orders do: [:each | total := total + each price]
total                                    // => sum, threaded by the inline fold

count := 0
[count < 10] whileTrue: [count := count + 1]

found := nil
items do: [:x | (x > 3 and: [found isNil]) ifTrue: [found := x]]

// On a dynamic receiver the stdlib's own `do:` runs the Tier 2 block:
summary := 0
aDictionary do: [:v | summary := summary + v]

What becomes a permanent compile error, with the fix the message names:

sealed Object subclass: Twice
  class sealed twice: aBlock =>
    aBlock value
    aBlock value

Object subclass: Caller
  class run =>
    t := 0
    Twice twice: [t := t + 1]            // error (see below)
    t

  class runWell =>
    t := Twice twice: [1]                // the block answers a value instead
    t + (Twice twice: [1])

REPL session

beamtalk> total := 0. #(1, 2, 3) do: [:x | total := total + x]. total
6
beamtalk> t := 0. Twice twice: [t := t + 1]
error: block assigns captured variable `t`, but `twice:` is not a construct
       the compiler threads it through
  ┌─ repl:1:21
1 │ t := 0. Twice twice: [t := t + 1]
  │                      ^^^^^^^^^^^^ `t` is assigned here
  = help: return the new value from the block and assign it where it is called:
          `t := Twice twice: [t + 1]`
  = note: a block passed to a user-defined method, stored, or returned may read
          captured variables but not assign them (ADR 0133). The messages that
          thread assignments are the control constructs (ifTrue:, whileTrue:,
          to:do:, on:do:, ...) and the collection messages (do:, collect:,
          inject:into:, detect:ifNone:, ...).

Error examples

The same diagnostic fires for every escaping shape, naming the shape:

ShapeMessage fragment
f := [t := t + 1]"t is assigned in a block stored in f"
^[t := t + 1]"t is assigned in a block returned from run"
self forEach: [:o | t := t + o]"t is assigned in a block passed to forEach:, which is not a construct the compiler threads it through"
Erlang lists foreach: [:e | t := t + e] with: xs (passed as an FFI argument)"t is assigned in a block passed to Erlang lists foreach:with:, which calls it as a plain fun"
Logger onEvent: [:e | seen := seen + 1] (other process)"seen is assigned in a block passed to a class method; it would run in another process"

The run-time side keeps one structured error for the cases the compiler cannot see (a perform: with a runtime-built argument list, or a non-literal callable handed to a collection message): the existing stateful_block_dispatch, which already says "the block was not run". A block stored first and then laundered through FFI is not such a case: storing a block that assigns a captured local or a field is already an error (BT-3902, BT-3922), so no writing block exists to launder.

Amendment (2026-11-06, BT-4430): on:do: and ensure: are in place only when both operands are block literals. The rule above counts a block literal as in place when it is the direct argument of a control construct, and on:do:/ensure: are on that list. A half-literal send such as b ensure: [t := 9] or [t := 9] ensure: c meets that wording, but codegen runs the whole send as a closure when either operand is a block value (generate_ensure, control_flow/exception_handling.rs; block_facts::inlined_exception_blocks), so the literal half escapes with it and its write would be dropped. BT-4430 (#4844) made the analyser reject such a write with this ADR's message; this amendment makes that the rule. Threading the literal half anyway would make "in place" depend on the other operand and would need a one-literal-arm variant of every exception producer. The rewrite is one wrapper, [b value] ensure: [t := 9], and the error says so. A ^ or a read in such a block is unaffected, and an actor field write is accepted (it writes the live cell, ADR 0137). Tests: tests/repl-protocol/cases/bt4430_ensure_stored_receiver.btscript and the analyser tests added by #4844.

Amendment (BT-3936): a self-send in a closure that changes actor state. A block that assigns nothing can still contain self record: x, where record: writes a field. When that block is a real closure (a block passed to the actor's own method, or stored), the send dispatches against the State the closure captured at creation, and the callee's new State has nowhere to go: the closure answers one value. This is not an escaping-block assignment, so the compile-time rule above does not see it. It is a run-time check in the one place an actor self-send dispatch is generated (dispatch_codegen.rs; every form: threaded, discarding, sealed), active only inside a closure (a Tier 1 closure). It compares the callee's returned State with the State it was dispatched against using =:= (pointer identity first, so the read-only case is cheap). A different map is compared once more with the codegen-internal __local__<name> threading keys stripped (beamtalk_actor:strip_local_temps/1, the helper the gen_server boundary uses), because a read-only callee that rebinds a local through a conditional, on:do: or ensure: changes only those keys. Equal answers normally; different raises #beamtalk_error{kind = stateful_block_dispatch} carrying the selector and the hint "A self-send inside a block changed actor state, but the block cannot return it; return the value and assign it in the method instead". No threading is reintroduced and no surrounding lowering changes. A literal block the compiler inlines into the method (self.items do: [...]) is not a closure and still threads State, so its self-sends keep their changes. A Tier 2 closure (StateAcc in, {Result, StateAccN} out) carries State back to its caller, so it is exempt; a consumer that cannot take that state back already raises stateful_block_dispatch itself.

The error is an ordinary Error: an on: Error do: written inside the closure around the self-send catches it. That is the user's explicit choice to catch every Error, and the error stays catchable rather than being made special.

Value types and class methods do not need the check: a Value method cannot assign a slot, so a self-send never changes anything to lose, and a class method has no State (class variables are written in place, ADR 0130). A user-defined binary selector sent to self in an actor (self + 5) compiles through the same self-dispatch as a unary or keyword send (BT-3985), so it threads State at method level and meets this check in a closure; in a class method it is a direct class-side send. A super send inside a closure (the beamtalk_dispatch:super/5 instance path) runs the same comparison on its reply. A super send inside a literal block the compiler would otherwise inline (a do: loop, a conditional branch, or a list-op host such as self.items collect: [:x | super bump: x]; also select:, inject:into:, detect:) is not a State-threading position, so a callee that changes state raises here instead of threading; threading it is a separate piece of work (BT-3995).

Prior Art

Smalltalk-80 and Cog. Smalltalk-80 blocks were not real closures: a block shared its home context's temporaries and could not be re-entered. Full closures came later, and modern Pharo/Squeak compilers (Cog) classify blocks as clean, copying or full, find the temps a block writes, and hoist them into a heap-allocated "remote temp vector" shared by reference between block and home. Beamtalk's Tier 1/Tier 2 split and its threading analysis are the same classification. The difference is the last step: Cog allocates one shared array; the BEAM cannot share by reference, so Beamtalk must thread the vector through every return value. This ADR keeps Cog's analysis for the inline case and declines to simulate the shared heap for the escaping case.

Erlang and Elixir. Variables are immutable; a closure captures values. Idiomatic accumulation is lists:foldl / Enum.reduce returning the new accumulator, exactly the "return a value from the block" idiom the diagnostic recommends. Elixir users expect Enum.each(xs, fn x -> total = total + x end) to warn and do nothing; this ADR makes the Beamtalk equivalent a compile error with a fix, which is stricter and kinder.

Gleam. No mutation at all; list.fold is the only idiom. Beamtalk keeps more than Gleam (inline assignment in loops and conditionals) because do:-with-accumulator is the dominant Smalltalk shape and compiles to a fold anyway.

Newspeak. Full closures with shared mutable contexts, like Pharo; nothing to borrow on this point beyond the diagnostic style.

Pony and Akka. Actor languages that forbid a closure sent to another actor from capturing mutable state (Pony's reference capabilities make it a type error). The "sent to another process" row of the error table is the same rule.

Adopted: Cog's write-analysis for the inline case; Erlang's return-the-value idiom as the recommended fix; Pony's rule for blocks crossing an actor boundary. Rejected: simulating a shared mutable heap across method calls and processes (ADR 0132's approach).

User Impact

Newcomer (Python/JS/Ruby). Loops and conditionals that accumulate into a local work as expected. Passing a mutating lambda to a user function is the one thing that errors, with a message that shows the fix. Python's nonlocal and JS closure mutation make this surprising for a moment; the error is discoverable at compile time and in the REPL, never at run time.

Smalltalk developer. This is a real departure: in Pharo, Twice twice: [t := t + 1] answers 2. The justification is §4 of the principles: the behaviour depends on a shared heap the platform does not have, and the Smalltalk name (blocks, do:, inject:into:, ^ from a block) is kept everywhere. Everything in Symphony's 56 files already fits the rule.

Erlang/Elixir developer. This is how they already think. Generated code for a user HOM becomes a plain fun call, debuggable with dbg, with no {Result, Acc} tuples or __t2_ entries in stack traces.

Production operator. Fewer generated functions per module (no second entry per block-taking class method), no metadata maps to keep in sync across hot reload, and the runtime dispatch (beamtalk_dispatch) loses two gates.

Tooling developer. The LSP can report the diagnostic at the assignment with a code action ("return the value instead"). Static analysis gets simpler: "does this block escape" is a syntactic question with one answer, not a fixpoint over the unit.

Steelman Analysis

A. Keep the promise; consolidate onto one ThreadedIr pass (rejected)

The strongest point here is the BEAM veteran's, and this ADR adopts it for the inline case (§Implementation Phase 3). It is rejected for the escaping case because the IR does not remove the two costs that are intrinsic to it: a cross-method calling convention (two entries per block-taking method, metadata, a runtime resolution walk, Phases 2 to 6 of ADR 0132) and a cross-process question that has no good answer (a block sent to another process assigning a local of a method that may have returned is a race, not a feature). The measured demand is zero.

B. Inline-only mutation, escaping blocks read but do not assign (chosen)

C. Mutable reference cells (process-dictionary or atomics boxes)

D. Status quo: keep lowering per construct, finish ADR 0132 as planned

Tension points

Alternatives Considered

A. Keep the promise and consolidate the lowering onto one ThreadedIr pass

Described above. Its implementation half is adopted for the inline case (Phase 3); its semantic half is rejected.

C. Mutable reference cells

Described above; rejected.

D. Status quo

Described above; rejected.

E. A declared annotation (threads: aBlock) instead of a rule

A method could declare which block parameter it threads, making the escaping case opt-in. Rejected: it keeps the whole ADR 0132 mechanism for the annotated methods, so it removes none of the cost, and it moves the burden to library authors for a feature no scanned codebase uses.

F. Call-site specialization (inline a sealed same-module callee)

ADR 0128 Option 4 / BT-3610. Rejected: it covers only sealed same-module callees, needs the inlined body to be re-lowered per call site, and still leaves every other callee at the §6 error, so it is a narrower B with more code.

Consequences

Positive

Negative

Neutral

Implementation

Phases, each its own PR or small epic; /plan-adr turns these into issues.

Phase 0: statuses and holds (S). Mark ADR 0132 and ADR 0128 Superseded by this ADR, amend ADR 0041's claim, update docs/beamtalk-language-features.md §Blocks and docs/agents/expanded.md. Close BT-3872 (#4374 unmerged), BT-3873, BT-3874, BT-3885 follow-ups and BT-3893; close BT-3865 as superseded.

Phase 1: the diagnostic (M). One recognizer in beamtalk-core (semantic_analysis::block_escape, extending the existing ADR 0131 §6 check) answers "does this block literal escape, and which captured variables does it assign". It emits the diagnostic above at the assignment span, with the shape-specific fragment and the fix. The ADR 0132 §6 inventory's PIN-BUG cases flip to positive diagnostic tests. The LSP reports it as a diagnostic with a code action. The note's list of known constructs is generated from state_threading_selectors.rs so the list has one source (there is no beamtalk explain command; the note carries the list). Decide here, with a test, what a uses: Enumerable class's expanded inject:into: / collect: / select: do with a Tier 2 block: they are stdlib code, so they may honour the Tier 2 protocol as the stdlib collections do (the block then threads through the user's do: only if that do: is also protocol-provided or forwards to a stdlib collection), or they refuse it with stateful_block_dispatch like any user method. Either answer is acceptable under this ADR; the one that is not is dropping the write. Decided (BT-3903): honour, with the BT-3916 receiver guard; see the amendments under § Consequences.

Phase 2: removal (L). In dependency order: the caller-side hook that was never emitted; send_threaded/4, call_threaded/3, call_threaded_with_arguments/3, is_tier2_block/1, lookup_threaded_*, threaded_target and the tier2_* metadata in the runtime, with their tests; threading_abi.rs and the generated header; threaded_entry.rs, the __t2_ exports, specs and Tier2Entry metadata in codegen; the Acc family and its verifier checks (AccAsScratchSeed, OwnLocalKeyInAcc, NlrInThreadedBody, the Acc rows of NlrSlotShapeMismatch, ConstructFamilyDropped for Acc); tier2_callee.rs and MethodInfo::threading_params with the generated builtins regenerated; opaque_fold.rs and FoldCarrier, so a non-literal callable in an actor method is the plain send. The shared tier2 conformance fixture and the threaded_* EUnit modules go with them. Stdlib .beam output must be byte-identical except for the two removed empty metadata keys.

Phase 3: consolidate the inline lowering onto ThreadedIr (XL). Make ThreadedIr the emission input for whole method bodies: every assignment is a Bind wherever it sits (closes the BT-3860 class), every construct is a frame with explicit families (closes BT-3891, BT-3875, BT-3897), the legacy write-backs go (BT-3833), and ThreadedBodyState-style generator globals are owned by the frame stack. Acceptance: every open child of BT-3883 is a passing corpus case, and BT-3841's 733-shape measurement reports zero silent drops. Expression codegen (sends, literals, primitives, the typed-leaf Document emission) is unchanged.

Affected components: beamtalk-core (semantic analysis, one new recognizer, one removed), beamtalk-codegen (removal, then the IR pass), the runtime (beamtalk_dispatch, beamtalk_class_dispatch, beamtalk_class_metadata), the LSP (diagnostic plus code action), docs. Parser and REPL protocol are unchanged; the REPL inherits the diagnostic.

The one single-source-of-truth module this touches is state_threading_selectors.rs: the known-construct list is already the one list codegen, the index and the §6 check read, and Phase 1 makes explain read it too rather than restating it. No Rust/Erlang conformance fixture is needed after Phase 2 because nothing about this rule crosses the boundary; the Tier 2 block shape that remains is already pinned by the existing block protocol tests.

Migration Path

Implementation Tracking

Epic: BT-3901 Issues: BT-3902, BT-3903 (Phase 1); BT-3904, BT-3905, BT-3906, BT-3907, BT-3908 (Phase 2); BT-3909 (Phase 2/3 boundary); BT-3910, BT-3911, BT-3912, BT-3913 (Phase 3); BT-3914 (LSP code action); BT-4003 (the BT-3912 residuals made compile errors, among them the permanent ensure: rule under Consequences) Status: Implemented (2026-11-03) — Epic BT-3901 done; all phases complete. BT-3910, BT-3911 and BT-3912 lowered every local assignment, conditional/match/handler arm and loop/fold/REPL body through frames; BT-3913 retired DENY_SET/ALLOW_SET (the 733-shape oracle reports zero silent drops), moving ADR 0131 to Implemented.

The ADR 0131 residuals epic BT-3883 is cancelled and replaced by BT-3901: BT-3862, BT-3858 and BT-3843 are absorbed by BT-3902 and BT-3903; BT-3860, BT-3833, BT-3841, BT-3861, BT-3875, BT-3876, BT-3878, BT-3891 and BT-3897 are duplicates of the Phase 3 issue that closes each of them. Three codegen residuals filed outside BT-3883 (BT-3849, BT-3853, BT-3854) are duplicates of BT-3911 and BT-3912 for the same reason, and BT-3884 moves under BT-3901 next to BT-3902.

References