Async & Concurrency
Maxon has two concurrency tools:
async/awaitstart a coroutine of the current green thread. Coroutines overlap waiting — for a timer, a socket, a child process — without creating threads.spawnstarts a service: state of its own that handles one message at a time, on whichever green thread takes its next message, in parallel with other services on other processors. You talk to it through messages.
Both run on the runtime’s scheduler, which maps green threads onto a pool of OS threads. There are no
locks or atomics in user code: a value is only ever reachable from one green thread at a time, except
where it is shared read-only — held by a module-level let, or published through a
default or a SharedValue
(below).
Starting a Coroutine
Section titled “Starting a Coroutine”async before a call starts the callee as a coroutine and returns a promise:
typealias Score = int(0 to 1000)
function slowDouble(n Score, delay Milliseconds) returns Score sleep(delay) print("finished {n} after {delay} ms\n") return n * 2end 'slowDouble'
function main() returns ExitCode let a = async slowDouble(10, delay: 60) let b = async slowDouble(20, delay: 20) let ra = await a let rb = await b print("sum={ra + rb}\n") return 0end 'main'finished 20 after 20 msfinished 10 after 60 mssum=60Both coroutines start before either is awaited, so their sleeps overlap and the program takes about 60 ms, not 80.
sleep(milliseconds)parks the current green thread; it takes aMillisecondsvalue.asyncapplies to a direct call of a function or a static method. It cannot start a closure, an indirect call, an instance method, or a static that reads its generic type’s layout (E2015): a coroutine is handed its written arguments only. A generic function is started at the instance its arguments infer, as a call would be. A qualified callee reads as the direct call reads it, at any length:async sub.Calc.seven()andasync outer.inner.six()start what those calls name.- An
asynccall takes any number of arguments of any type, except a value held at an opaque type parameter, which is E2015: start a function of a concrete type, or call it directly. - A callee may keep an argument it is handed (move it into a record it returns, for one); a coroutine dropped before it runs releases what it was handed instead.
- The arguments are shared, exactly as an ordinary call shares them. The caller and its coroutines are
one strand of one green thread, so the coroutine takes a plain count of its own on each managed argument
and the caller’s binding stays usable: a
varhanded toasyncis read and written after the call, aletis shared read-only, and one binding other than a promise may be handed twice in one call. A scalar is copied. Passing a handle is how a socket or a server is shared with a coroutine. A call that hands the coroutine the caller’s mutable data makes its promise a tied promise. - A promise argument moves. A coroutine can still be running after the frame that started it has ended,
so an
asynccall hands a promise, or a value whose type holds one, only to a parameter the callee takes — one it awaits, cancels, stores or returns. The coroutine then owns the thread, and the caller’s binding is spent. A parameter that only reads it is E3141: pass the promise to one that takes it, or await it and pass the result. One promise at two arguments of one call is E3102. - A variable handed to a
mutableparameter is lent to the coroutine. The coroutine receives the caller’s own cell, and its write is visible once the promise is awaited or cancelled. Until then the variable is lent like a move that ends at the drain: reading it, writing it or passing it is E3102 (use of moved value 'n': it is lent to the coroutine of theasynccall at 13:22 until that promise is awaited or cancelled), a sibling field of a lent local too, and naming it in the statement that starts the coroutine is E3186. Avar, or a field of a local, may be lent; any other storage at a by-reference position is E2015 (anasynccall takes only a local variable by reference), a literal is E2013, and the variable’s declared type must be the parameter’s type (E3005, see Parameter Passing). A coroutine that writes a parameter is refused a read-only argument (E3207), as an ordinary call is.specs/regions-async-lend.mdpins each case;the-coroutine-writes-the-callers-variable-and-the-await-shows-itruns one. - A unique value is lent to the coroutine the same way. A local or a parameter handed to
an
asynccall, a socket or anHttpServerincluded, is the coroutine’s until the promise is awaited or cancelled: a read,close(), pass or move of it before then is E3102, and after the await or the cancel it is the caller’s again. A server that runs in a coroutine is stopped with.cancel()on its promise, thenclose()d;close()while the promise is pending is E3102. The cases are inspecs/regions-async-lend.md. - A call passes an
isolatedvalue toasynconly in anisolatedparameter, which moves it (E3207). - A closure that captured a binding owns it, so handing that binding to
asyncafterwards is E3102. - The callee must be able to wait — call
sleep,await,Scheduler.yield(), send a service message with asendTimeout:, or perform file, socket or process I/O, directly or through its callees. A function that never yields is E3073 (function never yields; 'async' is for I/O-concurrent work only): there is nothing to overlap.
Awaiting Results
Section titled “Awaiting Results”await promise returns the coroutine’s result. If it has finished, await returns at once; otherwise the
awaiting green thread parks and the scheduler runs other work until the result is ready. A coroutine
that returns nothing is awaited as a statement: await p.
A promise is consumed exactly once. Awaiting it twice, or using it after .cancel(), is E3142; awaiting
inside a loop a promise that was started outside the loop is E3100.
Throwing Async Functions
Section titled “Throwing Async Functions”A promise from a throwing function is awaited with try await, which accepts every otherwise form a
synchronous try does:
enum FetchError implements Error notFoundend 'FetchError'
function lookup(key String) returns String throws FetchError sleep(5) if key == "missing" 'absent' throw FetchError.notFound end 'absent'
return "value-of-{key}"end 'lookup'
function main() returns ExitCode let good = async lookup("x") let bad = async lookup("missing") let g = try await good otherwise "none" let m = try await bad otherwise (e) 'failed' match e 'why' notFound then print("lookup failed: notFound\n") end 'why' return 0 end 'failed'
print("{g} {m}\n") return 1end 'main'Plain await on a throwing promise is E3057, unless a try block or a
test body handles it; try await on a promise that cannot throw is E3055.
The awaited form may be parenthesized: try (await p) otherwise … is try await p otherwise ….
Promises in Collections and Fields
Section titled “Promises in Collections and Fields”A promise can be stored in a container, a field, a tuple, a union payload or an array literal, captured by a
closure, or held by a generic type, when its type is named: Promise with T for a function returning T,
and Promise with (T, E) for one that also throws E. A store takes any promise the storing function owns:
- an
asyncspawn, or a service reply received in that function; - a promise parameter;
- a promise a call returned;
- a promise moved out of storage by
pop,removeor amatcharm, or yielded bytry … otherwise.
The store moves the promise: the container or field now owns the thread, and the function’s own name for it
is spent (E3102). The one condition is that the types agree, and E3098 names what differs when they
do not: a result type other than the slot’s, or an error type the slot drops, changes or adds. A promise
handed to a parameter, or to a container’s method such as Map.upsert, is held to the same rule. A call
through a function value hands the promise over to the callee.
A mutable promise parameter the callee reassigns (q = async work()) writes into the caller’s own variable: the
callee drops the thread the variable held, the variable takes the new one, and the caller awaits it as any
other promise name. The same holds through a function that only hands the parameter on, and at a position a
function type passes by reference. The argument is a var the caller owns: a let or a let field is
E2013, and so is a name a closure captured or a promise an array still holds. Inside a loop, await x after such a call
spends x, so the call on the next iteration is E3102.
typealias Tag = int(0 to 100)typealias TagPromise = Promise with Tagtypealias TagPromiseArray = Array with TagPromise
function nap(delay Milliseconds, tag Tag) returns Tag sleep(delay) return tagend 'nap'
function main() returns ExitCode let naps = TagPromiseArray.create(0) naps.push(async nap(200, tag: 1)) naps.push(async nap(20, tag: 2)) naps.push(async nap(100, tag: 3))
let first = naps.awaitAny() print("first finished: index {first}\n") // index 1
var sum = 0 as Tag for p in naps 'drain' sum = sum + await p end 'drain'
print("sum of tags={sum}\n") // 6 return 0end 'main'Waiting for the first of several. promises.awaitAny(), on an Array with Promise with …, parks until
any promise in the array has finished and returns its index. It consumes nothing: every promise, the winner
included, is still awaited (or dropped) afterwards. An already-finished promise is returned without parking.
p.isComplete() asks one promise whether it has finished, without parking or consuming it.
awaitAny is a wait and a yield: the compiler cannot see which coroutine or service produced an array element,
so a function that calls it waits on a party it cannot see. A message or a spawn factory that reaches it is
E3221; a modify block, an acquire block or a one-call
open that reaches it, directly or through a callee, is
E3205. main and a plain coroutine may select.
Reading a promise out of storage. A promise has one owner, so reading one out of the array or the struct
field that holds it starts a MOVE out of that slot: consuming the read empties the slot, and a read never
consumed stays the container’s and is dropped with it. get(i), first(), for p in array, an array
iterator’s current() and peek(n), a destructured for (iter, p) in array.withIterator(), and a read of a
promise-typed field all name their slot. A read that cannot name one is E3141: last(), a list’s elements,
a Map’s values, and a withIterator() pair bound whole. pop and remove move the promise out, and the
caller owns it outright. A member of a type you declare, a pop of your own included, is judged by its
body: it moves its element out when every return hands back what a library pop/remove took out of a
field of self (directly, through a var local bound to one, or through another such member of a field’s
type), or a parameter the declaration the call binds takes; one that returns a borrow (self.items.last()) is
E3141. A static of a generic type that hands back a promise an argument holds — an instance passed in,
or an array, map, tuple or struct reaching one — reads it out of that argument as a method reads its
receiver, so it is E3141 too, unless the declaration the call binds takes that argument. Reading a promise out of a temporary — try make().get(0) — keeps that temporary
alive to the end of the enclosing scope, so the promise outlives the expression it came from.
Consuming a promise. await, .cancel(), a push or set into another container, a store into a field
or a union case, and passing it to a parameter the callee takes all consume it: each empties the slot the
promise was read out of, and hands the thread either back to the runtime or to its new owner. A callee takes
a promise parameter it awaits, cancels, stores or returns, or hands on to a callee that takes it; a promise
passed to a parameter the callee only reads stays with the caller. A call of push, set, insert,
upsert, append or prepend stores its bare arguments whatever the receiver is, so a function that
hands its promise parameter to such a method takes the promise even where the receiver’s own method only
reads it. An async call is stricter (see Starting a Coroutine): the
callee must take the promise. A store into a promise field also releases the thread that field was
holding, exactly once. Three refusals follow:
- E3141 — the slot a read came out of has already been spent, at any of those doors. Two reads of one slot
hold one promise, so only one of them may be consumed; where the compiler cannot see that both name one slot,
the program aborts at run time with exit code 118 instead, and so does
p.isComplete()on such a read. Anasynccall that hands a promise to a parameter the callee only reads is E3141 too, and so is a store of a conditional expression (h.p = a if c else b): store on each branch instead. So is a closure giving away a promise it captured, since its body may run any number of times — in a generic body, a capturedTstored or returned where the program instantiatesTwith a promise. Await it in the function that spawned it, or hand the closure what it needs as a parameter. - E3102 — a promise already moved into storage is used again afterwards, or one promise is passed at two
arguments of one call where a parameter takes it. A generic factory’s
Tparameter stored twice, or in a loop, is this too where the program instantiatesTwith a promise. - E2015 — a promise read outside a loop is given away inside it, or inside a
whilecondition. Read it inside the loop instead.
Returning a promise. A function may return a promise it owns — a spawn, a bound spawn, one taken with
pop/remove, or a promise parameter — and the caller then owns it, to await, cancel, drop or
store. A return of
a promise no frame owns is E3141: one read out of a container that still holds it, a merge of two
promises (p if c else q), or a second name for a parameter.
Tied and Must-Use Promises
Section titled “Tied and Must-Use Promises”Every promise held in a local is must-use. On every path out of its scope it is awaited, cancelled with
.cancel(), stored, returned, or passed to a parameter that takes it. Dropping it at the end of its scope,
overwriting it, discarding it with _ =, or leaving the function on a path that does none of these is
E3213:
error E3213: this drops 'later', which was never awaited, cancelled, stored or returned: `await later`, call `later.cancel()`, store it or return iterror E3213: this drops a promise that was never awaited, cancelled, stored or returned: `await` it, call `.cancel()` on it, store it or return it_ = async slow() is E3213, as is a var re-armed before its promise is consumed, a promise awaited on one
path only, an early return before the await, and a service reply bound to a local and never consumed
(let reply = try h.say("a")). A service message’s reply discarded with _ = is an explicit
fire-and-forget, and the message is still delivered: _ = try h.say("a") otherwise …. A promise inside a
container or a field is cancelled with its holder. specs/promise-must-use.md pins each case.
An async call given the caller’s mutable data produces a tied promise. The coroutine holds that data
until it ends, so the promise is awaited or cancelled and nothing else. It lives in a local and is awaited by
a consuming await that every path reaches before the function returns:
typealias Tally = int(0 to u64.max)
type Row export var n as Tally
static function create(n Tally) returns Self return Self{n: n} end 'create'end 'Row'
function bump(row Row) returns Tally sleep(1) row.n = row.n + 1 return row.nend 'bump'
function main() returns ExitCode let row = Row.create(1) let later = async bump(row) let n = await later print("{n}\n") return 0end 'main'Every way out of the function, an early return, a throw and a propagating try included, first awaits or
cancels each tied promise still live there. A path that does neither is E3212:
error E3212: this exit leaves 'later' neither awaited nor cancelled, and the coroutine of the `async` call at 19:20 still holds the data it was given: `await later` or call `later.cancel()` before this exitAn await inside one if branch, one match arm or one ternary arm does not drain the promise. A tied
promise cannot be returned, held in a field or container, or passed to a parameter, because the callee would
keep it: each is E3212 (the promise of this `async` call is tied to the mutable data it was given: it is awaited or cancelled and nothing else, never returned, stored, captured, sent or passed on, because the coroutine still holds the caller's data), and a closure that captures one is E3141. .cancel() on a
tied promise stops the coroutine from beginning another wait on a far end and then waits for it to finish, so
the data is written, or left untouched, before the function goes on. That wait is why a modify block cannot
call a function that cancels one (Waiting and Yielding).
An async call is untied when none of its arguments carries the caller’s mutable data, as with plain values
and a second holder of a SharedValue (wakes.push(async drain(cell.clone()))). Such a promise may be
stored, and the must-use rule alone governs it. To untie a call, pass a .clone() of the argument. specs/regions-tied.md pins the cases; an-early-return-cancels-the-tied-coroutine-and-waits-for-it
and a-throw-exit-cancels-the-tied-coroutine-and-waits-for-it run the cancel paths.
Cancellation and Dropped Promises
Section titled “Cancellation and Dropped Promises”promise.cancel() consumes a promise. On a tied promise it waits for the
coroutine to finish; on any other it returns at once. A promise held in an array or a field is dropped with
its container, and a promise held in a local is must-use. A cancelled or
dropped promise has the effects below.
- A coroutine that has not started never runs.
- A coroutine that has already started is not interrupted where it stands: it resumes and runs on, and
its result is discarded. What it may no longer do is begin an operation that waits on a far end. Its
next
TcpClient.connect,TcpListener.accept,send,sendFrom, orTcpListener.bindto a host name throws that operation’s ownNetworkErrorvariant at once, and its nextreadSomethrowsStreamError.failed, instead of parking for a wake-up nothing will send.close()still completes, and so does abindto a numeric address. A service send it makes to a full mailbox failsmailboxFullat once, with or without asendTimeout:, and a send already waiting for room failsmailboxFullwhen the promise is dropped (see Mailboxes and failed sends). - Cancellation is cooperative: it marks the coroutine and never tears it down mid-frame, so the coroutine
runs to the end of its own code. A
sleepit is parked in ends early, and eachsleepit makes afterwards yields once, so its siblings run, and then returns at once. A linear value it holds is consumed by its own code on the path the early return of the wait leads it down, so a finalizer runs and nothing leaks.
Yielding
Section titled “Yielding”Scheduler.yield() gives other runnable work a turn and then continues. It never blocks and uses no timer
(unlike sleep(0)); when nothing else is runnable it returns promptly. Use it in a loop that polls for a
condition; use await or sleep to actually wait.
Services — spawn
Section titled “Services — spawn”A service is an ordinary type started with spawn. spawn Type.factory(args) returns a handle
and runs a static factory of the type as the service’s first message, on a green thread other than the spawner’s;
the service keeps the state the factory builds. The handle’s methods
are exactly the type’s export and public instance methods; each call on the handle is a message the
service handles one at a time, in order.
typealias Count = int(0 to 1000000)
type Calc var count as Count
static function create() returns Self return Self{count: 0} end 'create'
export function bump(by Count) self.count = self.count + by end 'bump'
export function total() returns Count return self.count end 'total'end 'Calc'
function main() returns ExitCode let h = spawn Calc.create() try h.bump(3) otherwise ignore // a message with no reply try h.bump(4) otherwise ignore let n = try await h.total() otherwise 0 // a message with a reply print("total={n}\n") // total=7
h.shutdown() let after = try await h.total() otherwise (e) 'stopped' match e 'why' mailboxFull then print("mailbox full\n") serviceStopped then print("service stopped\n") end 'why' return 0 end 'stopped'
print("unexpected {after}\n") return 1end 'main'- The same type is still a plain value.
Calc.create()withoutspawnis an ordinary record with ordinary calls, so a service’s logic is unit-testable without threads. - The factory runs before any message. It runs on a green thread other than the spawner’s, so its output follows the spawner’s until the spawner waits for the service, and a coroutine it starts belongs to the strand that runs it.
- An idle service owns no green thread. A message that reaches an idle service starts a runner that handles the queued messages in order, at most 64 per turn, and yields between turns so every other runnable service runs. A handler that sleeps or does I/O keeps its service held for as long as the sleep or the peer takes, and messages queue behind it up to the mailbox’s capacity. A handler never waits on another party (Holders Never Wait).
- A factory that throws makes the
spawna throwing call. The spawner waits until the factory has run, then receives either the handle or the factory’s error, of the factory’s own type. Writetry spawn Type.factory(…)with anotherwise, propagate it from a throwing function, or place it in a block-formtry; aspawnof a throwing factory that nothing catches is E3057, andtryon a factory that cannot throw is E3055. A factory that throws starts no service, and the factory’s output comes before anything the spawner prints after thespawn. A factory that cannot throw returns the handle at once. - Messages. Every send is a throwing call, because it can fail at the send (see
Mailboxes and failed sends): write
try h.method(…)with anotherwise, or propagate it. A send with notryis E3057, except inside a block-formtryor atestbody, which take its error. - Replies. A method that returns a value, or throws, delivers a reply.
try await h.method(…)sends it and awaits the reply, and its onetrycovers both: the error it binds has the send’s casesmailboxFullandserviceStoppedbeside the method’s own.let p = try h.method(…)sends it and keeps the reply as a promise, whose error type is the method’s own alone:Promise with (T, E)for a method that throwsE,Promise with Tfor one that throws nothing, which a plainawait presolves. A baretry awaitthat propagates is refused (E3059) when the method throws too, because the two errors have no single type to propagate: handle it withotherwise (e)andmatch e, or split it intolet p = try h.method(…)andtry await p. - A reply is kept, or discarded on purpose. A method that returns or throws, sent as a statement, is
E3190. Await the reply, keep it, or discard it on purpose with
_ = try h.method(…). - Private methods are not messages. Calling a non-exported method or a static through a handle is
E3136: a handle reaches exactly the type’s
exportinstance methods. - A message is as visible as its service, and no more. Its
exportmakes it a message rather than widening it past the type, so the types its signature names need only the service type’s visibility (E3167): an unexported service’s messages may name unexported types. - Shutdown.
h.shutdown()closes the mailbox: the messages already queued still run, and then the service stops. Every later send fails withserviceStopped. It always succeeds, on a full mailbox too. Dropping the last handle does the same. A queued message always runs, so a reply always resolves. - The target of
spawnmust be a static factory that returns its own type; anything else — including a barespawn f(), a qualified chain that names no type, or a chain whose head is a binding in scope — is E3134, in adefaultas anywhere else. The type may be qualified, at any length:spawn sub.Calc.create()starts a type declared insub/,spawn outer.inner.Calc.create()one two directories down, andspawn stdlib.Range.create(1, finish: 4)the library’sRangein a program that declares its own. A factory the spawning file cannot see is E3008. - Generic services. A generic type can be spawned; its handle type is spelled through an alias,
typealias StringBoxHandle = Box.handle with String. Aspawnon the bare generic name reads its type arguments off the factory’s arguments; a factory that fixes no type is E2015. A factory argument held at an opaque type parameter — aTvalue inside a generic function — is E2015; spawn from a function of a concrete type. - A refusal of a
spawn’s target or factory (E3134, E3008, E2015) points at thespawnkeyword. - A message or a factory that waits on another party is E3221, so services never wait on each other in a cycle (Holders Never Wait).
spawnis a contextual keyword; it remains usable as a name.
What crosses a message. A value sent to a service must not stay reachable from the sender in a way either side could write, because the two green threads may run at the same time on different processors:
- A parameter or reply that holds data of its region names how it crosses. A message parameter, a
message reply or a factory parameter whose type is a record, a union with a payload, an array or other
container, or an interface value is written
isolated Torimmutable T; with neither, thespawnthat makes the type a service is E3217, naming the parameter or message.isolatedhands the value over: the sender passes a fresh region or anisolatedlocal (Separate Regions) and cannot read it afterwards.immutableshares frozen data that both threads only read: the sender passesfreeze x.clone()or animmutablevalue (Frozen Data). Only the factory thespawnnames is judged, and a reply is judged at its declaration, so a generic message thatreturns Tis not refused here. A word is needed on none of these: numbers,bool,ExitCode,String,Character, enums, unions whose cases carry nothing, service and interface handles,SharedValuecells, a tuple none of whose elements owns heap, and auniquetype, which moves and crosses as the whole of its region (the OS handlesTcpClient,TcpListener,TlsStream,TlsListenerand the types that hold them areunique). - Four kinds of value cannot cross at all, and are E3217 too: a promise or any type that can hold one (a
record with a promise in a field, a union with a case carrying one, an array or list of promises, empty or
not), because a coroutine belongs to the strand that started it and a promise that crossed would be dropped,
awaited or cancelled by a strand that does not own it; a function value, a closure record that owns what it
captures; an opaque type parameter, whose layout is not known at the send; and an OS handle bound to a
thread, such as a
MachinePin, also when it is held at an interface type.awaitthe promise and send or return the result, or send the scalar the value is derived from. A reply the cell cannot carry is E3140, and a state field that can hold a promise is E3216; those are reported before E3217. - A local
letorvar, a temporary or a literal argument the sender owns is moved into the service; reading the sender’s variable afterwards is E3102. Replies are moved too, and so is every argument aspawnhands its factory, whether or not the factory keeps it. The handler owns what it was moved, so it may keep it or write it. - An
isolatedargument must be a value no other name reaches: a fresh call result, anisolatedlocal or a local initialised from a fresh value that this send reads first. A value read out of a field or an element of avar, the source of an enclosingforloop, or an element a member hands back out of a field’s container (return self.queue.pop()) is still held by its container, so it is notisolated(E3200); send a.clone(). Anisolatedlocal that an enclosingforiterates (for x in itemsorfor (it, x) in items.withIterator()) is held by the loop until it ends, so a message or factory argument of it inside the loop is E3200 as well; send it after the loop. - A value crosses a thread only as the whole of its region. The rule holds for a send argument, a
spawnfactory argument, a reply and the arguments a failed send hands back. The value is a fresh expression, a variable declaredisolated, or an owneduniqueor linear value of a closed type: one whose closure holds no plain part (see Linear Types and Finalizers). Auniquevalue whose type holds a plain record, array, union, function value or interface value, and that is not fresh or declaredisolated, is E3200: the message names the plain part, which the sender or another holder may still reach. Declare the partisolated, pass a fresh value, or consume the value where it is. - An
immutableargument must be frozen data:freeze x.clone(), a constant, a module-levellet, or aSharedValueor registry read. It is shared: its graph is marked shared, so every count on it steps atomically, and neither side may write it. A mutable argument at animmutableparameter is E3207. AStringis a value; its buffer count becomes atomic when it is sent. - A tuple none of whose elements owns heap —
(Amount, Amount), say — is a value. When the sender is not its one owner, it is copied wherever it crosses: a send, a factory argument,SharedValue.publishorKey.register. The service gets the copy and the sender keeps its own. - A value held at an interface type crosses as a message argument, in a service’s state and as a reply, moved like any other value; a conformer whose graph cannot cross is refused at the send, as it is at its own type.
- An OS handle crosses by move. A
TcpClient, aTcpListeneror aTlsStreamisunique: bound withlet, pushed into a container or handed to aspawn, it moves, and reading the sender’s name afterwards is E3102; the receiving green thread reads and writes it, and the network poller wakes it wherever it runs.clone()of one is E3214. ASharedValueor a registry value that reaches one is E3171. - Freezing or publishing a graph walks it to mark every record shared. A value held at an interface type is
walked through the conformer it holds, so every conformer the program converts to that interface is judged
at the
freeze, the publish or the registration: one no walk can be built for is E3171, naming the interface, the conformer and the field, with a note where the conformer is converted.
A service’s state holds no promise. A field of a service type that is a Promise, an array of promises, or a
record or union that holds one is E3216, reported at the
spawn. Each message may run on a different green thread, and a coroutine belongs to the strand that started it,
so a promise kept in the state could be awaited or dropped by a strand that does not own it. A message or the
factory awaits or .cancel()s the coroutines it starts before it returns, and keeps their result in the field.
A service’s state reaches no handle to its own type. A service is freed when its last handle is dropped, so
state that holds a handle to the service itself keeps it alive for ever. That is
E4014, with the cycle in the message: a field var me as Echo.handle; two services whose states hold each other’s handles (Ping holds a Pong.handle and Pong holds a
Ping.handle); an interface handle whose conformers include the service; a function-valued field, union
payload or container element while some closure in the program captures a handle that reaches the service,
because a function type does not say what its closure captured; and an interface-typed field, union payload or
container element while some generic instance that implements the interface is built at a type parameter (a
Wrap with T that hands out a Gen with T as a Sink), because the instance a caller’s T makes is written
nowhere and may hold any handle. Pass the handle with each message
(start(oracle Oracle.handle, me Asker.handle)), which keeps it only for the message, or give the services
distinct types. A chain of distinct services, each holding the next one’s handle, is not a cycle.
Module-level state. A service keeps its state in its own fields and hands results back through replies. A
module-level let is immutable image data, so a handler or factory reads the one copy every thread shares,
and it can hold no OS handle, function value or promise. A spawn in a global initializer is E3220, like any
call (a default starts a program-wide service before main; see
Top-Level Bindings).
Output order. Text printed by main and by a service handler or factory may interleave in any order; sequence it
through awaited replies when order matters.
Mailboxes and failed sends
Section titled “Mailboxes and failed sends”A mailbox holds at most its capacity of queued messages: DefaultMailboxCapacity (1024), or the
MailboxCapacity (int(1 to 2^31)) that spawn(capacity: n) Type.factory(args) names. The capacity is a
ceiling: the mailbox’s memory grows with its backlog, up to the capacity. A message counts from the moment its
send is accepted until the service starts handling it, so a service that has not started yet takes exactly
its capacity of messages and the next send finds the mailbox full; the message being handled does not count.
A send queues the message, or fails with an error the compiler declares for each message,
<Service>.<message>.sendError, whose two cases carry the arguments the send was given:
mailboxFull(<arguments>)— the mailbox holds its capacity;serviceStopped(<arguments>)— the service has been shut down.
sendTimeout:. Every message call takes a reserved last argument, sendTimeout: Milliseconds, which
says how long a send waits for room in a full mailbox. It defaults to 0: a send to a full mailbox fails
mailboxFull at once. It may be the call’s only argument, h.ping(sendTimeout: 5000). It stays with the
send: the handler receives the message’s own arguments alone.
- A send given a positive timeout waits in line behind the senders already waiting on that mailbox. Each message the service takes frees a slot, and the first waiting sender’s message goes into it, so the waiting sends are delivered in the order they began to wait.
- The service shutting down fails every waiting send with
serviceStopped. - The timeout passing fails the send with
mailboxFull. sendTimeout: ForeverMswaits as long as it takes, untimed: the blocking send of a Go channel. When the mailbox stays full and every green thread is waiting, the program stops with exit code 92 (see Exit Codes).- A send in a coroutine whose promise has been dropped (see
Cancellation and Dropped Promises) fails
mailboxFullat once, and so does a waiting one when the promise is dropped. This is the one way a send givenForeverMsfailsmailboxFull. - A message that declares a parameter named
sendTimeout, and an argument aftersendTimeout:, are E3192.
The arguments come back owned by the caller, so they can be sent again, to this service or another. An
immutable value the send shared (see above) comes back as a copy. One whose type has no deep copy comes back
as the shared value itself, which the caller may read and keeps for itself. A message with no parameters
has payload-free cases. Through an
interface handle the error is <Interface>.<message>.sendError.
typealias Count = int(0 to 1000000)
type Store var kept as Count var last as String
static function create() returns Self return Self{kept: 0, last: ""} end 'create'
export function keep(line String) self.kept = self.kept + 1 self.last = line end 'keep'end 'Store'
function main() returns ExitCode let h = spawn(capacity: 64) Store.create()
for i in 0 upto 1000 'eachLine' try h.keep("line {i}", sendTimeout: 50) otherwise (e) 'refused' match e 'why' mailboxFull(back) then print("dropped {back}\n") serviceStopped then return 1 end 'why' end 'refused' end 'eachLine'
return 0end 'main'- A full mailbox is the sender’s to handle. Wait for room with
sendTimeout:, as above, send elsewhere, or drop the message. A send with a positive timeout waits, so a message or aspawnfactory that makes one is E3221: a message sends withsendTimeout: 0, which failsmailboxFullinstead of waiting.main, a test body and a coroutine hold no service and may wait. - ⚠ Retrying coroutines can livelock. A yield runs the green thread’s other runnable coroutines first.
When every coroutine of one green thread retries a send without a timeout to the same full service, at one
processor with preemption off (
MAXON_MAX_PROCS=1,MAXON_PREEMPT=off) the coroutines hand the processor to each other and the service waits for it forever. Give the send asendTimeout:, which parks the coroutine until there is room. - A send error is propagated by a bare
tryin a function thatthrows <Service>.<message>.sendError, or rethrown withthrow efrom the binding that caught it. otherwise ignoredrops a failed send and releases its arguments.
Interface Handles
Section titled “Interface Handles”A service type may implements an interface, and I.handle is a handle to any running service whose type
implements I. Each requirement of I is a message: a call through an I.handle is sent to whichever
service the handle holds, by the same rules as the service’s own handle. Its send error is
I.<requirement>.sendError, with the same mailboxFull and serviceStopped cases.
typealias Count = int(0 to 1000000)
interface Tally function add(mutable self, by Count) function total() returns Countend 'Tally'
type Counter implements Tally var n as Count
static function create() returns Self return Self{n: 0} end 'create'
export function add(by Count) self.n = self.n + by end 'add'
export function total() returns Count return self.n end 'total'end 'Counter'
function report(t Tally.handle) returns Count try t.add(5) otherwise ignore return try await t.total() otherwise 0end 'report'
function main() returns ExitCode let total = report(spawn Counter.create()) print("total={total}\n") // total=5 return 0end 'main'- A
T.handleconverts toI.handlewherever anI.handleis expected: a binding, an argument, a return, a field, an array element, a message argument, aKey.registerand a call through a function value or a closure.as I.handleconverts explicitly. - Every requirement must be sendable: its parameters must cross a message (E3217) and its reply must be
carriable (E3140). One send serves every implementer, so the services a program sends to through
I.handledeclare each requirement with the same parameter, return andthrowstypes (E3177); send through each service’s own handle otherwise. - A requirement sent through
I.handleis a message of every service implementingI, so each declares it as anexportinstance method. Sending one that an implementer declares another way (an unmarked method, say), or that no implementer declares, is E3136. - A handler that awaits a reply through an
I.handlewaits, so it is E3221 like any other waiting message.
Atomic Updates — acquire
Section titled “Atomic Updates — acquire”acquire a, b 'label' … end 'label' otherwise 'stopped' … end 'stopped' takes the services behind two or
more handles at once and runs its block with their states. The block’s name move below is its label:
typealias Money = int(i64.min to i64.max)typealias EntryArray = Array with Money
type Account var balance as Money var history as EntryArray
static function create(opening Money) returns Self return Self{balance: opening, history: EntryArray.create(0)} end 'create'
function canPay(amount Money) returns bool return self.balance >= amount end 'canPay'
function change(by Money) self.balance = self.balance + by self.history.push(by) end 'change'
function historyCopy() returns isolated EntryArray return self.history.clone() end 'historyCopy'
function replaceHistory(entries isolated EntryArray) self.history = merge entries end 'replaceHistory'
export function balanceNow() returns Money return self.balance end 'balanceNow'end 'Account'
function transfer(source Account.handle, target Account.handle, amount Money) returns bool acquire source, target 'move' if not source.canPay(amount) 'short' return false end 'short'
source.change(-amount) target.change(amount) end 'move' otherwise 'stopped' return false end 'stopped'
return trueend 'transfer'
function copyHistory(first Account.handle, second Account.handle) returns bool acquire first, second 'copy' let copy = second.historyCopy() first.replaceHistory(copy) end 'copy' otherwise 'stopped' return false end 'stopped'
return trueend 'copyHistory'
function main() returns ExitCode let a = spawn Account.create(100) let b = spawn Account.create(0) let moved = transfer(a, target: b, amount: 30) let left = try await a.balanceNow() otherwise 0 print("{moved} {left}\n") let copied = copyHistory(b, second: a) print("{copied}\n") return 0end 'main'Output: true 70 and true. No message to either account runs between the debit and the credit, so no message
sees the money in flight.
- Each name is the service’s state. Inside
transfer,sourceandtargetareAccountvalues; the names are written where the handles are in scope, and each handle is of a spawned service type. A handle reached through an expression is bound withletfirst (let source = self.left). - The block takes every service it names at once. It runs on the caller’s green thread; the calling
coroutine parks until all the services are free, and the thread’s other coroutines keep running meanwhile.
return,break,continueandthrowleave it as they leave any block, and every service is released on the way out.acquire s, snames one service and takes it once. otherwiseis the block that runs when a service has stopped. It holds no service. It follows the block’sendon the same line, aselsedoes, and takes a label of its own;otherwise (e) 'stopped'binds the position in the name list of a service that stopped. Anacquiretakes no mailbox capacity, so a stopped service is its only failure.- One state is open at a time. Reading a field of a state or calling a method on it opens it for that one
statement. What the statement hands back leaves it only as a value,
immutabledata or a freshisolatedvalue (E3202):let held = source.cellis refused;let n = source.cell.nandlet copy = source.cell.clone()are not. A call that opens a state and hands back mutable data of it is judged where its result leaves the statement, so a number read out of the result is accepted and binding, returning or storing the result is refused. - A statement reaches one acquired state. Two names of one block may be one service, so a statement that
reaches
firstandsecondis E3201:first.replaceHistory(second.historyCopy())is refused, andcopyHistorybinds the value read fromsecondin a statement of its own first. Several statements on one state usemodify source 'debit' … end 'debit'; inside it every other state is read-only. - A state stays in the block. Binding the name, returning it, storing it, moving it into an
isolatedparameter or aspawn, or sending it throughasyncis refused (E3202, E3205): the service keeps its state. - The block runs to its end holding every service.
async, a coroutineawait, anacquireand a call that may wait or yield are E3205 inside it, as in amodifyblock. Anacquirein code that holds a service is E3221 (Holders Never Wait).
Holders Never Wait
Section titled “Holders Never Wait”Code that holds a service never waits on another party. A message runs to its end holding its own service, a
spawn factory holds the service it starts, and an acquire block holds the services it names. Were one of them
to wait for a reply, two services could each wait for the other for ever. A message or a factory that may wait is
E3221, and the diagnostic names the chain to the wait:
error E3221: the message 'ask' may wait (it awaits a reply from 'Worker' at line 10) while holding its own service; send the request with this service's handle and handle the reply in another messageThese wait on another party:
- an
awaitof a message reply or of a promise whose coroutine the compiler cannot see, such as one read out of an array; awaitAny, which parks until one promise of an array has completed;- a send with a positive
sendTimeout:, which waits for mailbox space; - an
acquire; - the spawn of a factory that throws, whose spawner waits for the factory’s result;
Scheduler.quiesce()andCownTorture.violations, which park until other green threads are idle or have finished;- a call to a function that does any of these, and the start of a coroutine that does.
main, a test body and a coroutine hold no service and may wait. HttpServer.serve and
TraceCapture.stopCapture wait, so they are called from main, a test body or a coroutine. Sleeping, and file,
socket and process I/O, hold the service for as long as the sleep or the peer takes, and messages queue behind
it up to the mailbox’s capacity. An await of a coroutine the same function started is a yield.
The continuation pattern. A message that needs another service’s answer sends the request with the
data the answer needs, and returns. The answer comes back as a message of its own, handled by the same
service: the request carries the asker’s handle, or a Reply the answer
completes. A handle a message carries lives only until the message returns, so a request may carry the asker’s
own handle (E4014 concerns handles kept in a field).
Deferred Replies — Reply
Section titled “Deferred Replies — Reply”A message that returns a value answers when its handler returns. reply.later() lets a message answer from
somewhere else: written as the whole initializer of a let at the top level of the message’s body, it takes the
message’s reply and hands back a Reply with T, where T is the message’s reply type. The caller’s await
stays pending until some service calls answer(value) on that Reply, which consumes it and completes the
reply:
typealias Tally = int(0 to u64.max)typealias TallyReply = Reply with Tally
type Clerk var served as Tally
static function create() returns Self return Self{served: 0} end 'create'
export function look(waiting TallyReply) self.served = self.served + 1 waiting.answer(self.served * 21) end 'look'end 'Clerk'
type Desk let clerk as Clerk.handle
static function create(clerk Clerk.handle) returns Self return Self{clerk: clerk} end 'create'
export function ask() returns Tally throws ReplyStopped let pending = reply.later() try self.clerk.look(pending) otherwise ignore return end 'ask'end 'Desk'
function main() returns ExitCode let clerk = spawn Clerk.create() let desk = spawn Desk.create(clerk.clone()) let total = try await desk.ask() otherwise panic("the clerk answered") print("{total}\n") return 0end 'main'Output: 21. Neither message waits: Desk.ask returns as soon as it has sent, and the answer reaches main from the
Clerk.
- A
Replyis unique. It lives in a service’s state, in a container or in a message argument, and moves like any unique value, so it is answered at most once. AReplyis answered through the local or parameter that holds it: take it out of a field first (let pending = try self.waiting.pop() otherwise return), thenpending.answer(value).answeris a send that returns at once, so any message may call it. - A message that defers declares
throws ReplyStopped. AReplydropped unanswered, a holder freed with it still inside included, fails the caller’sawaitwithReplyStopped.serviceStopped. - After
reply.later()the message’s ownreturncarries no value. The answer travels through theReply. A message that defers is called only by a send through the service’s handle. reply.later()is a statement of the message’s own body. It is refused in anif, a loop, amatchor atryinside the body, in a closure or a default value, a second time in one message, in a message with noreturnsclause or one that returns an interface value, and in a generic service (E3222).- A
Replystays in the code of the service that holds it. No function declares a result whose type can hold one (a message’s reply, a promise’s payload and a helper’s result included), noasynccall takes a parameter that can hold one, no closure captures one, and no such value is widened to an interface type, because a function value and an interface value carry what they hold to whatever code receives them (E3222). AReplytaken out of an acquired state cannot outlive the statement that opens the state (E3202). - A
Replyis answered, and a promise is awaited. A service’s state and its message arguments hold aReplyfreely, where E3216 and E3217 refuse a promise.
Program-Wide Defaults — default
Section titled “Program-Wide Defaults — default”A top-level default Key = expression declares the program-wide default for Key. Any thread reads it with
Key.current() and replaces it with Key.register(x); every later current() sees the replacement.
- A service key is an interface. The expression spawns a type that implements it
(E3170 otherwise), and
Key.current()returns an ownedKey.handle. - A value key is a type whose graph a share walk can mark: one that reaches no OS handle, function value
or promise, also through a conformer the program converts to an interface the graph holds
(E3171 otherwise). Its fields may be
var, and may hold containers. The expression builds one, and may spawn services for its fields.Key.current()returns the published record, read-only all the way down: a write through it is E3197 (E3207 where it is handed to a parameter the callee writes), andclone()makes a mutable copy.
typealias Count = int(i64.min to i64.max)
interface Greeter function greet(mutable self) returns Countend 'Greeter'
type Polite implements Greeter var calls as Count
static function create() returns Self return Self{calls: 0} end 'create'
export function greet() returns Count self.calls = self.calls + 1 return 7 end 'greet'end 'Polite'
type Config export let retries as Count
static function create(retries Count) returns Self return Self{retries: retries} end 'create'end 'Config'
default Greeter = spawn Polite.create()default Config = Config.create(3)
function main() returns ExitCode let answer = try await Greeter.current().greet() otherwise 0 Config.register(Config.create(5)) print("{answer} {Config.current().retries}\n") // 7 5 return 0end 'main'- When it is built. Defaults are built in dependency order after the last global initializer has
returned and the module’s
lets are marked shared, and beforemain. Only a default some code reaches — through its key’scurrent()orregister()— is built, so a default’s service runs only in a program that uses its key. Defaults whose expressions reach each other are E3172, and acurrent()orregister()reachable from a global initializer is E3173. - Precedence. A program’s own
defaultfor a key replaces the standard library’s. Two for one key on the same side are E3169. - A service lookup is a snapshot. A handle taken before a
registerkeeps reaching the service it was taken from; that service runs until its last holder drops it, then drains its queue and exits. - A value lookup is lock-free: an acquire load and a retain, bracketed by two counter updates on the cell.
A replaced value is freed as soon as no lookup is between loading it and retaining it, so a cell holds
its current value and a bounded few replaced ones while it lives. A registered value must be solely
owned by the caller (E3174; publish a
.clone()) or a tuple of heap-free elements, which is copied (Moves and Sharing), and it is marked shared before any other thread can read it. A value a reader already holds stays valid after it is replaced. Key.register(new, replacing: old)publishesnewonly whileoldis still the current value, and returnstruewhen it did. Onfalse,newis consumed and dropped. Build the value again from a freshcurrent()and retry, so two threads updating one key keep both updates.registermay be called from any thread, a service handler included.currentandregisterbelong to the registry, so a key type that declares a static member of either name is E3175.- At exit, the drain that runs the services’ queued messages keeps the defaults live, so a handler may
still look one up; they are released once every service is idle, and a default’s service then drains and
exits. Module and
staticlets are released inside the drain after the services settle, so a handler may read them there too.
SharedValue — a Live Value Made at Run Time
Section titled “SharedValue — a Live Value Made at Run Time”SharedValue with T is a value key’s slot created at run time: one live value that every holder of the cell
reads. T follows the value-key rule, or is a String, a service handle or a scalar
(E3171 otherwise).
typealias Count = int(0 to 1000)
type Config export let n as Count
static function create(n Count) returns Self return Self{n: n} end 'create'end 'Config'
typealias ConfigCell = SharedValue with Config
type Reader let cell as ConfigCell
static function create(cell ConfigCell) returns Self return Self{cell: cell} end 'create'
export function read() returns Count return self.cell.current().n end 'read'end 'Reader'
function main() returns ExitCode let cell = ConfigCell.create(Config.create(1)) let reader = spawn Reader.create(cell.clone()) let before = try await reader.read() otherwise 0 cell.publish(Config.create(6)) let after = try await reader.read() otherwise 0 print("{before} {after}\n") // 1 6 return 0end 'main'ConfigCell.create(v)makes a cell;current()reads its value lock-free;publish(v)replaces it for every holder;publish(v, replacing: old)is the conditional form, answering asKey.register(new, replacing: old)does.- Readers take a read-only snapshot and a writer publishes a whole new value, so a value a reader holds
stays valid across later publishes. A value
current()returns is read-only all the way down, as a value key’s is. A published value must be solely owned (E3174) or a tuple of heap-free elements, which is copied (Moves and Sharing). - The cell is shared by reference:
clone()hands out another reference to the same value, and a cell crosses a message like a service handle.
I/O and Waiting
Section titled “I/O and Waiting”Operations that wait park their green thread instead of blocking an OS thread: sleep, await, socket
operations (TcpClient.connect, send, readSome, TcpListener.accept) and waiting on a child process. A
parked green thread holds no processor, so a server waiting in accept() costs nothing while idle.
File and directory operations yield to other work before each call into the operating system and are
started with async like any other waiting function (try await for the throwing ones such as
File.readText). The standard library reference documents the file, network and process
APIs.
A failed operation reports the reason its own call into the operating system gave, such as the case of a file
error or the os error N of a SubprocessError, even when its green thread ran on another OS thread between
that call and the report.
The Scheduler
Section titled “The Scheduler”- Green threads. Every green thread starts on a small stack that grows on demand, so thousands are
cheap. A stack stops growing at 1 GiB; a recursion past it stops the program with
panic: stack overflow. - Parallelism. By default the scheduler creates one processor per logical CPU. The environment
variable
MAXON_MAX_PROCS=Nsets the count exactly, for any decimalNfrom 1 to 2147483647, including a count above the CPU count; any other value leaves the default.Scheduler.processorCount()answers the resolved count. Services use the processors in parallel; anasync-only program’s coroutines stay on the green thread that started them. - Preemption. A green thread that has run for 10 ms is stopped and moved behind the other runnable
work, so a CPU-bound loop cannot starve the rest of the program. It can be stopped at any instruction of
user and standard-library code, outside the short compiler-generated sequences that must run whole, such
as an inline allocation; the runtime’s own code (the scheduler, the allocator, the context switch) always
runs uninterrupted. It is also stopped at its next function entry,
spawn,asynccall, service send,awaitorawaitAny, or when a service takes its next message.MAXON_PREEMPT=offdisables preemption;on, or unset, is the default, and any other value makes the program exit at start-up with code 116. - Coroutines switch only where they wait: at
await,sleep,Scheduler.yield(), I/O, and a service send given asendTimeout:, while its mailbox is full.
The CLI reference lists the environment variables a compiled program reads.
Exit Codes
Section titled “Exit Codes”Each of these aborts writes fatal error: runtime abort N (name) to stderr, then exits with code N.
| Exit code | Cause |
|---|---|
| 75 | a green thread was neither awaited nor dropped when the program ended |
| 90 | a service’s message loop received a message its type does not declare — reachable only if a send the compiler built names no message of the service |
| 92 | deadlock: main is unfinished and every green thread waits for good (for example awaitAny on an empty array, or a sendTimeout: ForeverMs send to a mailbox that stays full) |
| 96 | a share walk (freeze, SharedValue.publish, Key.register) reached a value held at an interface type whose conformer no walk can be built for — reachable only if a share door the front end should have refused (E3171) was compiled |
| 98 | a service send waiting for room broke the protocol between the sender and the party that wakes it — reachable only through a send the compiler built wrongly |
| 116 | MAXON_PREEMPT holds a value other than on or off |
| 120 | a deep copy reached an interface-typed field whose conformer cannot be duplicated — reachable only if a .clone() the front end should have refused was compiled |
Exit code 70 with fatal error: <reason> on stderr is a broken runtime invariant: a bug in the compiler or
its runtime, worth reporting with the program that produced it. One reason marks a limit of the host:
on x64-windows, fatal error: exception dispatched below green thread stack bottom ends a program whose
green thread faulted with too little stack left for the operating system’s exception dispatch, whose size
grows with the processor’s vector state.
Exit code 2 with fatal error: cannot open standard fds is the start-up check described under
Entry Point.
Targets
Section titled “Targets”Green threads, async, sleep, awaitAny and services run on every native target. wasm32-wasi has one
thread: sleep waits the whole program there, and async, awaitAny and services are E3104, reported
at the call when the language checks find no other error in the program.