---
title: "31. HTTP servers"
url: https://una-lang.org/en/docs/spec/31-http-servers/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/spec/31-http-servers.md
---

# 31. HTTP servers

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

A server answers HTTP/1.1 requests through the host capability `HttpServer`, granted by address with limits. The rules of ADR 0123 join this chapter as they land, each with its tests. A program names the capability and is checked against §1, and a package's `serve` section against §7. Its operations run in both engines over the host code of §2 to §6 (`crates/una-http`), on serve threads that start before `main` (§6 rule 14). `una run` runs a program that serves and the driver of §7, and `una build` builds either into an executable that serves (§1 rule 10, §7 rule 5).

**Editions.** The rules of this chapter apply only to packages of edition `0.4` and later (`spec/13 §7`). Earlier editions do not change, and the client of `spec/24` does not change.

## 1. The capability

The declarations of ADR 0123 rules 0 to 5 and the static rules of its Information flow, with the label `L_srv` of its S4 amendment (IF-S1), are in this section. The operations of `HttpServer` run in both engines: `una run` reaches them, and so does the executable of `una build` (rule 10).

1. **Edition and names.** Every name of this section exists only in packages of edition `0.4` and later. `std.host` declares them, and the prelude does not put them in scope: a module imports them, as `import std.host (HttpServer, Request, Reply)` (`spec/10 §11` rule 10). An import of one is never redundant, an import of `Method` or `ServeError` brings its variants, and a kind of the package named `Request` or `Reply` stays legal. In earlier editions an import of these names is U1001, as an unknown name is. This section adds no keyword.
2. **Declarations.** `std.host` declares, in edition `0.4`:

   ```una
   --- The methods a request may have. The host answers any other with 501.
   pub kind Method = Get | Head | Post | Put | Patch | Delete | Options

   --- One decoded query parameter, as `name=value`.
   pub kind Param
     name: internal Text
     value: internal Text

   --- A request, as the host read it (§3 and §4).
   pub kind Request
     method: internal Method
     target: internal Text             -- the request target as received, in origin-form
     segments: internal List[Text]     -- the path, split on "/" and percent-decoded segment by segment
     params: internal List[Param]      -- the query, decoded, in order
     headers: internal List[Header]    -- names in ASCII lower case, in the order received
     body: internal Text
     peer: internal Text               -- the peer's IP address, without its port
     listener: internal Text           -- the grant's address, as the grant writes it

   --- A request and the reply right to answer it.
   pub kind Exchange
     request: internal Request
     right: internal ReplyRight

   pub kind Status = Int where 200 <= it and it <= 599

   pub kind Reply
     status: internal Status
     headers: internal List[Header]
     body: internal Text

   pub kind ServeError = Interrupted | TimedOut | Closed | NotHeld | BadReply

   pub capability HttpServer
     op next() -> internal Exchange
       fails ServeError
       accepts internal
     op reply(to: ReplyRight, reply: Reply) -> Unit
       fails ServeError
       accepts internal
     op close() -> Unit
       accepts public
   ```

   - **`params`.** ADR 0123 rule 1 names the field of the decoded query `query`, a word that `spec/01` reserves in every edition, so a field of that name could never be read. The field is `params`, as ADR 0123's amendment of 2026-11-06 (slice S5), section A, states.
   - **`Header`** is the kind of `spec/24 §1`, whose `value` is `internal Text`.
   - **Labeled fields.** The fields are `internal`, so a program can build a `Reply` from request data, and a test or a handler can build a `Request` from `internal` data. A constructor field is a flow site (`spec/07 §7` rule 2), so a `secret` value in a field of a `Reply` is U4001 where the reply is made.
   - **`Status`** is a refinement of `Int`: every `Reply(status: s, ...)` carries the obligation `200 <= s and s <= 599` (`spec/12 §3`), refuted U5001 and unknown U5002.
   - **`ReplyRight`** is an opaque built-in type of `std.host`: it has no constructor, no literal, no fields and no order. Its values come only from `next` and, in tests, from `std.testing.test_exchange` (§8). Two reply rights are equal when they name the same exchange, so `==` and `!=` apply to it. Interpolation writes `<reply-right>`.
   - **Failures.** `next` fails with `Interrupted` at a host stop (`spec/26`), `TimedOut` when a deadline of the program cuts its wait (`spec/27 §5`), and `Closed` after `close`. `reply` fails with `NotHeld` and `BadReply` (rules 4 and 13 of ADR 0123, §5 rule 1). `close` cannot fail, so a handling clause on it is U3025.
   - **What each accepts.** `reply` accepts `internal` (IF2). `close` accepts `public` only, so a server cannot close itself on the strength of a request's content: under a raised program counter it is U4003 (IF1). `next` accepts `internal`: ADR 0123 writes no `accepts` on it, and whether a task takes a request off the queue, and with it a `/once` slot that other tasks' deliveries wait for, could otherwise depend on `secret` data; under a `secret` program counter it is U4003.
   - **What parks.** `next` parks its task while no request is ready, and is an interruptible operation (`spec/26`, `spec/27`). `reply` and `close` never wait.
   - **One instance.** A run has one host instance of `HttpServer`, `host:HttpServer`, which serves every `serve` grant (§2).
   - **Grants and examples.** A `uses` of an `HttpServer` operation that no `serve` grant allows is U3012 (`spec/05 §7` rule 2); a grant allows all three operations, and the repair is a description only, since no address can be chosen for the programmer. A test whose `do` line needs `HttpServer` without a `given` handler is U3014 (`spec/05 §9` rule 5). A test MAY install a handler of `HttpServer` with `given`, as for every capability; its operations are ordinary handler code.
3. **Reply rights** (ADR 0123 rule 4). Every exchange comes with a reply right, held by exactly one task at a time:
   1. `next` gives the reply right of its exchange to the task that called it.
   2. `start e` moves to the started task every reply right that the calling task holds and that is reachable from the values `e` captures, closures included.
   3. No other construct moves a reply right: a branch of `together`, the body of a `together for` and a branch of `first of` act for the task that runs the construct (rule 4).
   4. `reply` succeeds only for a reply right that the calling task holds and has not answered; otherwise it fails with `NotHeld`, and nothing is sent. A successful `reply` releases it.
   5. When a task ends holding reply rights, the host answers each one, in the order the task received them: `500` when the task returned, failed or ended alone, `503` with `Retry-After: 1` when it was canceled, cut by `within` or stopped; each appends the event `{"seq": n, "task": "<path>", "outcome": {"kind": "unanswered", "status": s}}`.
   6. Which task holds a reply right depends only on the order of `next`, `start` and `reply` in each task, never on timing.
   7. Each exchange ends by one atomic transition, the first of the program's `reply`, the host's `answer` deadline, an auto-answer, its peer leaving or a stop; a `reply` after another transition returns `unit` and sends nothing.

   Items 1, 2 and 4 to 7 are the runtime's (rule 10). What the checker can see of them is checked now: item 3 through rule 4, and the auto-answers of item 5 through IF6 (rule 5 item 6). Both engines implement them over the engine of §6 (rule 10), with one table of reply rights (`una_http::serve::rights`), and under `--virtual-time` they give a run the same bytes, output and trace (ADR 0117 rule 12):
   - **A reply right** is one word that names an entry of the run's table, `(slot << 32) | generation`; a slot's generation grows at each reuse and a slot whose generations are spent is retired, so no word names two exchanges of a run. Holding, moving and releasing one is O(1) amortized.
   - **The walk of item 2** reads only the captures whose types can hold a reply right, which the checker marks for IF6 and Core IR names on the `start` (`rights`): a `ReplyRight`, a value that can hold one, and, in a package that imports `HttpServer`, `Exchange` or `ReplyRight`, or `test_exchange` of `std.testing` (§8), a function value or a value of a type parameter. They are walked in the order of their names, each value depth first, left to right, the values a closure holds included, an allocation that several values share once, at its first meeting; so a right that a task holds and that a capture reaches moves, in that order, and one it does not hold stays where it is. The capabilities a started task inherits are not values it captures: a right held in the state of a handler that the task inherits, and that no captured closure holds, does not move, so a `reply` through that handler in the started task fails with `NotHeld`, and the task that holds the right answers it at its end. Native code moves the rights that the values of the closure `start` copies reach, before the instances of its capabilities, in the order of their names and in the same order inside each; a capture that the checker does not mark holds no reply right, so both engines move the same rights in the same order. A handler instance's own instances are capabilities too, and neither engine walks them.
   - **Item 5.** A task that the run's end stops, by a host stop's hard stop or by an abort of the run, is stopped: `503`. A task whose body never ran, or that ended by a fault of the interpreter, the root task included, answers `503` and appends no event. Quiet code appends no `unanswered` event, as it appends no event of an operation (`spec/26 §6` rule 4). The `unanswered` events of a task come before the event that ends it, `cancelled` or `aborted`. In native code, an abort of a run that serves does not end the process at once, as in the interpreter: an abort by a started task stops every task at its next check point, and an abort of the root unwinds the root through its `tasks` statements, which cancel their tasks, each with its `cancelled` event; the host answers the rights each task holds, its events are written, and the root then ends the run with the first abort. At the hard stop (U6007), in both engines, the run's watcher makes the engine's hard stop before any check point sees the hard stop: from then on the engine discards every answer and reply of the program that has not yet taken its exchange, and its serve threads answer each exchange still open `503` with `Retry-After: 1` in one non-blocking write and close every connection (§6 rule 9). A reply already in progress when the hard stop comes, one that checked the stop before it and takes its exchange after it, may be lost: neither it nor the `503` reaches the peer. The host then answers every right still held, which sends nothing, and appends no `unanswered` event for any of them. Native code ends the process there, after waiting at most one second for the serve threads, without waiting for its tasks; the interpreter ends each task at its next check point. At an internal error (U8001) the engines differ. Native code makes the engine's hard stop first, as above, then ends the process, with no `unanswered` event. The interpreter's tasks end as at an abort of the run: each answers the rights it holds `503` with `Retry-After: 1` itself, appending their `unanswered` events, and the engine's hard stop comes at the run's end; an internal error of the engine itself (§6 rule 13) refuses those answers and makes the hard stop at once.
   - **`next` after a host stop** fails with `Interrupted` wherever it is called, before it takes any request, so a stopped run never delivers one (rule 2, `Failures`), unless the run has aborted (Waiting).
   - **Waiting.** A `next` with no request to deliver lets another ready task run first, but not one that waits in `next` itself and can only wait on: when every ready task waits there, the task that runs waits for the engine, so a pool of tasks that call `next` waits instead of passing the turn among themselves. A waiting task that its cancellation or its deadline ended counts as one that can run, so it runs at once, and the wait for the engine lasts no longer than the earliest deadline of the tasks waiting in `next`. A task canceled while it waits in `next` ends the operation with the outcome `interrupted`, takes no request, and the request stays queued for a later `next`. An abort of the run by a started task ends a `next` in progress with the outcome `aborted`, before it takes any request, and the task ends as the aborted run's tasks do. An abort of the root task ends no other task's `next` at once: the root unwinds through its `tasks` statements, which cancel their tasks, so a task waiting in `next` ends the operation `interrupted`, as a canceled one does, with its `cancelled` event, and the root then ends the run with the abort (item 5). `next` checks an abort of the run first, then `Closed`, then the host stop: a `close` or a host stop that comes with the abort does not turn the run's end into a failure the task can handle, and the rights it holds are answered `503` (item 5).
4. **No server operations in branches** (U3033, ADR 0123 rule 5). The effect set (`spec/05 §3` rule 3) of a branch of `together`, of the body of a `together for` and of a branch of `first of` MUST NOT contain an operation of `HttpServer`. U3033 is reported at each of these, written in the branch, inside a lambda written there too:
   - an operation of `HttpServer`, "`@server.reply` cannot run in a branch of `together`; answer after the block";
   - a call of a function, a call of a function value, a function named or passed as a value, and a handler installed with `with`, whose requirements hold `HttpServer`;
   - an operation of a capability that has a handler in the package whose `uses` hold `HttpServer`, or another such capability, whatever handler serves it, since a handler's parameters may hold a reply right;
   - in a program that imports a name of the server, a call of a `uses of` parameter (`spec/05 §9` rule 9), or its passing on, since the code its callers pass is not known in the branch and may reply: "`f` runs the code its callers pass, which in a program that serves can perform an operation of `HttpServer`, and that cannot run in a branch of `together`; call it after the block".

   The repair, a description only, moves the operation after the construct. Each check is O(1) per site, beside a search over the package's handlers computed once.
5. **Information flow** (ADR 0123 IF1 to IF7).
   1. **Requests are input** (IF1). `next` returns an `internal Exchange`. Whether `next` succeeds is `public`: no argument decides it, and its failures come from host stops, from `close`, which accepts `public` only, and from deadlines, which `spec/27 §5` labels. So an accept loop stays at a `public` program counter, and it can print.
   2. **Replies accept `internal`** (IF2). Every argument of `reply` is a sink with `accepts internal`: a `secret` value reaches a reply only through a policy (`spec/07 §5`).
   3. **Failures of `reply`** (IF3) are labeled `internal` at least: `NotHeld` and `BadReply` are decided by the reply right, the reply and the task's own reply rights, which the program's order decides. `attempt` gives an `internal` `Result`, and `if error pass` and `if error fail` are U4002.
   4. **No host deadline becomes a value** (IF4): the host's deadlines, a peer that leaves and full queues change only what the network carries (rule 3 item 7).
   5. **The request stream** is input from outside, and its dependence on the server's timing is out of model (IF5, `spec/07 §1`), as is which request a call of `next` receives when several serve threads hold requests.
   6. **Auto-answers** (IF6). A `start e` whose captures can hold a `ReplyRight`, by their types, or, in a package that imports `HttpServer`, `Exchange` or `ReplyRight`, or `test_exchange` (§8), include a function value, which may have captured one, moves reply rights, whose auto-answers depend on how its task ends. It is checked as a `reply` at the `start`. A capture of a type parameter's type, or of a type not yet solved, counts as one that can hold a reply right only in a package that imports `HttpServer`, `Exchange` or `ReplyRight`, since the checker sees every module of the program, its dependencies included. The program counter of the `start`, joined with the effect floor and the timing floor around it, and with `τ(e)` when it has `within`, MUST flow to `internal`, else U4003 at the word `start`. The capture test is one look at the type of each local `e` reads, O(1) per read with a table of the kinds that can hold a reply right, computed once.
      - **The depth of its task** (#1674, ADR 0123, amendment of 2026-11-06 on the depth of a request task). A started task that runs past `--task-depth` ends alone, and the host answers its rights `500` where the program would have replied, so the status a peer reads can tell how deep the task went. Such a `start` is also U4003 when both hold:
        1. **its task can push frames without a bound its code shows:** what it runs, along the call graph of ADR 0116 P1 with an edge from each policy to its `via` function, reaches a cycle (a function, a handler, a `via` or a lambda that can call itself again), a call of a function value or of a `uses of` parameter (the lambda node `Λ`, which a prelude function that applies a function argument, such as `map`, reaches too), or code whose calls the checker does not hold: a function or handler of a standard module other than the prelude, or of a dependency not checked with the package;
        2. **it can hold data above `internal`:** its program counter, what it reads from outside, binds or receives from an operation, or what any node it reaches declares in its signature (parameters, result, a handler's parameters, an operation's result, `accepts` and failure), binds, receives or, in a lambda, captures. A symbolic label `ℓ_T` counts as above `internal` in what the `start` itself reads, binds or receives, since a `start` in a generic body takes the values of its type parameters from callers outside the task; and in what the lambdas of the package hold, when the task can be handed a function value made outside it (a capture, or a handler parameter or operation answer that may hold one). It does not count in the signature and body of a generic function the task reaches, whose type parameters take what the task passes, counted where the task holds it.

        Without item 2, the task's depth depends on `internal` data at most, which the answer accepts. Without item 1, its depth is bounded by the longest chain of calls its code shows, so it ends alone only when `--task-depth` is set below that chain; which chain runs is then decided at a branch, and in a program that starts tasks a branch that data above `internal` decide is refused (`spec/27 §8` rule 5), so a lowered `--task-depth` makes such a task end alone, or not, by `internal` data at most, which the answer accepts (#1681, `security/server_start_static_depth_secret`). This holds while `spec/27 §8` rule 5 stands: an amendment of ADR 0117 that withdraws it MUST keep a rule for the depth of started tasks, or #1681 reopens (DECISIONS-OPEN item 18). At `internal`, whether such a task's later effects run, besides its answer, is the residual of #1677 (`spec/27 §8` rule 5), which with a lowered `--task-depth` needs no recursion, only a branch. A more precise rule is #1682. The prelude's functions are host code in both engines and push no frame of Una code but through a function argument. **Precise form of item 2** (#1682, which ADR 0123's amendment of 2026-11-06 allows as a refinement that only accepts more). A frame is pushed only by a call, so the task's depth follows only what decides its calls. When every call the task can make lies in code whose decisions the checker records with their labels, item 2 is replaced by: a function it reaches, or the body that holds the `start`, holds a check point that data above `internal` decide, with a concrete label (a call, an operation or a loop under such a program counter, `spec/27 §8` rule 5, recorded whether or not that rule reports it), or a call of a generic function whose check points a type argument above `internal` decides. The coarse item 2 stays when the task reaches `Λ` (a call of a function value, or a prelude function that applies one), a handler's operation, a `via` function, whose body is checked without labels (`spec/07 §5` rule 3), or code the checker does not see (a function of a standard module other than the prelude, as `std.collections`'s from edition 0.5, `security/server_start_depth_unseen_secret`; in edition 0.4 those are `std.testing`'s, for tests and handlers' operations only; or a module that failed to parse; path dependencies are checked with the package), or when the `start` lies in a handler's operation body, whose holder no function names, or when the `start`'s own data carry a type parameter's label; a predicate and a body that evaluates a `checked` predicate count so too, conservatively, though a `reflect` predicate's body records its check points and `checked` on data above `public` is refused (`spec/07 §3`). So a task that recurses on the request's length and also holds a `secret` key that decides none of its calls is accepted (`security/server_start_depth_holds_secret`, live in both engines: its `200` or `500` follows the body's length, whatever the key), and one whose recursion the key decides is refused (`security/server_start_depth_secret`): "its task can recurse, through `srv.deep`, and data above `internal` decide some of its calls, which may decide how deep it goes; a started task that runs past `--task-depth` ends alone and its rights are answered `500`". One that calls a policy whose `via` recurses keeps the coarse test (`security/server_start_depth_via_recursion`). The cost is two more closures over the strongly connected components, O(V + E), and one pass over the recorded check points, O((sites + calls) log n). A request task can read `secret` data, call prelude functions and reply with what a policy releases, when it neither recurses nor calls a function value; one that recurses can do so on `internal` data, and hold `secret` data that decides none of its calls. The default of `if error use` runs under the label that decides the failure, as every branch does (`spec/07 §3`).
      - **Cost.** One graph of the package, one search for its cycles and two closures over its strongly connected components, O(V + E), built at the first `start` that moves reply rights; then O(size of the seed of `e`) lookups per `start`. Recording what a node holds costs O(open sites + log n) per binding and per operation. `tests/start_reach_scaling.rs` of `una-check` keeps 2000 `start`s linear.
   7. **The label `L_srv`** (ADR 0123, S4 amendment IF-S1). In a package whose code performs an operation of `HttpServer`, the serve threads' work after each hand-off site, an operation of `HttpServer` or a `start` of item 6, can shift every timing site of the program, so `L_srv = internal ⊔ ⨆ over hand-off sites s of (sfx(s) ⊔ Suf*(node(s)) ⊔ τ_conc(s)) ⊔ L_res` joins `τ` of every timing site, as `L_res` does (`spec/26 §7` rule 5): every `within`, `first of` and `for ever within`, every tick, `L_lim` and the statement a `limiter` scopes over. It is `public` in a package without an operation of `HttpServer`. A message whose label it raises names "the requests that the serve threads handle after the server operations in `m.f`".
      - **Preview over-approximation.** `sfx(s) ⊔ Suf*(node(s))`, the code that can run after `s`, is taken as `τ⁰` of the bodies of every ancestor of the function that holds `s`, that function included, in the call graph of ADR 0116 P1, the rule of `L_lim` (`spec/27 §9` rule 5); and `τ_conc` is the preview's, `⊤` for a site in a task, a `tasks` block, a lambda or a handler's operation (`spec/27 §11`, which names the sites that keep it). Both are sound and coarser than the amendment's, so code that runs only before the first server operation still raises the label here; they MAY become more precise, and MUST NOT become stricter. In a server of the language form, whose `next` stands in the block of a `tasks` statement, `L_srv` is `⊤` under the preview, and so is every timing site of the package.
      - **Cost.** One pass over the call graph, linear in its nodes and edges, and linear in the hand-off sites.
   8. **In practice** (IF7). A request task branches on `internal` data, so its program counter is `internal`: it can call `Http`, `Files.write`, `limiter` and `reply`, and cannot print. Under the preview's `τ_conc`, a `start ... within` in the block of a `tasks` statement whose expression performs an operation that accepts `internal` is refused already (`spec/27 §5`), so the language form below starts its tasks without `within`, and the host's `answer` deadline bounds what each peer waits.
6. **The language form** (ADR 0123 rule 15). A server is a `diverges` function with a `for ever` loop that calls `next` and starts a task per request:

   ```una
   answer(exchange: internal Exchange) -> Unit
     uses @server: HttpServer[reply]
   =
     @server.reply(to: exchange.right, reply: Reply(status: 200, headers: [], body: "ok"))
       if error use unit

   serve_all() -> Unit
     uses @server: HttpServer[next, reply, close]
     diverges
   =
     tasks at most 1000 at once
       for ever
         let next = attempt @server.next()
         when next
           is Ok(exchange) ->
             start answer(exchange)
           is Err(failure) -> unit
       on stop
         @server.close()
   ```

   `next` waits, parked, and fails with `Interrupted` at a host stop, which ends the loop at its next iteration start. `tasks at most N at once` bounds the program's tasks, and the grant's `/once` the exchanges open. A server that answers in its loop, with no `tasks`, is legal too.
7. **Trace events.** `next`, `reply` and `close` are events of `spec/11 §5`, with `instance` `host:HttpServer`. Their values are redacted by their labels, as every event's are, and, whatever their labels, they are written in the reduced form of ADR 0123 rule 1, in a recording kept for replay too: the values of the headers `authorization`, `proxy-authorization`, `cookie`, `set-cookie`, `x-api-key` and `x-auth-token` as `<credential>`, in requests and in replies; the values of query parameters, in `params` and in `target`, written as bodies are; a body as `{"length": n, "hmac": "<hex>"}`, its length in bytes and an HMAC-SHA-256 of it under a key of the run; a reply right as `<reply-right>`. Path segments, header names, other header values, the method, the peer, the listener and statuses stay as they are. Both engines build these events with one implementation (`una_interp::serve_trace`), so they write the same text:
   - **Where.** The reduction applies to every value of the kinds `Request`, `Reply`, `Header` and `Param` of `std.host` in the arguments and the outcome of these events, where the event is built, before any output: the human and `--json` traces, and the trace file of an executable, all read the same events, so no path writes the clear form. A run keeps no other recording of host results.
   - **Form.** A header is a credential by its name in any letter case, so a reply's `Set-Cookie` is one, and so is every header whose name is not a token (RFC 9110 §5.6.2), such as `"set-cookie "` or a name with a tab or a control byte, which the host refuses to send (`BadReply`) and whose value is still never written. `<credential>` and the body form are written bare in the value's Una form, as `<reply-right>` is. A `target` stays a quoted text, its path as it is and, in its query after the first `?`, each value of a part `name=value`, split at its first `=`, replaced by the body form of the value as received, before its percent-decoding; a part without `=` is a name and stays, so the target keeps its shape. In `params` the body form is of the decoded value.
   - **The key.** 32 bytes drawn from the host's random source when the run starts, all zeros under a script of connections (ADR 0123 rule 21), so that two runs of one script, in either engine, give the same trace. The engine of the run holds it, and it is never written.
   - **Under the labels of this section** every field of `Request` and `Reply` is `internal`, so a run's trace shows each as `<redacted:internal>`, a `reply` whose `Reply` is built from `public` data included (`Reply(status: <redacted:internal>, headers: <redacted:internal>, body: <redacted:internal>)`), and the outcome of `next` as `{"kind": "redacted", "level": "internal"}`; the reduced form lies beneath that redaction. The runs of `tests/serve_runs/` also compare it in both engines with the redaction of labels lifted, which only the scripted engine of the toolchain's own tests can ask for.
   - **Cost.** O(b) for b bytes of a body or a target, one HMAC over them; O(1) for every other field.
8. **Diagnostics.** U3033 is new (`spec/13 §4`). U1001, U3012, U3014, U3025, U4001, U4002, U4003, U5001 and U5002 cover the rest.
9. **Costs.** Holding, moving and releasing a reply right are O(1) each. The move at `start` moves the rights in the order of rule 3 item 2, with the same result in both engines, in O(objects that the marked captures reach) in the interpreter and O(objects that the task's captured values reach) in native code, which walks all captures after the copy succeeds and before the task is queued (the same order as the copy itself in cost), and costs nothing at a `start` whose captures cannot hold a reply right; ADR 0123 Costs states what native code adds to the copy of the captures. The checks of this section are linear in the sites they look at.
10. **`una run` runs; `una build` builds.** The operations of `HttpServer`, the holding and moving of reply rights at run time, the state machine of rule 3 item 7, the auto-answers and their events, and the reduced trace form, are in place in both engines over the engine of §6, which a run that serves starts before `main` (§6 rule 14). `una run` of a program whose entry function, `main` or a driven module's `init`, `step` or `on_stop`, uses `HttpServer` runs it in the interpreter over live listeners, after every check of the program and of its grants, with the plain toolchain and no test flag. `una build` of such a program, after the same checks of the program, with the plain toolchain and no test flag, makes an executable that runs it in native code over live listeners: it checks its grants, those of `run grants` and of its own `--grant` flags, before `main`, starts the serve threads before `main` (§6 rule 14) and takes host stops as `una run` does. The scripted engine of `--serve-script` runs only in the toolchain's own test builds, in both engines: in native code only in an executable linked with the runtime built with its `test-hooks`, which no shipped `una` has (§8 rule 6). In a run without the engine, which no program reaches, the trace writes every argument of an operation of `HttpServer` as an `internal` value is, redacted, whatever its label. `una check` checks such a program fully, and `una test` runs tests that install a handler of `HttpServer` with `given`.

## 2. Grants

A `serve:` grant lets a run accept connections on one address and port, with limits that every server has whether its grant writes them or not (ADR 0123 rules 6 to 9). The limits named in §3, `line`, `headers`, `header` and `body`, are items of this section.

1. **The text form.** In `--grant` (`spec/13 §5`): `serve:<scheme>://<address>:<port>`, then items as suffixes `;<item>`.
   - `<scheme>` is `http` or `https`, in lower case.
   - `<address>` is an IPv4 address in dotted-quad form, or an IPv6 address in brackets, written in its canonical form (RFC 5952: lower case, the longest run of zero groups compressed, no leading zeros), so one address has one spelling. `0.0.0.0` and `[::]` mean every interface. A host name, a zone, an IPv4-mapped IPv6 address (`[::ffff:127.0.0.1]`, written as the IPv4 address instead) and a multicast address are refused: nothing resolves a grant, and a socket bound with `IPV6_V6ONLY` receives no IPv4 connection. A link-local IPv6 address (`fe80::/10`) is unsupported: without a zone it cannot be bound, so the run fails closed with the usage error of rule 7.
   - `<port>` is from 1 to 65535, always written, with no leading zero. Nothing follows it but items.
   - A number in an item is decimal digits with no sign and no leading zero (`0` alone where the range allows it).
2. **Items.** Each item has a default, and each is given at most once; one rate at most, of any period, since a grant keeps one token bucket.

   | Item | Meaning | Default | Range |
   | --- | --- | --- | --- |
   | `N/once` | exchanges delivered and not yet answered | 256 | 1 to 2^31 − 1 |
   | `N/second`, `N/minute`, `N/hour` | exchanges delivered per period, a token bucket | none | 1 to 2^31 − 1 |
   | `waiting=N` | requests read and waiting to be delivered | 1024 | 0 to 2^31 − 1 |
   | `connections=N` | open connections | 1024 | 1 to 1,048,576 |
   | `peer=N` | open connections from one peer | `max(16, connections / 16)` | 1 to 1,048,576, or `none` |
   | `handshakes=N` | TLS handshakes started per second; one peer may start `max(4, N / 16)` | 512 | 1 to 2^31 − 1 |
   | `requests=N` | requests on one connection | 1000 | 1 to 2^31 − 1 |
   | `line=K` | the request line, in KiB | 8 | 1 to 64 |
   | `headers=N` | header lines of a request, trailers included | 100 | 1 to 1000 |
   | `header=K` | the header section, trailers included, in KiB | 16 | 1 to 256 |
   | `body=K` | a request's body, in KiB | 1024 | 0 to 1,048,576 |
   | `buffers=M` | bytes of request bodies held for the grant, in MiB | 64 | 1 to 65,536 |
   | `peer_buffers=M` | the share of `buffers` of one peer, in MiB | `max(1, buffers / 64)` | 1 to 65,536, or `none` |
   | `replies=M` | bytes of replies not yet written, in MiB | 64 | 1 to 65,536 |
   | `peer_replies=M` | the share of `replies` of one peer under pressure, in MiB | `max(1, replies / 64)` | 1 to 65,536, or `none` |
   | `delivered=M` | bytes of the requests of open exchanges, in MiB | 256 | 1 to 65,536 |
   | `idle=S` | seconds a connection waits for a request's first byte | 5 | 1 to 3600 |
   | `read=S` | seconds to read a whole request | 20 | 1 to 3600 |
   | `write=S` | seconds to write a whole reply | 30 | 1 to 3600 |
   | `answer=S` | seconds from the end of a request to the start of its reply | 30 | 1 to 86,400 |
   | `hosts=a,b` | the names `Host` may carry (rule 5) | IP literals and `localhost` | names, or `*` |
   | `certificate=F`, `key=F` | the certificate chain and the private key, PEM files | none | `https` only, and required there |
   | `tls12` | also accept TLS 1.2 | off | `https` only |

   A derived default is computed from the values the grant gives, so `connections=4096` makes the default `peer` 256. Sizes and counts are compared in unsigned 64-bit arithmetic that never wraps. Every default is settled: a later release may only tighten one.
3. **The `ita.una` form.** Under `run grants`, `serve "<scheme>://<address>:<port>"`, then one item per line below it, each the item of rule 2 it names:

   ```ebnf
   serve_grant = "serve" text_lit NEWLINE [ INDENT serve_item { serve_item } DEDENT ] ;
   serve_item  = ( "certificate" text_lit | "key" text_lit | "tls12"
                 | "at" "most" int_lit ( "at" "once" | "per" ( "second" | "minute" | "hour" ) )
                 | ( "waiting" | "connections" | "requests" | "headers" ) "at" "most" int_lit
                 | "peer" ( "at" "most" int_lit | "none" )
                 | "handshakes" "at" "most" int_lit "per" "second"
                 | ( "line" | "header" | "body" ) "at" "most" int_lit "KiB"
                 | ( "buffers" | "replies" | "delivered" ) "at" "most" int_lit "MiB"
                 | ( "peer_buffers" | "peer_replies" ) ( "at" "most" int_lit "MiB" | "none" )
                 | ( "idle" | "read" | "write" | "answer" ) "within" int_lit ( "second" | "seconds" )
                 | "hosts" text_lit { "," text_lit } ) NEWLINE ;
   ```

   ```una
   run
     grants
       serve "https://0.0.0.0:8443"
         certificate "tls/chain.pem"
         key "tls/key.pem"
         at most 256 at once
         at most 6000 per minute
         body at most 64 KiB
         answer within 10 seconds
         hosts "shop.example", "*.shop.example"
   ```

   A unit is written where the table has one, and only that unit, so no line is read in a unit it does not name.
4. **Errors and editions.**
   - In `ita.una`, each of these is U7008 at its line: a line of another form, an item given twice or a second rate, a value out of range, `certificate`, `key` or `tls12` on an `http` grant, an empty path or a path with `;`, and a `hosts` line of rule 5's errors; at the grant's line, an invalid scheme, address or port, an `https` grant without `certificate` or `key`, and an overlap (rule 6).
   - With `--grant`, each is a usage error, exit code 2, before anything runs; so is a `serve:` grant for a single file or a package of an edition before `0.4`.
   - In `una.toml`, a `serve:` grant is U7002 in every edition: before `0.4` there is no server, and from `0.4` the grants are read from `ita.una`.
   - A grant allows all three operations of `HttpServer`.
5. **`hosts`.** Each name is a registered name of letters, digits, `-`, `_` and `.`, with no empty label and a last label that is neither all digits nor starts with `0x`, as `Host` writes one (§3 rule 5); one trailing `.` is removed and the name is compared in ASCII lower case. A name MAY start with `*.`, which stands for exactly one label (`spec/24 §2`); `*` alone accepts every name of valid syntax and is the only item of its list. An IP literal, a port, an empty name and a name given twice are errors. With the `Host` read by §3 rule 5:
   - without `hosts`, on every grant whatever its address, the name MUST be `localhost` or an IP literal, else `421`;
   - with `hosts`, the name MUST equal a listed name or match a `*.` name, else `421`; an IP literal matches no name.
6. **Overlap.** Each address and port is granted once, and a wildcard address may not share its port with another grant of its family, whatever the schemes. IPv6 sockets are bound with `IPV6_V6ONLY`, so `[::]:p` and `0.0.0.0:p` do not overlap. In `ita.una` the later of two grants that overlap is U7008; among the grants of a run, manifest and flags together, an overlap is a usage error.
7. **Before `main`.** After the checks of `spec/13 §5` and before `main` starts, the host, in this order:
   1. raises the run's limit of open descriptors to the sum of `connections` over the grants, plus 64, within the hard limit; a run that cannot is a usage error;
   2. for each `https` grant, opens the key file and then the certificate file, once each, checks each open descriptor, and reads each from that descriptor (rule 8);
   3. binds one listening socket per grant, without `SO_REUSEPORT`, with `IPV6_V6ONLY` on IPv6, so no other process shares its connections; an address that cannot be bound is a usage error that names it. The socket sets `SO_REUSEADDR`, so a server restarts while connections of its previous run are in `TIME_WAIT`; a second listener on the same address and port is refused. On macOS and the BSDs, another local process can still bind a more specific address on the same port while a grant binds the wildcard (`0.0.0.0` or `[::]`), and then receives the connections to that address. The defense is a grant that names a specific address rather than the wildcard.
   4. for a program that serves, starts its serve threads over those listeners, which accept nothing until its first server operation (§6 rule 14).
8. **TLS files.**
   - **Opening.** Each file is opened once, following symbolic links, without blocking on a FIFO, and checked on the open descriptor with `fstat`, never by its path, so a file swapped between the check and the read is impossible. Each MUST be a regular file of at most 1 MiB. Relative paths resolve as other grants' paths do (`spec/13 §5`).
   - **The key file** MUST also be owned by the run's effective user or by root, have no write bit for its group and no bit for others (`st_mode & 0o027 == 0`), and have its group read bit only when its group is the run's effective group or a supplementary group. A key owned by another user is refused even when the run is root's.
   - **Contents.** The certificate file holds a chain of `CERTIFICATE` blocks, leaf first; the key file a private key in PKCS#8, SEC1 or PKCS#1 form. A file that cannot be read, or that holds no such block, is a usage error.
   - **The key stays in the host.** No operation returns it, and it is in no value, trace, diagnostic or report.
   - **The protocol, pinned.** TLS 1.3 only, unless the grant says `tls12`, which adds TLS 1.2 with the extended master secret required. No renegotiation, no early data, no stateless session tickets (resumption through a bounded in-memory cache only), no key log, ALPN `http/1.1` only, and no client certificates.
   - **Pending.** The check that the key matches the certificate, and the TLS server itself, wait for the decision on the project's TLS provider (#1059); until then a run with an `https` grant loads and checks its files and binds, as every grant does, and nothing accepts on any listener.
   - **Other platforms.** An `https` grant is a usage error on a platform other than macOS and Linux, until a later record defines the check of a file's access list.

## 3. Reading a request

The host refuses every request that two HTTP implementations might read differently, and never repairs one. Each refusal answers the status shown, with `Connection: close`, and closes the connection after it, so the host never looks for where a broken request ends.

1. **Request line.** It MUST be `method SP target SP version CRLF`, with single spaces and nothing before the method; an empty line before it is refused, not skipped. A line that is not three parts split by single spaces, a method that is not a token (RFC 9110 §5.6.2), or a target with a byte outside the printable ASCII range 0x21 to 0x7E is `400`. A version other than `HTTP/1.1` and `HTTP/1.0` is `505`. A token that is not one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE` and `OPTIONS`, in upper case, is `501`, `CONNECT` and `TRACE` included. A request line longer than `line`, its CRLF included, is `414`, refused as soon as it cannot fit and before its bytes are kept.
2. **Line ends.** Every line MUST end with CRLF. A bare LF, or a CR not followed at once by LF, anywhere in the request line, the header section or the chunked framing, is `400`.
3. **Header lines.**
   1. A header line is a name that is a token, followed at once by `:`, then a value. A line that starts with a space or a tab (obsolete folding) is `400`; whitespace before the colon is `400`.
   2. A value is trimmed of spaces and tabs at both ends. A byte below 0x20 other than tab, or 0x7F, in a value is `400`. A value that is not UTF-8 is `400`, and is never repaired.
   3. A `Connection` header is a list of tokens separated by commas, with optional spaces and tabs around each. Every token, compared in any letter case, MUST be `close`, `keep-alive`, or a header that belongs to the connection: `connection`, `keep-alive`, `proxy-connection`, `te`, `trailer`, `transfer-encoding`, `upgrade` and `content-length`. Any other token, or an empty element, is `400`, so a peer can never make the host remove a header that a front proxy added, or `host`.
   4. A header name that differs from `host`, `content-encoding`, `expect` or a header of rule 3.3 only by `_` in place of `-`, such as `Transfer_Encoding`, is `400`: a proxy that maps one to the other would read a framing or a host that the server does not.
   5. The header section's lines, its trailers' included, count against `headers`, and its bytes, each line with its CRLF and the empty line that ends it included, against `header`. Over either, `431`, refused before the bytes over the limit are kept.
4. **Framing, the defense against smuggling.** In this order:
   1. `Content-Length` and `Transfer-Encoding` together: `400`.
   2. `Transfer-Encoding` in an `HTTP/1.0` request: `400`.
   3. Two `Transfer-Encoding` headers: `400`.
   4. A `Transfer-Encoding` whose whole value is not `chunked`, in any letter case: `400` when it is malformed (empty, an empty element, an element that is not a bare token, parameters included) or names `chunked` twice; else `501`, since it names a coding the host does not implement.
   5. Two `Content-Length` headers, even with equal values: `400`.
   6. A `Content-Length` value that is not 1 to 19 ASCII digits alone, with no sign, whitespace or list: `400`. A value above `body`: `413`, before any byte of the body is read.
   7. Neither header: an empty body.
   8. **Chunked bodies.** Each chunk size MUST be 1 to 16 hex digits alone, with no whitespace, sign or extension; anything else is `400`. This departs from RFC 9112 §7.1.1, which asks a recipient to ignore unknown chunk extensions, because lenient reading there has been a route for smuggling. The line after a chunk's data MUST be empty. A chunk whose size would take the body past `body` is `413` at its size line, before any of its data is kept. Trailers are header lines of rule 3, read and dropped; their lines and bytes count against what the header section left of `headers` and `header`, not a fresh allowance.
5. **`Host`.** A request MUST carry exactly one `Host`, `HTTP/1.0` requests included, else `400`. Its value is a host and an optional `:` with a port of 1 to 5 digits, at most 65535. The host is a registered name of letters, digits, `-`, `_` and `.`, with no empty label; an IPv4 address in dotted-quad form; or an IPv6 address in brackets, without a zone. A registered name whose last label is all digits, or starts with `0x`, and which is not an IPv4 address, such as `127.1`, is `400`, since resolvers read such names as addresses in different ways. Anything else, such as an empty value, `a/b@c`, or an empty port, is `400`. One trailing `.` of a registered name is removed, and the name is compared in ASCII lower case; the program sees the value as sent. Which names a grant accepts (`421`) is the grant's (§2 rule 5).
6. **Encodings and expectations.** A `Content-Encoding` other than `identity`, in any letter case, is `415`. In an `HTTP/1.1` request, `Expect: 100-continue`, in any letter case, asks the host to send `100 Continue` once it admits a body; any other expectation is `417`. In an `HTTP/1.0` request, `Expect` is ignored.
7. **Order.** The request line is checked when it ends. The whole head is checked when its empty line arrives, before any byte of the body is read, in this order: the framing of rule 4, `Connection`, `Host`, the target of §4, `Content-Encoding`, `Expect`.
8. **The body** is read to the end its framing gives, and no further: the bytes after it belong to the next request, which is read only after the reply to this one is written. A body that is not valid UTF-8 is `400`.
9. **What the program sees.** The headers of rule 3.3 that belong to the connection are removed. The other names are in ASCII lower case, in the order received, with their trimmed values. The connection closes after the reply when `Connection` lists `close`, or when the request is `HTTP/1.0`.
10. **Splits.** Reading is incremental, and a request split at any byte boundary reads exactly as in one piece. Each byte is examined a bounded number of times, so reading is linear in the bytes read.

## 4. The target

1. **Forms.** The target MUST start with `/` (origin-form), or be in absolute-form, `http://` or `https://` in any letter case followed by an authority and an optional path and query. An absolute-form target is accepted only when its scheme is the grant's and its authority equals the `Host` value in ASCII letter case; it is then rewritten to the origin-form of its path and query, `/` for an empty path, which the program sees as `target`. Else it is `400`. The asterisk-form and the authority-form are `400`.
2. **Characters.** The path holds only `/` and the characters of an RFC 3986 `pchar`; the query, after the first `?`, holds those and `?`. Each `%` MUST be followed by two hex digits. Anything else is `400`: a `#`, a space, `\`, `|`, `{`, `"`, `^`, a backquote, `<`, `>`, `[`, `]`, and any byte above 0x7E. RFC 3986 does not allow them unencoded.
3. **Segments.** The path after its first `/` is split on `/`, and each segment is percent-decoded alone, so an encoded `/` never makes a new segment. A segment that decodes to `.` or `..`, or that holds `/`, `\`, NUL or another control character (below 0x20, or 0x7F), or that is not UTF-8 after decoding, is `400`. `/` gives `[""]`, and `/a//b` gives `["a", "", "b"]`. Forms that other servers read as special, such as `..;` and the double-encoded `%252e%252e`, are ordinary segments.
4. **Query.** The query is split on `&`, and empty parts are skipped. Each part is `name=value`, split at its first `=`, or `name` with the value `""`. A `+` decodes to a space, then percent-decoding applies. A name or value that is not UTF-8 after decoding is `400`.

## 5. Writing a reply

1. **Checks.** Before any byte is written, a reply MUST have a status from 200 to 599; no body on a `204` or a `304`; header names that are tokens, in any case; header values with no CR, LF, NUL or other control character but tab, and no 0x7F; none of `Connection`, `Content-Length`, `Date`, `Keep-Alive`, `Proxy-Connection`, `TE`, `Trailer`, `Transfer-Encoding` and `Upgrade`, in any letter case; at most 100 headers, and at most 64 KiB of them, each counted as `name: value` with its CRLF. Otherwise `reply` fails with `BadReply`, nothing is sent, and the reply right stays held.
2. **The bytes.** `HTTP/1.1 <status> <reason>`, with the reason phrase of RFC 9110 §15 (and of RFC 6585 for `429` and `431`), or an empty one for any other status; then `Date` as an IMF-fixdate; `Content-Length` with the length of the body given, except on a `204` or a `304`; the program's headers, in order, as given; `content-type: text/plain; charset=utf-8` when the reply names no content type and carries a body; `Connection: close` when the connection closes after the reply; the empty line; and the body, unless the request was `HEAD` or the status is `204` or `304`. A `HEAD` reply keeps the `Content-Length` of the body given and gets no default content type.
3. **The host's own answers** (refusals, `421`, `503`, `500`) have an empty body, `Content-Length: 0`, `Retry-After: 1` where ADR 0123 rule 14 asks for it, and `Connection: close` when the connection closes, as it does after every refusal of §3 and §4. `100 Continue` is the status line and the empty line alone.
4. **Cost.** Checking and writing a reply of r bytes is O(r), into one buffer reserved once.

## 6. Connections and serve threads

The host code in `crates/una-http/src/serve` is the same in both engines and runs on **serve threads**: threads that never run program code and whose work is bounded and linear in the bytes and events they handle (ADR 0123 rules 12 to 14 and 17 to 20; `docs/plan/0123-s4-design.md`). A run of a program that serves starts them before `main` (rule 14), under `una run` and in the executable of `una build` alike (§1 rule 10); any other run with a `serve:` grant holds its listeners and accepts nothing.

1. **Serve threads.** `una run` and executables take `--serve-threads <n>`, from 1 to 256, by default the number of the machine's cores (`spec/27 §3`). A value that is not a number, or is out of range, is a usage error, exit code 2, before `main` starts. A run that serves nothing accepts the flag and uses none. Each serve thread owns its connections, its timers and an inbox, and has a readiness queue of its own (`kqueue` or `epoll`) and a pair of sockets that wake it. Only plain owned data crosses between threads: a connection, the bytes of a request, a serialized reply.
2. **Accepting.**
   1. Accepting begins at the run's first server operation. Before it, no listener is registered, and a peer's connection waits in the kernel's backlog.
   2. Each grant keeps the one listening socket that §2 rule 7 binds, without `SO_REUSEPORT`. Every listener is registered, one-shot, in one accept poller, which is itself registered, one-shot, in the readiness queue of one serve thread at a time, the one that holds the turn (thread 0 first). That thread accepts at most 16 connections of each listener that fired, registers the listener again, and passes the turn to the next serve thread by a message. So exactly one thread accepts from a listener at a time, a listener event wakes one thread whatever their number, and a burst of connections is spread over the threads in turn.
   3. A slot of `connections` is taken before `accept` is called, so every descriptor the host accepts, one closed at once included, holds one. At `connections` the host does not register the listener again until a connection of the grant closes, and the kernel's backlog holds the rest. `ECONNABORTED` and `EINTR` are skipped; any other error of `accept` stops accepting on that listener for 100 ms.
   4. A connection is then checked in this order: `peer`, and for an `https` grant the peer's and then the grant's handshake rates (rule 10). A connection over any of them is closed at once, before any byte is read. Else it is placed on the serve thread named by SipHash-2-4 of the listener, the peer's address and the peer's port, under a key of 128 bits drawn from the operating system's random source for the run and shown nowhere; the place does not depend on the order of accepts, on which thread accepted, or on how busy any thread is.
   5. A peer is an IPv4 address, or the /64 prefix of an IPv6 address; an IPv4-mapped IPv6 address is its IPv4 address. The host keeps the peers with open connections, or with a handshake bucket that is not full, in a table of 64 shards: at most `connections + handshakes` entries.
3. **A connection** is in one of four states, with at most one timer at a time (§2 rule 2: `idle`, `read`, `write` and `answer`; every timer is a total and trickling bytes never extends it):
   1. *Reading.* The first request of a connection is read within `read` of the accept. A later request waits `idle` for its first byte, then `read` for the rest. A request not read in full within `read` is answered `408` and the connection drains and closes (rule 8); a connection that sent no byte of it is closed without an answer. A connection idle past `idle` is closed.
   2. *Waiting.* From the end of the request until the reply is handed over, within `answer`: after `answer` an undelivered request, or a delivered exchange that was not answered, is answered `503` with `Retry-After: 1`, and a reply that comes later is discarded. The host reads no more than the head reserve while it waits, so a peer that leaves is seen at once, and its exchange ends with its reply discarded.
   3. *Writing.* The reply is written within `write`, and the host reads nothing more from the connection meanwhile. Then the connection reads its next request, or closes when the request said `Connection: close`, when it was `HTTP/1.0`, when the connection reached `requests`, or when a host stop is under way.
   4. *Draining* after a refusal (rule 8).
4. **Bytes of requests, in shares.** The head of a request, `line` and `header` bytes, is counted in `connections` at the accept and waits for no shared budget. A body is admitted before its first byte is read: a declared `Content-Length` reserves its whole length, a chunked body reserves 64 KiB before each step, in the grant's `buffers` and the peer's `peer_buffers`; a reservation that fits neither is answered `503` with `Retry-After: 1` at once, and nothing else waits. `100 Continue` is sent only after the admission. The reservation is released when the request is delivered or refused.
5. **Delivery.** A request read in full takes a place among the `waiting` requests (`503` with `Retry-After: 1` when none is free), and is delivered when the next exchange fits the grant's `delivered` bytes, its `/once` slots and its rate, in this order, each undone if a later one fails. Requests are delivered first come, first served among those one serve thread read for one grant; across threads the queues are visited from a rotating cursor, so no queue waits behind another indefinitely. The wait is bounded by `answer`. A request whose bytes as read, its head, its body and their framing, exceed the grant's whole `delivered` could never be delivered, and would hold its queue's front until `answer`: it is answered `503` with `Retry-After: 1`, the answer of ADR 0123 rule 14 for no room in `delivered`, at once and before it takes a place among the `waiting` requests; a declared `Content-Length` is checked when the head is read, before any byte of the body, and a chunked body when the request is read in full (#1675). The rate is a token bucket kept as one timestamp per grant, updated by compare-and-swap, with the interval rounded up to a whole nanosecond and never to zero; it holds `N` tokens.
6. **Replies, in shares.** A reply is checked and serialized once (§5), reserved on the grant's `replies` and the peer's share, cut into segments of at most 16 KiB, and handed to the connection's owner; handing it over never waits on a peer and never fails for the reservation. Each segment is dropped, and its bytes given back, as soon as its last byte is written. When a reservation leaves the grant over `replies`, the same call, before it allocates, closes connections until the grant is back under: the one with the most bytes left of the peer furthest over its `peer_replies` share; when no peer is over its share, the one with the most bytes left of all; ties to the connection accepted first. A closed connection's reply is dropped at once and is never written, which the program never sees. A single reply larger than `replies` is kept only while the grant has no other reply pending, else its connection is closed at once. The pending bytes of a grant are at most `replies` plus the replies being reserved at that moment.
7. **The host's own answers.** Each has an empty body and `Content-Length: 0`; `Retry-After: 1` is written where shown; `Connection: close` always.

   | Status | When | `Retry-After` |
   | --- | --- | --- |
   | `400`, `413`, `414`, `415`, `417`, `431`, `501`, `505` | a refusal of §3 and §4 | no |
   | `421` | `Host` is not allowed (§2 rule 5) | no |
   | `408` | a request is not read in full within `read` | no |
   | `503` | `waiting` is full; a body does not fit its shares; a request waits past `answer`, or can never fit `delivered` (rule 5); an exchange is not answered within `answer`; a host stop finds a request undelivered or being read; the hard stop; the task holding the reply right is canceled | yes |
   | `500` | the reply right is dropped without a reply | no |

8. **Closing after a refusal.** After an answer that closes the connection, the host shuts down its sending side, reads and drops what the peer still sends, at most 64 KiB or for one second, and then closes, so that the peer reads the status instead of a reset. The connection keeps its slot and its place among the peers until it closes.
9. **Stopping.** At a host stop the host closes every listener at once and closes idle connections; requests undelivered or still being read are answered `503`; delivered exchanges drain, each reply carrying `Connection: close`; a reply serialized just before the stop may lack the header, and its connection closes after it all the same. At the hard stop, each open exchange is answered `503` in one non-blocking write, and every connection closes, without waiting on a peer. A reply to an exchange that the hard stop, `answer` or a departed peer ended returns as if it had been sent.
10. **Handshakes.** For an `https` grant, `handshakes` per second per grant and `max(4, handshakes / 16)` per second per peer are token buckets, each full at the start and holding one second of tokens, charged at the accept; at most half of the serve threads, rounded up, are inside a handshake step at a time. Until the TLS server lands (§2 rule 8), a run with an `https` grant does not start serving: the host fails closed instead of serving plain bytes on an `https` address.
11. **Descriptors.** The run's limit of open descriptors is raised before `main` to the sum of `connections` over the grants, plus one listener per grant, one for the accept poller, three for each serve thread (its readiness queue and its pair of wake sockets), 256 sockets for the program's own `Http` requests, the helpers of `Files`, and 64 for `Console`, the reactor and the runtime; a run that cannot is a usage error that names the sum. The cap on the sockets of the program's `Http` requests is then the soft limit less everything but those 256.
12. **Costs.** Accepting, queueing and delivering a request, reserving and releasing a share, taking a token, arming and canceling a timer, and closing are O(1) expected; reading b bytes is O(b); a reply of r bytes costs O(r) to check and serialize and O(log c) per connection closed for pressure over c connections with a reply pending; a host stop is O(connections + queued requests).
13. **Faults.** A panic of the host is contained to the connection it happens on, and the run stops instead in three cases (ADR 0123, amendment of 2026-11-02, decision 10).
    1. *Contained.* A panic in a connection's step outside the serve thread's timers and readiness registrations, in the hand-off of an accepted connection (from the slot taken before `accept` to the connection's place in its owner's table), in a peer's expiry, in the closing of a connection, or inside a socket's write of a pending reply (which runs with the reply's lock held but changes nothing it protects, so the panic is carried out of the lock first), is caught where it happens and counted: it closes that connection at most, and no serve thread ends by it. What the connection holds is given back in every window: a fault in the peer's admission after its place was taken gives the place back, a fault in the hand-off before the connection reaches its owner's inbox, or before the owner put it in its table, gives back the slot and the place, and a fault inside the closing passes the step that faulted and still gives back everything after it, its `connections` slot and its peer's place included, each once: every step of the closing is marked done before it runs, so it runs at most once, and a closing resumes at most 8 times, more than its steps. A contained fault does not reach the process's panic hook, so faults cannot flood standard error.
    2. *Stopping the run.* The run stops when a callback the program's side registered (`on_ready`, `on_slot_freed`) panics; when a panic happens while a lock of a grant's shared state is held (a delivery queue, an exchange's request, a connection's pending reply, the pressure heaps, a registry shard, a shard of the peer table), after which that state may be inconsistent and is never served from again, even when the panic was contained where it happened (the socket's write of item 1 is not such a panic, since it changes nothing the lock protects); and when the run's contained faults pass 64, the same for every run and not a setting (the 65th stops it). A panic that began before the lock was taken, such as an exchange dropped while its task unwinds, does not count. These panics print through the panic hook. A callback that panicked is not called again once its panic is seen; calls already under way on other serve threads finish, so it runs at most once more per serve thread.
    3. *The stop.* A stop is the hard stop (rule 9), made once, at the first point that holds no lock of a grant: each open exchange is answered `503` in one non-blocking write, every connection closes, and every listener closes at the next pass of a serve thread's loop. A failure recorded on the program's side (in a delivery or a reply) wakes every serve thread as the program's side unwinds, so the stop does not wait for their next event. From the failure on, nothing is accepted, a reply that checks for it returns as if it had been sent and is never written, and the program's next request reports the failure instead of a request; a reply that passed the check just before the failure was recorded may still be queued, and the hard stop closes its connection. Its error names the cause: `the serve engine stopped the run: a serve callback panicked`, `... a panic left the shared state of a grant inconsistent`, or `... more than 64 faults were contained`. When the engines meet a program (step 5) the run aborts with that message as U8001, an internal error of the host, with exit code 3 (`spec/11 §4`), and the status `aborted`.
    4. *A thread that ends.* A panic inside the thread's timers or readiness registrations, which every connection of the thread shares, including one in the closing after a contained fault, or anywhere else in the thread's loop, ends the thread, and prints. A serve thread that ends closes every connection it owned and gives back what they held (rules 2, 4, 5 and 6; a panic inside the giving back of one connection is contained, and the others still close), hands on the turn to accept and the peers' expiries it was timing, and registers again every listener whose event its last wait for connections returned and whose burst did not end; a message for it is handled by its sender; a new connection whose keyed owner ended is placed on the next serve thread in the ring that has not ended. When the panic that ended it held a lock of a grant's shared state, the run stops as in item 2.
    5. *What the program sees.* Contained faults are counted per grant and for the run. ADR 0123's amendment of 2026-11-06 (slice S5), section I, declares what the program will see: `op faults() -> internal Int`, a fourth operation of `HttpServer` that reads the run's count, `accepts internal`, with no failure, never parking, refused in a branch of `together` by U3033 and allowed by a `serve:` grant with the others; and, for each contained fault, a host event with no task and no operation, `{"seq": n, "outcome": {"kind": "fault", "site": "step" | "accept" | "peer-expiry" | "abandon", "listener": "<grant>"}}`, written at the program's next server operation after it, before that operation's own event. **Pending:** both land with a later part of #1571, in both engines; until then `std.host` does not declare `faults`, and contained faults are counted and not shown to the program.
14. **Starting and ending** (S4 amendment B.2, ADR 0123 rule 18). A run whose program serves, one whose entry functions use `HttpServer` (§1 rule 10) and that holds a `serve:` grant, starts every serve thread, its poller and its wake pair, and the accept poller, before `main`, over the listeners of §2 rule 7, and draws the key of its reduced trace form (§1 rule 7) from the host's random source; the panic hook of rule 13, chained over the runtime's own, is installed on the thread that starts the run before any of them. A run that serves nothing starts none of them. Once they have started, and before the run's first request, the run writes on stderr one line for each `serve:` grant, in the order of its grants, the same in both engines: `serving on <address>:<port> (granted by the package)` for a grant of `run grants`, and `` (granted by a `--grant` flag) `` for one of a flag; an IPv6 address is written in brackets. A run that holds a `serve:` grant and serves nothing binds its listeners before `main` (§2 rule 7), accepts nothing on them and writes no such line. Nothing is accepted until the run's first server operation. Only a run that can take a host stop, one with a `serve` section, a driver, or a `main` that says `diverges` (ADR 0116 rule 18), installs the handlers of SIGINT and SIGTERM; a server of the language form whose `main` does not say `diverges` keeps their default actions, so SIGTERM ends its process at once, with no drain, and a shell reports exit code 143. The run's watcher of host stops (ADR 0116 rule 14) hands each request to the engine: the host stop of rule 9 when the first request reaches the run, and the hard stop when it comes. At the run's end the engine stops as at a host stop, and the run waits for the serve threads to write what it answered and close, for at most the grace period (`--stop-grace`, ADR 0116 rule 16); past it, and at once after the hard stop or an internal error, the engine makes the hard stop and the run waits for its threads at most one more second. A `next` waits for the engine on a condition that each queued request, each ended exchange, each closed connection and each delivery signals to one waiting `next`, and each stop to all of them, and looks at its own cancellation, an abort of the run and a host stop at least every 10 ms. A signal wakes only a `next` whose last attempt came before it, and a `next` that a signal woke and that ends without a further attempt, at a cancellation, hands the signal on, so a request costs O(1) wakes whatever the number of waiting `next`s. The signal of a delivery wakes one more `next` because one ended exchange can let several queued requests through, when the bytes it gives back to the `delivered` budget fit more than one of them. Every serve thread is in place, its wake pair in its readiness queue, before the run's first job; a run in which one cannot register it, or the accept poller, is a usage error before `main`. A run under `--virtual-time` that holds a `serve:` grant is a usage error before `main`, in both engines (ADR 0123, S4 amendment C), since live peers send in real time; only the scripted engine of the toolchain's tests stands for the `--serve-script` of step 7 there.

**Block for the capability.** The serve threads decide observable timing: `408` against a silent close, `idle` against `read`, the order of delivery, and the placement of connections. The checker computes the `L_srv` labels of the S4 design (`docs/plan/0123-s4-design.md` §10) with the preview's terms (§1 rule 5 item 7); `una run` lets any program meet the engines (§1 rule 10), and the five timing oracles below MUST pass on the engines a release ships. The five oracles of the S4 design §11.5 exist (`crates/una-cli/tests/timing_channels.rs`): `serve_prefix_secret` and `serve_prefix_early_peers`, which time the reply to a probe instead of a deadline's outcome, since the preview's `L_srv`, `⊤` for a server of the language form, refuses a reply that carries one; and the positive controls `serve_handoff_residue` (SC2: reply bytes pending to a peer that does not read decide, through `replies` and `connections`, whether a later `next` under a deadline receives its request) and `serve_delivery_history` (SC3: the time between two deliveries under a rate decides the same), servers without `tasks` whose `public` twins MUST show the channel, and whose `secret` versions, the conformance cases `serve_handoff_residue_secret` and `serve_delivery_history_secret`, are refused with U4003; and `serve_owner_spread` (SC1, M1: the placement of connections), which observes the owner of each of 8 connections of one address over 8 serve threads directly: timing could not show the owner on the gate machine (one serve thread and 8 replied alike, ratios 0.4 to 1.17 over 9 workloads, in both engines), so the toolchain's test builds have a placement probe, under the `test-hooks` feature that no shipped `una` or `libuna_rt.a` has, which writes the serve thread that placement chose for each accepted connection, before the peer's admission, and can place by `port mod M` with no key. The harness picks connections whose source ports are all multiples of 8, the family that `port mod 8` without a key puts on one serve thread. Under the keyed placement, for each of the program's two keys (which make `public` set-up code before the first server operation 0 or about 300 ms long), a run MUST NOT put all 8 on one owner, and over the 160 connections of 20 runs every serve thread MUST own between 3 and 44, bounds fixed in advance from Binomial(160, 1/8); the positive control, the same connections under the unkeyed port-mod-8 placement (`port mod 8` with no key), MUST put all 8 on one owner in every run. This shows that the keyed placement spreads connections that the unkeyed port-mod-8 placement concentrates, and that the probe and the crafted ports do separate those two. Other placements without a fresh key spread multiples of 8 and pass it, such as `(port >> 3) mod 8`, an unkeyed SipHash, round-robin by accept order, the thread that accepted, or the keyed hash under a fixed key: the ports differ from run to run and cannot be replayed, so a fixed key is not covered (the oracle logs, as a diagnostic, how often a port that recurs across runs keeps its owner). It does not show that a peer cannot predict an owner, which rests on the key's secrecy and on SipHash-2-4 as a pseudorandom function (assumed); it observes the test build, whose placement calls the same function as a shipped build's; and it does not measure the time of a reply on its owner. Its timings, crafted ports against ports as they come and one serve thread against 8, are logged as diagnostics and not asserted. Its client uses the standard library only, which cannot bind a source port before it connects: the ports are found among the ephemeral ones and the others closed before the first server operation, so the property of the ports is fixed and the ports themselves are not. Each of the five runs in both engines, as `<oracle>_native` over the executable that `una build` makes (for `serve_owner_spread`, linked with the runtime built with its `test-hooks`) and `<oracle>_interpreter` under `una run`, since the waiting and waking of the serve engine is separate code in each: the same harness, assertions and sample sizes, with the iterations of `public` set-up and probe work scaled per engine so that their times are alike. All five passed in both engines on 2026-11-08, on the commit this lift of §1 rule 10 builds on, and a release runs them again on its candidate (`docs/release-gates.md`).

## 7. The host-driven form: `serve`

ADR 0123 rules 16 and 22, with decisions S6-D1 to S6-D6 of `docs/plan/0123-s6-design.md`. The section, its checks, its usage errors and the report's entries are in this section. The driver that runs the program of rule 4 runs in both engines, over the operations of `HttpServer` (§1 rule 10): `una run` runs it, and `una build` builds it into an executable that runs it (rule 5).

1. **The section.** In `ita.una` (`spec/30 §2`), the `serve` section names the module whose functions the host calls, and optionally a per-request deadline in milliseconds:

   ```text
   serve
     module shop.api
     within 10000
   ```

   - Its lines are `module`, a module of the package, and `within`, an integer from 1 to 86,400,000. A missing `module`, a `within` out of range, a line of another form, a line given twice, the section given twice, a module that is not a module of the package, and a `serve` section beside a `run entry` or a `drive` section (a package runs one program), are U7008 at the line, or at the value for one out of range. A section with any problem inside it, one the grammar finds included (a line given twice, an unknown line, a malformed literal), is not read: nothing else is reported of it, and a run never serves what it does not say.
   - `una.toml` has no `[serve]` table: edition `0.4` is written in `ita.una` only (ADR 0122), so `[serve]` in `una.toml` is U7002 as any unknown table. A dependency's `serve` section is not read, as its `run` and `drive` sections are not (ADR 0122 rule 12).
   - `run grants` keeps its meaning. A run of a package with a `serve` section and no `serve:` grant, in `run grants` or by `--grant`, is a usage error, exit code 2, before anything starts.
2. **The module.** It declares:

   ```una
   pub handle(request: internal Request) -> internal Reply
   pub on_stop() -> Unit                 -- optional
   ```

   with `Request` and `Reply` of `std.host` (§1 rule 2), and neither has a `requires` clause: the host calls `handle` for every request it reads and `on_stop` at every stop, and no call of the host establishes a precondition, so a `requires` would be a fact the verifier assumes and nothing proves. A `requires` on either is U7008 at the section's `module`, with the clause as the related span, in `una check`; so is a refined type of a parameter or of the result of either, written there or carried by a refined kind such as `kind Full = Request where it.body != ""`, with the type as the related span, since a refinement of the parameter is the same precondition and the shape is exact. A module without `handle` of exactly this shape (public, no type parameters, one parameter passed by value whose type is `internal Request`, the result `internal Reply`), or with an `on_stop` that is not `pub on_stop() -> Unit`, is a usage error, exit code 2, of `una run` and `una build`, as for `drive` (`spec/26 §2`); the message names the module, the section and the first difference found.
3. **Checks** (`una check`):
   1. `handle` and `on_stop` MAY declare `uses`, checked against the grants as `main`'s are (U3012, `spec/05 §7`): against `run grants` in `una check`, and against the final grants, `--grant` flags included, in `una run`.
   2. `handle` MAY declare `fails`. `on_stop` MUST NOT (U3029 at the clause): the host has no caller to give a failure to.
   3. Neither may say `diverges` (U3027 at the clause): every request, and the stop, ends after finitely many steps (ADR 0116 rule 9).
   4. Neither may name `HttpServer`, or a capability whose handlers can perform one of its operations (§1 rule 4), in its `uses` (U3033 at the binding; decision S6-D3). In this form the host owns every exchange and answers each request with the reply `handle` returns, so a `handle` that took, answered or closed exchanges would take work from the driver, or stop the server from a request. A public function's effect set is bounded by its declared `uses` (`spec/05 §3`), so this refuses every operation of `HttpServer` in their effect sets, through a callee, a function value or a handler included. A server that takes requests itself is written in the language form (§1 rule 6, ADR 0123 rule 15) without a `serve` section.
   5. A `Reply` built from `secret` data is U4001 at the field, as for every constructor of `Reply` (§1 rule 2).
   6. **The driver is a hand-off site** of `L_srv` (§1 rule 5 item 7, IF-S1): its `next` is inside the `tasks` statement whose started tasks run `handle`, so the preview's `τ_conc` at it is `⊤`, as for the language form's `next`, and `L_srv` of a package with a `serve` section is the top label. It raises every timing site of the package (a `within`, a `first of`, a limit), as it does in a language-form server.
   7. **`within`.** With `within w`, the driver's `start answer(exchange) within w` moves the exchange's reply right to its task, whose cut by the deadline the host answers with `503` (§1 rule 3). That answer accepts `internal`, so `τ(e)` of the started expression, the timing of `handle` joined with `L_res` (which holds `L_srv`) and `τ_conc`, MUST flow to `internal`: U4003 at the value of `within` otherwise (§1 rule 5 item 6, IF6). While `L_srv` of the preview is `⊤` (item 6), every `within` of a `serve` section is U4003, as the language form's `start ... within` is; the label MAY become less strict with a more precise `L_srv` (#1155), and MUST NOT become stricter. Without `within`, the grant's `answer` bounds what each peer waits (§2), and `handle` cannot diverge.
4. **Meaning.** `una run` and the executable that `una build` writes run this program, with `handle` and `on_stop` from the module (ADR 0123 rule 16):

   ```una
   main() -> Unit
     uses @server: HttpServer[next, reply]
     diverges
   =
     tasks at most B at once                   -- B: the sum of `/once` over the run's `serve:` grants, within the default bound
       for ever
         let next = attempt @server.next()
         when next
           is Ok(exchange) ->
             start answer(exchange) within w   -- `within w`, and the clause below, only with `within`
               if error use unit
           is Err(failure) -> unit
     on_stop()                                 -- only when declared, after every request has drained

   answer(exchange: internal Exchange) -> Unit
     uses @server: HttpServer[reply]           -- and the `uses` of handle
   =
     let reply = handle(exchange.request)
       if error use Reply(status: 500, headers: [], body: "")   -- only when handle declares fails
     @server.reply(to: exchange.right, reply: reply)
       if error use unit
   ```

   - A failure of `handle` becomes `500` with an empty body, never the failure's payload. A `reply` that fails with `BadReply` sends nothing, and the task's end then answers `500` (§1 rule 3).
   - The driver is engine code equivalent to this program, not Una source or Core IR that the package gains (decision S6-D4): `una core` of the package does not change, and `handle` stays an ordinary function for the checker, the verifier and tests, which call it directly with a `Request` they build.
   - At a host stop, `next` fails with `Interrupted`, the loop ends, the started tasks drain, `on_stop` runs on the main task with the run's grants, and the run ends with exit code 0; at the hard stop every task is canceled, the auto-answers of their reply rights are sent, `on_stop` does not run, and the run ends with U6007 (ADR 0123 rule 18).
   - The `tasks` statement is bounded by `B`, the sum of `/once` over the run's `serve:` grants, within the default bound of a `tasks` statement (`spec/27 §7`, `max(64, M)` within the cap on tasks), and at least 1 (#1724). A started task holds its place until its `handle` and its `reply` end, not only while its exchange is open: a peer that leaves, or an `answer` that passes, ends the exchange and gives back its `/once` place, but not the task's place. While `B` tasks run, the driver waits at `start` and takes no request, and the requests wait in the engine under its own limits, answered `503` at `answer` when no place frees in time. The bound is shared by the grants (decision S6-D6).
5. **Run and built.** `una run` of a package with a `serve` section reports, in this order, the usage error of rule 2 and the usage error of a missing `serve:` grant (rule 1), and then runs the driver in the interpreter, as it runs a program of the language form (§1 rule 10). `una build` reports the usage error of rule 2 and requires no `serve:` grant, since the executable's grants may come from its flags; the executable reports the usage error of rule 1 at its start. Each usage error has exit code 2, and each comes before any listener is bound or any program code runs. `una check`, `una test` and `una report` of such a package work: tests call `handle` directly. `una build` builds the driver into an executable, whose description carries the section as `"serve": {"module": ..., "within": ...}` and which runs it, as it builds a program of the language form (§1 rule 10); an executable whose description names a `within` refuses to start. In both engines the serve threads start before the driver, which is the run's main task and accepts from its first `next`; the requests' events are those of the program of rule 4, the root task's and those of its started tasks `s1.k`, byte for byte, in both engines (`tests/serve_runs/serve_section_*`). The driver of a `within` waits for the label of rule 3 item 7, which refuses every `within` today.
6. **The report** (`spec/13 §6`, ADR 0123 rule 22), additions within `una.report/2`, for a package with a `serve:` grant or a `serve` section, which **serves**:
   - `tcb.host_capabilities` lists `HttpServer` when the package serves, or when a function or handler of it uses `HttpServer`.
   - `tcb.serve_grants` lists each `serve:` grant of `run grants`, in order, as `{"address": "127.0.0.1:8080", "scheme": "http", "limits": {...}, "checks_host": true}`: `limits` holds every item of §2's table but the TLS files and `hosts`, with its default applied, sizes in bytes, times in seconds, a rate as `"N/second"`, and `null` for `none` or no rate; `checks_host` is `false` for `hosts=*`. A package that serves nothing has `[]`.
   - `tcb.server` is `"una-http/serve"`, the server code of the host, for a package that serves, and `null` otherwise; `tcb.tls` is `null` while no TLS server is built (§6 rule 10).
   - `out_of_model` gains, at its end: "what a server's peers send in reaction to its timing, and which requests its full queues refuse"; "what a peer receives when the host's deadlines cut an exchange"; and "which request a call of `next` receives when several serve threads hold requests, which the timing of every task of the run and of the serve threads decides" (ADR 0123 S4 amendment, section E).
   - `warnings`, a new key after `out_of_model`, a list of sentences, `[]` when none, in the order of the grants: a plain `http` grant on an address that is not loopback, a wildcard included; a grant with `hosts=*`; with `peer=none`; with `peer_buffers=none`; with `tls12`. Warnings appear in the report only.
   - The human form prints `server:` in the `tcb` lines, a `servers:` section with one line per grant, and each warning as a `warning:` line after `out of model`.
7. **Costs.** The section is read in O(lines); the checks of rule 3 are O(clauses + uses) of the two functions, with the timing label of item 7 the one rule of every timing label, O(functions + call edges + operations); the report's entries are O(grants).

## 8. Tests

The functions of `std.testing` for servers, ADR 0123 rule 21 (`spec/14 §4`). They exist only in edition `0.4` and later, and, as every function of `std.testing`, only tests and the handlers that only tests install call them (U3015).

1. **`test_request(method: Method, target: Text, body: Text) -> Request fails TestRequestError`** gives the request the host would read from a peer that sent the request line of `method` and `target` with `HTTP/1.1`, the one header `Host: test`, and `body` framed by its length. The host's own reader reads it (§3, §4), with no limit but the request's own size, so only the target's form can refuse it:
   - the target is read by §4: origin-form, or the absolute-form on the authority `test` with the scheme `http`, rewritten to origin-form; `segments` and `params` are decoded as the host decodes them;
   - `headers` is `[Header(name: "host", value: "test")]`, since `Content-Length` belongs to the connection (§3); `body` is `body`; `peer` is `"192.0.2.1"`, an address of the block that RFC 5737 sets aside for documentation; `listener` is `"test"`;
   - where the host would answer `400`, it fails with `Refused`: a target that is empty or holds a byte outside printable ASCII (which would end or split the request line, §3 rule 1), the asterisk-form, the authority-form, an absolute-form on another authority or scheme, a `#`, a bad percent-encoding, and a segment or a parameter that §4 refuses.
2. **`pub kind TestRequestError = | Refused`** is declared by `std.testing`, a sum of one variant, which `fails` requires (`spec/06`). ADR 0123 rule 21 writes it `= Refused`, which the grammar reads as an alias of a type `Refused` (`spec/02 §2`); ADR 0123's amendment of 2026-11-06 on `TestRequestError` corrects it.
3. **`test_exchange(request: Request) -> Exchange`** gives an exchange of `request` with a fresh reply right: distinct from every reply right the run gave before, from `next` or from `test_exchange`, and equal only to itself. A handler of `HttpServer` that a test installs receives it in `reply` as any value; the host's table never holds it (§1 rule 3), so it names no exchange of a peer.
4. **What a package uses.** An import of `test_request`, `test_exchange` or `TestRequestError` makes the package one that uses the server's kinds, as an import of a name of §1 does, so Core IR declares them, and only then does Core IR declare `TestRequestError`, `test_request` and `test_exchange`; an import of `test_exchange` makes it one whose values can hold a reply right (§1 rule 5 item 6). Core IR of a package that imports none of them does not change, a server's that imports only names of §1 included.
5. **Engines and costs.** Tests run in the interpreter (`spec/08 §2`), and native code never reaches `std.testing` (U3015). `test_request` is O(t + b) for a target of t bytes and a body of b bytes, one pass of the host's reader; `test_exchange` is O(1).
6. **Scripts of connections** (ADR 0123 rule 21). A script stands for the peers of a run's `serve:` grants under virtual time, one JSON object per line, `at` in virtual milliseconds, each line exactly one of these forms (`una_http::serve::script_file`):
   - `{"at": <ms>, "connection": <k>, "grant": "<address>", "peer": "<ip>", "reads": "eager" | "paced"}` opens connection `k` on the grant whose address, as `listener` writes it (§1), is `<address>`, from the IP address `<ip>`;
   - `{"at": <ms>, "connection": <k>, "bytes": "<base64>"}` sends bytes, in the padded standard base64 of RFC 4648 §4;
   - `{"at": <ms>, "connection": <k>, "read": <n>}`, `n` at least 1, lets a `paced` connection receive `n` more bytes;
   - `{"at": <ms>, "connection": <k>, "close": true}` closes the peer's side, and no line follows it on that connection.

   Lines end with LF, the last one optionally, and each is one JSON object with nothing before its `{` or after its `}`: an empty line, a line of spaces or tabs, a CR anywhere (so a CRLF line end), a key that is not one of the forms', and a key given twice are refused. A script with no lines opens no connection. `at` never decreases from a line to the next, and lines of equal `at` take effect in their order. A connection is opened once, before its other lines, and one peer address opens at most 64,512 connections: the engine gives the connections of a peer address the ports 1024 to 65535 in the order the script opens them, so the connection numbers, any whole numbers, never make a port. A script is read and checked in full before anything runs; the first line that is not one of the forms or breaks a rule above is refused, named by its number, counted from 1. Reading is O(n) in the bytes of the script.

   `una run` and executables take `--serve-script <file>` and `--serve-out <file>`. These are usage errors, exit code 2, with the same message in both engines, in this order: before the package is read and before the ranges of `--workers`, `--task-depth`, the thread counts and `--max-depth` are checked, `--serve-script` without `--virtual-time`, and `--serve-out` without `--serve-script` (a flag value that is not a number or is out of its own range, such as `--deadline 0`, is refused while the flags are read, before these); then, after the checks of the program, rule 10 of §1 among them, and after the key files, a run with no `serve:` grant, a script that is not a regular file (opened without blocking and checked on its descriptor, so a FIFO or a device is never read), one larger than 64 MiB, one that cannot be read or is not UTF-8, and a script refused above. A script read and checked is then, while the scripted engine does not run outside the toolchain's own tests, the usage error "the scripted connections of `--serve-script` do not run in this release yet". A run that ends with any of these binds no listener and makes no file: the trace file of `--trace` is made only after them, in both engines, and `--serve-out` is not opened. Only the toolchain's own test builds of `una` and of the runtime, in a run whose environment sets `UNA_TEST_RUN_SERVER=1`, serve the script: the engine of §6 takes the script's connections in place of listeners, binds none, and advances the script while the program waits in `next`, one instant at a time, every line of that instant in order. The engine's clock moves only to the script's next line or the engine's next timer. The serve threads finish their work at each instant, so a pipelined request is read, and a refused one answered, at the instant the reply before it is written; a request they queue while the program waits is delivered to it at that instant, before the clock moves or the script ends (issue #1738). Both engines do the same. At the run's end, after the lines the program did not wait for and one more hour of the engine's clock, `--serve-out` gets what each connection received:
   - one compact JSON object per LF-ended line, its keys in lexicographic order: `{"at", "bytes", "connection"}` with the bytes that left at that millisecond in padded base64, `{"at", "connection", "shutdown": true}` when the host shut its sending side, `{"at", "closed": true, "connection"}` when it closed the connection, and `{"at", "connection", "refused": <reason>}` for a connection refused at accept, which also has its `closed` line at the same time;
   - sorted by time, then connection, then kind in the order `bytes`, `shutdown`, `closed`, `refused`;
   - a reason is one of `full` (the grant's `connections`), `peerlimit` (the peer's `peer`), `handshakes`, `peerhandshakes`, `nothread`, `fault` and `failed`.

   **What it holds.** The file holds exactly the bytes the script's peers received: what the host wrote, statuses and its own headers, and what the program put in its replies, unredacted. Unlike the trace (§1 rule 7), it keeps `internal` data, a value a policy released into a reply, and credentials such as `set-cookie`, since those are what a peer of the server reads; it gives no reader more than the program's peers had, and only those who may read what the server sends should read it. It is written once, after the run: opened without following a symbolic link in its last component and without blocking, so a link or a FIFO with no reader is refused; a file that is not a regular file, or that has more than one name (a hard link), is refused; its mode is set to `0600`, an existing file's included, before it is truncated and written, so a reader that opened an existing file before the run keeps what its descriptor allows. After the run's own diagnostics, both engines then write, in this order, what the engine leaves not at rest (counters, peers, timers, connections accepted before any server operation) as `warning:` lines on stderr, which do not change the exit code, and, for a file that cannot be written or is refused, the line "error: cannot write the connections to `<path>`: `<reason>`", a usage error: the exit code is then the higher of the run's own and 2. A `--trace` that cannot be written is reported last, after the run's own diagnostics and these, as "error: cannot write the trace to `<path>`: `<reason>`" in both engines, also a usage error: the exit code is the higher of the run's and 2. Both engines write the same file, byte for byte. Without `--serve-script`, `--virtual-time` still takes no `serve:` grant (§6 rule 14).

   **The security hunt** (ADR 0123 implementation plan, step 10, #1011). The hunt's family N (`docs/plan/security-hunt-generators.md`, `hunt servers` in `scripts/security-hunt`) runs servers through scripts of connections with a test build of `una`, so it binds no listener. Its programs send the refusals of §3 and §4 and their well-formed twins, each followed by a request a smuggling peer would want read, whole and split at random byte boundaries; a peer must receive the host's own answer alone, with the status of the rule, and the request behind it must never be read. Its handlers also echo a request's decoded query value into a header of their reply, a CR, an LF or a NUL included, and write names the host refuses: such a reply must fail with `BadReply` and send nothing (§5 rule 1), so nothing it carries reaches the peer. A run of the two-run oracle over handlers that read `secret` data compares what the peers receive, the `internal` observer of IF2, across values of the secret: it must not change, but for what a policy releases. This is a check of the rules above, not a rule of its own.

## 9. The formal model

(ADR 0123 S10, rule 11 of its implementation plan; #1012.) The formal track's model of Core (`formal/UnaFormal/F1`, `docs/plan/formal-track.md`) does not model the server yet. It is a statement about the model and the re-check of `una.core/1` documents, not a rule on programs: no verdict of `una check` depends on it.

1. **Not re-checked, never accepted.** The re-check reports as not re-checked, with a reason that names ADR 0123, every declaration whose Core holds a construct of the server: the base type `ReplyRight`; a kind of §1 rule 2 that Core declares in the module `prelude` (`Method`, `Param`, `Request`, `Exchange`, `Reply` and `ServeError`), as a type, a failure's kind, a constructor or a pattern; a name of §8 in the module `std.testing` (`TestRequestError`, `test_request`, `test_exchange`); or a node that names the capability `HttpServer`: an operation (`next`, `reply`, `close`), a `uses` entry, a handler of it. As for every form outside the model, each declaration that reaches one, by a call, an instance or a record type with a field of one, is not re-checked either. The function `handle` of a `serve` section (§7 rule 2) is such a declaration, since its parameter is a `Request`, and the driver of §7 rule 4 is engine code outside Core, which the re-check never reads. `Status` is an `Int` with a refinement in Core, and `Header` the kind of `spec/24 §1` that the model reads, so neither is a construct of the server.
2. **By module.** A kind of the program named as one of the server's (§1 rule 1) is declared in its own module and read as before. A `uses` entry names its capability without its module, so a capability of the program named `HttpServer` is refused with the host's: the re-check fails closed.
3. **What the model will cover** (ADR 0123 S10): `next` as an input stream and `reply` as an effect; T6 under a fixed stop schedule with the stream as input; and a lemma that which task holds a reply right is a function of each task's own order. The parser of §3 and §4 stays outside the model, and its fuzzing and differential tests stand for it. The milestones are #1863 (`next`), #1864 (`reply` and the reply rights) and #1865 (T6 and the lemma); until they land, rule 1 holds.
