Stories: Concurrency
See also:
spec/concurrency.md— the rules these chapters explain.
Parallelism you can’t see, concurrency you must ask for
Two unrelated ideas travel under the one word concurrency, and most of the trouble in this part of the design came from refusing to let them stay merged. One is going faster: running work that does not depend on other work at the same time, so a multi-core machine finishes sooner. The other is changing what the program computes: letting independent lines of execution interleave, race, and produce results that depend on who got there first. The first is an optimization the programmer should never have to think about; the second is a semantic decision the programmer must make deliberately, because it can change the answer. A language that hands the programmer one knob labelled “concurrency” forces the programmer to reason about meaning every time the goal was only speed, and to reason about speed every time the goal was a change of meaning.
So the first move is to split the word in two and give each half opposite rules. Parallelism is the compiler’s business and is defined to be unobservable: the compiler may run provably independent work at once, but only when doing so cannot change the output — it may move timing, never results (concurrency.md §2.2). Concurrency is the programmer’s business and is the opposite: spawn explicitly opts out of serial equivalence, and program results may legitimately depend on scheduling (§3.7). The same machine runs both, but they answer to different masters: one may never be noticed, the other must always be asked for.
The unobservable half only works because an earlier document already paid for it. The compiler can parallelize the residual graph only where it can prove two pieces of work do not conflict, and that proof is exactly what the effects story built — effects are inferred and visible in the structure, so independence is a property the compiler can read rather than guess. The same machinery determines which calls disappear before the runtime graph even exists: a Total Pure call with known inputs is evaluated at compile time and removed entirely (§2.3), which is why the four-level ladder bothered to separate Total Pure from merely Pure — that line is the line between work the compiler can erase and work it can only parallelize.
The hardest road not taken here was async/await. It is the dominant answer — Rust, C#, JavaScript, Python all encode “this might run concurrently” into the function’s type, so a function becomes a different kind of function the moment some caller wants to run it off the main line, and that color spreads up the call chain until half the program is dyed. Zane refuses it outright (§5.3): whether work runs concurrently is a property of the call site, chosen with spawn, not a permanent property of the definition. The same function is called normally in one place and spawned in another, and its signature does not change. This keeps the language out of the function-coloring trap, but it is not free: because parallelism is the compiler’s call, governed by profitability heuristics over instruction counts and IO (§2.2), the programmer cannot force a pure computation to run in parallel or forbid it — the language guarantees only that the answer will not change, never a particular timing. The one coarse lever they do get is @threads (§2.4), a whole-program pool size, not a per-call placement. That is the deliberate shape of the bargain: total control over meaning through spawn, almost none over timing, and we think that is the right place to draw the line.
spawn, and why it marks only a call
If concurrency must be asked for, the asking needs a syntactic home, and the shape of that home settled more than it first appears. The question was deceptively small — what, exactly, are you allowed to spawn? The expressive answer is “anything”: a block, a branch, a loop body, any chunk of work you want to peel off. We took the restrictive answer instead. spawn may target a function call and nothing else (concurrency.md §3.1) — spawn [ ... ] and spawn if ... are illegal — and the reason reaches forward into the safety rules. Every check that makes concurrency safe in Zane is read off a callee’s signature: whether it needs mut access, which external resources it reads or writes. A function call presents that signature; an arbitrary block does not. Letting you spawn a block would force the compiler to derive an effect signature for a lump of inline code reaching into whatever surrounds it, which is exactly the open-ended analysis the call-only rule sidesteps. The restriction is what keeps conflict detection signature-based and statically decidable.
That wording later exposed a terminology mistake rather than a design boundary. We had used “function call” loosely to mean a call with a verb signature, while Zane uses function narrowly for a verb without this. A method call presents the same signature — including its receiver and mut permission — and we always intended it to be spawnable for the same reason a function call is. The standing boundary is therefore function or method calls, and nothing else. Blocks and control flow remain outside it because they provide no verb signature for the analysis to read.
With the unit settled, the next question is how a spawned result comes back. A spawned call that returns a value binds to a symbol like any other, and the trick is what reading that symbol does: it blocks until the call finishes (§3.2). There is no future object, no .await, no .get() handle. The road not taken was the explicit future — a Future<T> you thread around and resolve later — and it loses on the same ground as async coloring: a future is a second type wrapped around the real type, and it spreads the same way. Making the bound symbol be the value, and putting the only blocking point at the moment of use, keeps the data dependency visible exactly where it matters — you can see, at the read, that this is where the program waits — without minting a new type to carry it.
The same instinct settles the abortable case. A spawned call that can fail still attaches its ? or ?? handler directly to the spawn expression (§3.3), not at some later result-read site. We considered deferring the handling to where the value is read — it would mirror the blocking model — but it would have split error handling into two dialects, one for ordinary calls and one for spawned ones, and the whole point of the error-handling model is that an abortable call is handled at the call. A spawn is the call; the handler belongs there, and the bound symbol simply carries the already-handled type. So concurrency does not get its own error story; it inherits the existing error story intact.
Two smaller rules round out the call model and both follow from taking ordering seriously. The compiler never reorders spawns — source order is start order, and each blocking read happens exactly where written (§3.6) — because once the programmer has opted into observable concurrency, the source is the only record of intent the compiler is allowed to honor. And a stalling call, when spawned, is parked rather than left to occupy a worker thread while it waits (§3.4), so a bounded pool can hold many more waiting calls than it has threads. The cost of the call-only discipline is paid in ergonomics: to run a compound computation concurrently you must first name it as a function, since you cannot wrap a block — and the no-capture rule of a later chapter sharpens that cost, because the function cannot quietly reach for its surroundings either. We judged the verbosity a fair price for a spawn whose safety the compiler can settle by looking only at a signature.
The water tower: lifetimes that survive the spawn
Spawning a call creates a problem the rest of the memory model never had to face: the work outlives the statement that launched it. Up to now, lifetimes were a lexical matter — the lifetimes story settled every question of “does the owner outlive the ref” by comparing declaration scopes, and the memory story guaranteed an object stays put for as long as its scope holds it. But a spawned call can still be running when its enclosing scope reaches the end of its lexical block. The scope’s owned objects are scheduled for destruction at that brace; the spawned work may still be reading them. The lexical guarantee, which presupposed that execution leaves a scope exactly once and only after everything inside it has finished, suddenly has a hole the width of every outstanding spawn.
The obvious escapes were all escapes we had already refused elsewhere. A garbage collector would paper over the problem by keeping objects alive until nothing references them — but the whole project is built on having neither a collector nor a lifetime vocabulary, and reintroducing one just for concurrency would be a quiet surrender of that bet. Reference counting every object that might be shared with spawned work pays a runtime tax on the common case to fix a rare one. Forcing spawned calls to take ownership, or to work on copies, would make the model safe by making it useless for the ordinary case — handing some live state to a background task. And the route most languages take — explicit join handles the programmer must await, thread::scope and its kin — puts the safety back in human hands, where a forgotten join is a use-after-free.
The resolution keeps the lexical spirit and pushes it through the spawn: a scope does not complete until every spawned call inside it has completed, and its owned objects are destroyed only when the scope finally drains (concurrency.md §4.1). The spec’s image is a vertical water tower with a horizontal plate held in place by each still-running spawned call; the water — destruction — cannot fall past a plate that is still there. Each finished call removes its plate and the level drops to the next; only when the last plate is gone does the water reach the bottom and ordinary destruction run. The scheme is satisfying because it adds no new vocabulary and no new runtime bookkeeping the model did not already have: it is the same scope-drain mechanism the destruction rules already used, with its trigger moved from “the block ends” to “the block ends and all its spawns have returned.” The lexical lifetime guarantee now simply extends to cover the concurrent work a scope launched, exactly as if that work were still inside the braces — which, in lifetime terms, it is.
The cost is real and worth stating plainly, because a reader will hit it. The granularity of the extension is the scope, not the individual object: one long-running spawn holds the whole scope’s owned objects alive until it returns, even objects it never touched, because the drain is all-or-nothing. There is no early release. And since the language offers no cancellation — the subject of a later chapter — a spawn that never returns holds its scope open forever, with no language-level way to pry it loose. We accepted this as the honest shape of “no GC, no join handles”: the safety is automatic and unforgettable, and the price is that liveness is coupled to the coarse unit of the scope and to the spawned call’s own willingness to finish.
Safety the compiler proves from signatures, not locks
The water tower guarantees a spawned call’s objects are still alive; it guarantees nothing about two spawned calls touching the same live object at once. Liveness is not enough — the classic hazard is the data race, two concurrent accessors of one object where at least one writes. The mainstream answers all push the work to runtime: locks and mutexes the programmer places by hand and hopes are correct, atomics for the brave, or a race detector that finds the bug only on the run where it happens to manifest. Each makes correctness a runtime property the type system never sees, which is precisely the kind of unprovable obligation the rest of the language works to avoid.
Zane rules the race out statically instead, and again it spends a debt the effects story already funded. The single-writer rule states that at most one concurrent mut accessor may exist for any object; two spawned calls that both need mut access to the same object are a compile-time error, not a runtime lock (concurrency.md §4.2). For state outside the object graph — files, sockets, the world — the effect system classifies each access as read or write and serializes anything that conflicts: read/read runs free, but read/write and write/write are forced into order, and the compiler arranges it from the effect signatures without the programmer writing a single lock (§4.3). This is the deep reason spawn targets only calls (from the previous chapter): both checks are read straight off the callee’s signature — its mut-ness, its resource effects — and a call is the construct that has a signature to read. The safety rule and the spawn-shape rule are the same decision seen from two sides.
This is also where the prohibition on capture earns its place. Lambdas and value-blocks must not capture outer variables; every dependency is passed explicitly (§5.2). The rule looks like an ergonomic tax until you see it from the analysis’s side: a capture is an access that the signature does not show, a side door through which a spawned closure could reach a shared object the single-writer check never counted. The alternative — allowing capture and inferring the captured effects through to the closure’s call sites — is exactly the whole-closure effect analysis the no-capture rule retires, and it would make the conflict check depend on flow the signature can no longer summarize. Forbidding capture keeps the signature the complete truth about what a spawned call touches. A last sharp edge is closed by §4.4: an & handed to spawned work resolves to its own value against the same owner, so rebinding the caller’s & symbol afterward retargets only the caller’s storage and cannot reach in and redirect the reference the spawned work already holds — the shared-mutable-binding hazard, removed by making the binding unshared.
The costs here are the most contentious in the document, and pretending otherwise would be dishonest. The single-writer rule is conservative at the granularity of the whole object: two spawned calls that write disjoint parts of one object, or that the programmer has coordinated by some scheme the compiler cannot see, are rejected anyway, because the check sees only “needs mut to this object,” not “needs mut to this corner of it.” Patterns that are genuinely race-free are turned away for want of a proof the signature can carry. And no-capture makes concurrent code verbose in the ordinary case — every dependency a spawned call needs becomes an explicit parameter, with nothing allowed to ride along implicitly. We took both costs deliberately: they are the price of a concurrency model with no locks to misplace and no race detector to run, where a program that compiles is already free of the data races the rules describe.
What the core deliberately leaves out
Having built spawn, the water tower, and signature-based safety, the strongest pull is to keep going — to furnish the concurrency core with the apparatus every mature concurrent language seems to grow: cancellation and kill groups, channels, an actor or process primitive, structured shutdown. We stopped instead, and the omissions are a design position, not an unfinished to-do list. There is no cancellation, no shutdown ordering: a spawned function runs until it returns or the process is killed from outside (concurrency.md §5.1). And there is no language-level Process type, actor, or channel; long-running concurrent work is just ordinary spawned calls plus state that flows under the ownership and effect rules already in force (§5.4).
The roads not taken are well-trodden and genuinely good — structured cancellation as in Kotlin’s coroutines or Go’s context, CSP channels as in Go, the actor model as in Erlang — so the reasoning for declining each matters. Cancellation is the feature we refused on principle rather than budget: a cancellable task must be stoppable at defined points, which reintroduces hidden suspension and a form of the control-flow coloring the first chapter spent its effort removing, and it tangles with the water tower besides — cancelling work that a draining scope is waiting on has no clear meaning. Channels and actors we declined on a different ground: they are orchestration philosophies, and baking one into the core would commit every Zane program to it. They belong in libraries, built from spawned calls and owned state, where a program can choose the model that fits rather than inherit ours. The throughline is the language-wide preference for a small, predictable core over a feature-rich one.
This is the chapter where the costs are heaviest, and they compound the costs before it. Without cancellation, runaway or no-longer-wanted work cannot be stopped from within the language; joined with the water tower, a spawn that hangs holds its scope’s objects alive indefinitely with no recourse short of killing the process. The orchestration patterns working programmers reach for daily — timeouts, fan-out/fan-in with early cancellation, graceful shutdown that drains in order — must be assembled by hand or supplied by libraries, and a few of them, true preemptive cancellation chief among them, simply cannot be built safely on top of this core at all, because the core gives nothing to build them from. That is the sharpest admission in the concurrency design: the model is deliberately small enough that some features everyone expects are not merely absent but out of reach, and we are betting that a concurrency core you can hold entirely in your head, with no hidden control flow, is worth more than one that ships every convenience and the unpredictability that comes with them.
Value-typed mutation: closing the aliased-write gap
The single-writer rule of the previous chapter turned out to miss a write that reaches an object through an alias, and closing that hole meant rebuilding the rule. The single-writer rule read the receiver instance off each spawned mut call and forbade two of them from naming the same object. What it could not see was mutation reaching an object by a second path. Zane lets you mutate through an &, and a reference type could hold an & field, so a wrapper holding &Engine and a bare Engine present two different receiver types at their signatures while both driving writes into the one Engine — one directly, one through the wrapper’s alias. The per-instance check passed; the data race did not. This was filed as issue #98, deliberately left open, with the spec and the chapter above left standing as the honest record of a rule that did not yet hold.
Closing it looked, at first, like a choice between two bad options. One was to make the single-writer check see the second path — compute each spawned call’s transitive mutation set and prove that two of them cannot alias. That is whole-program alias analysis, and it is exactly the non-local reasoning the rest of the language spent its effort avoiding; the lifetimes design bought its safety by looking at a declaration, not by tracing a program, and we were not willing to give that up here. The other was to serialize conservatively — force any two mut calls whose reachable types could overlap into sequence — which is sound but throws away the parallelism that was the point. Neither was a design we wanted to sign.
The way out was not to restrict mutation but to enable it, and that is the part worth getting right, because the restriction everyone remembers is a corollary of it rather than the idea itself. A value type’s alias-freedom was exactly the property that would make concurrent mutation safe — but it was useless while value types were immutable, because there was no way to express shared mutable state as a value in the first place. So the move was to make value types mutable in place. That is less small than it sounds: mutating a copy helps no one, so a mutation has to reach the caller’s real storage — a borrow, not a copy — and a mutable-yet-alias-free record did not exist as a kind at all. Supplying one is what forced struct and class apart into a single value/reference axis — a type is a value unless marked # (foundations.md §7) — with the value side transitively alias-free by construction, holding no & and no reference field anywhere downstream (memory.md §2.10). Only then, with a mutable alias-free value in hand, does the concurrency rule fall out for free: a spawned call may mutate only a value-typed receiver (concurrency.md §4.2). Because a value’s reachable graph contains no reference, there is no second path — the #98 wrapper cannot be built, since a type holding an & field is not a value type. The compiler rules out the aliased race from the receiver’s type alone, which is precisely the “check by looking” the alias-analysis road would have abandoned.
Two consequences fall out that make the rule look less like a patch and more like the design’s natural shape. First, since only value types are ever mutated by spawned work, reference types are frozen for the duration of the concurrency, so every concurrent read of the reference-typed object graph is safe with no further rule. Second, the old per-object single-writer check survives in a cleaner form: at most one live spawn may hold a mutable borrow of a given location (§4.3), and because value types carry no &, a location’s identity is unambiguous, so that disjointness is again a spawn-site check rather than a program trace. The one addition needed to keep real-time work honest is that a reader of a value another spawn is writing takes a coherent snapshot rather than blocking (§4.4) — copying a value is the snapshot — which replaces lock-based serialization for in-memory state and is why an audio reader never waits on a parameter writer.
The cost is real and it is the mirror image of the gain. Shared mutable state that crosses a spawn must now be expressible as a value — a self-contained tree with no internal sharing — because the rule lets you mutate only values concurrently. Genuinely graph-shaped mutable state, with aliased sub-objects or cycles, cannot be handed to two spawns at all; it has to be restructured into values or kept single-threaded. We think that is the right price, and not only because it is safe by construction: the patterns that most need concurrent mutation — a parameter block, an audio buffer, a snapshot of world state — are already value-shaped, and the patterns that are not are exactly the patterns where a silent data race would have been hardest to find. The rule that began as a hole in a per-instance check ended as a single sentence about the receiver’s type, and the reason it can be that small is that the value/reference axis had already done the work.
Closing gaps in the two signature-safety rules
The signature-based safety this document rests on is stated in two rules, and writing block arguments forced us to read both closely enough to notice that each one enforced less than its wording stated.
The first is the rule that a spawned call may mutate only through a value-typed subject. What it checked was narrower: the subject of the spawned call. A function has no subject, so a spawned function that mutated a reference object through an & parameter satisfied every check and violated the rule in the same breath — and the guarantee riding on that rule is a large one, that reference types are never mutated by spawned work and every concurrent read of the reference graph is therefore safe by construction. The gap was narrow in practice, since the mutation had to be routed through a parameter, but a guarantee that holds only usually is one the compiler cannot lean on. The fix belongs at the declaration rather than the spawn site: a verb that mutates a non-this parameter is unspawnable, a property the compiler settles once where the body is compiled, so no call site has to reason about a body it cannot see.
The second is the single-writer rule, which forbids two live spawned calls from mutably borrowing one location and checks it by inspecting the subjects at the spawn site. A spawn site inside a loop body is one site and many live calls — the water tower keeps every iteration’s work alive until the scope drains — so inspecting the site once settled nothing about iterations two onward. The remedy that stays syntactic is to require such a spawn to take its subject from storage declared inside the loop body, which gives each iteration its own location and needs no count of the iterations.
Neither of these came from the block work; both were already true and we noticed neither until adjacent work made us re-read the sentences. That is the honest account of how they were found, and it is worth recording because the whole no-locks position rests on these two rules: the reason we can refuse whole-program alias analysis is that these checks are supposed to be complete. A check that is nearly complete gives that up quietly.
spawn in a loop runs one pass at a time
spawn was built for a handful of workers that each do different work, a user interface on one and audio on another. A program that needs many workers running the same step, a server with a handler for each connection, had no means of expressing that need. The obvious attempt is a loop with a spawn in its body, and it runs serially. Each pass of the body is a scope, the water tower holds a scope open until the spawns inside it have finished (concurrency.md §4.1), and so each pass waits for its handler before the next begins. A worker’s step fares no better: it is a lambda with a frame of its own, and a spawn inside it waits for the step to drain.
Reading the drain rule against a loop also exposed a contradiction inside the spec. The chapter that closed the single-writer gaps had required a spawn in a loop body to take its subject from storage declared in the body, because “the water tower keeps every iteration’s work alive until the scope drains” (concurrency.md §4.3). Under the drain rule as written, no pass’s spawn outlives the pass, and the requirement protected nothing. One of the two sentences had to go. We kept the drain rule and dropped the requirement: a loop stays serial, and running many workers gets a construct of its own, so that a loop does not have to become one.
The construct arrived in stages. The first was a leaky scope, a loop body whose spawns outlive it, which we had first sketched together with explicit compile-time evaluation. It was a block-shaped concurrency construct, the road spawn refused when it came to mark only a call. The second was a worker over a container, one per element, joined when all of them finish. Each element is its own location, so the single-writer rule held by construction, but it covered only a set of workers fixed when they start. Connections arrive while others are being served, and a finished handler’s storage has to be released when that handler finishes, not when the scope that started them all drains. Both needed a value that owns running workers and frees each one’s storage on its own: a pool.
The cost is that the language now has two ways to start concurrent work that look alike from a distance. spawn starts one call and the scope waits for it; a pool starts many and frees each separately, and which to reach for depends on whether the workers are a few different tasks or many copies of one.
Workers send events to one owner: WorkerPool
A pool settled how many workers can run. It did not settle how they talk to each other, and almost every program that wants many workers needs them to. We wrote a chat server against the rules as they stood to find out what they allowed. A session cannot write another session’s socket, which belongs to another session, so no session can send to everyone: each one posts to an outbox of its own, and every other session reads that outbox by snapshot (concurrency.md §4.4) and delivers the new posts to its own client. Every safety argument in it came straight from the existing rules, and it was a channel built by hand: each session scanned every outbox many times a second, which grows with the square of the room, and a slow reader silently lost what the ring had overwritten.
Before designing anything we listed what workers in real programs read and write: web and chat servers, a game server and a game client, a publish-and-subscribe broker, a cache, a database, a crawler, a build system, a market-data feed. Nearly all of them fell into one pattern. A worker writes only its own session’s state. The state the workers share has a natural single owner, the world’s tick, the room, the order book, and the workers send it intents to apply rather than writing it themselves. Shared state does not need to be written by several workers at once. Order matters more than simultaneity, since every client of a room must see the same order and a game tick must apply its actions deterministically, and the systems built this way are single-writer on purpose: a game server’s main tick, Redis, the single-writer principle of LMAX. One owner is fast enough when it does nothing but the writes, with parsing, validation and the serving of reads left to the workers, and when it applies everything waiting in one batch, which raises its throughput as the load rises, the way a database’s group commit does. A general-purpose database is the exception, because which rows a transaction touches is only known when it runs, and Zane’s single-writer rule proves disjointness at compile time. Splitting its data into parts, each with one owner, is the answer that fits; a table that checks disjointness at run time and aborts on a conflict was the answer we left for later.
Our first sketch from that was three separate pieces: the pool, an inbox that workers move intents into, and the owner that drains it. Spread over three pieces it was too restrictive to use, so we folded it into one type, constructed with a function for events and given workers one at a time, each a step over its own element with a means of publishing events. We first called it Worker, and renamed it WorkerPool once we noticed that the spec already calls one subject with its step a worker (control-flow.md §3.7): every element is a worker in that sense, and a type holding many of them read as if it were one. The function that writes S was the handler until the spec’s other handler, the handler a ? attaches to an abortable call, made the word ambiguous; we named it the funnel, since many workers pour events in and one outlet applies them. The method that adds a worker became start rather than spawn, which would have reused the keyword for a different act, and what a pool holds became an element, as in any container, because “slot” was taken and “source” too, the latter kept as event source for what a worker waits on. Its first form needed refining in three places. That function needed state of its own to write, so a WorkerPool holds a shared value S, the function is its one writer, and every step reads it by snapshot. Publishing an event could not be treated as read-only, as the first form had it, because the function writes S in response, and a call the compiler took for a pure one could be folded, moved or dropped. So a publish is a write of the pool’s state, applied when the funnel takes the event, and the compiler may not fold, move or drop it; nobody writes a lock. An event also outlives the step call that published it, waiting in the queue until the funnel takes it, so an event is a value type copied in, as S is, and nothing it holds can die under it. And the first form let the handler answer an event, with the worker reading the answer the way a spawned call’s result is read, blocking at the read (§3.2). We dropped the answer once steps stopped blocking, as the next chapter recounts, since reading one would suspend a step; a funnel with news for a worker writes it into S. Each element is written by its own step and S only by the funnel, so no location has two writers (concurrency.md §4.3).
None of this makes WorkerPool a second spawn, and it does not walk back what the core left out. The two are for different work. spawn starts a specific process, one call that does one particular job beside the others, such as the user interface or the audio. A WorkerPool runs bulk work, many workers running the same step over elements of their own. A language meant for servers, and for most programs that serve many users at once, needs the second as much as the first, so Zane would have needed a mechanism to create bulk workers whatever shape it took. The funnel applies events one at a time, as an actor works through its mailbox, but a WorkerPool is not an actor system: its workers send only to their own funnel, the funnel sends nowhere, and nothing addresses anything else. General actors and channels, with messages between arbitrary parties, stay where the earlier chapter put them, in libraries. A library could not have built WorkerPool itself, because many workers writing into one queue is exactly what the single-writer rule forbids anything but the language to provide.
The costs are the costs a single owner always has. Its throughput is one core’s worth, and state that outgrows it has to be split into parts with an owner each. The queue between workers and owner has no limit, as a list has none, so a publish never fails and overload shows as a growing backlog rather than as an error. We considered a limit, which would let a worker notice overload and turn a client away, but every publish would then have carried a handler, and a program that wants to turn work away can have the handler record its backlog in S for the workers to read.
The runtime wakes a worker when its event sources are ready
A chat session has two reasons to run: its client sent a message, or the room changed. Our first WorkerPool sessions blocked in receive on the socket, so a session whose client was silent never got to the part of its step that delivers other sessions’ messages. The patch was a receive with a timeout, so every session woke on a timer to look at the room, and every message waited for the next tick.
Polling had a second form, which looked better until we priced it. A step that only checks whether its socket has data, and otherwise finishes so that work calls it again, never blocks. But if the runtime calls it again at once, every idle worker spins a core checking an empty socket, and a server is mostly idle connections. A timer between calls trades that for the latency we were trying to remove. The other roads put the waiting in user code. A primitive that blocks until any of several sources is ready would have worked, but it is suspension inside a step, close to what the chapter on omissions held against cancellation. Callbacks given to the WorkerPool were the last road. A callback run by the funnel cannot reach the sessions’ sockets, which belong to their slots. One run on each element would have needed the step to stop blocking anyway, and splitting a session into a callback for its data and another for the room’s changes turns straight-line code into a set of reactions.
What settled it was noticing that a step already is a callback: work calls it, it returns, and work calls it again. The only open question was when the runtime calls it next, and the runtime is the one place that can wait without spinning. Operating systems take a list of sources and sleep until one is ready, which is how every efficient server waits on thousands of idle connections. So a worker is started with the event sources it waits on, its socket in the chat server, and the runtime calls its step again when one of them is ready or when the funnel has changed S. A timer is a source like any other and is passed in the same way, as every event loop treats one. We briefly gave the pool a separate form of start that took an interval, mirroring workEvery, and dropped it: it made a timer a special case of the API when it is only another event source to wait on. Between calls the worker costs nothing. A worker started without event sources, bulk computation with nothing to wait for, is called again at once, as work already does. Inside a step, reads do not block: a read with nothing waiting gives nothing, and the step finishes. No step needs to suspend, and the language gains no waiting primitive.
The costs are small and real. A step that does make a stalling call is parked, as a spawned call is, so the design discourages waiting in a step rather than forbidding it. A step may also be called with nothing to do, when S changed but holds nothing new for that worker; it finds nothing and returns. And the runtime can wait only on event sources it can watch. The sockets of the intrinsic networking we plan will be such event sources from the start, but an event source behind C will need a mechanism to hand the runtime a waitable handle, such as a file descriptor, before a worker can be spawned on it.
A worker pool’s element may reference constants
The chat server written with WorkerPool would not compile, and the reason reached past chat. A session sends and receives on its socket through the network capability, and a capability is written only through this of a mut method that stores it (effects.md §6.2). Spawned work, though, may mutate only a value-typed subject (concurrency.md §4.2), a value type holds no &, and every handle is a reference type, as the FFI rules state outright: a spawned call never mutates one (ffi.md §5.6). Outside the root package’s console and runtime, no spawned work could write to the outside world at all. That also ruled out the audio worker spawn had been built for.
Our first fix was an exception for capabilities: a pool could own a reference-typed element if every & in it named a capability, since writes through a capability are already ordered. It worked, and it read as a special case made for I/O. The &Net is harmless not because it is a capability but because it is a constant. The value-type rule exists to rule out two paths reaching one mutated object, and an & to an object that nothing in the program ever writes or replaces is a path to nothing mutable, however many workers hold it. So the rule became general. A pool’s element may be a reference type when the pool owns it outright, because it was moved in, and every & reachable from the element names a constant (concurrency.md §6.4). A package constant is one, since package scope holds nothing mutable (packages.md §5.1). A capability is another: it has no fields for the program to write and is never overwritten in place, and what its calls change is state outside the program, which the rule for capability access already orders. An & to an object the program built and can still write stays forbidden, even when the workers only read it, because its owner could write it while they read.
The cost falls on configuration computed while the program runs. A table of routes built from the program’s arguments is not a constant, so it reaches the workers through the shared state, where they read it by snapshot, or is copied into each element. We preferred a rule that can be checked from what each & names to one that has to know which objects nobody writes while the workers run.
Making workers able to do I/O at all left them doing it one call at a time, which the FFI story takes up.
Parking is dropped: a wait holds back only its caller
Parking was the rule a worker pool leaned on when a step waited. A stalling call made with spawn, or made in a pool’s step, was parked: the runtime set it aside so that it held no thread while it waited. The previous chapter used it to make waiting in a step merely discouraged rather than forbidden. When the compiler came to implement it, we had to state which calls are stalling, and the spec had never stated it. No signature marks a call as one that waits, so the runtime had nothing to recognize a stalling call by. And to set a call aside in the middle of its body, the runtime needs every verb that might wait compiled so that it can suspend and resume, or a stack of its own for every call that might be parked. Either one is the hidden suspension that we ruled out along with cancellation in the chapter on omissions.
So we asked first what a worker waits for, and found that it need not wait for input at all. Input arrives as a callback. A step calls network!listen(3000, callback) and returns, and the runtime calls callback when a connection arrives on the port. Each worker can listen on a port of its own, and nothing sits in a read while the port is quiet. Waiting for time became register, which calls a step each time an event source is ready (the control-flow story). After that, the language has two calls that wait: a read of a spawned call’s result, which was always a wait, and register, which waits for its event source between steps (concurrency.md §3.4). Neither one needs a definition of stalling, because each is a call the compiler can name.
That left the question parking had answered: the effect of a wait on everything else. A step of a pool might read a spawned call’s result, or run a register of its own, and the language presents every worker as running at the same time as every other. A wait that held other workers back would break that, and it would make the cost of a wait depend on which thread the runtime had happened to run it on. So the rule is the rule that the concurrent model already implied: a waiting call holds back only its caller, whose statements after the call run once the wait is over. Every other spawned call and every pool worker keeps running, wherever the call is made, whether in a spawned call, in a step, or in code that runs without spawn. A call that waits is an ordinary call (§3.5): without spawn its caller waits with it, and with spawn its caller continues. The spec leaves to the runtime how it keeps that rule. A runtime can start a stand-in thread for each thread that waits, or suspend a waiting call off its thread and resume it once the wait is over.
The cost falls on calls into C. The runtime cannot see into foreign code, so a C function that blocks, a sleep or a read on a blocking socket, keeps its thread for as long as it blocks, and enough of them at once leave the pool without threads to run its other workers. We did not try to define stalling for C, since that would have been the stalling marker again, scoped to one boundary. The fix belongs to the bindings: a C library whose calls wait should reach Zane as an event source or a callback, as the planned networking will.
Why exports may do what spawns may not
A CLAP host calls a plugin from two threads: its main thread makes the GUI calls, and its audio thread calls process, at the same time. Zane had one model for work that runs at once, spawn, and it lets a spawned call mutate only a value-typed subject. Applied to exports, that rule would have forbidden the plugin’s own reference-typed instance objects. Yet overlapping export calls look like spawned calls, and both follow the same two rules: one writer per location, and snapshot reads. The difference lies in where the objects live.
A spawned call’s subject lives in a scope that other code shares, and a reference-typed subject may be reached through & values the compiler cannot see, so proving that no alias exists would need whole-program analysis. A C-held object lives in a top-level scope that nothing else reaches, so the argument C passes is its only path, and the store rule proves the absence of aliases (concurrency.md §4.7). What a spawn site orders through the compiler, a host orders through the host rule: it never runs two calls that write one object at once, and never runs a call that ends an object beside another call on it. C libraries document the same rule for their own objects. The closest precedent in Zane is a worker pool’s element, which may be a reference type too, because the pool alone owns it and every & it reaches names a constant or a capability.
So a plugin is split into two objects, one per thread, each with one writer. The GUI calls write the instance, process writes the audio state, and each reads the other as a snapshot that is tear-free and never blocks, so process never waits on the GUI. VST3 already splits a plugin the same way. The compiler adds one check of its own on top of the host rule: an export that writes its subject takes no second parameter that reaches it, because C might pass one pointer twice (concurrency.md §4.7 lists every check).
We rejected three alternatives. Lanes on exports, where the host guaranteed which calls never overlap and the compiler checked which lane writes each field, were needed only while one object’s fields were split between threads. One instance object with its fields split between threads would have had the compiler track which thread writes each field, and every written field would have had to be a value type. Spawns on reference-typed subjects were tempting by analogy, but the export case works only because a C-held object has a single path, and a spawn’s subject has no such guarantee.
The cost is trust. Zane trusts the host on two points, as it trusts a foreign signature: a pointer names a live object of the right type, and the host obeys the host rule. A host that breaks either gives the program no meaning the spec defines, exactly as a C plugin’s host would.
A spawn’s handler and its loans end where its block does
Two questions the spec had left open came back already answered by the compiler’s runtime, and both answers turn on the same moment: the end of the block a spawn is written in.
The first was when an abortable spawn’s handler runs. The spec stated that the handler attaches at the spawn and that reading the symbol blocks, and nothing about the thread, the moment, or a symbol that nothing reads. The runtime settles the call once, on the thread that made the spawn: at the first read of its symbol, or where its block ends when nothing has read it by then (concurrency.md §3.3). The handler is written in the spawning block and may write that block’s locals, so running it on the spawning thread keeps those writes in the order the block runs them. A block left early, by a return, an exit or an abort, still waits for the call as it drains, but the code the handler would have rejoined is gone, so the handler does not run and the outcome is dropped with the block.
The second was a race the safety rules did not cover. Spawned calls never write a reference-type object, so every concurrent read of one is safe among spawns, and a spawn holding a mutable borrow keeps the spawning block off that location. Neither rule spoke to the spawning block itself writing an owner it had passed to a spawn that only reads it. The block keeps running while the spawn does, so dial.reading = Gauge(Int(3)) beside a running glance(view) is an ordinary data race, and if the replaced member owned boxed data, the spawn would follow handles into freed blocks. So a spawn is lent every owner it is passed, directly or through a reference, until its block drains, and the block may not write a lent owner meanwhile (concurrency.md §4.3). A spawned mutation of part of a lent owner stays legal, since a concurrent read of it takes a coherent snapshot.
We looked at closing the gap from the writer’s side instead, by forbidding a spawned mutation of any value reached through a reference type. That gives up spawn world.physics!step() beside spawn world.audio!mix(), the parallel mutation of disjoint parts of one object that is the reason those spawns are allowed, and it closes nothing, because the writer in the race is the spawning block, not a spawn. We also looked at a runtime answer, versioning the block’s own writes so that readers retry them as they retry a spawn’s. That rejects no program, but it puts every write to a lent owner, and every read of one in the spawn, on the slow path. The compile-time rule costs nothing at run time.
Its cost is precision. The rule names the owner a reference points to, and a compiler cannot always follow a reference to its owner, so one that falls back on the reference’s type rejects some writes that would never race. The spec states the goal and leaves how closely a compiler follows references to the compiler, which can only grow more precise without changing the rule.
A publish goes to the running pool, and missed ticks merge
Two more open questions came back from the worker-pool runtime. The first was what a step’s publish function does once it leaves the step. The function value captures nothing and is the same for every pool of one event type, so a program can store it like any other value: in a value-typed element, which elements then copies out to the caller; in an event, which the funnel writes into the shared state; or in the element of a second pool, whose step calls it. The runtime finds the pool through the work that is running the call, so a publish goes to the pool whose step or funnel is running it, and a call where no pool of its event type is running it stops the program (concurrency.md §6.5).
That makes the second-pool case defined, and surprising: a publish function carried into another pool of the same event type publishes there, not to the pool it came from. We weighed making the function value carry its pool, which would send that event home, but a function value that carries its pool is capturing state, and lambdas capture nothing. Stopping the program in the second-pool case instead would need the same pool pointer to tell two pools of one event type apart. The rule we took keeps function values capture-free and describes the runtime’s existing behaviour.
The second was what a step slower than its timer sees. A timer is ready each time its interval has passed since it was last ready, and that left open a step that runs past several intervals. The runtime merges them: a timer is ready at most once per call of its step, and its next deadline is the first deadline on its schedule after the call, so a slow step is called once more, not once for each interval it missed (concurrency.md §6.3). Queuing the missed ticks would call a slow step back to back for intervals whose moment had already passed, and the step would fall further behind each time it ran long. A register on a timer counts the same way. The cost is that a step cannot read from its timer how many intervals it missed.