# RFC 0015: Scalar Atomics and the Aji Memory Model (Phase 5) Status: Accepted (revision 2 with the owner's editorial corrections). U1–U4 accepted. Revised: - the model is named the Aji RC11 profile, stronger than ISO C11/C++20; NO-THIN-AIR is the axiom and the forbidden load-buffering outcome is its consequence; - the effect rule is written literally; - `atomic` is linear, with `atomic.take`; - every operation takes `ref>`; - `cmpxchg` has a failure-ordering table and two results; - target support is normative; - the enumerator is an oracle, not the definition: `observed ⊆ allowed` for every program, `observed_exhaustive = allowed` only for the finite normative litmus corpus. Scope: AIR format 0 extension (feature `atomics`); `.aji` 0.1 layer 10; the memory model of spec 04 §20–§31 Language version: 0.1 Supersedes: RFC 0003 (Proposed, never accepted). Its intent is kept; its open points are decided here. Builds on: RFC 0006 (flat effects), RFC 0011 (tasks, scheduler), RFC 0012 (channels, mutex), RFC 0013 (source language), RFC 0014 (graph owners as the model for linear containers) Integrated into: - spec 02 §6; - spec 04 §20–§31, §35, §36, §42; - spec 05 §13; - spec 07 §8; - spec 07a (feature `atomics`); - spec 09 §9; - spec 11 §4, §8; - spec 13 §4; - spec 15 §12; - `reference/air-text.ebnf`, `air-features.md`, `error-codes.md` (`E4202`, `E4203`), `type-properties.md`, `concurrency-litmus.md`. ## Summary Phase 5 adds one linear type, `atomic` for scalar `T`, and the operations on it: new, take, load, store, read-modify-write, compare-exchange and fence. Every memory operation names its ordering. Phase 5 also makes the memory model normative and executable. Safe Aji then has three layers: ```text ordinary safe memory → DRF-SC: the verifier excludes data races; every execution is explainable by an interleaving atomic memory → the Aji 0.1 atomic model: the Aji RC11 profile (spec 04 §20) unsafe code → its own proof obligations (spec 13); format 0 has no unsafe atomic operation ``` The sentence "a native execution equals some interleaving" (spec 04 §36.1) stays true exactly for programs whose effects contain no `atomic.weak`. For other programs the model replaces it. Out of scope, each for a later RFC: - atomic pointers, references or `iref`s; - reclamation (hazard pointers, epochs, RCU); - lock-free collections; - weak (spuriously failing) compare-exchange; - `atomic` inside graphs, aggregates or `arc` (U4); - record/replay files (U3, Q-017). ## Motivation The concurrency preference order (AGENTS.md) ends in atomics before unsafe raw concurrency. Phases 3 and 4 cover the levels above it: ownership transfer, shared immutable graphs and mutexes. What the language cannot express today without a mutex: - counters, flags and statistics updated by many tasks; - one-time publication (a ready flag); - the building blocks of later lock-free libraries. Each of these is a lock around one word or unsafe code. Both are worse for verification than an explicit atomic with a named ordering. The memory model is the larger part of this RFC. Spec 04 §20–§31 names the relations but does not define them, so neither a correct result nor a conforming interpreter is defined. This RFC makes the model precise, decides which weak behaviors exist, and fixes what the deterministic interpreter and a native backend must do. Phase 5 is the first phase where the verifier cannot reduce concurrent behavior to ownership plus a scheduler interleaving. The model therefore comes before the code. ## Invariants 1. **No default ordering.** Every atomic memory operation names its orderings in the opcode. Each operation has a fixed set of valid orderings; any other is `E4201`. 2. **Atomic cells are reached only atomically while shared.** An `atomic` is linear. Through a borrow it is reachable only by atomic instructions: an ordinary `load` through `ref>` is `E4202`. The contents leave a cell only through `atomic.take`. That consumes the owner and needs the absence of every borrow (existing borrow and loan rules), so it is happens-before ordered with every atomic access. 3. **DRF for ordinary memory.** A verified safe program has no data race on ordinary memory. This holds by the ownership, borrow and loan rules together with invariant 2. The interpreter's race detector (P5-6) checks it dynamically. 4. **SC without `atomic.weak`.** If the transitive effects of a safe program contain no `atomic.weak`, every execution is sequentially consistent: its observable behavior is that of an interleaving of the deterministic scheduler. 5. **Weak behavior is visible.** A `seq_cst` operation requires `effects [atomic]`; a non-`seq_cst` operation requires `effects [atomic, atomic.weak]`. Effects are flat, so both are declared by every caller up to `@main`, and `aji report` lists every weak site. 6. **Executable model.** The axioms are normative. An independent enumerator is an executable oracle derived from them, not the definition, and enumerates exactly the executions the model allows. The interpreter never produces a forbidden outcome (`observed ⊆ allowed`). For the finite normative litmus corpus, exhaustive exploration produces every allowed outcome (`observed_exhaustive = allowed`). 7. **Determinism.** For fixed program, inputs, `--seed`, `--schedule-seed` and `--quantum`, the run record is identical. Weak-memory choices are drawn from the schedule stream. 8. **No hidden locks.** An `atomic` exists on a target only if the target implements it natively and lock-free. Otherwise the module is rejected for that target. ## Decisions (revision 2) ### D1. Atomic types: linear `atomic` for scalar `T` (revised) `atomic` is defined for `T ∈ {bool, u8, u16, u32, u64, usize, i8, i16, i32, i64, isize}`, the **AtomicScalar** types. Any other `T` is `E1001`, including 128-bit integers, aggregates and handles. `atomic` is **linear**, `Send` and `Share`, and not copyable. Revision 1 made it a plain value. Then `let b = a;` would be ambiguous: does it copy the current value or the synchronization cell? As a linear value it is a cell with one owner, like the graph owners of spec 03 §22–§24 and like `mutex`. - **Where it may appear.** Like graph owners: SSA values, parameters, returns, block arguments, channel elements and mutex contents. - **Where it may not appear.** Struct fields, enum payloads, array elements, and the contents of `local`, `own` or regions. Those need `linear_aggregates`, which stays reserved. An array of atomic counters is therefore deferred with that feature. - It is not `IslandSafe` (`E2111`), so it is excluded from graphs and `arc` (U4). - Size and alignment equal those of `T`. ### D2. Creating, using and taking | Operation | Rule | |---|---| | `%a = atomic.new %v` | `T` → `atomic`; no effect, since no concurrent operation has happened yet | | `%r = borrow.ref %a` | the container borrow, as for graph owners; `ref>` is what every operation takes and what tasks receive | | `%v = atomic.take %a` | consumes `atomic`, gives `T`; no effect; any live borrow is `E2101`, or `E4101` if lent to a live task; this continues the `mutex.take` pattern | A linear atomic that is never taken, moved or returned is a leak (`E3002`). ### D3. Every operation takes `ref>` (revised) Load, store, the RMWs, `cmpxchg` and nothing else touch the cell, and all of them take `ref>`. That is atomic interior mutability: several tasks hold shared borrows of one cell and change it through them. `mut>` is not an operand (`E1001`), so there is one canonical form. An ordinary `load` through `ref>` is `E4202`. Ordinary `store` needs `mut`, which no operation produces. ### D4. Orderings per operation (revised for `cmpxchg`) | Operation | Allowed orderings | |---|---| | `atomic.load` | `relaxed`, `acquire`, `seq_cst` | | `atomic.store` | `relaxed`, `release`, `seq_cst` | | RMW (`xchg`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`) | `relaxed`, `acquire`, `release`, `acq_rel`, `seq_cst` | | `atomic.fence` | `acquire`, `release`, `acq_rel`, `seq_cst` (no relaxed fence) | `atomic.cmpxchg` failure orderings by success ordering: | Success | Allowed failure | |---|---| | `relaxed` | `relaxed` | | `acquire` | `relaxed`, `acquire` | | `release` | `relaxed` | | `acq_rel` | `relaxed`, `acquire` | | `seq_cst` | `relaxed`, `acquire`, `seq_cst` | A failed CAS is a load, so its ordering never has a release part, and it is never stronger than the success ordering. This is smaller than C++17, which allows a failure ordering stronger than the success ordering. The extra cases add backend fence combinations and almost no value. There is no `consume`. Arithmetic RMWs are modular and say so in the name, as ordinary arithmetic does. There is no checked atomic arithmetic: a trap after the write is visible would leave the location changed. Use a `cmpxchg` loop instead. `add.wrap` and `sub.wrap` are defined for integers; `xchg`, `and`, `or` and `xor` for integers and `bool`. ### D5. Strong compare-exchange with two results (revised) ```text %old, %exchanged = atomic.cmpxchg.. %p, %expected, %desired ``` The results are `%old: T` (the value read) and `%exchanged: bool`. It succeeds exactly when `%old == %expected` (bitwise). Then it has written `%desired` with ordering `succ`; otherwise it was a load with ordering `fail`. - Two results, so agents do not recompute success. Format 0 already has two-result instructions (`slice.split`). - In source: `let (old, exchanged) = atomic.compare_exchange(ref a, expected, desired, acq_rel, acquire);`. - There is no spurious failure. A weak CAS is deferred. ### D6. `atomic.weak` marks every ordering other than `seq_cst` (U2 accepted) Effects stay flat (RFC 0006). The 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 ``` - A `cmpxchg` is non-`seq_cst` if either ordering is. - `atomic.weak` never stands alone. - With only `seq_cst` accesses a fence cannot add a weak outcome, so fences need only `atomic`. This rule supersedes spec 04 §25, which marked relaxed operations only. Release/acquire already gives non-interleaving outcomes: SB with release stores and acquire loads gives `r1 = r2 = 0`, and with IRIW the readers disagree on the order of independent writes. Hence the invariant: ```text atomic.weak ∉ transitive effects ⇒ all atomic accesses are seq_cst ⇒ every safe execution is explainable as an SC interleaving ``` ### D7. The model: the Aji RC11 profile (U1 accepted, renamed) The normative model is **the Aji 0.1 atomic model, the Aji RC11 profile**: the consistency axioms of RC11 (Lahav, Vafeiadis, Kang, Hur, Dreyer, PLDI 2017), restricted to the operations Aji has. - **NO-THIN-AIR is included.** RC11 already contains it (`sb ∪ rf` acyclic). The profile is therefore stronger than ISO C11/C++20, which leave out-of-thin-air values informally excluded and allow load buffering. It is not a strengthening of RC11 itself. - **The model is defined by its relations and axioms.** The litmus outcomes are consequences of the model, not its definition. One consequence of NO-THIN-AIR is that the cyclic load-buffering outcome is forbidden. Spec 04 §20 receives: - **Events:** - atomic reads `R`, writes `W` and read-modify-writes `U`, which are both; - fences `F`; - ordinary accesses; - the synchronization events of built-in primitives. Storing the value of `atomic.new` into the cell is the initializing write, first in modification order. - **Relations:** - `sb`: sequenced-before, the program order of a task; - `rf`: every read reads exactly one write to its location, with that write's value; - `mo`: a strict total order of the writes to each location; - `rmw`: links a `U`'s read part to its write part. ```text fr = rf⁻¹ ; mo eco = (rf ∪ mo ∪ fr)⁺ rs = [W] ; (rf ; rmw)* (release sequence, C++20) sw = [E ⊒ rel] ; ([F] ; sb)? ; rs ; rf ; [R] ; (sb ; [F])? ; [E ⊒ acq] ∪ sw_prim hb = (sb ∪ sw)⁺ ``` `E ⊒ rel` means a write, RMW or fence with ordering `release`, `acq_rel` or `seq_cst`, and dually for `acq`. - **Primitive synchronization (`sw_prim`):** each built-in primitive has a total order of its operations consistent with `hb` (lock semantics, as C++ mutexes, outside the `seq_cst` order). Its edges: - `task.spawn` → the child's first event; - the child's last event → its `task.join`; - a successful `channel.send` → the `channel.recv` that takes that message; - `channel.close_sender` → the `closed` outcome it causes; - `mutex.unlock` → the next `mutex.lock` of that mutex; - `task.cancel` → the `cancelled` outcome it causes. - **Consistency.** An execution is consistent iff: 1. *Coherence:* `hb ; eco?` is irreflexive. 2. *Atomicity:* `rmw ∩ (fr ; mo) = ∅`. 3. *SC:* `psc` (RC11, built from `scb` over `seq_cst` accesses and fences) is acyclic. 4. *No-thin-air:* `sb ∪ rf` is acyclic. Consequence: the cyclic load-buffering outcome is forbidden. - **Data race:** two conflicting accesses (same location, at least one a write), at least one of them ordinary, not ordered by `hb`. A verified safe program has none (invariant 3). In unsafe code a race is Undefined Aji Behavior. - **Outcome:** the observable behavior of a consistent execution. That is the run record without scheduler bookkeeping: result or trap, captured output, written files. **DRF-SC (spec 04 §22).** By the RC11 theorem for programs whose atomics are all `seq_cst`, together with lock semantics for the primitives: > A verified safe program whose transitive effects contain no `atomic.weak` has only sequentially consistent executions. With `atomic.weak`, ordinary memory is still race-free: an ordinary read sees the unique `hb`-latest write. Only atomic cells show weak behavior. **Cost.** On AArch64, POWER and RISC-V a relaxed load must not be reordered with a later store. P7 implements this with a fake control dependency or `ldar`; on x86-64 it is free. A weaker model for performance would be a separate feature, never a weakening of published semantics. ### D8. Mixing atomic and ordinary access - **Safe code.** - Ordinary access to a cell is only `atomic.new` (initialization) and `atomic.take` (final read under exclusive ownership). Both are ordered by `hb` with every atomic access to the cell. - `load` through `ref>` is `E4202`. - **Unsafe code.** Format 0 has no unsafe operation on atomic cells. A later RFC that adds one makes mixing an obligation of its unsafe boundary (spec 13 §4). A race there is Undefined Aji Behavior. ### D9. Atomic pointers and reclamation stay outside safe Aji `atomic` is restricted to scalars: `atomic>`, `atomic>`, `atomic>` and `atomic>` are `E1001`. An index into owned storage held in an `atomic` is the safe substitute, and its bounds are checked as usual. Lock-free pointer structures, hazard pointers, epochs and RCU are a later RFC. It must define the unsafe boundary and the reclamation obligation. ### D10. The interpreter and the enumerator (resolves Q-015; revised wording) - **Normative axioms** (D7) define the model. - **The axiomatic oracle** (P5-1a) is an **executable oracle derived from the axioms, not the definition**. For a small program it enumerates exactly the executions the model allows. - **When they disagree.** A disagreement between the oracle, the interpreter and a hand-derived expected set is first treated as a bug in the oracle or the interpreter. The model changes only through a new RFC, never to match a tool. - **Interpreter exploration, two separate obligations:** ```text general programs: observed ⊆ allowed normative litmus corpus: observed_exhaustive = allowed ``` - The first is soundness. It is checked by the corpus, by a differential test (small random programs, with the interpreter's outcomes a subset of the oracle's) and by the race detector (P5-6) in all conformance tests. - The second holds for the finite normative corpus only. It is much stronger than "no forbidden outcome was seen". - An operational interpreter is not required to be able to produce every allowed execution of an arbitrary program. A declarative weak-memory model and online execution are different things. - **Determinism.** Each weak choice is a draw from the schedule generator (spec 04 §36.2) and counts in `schedule.choices`. A program with no non-`seq_cst` access makes no extra draw. - **Scheduling points.** Every atomic memory operation is a scheduling point. Implementation design (not normative): a timestamped message machine. - Each atomic cell keeps its writes in modification order, each with a release view. - Each task keeps a view. - A non-`seq_cst` read chooses among the messages its view allows. - `seq_cst` accesses and fences also use a global SC view. - With no weak access, every read takes the latest message, so the machine is the existing interleaving interpreter. ### D11. What a native backend must preserve (P7) 1. Every observable behavior of a native run is the outcome of some consistent execution (D7). 2. Ordinary accesses may be optimized under the DRF assumption. 3. Atomic operations use mappings sound for the Aji RC11 profile on the target. NO-THIN-AIR requires that a relaxed load is not reordered with a later store. 4. No atomic is emulated with a lock (invariant 8). 5. Built-in primitives provide at least the `sw_prim` edges. Spec 04 §36.1 changes accordingly. ### D12. Target support is normative (new) - The target description (spec 09 §9) lists the AtomicScalar widths the target implements natively and lock-free. - A module that uses `atomic` for an unlisted width is rejected for that target at build time with `E4203` (`atomic.unsupported_width`). It is never lowered to a lock, because that would change the progress and blocking properties an agent or auditor reads from the program. - The deterministic and hosted profiles of the reference interpreter support every AtomicScalar width. - Every 64-bit target in the platform table supports all eleven types. ### D13. Record and replay leave Phase 5 (U3 accepted) In the deterministic profile, seeds and quantum already reproduce a run, including weak choices (invariant 7). A replay file for hosted or native runs would have to record more: - reads-from choices; - modification orders; - the SC order; - weak choices. That is separate work. P5-8 and Q-017 move to Phase 8. ### D14. Feature `atomics` - Depends on `effects` and `ownership`. Atomics are useful without tasks, and lending a cell to a task needs `tasks`, like any loan. - Type: `atomic`. - Instructions: `atomic.new`, `atomic.take`, `atomic.load.*`, `atomic.store.*`, the RMW family, `atomic.cmpxchg.*.*`, `atomic.fence.*`. - Codes: `E4201`, `E4202`, `E4203`. - Effects: `atomic` and `atomic.weak`, already registered. - The feature stays `reserved` until the implementation publishes it (P5-2a). ## Instructions (AIR) Notation: - `` is an ordering valid for the operation (D4). - `T` is AtomicScalar. - `P` is `ref>`. | Instruction | Operands → result | Effects | Verifier | Runtime | |---|---|---|---|---| | `%a = atomic.new %v` | `T` → `atomic` (linear) | — | `T` AtomicScalar (`E1001`) | creates the cell with its initializing write | | `%v = atomic.take %a` | `atomic` (consumed) → `T` | — | no live borrow (`E2101`; `E4101` if lent) | reads the cell's final value; frees nothing else | | `%v = atomic.load. %p` | `P` → `T` | `atomic`; `atomic.weak` unless `seq_cst` | `E4201` | atomic read; scheduling point | | `atomic.store. %p, %v` | `P`, `T` | as load | `E4201` | atomic write; scheduling point | | `%old = atomic.. %p, %v` | `P`, `T` → `T` | as load | `E4201`; `add.wrap`/`sub.wrap` on integers only (`E1001`) | atomic RMW; returns the value read | | `%old, %ok = atomic.cmpxchg.. %p, %exp, %new` | `P`, `T`, `T` → `T`, `bool` | `atomic`; `atomic.weak` unless both are `seq_cst` | `E4201` for `s`, and for `f` against the D4 table | strong CAS (D5) | | `atomic.fence.` | — | `atomic` | `E4201` | fence event; scheduling point | `` 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. - **Memory:** one event on the cell `%p` points to (D7). - **Traps:** none. - **Transfer function:** borrow states are unchanged; results are fresh plain values. - **Not syntax sugar:** each instruction is a memory event with its own ordering. No combination of ordinary instructions or mutex operations gives the same outcome sets on the litmus corpus. ## Verifier rules - **Types.** `atomic` is well formed only for AtomicScalar `T` (`E1001`). It is linear, `Send`, `Share` and not `IslandSafe` (`E2111`). As an aggregate member or as the contents of `local`, `own` or a region it needs `linear_aggregates` (`E0006`). - **Orderings.** The D4 tables give `E4201`, with fields `operation`, `ordering` and `allowed`. For `cmpxchg` the `allowed` field holds the failure set for the given success ordering. - **Ordinary access.** `E4202` on `load` through `ref>`, with `found` and `use: "atomic.load"`. - **Effects.** D6; a missing atom is `E3101`, unchanged. - **Borrows and loans.** Unchanged. `ref>` can be lent to any number of tasks. `atomic.take` while a borrow is live or lent is `E2101` or `E4101`. - **Target.** `E4203` is a build-time target check (P7). The verifier and the interpreter never emit it. ## Runtime rules (interpreter) - The cell holds its message history (D10). Without weak accesses the history is never consulted beyond its last message. - The budget charge of `atomic` equals that of `T` when stored in a channel or mutex. - The run record changes only in `schedule.choices`, which also counts weak choices. - `aji report` lists atomic sites, weak ones marked. ## Valid example (`.aji`) ```aji module demo.atomics fn bump(c: ref>, n: u64) -> u8 effects [atomic, atomic.weak] { var i: u64 = 0; while i < n { let prev = atomic.add.wrap(c, 1u64, relaxed); i = i + 1; } 0u8 } fn publish(data: ref>, ready: ref>) -> u8 effects [atomic, atomic.weak] { atomic.store(data, 42u64, relaxed); atomic.store(ready, true, release); 0u8 } fn main() -> u64 effects [atomic, atomic.weak, task.spawn, task.wait] { let count = atomic.new(0u64); let data = atomic.new(0u64); let ready = atomic.new(false); var seen: u64 = 0; { ref c = count; ref d = data; ref r = ready; scope s { let a = task.spawn(s, bump, c, 1000u64); let b = task.spawn(s, bump, c, 1000u64); let p = task.spawn(s, publish, d, r); if atomic.load(r, acquire) { seen = atomic.load(d, relaxed); // 42 whenever ready was observed } let ra = task.join(move a); let rb = task.join(move b); let rp = task.join(move p); } } let total = atomic.take(move count); // 2000 on every schedule let unused = atomic.take(move data); let flag = atomic.take(move ready); total + seen } ``` The result is 2000 or 2042. A counter that uses only `seq_cst` declares only `effects [atomic]`. ## Rejected examples | Program | Code | |---|---| | `atomic.load(r, release)` | `E4201` (allowed: `relaxed`, `acquire`, `seq_cst`) | | `atomic.compare_exchange(r, 0u64, 1u64, relaxed, acquire)` | `E4201` (failure stronger than success; allowed: `relaxed`) | | `let v = *r;` with `r: ref>` | `E4202` (use `atomic.load`) | | `let b = a;` then a use of `a` | `E2001` (linear) | | `let a = atomic.new(0u64);` never taken | `E3002` | | `atomic.take(move count)` while `ref c = count;` is lent to a live task | `E4101` | | `atomic.add.wrap(c, 1u64, relaxed)` in a function with `effects [atomic]` | `E3101` (missing `atomic.weak`) | | `atomic.new(1u128)`, `atomic>` | `E1001` | | a struct field of type `atomic` | `E0006` (`linear_aggregates`) | | `island.create(atomic.new(0u64), heap)` | `E2111` | ## Litmus corpus (P5-1a) The table is the hand-derived expected core of the corpus. P5-1a confirms each set with the enumerator, applying the D10 rule: no expected set is edited to match a tool without a diagnosis. | Test | Shape | Allowed | Forbidden | |---|---|---|---| | MP rel/acq | `x=1 rlx; y=1 rel` ‖ `r0=y acq; r1=x rlx` | (0,0) (0,1) (1,1) | (1,0) | | MP rlx | all relaxed | all four | — | | MP fences | `x=1; fence rel; y=1` ‖ `r0=y; fence acq; r1=x` (rlx accesses) | (0,0) (0,1) (1,1) | (1,0) | | SB rlx, SB rel/acq | `x=1; r0=y` ‖ `y=1; r1=x` | all four, including (0,0) | — | | SB seq_cst | all `seq_cst` | (0,1) (1,0) (1,1) | (0,0) | | SB fences | rlx accesses with `fence seq_cst` between, both sides | (0,1) (1,0) (1,1) | (0,0) | | LB rlx | `r0=x; y=1` ‖ `r1=y; x=1` | (0,0) (0,1) (1,0) | (1,1) (a consequence of NO-THIN-AIR) | | IRIW acq | writers `x=1`, `y=1`; readers `x;y` and `y;x`, acquire | includes (1,0,1,0) | — | | IRIW seq_cst | all `seq_cst` | every other tuple | (1,0,1,0) | | CoRR | `x=1` ‖ `r0=x; r1=x` (rlx) | (0,0) (0,1) (1,1) | (1,0) | | CoWW | `x=1; x=2` (rlx), final `x` | 2 | 1 | | relaxed counter | 2 tasks × 2 `add.wrap rlx` | final 4 | 2, 3 | | CAS mutual exclusion | `cas(x,0→1)` ‖ `cas(x,0→2)` (rlx) | (0,1) (2,0) | (0,0) | | CAS failure acquire | `d=1 rlx; f=1 rel` ‖ `r0=cas.acq.acq(f,0→5); r1=d rlx` | (0,·) (1,1) | (1,0) | | CAS failure relaxed | same with `cas.acq.rlx` | (1,0) too | — | | release sequence | `d=1; f=1 rel` ‖ `add.wrap(f,2) rlx` ‖ `r0=f acq; r1=d` | (0,0) (0,1) (1,1) (2,0) (2,1) (3,1) | (1,0) (3,0) | | channel handoff | `x=1 rlx; send` ‖ `recv; r=x rlx` | 1 | 0 | | mutex handoff | `lock; x=1 rlx; unlock` ‖ `lock; r=x rlx; unlock` (that lock order) | 1 | 0 | | spawn/join | parent `x=1 rlx`, then spawn; the child reads `x` (rlx), then writes `x=2` (rlx); the parent reads `x` (rlx) after the join | child 1; parent 2 | child 0; parent 1 | | non-atomic race | two tasks `store` the same ordinary `u64` | rejected (`E4101`) | — | | mixing | ordinary `load` through `ref>` | rejected (`E4202`) | — | Notation: - A tuple lists the reading registers in order. - In IRIW the tuple is reader 1's `(x, y)` followed by reader 2's `(y, x)`. - In CAS failure acquire, `r0=0` means the CAS succeeded, and then either `r1` is allowed. ## Diagnostics impact - `E4201` `atomic.invalid_order`: registered, now used. - New `E4202` `atomic.ordinary_access`: "Atomic cell accessed by an ordinary load". - New `E4203` `atomic.unsupported_width`: "Atomic width not implemented lock-free by the target". Emitted only by the build-time target check. - Unchanged codes with new uses: `E1001`, `E0006`, `E2001`, `E2101`, `E2111`, `E3002`, `E3101`, `E4101`. - No new trap. ## Spec integration As listed in the header. Three things wait for the implementation (vertical rule), so agents never read about features `aji features` does not report: - the formal axioms go into spec 04 §20 but not into the agent bundles; - the bundles get the orderings tables, the `atomic.weak` rule, "without `atomic.weak`, interleavings" and the MP and counter idioms; - the Quick Reference subsection. ## Compatibility - No published module changes: `atomics` was reserved. - AIR format 0 is extended as spec 07 §8.7 allows. - The changes to spec 04 §25 and §36.1 concern only programs with atomics, which could not exist before. - RFC 0003 becomes "Superseded by RFC 0015". ## Deterministic interpreter behavior - Same inputs and seeds give the same record. - Programs without weak accesses make no new draws. - Weak reads draw from the schedule stream. - Every atomic memory operation is a scheduling point. - Collect-every-step mode and `--stress` cover atomics. - The race detector runs in conformance tests. ## Agent complexity impact - **New concepts:** - a linear shared-mutable scalar cell, changed only by atomic operations through `ref`; - five orderings and the tables of D4; - the rule "no `atomic.weak` means interleaving reasoning is exact"; - with `atomic.weak`, the litmus idioms (MP, counter). The formal model is not needed to write correct code with the idioms, and the Quick Reference places atomics after channels and mutexes. - **New verifier state:** none. There are three table checks and the existing linearity and borrow tracking. - **New syntax and instructions:** - 1 type and 8 instruction families; - in source, 13 operations, the ordering words, and the second multi-result binding (`compare_exchange`). - **Interactions:** - loans (sharing through `ref`); - effects (`atomic.weak` propagates to `@main`); - linearity (`atomic.take`); - graphs and aggregates (excluded). - **Repairability:** - `E4201` lists the allowed orderings; - `E4202` names the operation to use; - `E3101` names the missing effect. - **Could existing primitives express it?** A `mutex` expresses a counter and a flag, but adds blocking, a critical-section rule and a guard. Atomics are the explicit lower level, not a replacement. - **Bundle growth (estimates, measured after implementation):** | Bundle | Estimate | |---|---| | Quick Reference | +500–700 tokens | | Source Reference Bundle | +2–3k | | AIR bundle | +3–4k (≈ +9 %); formal axioms excluded | - **New diagnostics an agent sees in source:** `E4201`, `E4202`, and `E3101` for `atomic.weak`. ## Alternatives considered - **ISO C++20 model with load buffering allowed:** rejected (D7). It leaves out-of-thin-air values informal. An executable interpreter would need promises. - **SC-only atomics:** rejected. They lose acquire/release publication and relaxed counters. - **`atomic.weak` for relaxed only:** rejected (D6). - **A plain copyable `atomic` value** (revision 1): rejected (D1). `let b = a` would be ambiguous. - **`mut>` operands:** rejected (D3). One canonical form. - **C++17 failure orderings, independent of success:** rejected (D4). - **A single-result CAS:** rejected (D5). - **Lock-based emulation of unsupported widths:** rejected (D12). - **An operational store-buffer model as the definition:** rejected (D10). It is incomplete for release/acquire. - **Weak CAS, `max`/`min` RMWs, 128-bit atomics, atomic arrays:** deferred. Arrays come with `linear_aggregates`. ## Unresolved questions - **Q1.** `atomic` as an aggregate member or in arrays, with `linear_aggregates`. - **Q2.** Long-lived shared atomics: `arc` with atomic contents, by a change to `ArcSafe` (U4). - **Q3.** A weaker opt-in model for performance, as a separate feature. - **Q4.** Record/replay format (Q-017, Phase 8).