861 lines
48 KiB
Markdown
861 lines
48 KiB
Markdown
# 04. Concurrency and Atomics
|
||
|
||
This file is normative. Rationale is in RFCs 0002 and 0003.
|
||
|
||
## 1. Design hierarchy
|
||
|
||
Safe Aji SHOULD solve concurrency in this order:
|
||
|
||
```text
|
||
1. ownership transfer
|
||
2. shared immutable data
|
||
3. synchronized shared mutable state
|
||
4. atomics
|
||
5. unsafe raw concurrency
|
||
```
|
||
|
||
The language makes weaker, more error-prone mechanisms increasingly explicit.
|
||
|
||
## 2. Execution units
|
||
|
||
Aji distinguishes:
|
||
|
||
- `Task`: runtime-scheduled unit that may migrate between scheduler workers;
|
||
- `LocalTask`: task pinned to a scheduler worker because captured state is `Local`;
|
||
- `Thread<T>`: operating-system thread handle.
|
||
|
||
## 3. Structured task scopes
|
||
|
||
Tasks are created inside a lexical/dynamic task scope:
|
||
|
||
```aji
|
||
task.scope s {
|
||
let t = task.spawn(s, worker, move input)?;
|
||
let result = task.join(move t)?;
|
||
}
|
||
```
|
||
|
||
A child task MUST NOT outlive its scope.
|
||
|
||
A scope cannot complete while live child handles exist unless they have been explicitly joined, cancel-joined or transferred to a permitted supervisor abstraction.
|
||
|
||
Silent detachment is prohibited.
|
||
|
||
## 4. Detached execution
|
||
|
||
Detached tasks require explicit authority such as `cap<task.detach>`.
|
||
|
||
Captured values must be owned, `Send`, and independent of the parent lifetime.
|
||
|
||
General application code SHOULD prefer supervisors or structured scopes.
|
||
|
||
## 5. Send and Share
|
||
|
||
A value moved into a migratable task or thread must satisfy `Send`.
|
||
|
||
A value observed concurrently through immutable borrows must satisfy `Share`.
|
||
|
||
Thread-affine resources are `Local` and therefore cannot enter migratable tasks.
|
||
|
||
## 6. Borrowing into scoped tasks
|
||
|
||
A structured child task may borrow parent data if the verifier proves the child completes before the borrowed storage expires.
|
||
|
||
Mutable data may be borrowed into multiple child tasks only when the borrowed regions are proven disjoint.
|
||
|
||
## 7. Shared mutable state
|
||
|
||
Ordinary `mut<T>` may not be concurrently shared.
|
||
|
||
Safe shared mutation uses approved synchronization types:
|
||
|
||
```text
|
||
Mutex<T>
|
||
RwLock<T>
|
||
atomic<T>
|
||
Channel<T>
|
||
```
|
||
|
||
## 8. Verified interior mutability
|
||
|
||
Synchronization wrappers such as `Mutex<T>`, `RwLock<T>` and atomic types are verifier-known interior-mutability abstractions.
|
||
|
||
Their internal mutable storage is not directly reachable through ordinary `ref<T>` or `mut<T>` operations. Mutation is exposed only through operations whose synchronization semantics are known to the verifier.
|
||
|
||
Ordinary user-defined structs cannot obtain shared interior mutation merely by hiding a mutable field behind a method. Equivalent abstractions require an audited unsafe implementation or a verifier-known intrinsic.
|
||
|
||
A synchronization wrapper may therefore be `Share` even though it internally changes state. Its `Share` implementation is defined by the wrapper's synchronization contract, not by ordinary field immutability.
|
||
|
||
## 9. Mutex
|
||
|
||
A mutex guard is linear and provides exclusive `mut<T>` access.
|
||
|
||
```aji
|
||
let g = mutex.lock(ref m)?;
|
||
modify(g);
|
||
mutex.unlock(move g);
|
||
```
|
||
|
||
A successful lock has acquire semantics. Unlock has release semantics.
|
||
|
||
Mutex guards are not `Send` by default.
|
||
|
||
Core mutexes do not automatically implement poisoning because Aji has no exception unwinding.
|
||
|
||
## 10. Ordered mutex profile
|
||
|
||
Aji MAY provide `OrderedMutex<Rank, T>`.
|
||
|
||
While holding rank `R`, acquiring a lower/equal forbidden rank is rejected according to profile rules.
|
||
|
||
This profile can eliminate a class of lock-order deadlocks but is not required for all programs.
|
||
|
||
## 11. RwLock
|
||
|
||
`RwLock<T>` permits:
|
||
|
||
- multiple read guards yielding `ref<T>`;
|
||
- exactly one write guard yielding `mut<T>`.
|
||
|
||
Fairness is runtime-specific unless a runtime profile promises otherwise.
|
||
|
||
AIR format 0 defers `RwLock` (reserved feature `rwlock`; RFC 0012). The AIR mutex is specified in §40–§41.
|
||
|
||
## 12. Channels
|
||
|
||
Channels transfer ownership.
|
||
|
||
```aji
|
||
let (tx, rx) = channel.create<Message>(capacity = 1024)?;
|
||
channel.send(ref tx, move message)?;
|
||
let message = channel.recv(ref rx)?;
|
||
```
|
||
|
||
Channels are bounded by default.
|
||
|
||
Capacity `0` denotes a rendezvous channel.
|
||
|
||
Unbounded queues are library constructs whose allocation behavior must be explicit.
|
||
|
||
A successful send synchronizes with the receive that obtains the transferred value.
|
||
|
||
AIR realization: §38 (separate `sender<T>`/`receiver<T>` endpoints, MPSC).
|
||
|
||
## 13. Island messaging
|
||
|
||
`island<T>` is the preferred representation for large mutable messages and object graphs. Sending an island transfers ownership in O(1) without exposing shared mutation. An immutable graph is shared as `frozen<T>` (lent by `ref`) or `arc<T>` (several owners): spec 03 §12–§14, §22–§24.
|
||
|
||
## 14. select
|
||
|
||
Aji may wait on multiple events:
|
||
|
||
```aji
|
||
select {
|
||
recv(rx1) => ...
|
||
recv(rx2) => ...
|
||
timer(deadline) => ...
|
||
cancelled(token) => ...
|
||
}
|
||
```
|
||
|
||
When multiple branches are ready, normal mode does not promise source-order selection. Deterministic mode must define a stable choice.
|
||
|
||
AIR realization: §39 (channel arms only; seeded choice among ready arms).
|
||
|
||
## 15. Cancellation
|
||
|
||
Cancellation is cooperative.
|
||
|
||
A task is not asynchronously interrupted at arbitrary instructions.
|
||
|
||
Cancellation is observed only at explicit cancellation points, including selected waits, channel operations, timer operations and `task.check_cancel`.
|
||
|
||
Structured cancellation propagates from parent to descendants.
|
||
|
||
AIR realization: §37. In format 0 propagation is explicit: `task.join.cancel` lets a parent observe its own cancellation and forward it with `task.cancel`.
|
||
|
||
## 16. Cancellation shielding
|
||
|
||
A bounded scope may defer cancellation observation:
|
||
|
||
```aji
|
||
task.cancel_shield {
|
||
commit_metadata();
|
||
}
|
||
```
|
||
|
||
The cancellation request remains pending and is observed after leaving the shield.
|
||
|
||
AIR realization: `task.shield.begin`/`task.shield.end` (§37.3).
|
||
|
||
## 17. Task failure
|
||
|
||
Task functions return normal values or `Result<T, E>`.
|
||
|
||
A failing task does not implicitly terminate siblings. Supervision policy is explicit and may implement fail-fast, collect-all, first-success or restart semantics.
|
||
|
||
## 18. Blocking
|
||
|
||
Operations that block an OS thread declare `thread.block` in their effects.
|
||
|
||
A cooperative scheduler may reject direct blocking calls from ordinary tasks and require a blocking pool or dedicated thread.
|
||
|
||
## 19. Asynchronous I/O
|
||
|
||
An asynchronous operation retains ownership/borrow claims over its buffers until completion.
|
||
|
||
```aji
|
||
let op = io.read_start(file, borrow mut buffer)?;
|
||
// buffer unavailable
|
||
let n = io.wait(move op)?;
|
||
// buffer available again
|
||
```
|
||
|
||
This prevents use or mutation while the OS/runtime may access the buffer.
|
||
|
||
## 20. Memory model
|
||
|
||
The memory model of Aji 0.1 has three layers (RFC 0015):
|
||
|
||
```text
|
||
ordinary safe memory → DRF-SC (§21–§22)
|
||
atomic memory → the Aji 0.1 atomic model: the Aji RC11 profile (this section)
|
||
unsafe code → its own proof obligations (spec 13 §4)
|
||
```
|
||
|
||
The atomic model, the **Aji RC11 profile**, consists of the consistency axioms of RC11 (Lahav, Vafeiadis, Kang, Hur, Dreyer, PLDI 2017), restricted to the operations of §23–§27. That includes RC11's NO-THIN-AIR axiom (§20.4, axiom 4).
|
||
|
||
The model is defined by the relations and axioms of §20.1–§20.4, not by litmus outcomes. It is stronger than ISO C11/C++20. One consequence is that the cyclic load-buffering outcome is forbidden (`reference/concurrency-litmus.md`, LB).
|
||
|
||
A weaker model MAY later be added only as a separate feature. Published semantics MUST NOT be weakened.
|
||
|
||
### 20.1 Events
|
||
|
||
An execution consists of events:
|
||
|
||
- atomic reads `R` and writes `W`, each with a location, a value and an ordering;
|
||
- fences `F`;
|
||
- ordinary reads and writes;
|
||
- the synchronization events of the built-in primitives (§20.3).
|
||
|
||
**Read-modify-write.** A successful read-modify-write, including a successful compare-exchange, consists of two events:
|
||
|
||
- a read event and a write event of the same location, related by `rmw`;
|
||
- the read is immediately `sb`-before the write;
|
||
- both carry the operation's ordering.
|
||
|
||
A failed compare-exchange is a single read event with the failure ordering. It writes nothing and is not in `rmw`.
|
||
|
||
**Distinguished initialization write.** Every atomic cell has one initialization write, the value given to `atomic.new`. It is a service event of the model, not a source-level access:
|
||
|
||
- it precedes every other write of the cell in `mo`;
|
||
- it happens-before every program access to the cell;
|
||
- it starts no `sw`, and is never part of a data race.
|
||
|
||
**Taking the cell.** `atomic.take` is an ordinary read of the cell. It is happens-before-ordered after every atomic access by §28.
|
||
|
||
### 20.2 Relations
|
||
|
||
An execution has:
|
||
|
||
- `sb` (sequenced-before): the program order of the events of one task;
|
||
- `rf` (reads-from): relates each read to exactly one write to the same location, whose value it reads;
|
||
- `mo` (modification order): a strict total order on the writes to each location;
|
||
- `rmw`: relates the read event of each successful read-modify-write to its write event (§20.1).
|
||
|
||
Derived:
|
||
|
||
```text
|
||
fr = rf⁻¹ ; mo from-read
|
||
eco = (rf ∪ mo ∪ fr)⁺ extended coherence
|
||
rs = [W] ; (rf ; rmw)* release sequence (C++20 form)
|
||
sw = [E ⊒ rel] ; ([F] ; sb)? ; rs ; rf ; [R] ; (sb ; [F])? ; [E ⊒ acq] ∪ sw_prim
|
||
hb = (sb ∪ sw)⁺ happens-before
|
||
```
|
||
|
||
`E ⊒ rel` is a write or fence whose ordering is `release`, `acq_rel` or `seq_cst`. `E ⊒ acq` is a read or fence whose ordering is `acquire`, `acq_rel` or `seq_cst`. A read-modify-write's two events carry its ordering, so its write event is `⊒ rel` and its read event `⊒ acq` as the ordering says. `[X]` restricts a relation to events in `X`.
|
||
|
||
The release sequence is deliberately the C++20 form. It continues only through read-modify-writes that read from it, not through later plain stores of the releasing task (as C11 and the original RC11 do).
|
||
|
||
### 20.3 Synchronization of built-in primitives
|
||
|
||
**Object orders.** Each task, channel and mutex has a total order of its operations. These orders are not part of the `seq_cst` order: they are lock semantics, as for C++ mutexes. Each order is **consistent with `hb`**: for any `a` and `b` in the domain of the order, if `a hb→ b` then `a` precedes `b` in the order. No `hb` edge points backwards in it.
|
||
|
||
**`sw_prim`** contains:
|
||
|
||
- `task.spawn` → the first event of the spawned task;
|
||
- the last event of a task → the `task.join` (or `task.join.cancel`) that returns its result;
|
||
- a successful `channel.send` of a value → the `channel.recv` (or `select` arm) that obtains that exact value;
|
||
- `channel.close_sender` of the last sender → the `closed` outcome it causes;
|
||
- `mutex.unlock` → the next `mutex.lock` of the same mutex;
|
||
- `task.cancel` → the `cancelled` outcome it causes.
|
||
|
||
**Channels.**
|
||
|
||
- A buffered channel is FIFO. Successful sends enter one enqueue order of the channel, and receives remove values in that order. With several senders, the execution (the scheduler) determines the enqueue order. Once it exists, receivers observe it.
|
||
- A rendezvous channel (capacity 0) has no buffer. The scheduler chooses which waiting send is matched with a receive.
|
||
- Each value is received at most once.
|
||
- **Capacity affects blocking and scheduling, not memory ordering, in Aji 0.1.** A receive that frees a slot, and the send it unblocks, are related by nothing beyond the edges listed above.
|
||
- A semantics in which capacity itself creates synchronization (as in Go) may only be introduced as a separate feature by an RFC. The published model is never strengthened silently.
|
||
|
||
### 20.4 Consistency
|
||
|
||
An execution is consistent iff:
|
||
|
||
1. **Coherence:** `hb ; eco?` is irreflexive.
|
||
2. **Atomicity:** `rmw ∩ (fr ; mo)` is empty.
|
||
3. **SC:** `psc` is acyclic. `psc` is RC11's partial SC relation over `seq_cst` accesses and `seq_cst` fences:
|
||
|
||
```text
|
||
scb = sb ∪ (sb|≠loc ; hb ; sb|≠loc) ∪ hb|loc ∪ mo ∪ fr
|
||
psc_b = ([E_sc] ∪ [F_sc] ; hb?) ; scb ; ([E_sc] ∪ hb? ; [F_sc])
|
||
psc_F = [F_sc] ; (hb ∪ hb ; eco ; hb) ; [F_sc]
|
||
psc = psc_b ∪ psc_F
|
||
```
|
||
|
||
4. **No-thin-air:** `sb ∪ rf` is acyclic.
|
||
|
||
Consequence: the cyclic load-buffering outcome (each task reads the value the other writes later in program order) is forbidden.
|
||
|
||
The **outcomes** of a program are the observable behaviors of its consistent executions: the run record without scheduler bookkeeping, that is, result or trap, captured output and written files.
|
||
|
||
### 20.5 The oracle and the interpreter
|
||
|
||
There are two distinct obligations:
|
||
|
||
- **Axiomatic oracle.** `tools/litmus` holds an enumerator derived from §20.1–§20.4. For a small program it enumerates exactly the consistent executions, and hence the allowed outcomes. It is an executable oracle, not the definition. When it, the interpreter and a stated outcome set disagree, the disagreement is diagnosed as a defect of a tool or of the stated set. The model changes only through an RFC.
|
||
|
||
**Status of the corpus.** The 20 tests of `tests/litmus/` are the normative conformance corpus of the Aji 0.1 atomic model. They are normative consequences of §20.1–§20.4, not its definition. For each test:
|
||
|
||
```text
|
||
oracle allowed set == stated allowed set
|
||
interpreter exhaustive outcomes == stated allowed set
|
||
```
|
||
|
||
Changing the allowed or forbidden set of a published test changes the memory model and requires an RFC. New tests that only cover the existing axioms may be added as extensions of the corpus.
|
||
- **Interpreter exploration.**
|
||
- For every program, every outcome the interpreter produces is allowed (`observed ⊆ allowed`).
|
||
- For each test of the finite normative litmus corpus (`reference/concurrency-litmus.md`), exhaustive exploration produces every allowed outcome (`observed_exhaustive = allowed`).
|
||
- The interpreter is not required to be able to produce every allowed outcome of an arbitrary program.
|
||
|
||
## 21. Data race
|
||
|
||
Two accesses **conflict** when they access the same location and at least one writes.
|
||
|
||
A **data race** is a pair of conflicting accesses, at least one of them ordinary, that `hb` does not order.
|
||
|
||
A verified safe program MUST have no data race in any consistent execution. The ownership, borrow and loan rules (§34) guarantee this, together with the atomic access rule (§28). The interpreter's race detector checks it dynamically. A race in unsafe code is Undefined Aji Behavior.
|
||
|
||
## 22. DRF-SC guarantee
|
||
|
||
> A verified safe program whose transitive effects contain no `atomic.weak` has only sequentially consistent executions: each outcome is the outcome of an interleaving of its tasks' events in which every read reads the latest write.
|
||
|
||
The basis is RC11's theorem for programs whose atomics are all `seq_cst`, with the lock semantics of §20.3. With `atomic.weak`:
|
||
|
||
- ordinary memory is still race-free, and an ordinary read sees the unique `hb`-latest write;
|
||
- only atomic cells may show outcomes no interleaving gives.
|
||
|
||
## 23. Atomic types
|
||
|
||
`atomic<T>` is defined for the **AtomicScalar** types:
|
||
|
||
```text
|
||
bool u8 u16 u32 u64 usize i8 i16 i32 i64 isize
|
||
```
|
||
|
||
Any other `T` is `E1001`: 128-bit integers, aggregates, references, owners and handles alike.
|
||
|
||
`atomic<T>` is **linear**, `Send` and `Share`, and not copyable.
|
||
|
||
- It may appear where graph owners may (spec 03 §22): SSA values, parameters, returns, block arguments, channel elements and mutex contents.
|
||
- As an aggregate member or individual own<T> content it needs `linear_aggregates` (spec 03 §25; E0006 without it). Frame/bulk-region/heap-array content remains Copy-only.
|
||
- It is not `IslandSafe` (`E2111`).
|
||
- Size and alignment equal those of `T`.
|
||
|
||
Every operation on a cell takes `ref<atomic<T>>`, so several tasks can share one cell through shared borrows. `mut<atomic<T>>` is not an operand of any atomic operation.
|
||
|
||
A target implements `atomic<T>` only natively and lock-free (spec 09 §9). A module using a width the target does not list is rejected for that target with `E4203`. An implementation MUST NOT emulate an atomic with a lock.
|
||
|
||
## 24. Atomic ordering
|
||
|
||
Exactly these orderings exist:
|
||
|
||
```text
|
||
relaxed acquire release acq_rel seq_cst
|
||
```
|
||
|
||
There is no `consume` and no default ordering. Every atomic memory operation names its orderings, and any ordering outside its row is `E4201`.
|
||
|
||
| Operation | Allowed orderings |
|
||
|---|---|
|
||
| load | `relaxed`, `acquire`, `seq_cst` |
|
||
| store | `relaxed`, `release`, `seq_cst` |
|
||
| read-modify-write | `relaxed`, `acquire`, `release`, `acq_rel`, `seq_cst` |
|
||
| fence | `acquire`, `release`, `acq_rel`, `seq_cst` |
|
||
|
||
### 24.1 Compare-exchange
|
||
|
||
Compare-exchange takes a success ordering (any of the five) and a failure ordering. A failed compare-exchange is a load: its failure ordering has no release part and is never stronger than the success ordering.
|
||
|
||
| Success | Allowed failure |
|
||
|---|---|
|
||
| `relaxed` | `relaxed` |
|
||
| `acquire` | `relaxed`, `acquire` |
|
||
| `release` | `relaxed` |
|
||
| `acq_rel` | `relaxed`, `acquire` |
|
||
| `seq_cst` | `relaxed`, `acquire`, `seq_cst` |
|
||
|
||
Compare-exchange is strong: it fails only if the value read differs from the expected value (bitwise). There is no weak (spuriously failing) form in Aji 0.1.
|
||
|
||
### 24.2 Read-modify-write operations
|
||
|
||
| Operation | Types | Writes |
|
||
|---|---|---|
|
||
| `xchg` | integers, `bool` | the operand |
|
||
| `add.wrap`, `sub.wrap` | integers | the old value plus or minus the operand, modulo 2ⁿ |
|
||
| `and`, `or`, `xor` | integers, `bool` | the bitwise result |
|
||
|
||
Each returns the value it read. There is no checked atomic arithmetic: a trap after the write is visible would leave the cell changed. A compare-exchange loop expresses checked updates.
|
||
|
||
## 25. Weak atomics
|
||
|
||
The effect rule, literally:
|
||
|
||
```text
|
||
seq_cst atomic operation → effects [atomic]
|
||
non-seq_cst atomic operation → effects [atomic, atomic.weak]
|
||
atomic.fence (any ordering) → effects [atomic]
|
||
atomic.new, atomic.take → no effect
|
||
```
|
||
|
||
- An atomic access is non-`seq_cst` if its ordering is not `seq_cst`; for compare-exchange, if either ordering is not.
|
||
- The function declares both atoms: `atomic.weak` never stands alone, because effects are flat (spec 05 §9.2).
|
||
|
||
The resulting invariant:
|
||
|
||
```text
|
||
atomic.weak ∉ transitive effects of @main
|
||
⇒ every atomic access is seq_cst
|
||
⇒ every execution of the safe program is explainable as an SC interleaving (§22)
|
||
```
|
||
|
||
Reason: release/acquire alone already allows outcomes no interleaving gives (SB, IRIW), so the line between interleaving reasoning and weak reasoning is `seq_cst`, not `relaxed`. `aji report` lists every weak site.
|
||
|
||
## 26. Sequential consistency
|
||
|
||
`seq_cst` accesses and fences are ordered by the SC axiom of §20.4. A program whose atomics are all `seq_cst` behaves as an interleaving (§22).
|
||
|
||
## 27. Fences
|
||
|
||
```text
|
||
atomic.fence acquire | release | acq_rel | seq_cst
|
||
```
|
||
|
||
There is no relaxed fence. Fences synchronize through `sw` (§20.2), and `seq_cst` fences take part in `psc`.
|
||
|
||
## 28. Mixing atomic and ordinary access
|
||
|
||
Safe code reaches the contents of a cell ordinarily only through `atomic.new` (initialization) and `atomic.take` (the final read). `atomic.take` consumes the cell and requires that no borrow is live or lent (`E2101`, `E4101`), so it is `hb`-ordered after every atomic access. An ordinary `load` through `ref<atomic<T>>` is `E4202`.
|
||
|
||
Format 0 has no unsafe operation on atomic cells. An unsafe operation that mixes atomic and ordinary access to one location (a later RFC) carries the obligation that no data race results (spec 13 §4). Violating it is Undefined Aji Behavior.
|
||
|
||
## 29. Atomic pointers and reclamation
|
||
|
||
Safe Aji 0.1 has no atomic reference, owner or handle: `atomic<ref<T>>`, `atomic<own<T>>`, `atomic<iref<T>>` and `atomic<arc<T>>` are `E1001`. Publishing an address does not solve reclamation. The safe substitute is an index into owned storage, kept in an `atomic<usize>`.
|
||
|
||
Lock-free pointer structures and their reclamation (hazard pointers, epochs, RCU) are left to a later RFC, which defines their unsafe boundary and reclamation obligation.
|
||
|
||
## 30. ABA
|
||
|
||
The verifier does not prove ABA absence. Algorithms use explicit countermeasures, such as generation counters in the compared value.
|
||
|
||
## 31. Progress guarantees
|
||
|
||
Aji does not infer lock-free/wait-free guarantees in v0.1.
|
||
|
||
Libraries may document an implementation as blocking, obstruction-free, lock-free or wait-free.
|
||
|
||
## 32. Deadlock and liveness
|
||
|
||
Core Aji does not guarantee deadlock freedom, livelock freedom, starvation freedom or scheduler fairness.
|
||
|
||
Optional verification profiles may establish stronger properties for restricted programs.
|
||
|
||
## 33. Tasks in AIR (feature `tasks`)
|
||
|
||
Decision record: RFC 0011.
|
||
|
||
Invariants:
|
||
|
||
1. **Structure.** A task never outlives the scope that spawned it: a scope cannot end while a task spawned from it is unjoined, and the entry function cannot return while any scope is live. There is no detachment.
|
||
2. **No data races on ordinary memory.** Memory reachable by two tasks at once is reachable only through shared borrows of `Share` data, or through exclusive borrows of provably disjoint places. A borrow lent to a task stays lent until the task is joined.
|
||
3. **Send/Share soundness.** A value moved into a task is `Send`; data observed through a shared borrow from several tasks is `Share`.
|
||
4. **Reproducibility.** For a given module, inputs, grants, seed and quantum, the schedule — and therefore the run record — is identical on every run.
|
||
5. **Exhaustive interleaving semantics.** A program's meaning does not depend on the scheduler beyond what its synchronization allows; schedule exploration may run any interleaving the scheduler can produce.
|
||
6. **Local verification.** Task handles, scopes and loans never leave the function that created them, so all concurrency checks stay intraprocedural.
|
||
7. **Bounded concurrency.** The deterministic profile bounds the number of live tasks independently of host memory.
|
||
|
||
Depends on `ownership`.
|
||
|
||
### 33.1 Types
|
||
|
||
| Type | Meaning | Class |
|
||
|---|---|---|
|
||
| `scope` | a structured task scope | linear, function-bound |
|
||
| `task<T>` | handle of a task that returns `T` | linear, function-bound; consumed by `task.join` |
|
||
|
||
**Function-bound.** A `scope` or `task<T>` may be passed between blocks of the function that created it (as a block argument) and used by `task.*`. It may not be a function parameter, a return type, an aggregate member, or stored in heap or region memory; those uses belong to the reserved feature `task_transfer` (`E0006` reason `feature_not_declared`). Keeping handles in their function keeps loans intraprocedural (invariant 6).
|
||
|
||
**Result type.** `task<T>` requires `T: Send`, and `T` must not transitively contain a borrow, a `scope` or a `task<…>`. A spawned function returning a borrow (for example one derived from a lent argument) belongs to the reserved feature `task_borrow_returns` (`E0006`): after `join`, whether the loan ends or continues as the returned borrow is deliberately left undefined in format 0.
|
||
|
||
### 33.2 Instructions
|
||
|
||
| Instruction | Operands → result | Effect | Verifier | Runtime |
|
||
|---|---|---|---|---|
|
||
| `%s = task.scope.begin` | → `scope` | — | — | opens a scope |
|
||
| `%t = task.spawn %s, @f(%a…)` | `scope`, arguments of `@f` → `task<T>` (`T` = return type of `@f`) | `task.spawn` | arguments checked like a `call`; argument rules of §35; borrow arguments are lent until `task.join` (§34); `effects(@f) ⊆ effects(caller)` (`E3101`); result rules of §33.1 | takes a task slot (§36.3), creates a runnable task; a scheduling point |
|
||
| `[%r =] task.join %t` | `task<T>` (consumed) → `T` | — | ends the loans of the task (§34) | waits until the task returned, frees its slot; a scheduling point |
|
||
| `task.cancel %t` | `task<T>` (not consumed) | — | — | sets the task's cancellation-request flag; a scheduling point |
|
||
| `%c = task.cancelled` | → `bool` | — | — | whether the current task's flag is set; a scheduling point |
|
||
| `task.scope.end %s` | `scope` (consumed) | — | every task spawned from `%s` must be joined on every path (`E4301`) | closes the scope |
|
||
|
||
**Cancellation is a request only** (spec 04 §15). `task.cancel` does not consume the handle, does not stop the task, does not release its resources and does not return its loans. Only `task.join` consumes the handle and returns the loans, and `task.scope.end` requires every child to be *joined*, not merely cancelled. `task.cancelled` reads the current task's flag; RFC 0012 adds cancellation points to waiting operations.
|
||
|
||
**A trap in any task terminates the whole execution** with that trap record (spec 01 §6). There is no recoverable task failure in format 0: `task.join` never reports a trapped child, so no unwinding or cleanup semantics for the child's resources are needed. Expected failure is a value the task returns.
|
||
|
||
### 33.3 Linearity and structure
|
||
|
||
- `task<T>` handles and scopes follow the linear rules of spec 06 §6 (`E3002` if never consumed). A live task handle at `task.scope.end` of its scope is `E4301` (`task.live_child_escape`), reported in preference to `E3002`.
|
||
- A scope is ended in the function that began it; `ret` with a live scope is `E3002`.
|
||
|
||
## 34. Lending borrows to tasks
|
||
|
||
A borrow argument of `task.spawn` is **lent to the task** from the spawn until the `task.join` that consumes the handle. Its state machine is:
|
||
|
||
```text
|
||
LIVE --spawn--> LOANED(task) --join--> LIVE --borrow.end--> ENDED
|
||
```
|
||
|
||
The state is static: a borrow stays `LOANED` until the `join`, even if the child has already finished at runtime, so the model is independent of the scheduler.
|
||
|
||
While `LOANED`:
|
||
|
||
- for the verifier it behaves as a live child borrow of the argument, owned by the task handle, with the argument's mode and path;
|
||
- ending the argument borrow, or any ancestor of it, while the task is live is `E4302` (`task.borrow_escape`);
|
||
an identified task includes its spawn position (spec 10 §2), retained through cancelled-join handle replacement without participating in loan/liveness checks;
|
||
- an access or a new borrow that conflicts with a loan of a live task is `E4101` (`concurrency.possible_data_race`) rather than `E2101`, since the other party runs concurrently;
|
||
- lending the same exclusive borrow, or overlapping exclusive borrows, to two live tasks is `E4101`; lending disjoint places (different fields, the halves of a `slice.split`, different region allocations) is accepted.
|
||
|
||
Example: two workers square the two halves of one buffer in parallel; both loans end at the joins.
|
||
|
||
## 35. Send and Share in AIR
|
||
|
||
`Send` and `Share` are derived structurally (spec 02 §6), with these base cases in format 0:
|
||
|
||
| Type | Send | Share |
|
||
|---|---|---|
|
||
| integers, `bool`, built-in enums | yes | yes |
|
||
| `cap<K>` (every kind) | yes | yes — the authority object is shared and its host side is synchronized |
|
||
| `file<…>`, `listener`, `stream` | yes | no |
|
||
| `own<T>`, `own_array<T>`, `buffer<T>` | if `T` is | if `T` is |
|
||
| `region` | yes | no — allocation through a shared borrow mutates the region |
|
||
| `ref<T>` | if `T` is `Share` | if `T` is `Share` |
|
||
| `mut<T>` | if `T` is `Send` | no |
|
||
| `slice<T>` / `slice_mut<T>` | as `ref<array>` / `mut<array>` | as `ref` / `mut` |
|
||
| `task<T>`, `scope`, `shield`, `guard<T>` | no (`Local`) | no |
|
||
| `sender<T>`, `receiver<T>` | yes | no |
|
||
| `mutex<T>` | if `T` is | if `T` is `Send` (the lock synchronizes access) |
|
||
| `island<T>` | yes | no — its owner may mutate it; freeze to share |
|
||
| `frozen<T>`, `arc<T>` | yes | yes |
|
||
| `iref<T>` | yes | yes |
|
||
| `atomic<T>` | yes | yes — every access is an atomic operation through `ref` (§23) |
|
||
| struct, enum, array | if every field/payload/element is | if every field/payload/element is |
|
||
|
||
So an aggregate holding capabilities is `Send` and `Share` exactly when its other members are (Q-014).
|
||
|
||
Argument rules at `task.spawn`:
|
||
|
||
```text
|
||
moved T → T: Send otherwise E4001 (concurrency.not_send)
|
||
ref<T> → T: Share otherwise E4002 (concurrency.not_share)
|
||
mut<T> → T: Send otherwise E4001
|
||
```
|
||
|
||
(`slice<T>` and `slice_mut<T>` follow `ref` and `mut`.) Handing a borrow to another task is sending or sharing what it points to.
|
||
|
||
## 36. The deterministic scheduler
|
||
|
||
### 36.1 Model
|
||
|
||
In both profiles of the reference interpreter, tasks are cooperative execution units on one host thread. A task runs until it reaches a **scheduling point** — `task.spawn`, `task.join`, `task.cancel`, `task.cancelled`, a waiting operation or another scheduling point of §37–§40, an atomic memory operation (§42), I/O, or the end of its **quantum** — and then the scheduler chooses the next task to run among the runnable ones.
|
||
|
||
Native backends (Phase 7) may run tasks in parallel. What they must preserve (RFC 0015):
|
||
|
||
1. Every observable behavior of a native run is an outcome of the program under the memory model (§20).
|
||
2. For a safe program whose transitive effects contain no `atomic.weak`, this means the outcome of some interleaving of this scheduler model (§22).
|
||
3. Ordinary accesses may be optimized under the data-race-freedom assumption (§21).
|
||
4. Atomic operations use mappings that are sound for the Aji RC11 profile on the target. In particular, NO-THIN-AIR requires that a relaxed load is not reordered with a later store.
|
||
5. No atomic is emulated with a lock (§23).
|
||
6. The built-in primitives provide at least the `sw_prim` edges (§20.3).
|
||
|
||
Unsafe code is bound by its own obligations (spec 13 §4).
|
||
|
||
The `hosted` profile uses the same cooperative scheduler on one host thread; in format 0 a blocking host I/O call blocks every task until it returns (task-aware I/O is later work).
|
||
|
||
### 36.2 Choice rule (deterministic profile)
|
||
|
||
Runnable tasks are kept in increasing order of creation. At each scheduling point the scheduler draws `x = next()` from the **schedule generator** and resumes runnable task number `x mod n` (the current task counts if it is still runnable).
|
||
|
||
The schedule generator is the generator of spec 11 §8.1, seeded with the **schedule seed**. It is a stream independent of the program's `random.fill` stream (seeded with `--seed`):
|
||
|
||
```text
|
||
--seed N program randomness (random.fill)
|
||
--schedule-seed M scheduler choices; default: seed XOR 0x5343484544554c45 ("SCHEDULE")
|
||
```
|
||
|
||
Varying the schedule seed while keeping `--seed` explores interleavings without changing the program's inputs.
|
||
|
||
### 36.3 Quantum and fuel
|
||
|
||
- One executed AIR instruction is one fuel unit and one quantum step; there is a single definition of "instruction executed".
|
||
- `--quantum N` (default 1 000) bounds the instructions a task executes between scheduling points; reaching it is a scheduling point. The quantum is an execution parameter like fuel, recorded in the run record, never a semantic property.
|
||
- Order at every instruction: the instruction begins → its fuel unit is consumed → it completes or blocks → its effects become visible → if it is a scheduling point (or ends the quantum), the scheduler decides. A blocked instruction consumes its fuel unit once, when it first begins; when its task resumes, it completes without consuming fuel again. While a task waits, its quantum is irrelevant.
|
||
- Fuel counts the instructions of all tasks together (spec 11 §7.2).
|
||
- **Task limit.** The deterministic profile has `max_task_slots`, default 1 024, set with `--task-limit N`. A slot is taken by a successful `task.spawn` and freed by its `task.join`; a finished but unjoined task still holds its slot. A spawn that would exceed the limit ends the run with the environment outcome `{"status":"limit_exceeded","kind":"tasks","limit":N}` (exit code 5, like fuel); it is not a trap.
|
||
- Quiescence (spec 11 §8): if every unfinished task waits and no future event can wake one, the run ends `blocked` — for example a task joining a task that waits on it.
|
||
|
||
### 36.4 Run record
|
||
|
||
The record of a run that spawned tasks or drew among `select` arms adds `"schedule":{"seed":S,"quantum":Q,"choices":C}`, where `S` is the schedule seed and `C` the number of scheduler choices made, including draws among ready `select` arms (§39) and weak-read choices (§42); two runs with equal records made the same choices. No draw is made when there is only one candidate.
|
||
|
||
### 36.5 Schedule exploration
|
||
|
||
The conformance runner gains `schedules: N`: the test runs with schedule seeds `0 … N−1` and an unchanged program seed, and every run must satisfy the expectation. Task choices and `select` choices vary together, from one stream. Systematic exploration (DPOR) is Phase 5 work.
|
||
|
||
## 37. Waiting and cancellation in AIR (feature `cancellation`)
|
||
|
||
Decision record: RFC 0012. Depends on `effects`, `tasks`.
|
||
|
||
Invariants of §37–§41:
|
||
|
||
1. **Explicit outcomes.** Every waiting operation completes on exactly one of its declared edges (`ok`, `closed`, `cancelled`). Cancellation is never a trap.
|
||
2. **Ownership transfer.** A value sent on a channel is owned by the sending operation until it completes. On `ok` it belongs to the channel and then to the receiver; on `closed` or `cancelled` it is handed back as a block parameter. A value is never observable by two tasks.
|
||
3. **No silent drop.** A value leaves a channel only through a receive. A receiver is consumed only when the channel is empty and no further value can enter it.
|
||
4. **No wait under a lock.** While a task holds a `guard<T>`, it executes no operation that may suspend. This is checked statically, including through calls (§41).
|
||
5. **Cooperative cancellation.** Cancellation is observed only at cancellation points (§37.2). An operation that can complete without waiting completes. Inside a shield cancellation is never observed. Shields nest properly.
|
||
6. **Reproducibility.** Task choices, choices among ready `select` arms and weak-read choices (§42) are drawn from the one schedule generator (§36.2).
|
||
7. **No hidden cleanup.** Nothing is unlocked, closed or dropped implicitly. A trap while holding a guard terminates the whole execution (§33.2).
|
||
|
||
### 37.1 The waiting-operation rule
|
||
|
||
The **waiting operations** are `task.join.cancel`, `channel.send`, `channel.recv`, `select` and `mutex.lock`. Each has a ready condition. 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 (§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 (§36.3). A waiting task counts as waiting for global quiescence (spec 11 §8). The plain `task.join` and the I/O intrinsics are not cancellation points in format 0.
|
||
|
||
### 37.2 Cancellation points
|
||
|
||
| Point | Observes cancellation |
|
||
|---|---|
|
||
| `task.check_cancel` | always when observable |
|
||
| `task.join.cancel`, `channel.send`, `channel.recv`, `select`, `mutex.lock` | only when it would otherwise wait (§37.1 step 2) |
|
||
|
||
`task.cancelled` (§33.2) is not a cancellation point: it returns the raw request flag and ignores shields.
|
||
|
||
### 37.3 Instructions
|
||
|
||
| Instruction | Operands → result | Effect | Verifier | Runtime |
|
||
|---|---|---|---|---|
|
||
| `task.check_cancel, ok -> @ok, cancelled -> @c` (terminator) | targets without parameters | — | — | `@c` if cancellation is observable, else `@ok`; a scheduling point |
|
||
| `task.join.cancel %t, ok -> @ok, cancelled -> @c` (terminator) | `task<T>` (consumed on both edges); `@ok(T)`, `@c(task<T>)` | `task.wait` | `ok`: as `task.join`, the task is joined and its loans end. `cancelled`: the same task is the parameter of `@c`; it is not joined and its loans stay `LOANED`, owned by the new handle value | 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 |
|
||
|
||
Loan state machine of `task.join.cancel` (extends §34):
|
||
|
||
```text
|
||
task<T> --task.join.cancel--+-- ok --------> joined; loans end; result T
|
||
+-- cancelled -> same task<T> as a block parameter;
|
||
not joined; loans stay LOANED
|
||
```
|
||
|
||
If the child has already returned, the join completes on `ok` even when cancellation is pending. Cancellation does not propagate to children automatically; a parent forwards it explicitly:
|
||
|
||
```text
|
||
cancelled(%t2: task<u64>):
|
||
task.cancel %t2
|
||
%r = task.join %t2
|
||
```
|
||
|
||
`shield` is linear, function-bound (§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`); every shield is ended before `ret` (`E3002`). Shield depth is dynamic per task, so a function called inside a shield runs shielded.
|
||
|
||
```text
|
||
%a = task.shield.begin
|
||
%b = task.shield.begin
|
||
task.shield.end %a ; E4305
|
||
task.shield.end %b ; ok
|
||
task.shield.end %a ; ok
|
||
```
|
||
|
||
### 37.4 Effect `task.wait`
|
||
|
||
The effect `task.wait` (no capability) states that a function may wait for another task. **In a module declaring `cancellation`**, every operation that may suspend requires it: `task.join`, `task.join.cancel`, `channel.send`, `channel.recv`, `select` and `mutex.lock` (`E3101`, spec 05 §9.3). A module that does not declare `cancellation` keeps the semantics of §33 unchanged; `channels` and `sync` imply `cancellation`.
|
||
|
||
## 38. Channels in AIR (feature `channels`)
|
||
|
||
Decision record: RFC 0012. Depends on `cancellation`, `heap`.
|
||
|
||
### 38.1 Types
|
||
|
||
| Type | Meaning | Class |
|
||
|---|---|---|
|
||
| `sender<T>` | a sending endpoint | linear |
|
||
| `receiver<T>` | the receiving endpoint, exactly one per channel | linear |
|
||
|
||
Endpoints may be block arguments, function parameters and return values, and may be moved into tasks. Aggregate membership and individual own<T> content require `linear_aggregates` (spec 03 §25); bulk heap arrays remain Copy-only. Channels are MPSC: several receivers are the reserved feature `receiver_dup`.
|
||
|
||
**Element rules** for `T` (also used by `mutex<T>`, §40):
|
||
|
||
- `T: Send` (`E4001`);
|
||
- `T` contains no borrow, `scope`, `task<…>`, `shield` or `guard<…>` (`E1001`);
|
||
- `T` contains no `sender<…>` or `receiver<…>`: reserved feature `channel_transfer` (`E0006`).
|
||
|
||
Linear elements (`own<T>`, `file<…>`, `stream`, `island<T>`, `frozen<T>`, `arc<T>`, …) are allowed.
|
||
|
||
### 38.2 Instructions
|
||
|
||
| Instruction | Operands → targets | Effect | Verifier | Runtime |
|
||
|---|---|---|---|---|
|
||
| `channel.make T, %n, %mem, ok -> @ok, err -> @err` (terminator) | `%n: usize`, `%mem: cap<mem.alloc>`; `@ok(sender<T>, receiver<T>)`, `@err(alloc_error)` | `mem.alloc` | element rules | charges `%n × size(T)` bytes (spec 03 §19); capacity 0 is a rendezvous channel; never waits |
|
||
| `%tx2 = channel.sender.dup %txr` | `ref<sender<T>>` → `sender<T>` | — | — | a new, separately linear sender of the same channel; `open_senders += 1` |
|
||
| `channel.send %txb, %v, ok -> @ok, closed -> @closed, cancelled -> @c` (terminator) | `mut<sender<T>>`, `T` (consumed on every edge); `@ok()`, `@closed(T)`, `@c(T)` | `task.wait` | on `closed` and `cancelled` the value comes back as the target's parameter | waiting operation (§38.3) |
|
||
| `channel.recv %rxb, ok -> @ok, closed -> @closed, cancelled -> @c` (terminator) | `mut<receiver<T>>`; `@ok(T)`, `@closed()`, `@c()` | `task.wait` | — | waiting operation (§38.3) |
|
||
| `channel.close_sender %tx` | `sender<T>` (consumed) | — | — | `open_senders -= 1`; a scheduling point |
|
||
| `channel.close_receiver %rx, ok -> @ok, pending -> @pending` (terminator) | `receiver<T>` (consumed on both edges); `@ok()`, `@pending(receiver<T>)` | — | — | §38.4; a scheduling point |
|
||
|
||
### 38.3 States and ready conditions
|
||
|
||
A channel has a FIFO buffer, a count `open_senders` and a receiver state:
|
||
|
||
| State | Meaning |
|
||
|---|---|
|
||
| `OPEN` | receiver open and `open_senders > 0`: sends are accepted |
|
||
| `RECEIVER_CLOSING` | the receiver has started closing: no send is accepted; buffered values remain and MUST be received |
|
||
| `DRAINED` | no future value can arrive (`open_senders = 0`, or `RECEIVER_CLOSING`) and the buffer is empty |
|
||
| `CLOSED` | the receiver has been consumed |
|
||
|
||
New values stop arriving in exactly two ways: the last sender closes, or the receiver starts closing. In both cases buffered values are received, never destroyed.
|
||
|
||
| Operation | `ok`-ready | `closed`-ready |
|
||
|---|---|---|
|
||
| send, capacity `n > 0` | `OPEN` and fewer than `n` values buffered | `RECEIVER_CLOSING` or `CLOSED` |
|
||
| send, capacity 0 | `OPEN` and the receiver waits in `channel.recv` or in a `select` with a receive arm on this channel | `RECEIVER_CLOSING` or `CLOSED` |
|
||
| recv, capacity `n > 0` | a value is buffered | `DRAINED` |
|
||
| recv, capacity 0 | `OPEN` and a sender waits in `channel.send` or in a `select` with a send arm on this channel | `DRAINED` |
|
||
|
||
A waiting rendezvous sender holds its value until a receiver takes it; waiting rendezvous senders are matched in the order they began to wait. When an operation completes against a waiting `select`, that `select` resumes on the matched arm without a draw. A successful send synchronizes with the receive that obtains the value (§12).
|
||
|
||
### 38.4 Closing the receiver
|
||
|
||
- If the buffer is empty, the receiver is consumed, the channel becomes `CLOSED` (waiting and future sends end `closed`) and control continues at `@ok`.
|
||
- Otherwise the channel becomes `RECEIVER_CLOSING` (sends end `closed`, including waiting rendezvous senders) and the receiver comes back on `@pending`. The program receives until `closed` and closes again.
|
||
|
||
The drain terminates because no value can enter. The channel's memory returns to the `mem.alloc` budget at the close that leaves the channel `CLOSED` with `open_senders = 0`.
|
||
|
||
## 39. `select` in AIR (feature `channels`)
|
||
|
||
Decision record: RFC 0012. Resolves Q-013.
|
||
|
||
```text
|
||
select [recv %rxb, ok -> @a, closed -> @a_done], [send %txb, %v, ok -> @sent, closed -> @gone], cancelled -> @c
|
||
```
|
||
|
||
- **Arms** are channel operations only: `[recv %rxb, ok -> @x, closed -> @y]` and `[send %txb, %v, ok -> @x, closed -> @y]`. A `select` has at least one arm and exactly one `cancelled` target. It requires `task.wait`.
|
||
- **Readiness.** An arm is ready when its operation is `ok`-ready or `closed`-ready (§38.3). The `select` is a waiting operation (§37.1) that is ready when at least one arm is.
|
||
- **Choice.** One ready arm is taken. With `k ≥ 2` ready arms the scheduler draws `x = next()` from the schedule generator (§36.2) and takes ready arm `x mod k` in textual order. The draw is a scheduler choice; textual order alone never decides.
|
||
- **Ownership along edges.** Let `V` be the distinct values named by send arms, in order of first appearance. The `select` consumes every value of `V` on every edge. Each target receives, after its own parameters (the received `T` on a receive arm's `ok`), the values of `V` not sent on that edge, in the order of `V`:
|
||
|
||
```text
|
||
select [send %tx1, %x, ok -> @to1, closed -> @c1], [send %tx2, %x, ok -> @to2, closed -> @c2], cancelled -> @c
|
||
; @to1() @to2() %x was sent
|
||
; @c1(%x) @c2(%x) @c(%x) %x comes back
|
||
```
|
||
|
||
A plain `channel.send` is the one-arm case. Arms may name the same endpoint borrow more than once.
|
||
|
||
## 40. Mutex in AIR (feature `sync`)
|
||
|
||
Decision record: RFC 0012. Depends on `cancellation`. `RwLock` is deferred (reserved feature `rwlock`).
|
||
|
||
| Type | Meaning | Class |
|
||
|---|---|---|
|
||
| `mutex<T>` | mutual exclusion around a `T` (element rules of §38.1) | linear: consumed by `mutex.take` |
|
||
| `guard<T>` | the current task holds the lock | linear, function-bound, `Local` |
|
||
|
||
`mutex<T>` is opaque: no `borrow.field`, `load` or `store` reaches its contents; it is the verifier-known interior-mutability abstraction of §8. It is a linear SSA value like a resource (format 0 has no droppable move-only class): `borrow.ref %m` gives the `ref<mutex<T>>` that tasks share through a loan (§34), and `mutex.take` consumes it once no borrow is live. `guard<T>` as a parameter, return type or aggregate member is the reserved feature `guard_transfer` (`E0006`).
|
||
|
||
| Instruction | Operands → result | Effect | Verifier | Runtime |
|
||
|---|---|---|---|---|
|
||
| `%m = mutex.make %v` | `T` (consumed) → `mutex<T>` | — | element rules | unlocked; no allocation |
|
||
| `%v = mutex.take %m` | `mutex<T>` (consumed) → `T` | — | no live borrow of `%m` (`E2101`; `E4101` if lent to a live task) | returns the contents; no unlock, no destructor |
|
||
| `mutex.lock %mr, ok -> @ok, cancelled -> @c` (terminator) | `ref<mutex<T>>`; `@ok(guard<T>)`, `@c()` | `task.wait` | the guard is a child of `%mr` (ending `%mr` while it is live is `E2102`); §41 | waiting operation; ready when unlocked; acquire |
|
||
| `%p = mutex.borrow %g` | `guard<T>` (not consumed) → `mut<T>` | — | child borrow of `%g`, ended before `mutex.unlock %g` (`E2102`) | — |
|
||
| `mutex.unlock %g` | `guard<T>` (consumed) | — | — | release; all tasks waiting on this mutex become runnable and the first scheduled takes it; a scheduling point |
|
||
|
||
No fairness is promised (§32). There is no poisoning and no implicit unlock; an unconsumed guard is `E3002`.
|
||
|
||
`mutex<T>` is always linear and never copyable, whatever `T` is; `mutex.take` is the only way to dismantle it. It requires that no borrow of the mutex is live. A guard is a child of the `ref<mutex<T>>` it was locked through (ending that borrow while the guard lives is `E2102`), and a task waiting in `mutex.lock` holds such a borrow, so no guard and no waiter can exist at `mutex.take`. Afterwards the mutex is dead, by the ordinary rules for a dismantled linear value (as after `own.take`): a further use is `E3001` and a further consumption `E2002`.
|
||
|
||
## 41. The critical-section rule
|
||
|
||
On every path where a `guard<T>` is live, a function MUST NOT execute an instruction that requires the effect `task.wait` or `task.spawn`, nor call a function whose declared effects include `task.wait` or `task.spawn` (`E4304`, `sync.wait_while_locked`, naming the guard and the instruction).
|
||
|
||
Consequences:
|
||
|
||
- a task holds at most one guard: `mutex.lock` requires `task.wait`, so `lock A; lock B` is `E4304` and lock-order deadlock cannot be expressed in safe AIR 0;
|
||
- a lock holder never waits for another task, so mutexes alone cannot deadlock;
|
||
- a critical section may call functions without those effects and pass them the `mut<T>` from `mutex.borrow`.
|
||
|
||
The check uses only the guard state and the callees' declared effects, so it stays intraprocedural (§33 invariant 6).
|
||
|
||
## 42. Atomics in AIR (feature `atomics`)
|
||
|
||
Model and rules: §20–§30. Notation in this section:
|
||
|
||
- `T` is AtomicScalar.
|
||
- `P` is `ref<atomic<T>>`.
|
||
- `<o>` is an ordering allowed by §24 for the operation.
|
||
|
||
| Instruction | Operands → result | Effects | Verifier | Runtime |
|
||
|---|---|---|---|---|
|
||
| `%a = atomic.new %v` | `T` → `atomic<T>` (linear) | — | `T` AtomicScalar (`E1001`) | creates a cell with its initializing write |
|
||
| `%v = atomic.take %a` | `atomic<T>` (consumed) → `T` | — | no live borrow of `%a` (`E2101`; `E4101` if lent to a live task) | ordinary read of the final value; frees the cell |
|
||
| `%v = atomic.load.<o> %p` | `P` → `T` | `atomic`; `atomic.weak` unless `seq_cst` | `E4201` | atomic read; scheduling point |
|
||
| `atomic.store.<o> %p, %v` | `P`, `T` | as `load` | `E4201` | atomic write; scheduling point |
|
||
| `%old = atomic.<rmw>.<o> %p, %v` | `P`, `T` → `T` | as `load` | `E4201`; `add.wrap`/`sub.wrap` on integers only (`E1001`) | atomic read-modify-write (§24.2); returns the value read; scheduling point |
|
||
| `%old, %ok = atomic.cmpxchg.<s>.<f> %p, %exp, %new` | `P`, `T`, `T` → `T`, `bool` | `atomic`; `atomic.weak` unless both orderings are `seq_cst` | `E4201` for `<s>`, and for `<f>` against §24.1 | strong compare-exchange: if the value read equals `%exp`, writes `%new` with `<s>` and `%ok` is `true`; otherwise it is a read with `<f>` and `%ok` is `false`; scheduling point |
|
||
| `atomic.fence.<o>` | — | `atomic` | `E4201` | fence; scheduling point |
|
||
|
||
`<rmw>` is one of `xchg`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`.
|
||
|
||
Common properties:
|
||
|
||
- **Ownership.** Only `atomic.take` consumes. A borrow operand is used, not ended. Borrow states do not change, and results are fresh plain values.
|
||
- **Memory.** One event of §20.1 on the cell `%p` points to. Nothing else.
|
||
- **Traps.** None.
|
||
- **Ordinary access** through `P`: `load %p` is `E4202` (`atomic.ordinary_access`).
|
||
|
||
**Deterministic interpreter.**
|
||
|
||
- *Soundness, every program.* Every outcome it produces is allowed: `observed ⊆ allowed` (§20.5).
|
||
- *Exact coverage, normative litmus corpus only.* For every test of `reference/concurrency-litmus.md`, the outcomes observed under exhaustive exploration equal the oracle's allowed set: `observed_exhaustive = allowed` (§20.5).
|
||
- *Weak reads.* A read whose ordering is not `seq_cst` may read any write the model allows. The choice is a draw from the schedule generator (§36.2) and counts in `schedule.choices`.
|
||
- *No weak access.* A run with no non-`seq_cst` access makes no extra draw, and every read reads the latest write.
|