From 4230c78dd19c1592e938cec653a25ab0de9dc88d Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 16:17:59 +0300 Subject: [PATCH] rfc: 0012 channels, mutex, select and cancellation points (Proposed) features cancellation, channels, sync; bounded/rendezvous channels with separate linear endpoints and a drain-then-close receiver protocol; waiting-operation rule with ok/closed/cancelled edges; shields with innermost-first nesting (E4305); mutex with function-bound guard and the no-wait-while-locked rule (E4304); select over channel operations with seeded choice among ready arms and per-edge ownership (Q-013); rwlock, channel_transfer, guard_transfer reserved; owner decisions D1-D3 --- docs/design/open-questions.md | 2 + docs/plan/phase-3-structured-concurrency.md | 2 +- ...0012-channels-mutex-select-cancellation.md | 412 ++++++++++++++++++ 3 files changed, 415 insertions(+), 1 deletion(-) create mode 100644 docs/rfcs/0012-channels-mutex-select-cancellation.md diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 239276d..fba3baa 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -107,6 +107,8 @@ Binary AIR has a `CAPABILITY_TABLE` (spec 07 §6). Undecided: how capabilities a Spec 04 §14 and spec 11 §6 require a stable rule in deterministic mode but do not define it. Also undecided: scheduler seed format and which choice points are recorded. +**Proposed (RFC 0012):** ready arms chosen by a draw from the schedule generator (not textual order); task choices and arm choices share one stream and one `choices` count. The schedule seed was settled by RFC 0011. + ## Q-014 — `Send`/`Share` for aggregates holding capabilities Spec 02 §6 derives properties structurally; spec 05 §5 says capability types define their own transfer rules. Undecided: the derivation for a struct mixing ordinary fields with `Local` or move-only capabilities. diff --git a/docs/plan/phase-3-structured-concurrency.md b/docs/plan/phase-3-structured-concurrency.md index e4c254b..97587f6 100644 --- a/docs/plan/phase-3-structured-concurrency.md +++ b/docs/plan/phase-3-structured-concurrency.md @@ -22,7 +22,7 @@ Non-normative. Part of the [implementation plan](README.md). | ID | Status | Task | Depends | Output | Done when | |---|---|---|---|---|---| -| P3-1 | doing | Resolve Q-013, Q-014; propose RFC 0002 for acceptance (Q-014 resolved by RFC 0011; Q-013 with RFC 0012) | — | spec 04, 11 | questions resolved | +| P3-1 | doing | Resolve Q-013, Q-014; propose RFC 0002 for acceptance (Q-014 resolved by RFC 0011; Q-013 proposed in RFC 0012) | — | spec 04, 11 | questions resolved | | P3-2 | doing | Contract tables: `task.*` (RFC 0011, done), `channel.*`, `mutex.*`, `rwlock.*`, select (RFC 0012); `thread.*` deferred to native backends | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects | | P3-2a | doing | Publish features `tasks` (done), `channels`, `sync` | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests | | P3-3 | done | Deterministic scheduler: seeds, choice points, choice log; global fuel across tasks and a separate `quantum` (spec 11 §7.2) | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run; fuel is the sum over all tasks | diff --git a/docs/rfcs/0012-channels-mutex-select-cancellation.md b/docs/rfcs/0012-channels-mutex-select-cancellation.md new file mode 100644 index 0000000..602f984 --- /dev/null +++ b/docs/rfcs/0012-channels-mutex-select-cancellation.md @@ -0,0 +1,412 @@ +# RFC 0012: Channels, Mutex, Select and Cancellation Points + +Status: Proposed +Scope: AIR format 0, features `cancellation`, `channels`, `sync` +Language version: 0.1 +Supersedes: — + +Resolves: Q-013 (deterministic `select` and the scheduler's choice points). Realizes spec 04 §7–§9, §12, §14–§16 for AIR. Builds on RFC 0011 (spec 04 §33–§36). + +Scope boundary: + +```text +RFC 0011: who may execute concurrently? +RFC 0012: how do concurrent tasks communicate, wait and coordinate? +``` + +Out of scope: `RwLock` (deferred, reserved feature `rwlock`), atomics (own RFC: after atomics the "every native outcome is an interleaving" model no longer suffices, spec 04 §36.1), timers, task-aware I/O and async buffer claims (`E4303`), multiple receivers. + +## Motivation + +After RFC 0011 tasks can only exchange data at spawn and join. Stage B of the evaluation (spec 14, `docs/evaluation/protocol.md`) needs the next two steps of spec 04 §1: ownership transfer between running tasks (channels) and synchronized shared state (mutex). It also needs waits that can be cancelled and a reproducible `select`. + +The design goal is a concurrency core that a weaker model can use safely. So the RFC chooses rules that remove whole classes of failure, even where they are stricter than Rust or Go: + +- every wait can end only in a listed outcome (`ok`, `closed`, `cancelled`) on its own CFG edge. There is no error enum, no exception and no trap; +- a channel never drops a value: a receiver can close only after it has drained the channel; +- a task never waits while it holds a lock guard. So mutexes alone cannot deadlock, and lock ordering never needs reasoning (§4.4); +- every scheduler-visible choice, including which ready `select` arm runs, comes from one seeded stream. `schedules: N` explores both. + +## Invariants + +1. **Explicit outcomes.** Every waiting operation completes on exactly one of its declared edges. Cancellation is never a trap. +2. **Ownership transfer.** A value sent on a channel is owned by the sending operation until the operation completes. On `ok` it belongs to the channel and then to the receiver. On `closed` or `cancelled` it is still the sender's. A value is never observable by two tasks. +3. **No silent drop.** A value is removed from a channel only by `channel.recv` or a `select` receive arm. A receiver is consumed only when the channel is empty and no more values can enter it. +4. **No wait under a lock.** While a task holds a `guard`, it executes no waiting operation. This is checked statically, including through calls. +5. **Cooperative cancellation.** Cancellation is observed only at the cancellation points of §2.2. An operation that can complete without waiting completes, even if cancellation is pending. Inside a shield, cancellation is never observed. Shields nest properly. +6. **Reproducibility.** Task choices and choices among ready `select` arms are drawn from the single schedule generator (spec 04 §36.2). Equal schedule seeds give equal runs. +7. **No hidden cleanup.** No guard is unlocked, no endpoint closed and no value dropped implicitly. A trap while holding a guard terminates the whole execution (spec 04 §33.2). + +## 1. Features and dependencies + +All three features are new to this RFC. `channels` and `sync` are reserved today with dependencies `[ownership]`. Their semantics cannot be stated without the task model, effects and, for channels, allocation budgets, so this RFC changes their reserved dependency lists (see decision D1 under Unresolved questions). + +| Feature | Depends on | Semantic block | +|---|---|---| +| `cancellation` | `effects`, `tasks` | effect `task.wait`; the waiting-operation rule (§2); `shield`, `task.shield.*`; `task.check_cancel`; the waiting form of `task.join` | +| `channels` | `cancellation`, `heap` | `sender`, `receiver`, `channel.*`, `select` | +| `sync` | `cancellation` | `mutex`, `guard`, `mutex.*`, the critical-section rule (E4304) | + +Reserved by this RFC (all unscheduled): + +| Feature | Depends on | Semantic block | +|---|---|---| +| `rwlock` | `sync` | `rwlock`, read and write guards (only `read_lock`, `write_lock` and `unlock`; no upgrade or downgrade) | +| `channel_transfer` | `channels` | `sender<…>`/`receiver<…>` inside channel elements or mutex contents; several receivers | +| `guard_transfer` | `sync` | `guard` as a parameter, a return type or an aggregate member | + +The published feature `tasks` is not changed (spec 07 §8.7). The new cancellation behavior applies only to new instructions. The plain `task.join` keeps its meaning, and `task.cancelled` keeps returning the raw request flag. + +## 2. Waiting and cancellation (feature `cancellation`) + +### 2.1 The waiting-operation rule + +A **waiting operation** is one of `task.join` in its terminator form, `channel.send`, `channel.recv`, `select` and `mutex.lock`. Each has a **ready condition** that may hold now or later. One rule covers all of them: + +```text +1. If the operation is ready, it completes with that outcome (ok or closed). + Pending cancellation is not consulted. +2. Otherwise, if cancellation is observable, it completes on its cancelled edge. +3. Otherwise the task waits. It becomes runnable when the operation becomes ready + or cancellation becomes observable. When it resumes, go to 1. +``` + +**Cancellation is observable** in a task when its cancellation-request flag (set by `task.cancel`, spec 04 §33.2) is set and its shield depth is 0. + +A waiting operation is a scheduling point when it completes and when it begins to wait. Fuel is paid once, when it first begins (spec 04 §36.3). A waiting task counts as waiting for global quiescence (spec 11 §8). If every unfinished task waits and none can become runnable, the run ends `blocked`. A cancellation request wakes a waiting task only if it makes cancellation observable for that task. + +The plain `task.join` and the I/O intrinsics (`net.accept`, reads on streams) are not cancellation points in format 0. + +### 2.2 Cancellation points + +| Point | Observes cancellation | +|---|---| +| `task.check_cancel` | always when observable | +| `task.join` (terminator form), `channel.send`, `channel.recv`, `select`, `mutex.lock` | only when it would otherwise wait (§2.1 step 2) | + +### 2.3 Instructions + +| Instruction | Operands → result | Effect | Verifier | Runtime | +|---|---|---|---|---| +| `task.check_cancel, ok -> @ok, cancelled -> @c` (terminator) | — ; both targets have no parameters | — | — | `@c` if cancellation is observable, else `@ok`; a scheduling point | +| `task.join %t, ok -> @ok, cancelled -> @c` (terminator) | `task`; `@ok(T)`, `@c()` | — | on the `ok` edge as plain `task.join` (consumes `%t`, ends its loans); on the `cancelled` edge `%t` and its loans stay live | waiting operation; ready when the task has returned | +| `%sh = task.shield.begin` | → `shield` | — | pushes `%sh` on the function's shield stack | increments the task's shield depth | +| `task.shield.end %sh` | `shield` (consumed) | — | `%sh` must be the innermost live shield (`E4305`) | decrements the shield depth | + +`shield` is linear, function-bound (as `scope` in spec 04 §33.1) and `Local`. The stack of live shields is part of the verifier state and must be identical on every edge into a block (`E3002`, like other linear state). Together with the innermost-first rule this makes shields properly nested regions. The depth is dynamic per task, so a function called inside a shield runs shielded. + +The cancelled edge of the waiting `task.join` lets a parent react to its own cancellation, for example by forwarding it with `task.cancel %t` and then joining. Downward propagation is not automatic: changing `task.cancel` would change the published `tasks` feature. + +### 2.4 Effect `task.wait` + +The new effect `task.wait` (no capability) is required by `channel.send`, `channel.recv`, `select` and `mutex.lock`. It is checked like every effect (spec 05 §9; `E3101`). It exists so that a function's public contract says whether it may wait for another task, which §4.4 needs. + +Joins do not need it. A function can join only tasks it spawned itself, because handles are function-bound, and spawning already requires `task.spawn`. + +## 3. Channels (feature `channels`) + +### 3.1 Types + +| Type | Meaning | Class | Send | Share | +|---|---|---|---|---| +| `sender` | sending endpoint | linear | yes | no | +| `receiver` | the receiving endpoint (exactly one per channel) | linear | yes | no | + +Endpoints are ordinary linear values. They may be block arguments, function parameters and return values, and may be moved into tasks. In format 0 they may not be aggregate members (reserved `linear_aggregates`) or heap contents (spec 03 §18: `own` holds value types). + +**Element type `T`** must satisfy: + +- `T: Send` (`E4001`); +- `T` contains no borrow (`E1001`) and no `scope`, `task<…>`, `shield` or `guard<…>` (`E1001`); +- `T` contains no `sender<…>` or `receiver<…>`; that is the reserved `channel_transfer` (`E0006`). + +Linear element types such as `own`, `file<…>` and `stream` are allowed. Moving them between tasks is what channels are for. + +### 3.2 Instructions + +All endpoint operations take a `mut` borrow of the endpoint. Only the close operations consume it. + +| Instruction | Operands → targets | Effect | Verifier | Runtime | +|---|---|---|---|---| +| `channel.make T, %n, %mem, ok -> @ok, err -> @err` (terminator) | `%n: usize` capacity, `%mem: cap`; `@ok(sender, receiver)`, `@err(alloc_error)` | `mem.alloc` | element rules of §3.1 | charges `%n × size(T)` bytes to `%mem` (spec 03 §19); a capacity of 0 creates a rendezvous channel. Never waits | +| `%tx2 = channel.sender.dup %txb` | `mut>` → `sender` | — | — | one more sender of the same channel | +| `channel.send %txb, %v, ok -> @ok, closed -> @closed, cancelled -> @c` (terminator) | `mut>`, `T`; targets without parameters | `task.wait` | `%v` is consumed on the `ok` edge only. On `closed` and `cancelled` it is still live and owned by the caller | waiting operation (§3.3) | +| `channel.recv %rxb, ok -> @ok, closed -> @closed, cancelled -> @c` (terminator) | `mut>`; `@ok(T)` | `task.wait` | — | waiting operation (§3.3) | +| `channel.close_sender %tx` | `sender` (consumed) | — | — | if it was the last sender, a drained receiver now sees `closed`; a scheduling point | +| `channel.close_receiver %rx, ok -> @ok, pending -> @pending` (terminator) | `receiver` (consumed on both edges); `@pending(receiver)` | — | — | §3.4; a scheduling point | +| `select …` (terminator) | §3.5 | `task.wait` | §3.5 | §3.5 | + +### 3.3 Ready conditions + +Values are delivered in FIFO order. + +| Operation | `ok`-ready | `closed`-ready | +|---|---|---| +| send, capacity `n > 0` | fewer than `n` values buffered | the receiver is closed or closing | +| send, capacity 0 | the receiver is waiting in `channel.recv` or in a `select` with a receive arm on this channel | the receiver is closed or closing | +| recv, capacity `n > 0` | a value is buffered | the buffer is empty and every sender is closed, or the receiver is closing | +| recv, capacity 0 | a sender is waiting in `channel.send` or in a `select` with a send arm on this channel | as above | + +`closed` takes precedence for a send: a send to a closed receiver is `closed` even if there is space. For a receive, buffered values take precedence: `closed` is reported only after the channel is drained. This is the RFC's answer to "last sender closed → recv after the queue is drained → closed". It is a concurrency state, not an `io_error`. + +On a rendezvous channel, a sender waiting in `channel.send` holds its value until a receiver takes it. A sender that leaves on `cancelled` or `closed` keeps the value. Waiting rendezvous senders are matched in the order they began to wait. When a send completes against a waiting `select`, that `select` resumes on the matched arm without a draw. + +A **synchronization edge** runs from a successful send to the receive that obtains the value (spec 04 §12). In the cooperative interpreter this is immediate; native backends must provide acquire/release ordering. + +### 3.4 Closing the receiver + +`channel.close_receiver` never drops a value: + +- if the buffer is empty, the receiver is consumed and the channel is closed for sending. Waiting and future sends end `closed`. The program continues at `@ok`; +- otherwise the channel enters the **closing** state. Sends end `closed` from now on, and waiting rendezvous senders also end `closed`. The receiver comes back on `@pending`. The program drains it with `channel.recv` until `closed` (buffered values first) and then closes it again, which now takes `@ok`. + +Because the closing state admits no new values, the drain loop terminates. A receiver can therefore stop early without leaking linear values, and the verifier needs no knowledge of the buffer contents. + +The channel's memory is returned to the `mem.alloc` budget when the receiver and the last sender have both been closed, at whichever of those closes comes last. That is an explicit instruction, so there is no hidden destructor. + +### 3.5 `select` + +```text +select [recv %rxb1, ok -> @a, closed -> @a_done], + [send %txb, %v, ok -> @sent, closed -> @gone], + cancelled -> @c +``` + +`select` is written on one line. The line breaks above are for readability. + +- **Arms** are channel operations, nothing else: `[recv %rxb, ok -> @x, closed -> @y]` with `@x(T)`, and `[send %txb, %v, ok -> @x, closed -> @y]`. A `select` has at least one arm and exactly one `cancelled` target. The arm targets have the parameters of the corresponding `channel.recv`/`channel.send` targets. +- **Readiness.** An arm is ready when its operation is `ok`-ready or `closed`-ready (§3.3). The `select` as a whole is a waiting operation (§2.1) whose ready condition is "at least one arm is ready". +- **Choice.** If exactly one arm is ready, it is taken. If `k ≥ 2` arms are ready, the scheduler draws `x = next()` from the schedule generator and takes the ready arm number `x mod k`, in textual order. The draw counts as a scheduler choice. It is not "first in text", so schedule exploration covers alternative ready branches. With `schedules: N`, task scheduling and arm selection vary together, from one stream. +- **Ownership along edges.** A value in a send arm is consumed only on that arm's `ok` edge. On every other edge of the `select` it is still live. The same value may therefore appear in several send arms: + + ```text + select [send %tx1, %x, ok -> @to1, closed -> @c1], [send %tx2, %x, ok -> @to2, closed -> @c2], cancelled -> @c + ``` + + This is the branch-edge ownership rule (spec 06 §6.3) applied per arm. The verifier applies the transfer function of the chosen arm to each edge. +- **Borrows.** Arms may name the same endpoint borrow more than once. Only one arm runs. + +## 4. Mutex (feature `sync`) + +### 4.1 Types + +| Type | Meaning | Class | Send | Share | +|---|---|---|---|---| +| `mutex` | mutual exclusion around a value of type `T` | move-only; linear if `T` is linear | if `T: Send` | if `T: Send` | +| `guard` | proof that the current task holds the lock | linear, function-bound, `Local` | no | no | + +`T` must satisfy the element rules of §3.1. A `mutex` is opaque: no `borrow.field`, `load` or `store` reaches its contents. That makes it the verifier-known interior-mutability abstraction of spec 04 §8. Tasks share a mutex by a `ref>` loan (spec 04 §34). Its `Share` property comes from the lock, not from immutability. + +`guard` is function-bound in the sense of spec 04 §33.1. Using it as a parameter, a return type or an aggregate member is the reserved `guard_transfer` (`E0006`). So the critical section is always visible in one function. + +### 4.2 Instructions + +| Instruction | Operands → result | Effect | Verifier | Runtime | +|---|---|---|---|---| +| `%m = mutex.make %v` | `T` (consumed) → `mutex` | — | element rules | an unlocked mutex holding `%v`; no allocation | +| `%v = mutex.take %m` | `mutex` (consumed) → `T` | — | ordinary move rules (no live borrow of the place holding it) | — | +| `mutex.lock %mr, ok -> @ok, cancelled -> @c` (terminator) | `ref>`; `@ok(guard)`, `@c()` | `task.wait` | the guard is a child of `%mr`: ending `%mr` while the guard is live is `E2102`; critical-section rule (§4.4) | waiting operation; ready when unlocked; acquire | +| `%p = mutex.borrow %g` | `guard` (not consumed) → `mut` | — | `%p` is a child borrow of `%g`; it must be ended before `mutex.unlock %g` (`E2102`) | — | +| `mutex.unlock %g` | `guard` (consumed) | — | — | release; every task waiting in `mutex.lock` on this mutex becomes runnable, and the first one scheduled takes the lock; a scheduling point | + +No fairness is promised (spec 04 §32). Because waiters are woken together and the schedule generator picks the order, schedule exploration covers the possible acquisition orders. + +### 4.3 No poisoning, no implicit unlock + +A trap terminates the whole execution (spec 04 §33.2), so there is no state where another task could observe a mutex abandoned mid-update. Nothing is unlocked implicitly. A `guard` that is not consumed on some path is `E3002`. + +### 4.4 The critical-section rule (`E4304`) + +On every path where a `guard` is live, the function MUST NOT execute: + +- a waiting operation (§2.1), including `mutex.lock`; +- `task.spawn`, or `task.join` in either form; +- a `call` (or an indirect call) of a function whose declared effects include `task.wait` or `task.spawn`. + +Violations are `E4304` (`sync.wait_while_locked`), naming the guard and the instruction. + +Consequences, by construction: + +- a task holds at most one guard at a time, since `mutex.lock` is itself a waiting operation; +- the holder of a lock never waits for another task. Every wait in `mutex.lock` ends when the holder runs to its `mutex.unlock`, unless the holder runs forever (fuel bounds that) or traps (which ends the run). **Mutexes alone cannot deadlock**, and no lock-ordering discipline is needed; +- a critical section may call ordinary functions and pass them the `mut` from `mutex.borrow`. Their effect sets say whether they may wait. + +The check reads only the caller's guard state and the callees' declared effects, so it stays intraprocedural (spec 04 §33 invariant 6). `sync` depends on `effects` through `cancellation`, so callee effect sets are always available. This is stricter than common runtimes. A future feature may relax it if evaluation shows the need. It is deliberately not reserved now. + +## 5. Scheduler and run record (resolves Q-013) + +- Choice points: (a) the choice of the next task among `n ≥ 2` runnable tasks (spec 04 §36.2), and (b) the choice among `k ≥ 2` ready `select` arms (§3.5). Both draw from the schedule generator. No draw is made when there is only one candidate. +- `"schedule":{"seed","quantum","choices"}` counts both kinds of choice. The record is emitted when tasks were spawned or a `select` drew. +- The `hosted` profile uses the same rule. +- The conformance runner's `schedules: N` needs no change. Stress modes (P3-12) add cancellation during waits and slow consumers. + +## Valid examples + +Producer/consumer. The receiver stops after the sender closes, and the drain protocol is visible: + +```text +fn @produce(%tx: sender) -> u8 +effects [task.wait] +entry: + %txb = borrow.mut %tx + %v = const.u64 7 + channel.send %txb, %v, ok -> @done, closed -> @done, cancelled -> @done +done: + borrow.end %txb + channel.close_sender %tx + %z = const.u8 0 + ret %z + +fn @main(%heap: cap) -> u64 +effects [mem.alloc, task.spawn, task.wait] +entry: + %two = const.usize 2 + channel.make u64, %two, %heap, ok -> @made, err -> @no_memory +made(%tx: sender, %rx: receiver): + %sc = task.scope.begin + %t = task.spawn %sc, @produce(%tx) ; sender moved into the task + %rxb = borrow.mut %rx + channel.recv %rxb, ok -> @got, closed -> @empty, cancelled -> @empty +got(%v: u64): + borrow.end %rxb + ... ; join, close_receiver (handle pending), scope.end, ret %v +``` + +A counter shared through a mutex. The critical section contains no wait: + +```text +fn @bump(%mr: ref>) -> u8 +effects [task.wait] +entry: + mutex.lock %mr, ok -> @locked, cancelled -> @stop +locked(%g: guard): + %p = mutex.borrow %g + %x = load %p + %one = const.u64 1 + %y = add.checked.u64 %x, %one + store %p, %y + borrow.end %p + mutex.unlock %g + ... +``` + +`select` with the same value in two send arms: + +```text + select [send %a, %job, ok -> @sent_a, closed -> @a_gone], [send %b, %job, ok -> @sent_b, closed -> @b_gone], cancelled -> @stop +``` + +## Rejected examples + +```text +locked(%g: guard): + channel.recv %rxb, ok -> @got, closed -> @end, cancelled -> @end ; E4304: waits while %g is live +``` + +```text + %s1 = task.shield.begin + %s2 = task.shield.begin + task.shield.end %s1 ; E4305: %s2 is the innermost live shield +``` + +```text + channel.send %txb, %v, ok -> @sent, closed -> @closed, cancelled -> @c +sent: + %w = struct.get @Msg.id, %v ; E2001: %v was moved on the ok edge +``` + +```text + channel.make ref, %n, %heap, ok -> @ok, err -> @err ; E1001: channel elements contain no borrow +``` + +Expected diagnostic of the first example: + +```json +{"code":"E4304","kind":"sync.wait_while_locked","severity":"error","function":"worker","block":"locked","inst":0,"guard":"%g","op":"channel.recv","message":"waiting operation while a lock guard is live"} +``` + +## Diagnostics impact + +New codes: + +| Code | Kind | Meaning | +|---|---|---| +| E4304 | sync.wait_while_locked | Waiting operation, spawn, join or call of a waiting/spawning function while a lock guard is live | +| E4305 | task.shield_order | Shield ended while a more inner shield is live | + +Existing codes used: + +- `E4001` and `E1001` for element rules; +- `E2001` and `E2002` for moved send values; +- `E2102` for guard and access borrows; +- `E3002` for leaked endpoints, guards and shields, and for differing shield stacks at a join; +- `E3101` for `task.wait`; +- `E0006` for `rwlock`, `channel_transfer` and `guard_transfer`. + +No new trap codes. No new environment outcomes: deadlocks remain `blocked`. + +## Spec integration + +On acceptance: + +- spec 04: new §37 (waiting and cancellation), §38 (channels), §39 (select), §40 (mutex), §41 (critical-section rule); §14–§16 point to them; §11 marks RwLock as deferred; +- spec 02 §6 / spec 04 §35: Send/Share rows for the new types; +- spec 05: effect `task.wait`; +- spec 07 §8: types and the `select` syntax; spec 07a: contract rows; +- spec 08: verifier stages (shield stack, guard state, E4304); +- spec 11 §8: choice points, record; +- `reference/air-text.ebnf`, `air-features.md`, `effects.md`, `error-codes.md`; +- `docs/agent/bundle.txt`; +- Q-013 marked resolved. + +## Compatibility and migration + +Additive under spec 07 §8.7: three new features, new types, instructions, one effect and two diagnostic codes. `tasks` and every published feature keep their meaning. The plain `task.join` is not a cancellation point, and `task.cancelled` ignores shields (it reads the raw flag). The only change to the registry beyond additions is the dependency lists of the reserved `channels` and `sync` (decision D1). No module can use a reserved feature today, so no accepted or rejected module changes status. + +## Agent complexity impact + +- **New concepts:** + - endpoint pair; + - bounded and rendezvous capacity; + - the drain-then-close protocol; + - the three wait outcomes; + - cancellation points and shields; + - mutex, guard and the critical-section rule; + - `select` arms with per-edge ownership. +- **New verifier state:** + - per function, a stack of live shields; + - the set of live guards; + - per-edge consumption for `channel.send` and `select`, which reuses the existing per-edge linear machinery (as for `fs.close`). +- **New syntax:** + - 3 features, 5 types, 1 effect; + - 13 instructions: `task.check_cancel`, waiting `task.join`, `task.shield.begin`/`end`, `channel.make`/`sender.dup`/`send`/`recv`/`close_sender`/`close_receiver`, `select`, `mutex.make`/`take`/`lock`/`borrow`/`unlock` (counting `select` once). +- **Interactions:** loans (sharing a `ref`), effects (`task.wait`, the E4304 call rule), linearity (endpoints, guards, shields), heap budgets (channel buffers), the scheduler (choices). +- **Repairability:** + - each outcome is an edge the agent must route, so a forgotten case is a CFG error, not a runtime surprise; + - E4304 names the guard and the offending instruction; the repair is "unlock before waiting"; + - deadlocks between mutexes are impossible, so the repair space of `blocked` runs shrinks to channel and join cycles. +- **Could existing primitives express it?** No. Tasks can exchange data only at spawn and join. +- **Uniformity chosen over brevity:** one waiting-operation rule for all waits; one close-on-both-edges pattern (as `fs.close`); endpoint operations always take `mut`. +- **Agent Reference Bundle growth:** estimated +12–16 % tokens (about five new spec sections plus registry rows). RFC 0011's estimate was 3 points low, so this is a deliberately cautious range. It will be measured on integration. + +## Alternatives considered + +- **One `channel` value**: closing would need two meanings on one value; separate endpoints make "last sender closed" and "receiver closed" explicit and allow `dup` for several producers. +- **Unbounded channels**: implicit, unbounded allocation; rejected (spec 04 §12). Unbounded queues remain library constructs. +- **Dropping buffered values on `close_receiver`**: a hidden destructor for linear elements; rejected for the drain protocol (§3.4). +- **Allowing waits while locked** (Rust, Go): reintroduces lock-order deadlocks and guard-across-await bugs, which are hard for agents to see. Rejected for format 0. +- **`select` picks the first ready arm in text**: reproducible, but schedule exploration would never see the other branch. Rejected for a seeded draw. +- **`select` over arbitrary expressions**: rejected; arms are operations with fixed transfer functions. +- **Cancellation as a trap or a universal `TaskError`**: rejected; outcomes are edges. +- **Automatic downward cancellation propagation**: would change the published `task.cancel`. Instead the waiting `task.join` lets a parent forward cancellation explicitly. +- **Shield as a lexical block or a separate task**: AIR has no lexical blocks; a linear token with innermost-first ending gives proper nesting with existing machinery. +- **`RwLock` now**: read and write guards, fairness, starvation and several concurrent guards add little expressive power over a mutex, ownership partitioning and channels. Deferred (reserved `rwlock`). +- **Channel capacity in the type, buffer in frame storage**: avoids the heap but makes endpoints borrows, which cannot be moved into tasks or returned. Rejected for linear endpoints with an explicit `mem.alloc` charge. + +## Unresolved questions + +Decisions requested from the owner: + +- **D1 — dependencies of the reserved `channels` and `sync`.** The registry says a reserved feature's name and dependencies are fixed, but `[ownership]` cannot state the semantics, and §1 needs `cancellation`/`heap` and `cancellation`. No module is affected, since reserved features are unusable. Proposal: allow the change this once, recorded in DD-014's log. +- **D2 — waiting `task.join`.** Proposal: a new terminator form in `cancellation`, with no automatic propagation. Alternative: no cancellable join at all; parents must poll `task.check_cancel` between joins. +- **D3 — `channel.sender.dup` in format 0.** Proposal: yes. Several producers into one receiver is the common fan-in, and "last sender closed" needs it to be meaningful. Alternative: one sender per channel; fan-in uses one channel per producer and `select`.