---
title: "27. Tasks and time"
url: https://una-lang.org/en/docs/spec/27-tasks-and-time/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/spec/27-tasks-and-time.md
---

# 27. Tasks and time

Status: Normative, edition 0.4 preview (ADR 0117).

How tasks run, wait and are bounded: lightweight tasks on a few workers, and later `within`, `first of`, `tasks` and `start`, and limits on grants. The rules of ADR 0117 join this chapter as they land, each with its conformance cases; until a rule has landed, the construct it defines is a syntax error (U0101) or its word is reserved (U0103).

**What has landed.** Sections 1 to 4, the runtime of tasks (ADR 0117 rules 1 to 3, slice S1). They add no construct and change no output, failure or trace of any edition: they say how the native backend runs the tasks of `together` and `together for` (`spec/19 §8`), and which flags bound it. Section 5, `within` and interruption (ADR 0117 rules 4, 5 and 13, IF2, slice S2), in edition `0.4`. Section 6, `first of` (ADR 0117 rules 4, 6, 10, 12 and 13, IF3, slice S3), in edition `0.4`. Sections 7 and 8, `tasks` and `start`, traces written as they happen, the interpreter's coroutines and the schedule both engines share under virtual time (ADR 0117 rules 7, 10, 11, 12 and 13, slice S4), in edition `0.4`. Section 9, limits on `Http` grants (ADR 0117 rule 8, IF4, slice S5), in edition `0.4`. Rule 3 of section 2, the reactor (ADR 0117 rules 3 and 4, slice S7), which changes when the waits of `Http` end, never an outcome, a failure or a trace.

## 1. Tasks and workers

1. **Tasks are coroutines.** In native code, each task of `together` and `together for` runs on a coroutine: a stack of its own, which the runtime can suspend and resume on the same thread. A task keeps its own heap, and the copies at its fork and its join are those of `spec/19 §8` rule 2 (ADR 0113).
2. **Workers.** Coroutines run on `--workers` operating-system threads, the workers, numbered from 0. A task runs on the worker chosen when it is forked, and never moves to another (pinning), so its heap, reference counts and runtime state are only touched by one thread. Placement is structural: a task forked as the `i`-th part of a block, `i` counted from 1 (the branch index for `together` and `first of`, the element index for `together for`, and for a started task its place among the `start`s of its `tasks` statement, in the order they run, those in quiet code not counted, §7 rule 5; a task started in quiet code counts as the part numbered by the position of its `start` in the program, so all the tasks one quiet `start` starts share a worker, a cost of quiet code only), by a task that runs on worker `w`, runs on worker `(w + i) mod N`, where `N` is `--workers` (ADR 0116 amendment, P6). The root task counts as worker 0 for placement: it runs on the `una-main` thread, which is not a worker, or, in a program with a `tasks` statement, on worker 0 itself (rule 3). Choosing it takes O(1) time, and the runtime keeps no placement state across blocks. So a task's worker depends only on the program's structure, never on how many tasks earlier code started: a counter shared by the whole run would carry the number of tasks that code forked into the timing of later blocks, and code that branched on `secret` data would then change the timing of a later `public` block, which a deadline turns into a value (ADR 0116 IF6).
3. **The root task** runs `main` on a thread of its own, with the stack that `--max-depth` needs (`spec/16 §3` rule 3), and waits at the join of its tasks. In a program with a `tasks` statement (§7), the root runs on a coroutine of worker 0 instead, with the same stack, so that it takes turns with the tasks it starts.
4. **Threads start before `main`.** The executable of a program that holds a task construct, a `within` or a `for ever` starts all its `--workers` workers, both helper pools of §2 at their full sizes and the timer thread of §5 before `main` runs (ADR 0116 amendment, P8), and `main` begins once every one of them runs, each worker with the state a task's resume needs already made. Before `main`, every worker has also run one task of a block through the runtime's whole path, from the start's reservation to the join, its closure a closure object copied into the task's heap at the fork, as the closure of every block is, and its value an object copied out of the task's heap and into the root's at the join, so what a task's first run on a worker makes, and the allocations of a task's copies at both ends, have happened whatever earlier code started (#1254): O(N) tasks for N workers, once per run, in batches of 64, with transient memory bounded by one batch. The state of the system allocator, the processor's caches and the host's load remain out of model (ADR 0116 amendment, P12). Whether a thread exists is then never state that earlier code left, possibly code on `secret` data, and no construct pays for starting one: in particular, no `within` starts the timer thread, whether or not an earlier `within` ran. It also fills the pool of task stacks to its 64 stacks, each of the size the largest task asks for, which every later stack has: a construct maps a stack only while more than 64 tasks are live at once, as its own structure decides, never because earlier code started fewer tasks than the pool holds. The pooled stacks are reserved address space; their pages are handed back and they count toward `--max-memory` only as a task uses them (§4). So a program with tasks reserves, before `main`, 64 stacks of the size §4 rule 1 gives for `--max-depth`, from the program's frame bound (#1152): about 1.6 GiB of address space at the default 10,000 for a frame bound of 1 KiB, and at most the 21 GiB that `--max-depth` alone gives (`spec/16 §3`). A system that refuses such a reservation, as Linux can under strict overcommit (`vm.overcommit_memory=2`), which charges every mapping in full, stops the run with U6003 before `main`; a lower `--max-depth` shrinks the reservation. A thread that cannot start, or a stack that cannot be mapped, stops the run before `main` with U6003, exit code 1, and no position. A program that holds none of these constructs makes no worker, no helper and no timer thread, and performs every host operation on its own thread, at no cost.
5. **The interpreter** runs the tasks of a block, and the branches of `first of`, one after another, in index order, on its one thread (`spec/19 §8` rule 1, §6). It runs started tasks on coroutines of that thread, one at a time (§8), with one exception for `Http` requests in a run that serves live peers, which may run on helper threads while their tasks park (§8 rule 2). It accepts the flags of §3 and checks them as the executable does.

## 2. Waiting

1. **Joins park.** A task that waits for the tasks of its block, at their fork or at their join, parks: its worker runs other tasks until the wait ends. So a join never holds a worker that its own tasks need, and a run cannot deadlock on its workers, with `--workers 1` included.
2. **Helper pools.** A host operation of a task that may block runs on a helper thread while the task parks:
   - `Files.read` and `Files.write`, on the file pool of `--file-threads` threads;
   - a `Console.print` whose output cannot take the line without waiting, on the same pool; a line that stdout can take at once is written by the task's worker;
   - the name resolution and the connection of an `Http` operation, on the I/O pool of `--io-threads` threads (rule 3).

   Both pools start at their full sizes before `main`, as the timer thread of §5 does (§1 rule 4). Each pool serves its operations first in, first out. The pools are separate, so requests never delay a `Files` operation or a print of another task. Only the operation's arguments and result cross to a helper; the task's heap, trace and state stay on its worker.
3. **The reactor.** The rest of an `Http` operation of a task runs on the task's own worker, and each wait on its connection parks the task on the reactor: one thread of the process that waits on every parked connection at once, through `kqueue` on macOS and `epoll` on Linux, and makes a task ready again when its connection is ready, when its deadline passes, when a host stop reaches it (ADR 0116 rule 12), or when its task is canceled (§5, §6, §7), but for a deadline's cut of its `tasks` statement, which wakes no parked task (rule 4). So a request that waits on a server that never answers holds no thread. The sockets of such requests are capped for the process at its soft limit of open descriptors less a reserve of a quarter of it, and at least 64, for `Files`, `Console` and the runtime: a request holds one place from its first connection to its end, and one that finds none free waits for one, first come, first served, a wait that its deadline and a cancellation cut. So requests can never take the descriptors that a `Files` operation of another task needs. The wait of the connection step in the I/O pool is covered by the request's deadline too. An interrupted request's connection is closed when its task resumes, before the task goes on. If the reactor cannot start, the whole operation runs on the I/O pool instead, with the same meaning. A task's `next` of `HttpServer` (`spec/31 §1`) that waits for a request parks on the reactor too, woken by the serve engine's signal for one waiter, by its deadline, or by its cancellation, so no number of tasks waiting in `next` holds a helper of the I/O pool that the `Http` operations of other tasks need (#1723); only when the reactor cannot hold the wait does it wait on a helper. The reactor's thread starts before `main` in a run whose grants include `Http` or `serve:` and whose program holds a task construct (§1 rule 4, ADR 0116 amendment P8), never at a task's first wait, and none starts under `--virtual-time`, where no task parks on it; a reactor that cannot start stops the run before `main` with U6003, as a worker that cannot start does.
4. **An interrupted exchange** (ADR 0116 amendment, P9, #1148). A request that runs on a helper of the I/O pool, without the reactor or with a grant that carries limits (rule 3), runs there until its exchange returns, so what the helper does after its task was canceled is bounded as follows. On the reactor, a cancellation that wakes the parked task (rule 3) raises the request's abandon too, so its exchange stops in the same way, on its task, and a job of it still waiting on the lookup or connect pools ends at once; a deadline's cut of its `tasks` statement wakes no parked task and raises no abandon (last item).
   - **On the pools, non-blocking.** A helper's request runs on its helper of the I/O pool, but for the lookup of its name and its connection, which it hands to the bounded lookup and connect pools of `spec/24 §4` rule 2 and waits for only until its deadline or its abandon. The client starts no thread per request, so a run's requests never take more than `2 × --io-threads + max(2, --io-threads / 4)` threads. From the connection on, the request never blocks on its socket: every read, write and step of the TLS handshake that would block waits with `poll` instead, for the time left before its deadline.
   - **The cancellation reaches the exchange, with no polling.** A cancellation of the task that interrupts its waiting request (§6 rule 7, §7 rule 4) abandons the request: a wait at a limit leaves its queues, never sent (§9 rule 4), and an exchange in progress is abandoned at its next I/O step. Its socket is shut down, which ends a wait on it at once; its wait for a lookup or a connection ends at once, which run on to their end on their pool's thread, residue that `L_res` covers, at most the pools' sizes, a connection job looking at the cancellation only between two addresses and each attempt bounded by the request's deadline; the flag is checked after each step, before the response is parsed to its end and before its body is decoded, so an abandoned exchange takes neither; it fails, its result dropped, and its connection is closed. On its helper, an abandoned exchange does at most one I/O step more: one read or write of at most 16 KiB, decrypted and parsed, or one step of the TLS handshake. A lookup or a connection it left in flight holds one pool thread until it returns, and that thread then closes what it reached: pool residue, bounded by the pools' sizes. No wait looks at the cancellation in slices: only a host stop in a `for ever` body, which the wake pipe may not tell, is looked at every 100 ms (`spec/26 §6`). At most `--io-threads` helpers can each be in such a step. That bound is a measure of cost; what makes the rule sound is the residue label `L_res` (`spec/26 §7` rule 5), which every timing site joins.
   - **A deadline is the request's own time-out.** A request waits no longer than the earliest deadline that covers it (§5 rule 6). The runtime passes that deadline to the helper as an instant of the monotonic clock, never as a duration counted from when the helper starts, so a request that waited for a free helper still ends at it, at its next I/O step.
   - **A task that a deadline cancels waits for its request.** When the deadline of a `within` around a `tasks` statement cuts its block, its started tasks share that deadline (§5 rule 5), and a task parked on a request is not woken: on a helper, it waits for its helper, whose exchange ends at the same deadline, at its next I/O step, with its own `TimedOut`; on the reactor, its waits run to their own time-out, the same deadline, and the request fails with `TimedOut` there too (#1266). The task then stops at its next check point. So the statement ends only once nothing of its work is left on a helper. Only a job that has begun on its helper is waited for: a task whose request is still queued for a helper is woken at once, and its request is never sent; it fails with `TimedOut` as well, and an `acquire` of `std.limit` queued the same way with `RateLimited` (§10).
   - **One outcome at the cut** (#1266). A request that a `within`'s cut of its `tasks` statement ends fails with `TimedOut`, its event that time-out failure, on every path: parked on the reactor, running on a helper, or still queued for one, never `interrupted`, which belongs to the other cancellations below. Whether a cut came, and so this outcome, is timing information (§5 rule 7, ADR 0116 rule 21): it MUST NOT depend on which path ran the request, which the grants' limits, `--io-threads` and the load of the pool decide, nor on whether the task or the statement saw the deadline first, a decision of the schedule that earlier code, possibly code on `secret` data, can move. `TimedOut` is the outcome that the request's own deadline, the same one, gives without the cut, the one the interpreter gives, and the one that waits for the helper instead of leaving residue on it. The runtime marks the cut on the statement's count of cancellation with a value of its own, so every wait tells it from another cancellation in O(1). A lookup or a connection that the deadline cuts may still hold a pool thread until it returns, bounded by the pools' sizes, which `L_res` covers. The cut meant here is a `within`'s around the statement: the deadline of a `for ever within` iteration cancels no task, and a `tasks` statement in such a body is counted by `L_res` whatever ends it. A task canceled otherwise, by a failure of the block, a race that its task lost or a cancellation from outside it, is woken at once, as §7 rule 4 says, and its request's residue is what `L_res` labels.
5. **Meaning.** Parking and helpers change when an operation runs, never what it does: its grants, its outcome, its event and its failure are those of `spec/14` and `spec/24`.

## 3. Flags

The executable (`spec/16 §3`), `una run` and `una test` take these flags:

| Flag | Range | Default |
| --- | --- | --- |
| `--workers <n>` | 1 to 1024 | the number of the machine's cores, at most 1024 |
| `--task-depth <n>` | 1 to `--max-depth` | 1000, or `--max-depth` when it is smaller |
| `--io-threads <n>` | 1 to 4096 | 64 |
| `--file-threads <n>` | 1 to 256 | 4 |

The executable and `una run`, not `una test`, also take `--serve-threads <n>`, 1 to 256, by default the number of the machine's cores, the threads that serve the connections of `serve:` grants (`spec/31 §6` rule 1); a run that serves nothing accepts it and uses none. A value that is not a number, or is out of its range, is a usage error, exit code 2, before `main` starts. `--task-depth` is checked against `--max-depth` whatever their order on the command line. `--task-depth` bounds the branches of `first of` (§6) and the tasks of `start` (§7): a branch may make at most that many calls below the depth of its block, a started task below the depth of its `start`, never more than `--max-depth` allows, and its stack is sized from that depth. Both engines apply the same limit, so both stop at the same depth.

## 4. Stacks and memory

1. **Stacks.** A task's stack is sized from the depth it may still use, as `spec/19 §8` rule 2 sizes it, and is mapped with an inaccessible guard region below it, so running past its end faults instead of writing other memory. Stacks come from a pool and are reused. In a run that filled the pool before `main` (§1 rule 4), every stack is mapped at the size the largest task asks for, while each task's budget stays the one its depth gives. (ADR 0117, amendment of 2026-11-09, accepted; #1152.) In an executable, the stack of a task that may still use `d` levels of depth has `min(16 MiB + d × F, S(d))` usable bytes, where `S(d)` is the size of `spec/19 §8` rule 2, which the interpreter keeps, and `F` is the program's **frame bound**: the largest frame the code generator laid out for any function compiled into the executable (its functions, lambdas, handler operations and entry wrappers, a superset of those a task can run), plus 16 bytes of call linkage and 16 of alignment, rounded up to 16 bytes. `F` comes from the program's text and `--max-depth` from the run's flags, so the size is public and the same for every input: it never depends on `secret` data, and the pool of §1 rule 4 still holds stacks of one size. A program for which the code generator cannot state some frame's size, or whose largest frame exceeds the 64 KiB of the guard region, keeps `S(d)`. Every call between compiled functions, direct, through a function value or to a handler's operation, passes the check of rule 2, and the runtime calls compiled code only at a task's base, so a level of depth holds at most one compiled frame; the 16 MiB hold the runtime's own work above the deepest call, a signal handler's frame and the task's base. A bound that were still too small would only stop the task sooner, with U6003 at the call by rule 2, never past its stack.
2. **Depth.** Every call checks the stack against its budget before it proceeds, so a task stops with U6003 at the call, as `spec/11 §7` says, well before its guard region. Reaching the guard region is a defect of the runtime, which ends the process by the signal.
3. **Memory.** The stack each task has used counts toward `--max-memory`, together with the heaps of the run (`spec/11 §7`, ADR 0061 amendment of 2026-10-18). It is measured at each call's depth check as the highest point the task's stack has reached, rounded up to 16 KiB, and released when the task ends. In native code this covers `main`'s stack too.

## 5. `within`

1. **Grammar** (ADR 0117 rule 5). In edition `0.4`, a statement's expression MAY take a deadline after its `with` clause, and `attempt` MAY take one:

   ```ebnf
   handled      = line_expr [ with_clause ] [ "within" add_expr ] NEWLINE [ INDENT handling { handling } DEDENT ] ;
   attempt_expr = "attempt" postfix [ "within" add_expr ] ;
   ```

   - **The word.** `within` is the word of a deadline right after `for ever` (`spec/26 §7`) and right after a token that ends an expression: a name, a capability reference, a literal, `)` or `]`. Anywhere else it stays reserved (U0103), so it is never a name. Before edition `0.4` it is a name, and a name after an expression is U0101.
   - **After `attempt`.** In `let r = attempt f(x) within d`, the `attempt` takes the deadline, so its `Result` holds the time-out. A `with` clause then follows the deadline: `attempt f(x) within d with @h = @g`. A `handled` whose expression is an `attempt` with its own `within` takes no second one (U0101).

   ```una
   import std.time (millisecond, second)

   let quote = fetch_quote() within 2 * second
     if error use cached_quote
   ```

2. **The deadline.** `d` is an `Int of Millisecond`, with `Millisecond` of `std.time`: a deadline in seconds, a unitless `Int` or another unit is U2028, and a type that is not an integer is U2001. It MUST be at least 1, a `refinement` obligation at `d` (`spec/12 §3`): `within 0 * millisecond` is U5001. It is evaluated first, before the `with` clause and the expression.
3. **The failure kinds.** `std.time` declares `pub kind Timed[E] = TimedOut | Failed(error: E)` and `pub kind Deadline = | Expired`, a sum of one variant (`spec/02 §2`). When `e` can fail with `E`, `e within d` fails with `Timed[E]`: `TimedOut` when the deadline passed, `Failed(error: x)` when `e` failed with `x` in time. When `e` cannot fail, it fails with `Deadline.Expired`. `attempt e within d` gives `Result[T, Timed[E]]`, or `Result[T, Deadline]`. A variant resolves by the kind its context gives (`spec/10 §11` rule 3).
4. **Handling** (`spec/06 §3`). `e within d` can always fail, so without an `if error` clause, and outside `attempt`, it is U3007. `if error use v` and `if error fail V(...)` take any failure. `if error pass` is legal when the function's error kind declares a variant `TimedOut` without fields, and `e` either cannot fail or fails with that same kind: `TimedOut` passes as the function's `TimedOut`, and `Failed(error: x)` as `x`. Otherwise it is U3008. No `fails` clause takes type arguments.

   ```una
   pub kind RouteError = NoPath | TimedOut

   plan(graph: Graph, start: Node, goal: Node) -> Route
     fails RouteError
   =
     let route = shortest(graph, start: start, goal: goal) within 50 * millisecond
       if error pass                       -- TimedOut passes as RouteError.TimedOut
     route
   ```

5. **Dynamics.**
   - The deadline is `d` after the run's clock reads at the `within`, real or virtual (`spec/26 §8`). It belongs to this `within`.
   - **In nanoseconds** (ADR 0116 amendment, P13). On the real clock the deadline is armed on a reading of the monotonic clock in nanoseconds, and every reading compared with it is one too: `e within d` has exactly `d` from the moment it was armed, to the resolution of the system's clock and sleep. A reading in whole milliseconds would give it between `d - 1` and `d` milliseconds, by the phase within a millisecond that earlier code left, possibly code on `secret` data. The timer thread fires each deadline at its own nanosecond: its timing wheel counts nanoseconds, with slots of one nanosecond at its finest level, and the thread sleeps until the wheel's next expiration, never to the end of a millisecond. Virtual time moves in whole milliseconds, and `Clock.now` reads milliseconds, as before.
   - **Past the deadline,** every interruptible operation waiting inside `e`, and every one that starts later, fails with its time-out failure, `HttpError.TimedOut` for `Http` (§6); `e` is canceled at its next check point (`spec/11 §7`): each call, operation and loop iteration, as a canceled task is (`spec/19 §6` rule 4). An operation in progress completes first, its handler's code included. Nothing inside it runs further: no handling clause, no inner `within`. Tasks started inside `e`, by `together` or `together for`, are canceled with it, and `e` ends once they have stopped. A `for ever` inside `e` ends as after a failure: its `on stop` runs on the state from before the loop, shielded from the deadline, and the cancellation then goes on (ADR 0116 rule 15). The cancellation leaves every frame of `e` as a failure does, releasing the values each one holds, so a program whose deadlines keep passing holds no more memory than one whose expressions fail.
   - **The outcome.** `e within d` succeeds only when `e` returns before its deadline, checked once more when `e` returns: an expression that returns at its deadline, or later, has missed it. Otherwise the result is `TimedOut` or `Expired`, even when `e` returned a value or a failure, which is dropped. In every outcome but success, `e`'s `edit` arguments keep their values from before the statement, as for any failure (`spec/17 §7` rule 1), and effects already performed stay (rule 2).
   - **Nesting.** An inner `within` whose own deadline has not passed never reports a time-out because an outer one passed: the outer cancellation goes through it, and only the outermost `within` whose deadline passed reports its time-out.
   - **Virtual time.** Under virtual time only the run's own waits move the clock (`spec/26 §8`), so a deadline passes inside `e` only through such a wait, as `std.testing.elapse` in a test's handler.
6. **Interruption** (ADR 0117 rule 4). In this edition the interruptible operations are those of `Http`. A request waits no longer than the earliest deadline that covers it, of a `within` or of a `for ever within` iteration, and fails with `HttpError.TimedOut` when it passes: its exchange ends at that deadline, at its next I/O step, on its helper or, parked on the reactor, on its task (§2 rules 3 and 4). What a request sent before its deadline passed stays sent, on either path, so an interrupted request is an effect in doubt.
   - **Never before the deadline.** An interruptible operation that a covering deadline ends, with its time-out failure (`RateLimited` for `acquire` of `std.limit`, §10), returns only once the run's clock has reached that deadline, in both engines, whatever unit a wait inside it counts in: a wait at a limit that reads the deadline in whole milliseconds reads the first millisecond at or after it, never one before. So when a `within`'s deadline cut an operation inside `e`, the `within` always finds its deadline passed when `e` returns, and times out with its `timeout` event (rule 7): a cut operation's `TimedOut` is never the failure of a `within` that succeeded in time.
7. **Trace.** A `within` that times out appends one event `{"seq": n, "outcome": {"kind": "timeout"}}`, with the `task` of its task and no operation, after the outcomes of the operations it interrupted, whose own events show their time-out failures (`spec/11 §5`), unless quiet code that is not `quiet timing` performed them (below). An operation in progress completes (`spec/19 §6` rule 4): the code of a handler serving an operation inside `e` is not cut by a deadline that was running when the operation began, so its event keeps its outcome, and `e` is canceled at the next check point after it. The outcome `{"kind": "interrupted"}` of ADR 0117 rule 10 belongs to an interruptible operation whose task is canceled while it waits, which `first of` brings (ADR 0117 amendment of 2026-10-19). Code inside a `quiet` expression appends no `timeout` and no `cancelled` event of its own, nor, unless the mark is `quiet timing` (`spec/09 §2`), the events of the operations it performs in a run's trace, and takes no `seq` for them (S-42, `spec/26 §6` rule 4).
   - **Canceled tasks.** When the cut stops a block of `together` or `together for`, or a `first of` (§6), inside `e`, every task of that block that has not returned ends with its event `{"seq": n, "task": "<path>", "outcome": {"kind": "cancelled"}}` (`spec/19 §7` rule 3), whether it had started or the cut kept it from starting, in the order of the tasks' paths, after the events the block's tasks wrote, and before the `within`'s `timeout` event. The start of each task is a check point for this rule, in both engines. So the events do not depend on the number of workers, nor on how many tasks had started: in both engines, a task that had not returned when the deadline passed gets exactly one `cancelled` event.
   - **Timing information** (ADR 0116 rule 21, IF5). Whether a `within` timed out, so its `timeout` event and the `cancelled` events of its tasks, and which tasks had returned when it did, depend on timing: on `τ(e)`, which may be above `public`. The trace records them as it records every outcome (`spec/11 §5`), under the accepted trace design of ADR 0116, as it records the `timeout` events of `for ever within`: an operator who reads a trace of a `within` whose `τ` is `secret` reads a bit of `secret` timing. The report's `timing` list names every such `within` (rule 9). Under virtual time a deadline passes inside `e` only through the run's own waits, a wait for a refill at a limit among them (§10), and both engines read the clock at every check point, so they cut `e` at the same one: these events, and the trace, are the same in every run and in both engines (§8 rule 3).
8. **Information flow** (ADR 0117 IF2). Let `t = τ(e)`, the timing label of `spec/26 §7` rule 5, computed by the same rule, with `ℓ(d)` included and with `τ_conc(e)` as §11 computes it.
   - **The failure** is labeled `t`, joined with the label of `e`'s own failure: `if error use v` runs under it and its value is raised by it (`spec/07 §7` rule 3), and `if error pass` and `if error fail` are U4002 when it is above `public`.
   - **The places `e` updates,** its `edit` arguments and the target of an assignment, MUST be labeled at least `t` (U4001 at the place, with the `within` as a related location).
   - **The timing floor.** Every operation inside `e`, and every call inside `e` with effects, is checked as if it ran under `pc ⊔ t`: the sinks of `spec/07 §7` rule 4 (U4003), and the effect bound of each call (U4002). Failures inside `e` keep the ordinary program counter.
   - **Residue.** `t` includes `L_res` (`spec/26 §7` rule 5, item 6), whether or not `e` makes a request: in a program whose started tasks or races make requests, every `within` is at least `internal`. A message about a label that `L_res` raised names the construct whose requests can be left running.
   - **Interruptible operations.** An `Http` operation that `e` can reach declares its failure `internal` (`spec/24 §5`), so `t` above `internal` is U4001 at the `within` (ADR 0116 IF8). A time-out over `Http` is therefore at least `internal`: it can be recovered from with `use`, `attempt` or `fail` under an `internal` handler, never passed on to a public failure.
   - **Computing `t`.** `t` depends on the whole package's call graph, so the checker computes it from a probe of its own checks, repeated until no label rises, and confirms after checking that no label it used was too low (U8001 otherwise).
9. **Report** (ADR 0117 rule 13). The report's `information.timing` list (`spec/13 §6`) holds each `within` whose `t` is above `public`, with its function and `t`, beside each `for ever within`.
10. **Core** (`spec/09`). `e within d` is `within(d, C_t, [C_w]) e`, with `d` an atom bound before it.
11. **Costs.** A `within` arms a timer in O(1) and ends it in O(1), in a timing wheel of 11 levels of 64 slots over nanoseconds of the monotonic clock, the finest slot one nanosecond wide, which covers about 584 years (ADR 0117 Costs; ADR 0116 amendment, P13). A timer fires in O(1) amortized: it moves down the levels at most 10 times, each move O(1), inside passes the timer thread makes at the start of a slot that holds it. Removal is eager: a canceled timer leaves the wheel at once, so after any history of armed and canceled timers the wheel holds only its live timers. Under the real clock, one thread per run, started before `main` (§1 rule 4), fires the timers, with one mutex that each `within` takes to arm and to cancel its timer. The thread wakes only at the next expiration, which is always a live timer's: its exact deadline, or the start of a slot that holds it, where it is cascaded, at most 10 times per timer and shared by the timers of that slot; when a timer earlier than that moment is armed; and when the timer it waits for is canceled, to wait for the next one instead. Arming moves the wheel's time to the moment of arming, so the moments a timer wakes the thread follow from its own arming moment and deadline, never from earlier code. Canceled timers cause no later wake; a task's check points see a passed deadline as a cancellation, so the check point's fast path is that of a task (ADR 0102). In the interpreter, each check point inside a `within` reads the clock once.

## 6. `first of`

1. **Grammar** (ADR 0117 rule 6). In edition `0.4`, `first of` races its branches, where a `block_expr` may stand: as the value of a `let` or of an assignment, or as the last line of a block.

   ```ebnf
   block_expr = when_expr | if_block | together_for | first_of ;
   first_of   = "first" "of" NEWLINE INDENT handled handled { handled } DEDENT ;
   ```

   ```una
   let quote = first of
     fetch_quote(url: "https://quotes-a.example/eur")
       if error pass
     fetch_quote(url: "https://quotes-b.example/eur")
       if error pass
   ```

   - **The words.** `first` opens a race only when `of` and the end of its line follow it. Anywhere else `first` and `of` are names, so the prelude's `first` stays a method. Before edition `0.4`, `first of` does not parse (U0101).
   - **Shape.** A body with fewer than two branches, or with a line that is not a `handled` expression (a `let`, a loop, a `when`), is U2035 at `first of`.
2. **Static semantics.**
   - **Tasks.** Each branch is a task, with the scope, capture and capability rules of a `together` branch (`spec/19 §2` rules 1, 3 and 4): it sees the bindings before the block and none of its siblings', and assigning, or passing as `edit` or `take`, a binding declared outside it is U2023. It is not a loop body for `stop` and `skip` (U2034), and it may not run forever (U3027).
   - **Types.** Every branch has one type `T`, the type of the `first of` (U2001).
   - **Failures.** A branch's failure is its expression's failure after its handling clauses (`spec/06 §3`), so a branch that can fail fails with the function's error kind (U3008), and `if error use` or `attempt` keep it from failing.
3. **Dynamics.**
   - The branches run concurrently. The first branch to return wins, and every other branch is canceled (`spec/19 §6` rule 4). The `first of` ends once every branch has returned, failed or stopped, with the winner's value.
   - A failure cancels nothing. When every branch fails, the `first of` fails with the failure of the lowest-indexed branch: all of them have ended by then, so the failure does not depend on timing.
   - A branch that runs too deep, past its depth limit (§3), or out of the run's memory, aborts the run with U6003, as a `together` task does (`spec/19 §8` rule 2).
   - A canceled branch leaves each of its frames by the path a failure takes, releasing the values each one holds, as a cut does (§5 rule 5), so a program whose races keep canceling branches holds no more memory than one whose branches fail. A branch that had already returned or failed when another won is not canceled: its result is dropped.
4. **Schedules.**
   - **The interpreter** runs the branches one after another, in index order, and stops at the first that returns, which is one legal schedule (ADR 0117 rule 11): no branch after it starts.
   - **Under virtual time** (`spec/26 §8`), native code runs the branches the same way, each to its end, in index order, up to the first that returns, whatever `--workers` is. So both engines give the same winner, output, failure and trace (`spec/16 §5`), also when the branches would end at the same virtual time: a tie goes to the lowest index.
   - **Under real time,** a run in which the winner decides the outcome is compared only for being an outcome the UAM allows under some timing (ADR 0117 rule 12).
5. **Paths.** The `i`-th branch of the `c`-th `first of` that the task `p` runs has the path `p.f<c>.<i>`, and `f<c>.<i>` in the root task, with `c` and `i` counted from 1. The paths of public code are unique, and differ from the numeric paths of `together` (`spec/19 §6` rule 1); those of quiet code are not (below).
   - **Quiet code** (S-39, S-40, `spec/26 §6` rule 4). A `first of` inside a `quiet` expression is not counted, and its branches have the paths `p.qf.<i>`, with no `c`. So whether quiet code ran a race, which may depend on data above `public`, never moves `c` for a later public one, nor the path of a later quiet one. A task started in quiet code runs in it (`spec/27 §7` rule 3), so none of its races are counted. Paths in quiet code are not unique: two quiet races of one task have the same paths, which only the events of quiet code carry.
6. **Trace** (ADR 0117 rule 10). The events of a `first of` are the winner's, then those of each other branch that started, in index order, each canceled one ending with its `cancelled` event (`spec/19 §7` rule 3); `seq` and the installation ids `with:<handler>#<n>` count in that order. When every branch fails, the events are in index order. A branch that never started has no events, unless a cut kept it from starting: a cut ends every branch that has not returned with its `cancelled` event, in index order (§5 rule 7).
7. **Interruption** (ADR 0117 rule 4). An interruptible operation, one of `Http` (§5 rule 6), that is waiting when its branch is canceled ends at once: its event has the outcome `{"kind": "interrupted"}`, with its operation and arguments, and the task stops, as at a check point, so its `cancelled` event follows. Its helper abandons the exchange at its next I/O step (§2 rule 4); what it sent before is an effect in doubt. Only the cancellation of the losers of a race, and of the tasks they started, interrupts a waiting operation: a task of `together` canceled by a failed sibling lets its operation complete, as `spec/19 §6` rule 4 says.
8. **Information flow** (ADR 0117 IF3). Let `t` be the join of `τ` of every branch, `L_res` included (`spec/26 §7` rule 5, item 6). Every branch runs beside the others (ADR 0116, amendment of 2026-10-25, C), so `t` is computed once for the whole race: the items of `spec/26 §7` rule 5 other than 5 and 6, over the race's code, every branch included, with item 4 as that rule states it (a lambda written at a call counts by its captures and its body, not as `⊤`), joined with `τ_conc` of the race at its own site (§11 rule 5), and with `L_res`. That is `κ(F) ⊔ τ_conc(F)` of C with `κ(F)` taken by IF5 as it stands; the `κ` of §11 rule 3, which counts a part that calls a prelude function with a function argument as `⊤`, is coarser, and it is what the sites inside a branch take through `ctx` (§11 rule 4), not `t` itself (draft amendment note `docs/plan/0116-race-label-note.md`). A race whose branches can reach an operation of `Http` raises `L_res` to its own `t`: a loser's request is cut before its time-out, and its helper's last step runs beside later code.
   - **The value** is labeled `t`, besides the labels of the winner's value, since timing decides the winner.
   - **The timing floor.** Every operation in every branch, and every call with effects, is checked as if it ran under `pc ⊔ t`: the sinks of `spec/07 §7` rule 4 (U4003), and the effect bound of each call (U4002), since a sibling that wins can cut it.
   - **The failure** follows the rules of `together` (`spec/19 §3` rule 2): whether the `first of` fails does not depend on timing.
9. **Verification** (ADR 0117 Verification). Each branch is verified alone, with the facts known before the block, as a `together` branch is (`spec/19 §4` rule 1). Each value a branch can return flows into `T`, whose refinements are obligations there. The result carries the facts of `T` only.
10. **Report** (ADR 0117 rule 13). The report's `out_of_model` list (`spec/13 §6`) ends with "waits at limits and at `start`" and "which branch of `first of` wins, beyond its label". Its `information.timing` list holds each `first of` whose `t` is above `public`, as `{"construct": "first of", ...}`, with its function and `t`.
11. **Core** (`spec/09`). `first of` with the branches `s₁` to `sₙ` is `first_of(s₁ | ... | sₙ)`, each `sᵢ` desugared with its `with` bindings, deadline and handling clauses, and closed over the bindings before the block.
12. **Costs** (ADR 0117 Costs). A `first of` of `n` branches starts `n` tasks, and its decision is one atomic compare-and-swap of the winner, followed by one cancellation of the other `n − 1`: O(n). The join adopts each branch's events once, O(events). Waking the losers parked on a request takes O(k log w), for the `k` waits on the race among the `w` of the process.

## 7. `tasks` and `start`

1. **Grammar** (ADR 0117 rule 7). In edition `0.4`:

   ```ebnf
   statement  = ... | tasks_stmt | start_stmt ;
   tasks_stmt = "tasks" [ "at" "most" add_expr "at" "once" ] NEWLINE INDENT block DEDENT ;
   start_stmt = "start" line_expr [ "within" add_expr ] NEWLINE [ INDENT handling { handling } DEDENT ] ;
   ```

   ```una
   tasks at most 100 at once
     for job in jobs
       start run_job(job)
         if error use log_failure(job)
   ```

   - **The words.** `tasks` begins a statement when, at the start of a statement, a newline and an indented block, or the word `at`, follow it. `start` begins a statement when, at the start of a statement, a name, a capability reference or `attempt` follows it. Elsewhere both are names: `start(x)`, `start = v` and a block that ends with `tasks` keep their meaning. Before edition `0.4`, such a line is U0101.
   - **Values.** A block whose last line is a `tasks` or a `start` has the value `unit` (`spec/17 §1`).
2. **Static semantics.**
   - **Where `start` stands.** In the block of a `tasks` statement, at any depth of `for`, `if`, `when` and `for ever` there; outside the block of any `tasks`, inside a task within it (a branch of `together` or `first of`, the body of a `together for`), or inside a lambda, which can be called once the statement has ended, it is U2035 at `start`. It refers to the innermost `tasks` whose block holds it.
   - **No `with` on `start`.** A `with` clause on `start` is U2035 at the binding: a `with` scopes over its statement, and the task outlives the statement. A handler that started tasks share is installed around the call of the function that holds the `tasks` statement; one installed inside the started function belongs to its task.
   - **The bound** is an `Int` (U2001) that MUST be at least 1, a `refinement` obligation at the bound (U5001), evaluated once, before the block. Without it, the bound is `max(64, M)`, `M` being `--max-memory` in MiB, and on Linux at most the cap of rule 4.
   - **The started expression** is a task, with the scope, capture and capability rules of a `together` branch (`spec/19 §2` rules 1, 3 and 4): assigning, or passing as `edit` or `take`, a binding declared outside it is U2023. It has type `Unit` (U2011), and it MUST NOT fail after its handling clauses (U3029): a call that can fail without `if error use` or `attempt`, `if error pass`, `if error fail` and `if none fail` are each U3029. A started call of a function that says `diverges` needs `diverges` on the enclosing function (U3027), also inside the body of a `for ever` or a task, since the `tasks` statement waits for it.
3. **Information flow** (ADR 0117 IF1, IF6). A started task runs under the program counter of its `start`, as a `together` branch does (`spec/19 §3` rule 1). The block of a `tasks` statement, and the functions it calls, run beside its tasks, so the timing label `τ_conc` (§11) covers them: the block is a part of the statement. A statement whose block or `start` expressions can reach an operation of `Http` raises `L_res` (`spec/26 §7` rule 5, item 6) to its own timing label and its `τ_conc`, since a cancellation can leave its tasks' requests on their helpers (§2 rule 4). How long a `start` waits at its bound, and the statement at its end, is timing, out of model (`spec/13 §6`).
4. **Dynamics.**
   - The block runs in the current task. `start e` starts a task for `e` and goes on; when as many tasks of its statement run as its bound, it first waits until one ends. A task started in quiet code (§7 rule 5) counts against the bound as any other does, so whether a `start` under a raised program counter ran can make a later public `start` wait, which in the interpreter reorders the public events: an open channel (#1545, `spec/26 §6` rule 4; a proposed amendment, `docs/plan/0117-quiet-bounds-amendment-draft.md`, would bound quiet tasks apart).
   - The statement ends once its block has ended and every task it started has ended, also when the block is left by `stop` or `skip` of an enclosing loop.
   - **A block that fails or stops** (a failure, a cut of a `within`, a cancellation) cancels every task the statement started (`spec/19 §6` rule 4): each stops at its next check point, an interruptible operation it waits on ends `interrupted` (§6 rule 7), and the statement fails or stops once they have all stopped. When the stop is the cut of a `within` around the statement, a task waiting on a request is not woken: it waits for its request, on its helper or on the reactor, which ends at that same deadline at its next I/O step with its own `TimedOut`, and a request still queued for a helper fails with `TimedOut` too, never sent: never `interrupted`, whichever path ran it (§2 rule 4). A canceled task leaves its frames by the failure path, as a cut does (§5 rule 5), so it holds no memory after the statement.
   - **A started task that runs too deep**, past `--task-depth` or short of its stack, in itself or in a task of a block it runs, ends alone: its events end with `{"seq": n, "task": "<path>", "outcome": {"kind": "aborted"}}`, stderr gets one line, `[U6003] Error: the started task <path> ended alone: <message> at <file>:<line>:<column>`, and the other tasks run on. Any other abort of a started task ends the whole run, as an abort of `main` does: the run's memory budget (U6003), a header value (U6004), host text (U6005), the hard stop (U6007).
   - **The cap.** On Linux each task's stack takes two memory mappings, so a run holds at most a quarter of `vm.max_map_count` started tasks at once, read when the run starts. A `start` past it aborts the run with U6003 at the `start`, `` this `start` exceeds the N started tasks this system allows at once ``, never with a failed mapping. A `start` whose stack cannot be mapped aborts the run with U6003 at the `start`.
   - **A host stop** reaches the `for ever` loops of the block and of the started tasks, at the start of their next iteration (`spec/26 §6`); the other started tasks run on, the statement waiting for them, until the hard stop.
   - **No handler instance outlives its statement**: a started task uses the capabilities in scope at its `start`, which the statement around it keeps alive until the task has ended.
5. **Paths.** The `k`-th task started by the `c`-th `tasks` statement that the task `p` runs has the path `p.s<c>.<k>`, and `s<c>.<k>` in the root task, with `c` and `k` counted from 1. The paths of public code are unique, and differ from those of `together` and `first of`; those of quiet code are not (below).
   - **Quiet code** (S-39, S-40, `spec/26 §6` rule 4). A `tasks` statement inside a `quiet` expression is not counted, as a race is not (§6 rule 5): its path part is `qs`, with no `c`, and a later public statement keeps its `c`. A `start` inside a `quiet` expression, which a `start` under a raised program counter is in a `public` statement too (S-40, #1512), is not counted either: its task has the path `p.s<c>.q`, or `p.qs.q` in a quiet statement, with no `k`. Since #1684 a `start` under a program counter above `internal` is U4002 in any case (§8 rule 5), so quiet tasks stand under `internal` data at most. So whether a `start` under a raised branch ran moves neither `k` for a later public `start` of the same statement, nor the worker that `k` places it on (§1 rule 2), nor the path of a later quiet task, whose events may occur whatever the secret (`spec/26 §6` rule 4). Paths in quiet code are not unique: the quiet tasks of one statement share theirs, which only the events of quiet code carry. A quiet task is placed by the position of its `start` in the program (§1 rule 2). This is a known cost, in quiet code only: every task one quiet `start` starts, such as those of a quiet `for` loop in a `tasks` statement, runs on one worker, since no count of quiet `start`s can place them without showing how many ran. Two quiet tasks that run too deep write the same U6003 line, which names their shared path.
6. **Verification** (ADR 0117 Verification). Each started expression is verified alone, in the context of its `start`, as a `together` branch is (`spec/19 §4` rule 1). The block is verified as a block in the current task. A `start` gives no fact, and no fact about an outer binding changes across it.
7. **Core** (`spec/09`). A `tasks` statement is `tasks(b) e`, `b` the bound, an atom bound before it, or none, and `e` its block, which returns the tuple of the outer bindings it updates, rebound after the statement (`spec/17 §4`); an `exit` of an enclosing loop in `e` crosses the statement. `start e` is `start(e)`, `e` desugared with its deadline and handling clauses and closed over the bindings before it.
8. **Report** (ADR 0117 rule 13). The report's `out_of_model` list (`spec/13 §6`) holds "waits at limits and at `start`".
9. **Costs** (ADR 0117 Costs). A `start` takes O(1), besides the copies of its captures (ADR 0113) and a stack from a pool in O(log k); one at its bound parks in O(1) and is woken in O(1). The end of a statement costs O(1) per task that ended. A program without a `tasks` statement pays nothing for this section.

## 8. Traces, schedules and equivalence

1. **Traces written as they happen** (ADR 0117 rule 10). The root task and the started tasks write their events as they happen; the tasks of `together`, `together for` and `first of` keep theirs until their join, which adopts them as §6 rule 6 and `spec/19 §7` rule 2 say, into the task that runs the block. `seq` numbers the events in the order they are written. An operation's event is written when the operation ends, after the events of the handler code that served it. The events of a block's tasks are numbered when the block's task writes them, after those that started tasks wrote meanwhile.
   - **Installations.** The root task and the started tasks number the handler instances they install with `with`, `with:<handler>#<n>`, run-wide, in the order the installations happen; the tasks of a block keep their numbering until their join, which numbers them as before. Quiet code (`spec/26 §6` rule 4) counts none of its installations: each is `with:<handler>#q`, which a join leaves as it is, so how many it installed never shows in an id (S-41); the operations such an instance serves append no event (#1544). This holds in every edition, the root task's installations included (`spec/11 §5`).
   - **`--trace <file>`**, on the executable (`spec/16 §3` rule 4) and on `una run`, writes the trace to the file as a JSON array as it goes: `[` with the first event, each event as it is written, and `]` when the run ends, so a finished run's file is the array of `spec/11 §5`, and a long run's trace does not grow in memory. A file that cannot be made is a usage error, exit code 2, before `main` starts. `una run --json` still holds the whole trace in its document.
   - A run that executes no `tasks` statement has the trace of `spec/19 §7` rule 4. A run that does has the order of real time across started tasks, out of model as the order of effects across tasks already is (`spec/07 §1`).
2. **The interpreter's schedule** (ADR 0117 rules 11 and 12). The interpreter stays deterministic for a given host behavior and runs on one thread, but for the helper threads of `Http` requests in a run that serves live peers (last item). In a run whose program has a `tasks` statement, the root task and each started task run on `una-sys` coroutines, one at a time:
   - they wait in one first-in, first-out queue; the task that runs goes on until it parks (a `start` at its bound, the end of a statement waiting for its tasks), ends, or has passed 1024 check points in its turn while another task is ready, and then goes to the back;
   - a started task joins the back of the queue when it is started, and the task that started it goes on; a parked task joins the back when a task it waits for ends;
   - `together`, `together for` and `first of` run inside the turn of the task that runs them, in index order;
   - **check points** are each call, each operation, each loop iteration, and each element of a prelude function over a list (`map`, `filter`, `first_where`, `fold`), counted on Core IR, the same in both engines;
   - a started task's stack is sized from `--task-depth`, as native code sizes it; host operations run on the interpreter's thread, except an `Http` request in a run whose serve engine serves live peers (`spec/31 §1` rule 10) and whose program has a `tasks` statement, made while one of the places of §2 rule 3 is free, of the number native code counts: there the request runs on a helper thread while its task parks, with the same outcome, holding that place until it returns; a request that finds no place free runs on the run's thread; nothing interrupts a request in flight but its deadline and, in the body of a `for ever`, a host stop, so a canceled task's request runs to its deadline, its result dropped and its event showing its own outcome where native code writes `interrupted`; and the task joins the back of the queue once the request has returned, so the order of the run's tasks also depends on when requests return, as the order of its requests already depends on when peers send them (ADR 0117, amendment of 2026-11-09).
3. **Native code under virtual time** (ADR 0117 rule 12). Under `--virtual-time`, native code follows the interpreter's schedule: one worker, whatever `--workers` says; the root on a coroutine of it in a program with a `tasks` statement; the tasks of `together`, `together for` and `first of` one after another, in index order, each to its end, on the turn of the task that runs the block; every check point counted, and the switch after 1024 of them between the root and started tasks; host operations run on the worker. So both engines MUST give the same output, exit status, failure and trace for any run of the constructs of this chapter, `tasks` included.
   - An executable built with check elision (ADR 0112) refuses `--virtual-time`: a usage error, exit code 2, before `main` starts, since a check point compiled away would move the switches. The equivalence tests build with `--no-elision`.
4. **Native code under the real clock** (ADR 0117 rule 2). Started tasks run on `--workers` workers, pinned, each worker's queue first in, first out; a task's turn ends at a check point once 10 ms have passed since the later of the turn's start and the moment another task became ready on its worker, while that task still waits, through the worker's attention word. When a turn ends MUST depend only on those two moments, kept in nanoseconds of the monotonic clock: the run's slicer starts before its first task runs, whatever the program starts later, and never ticks on a phase of the run, and the time a task ran alone, as the root does before its first `start`, never shortens the turn a waiting task sees. So whether or when earlier code started a task, and how long it ran, `secret` code included, never moves the end of a later turn (ADR 0117 rule 2, IF3). A run in which the schedule decides the outcome is compared only for being an outcome the UAM allows under some timing: each task's events and lines in its own order (`spec/19 §8` rule 4). The installations of started tasks happen in that order too, so the run-wide numbers of rule 1, `with:<handler>#<n>`, follow it: two started tasks that both install handlers may interleave their numbers, where the interpreter's schedule gives each task's in turn, and the comparison sets aside one renumbering of the run's installations, never more (#1542): a one-to-one renaming of the native ids onto the interpreter's, which keeps each handler and, within each task, the order of each handler's numbers, and leaves quiet, host and `given` ids as they are. The two runs need not show the same numbers: an installation whose instance serves no operation has no event, and under the real clock it can take a number before another task's. Under `--virtual-time` the whole traces are compared, ids included (rule 3).
5. **Check points that labeled data decide** (#1684, a conservative rule until an amendment of ADR 0117 makes the switch of rules 2 and 3 independent of them). The switch of rule 2 follows how many check points each task passes, the root task included, which counts its turn from the start of the run, so a count that data above `internal` decide would order the tasks' later effects by that data, in the interpreter and under `--virtual-time` the same in every run. In a package whose code holds a `tasks` statement, that has a `serve` section, whose driver runs each request's `handle` as a started task (`spec/31 §7` rule 4), or that calls a dependency not checked with it, each of these is U4002 when data above `internal` decide it, in code that a run of the program can reach (#1707): every function but a private one that only other such functions, or `test` declarations (`example` declarations in editions 0.1 and 0.2), call. The roots of that reach are each `pub` function, which a dependent package or the host can call (every entry, `handle`, `on_stop` and `[drive]` step is `pub`), and each function that a handler's operation or a lambda calls; each predicate, policy and `via`, each function of a standard module, each function used as a value, and each function that code outside every function but a `test` calls, are roots too, defensively: each already has a call edge from the code that reaches it, so they keep the rule from refusing less should an edge be missing; the reach follows the calls of functions in the call graph of ADR 0116 P1, O(F + E log X) for the X tests. `una test` runs tests, a run of the program never does, so a check point that only a test reaches moves no schedule of the program's started tasks, and the report's `information.timing` does not list it as a `task switch` either (`security/task_switch_example_only`, with its twin `security/task_switch_reached`):
   - a call of a function written in Una, any function but one of the prelude that takes no function, or of a function value, under a program counter above `internal`, joined with the effect floor of an operation body (`spec/07 §7` rule 4) and, for a function value, with its label, which decides which code runs;
   - an operation under such a program counter;
   - a `for`, `for until` or `for ever` loop whose body runs under such a program counter: the enclosing one joined with the label of the loop's range, list or condition (`spec/17 §3`, `spec/26 §4`);
   - a call of `map`, `filter` or `fold` whose arguments' top labels, joined with the program counter, are above `internal`, and of `first_where` with every label of its arguments, the labels of the predicate's parameters and result included, since its predicate decides how many elements it visits; the dense `map`, `zip_map`, `update` and `fold` of `spec/29` count as `map` does, by the top labels of their arguments;
   - a call of a function whose code the label rules do not check, in a standard module other than the prelude, in a dependency not checked with the package, or the `via` of a policy, with an argument one of whose labels is above `internal`, those of a function value's parameters and result included;
   - a call of a generic function whose code holds such a check point that only a type parameter's label decides, when one of the labels of its arguments is above `internal`, those of a function value's parameters and result included, since a function value's result can instantiate a type parameter; or, for a generic function used as a value, that check point itself;
   - the bound of a `tasks` statement, `at most n at once`, when the deep label of `n` is above `internal`: how many tasks run at once orders their effects too.

   The right operand of `and`, `or` and `implies` runs under the label of the left one, as the `if` of Core does (`spec/09`). A recursion needs no item of its own: it ends at a decision, so a depth that labeled data decide puts its recursive call under a raised program counter. `stop` and failures on labeled data already need a program counter that the loop or the caller starts with (`spec/26 §3`, `spec/07 §3`), and `skip` changes no count. A `start` under a raised program counter starts a task whose started call is such a check point, so it is U4002 too. The timing floor of a `within` does not count: a deadline cuts at a check point once the clock has passed it, and the interpreter's clock moves only with the run, never with a count of check points (but under the cost clock of rule 6, a mode for testing). The rule is coarse: a branch whose sides pass as many check points is refused too. It leaves out data at `internal`, as every request of `HttpServer` is (`spec/31 §1`): their count of check points may still order the public effects of started tasks, a known residual of the preview (#1708), open until the project decides between the amendment of ADR 0117 and a rule at `public`. The report lists each check point of the residual in its `information.timing` list (`spec/13 §6`), as `{"construct": "task switch", "function": "m.f", "label": "internal", "site": {...}}`: every one that the items above would refuse with `public` in place of `internal`, and that they do not refuse, so that a reader of the report sees where data at `internal` can order the effects of the package's tasks. The entries appear once the package is accepted: a package refused for any reason has a report of its diagnostics only. The depth of a started task is a channel of the same kind (#1677). A task that runs past `--task-depth` ends alone and the run goes on (§7); so does one short of its stack, whose frames' sizes its code fixes, not its data, so that case ends alone at a depth as the first does. What can then follow the data that decided its depth: whether its own later effects happen (prints, writes, operations on a handler's state that later code reads, `Http` requests a peer sees); its auto-answers, which IF6 bounds (`spec/31 §1`); the order of other tasks' effects, since a task that ends early frees its place under `at most n at once` and passes no more check points, which is #1708's residual; and its `aborted` event and line on standard error, which are the operator's output, out of model as the timing of the run is. The run's exit status does not change. Above `internal` such a recursion passes a check point under a raised program counter, so **this rule is what closes the depth channel above `internal`** (`security/task_switch_recursion`): an amendment that withdraws or narrows it MUST keep a rule for the depth of started tasks, or #1677 reopens above `internal`. At `internal` the channel is a known residual (`security/task_depth_internal`). A call in the right operand of `and`, `or` or `implies` under a left operand above `internal` is a check point that rule refuses (`security/task_switch_short_circuit`); a call with effects never stands there at all, since it must be the whole expression of a statement or `let` (U3013, `security/short_circuit_effect`). Its cost is O(1) per check point while the package is checked, and one pass over the recorded sites and generic calls after it for each of the two bounds, with ordered sets: O((sites + calls) log n).
6. **The cost clock** (ADR 0117, implementation plan step 7, #973). Under `una run --virtual-time --cost-clock` (`spec/13 §5`), the interpreter's virtual clock also moves by one millisecond, one tick, at each check point of rule 2, before the check point reads any deadline; nothing else changes the clock's rules (`spec/26 §8`). The run's time then follows how much work it did: a `within` or `for ever within` deadline passes after as many check points as it has milliseconds, a limit refills as check points pass, and `Clock.now` reads the run's count of check points plus its waits. So a deadline that a count of check points decides shows in the run's values, and a timing label (§5 rule 8, §6 rule 8, `spec/26 §7` rule 5) that misses data deciding that count turns into a difference of values that the security hunt's two-run oracle sees (`docs/plan/security-hunt-oracle.md`). The schedule of rule 2 is unchanged, and so is `first of` under virtual time: its branches still run in index order, each to its end. A run under the cost clock is deterministic: the same program and inputs give the same output, failure and trace. It is a mode of the interpreter for testing, not a time of the program: native code does not take it, so it has no equivalence across engines, and `una test` keeps the plain virtual clock. Its cost is one O(1) addition per check point, only in a run that asks for it.

## 9. Limits on grants

1. **Syntax** (ADR 0117 rule 8). In edition `0.4`, an `http` grant MAY carry limits. In `ita.una` they are lines under the grant (`spec/30 §2`):

   ```ebnf
   limit_line = "at" "most" int_lit ( "per" ( "second" | "minute" | "hour" ) | "at" "once" ) NEWLINE
              | "waiting" "at" "most" int_lit NEWLINE ;
   ```

   ```una
   run
     grants
       http "https://api.payments.example" get, post
         at most 100 per minute
         at most 8 at once
         waiting at most 1000
   ```

   In the text form of a grant spec (`spec/13 §5`), as `--grant` takes it, they are suffixes after the methods, each `;` and one of `<n>/second`, `<n>/minute`, `<n>/hour`, `<n>/once` and `waiting=<n>`, in any order: `http:https://api.payments.example:get,post;100/minute;8/once;waiting=1000`.
   - **Errors.** Each of these is U7008 at its line in `ita.una`, and makes a `--grant` spec invalid, a usage error: a limit line of another form, or one with lines below it; a count below 1 or above 2^31 − 1; a limit on a grant other than `http`; a kind of limit given twice on one grant, two rates counting as one kind whatever their periods.
   - **Editions.** Limits exist in edition `0.4` and later only: `una.toml` (editions `0.1` to `0.3`) has no form of them, and a limited `--grant` for a package of an earlier edition, or for an executable that embeds no `L_lim` (rule 5), is a usage error, exit code 2, before `main` starts.
2. **Meaning.**
   - **Per period:** at most `n` requests per second, minute or hour, in a burst of up to `n`, then one every period divided by `n`: a token bucket kept by GCRA, the generic cell rate algorithm, over the run's clock (`spec/26 §8`): the monotonic clock from the run's start, or the virtual clock of `--virtual-time`. A wait for a refill is a wait on time: under virtual time, where a host operation runs without parking, it moves the virtual clock to the refill, or to the request's deadline when that comes first (rule 4), so both engines give the same outcomes and readings of `Clock.now`, and the run takes no wall time to wait.
   - **At once:** at most `n` requests of the grant in flight.
   - **Waiting:** at most `n` requests waiting at the grant's limits, 1024 without the line.
   - **Several grants.** A request is charged to every grant that allows it (`spec/24 §2` rule 2), so a broader grant without limits does not bypass a narrower one with limits. Each hop of a redirect chain (`spec/24 §2` rule 3) is a request of its own, charged to the grants that allow its target.
   - **Below every handler.** The limits are enforced in the host layer that both engines share, below every handler and every rebinding: a rebinding shares the instance (`spec/11 §2`), so `with @x = @y` and `with @x = @y[ops]` stay limited.
   - **Scope.** Limits are per run: several processes, or a restart, each have their own.
3. **No deadlock.**
   - A request takes the tokens and slots of every grant that allows its target all at once, or none, holds its slots while it is in flight, and releases them when its response is read, before a redirect asks for its own.
   - A request holds nothing while it waits, and a request that holds slots never waits for a limit, so no cycle of waits can form.
   - **First come, first served.** A request that must wait gets a ticket, and is served when, for every limited grant it needs, it has the lowest ticket among that grant's waiters and the grant has a token and a slot free. A new request is served at once only when no request waits at any grant it needs. So the waiter with the lowest ticket waits only for capacity, and no waiter starves.
   - A request in a run where a grant carries limits never parks on the reactor: it runs on a helper of the I/O pool (§2 rule 3), and holds its slots until the helper returns, so the count in flight is never understated; and its wait at a limit holds its helper (`spec/24 §4` rule 4). An exchange whose task was canceled ends at its next I/O step (§2 rule 4, ADR 0116 amendment P9, ADR 0117 amendment of 2026-10-27), and its helper returns then: its slots are released at that moment, not when the peer would have answered, and a request waiting for them before that still waits.
4. **Waiting.** A request over a limit waits in the grant's queue, an interruptible wait:
   - **A full queue.** When a queue it must join holds `waiting` requests, it fails at once with `HttpError.RateLimited`, a variant `HttpError` has in edition `0.4` and later only, after `Interrupted` (`spec/24 §1` rule 3). The interpreter runs started tasks and the branches of a race one at a time, with host operations on its one thread (§1 rule 5, §8 rule 2), and so does native code under `--virtual-time` (§8 rule 3): there a grant never has two requests in flight or one waiting, so a full queue, and its `RateLimited`, occur only natively on the real clock, one of the outcomes the timing allows (§8 rule 4), and in the interpreter in a run that serves live peers and has a `tasks` statement, whose requests on helper threads and the one on its thread share the run's limits and can wait at them together (§8 rule 2, ADR 0117 amendment of 2026-11-09).
   - **Time.** `--http-timeout` covers the time it waits (`spec/24 §4` rule 2), and so do the deadlines of a `within` (§5) and of a `for ever within` iteration (`spec/26 §7`): past the earliest, it fails with `HttpError.TimedOut`, without being sent.
   - **Cancellation and stops.** A cancellation of its task that interrupts a waiting operation (§6 rule 7, §7 rule 4) ends it `interrupted` and takes it out of the queue, never sent, which a deadline's cut of its `tasks` statement does not: the wait ends at that deadline with its time-out failure (§2 rule 4); a host stop in the body of a `for ever` ends it with `HttpError.Interrupted` (`spec/26 §6`).
5. **Information flow** (ADR 0117 IF4). Whether a queue is full depends on when every request on its grant was made. A grant's bucket and slots are shared by every request of the run, so the time between two requests counts too (ADR 0116 P10, P11). `L_lim` is the meet of two labels, each of which covers that history:
   - **P10's, over the ancestors:** the join, over every site `s` that performs an operation of `Http`, of `τ⁰` of the body of every node from which the function holding `s` can be reached in the call graph of ADR 0116 P1, that function included (functions, the operations of handlers, which a call reaches through an operation of the handler's capability, and every lambda, which a call of a function value reaches), and of `τ_conc` at `s` (§11). Code that runs between two requests of one task lies in the body of such an ancestor of the later request, or in what it calls. At a site in a function's body, `τ_conc` never exceeds the ancestors' `τ⁰`.
   - **P11's, over the code between requests** (issue #1155): the join of `Gap(f)` over every function, operation of a handler and lambda `f` that can reach a request, of the driver's gaps in a driven run (all of `τ⁰(step)`, `Suf(init) ⊔ Pre(step)` and `Pre(on_stop)`), and of `τ_conc` at every site. `Pre(f)`, `Suf(f)` and `Gap(f)` are the labels of the code from `f`'s entry to its first request, from a request to its exit, and between two of its requests, over a control-flow graph of `f`'s Core IR whose nodes are its steps of evaluation (`spec/11`): failure edges lead from each step that can fail to its handling clause or to the exit, every step inside `e within d` has an edge to the deadline's cut, loops have their back edges, `start` and the task constructs are calls of their tasks, and a prelude function that applies a function argument takes the summaries of every lambda, with `τ⁰` of its arguments in its `Gap`. A call that reaches a request adds its callee's `Pre`, `Suf` and `Gap`; a loop whose body reaches a request counts its whole body; within one strongly connected component of the call graph every summary is `τ⁰` of the component's bodies. `Gap` also joins the label of the failure of every step that can fail, and the whole `τ⁰` of every step inside a `within` with the label its time-out carries, from which a request can be reached, since they decide whether a later request happens. Code before a run's first request that decides nothing, as `let spent = crunch(key)`, is not counted: every bucket starts full. A type that holds a type parameter, a binding whose label Core IR does not give, or a callee it does not hold counts as `⊤`, and P10's label then decides.

   Both labels are sound, so their meet is. The checker builds Core IR for P11 only when P10's label is above `internal`. `L_lim` also joins `L_res` (`spec/26 §7` rule 5, item 6), since a request left on a helper by a canceled task holds its slots, and the helper, until its exchange returns. `RateLimited`, and the `TimedOut` of a wait at a limit, are labeled with the join of `internal` and `L_lim`, so a program whose grants carry limits MUST have `L_lim` at most `internal`:
   - `una check` reports U4001, when a grant of `run grants` carries limits and `L_lim` is above `internal`, at each `Http` site whose own P10 label is above `internal` in a body whose `Gap` is above it, or at every such site when no body's `Gap` is; the message names the code between two requests that raised it (in the site's own function when that one did), the driver's gap, the tasks that can run beside it when `τ_conc` raised it, or the construct whose requests can be left running when `L_res` raised it;
   - `una build` embeds `L_lim` in the executable of an edition `0.4` package;
   - `una run` and the executable refuse a `--grant` with limits when `L_lim` is above `internal`: a usage error, exit code 2, before `main` starts, with the message "the grant `<spec>` has limits, but this program's requests are timed by `<label>` data".

   P10's label is computed in one pass over the strongly connected components of the call graph, linear in the functions, handlers, operations and edges of the package; P11's in one walk per body to build its graph, four searches over it and one pass over the components: O(V + E) in the steps of the package. `τ_conc` at a request in a function's body is that of §11; at a request in a lambda's body or in a handler's operation it is `⊤`, as the ancestors of such a request are not one function's (issue #1154). So a server whose requests run in started tasks beside work on `public` and `internal` data keeps `L_lim` at `internal`, and its grants can carry limits.
6. **Report.** How long a request waits at a limit is timing, out of model: the report's `out_of_model` list (`spec/13 §6`) holds "waits at limits and at `start`" (§7 rule 8). A full queue becomes a value only through `RateLimited`, which rule 5 labels.
7. **Costs** (ADR 0117 Costs). Finding the grants that allow a request takes O(G) for its `G` grants of `Http`, as before. Charging it takes O(1) per limited grant that allows it, under one lock per run held for that work only; a request that waits takes one queue entry per such grant, joined in O(1) and left in O(1) amortized. A run without limits pays nothing more.

## 10. `std.limit`

1. **The module** (ADR 0117 rule 9). In edition `0.4`, `std.limit` is an importable standard module (`spec/10 §11` rule 10), read only by a package that imports it, the mechanism by which `std.collections` is read in edition `0.5` (`spec/28 §2`); in earlier editions an import of it is U1001 at the module path. It declares:

   ```una
   pub kind Limited = | RateLimited

   pub capability Limit
     op acquire() -> Unit
       fails Limited
       accepts internal
   ```

   and exports the handler `limiter(at_most: Int, per: Int of Millisecond, waiting: Int) for Limit`, which the runtime provides, as it provides the host capabilities (`spec/05 §7`): it has no Una source, and no `handler` declaration of it exists in Core IR (`spec/09`). `with @x = limiter(...)` and a `given` line of an example install it by the rule that a `with` or a `given` names a handler (`spec/05 §9` rule 4, U3010), and `@x.acquire()` is an operation of `Limit` like any other, with its event in the trace (`spec/11 §5`) under the instance `with:limiter#<n>` or `given:<name>`.
2. **Installing.** Each installation carries three `refinement` obligations, at the arguments: `at_most >= 1`, `per >= 1` and `waiting >= 0` (U5001, U5002). Each installation is one instance with one bucket, shared by every task that uses the binding during the statement the `with` scopes over, the started tasks of a `tasks` statement inside it included (§7 rule 2); a rebinding shares it (`spec/11 §2`). A count beyond 2^64 − 1 counts as 2^64 − 1.
3. **Dynamics.** The bucket holds `at_most` tokens and refills evenly over `per` milliseconds: a burst of up to `at_most`, then one every `per` divided by `at_most`, kept by GCRA over the run's clock as the limits on grants are (§9 rule 2). `@x.acquire()` takes a token:
   - **At once** when one is left and no call waits at the bucket; otherwise it waits in the bucket's queue, served by ticket as §9 rule 3 says, an interruptible wait (§2).
   - **A full queue.** When `waiting` calls already wait, it fails at once with `RateLimited`, joining no queue; with `waiting: 0`, a call that finds no token fails at once.
   - **Deadlines.** The deadlines of the `within`s in progress (§5) and of the `for ever within` iteration (`spec/26 §7`) bound the wait. Past the earliest, no token is taken and the call fails with `RateLimited`, the one failure `Limited` has; the `for ever within` iteration observes its deadline at the operation, and a `within` at its next check point or when its expression returns, as for a request (§9 rule 4). A host stop in the body of a `for ever` (`spec/26 §6`) ends the wait the same way, with no token taken.
   - **Cancellation.** A cancellation of its task that interrupts a waiting operation (§6 rule 7, §7 rule 4) ends the call `interrupted` and takes it out of the queue; the task stops. A deadline's cut of its `tasks` statement ends it with `RateLimited` instead (§2 rule 4).
   - **Virtual time.** Under `--virtual-time` (`spec/26 §8`) a wait for a refill moves the virtual clock to the refill, or to the earliest covering deadline when that comes first, and takes no wall time, so both engines give the same outcomes, traces and readings of `Clock.now`; in a test, the clock is the test's virtual one.
   - **Natively,** the wait happens on a helper of the I/O pool while the task parks, as a request's wait at a limit does (§9 rule 3), never on the reactor; the interpreter waits on its thread.
4. **Information flow** (ADR 0117 IF5). `acquire` accepts `internal`, so it can be called under an `internal` program counter, as the started tasks of a server run once they have branched on a network result; under a program counter above it, the call is U4003 (`spec/07 §7` rule 4). `Limited` is labeled `internal`: whether a call of `acquire` fails, and its payload, carry `internal` for the program, whatever handler serves it, as the arguments that decide a host operation's failure label it (`spec/07 §7` rule 4). So `attempt @x.acquire()` gives an `internal` `Result`, a branch on it runs under an `internal` program counter, and `if error pass` and `if error fail` are U4002 (S-46, #1563). Whether a token is left depends on the timing of the code that shares the instance: the statement the `with` scopes over, or the `do` line of the example whose `given` line installs it, and, through `τ_conc` (`spec/26 §7` rule 5), the program's other tasks. So `τ` of that statement, computed as for a `within` (§5) but with the preview's `τ_conc` until §11 names the statement (§11), the handlers the statement's bindings install included, MUST flow to `internal`: U4001 at the `with` binding, or at the `given` line, otherwise, naming what raised it. That covers `waiting: 0` as well, where one task's own timing decides whether `acquire` fails.
5. **Report.** How long a call waits is timing, out of model: the report's `out_of_model` entry "waits at limits and at `start`" (§7 rule 8) covers it. A full queue becomes a value only through `RateLimited`, which rule 4 labels.
6. **Costs** (ADR 0117 Costs). An installation takes O(1). A call served at once takes O(1) under the bucket's lock, held for that work only; a call that waits takes one queue entry, joined in O(1) and left in O(1) amortized. A package that does not import `std.limit` pays nothing: the checker does not read the module, and no Core IR changes.

## 11. The timing label of concurrent work

Normative for `τ_conc` of a `within` (§5 rule 8), of a `first of` (§6 rule 8), of a `for ever within` (`spec/26 §7` rule 5), of the tick of a driven `step` (`conc(step)`, `spec/26 §2` rule 5), of the constructs that `L_res` counts (`spec/26 §7` rule 5, item 6) and of the requests that `L_lim` counts (§9 rule 5), as ADR 0116 states it in its amendment of 2026-10-25 (P0 to P5). The other timing sites, the statement a `limiter` scopes over (§10) and `L_srv` (`spec/31 §1`), keep the preview's `τ_conc` until this section names them: `⊤` for a site inside a lambda, a task, the block of a `tasks` statement or a handler's operation, in a function that a part of a task construct can reach, or, in a package with a task construct, in a function that a function value, a lambda or a handler's operation can run, whether or not a part reaches it; `public` otherwise.

1. **The whole program** (P0). The analysis sees every function whose code can run in the process: the package, the standard library and the prelude. A function with neither a body nor a summary is a node whose `τ⁰` and `conc` are `⊤`.
2. **The graph** (P1). It has a node per function, those of the prelude without a body included; one node `Λ` for every lambda of the package; one node per handler, for all of its operations; and one node `K(c)` per capability `c`. Each edge records its call site and the innermost construct of that site (rule 4):
   - a call of a function, or a use of its name as a value, goes from the node whose code holds it to that function; a policy call goes to its `via` function as well (`spec/07 §5`);
   - a call of a function value, or of a `uses of` parameter, goes to `Λ`; a prelude function with a parameter of function type has an edge to `Λ`, and `Λ` has an edge to every function named as a value;
   - an operation goes to `K(c)`, through the operation, and `K(c)` has an edge to each handler of `c`; a function has an edge to the operations of its `uses`, which covers a prelude function without a body; an installation goes to its handler;
   - a call inside a lambda's body leaves from `Λ`, and one inside a handler's operation from the handler. Code outside every node, such as an example's `do` line, records its edges too, which raise what they reach (rule 4).

   Every call counts, whether or not an entry reaches it.
3. **Parts and `κ`** (P2). `κ` here is the label `ctx` and `conc` carry; a race's own `t` counts its branches as §6 rule 8 states. The parts of a task construct `C` are each branch of `together` and of `first of`, the body of `together for`, and the block of `tasks` with each `start` in it. The list of `together for` and the bound of `tasks` are not parts. `κ(C)` is `τ⁰` of the whole construct, its list and its bound included: the items of `spec/26 §7` rule 5 other than 5 and 6, over the call graph of rule 2, where a part that calls a function value or a prelude function with a function argument has `⊤`. A site in a part counts `κ(C)`, the part that holds it included: its own code before the site decides which work of its siblings the site overlaps.
4. **Through calls** (P3). The constructs of one node's code form a tree by nesting; a lambda's body starts a tree of its own. `ctx` of a construct is `ctx` of its parent joined with its `κ`, and `ctx(s)` of a site or an edge is that of its innermost construct, or nothing outside every one. `conc(n)` of a node is the least label such that `conc(n) ≥ conc(m) ⊔ ctx(s)` for every edge from `m`, at the site `s`, to `n`, and `conc(n) ≥ ctx(s)` for every edge from code outside every node (rule 2); the members of a cycle of calls share one `conc`.
5. **At a site** (P4). For a site `e` in the code of the node `n`, `τ_conc(e) = conc(n) ⊔ ctx(e)`. A site in no node of the graph, such as one in an example's `do` line, has `τ_conc = ⊤`.
6. **What it means** (P5). `κ(C)` rises above a label `l` only when the work of some part of `C` can depend on data above `l`, whatever the number of tasks. A construct whose parts handle only `public` and `internal` data gives at most `internal`, and a program without task constructs has `τ_conc = public` everywhere. So does a site in a lambda or in a handler's operation that no part of a construct reaches, since nothing runs beside it.
7. **Fail closed.** A construct whose seed was not recorded, and a construct id that names no construct, count as `⊤`.
8. **Costs** (amendment, E). The graph, `κ` of every construct, `ctx` and `conc` are computed once per package, in O(V + E + F) joins over the `V` nodes, `E` edges and `F` constructs, plus `κ`'s reading of each construct's recorded seed; a cycle is one strongly connected component. `τ_conc` of a site is then O(1) joins.
