rfc: 0015 scalar atomics and the Aji memory model accepted (revision 2) and integrated into the spec

The Aji RC11 profile (RC11 with NO-THIN-AIR; stronger than ISO C11/C++20) as
normative axioms in spec 04 §20; DRF-SC; linear atomic<T> for AtomicScalar
with atomic.new/atomic.take; ref<atomic<T>> operands; ordering tables incl.
cmpxchg failure table and two results; effects [atomic] / [atomic, atomic.weak];
target atomic_widths and E4203; E4202; enumerator as oracle (observed ⊆ allowed,
exact equality on the normative litmus corpus). Feature atomics stays reserved
until P5-2a. Q-015 resolved; record/replay and Q-017 moved to Phase 8.
RFC 0003 superseded. AIR bundle +1.9 %.
This commit is contained in:
dev committed 2026-10-06 00:30:35 +03:00
1 parent 702d69b2c1
commit 2bbbd2135c
24 files changed
+927 -142

No files matched your search

+1
View File
@@ -49,6 +49,7 @@ Growth never blocks a merge automatically; a complex feature can be justified, b
| Phase 3 implementation | 19 | 38 | 134 576 | 20 884 | 35 324 (+0.6 %) | 35 424 (+0.6 %) | 36 453 (+0.6 %) |
| RFC 0014 islands, frozen graphs, arc (Phase 4) | 19 | 41 | 142 918 | 22 212 | 37 785 (+7.0 %) | — | — |
| P4-11 AIR text grammar for Phases 2–4 | 19 | 41 | 149 279 | 22 945 | 39 154 (+3.6 %) | 39 306 | 40 382 |
| RFC 0015 spec integration (atomics reserved) | 19 | 41 | 151 929 | 23 311 | 39 904 (+1.9 %) | 40 049 | 41 186 |
RFC 0011 crossed the 10 % warning line (its own estimate said "below 10 %"): four new sections in spec 04 (tasks, loans, `Send`/`Share` table, scheduler). Below the 20 % review threshold. RFC 0012 (+15.8 %, estimate 12–16 %): five sections in spec 04 (waits and cancellation, channels, select, mutex, critical-section rule). Implementation-time spec corrections (mutex linearity, `mutex.take` rules): +0.6 %. Phase 3 total since the Phase 2 baseline: +29.2 %. Next measurement: after the E-S smoke test, or with the next RFC.
+16
View File
@@ -94,5 +94,21 @@
"o200k_base": 39306,
"qwen2.5": 40382
}
},
{
"label": "RFC 0015 spec integration (atomics reserved)",
"language": "aji",
"air": 0,
"phase": 3,
"files": 19,
"sections": 41,
"bytes": 151929,
"lines": 2256,
"words": 23311,
"tokens": {
"cl100k_base": 39904,
"o200k_base": 40049,
"qwen2.5": 41186
}
}
]
+12 -2
View File
@@ -20,9 +20,9 @@ Status values: `open`, `resolved`.
| Q-012 | resolved | P2 | Capability representation and host instantiation |
| Q-013 | resolved | P3 | Deterministic `select` rule and scheduler seed |
| Q-014 | resolved | P3 | `Send`/`Share` derivation for aggregates holding capabilities |
| Q-015 | open | P5 | Operational weak-memory model for the interpreter |
| Q-015 | resolved | P5 | Operational weak-memory model for the interpreter |
| Q-016 | open | P0 | Floating-point determinism |
| Q-017 | open | P5 | Replay file format |
| Q-017 | open | P8 | Replay file format |
| Q-018 | resolved | P2 | Runtime diagnostics (traps) vs verifier diagnostics |
| Q-019 | resolved | P3 | Non-terminating programs in test tooling |
| Q-020 | resolved | P2 | Size bound for SSA array values |
@@ -119,6 +119,14 @@ Spec 02 §6 derives properties structurally; spec 05 §5 says capability types d
The SB litmus test requires the interpreter not to forbid `r1=0, r2=0` under relaxed ordering. Undecided: which executable model to use (store buffers, a promising-style semantics, or an axiomatic checker over recorded executions) and how much of C11's model to adopt.
**Resolved (RFC 0015):**
- The normative model is axiomatic: the Aji RC11 profile of spec 04 §20, including NO-THIN-AIR (`sb ∪ rf` acyclic).
- An enumerator derived from the axioms is the executable oracle (spec 04 §20.5).
- The interpreter is an operational machine. For every program, `observed ⊆ allowed`. For the finite normative litmus corpus only, `observed_exhaustive = allowed` (spec 04 §20.5, §42).
- Weak choices are draws from the schedule stream.
- Promises are not needed, because NO-THIN-AIR forbids the cyclic load-buffering outcome.
## Q-016 — Floating-point determinism
`f32`/`f64` exist (spec 02 §1) with no rules on NaN payloads, fused operations, rounding mode or denormals. Deterministic replay requires these to be fixed.
@@ -127,6 +135,8 @@ The SB litmus test requires the interpreter not to forbid `r1=0, r2=0` under rel
Spec 11 §4 mentions `.ajr` files without a format or compatibility rule.
Moved to Phase 8 by RFC 0015 (D13). The deterministic profile already reproduces runs from seeds and quantum. A replay file for hosted or native runs must record scheduler choices, reads-from choices, modification orders and the SC order.
## Q-018 — Runtime diagnostics
The error registry covers verifier/compiler errors. Traps and runtime check failures (bounds, generation, overflow) need stable machine-readable records too, either in the same registry (e.g. `R` codes) or a separate one.
+14 -13
View File
@@ -4,11 +4,11 @@ Non-normative. Part of the [implementation plan](README.md).
**Goal:** atomic types with all five orderings and fences, an interpreter that exhibits exactly the outcomes the memory model allows, systematic schedule exploration, and record/replay.
**Exit criterion:** the litmus suite (`reference/concurrency-litmus.md`) and atomic-publication conformance tests pass, including allowed weak outcomes.
**Exit criterion:** every litmus test passes with exact equality between observed and allowed outcomes; atomic-publication conformance tests pass in AIR and `.aji`.
**Spec inputs:** spec 04 §20–32, 11; `reference/concurrency-litmus.md`. RFC 0003 is proposed for acceptance (owner decision); acceptance integrates it into the spec.
**Spec inputs:** spec 04 §20–§30, §42; spec 05 §13; spec 11; `reference/concurrency-litmus.md`. Decision record: [RFC 0015](../rfcs/0015-atomics-memory-model.md) (Accepted, revision 2; supersedes RFC 0003).
**Blocking questions:** Q-015 operational weak-memory model, Q-017 replay format.
**Blocking questions:** none. Q-015 was resolved by RFC 0015; Q-017 moved to Phase 8 with record/replay.
**Owner decision (2026-10-05, after the Phase 4 exit review).** Phase 5 starts with the RFC. Implementation is on hold until all three of these are done:
@@ -54,17 +54,18 @@ Phase 4 commit frozen (tag p4-frozen)
| ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---|
| P5-0 | todo | M/C regression on the frozen Phase 4 commit (tag `p4-frozen`): M, C × Aji/source × N1–N3, 6 cells, same agents, tasks, evaluators and procedure as P6A-9 | — | `docs/evaluation/results/` | see "Regression gate" below |
| P5-1 | todo | RFC 0015: scalar atomics and the Aji memory model (supersedes RFC 0003); closes the owner's question list; resolves Q-015; scope of Q-017 | — | `docs/rfcs/0015-…` | Accepted by the owner and integrated into spec 04, 05, 07a, 11, 15 |
| P5-1a | todo | Normative litmus corpus: the classes MP, SB, LB, release/acquire publication, `seq_cst` ordering (IRIW, SB with `seq_cst`), relaxed counter, CAS success/failure, fence publication, forbidden non-atomic race, atomic/non-atomic mixing, plus the handoffs (mutex, channel, spawn/join). Each test has allowed and forbidden outcome sets, and an independent enumerator of the RFC's axiomatic model reproduces every set | P5-1 | `reference/concurrency-litmus.md`, `tests/litmus/` | the enumerator agrees with every stated set; owner review |
| P5-2 | todo | Contract tables: `atomic.load`, `atomic.store`, `atomic.rmw`, `atomic.cmpxchg`, `atomic.fence` | P5-1 | spec 07 appendix | all fields present, including allowed orderings per op |
| P5-2a | todo | Publish feature `atomics` | P5-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P5-3 | todo | Atomic types and ordering validation | P5-2 | `src/verifier/atomics.zig` | E4201 accept/reject for every op, including cmpxchg failure order |
| P5-4 | todo | `atomic` / `atomic.weak` effect marking | P5-3 | verifier + report | relaxed use without `atomic.weak` rejected per Q-011 outcome; weak sites listed in report |
| P5-5 | todo | Weak-memory model in the interpreter | P5-1 | `src/interp/weak.zig` | SB weak outcome reachable; MP forbidden outcome unreachable |
| P5-1 | done | RFC 0015: scalar atomics and the Aji memory model (supersedes RFC 0003); closes the owner's question list; resolves Q-015; scope of Q-017 | — | `docs/rfcs/0015-…` | Accepted by the owner and integrated into spec 04, 05, 07a, 11, 15 |
| P5-1a | todo | Litmus enumerator `tools/litmus` (an executable oracle derived from spec 04 §20, not the definition) and the normative corpus: the classes MP, SB, LB, release/acquire publication, `seq_cst` ordering (IRIW, SB with `seq_cst`), relaxed counter, CAS success/failure, fence publication, forbidden non-atomic race, atomic/non-atomic mixing, plus the handoffs (mutex, channel, spawn/join). Each test has allowed and forbidden outcome sets | P5-1 | `tools/litmus/`, `reference/concurrency-litmus.md`, `tests/litmus/` | the enumerator's allowed set equals every stated set, disagreements diagnosed (spec 04 §20.5); owner review |
| P5-2 | done | Contract tables: `atomic.new`, `atomic.take`, `atomic.load`, `atomic.store`, RMW, `atomic.cmpxchg`, `atomic.fence` | P5-1 | spec 04 §42, spec 07a | all spec 07 §4 fields present, with the ordering tables of spec 04 §24 (integrated with RFC 0015) |
| P5-2a | todo | Publish feature `atomics` (depends on `effects`, `ownership`) | P5-3 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests |
| P5-3 | todo | AIR parse/print, types (linear `atomic<T>`, AtomicScalar, not IslandSafe), ordering tables, `E4202` | P5-1a | `src/air/`, `src/verifier/` | `E4201` accept/reject for every operation and every cmpxchg success/failure pair; `E4202`; `E1001`, `E2111`, `E0006` cases |
| P5-4 | todo | `atomic` / `atomic.weak` effects (spec 05 §13); weak sites in `aji report` | P5-3 | verifier + report | each non-`seq_cst` ordering without `atomic.weak` is `E3101`; `seq_cst` needs only `atomic`; weak sites listed |
| P5-5 | todo | Interpreter: atomic cells with message histories, views, weak reads drawn from the schedule stream; atomic operations are scheduling points | P5-3 | `src/interp/` | sound on the corpus and the differential test; no extra draw without weak accesses; existing records unchanged |
| P5-6 | todo | Happens-before tracking and dynamic race detector (validates the verifier) | P5-5 | `src/interp/` | any race the verifier missed aborts the test run with a diagnostic |
| P5-7 | todo | Systematic schedule exploration with bounded budget | P5-5 | `src/interp/sched.zig` | `aji test --interleavings=N` explores distinct schedules deterministically |
| P5-8 | todo | Record and replay | P5-1 | `src/interp/replay.zig` | `aji run --record` / `aji replay` reproduce a failing concurrent run byte-for-byte |
| P5-9 | todo | Litmus suite runner | P5-5 | `tests/litmus/`, `zig build litmus` | each litmus test states allowed and forbidden outcomes; all pass |
| P5-7 | todo | Exhaustive bounded exploration of schedules and weak-read choices | P5-5 | `src/interp/` | for each litmus test, the outcome set observed equals the oracle's allowed set exactly |
| P5-8 | dropped | Record and replay: moved to Phase 8 (P8-10) by RFC 0015 D13 | — | — | — |
| P5-9 | todo | Litmus runner and differential test (random small programs; interpreter outcomes ⊆ oracle outcomes) | P5-7 | `tests/litmus/`, `zig build litmus` | all corpus tests pass with exact equality; differential test in CI |
| P5-9a | todo | `.aji` layer 10 (spec 15 §12), Quick Reference subsection after mutexes, source coverage rows, bundle measurement | P5-4 | `src/frontend/`, `docs/agent/` | `.aji` run/reject tests for every row; Quick Reference excerpts checked; growth recorded against RFC 0015's estimate |
| P5-10 | todo | Phase exit review | all | plan status | exit criterion passes |
## Regression gate (P5-0)
+1
View File
@@ -20,4 +20,5 @@ Non-normative. Part of the [implementation plan](README.md).
| P8-6 | todo | Packages: dependencies, lockfile, content addressing, sandboxed declared build extensions | — | spec 12, `src/pkg/` | dependency resolution is deterministic; unsafe dependencies reported separately |
| P8-7 | todo | Integrate `ajid` with the evaluation scaffold (E0-3) so Aji runs use the agent protocol | P8-2, E0-3 | scaffold adapter | scaffold drives Aji through `ajid`; protocol §28 records complete |
| P8-8 | todo | External agent trial on a reference task | P8-2…P8-5 | trial report in `docs/plan/` | exit criterion passes |
| P8-10 | todo | Record and replay (moved from P5-8 by RFC 0015): `aji run --record` / `aji replay`; the replay format (Q-017) records scheduler choices, reads-from choices, modification orders and the SC order | P8-1 | `src/interp/replay.zig`, spec 11 §4 | a failing concurrent run, weak-memory runs included, is reproduced byte for byte from its file |
| P8-9 | todo | Phase exit review; Aji 0.1 release-candidate checklist | all | plan status | all phases done; spec status updated |
+1 -1
View File
@@ -32,7 +32,7 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It
|---|---|---|---|---|
| `arc` | published | 4 | `capabilities`, `effects`, `heap`, `islands`, `ownership`, `resources` | `arc<T>`, `arc.*`, `ArcSafe` (spec 03 §24) |
| `arrays` | published | 1 | `ownership` | `array<T, N>`, `slice<T>`, `slice_mut<T>`, `array.splat`, `borrow.index[.proven]`, `slice.*`, `guard`, bounds facts (spec 07a, spec 08 §12) |
| `atomics` | reserved | 5 | `ownership` | atomic types, the five orderings, fences, `atomic.*` instructions |
| `atomics` | reserved | 5 | `effects`, `ownership` | linear `atomic<T>` for AtomicScalar `T`, `atomic.new`, `atomic.take`, `atomic.load`/`store`/RMW/`cmpxchg`/`fence` with explicit orderings, effects `atomic`/`atomic.weak`, `E4201`, `E4202` (spec 04 §20–§30, §42); specified by RFC 0015, published with its implementation (P5-2a) |
| `borrow_joins` | reserved | — | `ownership` | borrow-typed block parameters (spec 08 §11.6); unscheduled |
| `cancellation` | published | 3 | `effects`, `ownership`, `tasks` | effect `task.wait` (required by suspending operations, `task.join` included), waiting-operation rule, `shield`, `task.shield.*`, `task.check_cancel`, `task.join.cancel` (spec 04 §37) |
| `capabilities` | published | 2 | `effects`, `ownership` | `cap<K>`, built-in `cap_error`, `cap.narrow`, `intrinsic`, instantiation of `@main` (spec 05 §10–§12) |
+16 -1
View File
@@ -52,7 +52,8 @@ block = ident [ "(" [ param_list ] ")" ] ":" NL { instruction NL } ;
(* The first block is the entry block and takes no parameters. *)
instruction = [ local { "," local } "=" ] operation ;
(* More than one result only for instructions specified with several results (slice.split). *)
(* More than one result only for instructions specified with several results
(slice.split; atomic.cmpxchg with feature atomics). *)
operation = "const." int_type int_lit
| "const.bool" ( "true" | "false" )
@@ -74,6 +75,7 @@ operation = "const." int_type int_lit
| channel_op
| sync_op
| graph_op
| atomic_op
| terminator ;
(* Several instructions are terminators with named outgoing edges (spec 07a).
@@ -171,6 +173,18 @@ graph_op = "island.create" local "," local ok_err (* ter
| "arc.new" local "," local ok_err (* feature arc; terminator: root value, cap<mem.alloc> *)
| ( "arc.from_frozen" | "arc.clone" | "arc.release" ) local ; (* feature arc *)
(* Feature atomics (spec 04 §20–§30, §42). Each opcode is one dotted word; the
allowed orderings per operation are spec 04 §24 (E4201 otherwise). *)
atomic_op = "atomic.new" local
| "atomic.take" local
| "atomic.load." ordering local
| "atomic.store." ordering local "," local
| "atomic." rmw_op "." ordering local "," local
| "atomic.cmpxchg." ordering "." ordering local "," local "," local (* two results: old, exchanged *)
| "atomic.fence." ordering ;
rmw_op = "xchg" | "add.wrap" | "sub.wrap" | "and" | "or" | "xor" ;
ordering = "relaxed" | "acquire" | "release" | "acq_rel" | "seq_cst" ;
arith_op = ( "add" | "sub" | "mul" ) "." ( "checked" | "wrap" ) "." int_type
| ( "div" | "rem" ) ".checked." int_type
| ( "and" | "or" | "xor" ) "." ( int_type | "bool" )
@@ -204,6 +218,7 @@ type = int_type | "bool" | "void" | "never" | global
| ( "mutex" | "guard" ) "<" type ">" (* feature sync *)
| ( "island" | "frozen" | "iref" ) "<" type ">" (* feature islands *)
| "arc" "<" type ">" (* feature arc *)
| "atomic" "<" type ">" (* feature atomics; bool or an integer type up to 64 bits *)
| builtin_type ;
builtin_type = "cap_error" (* feature capabilities *)
| "alloc_error" (* feature heap *)
+49 -46
View File
@@ -1,59 +1,62 @@
# Concurrency Litmus Tests
These are semantic tests for the interpreter, verifier and native backend. Syntax is illustrative.
Litmus tests for the memory model of spec 04 §20–§30 (RFC 0015). They are semantic tests for the oracle, the interpreter and native backends.
## MP — message publication
The tests do not define the model; spec 04 §20 does. They are its consequences, and the normative conformance corpus for the interpreter (spec 04 §20.5).
Writer:
**Status:** draft corpus. The sets below were derived by hand from the axioms. P5-1a makes the corpus normative: every set is confirmed with the enumerator, the test files go into `tests/litmus/`, and the owner reviews the result. When the enumerator, the interpreter and a stated set disagree, the cause is diagnosed (spec 04 §20.5). A set is never edited to match a tool without a diagnosis.
```aji
atomic.store(ref value, 42, relaxed);
atomic.store(ref ready, true, release);
```
## Rules
Reader:
- Each test states its **allowed** outcome set and its **forbidden** outcome set. A test never states a single expected result.
- **Oracle:** the enumerator's allowed set MUST equal the stated allowed set.
- **Interpreter:**
- under exhaustive exploration, the observed outcomes MUST equal the allowed set, for these tests;
- for any program, under any exploration, no outcome outside the allowed set may appear.
- Unless stated otherwise:
- locations start at 0;
- tasks run in parallel under one scope;
- `rlx`, `acq`, `rel`, `ar`, `sc` abbreviate the five orderings.
```aji
if atomic.load(ref ready, acquire) {
let v = atomic.load(ref value, relaxed);
assert v == 42;
}
```
## Notation
If the reader observes the release publication, observing the prior value store must be consistent with the happens-before relation.
- `‖` separates tasks.
- A tuple lists the reading registers in program order of the tasks, task by task.
- `final x` is the value `atomic.take` reads after all joins.
## SB — store buffering
## Corpus
Initially `x = 0`, `y = 0`, both atomic.
| 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 `rlx` | all four | — |
| MP fences | `x=1 rlx; fence rel; y=1 rlx` ‖ `r0=y rlx; fence acq; r1=x rlx` | (0,0) (0,1) (1,1) | (1,0) |
| SB rlx | `x=1; r0=y` ‖ `y=1; r1=x`, all `rlx` | all four | — |
| SB rel/acq | stores `rel`, loads `acq` | all four, including (0,0) | — |
| SB sc | all `sc` | (0,1) (1,0) (1,1) | (0,0) |
| SB fences | `rlx` accesses, `fence sc` between store and load on both sides | (0,1) (1,0) (1,1) | (0,0) |
| LB rlx | `r0=x; y=1` ‖ `r1=y; x=1`, all `rlx` | (0,0) (0,1) (1,0) | (1,1), a consequence of NO-THIN-AIR |
| IRIW acq | `x=1 rel` ‖ `y=1 rel` ‖ `r0=x acq; r1=y acq` ‖ `r2=y acq; r3=x acq` | includes (1,0,1,0) | — |
| IRIW sc | all `sc` | every tuple except (1,0,1,0) | (1,0,1,0) |
| CoRR | `x=1 rlx` ‖ `r0=x rlx; r1=x rlx` | (0,0) (0,1) (1,1) | (1,0) |
| CoWW | `x=1 rlx; x=2 rlx`, final `x` | 2 | 1 |
| relaxed counter | 2 tasks × 2 `add.wrap(x,1) rlx`, final `x` | 4 | 2, 3 |
| CAS exclusion | `r0=cas.rlx.rlx(x,0→1)` ‖ `r1=cas.rlx.rlx(x,0→2)` (old values) | (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,0) (0,1) (1,1) | (1,0) |
| CAS failure relaxed | as above with `cas.acq.rlx` | (0,0) (0,1) (1,0) (1,1) | — |
| release sequence | `d=1 rlx; f=1 rel` ‖ `add.wrap(f,2) rlx` ‖ `r0=f acq; r1=d rlx` | (0,0) (0,1) (1,1) (2,0) (2,1) (3,1) | (1,0) (3,0) |
| channel handoff | `x=1 rlx; send(t)` ‖ `recv; r0=x rlx` | (1) | (0) |
| mutex handoff | `lock; x=1 rlx; unlock` ‖ `lock; r0=x rlx; unlock`, in that lock order | (1) | (0) |
| spawn/join | `x=1 rlx`; spawn ‖ child: `r0=x rlx; x=2 rlx`; after join `r1=x rlx` | (1,2) | (0,·) (·,1) |
Task A:
## Rejected programs
```text
store x=1 relaxed
r1 = load y relaxed
```
These are verifier tests, not outcome tests.
Task B:
```text
store y=1 relaxed
r2 = load x relaxed
```
Outcome `r1=0, r2=0` is permitted under relaxed ordering. The interpreter's weak-memory test mode must not incorrectly forbid it.
## Mutex handoff
Writes performed while holding a mutex before unlock must be visible to a later holder after successful lock acquisition.
## Channel handoff
Writes sequenced before successful `channel.send` are visible after the matching receive. Ownership of the moved message belongs only to the receiver after transfer.
## Spawn/join
Parent operations sequenced before spawn happen-before child start. Child operations happen-before successful join return.
## Invalid ordinary race
Two tasks writing the same ordinary `u64` through overlapping unsynchronized aliases must be rejected before execution.
| Test | Program | Code |
|---|---|---|
| ordinary race | two tasks `store` the same ordinary `u64` through overlapping borrows | `E4101` |
| mixing | ordinary `load` through `ref<atomic<u64>>` | `E4202` |
| invalid ordering | `atomic.load.release` | `E4201` |
| invalid failure ordering | `atomic.cmpxchg.relaxed.acquire` | `E4201` |
| take while lent | `atomic.take` of a cell whose `ref` is lent to a live task | `E4101` |
+2 -2
View File
@@ -4,8 +4,8 @@ Normative registry of effect names for AIR format 0 (spec 05 §9). Effects are f
| Effect | Authority required | Introduced by |
|---|---|---|
| `atomic` | none | Phase 5 |
| `atomic.weak` | none | Phase 5 |
| `atomic` | none | RFC 0015: every atomic memory operation (spec 04 §25) |
| `atomic.weak` | none | RFC 0015: every atomic access whose ordering is not `seq_cst` (spec 04 §25) |
| `clock.read` | `cap<clock.read>` | RFC 0007 |
| `ffi` | none (unsafe boundary, spec 13) | Phase 7 |
| `fs.read` | `cap<fs.read>` | RFC 0007 |
+2
View File
@@ -57,6 +57,8 @@ Draft registry. Codes are stable once released in a tagged compiler version.
| E4002 | concurrency.not_share | Non-Share value concurrently shared |
| E4101 | concurrency.possible_data_race | Conflicting ordinary access not ordered/synchronized |
| E4201 | atomic.invalid_order | Memory ordering invalid for atomic operation |
| E4202 | atomic.ordinary_access | Atomic cell accessed by an ordinary load |
| E4203 | atomic.unsupported_width | Atomic width not implemented lock-free by the target |
| E4301 | task.live_child_escape | Scope exits with live child task |
| E4302 | task.borrow_escape | Child task borrow can outlive parent storage |
| E4303 | io.buffer_in_flight | Buffer accessed while async operation owns/borrows it |
+3 -3
View File
@@ -8,7 +8,7 @@ A `Copy` value may be duplicated without changing ownership semantics.
Typical examples: integers, booleans, small aggregates containing only `Copy` fields.
Not `Copy`: `Own<T>`, `Region`, `Island<T>`, `File`, `Socket`, task/thread handles.
Not `Copy`: `Own<T>`, `Region`, `Island<T>`, `atomic<T>`, `File`, `Socket`, task/thread handles.
## Send
@@ -22,7 +22,7 @@ A `Share` value may be observed concurrently through immutable access.
Deeply immutable values are normally `Share`.
Interior-mutability wrappers must establish their own synchronization semantics to qualify.
Interior-mutability wrappers must establish their own synchronization semantics to qualify. `mutex<T>` does so by locking. `atomic<T>` does so because every access through a shared borrow is an atomic operation with an explicit ordering (spec 04 §23).
## Freeze
@@ -41,7 +41,7 @@ Examples may include thread-local handles, event-loop-local registrations or pla
An `IslandSafe` value may be stored in an island graph (spec 03 §22). Derived structurally:
- **IslandSafe:** integers, `bool`, built-in enums, `iref<U>`, and arrays, structs and enums of `IslandSafe` values.
- **Not IslandSafe:** borrows, owners, regions, graph owners (`island`, `frozen`, `arc`), resources, endpoints, `task`, `scope`, `shield`, `guard`, `mutex`, `cap<K>`.
- **Not IslandSafe:** borrows, owners, regions, graph owners (`island`, `frozen`, `arc`), resources, endpoints, `task`, `scope`, `shield`, `guard`, `mutex`, `atomic<T>`, `cap<K>`.
Because of it, a graph never holds outside authority or a mutable ownership edge, so freeze, conversion and transfer are O(1).
+1 -1
View File
@@ -1,6 +1,6 @@
# RFC 0003: Concurrency Memory Model
Status: Proposed
Status: Superseded by RFC 0015
Target: Aji 0.1
## Summary
+521
View File
@@ -0,0 +1,521 @@
# 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<T>` is linear, with `atomic.take`;
- every operation takes `ref<atomic<T>>`;
- `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<T>` 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<T>` 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<T>` is linear. Through a borrow it is reachable only by atomic instructions: an ordinary `load` through `ref<atomic<T>>` 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<T>` 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<T>` for scalar `T` (revised)
`atomic<T>` 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<T>` 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<T>`.
- **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<T>`; no effect, since no concurrent operation has happened yet |
| `%r = borrow.ref %a` | the container borrow, as for graph owners; `ref<atomic<T>>` is what every operation takes and what tasks receive |
| `%v = atomic.take %a` | consumes `atomic<T>`, 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<atomic<T>>` (revised)
Load, store, the RMWs, `cmpxchg` and nothing else touch the cell, and all of them take `ref<atomic<T>>`. That is atomic interior mutability: several tasks hold shared borrows of one cell and change it through them. `mut<atomic<T>>` is not an operand (`E1001`), so there is one canonical form. An ordinary `load` through `ref<atomic<T>>` 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.<succ>.<fail> %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<atomic<T>>` 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<T>` is restricted to scalars: `atomic<ref<T>>`, `atomic<own<T>>`, `atomic<iref<T>>` and `atomic<arc<T>>` are `E1001`. An index into owned storage held in an `atomic<usize>` 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<T>` 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<T>`.
- 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:
- `<o>` is an ordering valid for the operation (D4).
- `T` is AtomicScalar.
- `P` is `ref<atomic<T>>`.
| Instruction | Operands → result | Effects | Verifier | Runtime |
|---|---|---|---|---|
| `%a = atomic.new %v` | `T` → `atomic<T>` (linear) | — | `T` AtomicScalar (`E1001`) | creates the cell with its initializing write |
| `%v = atomic.take %a` | `atomic<T>` (consumed) → `T` | — | no live borrow (`E2101`; `E4101` if lent) | reads the cell's final value; frees nothing else |
| `%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 RMW; returns the value read |
| `%old, %ok = atomic.cmpxchg.<s>.<f> %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.<o>` | — | `atomic` | `E4201` | fence event; 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.
- **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<T>` 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<atomic<T>>`, with `found` and `use: "atomic.load"`.
- **Effects.** D6; a missing atom is `E3101`, unchanged.
- **Borrows and loans.** Unchanged. `ref<atomic<T>>` 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<T>` 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<atomic<u64>>, 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<atomic<u64>>, ready: ref<atomic<bool>>) -> 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<atomic<u64>>` | `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<ref<u64>>` | `E1001` |
| a struct field of type `atomic<u64>` | `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<atomic<u64>>` | 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<u64>` 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<T>` value** (revision 1): rejected (D1). `let b = a` would be ambiguous.
- **`mut<atomic<T>>` 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<T>` 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).
+1 -1
View File
@@ -124,7 +124,7 @@ The compiler derives:
- `Share`: may be observed concurrently through immutable access;
- `Freeze`: can be converted to deeply immutable state;
- `Local`: tied to its current execution context;
- `IslandSafe`: may be stored in an island graph (spec 03 §22). Derived structurally: integers, `bool`, built-in enums and `iref<U>` are `IslandSafe`, and so are arrays, structs and enums of `IslandSafe` values. Borrows, owners, regions, graph owners (`island`, `frozen`, `arc`), resources, endpoints, `task`, `scope`, `shield`, `guard`, `mutex` and `cap<K>` are not;
- `IslandSafe`: may be stored in an island graph (spec 03 §22). Derived structurally: integers, `bool`, built-in enums and `iref<U>` are `IslandSafe`, and so are arrays, structs and enums of `IslandSafe` values. Borrows, owners, regions, graph owners (`island`, `frozen`, `arc`), resources, endpoints, `task`, `scope`, `shield`, `guard`, `mutex`, `atomic<T>` and `cap<K>` are not;
- `ArcSafe`: may be held by an `arc` (spec 03 §24). The last release destroys it by freeing memory only. In format 0 it is exactly `IslandSafe`.
These are semantic properties, not user-extensible traits in v0.1. Their derivation for the types of AIR format 0 is the table of spec 04 §35.
+212 -68
View File
@@ -72,7 +72,7 @@ Safe shared mutation uses approved synchronization types:
```text
Mutex<T>
RwLock<T>
Atomic*
atomic<T>
Channel<T>
```
@@ -213,127 +213,226 @@ let n = io.wait(move op)?;
This prevents use or mutation while the OS/runtime may access the buffer.
## 20. Memory model relations
## 20. Memory model
Aji defines:
The memory model of Aji 0.1 has three layers (RFC 0015):
- `sequenced-before` within one execution unit;
- `synchronizes-with` edges from synchronization operations;
- `happens-before` as the transitive closure of those relations;
- per-atomic-object modification order.
```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`, writes `W` and read-modify-writes `U` (both a read and a write), each with a location, values and an ordering;
- fences `F`;
- ordinary reads and writes;
- the synchronization events of the built-in primitives (§20.3).
The cell created by `atomic.new` has an initializing write, first in the modification order of its location. `atomic.take` is an ordinary read of the cell.
### 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 part of each `U` to its write part.
Derived:
```text
fr = rf⁻¹ ; mo from-read
eco = (rf ∪ mo ∪ fr)⁺ extended coherence
rs = [W] ; (rf ; rmw)* release sequence
sw = [E ⊒ rel] ; ([F] ; sb)? ; rs ; rf ; [R] ; (sb ; [F])? ; [E ⊒ acq] ∪ sw_prim
hb = (sb ∪ sw)⁺ happens-before
```
`E ⊒ rel` is a write, RMW or fence whose ordering is `release`, `acq_rel` or `seq_cst`. `E ⊒ acq` is a read, RMW or fence whose ordering is `acquire`, `acq_rel` or `seq_cst`. `[X]` restricts a relation to events in `X`.
### 20.3 Synchronization of built-in primitives
Each task, channel and mutex has a total order of its operations, consistent with `hb`. It is not part of the `seq_cst` order: these are lock semantics, as for C++ mutexes. `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` → the `channel.recv` (or `select` arm) that receives that message;
- `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.
### 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.
- **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 overlap and at least one writes.
Two accesses **conflict** when they access the same location and at least one writes.
A data race exists when conflicting ordinary accesses occur concurrently without a happens-before ordering.
A **data race** is a pair of conflicting accesses, at least one of them ordinary, that `hb` does not order.
Safe Aji must reject programs in which such a race is possible under its verified alias/synchronization model.
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
Programs that use only safe synchronization and contain no ordinary-memory data races receive the following 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.
> ordinary-memory observations are explainable by a sequentially consistent interleaving consistent with happens-before.
The basis is RC11's theorem for programs whose atomics are all `seq_cst`, with the lock semantics of §20.3. With `atomic.weak`:
Explicit weak atomics may produce weaker observations for atomic coordination.
- 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
Initial types:
`atomic<T>` is defined for the **AtomicScalar** types:
```text
AtomicBool
AtomicU8 AtomicU16 AtomicU32 AtomicU64 AtomicUsize
AtomicI8 AtomicI16 AtomicI32 AtomicI64 AtomicIsize
bool u8 u16 u32 u64 usize i8 i16 i32 i64 isize
```
Support depends on target capabilities. Unsupported widths must be rejected or lowered through a conforming library abstraction with equivalent semantics.
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 as the contents of `local`, `own` or a region it needs `linear_aggregates` (`E0006`).
- 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 memory orders are defined:
Exactly these orderings exist:
```text
relaxed
acquire
release
acq_rel
seq_cst
relaxed acquire release acq_rel seq_cst
```
There is no `consume`.
There is no `consume` and no default ordering. Every atomic memory operation names its orderings, and any ordering outside its row is `E4201`.
No atomic operation has a default ordering.
| 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 Load
### 24.1 Compare-exchange
Allowed:
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.
```text
relaxed acquire seq_cst
```
| Success | Allowed failure |
|---|---|
| `relaxed` | `relaxed` |
| `acquire` | `relaxed`, `acquire` |
| `release` | `relaxed` |
| `acq_rel` | `relaxed`, `acquire` |
| `seq_cst` | `relaxed`, `acquire`, `seq_cst` |
### 24.2 Store
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.
Allowed:
### 24.2 Read-modify-write operations
```text
relaxed release seq_cst
```
| 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 |
### 24.3 Read-modify-write
Allowed:
```text
relaxed acquire release acq_rel seq_cst
```
### 24.4 Compare exchange
Compare exchange declares success and failure orderings separately. Failure ordering cannot be `release` or `acq_rel`.
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
Functions that use relaxed atomics SHOULD expose an `atomic.weak` effect or equivalent verifier-visible marker.
The effect rule, literally:
This makes weak-memory code easy to find during audits.
```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` operations participate in a single global total order consistent with each execution unit's sequenced-before relation for those operations.
`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
Aji supports:
```text
atomic.fence(acquire)
atomic.fence(release)
atomic.fence(acq_rel)
atomic.fence(seq_cst)
atomic.fence acquire | release | acq_rel | seq_cst
```
There is no relaxed fence.
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 cannot directly access atomic storage as ordinary storage.
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`.
Unsafe code that mixes conflicting atomic and non-atomic accesses must independently satisfy the memory model. Violating those unsafe preconditions is Undefined Aji Behavior.
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 v0.1 does not expose arbitrary atomic safe-reference manipulation because publication and reclamation are inseparable problems.
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 should use audited standard-library facilities such as epoch reclamation, hazard pointers or RCU-like mechanisms.
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 claim to prove general ABA absence.
Low-level algorithms must use explicit countermeasures such as generations, tagged values, hazard pointers or epoch reclamation.
The verifier does not prove ABA absence. Algorithms use explicit countermeasures, such as generation counters in the compared value.
## 31. Progress guarantees
@@ -433,6 +532,7 @@ Example: two workers square the two halves of one buffer in parallel; both loans
| `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).
@@ -451,9 +551,18 @@ mut<T> → T: Send otherwise E4001
### 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, I/O, or the end of its **quantum** — and then the scheduler chooses the next task to run among the runnable ones.
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; by invariant 5 they may only produce outcomes that some interleaving of this model produces. This guarantee applies to safe programs that use neither the future weak-memory atomic facilities nor unsafe code; atomic memory ordering is governed by the Aji memory model (spec 04 §20–§31).
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).
@@ -481,7 +590,7 @@ Varying the schedule seed while keeping `--seed` explores interleavings without
### 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); two runs with equal records made the same choices. No draw is made when there is only one candidate.
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
@@ -498,7 +607,7 @@ Invariants of §37–§41:
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 and choices among ready `select` arms are drawn from the one schedule generator (§36.2).
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
@@ -679,3 +788,38 @@ Consequences:
- 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.
+15
View File
@@ -274,3 +274,18 @@ The authority object of a `cap<mem.alloc>` carries a budget of simultaneously li
- A capability is represented as an index into a host-owned table of (kind, scope) entries. The index is not observable by the program.
- Narrowing appends a new table entry. Entries are never removed during a run.
- In the `deterministic` profile, grants refer to virtual resources (an in-memory file system, a captured stdout, a seeded clock and random source), so runs are reproducible.
## 13. Atomic effects (feature `atomics`)
The rule of spec 04 §25, checked like any other named effect (§9.3):
```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
```
For compare-exchange, the operation is non-`seq_cst` if either ordering is. A missing atom is `E3101`.
If `atomic.weak` is not among the transitive effects of `@main`, every atomic access is `seq_cst`, and every execution of the safe program is explainable as an SC interleaving (spec 04 §22).
+1 -1
View File
@@ -291,4 +291,4 @@ Feature membership: `local<T>`, `ref<T>`, `mut<T>` and the `from` clause belong
All value types of format 0 and Phase 1 are copyable. Move-only values arrive with `heap` in Phase 2.
Syntax additions (reference/air-text.ebnf): `-> type from %param` on function signatures, the type forms above, and `%a, %b = op` for instructions specified with two results (only `slice.split`).
Syntax additions (reference/air-text.ebnf): `-> type from %param` on function signatures, the type forms above, and `%a, %b = op` for instructions specified with two results (`slice.split`; `atomic.cmpxchg` with feature `atomics`, spec 04 §42).
+11
View File
@@ -275,6 +275,17 @@ Every terminator of these features follows spec 07 §8.2: each named target rece
`arc`: type `arc<T>`, instructions `arc.from_frozen`, `arc.new`, `arc.clone`, `arc.release`, `arc.root`, `arc.borrow`; `ArcSafe` and the quota lifecycle: spec 03 §24.
## Feature `atomics`
Status `reserved` until it is published with its implementation (P5-2a). Its contracts are fixed by RFC 0015:
- type: linear `atomic<T>` for AtomicScalar `T`;
- instructions: `atomic.new`, `atomic.take`, `atomic.load.<o>`, `atomic.store.<o>`, `atomic.<rmw>.<o>` (`xchg`, `add.wrap`, `sub.wrap`, `and`, `or`, `xor`), `atomic.cmpxchg.<s>.<f>` (two results), `atomic.fence.<o>`;
- the contract table: spec 04 §42;
- the orderings: spec 04 §24;
- the memory model: spec 04 §20–§30;
- effects: spec 05 §13.
## Run result
`aji run` executes the function `@main`, whose parameters MUST all be capabilities, bound by name at instantiation (spec 05 §10.2); without the `capabilities` feature it takes no parameters. On return it reports `{"status":"returned","value":V}` where `V` renders the returned value as JSON:
+4 -1
View File
@@ -80,5 +80,8 @@ Format version 0 defines one field:
| Field | Meaning |
|---|---|
| `pointer_bits` | width of `usize`/`isize` in bits: 32 or 64 |
| `atomic_widths` | the AtomicScalar widths, in bits, that the target implements natively and lock-free (feature `atomics`, spec 04 §23) |
The reference interpreter uses the target `air64` (`pointer_bits = 64`) unless a module declares target requirements (a later format version).
A module that uses `atomic<T>` for a width the target does not list is rejected for that target at build time (`E4203`, `atomic.unsupported_width`). An implementation MUST NOT emulate an atomic with a lock.
The reference interpreter uses the target `air64` (`pointer_bits = 64`, `atomic_widths = {8, 16, 32, 64}`) unless a module declares target requirements (a later format version).
+4
View File
@@ -39,6 +39,8 @@ aji run --record failure.ajr app.aji
aji replay failure.ajr
```
In the deterministic profile the run record together with `--seed`, `--schedule-seed` and `--quantum` already reproduces a run exactly, weak-memory choices included (spec 04 §42). A replay file for hosted or native runs would also have to record reads-from choices, modification orders and the SC order; its format (Q-017) is Phase 8 work (RFC 0015).
## 5. Concurrency exploration
Test mode may systematically or pseudo-randomly vary scheduling at synchronization points.
@@ -64,6 +66,8 @@ When `select` has multiple ready branches, deterministic mode must choose accord
Rule (RFC 0012, spec 04 §39): a draw from the schedule generator among the ready arms, counted in the run record's `schedule.choices`.
Weak-memory choices (which allowed write a non-`seq_cst` read reads, spec 04 §42) are drawn from the same generator and counted the same way.
## 7. Execution limits
Wall-clock time MUST NOT determine whether a run, test or verification terminates or what its outcome is.
+2
View File
@@ -70,6 +70,8 @@ Unsafe code must document applicable obligations, including:
Violation of an unsafe precondition may cause Undefined Aji Behavior.
Synchronization obligations are stated against the memory model (spec 04 §20–§21): an unsafe operation must not create a data race. In particular, an operation that mixes atomic and ordinary access to one location must keep every such pair ordered by happens-before. Format 0 has no unsafe operation on atomic cells (spec 04 §28).
## 5. Unsafe dependency report
The toolchain should produce a machine-readable report containing:
+35 -1
View File
@@ -177,7 +177,7 @@ Lowering: structured control flow becomes blocks and terminators. A variable ass
| `s[i]` | element value (borrow, load, end) |
| `s.len` | `slice.len`, or the static length of an array |
| `s[a..b]` | a sub-slice (`slice.sub` with start `a`, length `b - a`); a borrow, so it is bound or passed, never a value |
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`; the only multi-result binding. There is no general tuple destructuring. |
| `let (left, right) = s.split_at(k);` | `slice.split`: two disjoint borrows of `s`. Besides `atomic.compare_exchange` (§12), the only multi-result binding. There is no general tuple destructuring. |
| `slice.copy(mut dst, ref src)` | `slice.copy`, the only copy form |
**Writes.**
@@ -432,3 +432,37 @@ Lowering is deterministic: the same source and compiler give byte-identical AIR,
- Sizes count code only: non-empty lines that are not comments (`//` in source, `;` in AIR), each with its newline.
- `mechanical_air_eliminated_raw` = 1 − `source_bytes` / `air_bytes`: how much of the AIR text the author did not write. This is the main engineering metric.
- `mechanical_air_eliminated_normalized` = 1 − `source_bytes` / `air_bytes_normalized`: the same against AIR in which every byte-string materialization counts as one logical constant operation. Such a materialization is the instructions from the string's `local.zero` to its final `borrow.end`, a store per non-zero byte, because format 0 has no byte-array constant. It is replaced by the single notional line ` const.bytes %<storage>, <literal>`, where `<literal>` is the canonical spelling: printable ASCII as is, otherwise the escapes `\n \r \t \0 \\ \" \xNN`. The storage's `local.alloc` is real frame storage and stays. No other instruction is normalized. The rule is the same for every program, and `byte_string_constants` reports how many were replaced.
## 12. Atomics
Spec 04 §20–§30, §42; layer 10, RFC 0015. This layer is specified now and implemented in Phase 5, together with the publication of feature `atomics`. Until then the frontend rejects it as an unknown construct. The section enters the Source Reference Bundle with the implementation (P5-9a).
| Source | AIR |
|---|---|
| `atomic<T>` (`T` AtomicScalar) | `atomic<T>`; linear, borrowed in place like a mutex |
| `let a = atomic.new(v);` | `atomic.new` |
| `let v = atomic.take(move a);` | `atomic.take`; needs no live borrow of `a` |
| `atomic.load(c, o)` | `atomic.load.<o>` |
| `atomic.store(c, v, o);` | `atomic.store.<o>` |
| `atomic.swap(c, v, o)` | `atomic.xchg.<o>` |
| `atomic.add.wrap(c, v, o)`, `atomic.sub.wrap(c, v, o)` | `atomic.add.wrap.<o>`, `atomic.sub.wrap.<o>` |
| `atomic.and(c, v, o)`, `atomic.or(c, v, o)`, `atomic.xor(c, v, o)` | `atomic.and.<o>`, `atomic.or.<o>`, `atomic.xor.<o>` |
| `let (old, exchanged) = atomic.compare_exchange(c, expected, desired, s, f);` | `atomic.cmpxchg.<s>.<f>`, the second multi-result binding |
| `atomic.fence(o);` | `atomic.fence.<o>` |
The cell operand `c`:
- `c` is a `ref<atomic<T>>` binding or parameter, or a temporary `ref a` of an `atomic<T>` written as the argument.
- Passing the atomic itself, without `ref`, is `E7005`. So is writing `mut`.
- To share a cell with tasks, bind `ref c = a;` and pass `c`.
The orderings:
- They are the bare words `relaxed`, `acquire`, `release`, `acq_rel`, `seq_cst`, written last.
- They are not values: they cannot be bound, passed or computed (`E7006`).
- A word outside the operation's row is the verifier's `E4201`, reported at the ordering.
Other rules:
- `*c` and any other ordinary read of a cell is `E4202`.
- Effects are declared by the programmer (spec 05 §13).
+1 -1
View File
@@ -24,7 +24,7 @@ pub const Feature = struct {
pub const registry = [_]Feature{
.{ .name = "arc", .depends = &.{ "capabilities", "effects", "heap", "islands", "ownership", "resources" }, .status = .published, .phase = 4 },
.{ .name = "arrays", .depends = &.{"ownership"}, .status = .published, .phase = 1 },
.{ .name = "atomics", .depends = &.{"ownership"}, .status = .reserved, .phase = 5 },
.{ .name = "atomics", .depends = &.{ "effects", "ownership" }, .status = .reserved, .phase = 5 },
.{ .name = "borrow_joins", .depends = &.{"ownership"}, .status = .reserved, .phase = null },
.{ .name = "cancellation", .depends = &.{ "effects", "ownership", "tasks" }, .status = .published, .phase = 3 },
.{ .name = "capabilities", .depends = &.{ "effects", "ownership" }, .status = .published, .phase = 2 },
+2
View File
@@ -52,6 +52,8 @@ pub const registry = [_]Code{
.{ .id = "E4002", .kind = "concurrency.not_share", .meaning = "Non-Share value concurrently shared" },
.{ .id = "E4101", .kind = "concurrency.possible_data_race", .meaning = "Conflicting ordinary access not ordered/synchronized" },
.{ .id = "E4201", .kind = "atomic.invalid_order", .meaning = "Memory ordering invalid for atomic operation" },
.{ .id = "E4202", .kind = "atomic.ordinary_access", .meaning = "Atomic cell accessed by an ordinary load" },
.{ .id = "E4203", .kind = "atomic.unsupported_width", .meaning = "Atomic width not implemented lock-free by the target" },
.{ .id = "E4301", .kind = "task.live_child_escape", .meaning = "Scope exits with live child task" },
.{ .id = "E4302", .kind = "task.borrow_escape", .meaning = "Child task borrow can outlive parent storage" },
.{ .id = "E4303", .kind = "io.buffer_in_flight", .meaning = "Buffer accessed while async operation owns/borrows it" },