ADR 0135: Supervisor Instances and Start Arguments

Status

Implemented (2026-10-21) — BT-3963 (instance-side configuration, args into init) and BT-3962 (spawn family, nesting, discovery) done 2026-10-20 under epic BT-3957; BT-4033 amendment done 2026-10-21. Accepted (2026-10-20); amended 2026-10-21 (BT-4033, hang rule (b) covers every actor child). Extends and amends ADR 0059 and delivers ADR 0080 § Future Work #4 ("anonymous supervisor start"). Specifies BT-3962 and BT-3963.

Context

What a supervisor is today

ADR 0059 made supervisors classes whose configuration is a set of class-side methods: class strategy, class children (static) or class childClass (dynamic), class maxRestarts, class restartWindow, later class initialize: sup (BT-1285), class maxChildren (BT-3964) and class childShutdown (BT-3965). Starting one is MySup supervise, which the runtime turns into

supervisor:start_link({local, 'bt@MySup'}, 'bt@MySup', [])   % supervisor_codegen.rs generate_sup_start_link

so every supervisor class is a singleton per node, registered under its module name, supervise is idempotent (ADR 0080's "idempotent-startup convention": Ok(sup) whether this call started it or it was already running), and MySup current is whereis(Module) (beamtalk_supervisor:current/1). The generated init/1 ignores its argument and reads the class-side methods by direct module call (static_init/2, dynamic_init/2). supervise runs in the class gen_server, so a top-level supervisor is linked to the class process.

ADR 0059 was explicit about the consequence: "only one instance of WebApp can run at a time … If two instances of the same topology are needed, define two classes." It also said that an ad-hoc DynamicSupervisor new supervise would use anonymous registration; that was never implemented. ADR 0080 listed the gap as Future Work #4: "Anonymous supervisor start — supervisor:start_link/2 without {local, Name}. Enables per-tenant / per-request supervision trees where the same Supervisor subclass is instantiated multiple times. Requires a companion ADR on how auto-registration-by-class-name interacts with explicit anonymous starts."

This is that ADR.

Why "define two classes" stops working

The Thousand Island port (Catalina, beamtalk-catalina/PLAN.md) needs this tree per running server, with numAcceptors (default 100) copies of the middle layer:

ServerSupervisor (restForOne)                  args: ServerConfig
├── Listener
├── AcceptorPoolSupervisor (oneForOne)         children: 1..numAcceptors
│   └── AcceptorSupervisor[i] (restForOne)     args: {i, server, config}
│       ├── ConnectionSupervisor (dynamic)     childClass: config handler   maxChildren / shutdown: per server
│       └── Acceptor[i]                        holds its parent AcceptorSupervisor's handle
└── ShutdownListener

Nothing here can be a class-per-instance: the count comes from an option, the handler class is the user's, num_connections and shutdown_timeout are per-server options, and a node may run several servers plus a test suite that starts one per test. Thousand Island also passes each supervisor's own pid down to its children ({server_pid, self(), config}), which a class-side configuration method has no way to express. Today's runtime hard-wires a nested supervisor child to {Module, start_link, []} with id => Class (build_child_spec/2 and the is_supervisor branch of spec_to_otp/2), so a parent cannot even hold two children of one supervisor class, and a DynamicSupervisor whose child class is a supervisor can start only one child.

The same shape already exists in first-party code: beamtalk-exdura's ActivityWorkerSupervisor is a singleton shared by every ActivityWorkerPool ("maxRestarts => 1000 since all pools share this singleton supervisor") where one supervisor per pool is what the design wants; beamtalk-watcher/src/watcher.bt avoids Supervisor because "two Watchers ended up silently sharing one Dashboard"; and the supervisor tests in stdlib/test run serial because each supervise starts the one name-registered process for its class (e.g. dynamic_supervisor_max_children_test.bt, dynamic_supervisor_start_child_name_test.bt).

Constraints

Decision

Three changes, one of them breaking: supervisor classes gain the spawn family (§1); configuration moves from class-side methods to instance-side methods read from the instance being started (§2, breaking but mechanical, with a compiler fix-it); and supervisor classes answer supervisionSpec with integer ids allowed (§3). Two narrow behaviour changes ride along: supervise no longer links the tree to the class process (§1), and bare nested supervisor classes become anonymous children (§3).

1. Supervisor classes gain the Actor spawn family; supervise becomes sugar over it

Message (class side)RegistrationReturnsExists today?
supervise{local, Module}, idempotent, unlinkedResult(Self, Error)yes; now sugar over the spawn start helper, no longer linked to the class process
spawnnone (anonymous), unlinkedSelfnew
spawnWith: argsnone, unlinkedSelfnew
spawnAs: name{local, name}, unlinkedResult(Self, Error)new
spawnWith: args as: name{local, name}, unlinkedResult(Self, Error)new
named: namelookup + class checkResult(Self, Error)new (mirrors Actor named:)
currentlookup by ModuleSelf | Nilyes, unchanged

The vocabulary and semantics are Actor's (actor.bt): spawn/spawnWith: raise on start failure, as actor spawn does, with kind #supervisor_start_failed (the kind supervise already uses, where actor spawn uses #instantiation_error). supervise keeps meaning "ensure the application-level instance of this class is running"; spawn means "make one". That is OTP's own split between supervisor:start_link/3 with a name and start_link/2 without.

Named instances. The as: forms return a Result because a name can be taken; a taken name gives #name_registered, the kind actors return. named: returns Result(Self, Error) with the same error kinds as Actor named:: #name_not_registered for an unknown name, #wrong_class for a process that is not a supervisor of this class or a subclass, and #type_error for a non-Symbol name. Names come from a bounded, statically known namespace (ADR 0079): a per-server or per-tenant name must be one of a fixed set, never built from runtime data. Named instances are what observer, a remote shell and sys:get_state see by name, so an operator can find a running Catalina server without holding its handle.

supervise is not a second mechanism. It is defined as the spawn start helper, registered under the class's own module name and made idempotent:

// Supervisor / DynamicSupervisor (class side), in effect:
class supervise -> Result(Self, Error) =>
  // the spawn start helper, registered as {local, <module name>}; if already started, answer the running instance

It goes through the same runtime start helper as spawn/spawnWith: (see "Single source of truth"), keeps the two properties nothing else provides (idempotence and a class-derived name that mints no atom and that current finds), and keeps the initialize gate (await_initialized). OTP has no idempotent start; Beamtalk keeps one because re-evaluating MySup supervise in a REPL or workspace, and the [application] boot path, must not fail on the second run. So there is one way to start a supervisor plus one convenience, and the docs' rule supervise ensures, spawn creates describes a single concept.

srv := ServerSupervisor spawnWith: config                          // anonymous, one per Catalina start:
srv2 := ServerSupervisor spawnWith: otherConfig                    // a second one on the same node
http := (ServerSupervisor spawnWith: cfg as: #http_server) unwrap  // registered; the name must be bounded
(ServerSupervisor named: #http_server) unwrap == http             // => true
ExduraSupervisor supervise                                         // still the idempotent singleton
srv stop                                                           // per instance; srv2 keeps running

2. Configuration moves instance-side and is read from the instance being started

Supervisor configuration stops being class-side. Each setting is an instance method, and the runtime calls it on the supervisor being started, from inside that supervisor's init/1. So self is the supervisor's own handle and self args is its start args. There is one form per setting, with the default on the base class:

// Supervisor (stdlib/src/supervisor.bt), instance side
childSpecs -> List => self subclassResponsibility        // was: class children
strategy -> SupervisionStrategy => #oneForOne            // was: class strategy
maxRestarts -> Integer => 10                             // was: class maxRestarts
restartWindow -> Integer => 60                           // was: class restartWindow
args -> Object => ...                                    // new: the start args, nil for supervise / spawn

// DynamicSupervisor (stdlib/src/dynamic_supervisor.bt), instance side
childClass -> Class => self subclassResponsibility       // was: class childClass
maxChildren -> Integer | Symbol => #infinity             // was: class maxChildren
childShutdown -> ShutdownTimeout | Nil => nil            // was: class childShutdown
maxRestarts -> Integer => 10
restartWindow -> Integer => 60

(The literal defaults are today's class-side defaults, moved unchanged.)

A static supervisor reads exactly as before, without class:

Supervisor subclass: WebApp
  strategy => #oneForAll
  childSpecs => #(DatabasePool HTTPRouter)

The Catalina tree:

Supervisor subclass: AcceptorPoolSupervisor
  childSpecs =>
    ((1 to: (self args at: #config) numAcceptors) collect: [:i |
      AcceptorSupervisor supervisionSpec withId: i
        withArgs: #{#id => i, #server => (self args at: #server), #config => (self args at: #config)}]) asList

Supervisor subclass: AcceptorSupervisor
  strategy => #restForOne
  childSpecs => #(
    (ConnectionSupervisor supervisionSpec withId: #connections withArgs: (self args at: #config)),
    (Acceptor supervisionSpec withId: #acceptor withRestart: #permanent
       withArgs: #{#id => (self args at: #id), #parent => self, #config => (self args at: #config)}))

DynamicSupervisor(Handler) subclass: ConnectionSupervisor
  childClass => self args handler
  maxChildren => self args numConnections
  childShutdown => self args shutdownTimeout

3. Supervisor classes answer supervisionSpec, and child ids may be integers

Today supervisionSpec lives on Actor and a nested supervisor child is built by hand with start_link/0 and id => Class. Now:

Behaviour change: a bare supervisor class in childSpecs becomes an anonymous child. build_child_spec/2's hand-built supervisor branch is deleted; a bare class goes through Class supervisionSpec → childSpec → spec_to_otp/2 like any other child (see "Single source of truth"). So a nested InnerSup is no longer registered under its module name: InnerSup current no longer finds it, and InnerSup supervise no longer returns the nested instance (it starts a separate singleton). Use parent which: InnerSup or BT-3966's by-id lookup instead. Nothing in this repo or in the sibling beamtalk-* repos relies on the old behaviour (grepped), and the change removes a footgun: two parents that each nest the same bare supervisor class used to fail with already_started.

REPL session

pool := AcceptorPoolSupervisor spawnWith: #{#config => cfg3, #server => nil}   // cfg3 numAcceptors = 3
pool count                                   // => 3
pool whichChildren collect: [:c | c id]      // => #(1, 2, 3)   (BT-3966)
pool2 := AcceptorPoolSupervisor spawnWith: #{#config => cfg1, #server => nil}
pool == pool2                                // => false
AcceptorPoolSupervisor current               // => nil   (spawned instances are not "current")
pool args at: #config                        // => cfg3
pool stop. pool2 stop

Error examples

ServerSupervisor spawnWith: cfg as: #http_server
ServerSupervisor spawnWith: cfg as: #http_server
// => Result error: #name_registered  (the kind actors return from spawnAs:)

ServerSupervisor named: #no_such_server
// => Result error: #name_not_registered

ServerSupervisor named: #counter                     // #counter is an actor
// => Result error: #wrong_class

DynamicSupervisor subclass: Pool
  class childClass => Worker
// ⛔ Error: `class childClass` is no longer read by DynamicSupervisor; define it on the
//    instance side (drop `class`): `childClass => Worker`.

Supervisor subclass: Broken
  childSpecs => self count > 0 ifTrue: [#()] ifFalse: [#(Worker)]
Broken spawn
// => raises #supervisor_start_failed: configuration methods run inside the supervisor's
//    init; use `self args` and return specs, do not send messages to `self` (calling_self).

pool := AcceptorPoolSupervisor spawnWith: #{}        // childSpecs: self args at: #config is missing
// => raises with kind #supervisor_start_failed, wrapping the error from inside init —
//    same as a failing `class children` today.

ConnectionSupervisor spawnWith: (cfg withNumConnections: -1)
// => raises #supervisor_start_failed with the maxChildren validator's hint (from init/1)

Single source of truth

Prior Art

PlatformInstancesArgs
Erlangsupervisor:start_link(Mod, Args) anonymous; start_link(Name, Mod, Args) namedArgs → Mod:init(Args) returns {ok, {Flags, ChildSpecs}}; one module serves any number of trees; self() in init/1 is the supervisor
Elixiruse Supervisor; start_link(arg) with optional name:; placed in a parent as {MySup, arg}init(arg) builds children from arg; DynamicSupervisor has max_children and heterogeneous start_child/2
Gleam gleam_otp`static_supervisor.new(strategy)> add(...)
Akkasupervision is a property of every actor; no supervisor objectsn/a
Pharo / Squeakno supervision; instances come from class-side creation messages (new, on:, with:)arguments are keyword parts of the creation message

Adopted: Smalltalk's class-side creation messages (the spawn family, with keyword arguments), Erlang's named/anonymous split and init(Args), Elixir's "a supervisor is placed in its parent as {Module, arg}" (our supervisionSpec withArgs:), and Thousand Island's use of self() in init/1 (our self in childSpecs). Adapted: Beamtalk keeps per-setting methods (ADR 0059) rather than one init returning a spec, and moves them to the instance, where Erlang's init/1 already lives. Rejected: Gleam's builder value — Beamtalk supervisors are classes, and a builder would be a second way to say what childSpecs already says.

User Impact

Steelman Analysis

B: supervise always starts a fresh instance; superviseAs: registers

C: class-side class registration => #singleton | #none

D: single init: args returning the whole spec (Elixir style)

F: keep class-side configuration and add …For: args hooks (this ADR's first draft)

E: a new verb (start / startWith:) instead of spawn

G: an ancestor accessor (self supervisor, from '$ancestors') instead of passing self down

H: defer the named forms (spawnAs:, named:, withName:)

Arguments for shipping them now (adopted)

Tension points

Alternatives Considered

B: supervise starts fresh; superviseAs: registers

Rejected on merit (see Tension points): an idempotent "ensure it is running" start is needed for re-evaluated REPL/workspace code and the [application] boot path, and as sugar over the spawn helper it adds no mechanism. Everything B offers is available as spawn. (It would also break ExduraSupervisor supervise valueOrDo:, current after supervise, the repl-protocol supervisor.btscript / supervisor_initialize.btscript cases and ADR 0080's idempotent-startup convention, but that is secondary: this ADR breaks configuration anyway.)

C: class-side registration switch

Rejected: a class could not be both an app root (named) and a per-test instance (anonymous), which Catalina's test suite needs; and the meaning of supervise would depend on a declaration elsewhere.

D: class init: args returning a spec

Rejected: ADR 0059 chose per-setting methods and documented why. Moving those methods to the instance gives D's main benefit (configuration computed from init's argument, with access to the supervisor) without collapsing every setting into one return value that each subclass must rebuild.

E: start / startWith: instead of spawn

Rejected: it would avoid the intrinsic carve-out, but start: is a common user facade name (symphony, watcher, exdura, http, Catalina), and the spawn family already carries the named / unnamed / named: semantics users know from Actor.

F: keep class-side configuration and add …For: args hooks

The earlier draft of this ADR: every class-side setting gains a keyword variant (childSpecsFor:, strategyFor:, … seven in all), plus childSpecsFor:supervisor: for the parent handle, with delegating defaults. Rejected: two forms of every setting, a compile error for classes that define both, a pre-start check that evaluated the methods twice, and a special variant just to pass self. Instance-side methods give the same power with one form per setting, at the cost of a mechanical migration.

G: an ancestor accessor (self supervisor, from '$ancestors') for the parent handle

Deferred: with instance-side configuration the parent passes self explicitly, which is visible in the code and needs no pid-to-handle mapping. An accessor can be added later, without breaking anything, for children that were not given their parent.

H: defer named supervisor instances

Rejected: operability. A server started with spawnWith: alone is only a pid to observer and remote shells; spawnWith:as: gives it a name, and the named forms mirror Actor exactly on the same start helper.

children: as the configuration name

Rejected: with BT-3966's live-children sup children, the same name would mean "running children" and "child specs" on the same object.

superviseWith: args

Rejected: the instance's identity (singleton or not) would depend on whether args were passed.

Keep singletons; have Catalina generate classes

Rejected: numAcceptors is a runtime option and the handler class belongs to the user; code generation at start time is not a thing Beamtalk does.

Consequences

Positive

Negative

Neutral

Implementation

BT-3963 (instance-side configuration, initialize, args into init/1; size L, ~3 days; first):

  1. Stdlib: move every configuration method to the instance side (childSpecs, strategy, maxRestarts, restartWindow; childClass, maxChildren, childShutdown), with docs (including the no-messages-to-self and hang rules). Migrate every supervisor in stdlib, tests, examples and docs.
  2. Codegen and runtime: supervisor_codegen.rs emits start_link/1, start_link/2 and init(Args) → static_init/3 / dynamic_init/3, which build the handle and read each setting by instance dispatch; map calling_self to #supervisor_start_failed with the hint; delete precheck_dynamic_config and the class-side config readers (class_config_value, call_class_method_direct for configuration); '$beamtalk_child_class' and pool_child_class/1 for startChild/1,2,3.
  3. Validators (supervision_validators.rs): check_class_side_supervisor_config (compile error with fix-it for each removed class-side selector) and check_children_supervision_policy reading childSpecs bodies.
  4. Tests: stdlib/test/supervisor_start_args_test.bt and bt3963_* fixtures; validator unit tests; eunit for the args-aware resolver.

BT-3962 (spawn family, nesting, discovery; size L, ~3–4 days; after BT-3963): 5. Stdlib (supervisor.bt, dynamic_supervisor.bt, supervision_spec.bt): spawn, spawnWith:, spawnAs:, spawnWith:as:, named:, supervisionPolicy, supervisionSpec (class side); args and initialize (instance side; class initialize: removed); withId: accepts Symbol | Integer. 6. Codegen: (start_link/1,2 and init(Args) come from BT-3963.) dispatch_codegen.rs try_handle_spawn_await and the class_self_spawn arm lower supervisor receivers to the runtime start helper in the caller; type_checker/validation.rs skips the spawnWith: state-key check for them. 7. Runtime (beamtalk_supervisor.erl): one start helper for anonymous (unlink, init gate, pg:join) and named (#name_registered) starts; named/2; with supervise (start_link_supervisor/2) rewritten onto it (registered under the module, already-started → existing instance, unlinked); the beamtalk_supervisor_new post-dispatch hook sends instance-side initialize; build_child_spec/2 supervisor branch deleted; spec_to_otp/2 starts supervisor children through the start_supervisor_child trampoline (with the start_link/0 fallback for old modules); start_dynamic_supervisor_child/2,3,4 on the same trampoline; pg join in init/1 for top-level starts; widened id specs in whichChildren/1 and beamtalk_process_navigation:classify/3; args stored for sup args. beamtalk_process_navigation:default_root_pids/0 adds the pg group. 8. Tests: stdlib/test/supervisor_instances_test.bt (not serial) and bt3962_* fixtures; eunit for spec_to_otp/2 supervisor mapping, no-link, pg membership, named/2; codegen tests for the carve-out and start_link/1,2; a type-checker test for spawnWith: on a supervisor class.

Docs (both issues): language-features § Supervision Trees gets an "Instances and arguments" subsection (supervise ensures, spawn creates; unlinked; nesting via supervisionSpec; integer ids; instance-side configuration table; args/restart rule; parent-handle rule) and replaces "define two classes"; ADR 0059 status note; ADR 0080 Future Work #4 marked delivered.

Affected components: stdlib, runtime, codegen, type checker, semantic analysis, tests, docs. No parser change.

Migration Path

None for top-level code: supervise's result and idempotence, current, [application] supervisor = and Workspace startSupervisor: are unchanged, as is the withArgs: meaning for actor children. supervise no longer links the started tree to the class process; no code change is needed, and a crashing tree now leaves its class process alive. Configuration moves to the instance side (breaking, mechanical): drop class from strategy, maxRestarts, restartWindow, childClass, maxChildren, childShutdown, rename class children to childSpecs, and turn class initialize: sup into instance-side initialize (with self for sup). The compiler rejects the old forms with that fix-it, so nothing silently changes behaviour. One further behaviour change: a supervisor nested as a bare class in childSpecs is now an anonymous child, so InnerSup current returns nil for it; use parent which: InnerSup or BT-3966's by-id lookup. A DynamicSupervisor with a supervisor child class now starts anonymous children (before, the second startChild always failed). Packages that want per-instance supervisors (exdura's ActivityWorkerSupervisor) opt in by calling spawnWith: where they called supervise.

References