diff --git a/docs/agent/bundle.txt b/docs/agent/bundle.txt index bf28fe8..3d30f2c 100644 --- a/docs/agent/bundle.txt +++ b/docs/agent/bundle.txt @@ -32,6 +32,12 @@ docs/spec/08-verifier.md :: ## 12. Bounds facts docs/spec/08-verifier.md :: ## 13. Initialization docs/spec/08-verifier.md :: ## 14. Stage order +# Tasks, loans, Send/Share, scheduler +docs/spec/04-concurrency-and-atomics.md :: ## 33. Tasks in AIR +docs/spec/04-concurrency-and-atomics.md :: ## 34. Lending borrows to tasks +docs/spec/04-concurrency-and-atomics.md :: ## 35. Send and Share in AIR +docs/spec/04-concurrency-and-atomics.md :: ## 36. The deterministic scheduler + # Effects, capabilities, intrinsics docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index b2b07b3..239276d 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -19,7 +19,7 @@ Status values: `open`, `resolved`. | Q-011 | resolved | P2 | Effect hierarchy and discharge | | Q-012 | resolved | P2 | Capability representation and host instantiation | | Q-013 | open | P3 | Deterministic `select` rule and scheduler seed | -| Q-014 | open | P3 | `Send`/`Share` derivation for aggregates holding capabilities | +| Q-014 | resolved | P3 | `Send`/`Share` derivation for aggregates holding capabilities | | Q-015 | open | P5 | Operational weak-memory model for the interpreter | | Q-016 | open | P0 | Floating-point determinism | | Q-017 | open | P5 | Replay file format | @@ -111,6 +111,8 @@ Spec 04 §14 and spec 11 §6 require a stable rule in deterministic mode but do Spec 02 §6 derives properties structurally; spec 05 §5 says capability types define their own transfer rules. Undecided: the derivation for a struct mixing ordinary fields with `Local` or move-only capabilities. +**Resolved (RFC 0011):** `Send`/`Share` are structural; every capability kind is `Send` and `Share`, so an aggregate holding capabilities is `Send`/`Share` exactly when its other members are (spec 04 §35). + ## Q-015 — Operational weak-memory model 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. diff --git a/docs/reference/air-features.md b/docs/reference/air-features.md index b0553e2..860d6d0 100644 --- a/docs/reference/air-features.md +++ b/docs/reference/air-features.md @@ -44,7 +44,9 @@ Declaring `features [capabilities, effects, ownership]` grants no authority. It | `resource_joins` | reserved | — | `capabilities`, `effects`, `ownership`, `resources` | joins whose incoming edges carry different resource states (spec 06 §6.3); unscheduled | | `resources` | published | 2 | `capabilities`, `effects`, `ownership` | linear resources `file`, `file`, `file`, `listener`, `stream`; built-in `io_error`; I/O intrinsics (spec 06 §6–§7, `reference/intrinsics.md`) | | `sync` | reserved | 3 | `ownership` | `Mutex`, `RwLock`, linear guards | -| `tasks` | reserved | 3 | `ownership` | structured task scopes, spawn/join/cancel, `Send`/`Share` | +| `tasks` | published | 3 | `ownership` | `scope`, `task`, `task.*`, loans, `Send`/`Share`, deterministic scheduler (spec 04 §33–§36) | +| `task_borrow_returns` | reserved | — | `ownership`, `tasks` | spawned functions returning borrows; unscheduled | +| `task_transfer` | reserved | — | `ownership`, `tasks` | `scope` and `task` as parameters, return types, aggregate members or heap contents; unscheduled | | `unsafe` | published | 2 | `arrays`, `effects`, `ownership` | `assume`, `borrow.index.unchecked`, the `trusted` boundary, the effect `unsafe` (spec 13 §6–§8) | `capabilities` depends on `effects` so that every module that can perform an external operation is also effect-checked. diff --git a/docs/rfcs/0011-structured-tasks.md b/docs/rfcs/0011-structured-tasks.md index a447109..0d02294 100644 --- a/docs/rfcs/0011-structured-tasks.md +++ b/docs/rfcs/0011-structured-tasks.md @@ -1,8 +1,9 @@ # RFC 0011: Structured Tasks and the Deterministic Scheduler -Status: Proposed (revision 2: owner review items 1–10 applied) +Status: Accepted (revision 2, after owner review items 1–10) Scope: AIR format 0, feature `tasks` Language version: 0.1 +Integrated into: spec 04 §33–§36; spec 02 §6; spec 07a; spec 08 §14; spec 11 §7.2; `reference/air-features.md`; `docs/agent/bundle.txt` Supersedes: — Resolves: Q-014 (`Send`/`Share` for aggregates holding capabilities). Realizes spec 04 §2–§6, §15 (in part), §17 and spec 11 §5, §7.2 for tasks. Channels, mutexes, `select` (Q-013), waiting cancellation points and shields follow in RFC 0012. diff --git a/docs/spec/02-types-and-values.md b/docs/spec/02-types-and-values.md index 2c84624..30c743a 100644 --- a/docs/spec/02-types-and-values.md +++ b/docs/spec/02-types-and-values.md @@ -125,7 +125,7 @@ The compiler derives: - `Freeze`: can be converted to deeply immutable state; - `Local`: tied to its current execution context. -These are semantic properties, not user-extensible traits in v0.1. +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. Manual unsafe declarations MAY exist only for FFI/runtime wrappers and MUST state proof obligations. diff --git a/docs/spec/04-concurrency-and-atomics.md b/docs/spec/04-concurrency-and-atomics.md index 2c6fde1..64661a4 100644 --- a/docs/spec/04-concurrency-and-atomics.md +++ b/docs/spec/04-concurrency-and-atomics.md @@ -338,3 +338,138 @@ Libraries may document an implementation as blocking, obstruction-free, lock-fre Core Aji does not guarantee deadlock freedom, livelock freedom, starvation freedom or scheduler fairness. Optional verification profiles may establish stronger properties for restricted programs. + +## 33. Tasks in AIR (feature `tasks`) + +Decision record: RFC 0011. + +Invariants: + +1. **Structure.** A task never outlives the scope that spawned it: a scope cannot end while a task spawned from it is unjoined, and the entry function cannot return while any scope is live. There is no detachment. +2. **No data races on ordinary memory.** Memory reachable by two tasks at once is reachable only through shared borrows of `Share` data, or through exclusive borrows of provably disjoint places. A borrow lent to a task stays lent until the task is joined. +3. **Send/Share soundness.** A value moved into a task is `Send`; data observed through a shared borrow from several tasks is `Share`. +4. **Reproducibility.** For a given module, inputs, grants, seed and quantum, the schedule — and therefore the run record — is identical on every run. +5. **Exhaustive interleaving semantics.** A program's meaning does not depend on the scheduler beyond what its synchronization allows; schedule exploration may run any interleaving the scheduler can produce. +6. **Local verification.** Task handles, scopes and loans never leave the function that created them, so all concurrency checks stay intraprocedural. +7. **Bounded concurrency.** The deterministic profile bounds the number of live tasks independently of host memory. + +Depends on `ownership`. + +### 33.1 Types + +| Type | Meaning | Class | +|---|---|---| +| `scope` | a structured task scope | linear, function-bound | +| `task` | handle of a task that returns `T` | linear, function-bound; consumed by `task.join` | + +**Function-bound.** A `scope` or `task` may be passed between blocks of the function that created it (as a block argument) and used by `task.*`. It may not be a function parameter, a return type, an aggregate member, or stored in heap or region memory; those uses belong to the reserved feature `task_transfer` (`E0006` reason `feature_not_declared`). Keeping handles in their function keeps loans intraprocedural (invariant 6). + +**Result type.** `task` requires `T: Send`, and `T` must not transitively contain a borrow, a `scope` or a `task<…>`. A spawned function returning a borrow (for example one derived from a lent argument) belongs to the reserved feature `task_borrow_returns` (`E0006`): after `join`, whether the loan ends or continues as the returned borrow is deliberately left undefined in format 0. + +### 33.2 Instructions + +| Instruction | Operands → result | Effect | Verifier | Runtime | +|---|---|---|---|---| +| `%s = task.scope.begin` | → `scope` | — | — | opens a scope | +| `%t = task.spawn %s, @f(%a…)` | `scope`, arguments of `@f` → `task` (`T` = return type of `@f`) | `task.spawn` | arguments checked like a `call`; argument rules of §35; borrow arguments are lent until `task.join` (§34); `effects(@f) ⊆ effects(caller)` (`E3101`); result rules of §33.1 | takes a task slot (§36.3), creates a runnable task; a scheduling point | +| `[%r =] task.join %t` | `task` (consumed) → `T` | — | ends the loans of the task (§34) | waits until the task returned, frees its slot; a scheduling point | +| `task.cancel %t` | `task` (not consumed) | — | — | sets the task's cancellation-request flag; a scheduling point | +| `%c = task.cancelled` | → `bool` | — | — | whether the current task's flag is set; a scheduling point | +| `task.scope.end %s` | `scope` (consumed) | — | every task spawned from `%s` must be joined on every path (`E4301`) | closes the scope | + +**Cancellation is a request only** (spec 04 §15). `task.cancel` does not consume the handle, does not stop the task, does not release its resources and does not return its loans. Only `task.join` consumes the handle and returns the loans, and `task.scope.end` requires every child to be *joined*, not merely cancelled. `task.cancelled` reads the current task's flag; RFC 0012 adds cancellation points to waiting operations. + +**A trap in any task terminates the whole execution** with that trap record (spec 01 §6). There is no recoverable task failure in format 0: `task.join` never reports a trapped child, so no unwinding or cleanup semantics for the child's resources are needed. Expected failure is a value the task returns. + +### 33.3 Linearity and structure + +- `task` handles and scopes follow the linear rules of spec 06 §6 (`E3002` if never consumed). A live task handle at `task.scope.end` of its scope is `E4301` (`task.live_child_escape`), reported in preference to `E3002`. +- A scope is ended in the function that began it; `ret` with a live scope is `E3002`. + +## 34. Lending borrows to tasks + +A borrow argument of `task.spawn` is **lent to the task** from the spawn until the `task.join` that consumes the handle. Its state machine is: + +```text +LIVE --spawn--> LOANED(task) --join--> LIVE --borrow.end--> ENDED +``` + +The state is static: a borrow stays `LOANED` until the `join`, even if the child has already finished at runtime, so the model is independent of the scheduler. + +While `LOANED`: + +- for the verifier it behaves as a live child borrow of the argument, owned by the task handle, with the argument's mode and path; +- ending the argument borrow, or any ancestor of it, while the task is live is `E4302` (`task.borrow_escape`); +- an access or a new borrow that conflicts with a loan of a live task is `E4101` (`concurrency.possible_data_race`) rather than `E2101`, since the other party runs concurrently; +- lending the same exclusive borrow, or overlapping exclusive borrows, to two live tasks is `E4101`; lending disjoint places (different fields, the halves of a `slice.split`, different region allocations) is accepted. + +Example: two workers square the two halves of one buffer in parallel; both loans end at the joins. + +## 35. Send and Share in AIR + +`Send` and `Share` are derived structurally (spec 02 §6), with these base cases in format 0: + +| Type | Send | Share | +|---|---|---| +| integers, `bool`, built-in enums | yes | yes | +| `cap` (every kind) | yes | yes — the authority object is shared and its host side is synchronized | +| `file<…>`, `listener`, `stream` | yes | no | +| `own`, `own_array` | if `T` is | if `T` is | +| `region` | yes | no — allocation through a shared borrow mutates the region | +| `ref` | if `T` is `Share` | if `T` is `Share` | +| `mut` | if `T` is `Send` | no | +| `slice` / `slice_mut` | as `ref` / `mut` | as `ref` / `mut` | +| `task`, `scope` | no (`Local`) | no | +| struct, enum, array | if every field/payload/element is | if every field/payload/element is | + +So an aggregate holding capabilities is `Send` and `Share` exactly when its other members are (Q-014). + +Argument rules at `task.spawn`: + +```text +moved T → T: Send otherwise E4001 (concurrency.not_send) +ref → T: Share otherwise E4002 (concurrency.not_share) +mut → T: Send otherwise E4001 +``` + +(`slice` and `slice_mut` follow `ref` and `mut`.) Handing a borrow to another task is sending or sharing what it points to. + +## 36. The deterministic scheduler + +### 36.1 Model + +In both profiles of the reference interpreter, tasks are cooperative execution units on one host thread. A task runs until it reaches a **scheduling point** — `task.spawn`, `task.join`, `task.cancel`, `task.cancelled`, a waiting operation (RFC 0012, 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). + +The `hosted` profile uses the same cooperative scheduler on one host thread; in format 0 a blocking host I/O call blocks every task until it returns (task-aware I/O is later work). + +### 36.2 Choice rule (deterministic profile) + +Runnable tasks are kept in increasing order of creation. At each scheduling point the scheduler draws `x = next()` from the **schedule generator** and resumes runnable task number `x mod n` (the current task counts if it is still runnable). + +The schedule generator is the generator of spec 11 §8.1, seeded with the **schedule seed**. It is a stream independent of the program's `random.fill` stream (seeded with `--seed`): + +```text +--seed N program randomness (random.fill) +--schedule-seed M scheduler choices; default: seed XOR 0x5343484544554c45 ("SCHEDULE") +``` + +Varying the schedule seed while keeping `--seed` explores interleavings without changing the program's inputs. + +### 36.3 Quantum and fuel + +- One executed AIR instruction is one fuel unit and one quantum step; there is a single definition of "instruction executed". +- `--quantum N` (default 1 000) bounds the instructions a task executes between scheduling points; reaching it is a scheduling point. The quantum is an execution parameter like fuel, recorded in the run record, never a semantic property. +- Order at every instruction: the instruction begins → its fuel unit is consumed → it completes or blocks → its effects become visible → if it is a scheduling point (or ends the quantum), the scheduler decides. A blocked instruction consumes its fuel unit once, when it first begins; when its task resumes, it completes without consuming fuel again. While a task waits, its quantum is irrelevant. +- Fuel counts the instructions of all tasks together (spec 11 §7.2). +- **Task limit.** The deterministic profile has `max_task_slots`, default 1 024, set with `--task-limit N`. A slot is taken by a successful `task.spawn` and freed by its `task.join`; a finished but unjoined task still holds its slot. A spawn that would exceed the limit ends the run with the environment outcome `{"status":"limit_exceeded","kind":"tasks","limit":N}` (exit code 5, like fuel); it is not a trap. +- Quiescence (spec 11 §8): if every unfinished task waits and no future event can wake one, the run ends `blocked` — for example a task joining a task that waits on it. + +### 36.4 Run record + +The record of a run that spawned tasks adds `"schedule":{"seed":S,"quantum":Q,"choices":C}`, where `S` is the schedule seed and `C` the number of scheduler choices made; two runs with equal records made the same choices. + +### 36.5 Schedule exploration + +The conformance runner gains `schedules: N`: the test runs with schedule seeds `0 … N−1` and an unchanged program seed, and every run must satisfy the expectation. Systematic exploration (DPOR) is Phase 5 work. diff --git a/docs/spec/07a-air-instructions.md b/docs/spec/07a-air-instructions.md index f4e26bc..e50e14b 100644 --- a/docs/spec/07a-air-instructions.md +++ b/docs/spec/07a-air-instructions.md @@ -255,6 +255,10 @@ Instructions, budget accounting and verifier rules: spec 03 §18–§20. Summary Allowed only in functions that declare the effect `unsafe` or are `trusted` (`E6001`, spec 13 §6.4). +## Feature `tasks` + +Types `scope` and `task` (linear, function-bound), instructions `task.scope.begin`, `task.spawn %s, @f(…)`, `task.join`, `task.cancel`, `task.cancelled`, `task.scope.end`; loans, `Send`/`Share` and the scheduler: spec 04 §33–§36. + ## 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: diff --git a/docs/spec/08-verifier.md b/docs/spec/08-verifier.md index cbf30c6..22447e5 100644 --- a/docs/spec/08-verifier.md +++ b/docs/spec/08-verifier.md @@ -243,4 +243,4 @@ A `local` is uninitialized after `local.alloc` and becomes initialized by `lo ## 14. Stage order -Verification stages run in this order, stopping after the first stage that reports an error (spec 07 §8.6): resource limits (including value and frame size), CFG structure (including `local.alloc` placement), SSA, types (including capability kinds and narrowing forms), effects, unsafe boundaries (spec 13 §6.4), initialization, borrows, bounds. +Verification stages run in this order, stopping after the first stage that reports an error (spec 07 §8.6): resource limits (including value and frame size), CFG structure (including `local.alloc` placement), SSA, types (including capability kinds and narrowing forms), effects, unsafe boundaries (spec 13 §6.4), initialization, borrows (including task loans and scope structure, spec 04 §33–§34), bounds. diff --git a/docs/spec/11-determinism-and-replay.md b/docs/spec/11-determinism-and-replay.md index 551fb75..99c17ff 100644 --- a/docs/spec/11-determinism-and-replay.md +++ b/docs/spec/11-determinism-and-replay.md @@ -94,7 +94,7 @@ Running without a fuel limit is permitted (for example `aji run program.air`). C ### 7.2 Concurrent execution (from Phase 3) -With several tasks, fuel is global: the sum of instructions executed by all tasks. Two further, separate budgets apply to scheduling and MUST NOT be conflated with fuel: +With several tasks, fuel is global: the sum of instructions executed by all tasks (one executed instruction is one fuel unit and one quantum step; spec 04 §36.3). Two further, separate budgets apply to scheduling and MUST NOT be conflated with fuel: | Budget | Bounds | |---|---| @@ -102,6 +102,8 @@ With several tasks, fuel is global: the sum of instructions executed by all task | schedule budget | how many interleavings schedule exploration examines | | quantum | how many instructions a task executes before a forced scheduling point | +The scheduler, its choice rule, the schedule seed (independent of the program seed), the task limit and the run-record fields are specified in spec 04 §36. + ## 8. Execution profiles Decision record: RFC 0007.