diff --git a/docs/dev/testing.md b/docs/dev/testing.md index ea84b1e..7342bcd 100644 --- a/docs/dev/testing.md +++ b/docs/dev/testing.md @@ -38,7 +38,7 @@ Planned header extensions (added by the phase that needs them): ## Determinism checks -Every run test is executed twice by the runner from P0-10 onward and the outputs (stdout, trap record, trace hash) compared byte-for-byte. Concurrency tests additionally run under the stress modes listed in `plan/conformance-suite.md`. +Every run test is executed twice by the runner from P0-12 onward and the outputs (stdout, trap record, trace hash) compared byte-for-byte. Concurrency tests additionally run under the stress modes listed in `plan/conformance-suite.md`. ## Diagnostics as API diff --git a/docs/plan/README.md b/docs/plan/README.md index e6e0705..ba7d317 100644 --- a/docs/plan/README.md +++ b/docs/plan/README.md @@ -1,118 +1,97 @@ # Implementation Plan -## Phase 0 — Semantic skeleton +Non-normative. The order in which the Zig reference implementation is built, and how work is split into tasks. The spec defines what to build; this plan defines when. -Deliver: +## Sequencing principles -- AIR value/type model; -- text AIR parser and serializer; -- basic blocks and SSA validation; -- integer operations; -- structs/enums; -- interpreter; -- stable diagnostic envelope. +1. **Semantics before speed.** Interpreter and verifier define the language. No native code until the conformance corpus is stable (DD-007). +2. **AIR before source.** AIR is the conformance format. The `.aji` frontend comes after the core semantics are executable. +3. **Spec gate first in every phase.** Each phase opens by resolving its open questions (`../design/open-questions.md`) and writing the instruction contracts (spec 07 §4) for the opcodes it introduces. Code that implements unspecified behavior is not merged. +4. **Tests before code.** Every verifier rule lands with an `accept`/`reject` conformance pair and a stable diagnostic code. +5. **Exit criteria are executable.** A phase is done when its exit criterion passes in `zig build conformance`, not when its tasks are ticked. +6. **One task, one change.** A task is sized for one agent session and one reviewable change. -Exit criterion: AIR `hello` and arithmetic tests execute identically across runs. +## Milestones -## Phase 1 — Ownership and memory +| Milestone | Phases | Result | +|---|---|---| +| M1 — Verified core | P0, P1, P2 | Single-threaded Aji: ownership, regions, effects, capabilities and resources verified; file-copy and TCP echo run in the interpreter | +| M2 — Concurrent Aji | P3, P4, P5 | Structured tasks, channels, locks, islands and atomics with deterministic and randomized scheduling | +| M3 — Source language | P6 | All reference programs written as `.aji` | +| M4 — Native | P7 | LLVM backend; interpreter and native agree on the whole corpus | +| M5 — Agent-ready | P8 | `ajid` protocol and benchmark; candidate for Aji 0.1 | -Deliver: +## Phases -- `Own`; -- `ref` / `mut`; -- slices; -- initialization tracking; -- `Region` and generation semantics; -- bounds/range facts; -- ownership/borrow diagnostics. +| Phase | File | Goal | Exit criterion | Blocking questions | +|---|---|---|---|---| +| P0 | [phase-0-semantic-skeleton.md](phase-0-semantic-skeleton.md) | AIR model, text parser, CFG/SSA/type verifier, interpreter | AIR `hello` and arithmetic tests execute identically across runs | Q-001…Q-008, Q-016 | +| P1 | [phase-1-ownership-and-memory.md](phase-1-ownership-and-memory.md) | `Own`, borrows, slices, init tracking, regions, bounds | file-copy core implemented; UAF/alias/OOB rejected | Q-009, Q-010 | +| P2 | [phase-2-effects-capabilities-resources.md](phase-2-effects-capabilities-resources.md) | Effects, capabilities, linear resources, runtime intrinsics | safe file-copy and basic TCP echo | Q-011, Q-012, Q-018 | +| P3 | [phase-3-structured-concurrency.md](phase-3-structured-concurrency.md) | Task scopes, Send/Share, channels, mutex, cancellation, deterministic scheduler | parallel-map and channel ownership-transfer examples | Q-013, Q-014 | +| P4 | [phase-4-islands.md](phase-4-islands.md) | Islands, `iref`, transfer, freeze, `Frozen`, `Arc` | cyclic graph moves between tasks with no deep copy and no shared mutation | — | +| P5 | [phase-5-atomics-and-memory-model.md](phase-5-atomics-and-memory-model.md) | Atomics, orderings, fences, weak-memory interpreter, schedule exploration, replay | atomic publication litmus/conformance tests | Q-015, Q-017 | +| P6 | [phase-6-source-language.md](phase-6-source-language.md) | `.aji` parser, lowering, generics, contracts, formatter | all reference programs authored primarily as `.aji` | — | +| P7 | [phase-7-native-backend.md](phase-7-native-backend.md) | LLVM lowering, native runtime, three targets, ABI tests | interpreted and native executions pass the same corpus | — | +| P8 | [phase-8-agent-protocol.md](phase-8-agent-protocol.md) | `ajid`, inspect/trace, verification report, benchmark | external agent implements/repairs a reference task using only protocol + spec | — | -Exit criterion: file-copy can be implemented and verifier rejects representative UAF/alias/OOB cases. +## Dependency graph -## Phase 2 — Effects, capabilities and resources +```text +P0 ──► P1 ──► P2 ──► P3 ──► P4 + │ │ + └──────┴──► P5 ──► P6 ──► P7 ──► P8 +``` -Deliver: +Allowed overlap: -- effects; -- capability values; -- linear File/Socket resources; -- runtime intrinsics; -- explicit cleanup lowering. +- spec-gate tasks of a later phase may start any time; +- P6 grammar work (P6-1) may start after P2, since syntax does not affect AIR semantics; +- P8 protocol design (P8-1) may start after P2; `ajid` wraps `check.zig`, which exists from P0. -Exit criterion: safe file-copy and basic TCP echo. +## Error code coverage -## Phase 3 — Structured concurrency +Every registry code (`../reference/error-codes.md`) has a phase that must implement it with an accept/reject pair. -Deliver: +| Code | Phase | | Code | Phase | +|---|---|---|---|---| +| E1001 type.mismatch | P0 | | E3101 effect.undeclared | P2 | +| E1002 type.invalid_cast | P0 | | E3201 capability.missing | P2 | +| E1010 init.read_uninitialized | P1 | | E3202 capability.widen | P2 | +| E2001 ownership.use_after_move | P1 | | E4001 concurrency.not_send | P3 | +| E2002 ownership.double_consume | P1 | | E4002 concurrency.not_share | P3 | +| E2101 borrow.mutable_alias | P1 | | E4101 concurrency.possible_data_race | P3 | +| E2102 borrow.outlives_owner | P1 | | E4201 atomic.invalid_order | P5 | +| E2103 memory.out_of_bounds | P1 | | E4301 task.live_child_escape | P3 | +| E2104 memory.region_generation | P1 | | E4302 task.borrow_escape | P3 | +| E2110 island.escape | P4 | | E4303 io.buffer_in_flight | P3 | +| E2111 island.foreign_mutable_edge | P4 | | E5001 air.invalid_ssa | P0 | +| E3001 resource.use_after_consume | P2 | | E5002 air.invalid_cfg | P0 | +| E3002 resource.leak | P2 | | E5101 verifier.resource_limit | P0 | +| E6001 unsafe.required | P2 | | E6101 abi.unaligned_reference | P7 | -- task scopes; -- spawn/join; -- `Send` / `Share` derivation; -- scoped borrowing; -- bounded channels; -- mutex; -- cancellation; -- deterministic scheduler. +## Cross-cutting tracks -Exit criterion: parallel-map and channel ownership-transfer examples. +These run through all phases rather than belonging to one. -## Phase 4 — Islands +| Track | Rule | +|---|---| +| Spec | Each phase's first tasks update `../spec/` and the open-questions log. RFCs 0001–0004 move to Accepted in the phase that implements them (P1, P3, P5, P0 respectively). | +| Diagnostics | New codes are added to `../reference/error-codes.md` and `src/diag.zig` together; structured fields per code are documented in the spec section that defines the rule. | +| Determinism | Every run test is executed twice and compared from P0-12 on; concurrency tests add schedule stress from P3. | +| Audit reports | Each phase that adds an auditable fact (unsafe sites, effects, capabilities, weak atomics, eliminated checks) extends the report in `src/report/` (spec 10 §6, spec 13 §5). | +| Packages | Minimal `aji.toml` reading for capabilities in P2; dependencies, lockfile and sandboxed build extensions in P8 (spec 12). | -Deliver: +## Task conventions -- island allocator; -- `iref`; -- closure verification; -- move/transfer; -- freeze; -- `Frozen`. +- IDs are `P-` and never reused. A task split later becomes `P1-4a`, `P1-4b`. +- Status lives in the phase file's task table: `todo`, `doing`, `done`, `dropped`. Update it in the same change that completes the task. +- `Done when` is the acceptance test. If it cannot be checked mechanically, rewrite it. +- Discovered work goes into the current phase file as a new task, or into `../design/open-questions.md` if it is a spec gap. -Exit criterion: cyclic graph can move between tasks with no deep copy and no shared mutation. +## Status -## Phase 5 — Atomics and memory model - -Deliver: - -- atomic scalar types; -- all five orderings; -- fences; -- happens-before model in interpreter/testing tools; -- weak-atomic audit marking; -- schedule exploration. - -Exit criterion: atomic publication litmus/conformance tests. - -## Phase 6 — Source language - -Deliver: - -- source parser; -- source-to-AIR lowering; -- generics/monomorphization; -- contracts syntax; -- formatter. - -Exit criterion: all reference programs authored primarily as `.aji`. - -## Phase 7 — Native backend - -Deliver: - -- LLVM lowering; -- Linux x86_64; -- Linux aarch64; -- macOS aarch64; -- ABI tests. - -Exit criterion: interpreted and native executions pass the same conformance corpus. - -## Phase 8 — Agent protocol - -Deliver: - -- `ajid`; -- structured diagnostics; -- inspect/trace endpoints; -- machine-readable verifier state summaries; -- benchmark protocol. - -Exit criterion: an external coding agent can implement/repair a reference task using only the protocol and repository spec. +| Phase | Status | +|---|---| +| P0 | not started | +| P1–P8 | not started | diff --git a/docs/plan/phase-0-semantic-skeleton.md b/docs/plan/phase-0-semantic-skeleton.md index c305e45..8a90585 100644 --- a/docs/plan/phase-0-semantic-skeleton.md +++ b/docs/plan/phase-0-semantic-skeleton.md @@ -1,25 +1,41 @@ -# Phase 0 — Semantic skeleton: task breakdown +# Phase 0 — Semantic skeleton -Non-normative. Breaks Phase 0 of [`README.md`](README.md) into tasks small enough for one agent session each. +Non-normative. Part of the [implementation plan](README.md). -Exit criterion (from the plan): AIR `hello` and arithmetic tests execute identically across runs. +**Goal:** an executable core: AIR data model, text parser and serializer, CFG/SSA/type verification, and a deterministic interpreter for integer programs. -| ID | Task | Depends on | Output | Done when | -|---|---|---|---|---| -| P0-1 | Specify text AIR grammar | — | `docs/reference/air-text.ebnf`, updates to `docs/spec/07-air.md` | grammar covers module header, functions, `effects`, blocks with parameters, instructions, comments; seed tests in `tests/conformance/phase0` match it | -| P0-2 | AIR data model | P0-1 | `src/air.zig` (types, values, instructions, blocks, functions, module) | round-trips through P0-4 | -| P0-3 | Text AIR lexer + parser | P0-1, P0-2 | `src/air/parse.zig` | parse errors are diagnostics with spans; new parse codes registered in `error-codes.md` | -| P0-4 | Canonical serializer | P0-2 | `src/air/print.zig` | `parse ∘ print` is identity on the data model; output is byte-stable | -| P0-5 | CFG verifier | P0-3 | `src/verifier/cfg.zig` | `E5002` accept/reject tests pass | -| P0-6 | SSA/dominance verifier | P0-5 | `src/verifier/ssa.zig` | `E5001` accept/reject tests pass | -| P0-7 | Type verifier for integer ops, structs, enums | P0-3 | `src/verifier/types.zig` | `E1001` accept/reject tests pass | -| P0-8 | Verifier resource budget | P0-5 | budget in `src/verifier.zig` | `E5101` emitted deterministically; budget documented in spec 08 | -| P0-9 | Interpreter core | P0-6, P0-7 | `src/interp.zig` | arithmetic programs run; checked overflow traps per spec | -| P0-10 | `aji run` + run tests in conformance runner | P0-9 | `expect: run` header with expected stdout/trap | `hello` and arithmetic tests pass, output identical across 100 runs | +**Exit criterion:** AIR `hello` and arithmetic tests execute identically across runs. -## Open questions to resolve in P0-1 +**Spec inputs:** spec 00 §5–6, 01 §6, 02 §1–3, 07, 08 §1–2, §7, 10 §2, 11 §1. RFC 0004 moves to Accepted at the end of this phase. -- Comment syntax in text AIR (the conformance runner currently strips leading `;` lines itself). -- Spelling of constants (`const.u64 0` is provisional) and comparison results (`bool` vs `u1`). -- How `hello` reaches stdout before Phase 2 capabilities exist: a test-only intrinsic, or Phase 2 `io.write` brought forward. -- Whether parse errors get their own `E0xxx` range or join `E5xxx`. +**Blocking questions:** Q-001 grammar, Q-002 contracts, Q-003 parse codes, Q-004 traps, Q-005 budget, Q-006 target description, Q-007 integer edge cases, Q-008 `hello`, Q-016 floats. + +## Scope + +In: integer types, `bool`, `void`, `never`; structs, enums, fixed arrays as values; functions and direct calls; `br`, `cbr`, `switch`, `ret`, `trap`, `assert`; checked and wrapping arithmetic, bitwise ops, comparisons, explicit casts. + +Out: floats (deferred until Q-016 is answered), borrows, memory, effects other than `[]`, concurrency. + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P0-1 | todo | Specify text AIR grammar (Q-001) and parse-error codes (Q-003) | — | `docs/reference/air-text.ebnf`, spec 07, error-codes.md | grammar covers module header with version/feature bits, type declarations, functions, `effects`, blocks with parameters, instructions, comments; seed tests in `tests/conformance/phase0` conform to it | +| P0-2 | todo | Specify traps (Q-004), integer edge cases and casts (Q-007), target description (Q-006), verifier budget (Q-005), `hello` strategy (Q-008) | — | spec 01, 02, 08, 11 | each question marked resolved in `open-questions.md` | +| P0-3 | todo | Write contract tables for Phase 0 opcodes; add aggregate opcodes (struct/enum construct and access) if needed, via RFC 0004 amendment | P0-1 | spec 07 appendix | every in-scope opcode has all fields required by spec 07 §4 | +| P0-4 | todo | AIR data model | P0-1 | `src/air/{types,module,ops}.zig` | unit tests build the seed-test modules programmatically | +| P0-5 | todo | Text AIR lexer and parser | P0-4 | `src/air/parse.zig` | all seed tests parse; malformed input yields registered diagnostics with spans | +| P0-6 | todo | Canonical serializer | P0-4 | `src/air/print.zig` | `print(parse(x))` is a fixed point after one round; fuzz test on parser round-trip | +| P0-7 | todo | CFG verifier | P0-5 | `src/verifier/cfg.zig` | E5002 accept/reject tests pass (missing terminator, branch to unknown block, block-argument arity) | +| P0-8 | todo | SSA/dominance verifier | P0-7 | `src/verifier/ssa.zig` | E5001 accept/reject tests pass (undefined value, use not dominated, double definition) | +| P0-9 | todo | Type verifier | P0-5, P0-3 | `src/verifier/types.zig` | E1001 and E1002 accept/reject tests pass | +| P0-10 | todo | Deterministic verifier budget | P0-7 | `src/verifier/budget.zig` | E5101 test with an oversized module; budget value matches spec | +| P0-11 | todo | Interpreter core | P0-8, P0-9 | `src/interp/machine.zig` | arithmetic programs run; overflow, assert and explicit `trap` produce the trap records defined in P0-2 | +| P0-12 | todo | `aji run`; `expect: run` / `stdout:` / `trap:` in the conformance runner; double-run determinism check | P0-11 | `src/main.zig`, `tools/conformance.zig` | runner fails a test whose two runs differ | +| P0-13 | todo | Phase exit review | all | plan status, RFC 0004 status | `hello` and arithmetic suite pass; RFC 0004 marked Accepted; P0 status set to done | + +## Conformance tests to add + +- accept: arithmetic on every integer width; loops via block parameters; `switch`; nested calls; recursion. +- reject: E5001 ×3, E5002 ×3, E1001 (operand, result, block argument, return), E1002. +- run: checked overflow traps; wrapping does not trap; division by zero (per Q-007); `hello`. diff --git a/docs/plan/phase-1-ownership-and-memory.md b/docs/plan/phase-1-ownership-and-memory.md new file mode 100644 index 0000000..27068b2 --- /dev/null +++ b/docs/plan/phase-1-ownership-and-memory.md @@ -0,0 +1,38 @@ +# Phase 1 — Ownership and memory + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** safe single-threaded memory: `Own`, `ref`/`mut`, slices, initialization tracking, regions with generations, bounds and range facts. + +**Exit criterion:** the file-copy core (buffer handling, regions, slices) is implemented in AIR, and the verifier rejects representative use-after-move, aliasing and out-of-bounds cases. + +**Spec inputs:** spec 02 §4–5, 03 §1–11, 08 §3–6, 13 §2. RFC 0001 moves to Accepted (island sections may stay Proposed until P4). + +**Blocking questions:** Q-009 borrow lifetimes in AIR, Q-010 region generation checks. + +## Scope + +In: `move`, `copy`; `borrow.ref`, `borrow.mut`, `borrow.end`; `load`, `store`; `own.alloc`, `own.free`; `region.create`, `region.alloc`, `region.alloc_uninit`, `region.reset`, `region.destroy`; `slice.make`, `slice.sub`, split operations; `mem.copy`, `mem.zero`; `guard`; `Uninit`; `Option>`. + +Out: islands, `Arc`, `Pin`, raw addresses (beyond rejecting them in safe code). + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P1-1 | todo | Resolve Q-009 and Q-010; review RFC 0001 memory sections to Accepted | — | spec 03, 07, RFC 0001 | questions resolved; RFC status updated | +| P1-2 | todo | Contract tables for Phase 1 opcodes | P1-1 | spec 07 appendix | every in-scope opcode has all spec 07 §4 fields, including verifier transfer function | +| P1-3 | todo | Interpreter memory: allocations, provenance, bounds, region generations, uninitialized bytes | P1-2 | `src/interp/memory.zig` | unit tests: every access checks provenance; reading uninitialized bytes is detected in interpreter debug checks | +| P1-4 | todo | Initialization verifier | P1-2 | `src/verifier/init.zig` | E1010 accept/reject (scalar, struct field, array prefix) | +| P1-5 | todo | Ownership state machine | P1-2 | `src/verifier/ownership.zig` | E2001, E2002 accept/reject, including across branches and loops | +| P1-6 | todo | Borrow/alias verifier | P1-5 | `src/verifier/borrow.zig` | E2101, E2102 accept/reject; borrow ending on all paths | +| P1-7 | todo | Region lifetime and generation verifier | P1-6 | `src/verifier/region.zig` | E2104 accept/reject; reset with live reference rejected (spec 03 §8.2) | +| P1-8 | todo | Bounds and range facts; path sensitivity; `guard` | P1-6 | `src/verifier/bounds.zig` | E2103 accept/reject; check elimination after `if i < len` and after `guard` | +| P1-9 | todo | Slices and disjoint partitioning facts (`split_mut`) | P1-8 | verifier + interpreter | two disjoint `slice_mut` usable simultaneously; overlapping ones rejected with E2101 | +| P1-10 | todo | Structured diagnostic fields and repair candidates for E2xxx | P1-5…P1-9 | `src/diag.zig`, spec 10 | snapshot tests on full JSON for each E2xxx code, matching the spec 10 §2 example shape | +| P1-11 | todo | Report: remaining runtime checks and eliminated bounds checks | P1-8 | `src/report/checks.zig` | `aji check --report` lists checks per function, deterministic order | +| P1-12 | todo | Phase exit review | all | `tests/programs/file-copy-core/` | file-copy core runs; negative corpus for use-after-move, overlapping borrows, region reset with live reference, prior generation use, OOB all pass | + +## Conformance tests to add + +Negative corpus entries from `conformance-suite.md` owned by this phase: use after move, overlapping mutable borrows, region reset with live reference, use of prior region generation. Plus E1010, E2002, E2102, E2103. diff --git a/docs/plan/phase-2-effects-capabilities-resources.md b/docs/plan/phase-2-effects-capabilities-resources.md new file mode 100644 index 0000000..42ec207 --- /dev/null +++ b/docs/plan/phase-2-effects-capabilities-resources.md @@ -0,0 +1,38 @@ +# Phase 2 — Effects, capabilities and resources + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** authority and external resources become verifiable: effect sets, unforgeable capabilities with narrowing, linear resources with typestate, capability-gated runtime intrinsics, unsafe boundaries. + +**Exit criterion:** safe file-copy and a basic (single-task) TCP echo run in the interpreter. + +**Spec inputs:** spec 05, 06, 09 §1–3, 12 §1, 13 §3–5; `reference/intrinsics.md`. + +**Blocking questions:** Q-011 effect hierarchy, Q-012 capability representation, Q-018 runtime diagnostics. + +## Scope + +In: effect declarations and transitive checking; `cap<…>` values, delegation and narrowing; linear `File`, `Socket` with typestate; `resource.consume`; `intrinsic.call`; explicit cleanup edges; `unsafe` boundaries in AIR; filesystem, console, network, clock and random intrinsics; `hosted` and `deterministic` profiles for I/O. + +Out: tasks, threads, async I/O (P3); FFI to native code (P7). + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P2-1 | todo | Resolve Q-011, Q-012, Q-018 | — | spec 05, 07, 10 | questions resolved; runtime record format defined | +| P2-2 | todo | Formal signatures for fs, io, net, clock, random intrinsics | P2-1 | `reference/intrinsics.md` | each intrinsic lists types, effects, capabilities, ownership, failure, blocking (spec 09 §2) | +| P2-3 | todo | Contract tables for `intrinsic.call`, `resource.consume`, `call.indirect` | P2-1 | spec 07 appendix | all spec 07 §4 fields present | +| P2-4 | todo | Effect verifier | P2-1 | `src/verifier/effects.zig` | E3101 accept/reject, including transitive callees | +| P2-5 | todo | Capability verifier: unforgeability, narrowing, transfer rules | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject | +| P2-6 | todo | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected | +| P2-7 | todo | Unsafe boundary verifier | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject | +| P2-8 | todo | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs | +| P2-9 | todo | Entry-point capability instantiation from `aji.toml` `[capabilities]` | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) | +| P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test | +| P2-11 | todo | Reference programs: hello (real `io.write` if deferred from P0), file-copy, tcp-echo (single task) | P2-8 | `tests/programs/` | all three run; cleanup on every error path verified | +| P2-12 | todo | Phase exit review | all | plan status | exit criterion passes | + +## Conformance tests to add + +Negative corpus entries owned by this phase: missing capability, undeclared effect, linear resource leak. Plus E3001, E3202, E6001. diff --git a/docs/plan/phase-3-structured-concurrency.md b/docs/plan/phase-3-structured-concurrency.md new file mode 100644 index 0000000..a18eae3 --- /dev/null +++ b/docs/plan/phase-3-structured-concurrency.md @@ -0,0 +1,42 @@ +# Phase 3 — Structured concurrency + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** tasks that cannot outlive their scopes, ownership transfer through bounded channels, synchronized shared state, cooperative cancellation, and a deterministic scheduler. + +**Exit criterion:** `parallel_map` and `channel_transfer` examples run under deterministic and randomized schedules. + +**Spec inputs:** spec 04 §1–19, 11 §3, §5–6. RFC 0002 moves to Accepted. + +**Blocking questions:** Q-013 deterministic `select` and seeds, Q-014 Send/Share for capability-holding aggregates. + +## Invariants (AGENTS.md change checklist applies to every task here) + +- no child task outlives its scope; no silent detachment; +- values moved into migratable tasks are `Send`; concurrently read values are `Share`; +- concurrent mutable borrows are proven disjoint; +- buffers owned by in-flight async operations are inaccessible; +- every interpreter run is reproducible from its seed. + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P3-1 | todo | Resolve Q-013, Q-014; RFC 0002 to Accepted | — | spec 04, 11 | questions resolved | +| P3-2 | todo | Contract tables: `task.*`, `thread.*`, `channel.*`, `mutex.*`, `rwlock.*`, select | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects | +| P3-3 | todo | Deterministic scheduler: seeds, choice points, choice log | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run | +| P3-4 | todo | Send/Share/Local derivation | P3-1 | `src/verifier/send_share.zig` | E4001, E4002 accept/reject | +| P3-5 | todo | Task-scope verifier and scoped borrows | P3-2 | `src/verifier/tasks.zig` | E4301, E4302 accept/reject | +| P3-6 | todo | Concurrent alias / data-race rejection | P3-5 | `src/verifier/borrow.zig` | E4101 accept/reject; disjoint `split_mut` halves accepted in two tasks | +| P3-7 | todo | Interpreter tasks: spawn, join, cancel, cancellation points, shields, task failure | P3-3 | `src/interp/` | cancellation observed only at defined points; shield defers it | +| P3-8 | todo | Bounded and rendezvous channels with ownership transfer | P3-7 | interpreter + verifier | sender cannot use moved message (E2001); capacity 0 rendezvous test | +| P3-9 | todo | Mutex and RwLock with linear guards | P3-7 | interpreter + verifier | guard not `Send`; unlock consumes guard; E3002 on leaked guard | +| P3-10 | todo | Async I/O buffer claims | P3-7 | verifier + runtime | E4303 accept/reject | +| P3-11 | todo | Blocking effect and blocking pool policy | P3-7 | spec 04 §18, runtime | `thread.block` from ordinary task handled per spec | +| P3-12 | todo | Runner: `seed:`/`schedules:` headers; stress modes (1/2/N workers, random, forced yield, slow consumer, cancellation during waits, I/O reordering) | P3-3 | `tools/conformance.zig` | stress modes selectable; failing seed printed for replay | +| P3-13 | todo | Reference programs: parallel-map, channel transfer, tcp-echo with tasks | P3-8, P3-9 | `tests/programs/` | pass under all stress modes | +| P3-14 | todo | Phase exit review | all | plan status | exit criterion passes | + +## Conformance tests to add + +Negative corpus entries owned by this phase: non-Send transfer, non-Share concurrent read, task escape, async buffer use while in flight. Plus E4101, E4302. Scheduler tests for every synchronization primitive (testing policy in AGENTS.md). diff --git a/docs/plan/phase-4-islands.md b/docs/plan/phase-4-islands.md new file mode 100644 index 0000000..af1a2f8 --- /dev/null +++ b/docs/plan/phase-4-islands.md @@ -0,0 +1,36 @@ +# Phase 4 — Islands + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** uniquely owned closed mutable graphs that move between tasks in O(1), and irreversible freezing into shareable immutable graphs. + +**Exit criterion:** a cyclic graph moves between tasks with no deep copy and no shared mutation (`island-pipeline` reference program). + +**Spec inputs:** spec 03 §12–15, 04 §13; RFC 0001 island sections move to Accepted. + +**Blocking questions:** none recorded; log new ones before starting. + +## Invariants + +- `iref` points only inside its own island and is never dereferenced without access to the owning island; +- an island has no edges into foreign mutable memory; +- after transfer the sender holds nothing that reaches the island; +- a `Frozen` never yields a mutable reference in safe code; +- reference counts change only through explicit `arc.clone` / `arc.release`. + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P4-1 | todo | Contract tables: `island.create`, `island.alloc`, `island.freeze`, `iref` access, `arc.clone`, `arc.release` | — | spec 07 appendix | all spec 07 §4 fields present | +| P4-2 | todo | Island allocator in the interpreter (private regions, O(1) transfer) | P4-1 | `src/interp/memory.zig` | transfer cost independent of graph size (unit benchmark with fixed bound) | +| P4-3 | todo | `iref` verifier and closure checks | P4-1 | `src/verifier/island.zig` | E2110, E2111 accept/reject | +| P4-4 | todo | Island transfer through channels and task spawn; sender invalidation | P4-3 | verifier + interpreter | sender use after send rejected (E2001) | +| P4-5 | todo | Freeze and `Frozen`; Share/Send derivation | P4-3 | verifier + interpreter | concurrent reads of frozen graph accepted; mutable access rejected | +| P4-6 | todo | `Arc` for `Share` values | P4-5 | verifier + interpreter | `Arc` of non-`Share` rejected (E4002); count changes visible in trace | +| P4-7 | todo | Reference program: island-pipeline | P4-4, P4-5 | `tests/programs/island-pipeline/` | passes under all P3 stress modes | +| P4-8 | todo | Phase exit review | all | plan status, RFC 0001 | exit criterion passes; RFC 0001 fully Accepted | + +## Conformance tests to add + +Negative corpus entry owned by this phase: island internal reference escape. Plus E2111, freeze-then-mutate, `Arc` of non-`Share`. diff --git a/docs/plan/phase-5-atomics-and-memory-model.md b/docs/plan/phase-5-atomics-and-memory-model.md new file mode 100644 index 0000000..276f0cf --- /dev/null +++ b/docs/plan/phase-5-atomics-and-memory-model.md @@ -0,0 +1,37 @@ +# Phase 5 — Atomics and memory model + +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. + +**Spec inputs:** spec 04 §20–32, 11; `reference/concurrency-litmus.md`. RFC 0003 moves to Accepted. + +**Blocking questions:** Q-015 operational weak-memory model, Q-017 replay format. + +## Invariants + +- no atomic operation without an explicit, valid ordering; +- safe code never accesses atomic storage as ordinary storage; +- DRF-SC holds for programs without ordinary-memory races; +- the interpreter neither forbids allowed outcomes (SB `r1=0,r2=0`) nor produces forbidden ones (MP). + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P5-1 | todo | Resolve Q-015, Q-017; RFC 0003 to Accepted | — | spec 04, 11 | questions resolved | +| 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-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-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-10 | todo | Phase exit review | all | plan status | exit criterion passes | + +## Conformance tests to add + +Negative corpus entry owned by this phase: invalid atomic ordering. Litmus: MP, SB, mutex handoff, channel handoff, spawn/join, invalid ordinary race. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md new file mode 100644 index 0000000..e7b912d --- /dev/null +++ b/docs/plan/phase-6-source-language.md @@ -0,0 +1,26 @@ +# Phase 6 — Source language + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** `.aji` source that lowers deterministically and explicitly to AIR, with diagnostics mapped back to source spans. + +**Exit criterion:** all reference programs and `examples/` are authored primarily as `.aji` and pass the conformance corpus through the frontend. + +**Spec inputs:** spec 01, 02, 03 §4, 06 §3–4, 13 §1–2; `reference/grammar.ebnf`. + +**Rule:** a source feature is acceptable only if its lowering to AIR is deterministic, explicit and mechanically verifiable (spec 01 §8). The frontend is outside the TCB; the verifier still checks its output. + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P6-1 | todo | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous | +| P6-2 | todo | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics | +| P6-3 | todo | Modules, imports, name resolution | P6-2 | `src/frontend/resolve.zig` | unresolved names produce registered diagnostics | +| P6-4 | todo | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/types.zig` | generic code instantiates deterministically; constraint violations diagnosed | +| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) | +| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN | +| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code | +| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST | +| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes | +| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes | diff --git a/docs/plan/phase-7-native-backend.md b/docs/plan/phase-7-native-backend.md new file mode 100644 index 0000000..46802e9 --- /dev/null +++ b/docs/plan/phase-7-native-backend.md @@ -0,0 +1,25 @@ +# Phase 7 — Native backend + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** verified AIR compiled to native code through LLVM, with a native runtime whose behavior matches the interpreter. + +**Exit criterion:** interpreted and native executions pass the same conformance corpus on Linux x86_64, Linux aarch64 and macOS aarch64. + +**Spec inputs:** spec 00 §6, 07 §6–7, 09. + +**Rule:** native code is produced only from verified safe AIR (spec 07 §7). Optimizations may remove checks only when their failure is provably impossible (spec 00 §6). + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P7-1 | todo | Decide LLVM integration (emit textual `.ll` and invoke an external `clang`/`llc`, or link the LLVM C API); record as DD | — | `design/decisions.md` | decision recorded with TCB and reproducibility rationale | +| P7-2 | todo | Freeze opcode numbering for 0.1; binary AIR format | — | spec 07 §6, `src/air/binary.zig` | binary ↔ text round-trip; version and feature bits encoded (spec 00 §5) | +| P7-3 | todo | AIR → LLVM lowering for P0–P2 features | P7-1 | `src/backend/llvm/` | P0–P2 corpus passes natively on Linux x86_64 | +| P7-4 | todo | Native runtime: allocator adapters, regions, islands, traps, capability materialization, I/O | P7-3 | `src/runtime/native/` | runtime is listed in the unsafe report; no hidden allocation | +| P7-5 | todo | Native scheduler, synchronization primitives, atomics lowering | P7-4 | backend + runtime | P3–P5 corpus and litmus pass natively | +| P7-6 | todo | FFI (`extern "C"`), `@repr(C)`, `@align`, packed fields | P7-3 | backend | E6101 accept/reject; ABI tests against C | +| P7-7 | todo | Targets: Linux aarch64, macOS aarch64 | P7-5 | CI matrix | corpus passes on all three targets | +| P7-8 | todo | Parity runner: interpreter vs native on the full corpus | P7-5 | `zig build parity` | identical stdout and trap records | +| P7-9 | todo | Phase exit review | all | plan status | exit criterion passes | diff --git a/docs/plan/phase-8-agent-protocol.md b/docs/plan/phase-8-agent-protocol.md new file mode 100644 index 0000000..56bedf5 --- /dev/null +++ b/docs/plan/phase-8-agent-protocol.md @@ -0,0 +1,23 @@ +# Phase 8 — Agent protocol + +Non-normative. Part of the [implementation plan](README.md). + +**Goal:** a long-running machine interface (`ajid`) and audit artifacts that let an external coding agent implement and repair Aji programs without reading prose diagnostics; a benchmark that measures whether Aji achieves its mission. + +**Exit criterion:** an external coding agent implements or repairs a reference task using only the protocol and the repository spec. + +**Spec inputs:** spec 10, 12, 13 §5; `plan/conformance-suite.md` (agent benchmark). + +## Tasks + +| ID | Status | Task | Depends | Output | Done when | +|---|---|---|---|---|---| +| P8-1 | todo | Specify `ajid` transport and method schemas (parse, typecheck, verify, compile, run, test, trace, inspect, explain, benchmark) | — (may start after P2) | spec 10 | request/response schemas versioned and published | +| P8-2 | todo | `ajid` server over `check.zig`: parse, typecheck, verify, run, test | P8-1 | `src/ajid/` | protocol conformance tests; responses deterministic | +| P8-3 | todo | `trace` and `inspect`: verifier state summaries per value and instruction | P8-2 | `src/ajid/` | an agent can query ownership/borrow state at any instruction | +| P8-4 | todo | `explain` and repair-candidate coverage for every registry code | P8-2 | `src/diag.zig`, spec 10 | every code has structured fields and at least one repair candidate kind | +| P8-5 | todo | Verification report artifact (spec 10 §6) combining all `src/report/` outputs | P8-2 | `aji report` | single deterministic JSON document; schema documented | +| 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 | Benchmark harness: Aji vs Zig, Rust, C on shared task specs | P8-2 | `bench/` | records P(correct \| one iteration), iterations, tokens, defects | +| P8-8 | todo | External agent trial on a reference task | P8-2…P8-5 | trial report in `docs/plan/` | exit criterion passes | +| P8-9 | todo | Phase exit review; Aji 0.1 release-candidate checklist | all | plan status | all phases done; spec status updated |