From ab5814a7bb56f69e84ce40205d6742fe84329b11 Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 16:02:03 +0300 Subject: [PATCH] Phase 3: structured tasks and the deterministic scheduler (RFC 0011) - interpreter core rewritten around explicit per-task frame stacks so a task can be suspended at any instruction; behavior of all existing tests unchanged - tasks: scope and task (function-bound; task_transfer and task_borrow_returns reserved), spawn/join/cancel/cancelled/scope.end; cooperative scheduler with seeded choice rule, separate schedule seed, quantum = fuel unit, task limit (limit_exceeded kind tasks), global quiescence over waiting tasks; schedule field in the run record - verifier: Send/Share table (E4001, E4002), loans as task-owned borrows (E4302 on early end, E4101 on conflicts), E4301 at scope end, task effects (E3101) - CLI --quantum, --task-limit, --schedule-seed; runner schedules:, quantum:, task_limit:, limit_exceeded: - fixed: schedule seed default used orelse/^ precedence wrongly - 15 phase-3 conformance tests; 4000 mutants without a crash - Agent Reference Bundle +10.9 % tokens (recorded) --- AGENTS.md | 2 +- docs/agent/README.md | 3 +- docs/agent/history.json | 16 + docs/plan/phase-3-structured-concurrency.md | 18 +- docs/rfcs/0011-structured-tasks.md | 1 + src/air/features.zig | 7 +- src/air/module.zig | 32 +- src/air/parse.zig | 47 ++- src/air/print.zig | 17 + src/interp/machine.zig | 296 ++++++++++++++---- src/main.zig | 10 +- src/verifier/borrow.zig | 52 +++ src/verifier/budget.zig | 2 +- src/verifier/effects.zig | 14 + src/verifier/types.zig | 102 +++++- .../phase3/accept/tasks_disjoint_halves.air | 71 +++++ .../phase3/reject/tasks_access_lent.air | 71 +++++ .../phase3/reject/tasks_borrow_return.air | 23 ++ .../phase3/reject/tasks_end_lent_borrow.air | 68 ++++ .../reject/tasks_handle_as_parameter.air | 13 + .../phase3/reject/tasks_not_send.air | 32 ++ .../phase3/reject/tasks_not_share.air | 29 ++ .../phase3/reject/tasks_same_mut_twice.air | 70 +++++ .../reject/tasks_scope_end_unjoined.air | 21 ++ .../reject/tasks_spawn_without_effect.air | 22 ++ .../phase3/run/tasks_cancel_request.air | 31 ++ .../phase3/run/tasks_join_deadlock.air | 94 ++++++ tests/conformance/phase3/run/tasks_limit.air | 28 ++ .../phase3/run/tasks_parallel_square.air | 74 +++++ .../phase3/run/tasks_shared_read.air | 33 ++ tools/conformance.zig | 47 ++- 31 files changed, 1252 insertions(+), 94 deletions(-) create mode 100644 tests/conformance/phase3/accept/tasks_disjoint_halves.air create mode 100644 tests/conformance/phase3/reject/tasks_access_lent.air create mode 100644 tests/conformance/phase3/reject/tasks_borrow_return.air create mode 100644 tests/conformance/phase3/reject/tasks_end_lent_borrow.air create mode 100644 tests/conformance/phase3/reject/tasks_handle_as_parameter.air create mode 100644 tests/conformance/phase3/reject/tasks_not_send.air create mode 100644 tests/conformance/phase3/reject/tasks_not_share.air create mode 100644 tests/conformance/phase3/reject/tasks_same_mut_twice.air create mode 100644 tests/conformance/phase3/reject/tasks_scope_end_unjoined.air create mode 100644 tests/conformance/phase3/reject/tasks_spawn_without_effect.air create mode 100644 tests/conformance/phase3/run/tasks_cancel_request.air create mode 100644 tests/conformance/phase3/run/tasks_join_deadlock.air create mode 100644 tests/conformance/phase3/run/tasks_limit.air create mode 100644 tests/conformance/phase3/run/tasks_parallel_square.air create mode 100644 tests/conformance/phase3/run/tasks_shared_read.air diff --git a/AGENTS.md b/AGENTS.md index c0a8058..85fea3a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -139,7 +139,7 @@ zig fmt --check build.zig build.zig.zon src tools Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing. -`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. `aji run --manifest aji.toml` runs a package with the grants its manifest requests (`--grant` replaces one per parameter; spec 12 §1). `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted ""` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7). +`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. Scheduler flags: `--quantum N`, `--task-limit N`, `--schedule-seed N` (independent of `--seed`); conformance tests use `schedules: N` to run N schedule seeds. `aji run --manifest aji.toml` runs a package with the grants its manifest requests (`--grant` replaces one per parameter; spec 12 §1). `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted ""` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7). ## Testing policy diff --git a/docs/agent/README.md b/docs/agent/README.md index 2570c5c..409df6e 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -43,5 +43,6 @@ Growth never blocks a merge automatically; a complex feature can be justified, b | Milestone | Files | Sections | Bytes | Words | cl100k | o200k | Qwen2.5 | |---|---:|---:|---:|---:|---:|---:|---:| | Phase 2 baseline (AIR format 0) | 18 | 29 | 104 250 | 16 197 | 27 347 | 27 445 | 28 230 | +| RFC 0011 tasks (Phase 3, part 1) | 19 | 33 | 116 126 | 18 082 | 30 333 (+10.9 %) | 30 433 (+10.9 %) | 31 316 (+10.9 %) | -Next measurement: after Phase 3 (structured concurrency). +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. Next measurement: after RFC 0012 (channels, synchronization). diff --git a/docs/agent/history.json b/docs/agent/history.json index cf4d379..2688f91 100644 --- a/docs/agent/history.json +++ b/docs/agent/history.json @@ -14,5 +14,21 @@ "o200k_base": 27445, "qwen2.5": 28230 } + }, + { + "label": "rfc-0011 tasks (Phase 3, part 1)", + "language": "aji", + "air": 0, + "phase": 2, + "files": 19, + "sections": 33, + "bytes": 116126, + "lines": 1777, + "words": 18082, + "tokens": { + "cl100k_base": 30333, + "o200k_base": 30433, + "qwen2.5": 31316 + } } ] diff --git a/docs/plan/phase-3-structured-concurrency.md b/docs/plan/phase-3-structured-concurrency.md index 72d4e38..e4c254b 100644 --- a/docs/plan/phase-3-structured-concurrency.md +++ b/docs/plan/phase-3-structured-concurrency.md @@ -22,19 +22,19 @@ Non-normative. Part of the [implementation plan](README.md). | ID | Status | Task | Depends | Output | Done when | |---|---|---|---|---|---| -| P3-1 | todo | Resolve Q-013, Q-014; propose RFC 0002 for acceptance | — | 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-2a | todo | Publish features `tasks`, `channels`, `sync` | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests | -| P3-3 | todo | Deterministic scheduler: seeds, choice points, choice log; global fuel across tasks and a separate `quantum` (spec 11 §7.2) | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run; fuel is the sum over all tasks | -| 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-1 | doing | Resolve Q-013, Q-014; propose RFC 0002 for acceptance (Q-014 resolved by RFC 0011; Q-013 with RFC 0012) | — | spec 04, 11 | questions resolved | +| P3-2 | doing | Contract tables: `task.*` (RFC 0011, done), `channel.*`, `mutex.*`, `rwlock.*`, select (RFC 0012); `thread.*` deferred to native backends | P3-1 | spec 07 appendix | all spec 07 §4 fields including synchronization effects | +| P3-2a | doing | Publish features `tasks` (done), `channels`, `sync` | P3-2 | `reference/air-features.md`, `src/air/features.zig` | feature_not_declared / missing_dependency tests | +| P3-3 | done | Deterministic scheduler: seeds, choice points, choice log; global fuel across tasks and a separate `quantum` (spec 11 §7.2) | P3-2 | `src/interp/sched.zig` | same seed ⇒ identical trace; choice log replays a run; fuel is the sum over all tasks | +| P3-4 | done | Send/Share/Local derivation | P3-1 | `src/verifier/send_share.zig` | E4001, E4002 accept/reject | +| P3-5 | done | Task-scope verifier and scoped borrows | P3-2 | `src/verifier/tasks.zig` | E4301, E4302 accept/reject | +| P3-6 | done | Concurrent alias / data-race rejection | P3-5 | `src/verifier/borrow.zig` | E4101 accept/reject; disjoint `split_mut` halves accepted in two tasks | +| P3-7 | doing | 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:`/`quantum:` headers (schedule budget kept separate from fuel); 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-12 | doing | Runner: `seed:`/`schedules:`/`quantum:` headers (schedule budget kept separate from fuel); 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 | diff --git a/docs/rfcs/0011-structured-tasks.md b/docs/rfcs/0011-structured-tasks.md index 0d02294..9f053b9 100644 --- a/docs/rfcs/0011-structured-tasks.md +++ b/docs/rfcs/0011-structured-tasks.md @@ -3,6 +3,7 @@ Status: Accepted (revision 2, after owner review items 1–10) Scope: AIR format 0, feature `tasks` Language version: 0.1 +Measured Agent Reference Bundle growth on integration: +10.9 % tokens (estimate in this RFC: below 10 %). 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: — diff --git a/src/air/features.zig b/src/air/features.zig index 6f0b601..ea6887e 100644 --- a/src/air/features.zig +++ b/src/air/features.zig @@ -36,12 +36,14 @@ pub const registry = [_]Feature{ .{ .name = "resource_joins", .depends = &.{ "capabilities", "effects", "ownership", "resources" }, .status = .reserved, .phase = null }, .{ .name = "resources", .depends = &.{ "capabilities", "effects", "ownership" }, .status = .published, .phase = 2 }, .{ .name = "sync", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, - .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, + .{ .name = "task_borrow_returns", .depends = &.{ "ownership", "tasks" }, .status = .reserved, .phase = null }, + .{ .name = "task_transfer", .depends = &.{ "ownership", "tasks" }, .status = .reserved, .phase = null }, + .{ .name = "tasks", .depends = &.{"ownership"}, .status = .published, .phase = 3 }, .{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 }, }; /// Features implemented by this toolchain, sorted. -pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "unsafe" }; +pub const supported = [_][]const u8{ "arrays", "capabilities", "effects", "heap", "ownership", "regions", "resources", "tasks", "unsafe" }; pub const Reason = enum { unknown_feature, @@ -119,7 +121,6 @@ const test_registry = [_]Feature{ .{ .name = "regions", .depends = &.{"ownership"}, .status = .published, .phase = 1 }, .{ .name = "islands", .depends = &.{ "ownership", "regions" }, .status = .published, .phase = 4 }, .{ .name = "tasks", .depends = &.{"ownership"}, .status = .reserved, .phase = 3 }, - .{ .name = "unsafe", .depends = &.{ "arrays", "effects", "ownership" }, .status = .published, .phase = 2 }, }; fn expectProblems(declared: []const []const u8, sup: []const []const u8, want: []const Reason) !void { diff --git a/src/air/module.zig b/src/air/module.zig index 55d0400..b29394e 100644 --- a/src/air/module.zig +++ b/src/air/module.zig @@ -83,6 +83,9 @@ pub const Type = union(enum) { own: *const Type, own_array: *const Type, region, + // Feature `tasks` (spec 04 §33). + scope, + task: *const Type, pub const Array = struct { elem: Type, len: u64 }; @@ -91,8 +94,8 @@ pub const Type = union(enum) { return switch (a) { .int => |x| b.int == x, .named => |x| b.named == x, - .local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.eql(b.inner().?), - .region => true, + .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.eql(b.inner().?), + .region, .scope => true, .array => |x| x.len == b.array.len and x.elem.eql(b.array.elem), .cap => |k| b.cap == k, .builtin => |e| b.builtin == e, @@ -104,7 +107,7 @@ pub const Type = union(enum) { /// Element or pointee type of storage, borrow and slice types. pub fn inner(t: Type) ?Type { return switch (t) { - .local, .ref, .mut, .slice, .slice_mut, .own, .own_array => |x| x.*, + .local, .ref, .mut, .slice, .slice_mut, .own, .own_array, .task => |x| x.*, .array => |a| a.elem, else => null, }; @@ -121,11 +124,16 @@ pub const Type = union(enum) { /// Linear values: consumed exactly once (spec 06 §6.2–§6.3). pub fn isLinear(t: Type) bool { return switch (t) { - .resource, .own, .own_array, .region => true, + .resource, .own, .own_array, .region, .scope, .task => true, else => false, }; } + /// Function-bound types (spec 04 §33.1): never parameters, results or members. + pub fn isTaskBound(t: Type) bool { + return t == .scope or t == .task; + } + pub fn isMutBorrow(t: Type) bool { return t == .mut or t == .slice_mut; } @@ -139,7 +147,7 @@ pub const Type = union(enum) { /// Linear resources are neither values nor borrows: they are moved. pub fn isValue(t: Type) bool { return switch (t) { - .void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region => false, + .void, .never, .local, .ref, .mut, .slice, .slice_mut, .resource, .own, .own_array, .region, .scope, .task => false, else => true, }; } @@ -266,6 +274,13 @@ pub const Op = union(enum) { region_array: struct { region: ValueId, n: ValueId, value: ValueId, ok: u32, err: u32 }, region_reset: ValueId, region_destroy: ValueId, + // Feature `tasks` (spec 04 §33). + task_scope_begin, + task_spawn: struct { scope: ValueId, callee: u32, args: []const ValueId }, + task_join: ValueId, + task_cancel: ValueId, + task_cancelled, + task_scope_end: ValueId, ret: ?ValueId, trap, @@ -414,7 +429,12 @@ pub fn forEachUse(op: Op, ctx: anytype, comptime f: fn (@TypeOf(ctx), ValueId) v f(ctx, x.value); f(ctx, x.cap); }, - .own_take, .own_free, .region_reset, .region_destroy => |v| f(ctx, v), + .own_take, .own_free, .region_reset, .region_destroy, .task_join, .task_cancel, .task_scope_end => |v| f(ctx, v), + .task_scope_begin, .task_cancelled => {}, + .task_spawn => |x| { + f(ctx, x.scope); + for (x.args) |v| f(ctx, v); + }, .region_create => |x| f(ctx, x.cap), .region_new => |x| { f(ctx, x.region); diff --git a/src/air/parse.zig b/src/air/parse.zig index 4d783fe..87e512a 100644 --- a/src/air/parse.zig +++ b/src/air/parse.zig @@ -499,6 +499,10 @@ const Parser = struct { try p.requireFeature(b.feature(), t.span, t.text); return .{ .builtin = b }; } + if (eql(t.text, "scope")) { + try p.requireFeature("tasks", t.span, t.text); + return .scope; + } if (eql(t.text, "region")) { try p.requireFeature("regions", t.span, t.text); return .region; @@ -547,6 +551,15 @@ const Parser = struct { boxed.* = inner; return if (eql(t.text, "own")) .{ .own = boxed } else .{ .own_array = boxed }; } + if (eql(t.text, "task")) { + try p.requireFeature("tasks", t.span, "task"); + _ = try p.expect(.lt, "`<`"); + const inner = try p.parseType(); + _ = try p.expect(.gt, "`>`"); + const boxed = try p.arena.create(air.Type); + boxed.* = inner; + return .{ .task = boxed }; + } if (eql(t.text, "cap")) { try p.requireFeature("capabilities", t.span, "cap"); _ = try p.expect(.lt, "`<`"); @@ -600,6 +613,7 @@ const Parser = struct { /// Resources inside aggregates need the reserved feature `linear_aggregates`. fn gateLinearMember(p: *Parser, t: air.Type, span: Span) Error!void { + if (t.isTaskBound()) return p.requireFeature("task_transfer", span, "task handle or scope as a member"); if (t.isLinear()) try p.requireFeature("linear_aggregates", span, "linear value as a member"); } @@ -633,7 +647,9 @@ const Parser = struct { while (p.peek().tag != .r_paren) { const v = try p.expect(.local, "parameter"); _ = try p.expect(.colon, "`:`"); + const ty_span = p.peek().span; const ty = try p.parseType(); + if (ty.isTaskBound()) try p.requireFeature("task_transfer", ty_span, "task handle or scope as a parameter"); const id = try p.defineValue(v, .{ .param = @intCast(params.items.len) }); try params.append(p.arena, .{ .value = id, .ty = ty }); if (p.peek().tag != .comma) break; @@ -641,7 +657,9 @@ const Parser = struct { } _ = try p.expect(.r_paren, "`)`"); _ = try p.expect(.arrow, "`->`"); + const ret_span = p.peek().span; const ret = try p.parseType(); + if (ret.isTaskBound()) try p.requireFeature("task_transfer", ret_span, "task handle or scope as a result"); var ret_from: ?u32 = null; if (p.atWord("from")) { const from_tok = p.next(); @@ -955,6 +973,7 @@ const Parser = struct { break :op .{ .cap_narrow = .{ .form = parts[2], .cap = c, .args = args.items, .ok = ok, .err = err } }; } if (try p.parseAllocOp(op_tok)) |aop| break :op aop; + if (try p.parseTaskOp(op_tok)) |top| break :op top; if (eql(op_tok.text, "intrinsic")) { try p.requireFeature("capabilities", op_tok.span, "intrinsic"); const name = try p.expect(.word, "intrinsic name"); @@ -981,13 +1000,13 @@ const Parser = struct { _ = try p.expect(.nl, "end of line"); const produces_value = switch (op) { - .own_take => true, + .own_take, .task_scope_begin, .task_spawn, .task_cancelled => true, .@"const", .copy, .arith, .bit, .cmp, .cast, .struct_make, .struct_get, .enum_make => true, .local_alloc, .local_load, .borrow_ref, .borrow_mut, .borrow_field, .load => true, .array_splat, .borrow_index, .slice_make, .slice_len, .slice_sub, .slice_split => true, else => false, }; - const may_bind = produces_value or op == .call or op == .intrinsic; + const may_bind = produces_value or op == .call or op == .intrinsic or op == .task_join; if (result_tok) |rt| { if (!may_bind) return p.fail(rt, "instruction without result binding"); } else if (produces_value) { @@ -1013,6 +1032,30 @@ const Parser = struct { return .{ ok, try p.blockRef() }; } + /// Instructions of the feature `tasks` (spec 04 §33). + fn parseTaskOp(p: *Parser, op_tok: Token) Error!?air.Op { + const Name = enum { @"task.scope.begin", @"task.spawn", @"task.join", @"task.cancel", @"task.cancelled", @"task.scope.end" }; + const name = std.meta.stringToEnum(Name, op_tok.text) orelse return null; + try p.requireFeature("tasks", op_tok.span, op_tok.text); + return switch (name) { + .@"task.scope.begin" => .task_scope_begin, + .@"task.spawn" => blk: { + const s = try p.useValue(); + _ = try p.expect(.comma, "`,`"); + const callee_tok = try p.expect(.global, "function name"); + const callee = indexOf(p.fn_names.items, callee_tok.text) orelse c: { + try p.report("E0004", callee_tok.span, "unknown function", &.{.{ .name = "name", .value = .{ .str = callee_tok.text } }}); + break :c 0; + }; + break :blk .{ .task_spawn = .{ .scope = s, .callee = @intCast(callee), .args = try p.valueList() } }; + }, + .@"task.join" => .{ .task_join = try p.useValue() }, + .@"task.cancel" => .{ .task_cancel = try p.useValue() }, + .@"task.cancelled" => .task_cancelled, + .@"task.scope.end" => .{ .task_scope_end = try p.useValue() }, + }; + } + /// Instructions of the features `heap` and `regions` (spec 03 §19–§20). fn parseAllocOp(p: *Parser, op_tok: Token) Error!?air.Op { const Name = enum { @"own.new", @"own.array", @"own.take", @"own.free", @"region.create", @"region.new", @"region.array", @"region.reset", @"region.destroy" }; diff --git a/src/air/print.zig b/src/air/print.zig index deae090..27d772a 100644 --- a/src/air/print.zig +++ b/src/air/print.zig @@ -121,6 +121,12 @@ pub fn printType(m: air.Module, t: air.Type, w: *Writer) Writer.Error!void { try w.writeByte('>'); }, .region => try w.writeAll("region"), + .scope => try w.writeAll("scope"), + .task => |inner| { + try w.writeAll("task<"); + try printType(m, inner.*, w); + try w.writeByte('>'); + }, .bool, .void, .never => try w.writeAll(@tagName(t)), } } @@ -330,6 +336,17 @@ fn printOp(m: air.Module, f: air.Function, op: air.Op, w: *Writer) Writer.Error! try okErr(f, w, x.ok, x.err); }, .region_reset => |v| try one(f, w, "region.reset", v), + .task_scope_begin => try w.writeAll("task.scope.begin"), + .task_spawn => |x| { + try w.writeAll("task.spawn "); + try value(f, x.scope, w); + try w.print(", @{s}", .{m.functions[x.callee].name}); + try values(f, x.args, w); + }, + .task_join => |v| try one(f, w, "task.join", v), + .task_cancel => |v| try one(f, w, "task.cancel", v), + .task_cancelled => try w.writeAll("task.cancelled"), + .task_scope_end => |v| try one(f, w, "task.scope.end", v), .region_destroy => |v| try one(f, w, "region.destroy", v), .cap_narrow => |x| { try w.print("cap.narrow.{s} ", .{x.form}); diff --git a/src/interp/machine.zig b/src/interp/machine.zig index 41861df..b82d6a0 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -41,6 +41,9 @@ pub const Value = union(enum) { own: *Cell, /// `region`: index into the machine's region table. region: u32, + /// `scope` (no runtime state) and `task` (index into the task table). + scope, + task: u32, /// Value of a built-in enum such as `cap_error`. builtin: struct { which: air.authority.Builtin, variant: u32 }, @@ -72,7 +75,7 @@ pub const Outcome = union(enum) { returned: Value, trapped: Trap, /// The runner's fuel ran out (spec 11 §7). Not a trap. - limit_exceeded: struct { limit: u64, steps: u64 }, + limit_exceeded: struct { kind: []const u8, limit: u64, steps: u64 }, /// The host did not start the program (spec 05 §10.2). Not a trap. not_instantiated: NotInstantiated, /// The deterministic runtime found no future event that could complete @@ -122,6 +125,11 @@ pub const Options = struct { output: ?*Output = null, /// Non-null selects the `hosted` profile (spec 11 §8): real I/O through `io`. hosted: ?std.Io = null, + /// Scheduler (spec 04 §36): instructions per quantum, task slots, and the + /// schedule seed (default: program seed XOR "SCHEDULE"). + quantum: u64 = 1000, + task_limit: u64 = 1024, + schedule_seed: ?u64 = null, }; /// Observable output of a run in the deterministic profile. @@ -130,6 +138,8 @@ pub const Output = struct { stderr: []const u8, /// Files written during the run, sorted by path. files: []const struct { []const u8, []const u8 }, + /// Present when the run spawned tasks (spec 04 §36.4). + schedule: ?struct { seed: u64, quantum: u64, choices: u64 } = null, }; pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGrant }; @@ -142,6 +152,11 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound; var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) }; if (options.hosted) |io| m.host = .{ .arena = arena, .io = io }; + m.quantum = @max(options.quantum, 1); + m.task_limit = options.task_limit; + // Parenthesized: `orelse` binds tighter than `^`. + m.schedule_seed = options.schedule_seed orelse (options.world.seed ^ 0x5343484544554c45); + m.sched = .init(m.schedule_seed); defer if (m.host) |*hs| hs.deinit(); defer if (options.output) |o| { o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} }; @@ -178,12 +193,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti if (!known) return .{ .not_instantiated = .{ .reason = "unknown_parameter", .parameter = g.parameter } }; } - return switch (try m.call(idx, args)) { - .value => |v| .{ .returned = v }, - .trap => |t| .{ .trapped = t }, - .limit_exceeded => .{ .limit_exceeded = .{ .limit = m.fuel.?, .steps = m.steps } }, - .blocked => |l| .{ .blocked = l }, - }; + return m.runProgram(idx, args); } const TrapKind = enum { @@ -224,13 +234,39 @@ fn kindOf(e: TrapError) TrapKind { }; } -const CallResult = union(enum) { value: Value, trap: Trap, limit_exceeded, blocked: Location }; +pub const Wait = union(enum) { + join: u32, + accept: u32, + recv: u32, +}; + +const Frame = struct { func: u32, vals: []Value, block: u32, inst: u32 }; + +const Task = struct { + frames: std.ArrayList(Frame) = .empty, + state: enum { runnable, waiting, done } = .runnable, + result: Value = .void, + cancel: bool = false, + wait: Wait = .{ .join = 0 }, + wait_at: Location = .{ .function = "", .block = "", .inst = 0 }, + fuel_paid: bool = false, +}; const Machine = struct { arena: std.mem.Allocator, module: air.Module, - depth: u32 = 0, fuel: ?u64, + tasks: std.ArrayList(Task) = .empty, + current: u32 = 0, + quantum: u64 = 1000, + quantum_used: u64 = 0, + task_limit: u64 = 1024, + sched: world_mod.Prng = .init(0), + schedule_seed: u64 = 0, + choices: u64 = 0, + /// Live task slots (spawned and not yet joined). + live_tasks: u64 = 0, + spawned: bool = false, /// Host authority table; capabilities index into it. authorities: std.ArrayList(Authority) = .empty, world: world_mod.World, @@ -240,42 +276,120 @@ const Machine = struct { /// Instructions executed so far. steps: u64 = 0, - fn call(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!CallResult { - const f = m.module.functions[fn_index]; - m.depth += 1; - defer m.depth -= 1; + // ------------------------------------------------------------ tasks and the scheduler (spec 04 §36) + /// Runs task 0 (`@main`) and every task it spawns until the program + /// returns, traps, or the environment stops it. + fn runProgram(m: *Machine, fn_index: u32, args: []const Value) std.mem.Allocator.Error!Outcome { + try m.tasks.append(m.arena, .{}); + try m.pushFrame(0, fn_index, args); + while (true) { + const t = &m.tasks.items[m.current]; + if (t.state != .runnable) { + if (try m.schedule()) |o| return o; + continue; + } + const frame = &t.frames.items[t.frames.items.len - 1]; + const f = m.module.functions[frame.func]; + const b = f.blocks[frame.block]; + const inst = b.insts[frame.inst]; + const here: Location = .{ .function = f.name, .block = b.name, .inst = frame.inst }; + // Fuel is consumed when an instruction begins (spec 11 §7.1); a + // blocked instruction paid when it first began (spec 04 §36.3). + if (!t.fuel_paid) { + if (m.fuel) |limit| if (m.steps >= limit) return .{ .limit_exceeded = .{ .kind = "fuel", .limit = limit, .steps = m.steps } }; + m.steps += 1; + m.quantum_used += 1; + } + t.fuel_paid = false; + switch (try m.exec(f, frame.vals, inst)) { + .next => frame.inst += 1, + .jump => |target| { + frame.block = target; + frame.inst = 0; + }, + .call => |c| { + if (t.frames.items.len >= call_depth_limit) return .{ .trapped = .{ .code = TrapKind.call_depth.code(), .function = here.function, .block = here.block, .inst = here.inst } }; + try m.pushFrame(m.current, c.callee, c.args); + }, + .ret => |v| { + _ = t.frames.pop(); + if (t.frames.items.len == 0) { + t.state = .done; + t.result = v; + if (m.current == 0) return .{ .returned = v }; + if (try m.schedule()) |o| return o; + continue; + } + const caller = &t.frames.items[t.frames.items.len - 1]; + const call_inst = m.module.functions[caller.func].blocks[caller.block].insts[caller.inst]; + if (call_inst.result) |r| caller.vals[r] = v; + caller.inst += 1; + }, + .trap => |k| return .{ .trapped = .{ .code = k.code(), .function = here.function, .block = here.block, .inst = here.inst } }, + .wait => |w| { + t.state = .waiting; + t.wait = w; + t.wait_at = here; + t.fuel_paid = true; + if (try m.schedule()) |o| return o; + continue; + }, + .yield => { + frame.inst += 1; + if (try m.schedule()) |o| return o; + continue; + }, + .task_limit => return .{ .limit_exceeded = .{ .kind = "tasks", .limit = m.task_limit, .steps = m.steps } }, + } + if (m.quantum_used >= m.quantum) { + if (try m.schedule()) |o| return o; + } + } + } + + fn pushFrame(m: *Machine, task: u32, fn_index: u32, args: []const Value) !void { + const f = m.module.functions[fn_index]; const vals = try m.arena.alloc(Value, f.values.len); for (f.params, args) |p, a| vals[p.value] = a; + try m.tasks.items[task].frames.append(m.arena, .{ .func = fn_index, .vals = vals, .block = 0, .inst = 0 }); + } - var block: u32 = 0; - while (true) { - const b = f.blocks[block]; - for (b.insts, 0..) |inst, ii| { - // Fuel is consumed when an instruction begins (spec 11 §7.1). - if (m.fuel) |limit| if (m.steps >= limit) return .limit_exceeded; - m.steps += 1; - const step = try m.exec(f, vals, inst); - switch (step) { - .next => {}, - .jump => |t| { - block = t; - break; - }, - .ret => |v| return .{ .value = v }, - .trap => |k| return .{ .trap = .{ - .code = k.code(), - .function = f.name, - .block = b.name, - .inst = @intCast(ii), - } }, - .nested_trap => |t| return .{ .trap = t }, - .limit_exceeded => return .limit_exceeded, - .blocked => return .{ .blocked = .{ .function = f.name, .block = b.name, .inst = @intCast(ii) } }, - .nested_blocked => |l| return .{ .blocked = l }, - } - } else unreachable; // verified blocks end with a terminator + /// Whether a waiting task's condition holds now. + fn ready(m: *Machine, w: Wait) bool { + return switch (w) { + .join => |id| m.tasks.items[id].state == .done, + .accept => |hd| m.world.handles.items[hd].listener.pending.items.len != 0, + .recv => |hd| blk: { + const st = m.world.handles.items[hd].stream; + break :blk st.inbox.items.len > st.read_pos or st.peer_closed; + }, + }; + } + + /// A scheduling point (spec 04 §36.2): wakes ready waiters and picks the + /// next runnable task. Returns an outcome only at global quiescence. + fn schedule(m: *Machine) !?Outcome { + m.quantum_used = 0; + for (m.tasks.items) |*t| if (t.state == .waiting and m.ready(t.wait)) { + t.state = .runnable; + }; + var runnable: std.ArrayList(u32) = .empty; + for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.arena, @intCast(i)); + if (runnable.items.len == 0) { + // Global quiescence (spec 11 §8): unfinished tasks, none runnable, + // no known future event. Report the oldest waiting task. + for (m.tasks.items) |t| if (t.state == .waiting) return .{ .blocked = t.wait_at }; + unreachable; // task 0 finishing returns before scheduling } + if (runnable.items.len == 1) { + m.current = runnable.items[0]; // no choice to make: no draw + return null; + } + const x = m.sched.next(); + m.choices += 1; + m.current = runnable.items[x % runnable.items.len]; + return null; } const Step = union(enum) { @@ -283,11 +397,15 @@ const Machine = struct { jump: u32, ret: Value, trap: TrapKind, - /// A trap raised inside a callee, already located. - nested_trap: Trap, - limit_exceeded, - blocked, - nested_blocked: Location, + /// Push a frame; the call instruction completes when it returns. + call: struct { callee: u32, args: []const Value }, + /// The instruction cannot complete now; the task waits and the + /// instruction is resumed later without paying fuel again. + wait: Wait, + /// The instruction completed and is a scheduling point. + yield, + /// `task.spawn` would exceed the deterministic task limit. + task_limit, }; fn exec(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step { @@ -345,19 +463,7 @@ const Machine = struct { .variant = x.variant, .fields = try m.gatherMut(vals, x.args), } }), - .call => |x| { - if (m.depth >= call_depth_limit) return .{ .trap = .call_depth }; - const args = try m.gather(vals, x.args); - switch (try m.call(x.callee, args)) { - .value => |v| { - if (inst.result) |r| vals[r] = v; - return .next; - }, - .trap => |t| return .{ .nested_trap = t }, - .limit_exceeded => return .limit_exceeded, - .blocked => |l| return .{ .nested_blocked = l }, - } - }, + .call => |x| return .{ .call = .{ .callee = x.callee, .args = try m.gather(vals, x.args) } }, .br => |t| return m.jump(f, vals, t), .cbr => |x| return m.jump(f, vals, if (vals[x.cond].boolean) x.then else x.@"else"), .@"switch" => |x| { @@ -380,6 +486,34 @@ const Machine = struct { // No narrowing form is registered yet, so verified AIR contains // no reachable cap.narrow (spec 05 §10.4; forms arrive with RFC 0007/0008). .cap_narrow => |x| return m.narrow(f, vals, x), + .task_scope_begin => return bind(vals, inst.result, .scope), + .task_scope_end => return .next, + .task_spawn => |x| { + if (m.live_tasks >= m.task_limit) return .task_limit; + m.live_tasks += 1; + m.spawned = true; + const id: u32 = @intCast(m.tasks.items.len); + try m.tasks.append(m.arena, .{}); + try m.pushFrame(id, x.callee, try m.gather(vals, x.args)); + vals[inst.result.?] = .{ .task = id }; + return .yield; + }, + .task_join => |v| { + const id = vals[v].task; + const t = m.tasks.items[id]; + if (t.state != .done) return .{ .wait = .{ .join = id } }; + m.live_tasks -= 1; + if (inst.result) |r| vals[r] = t.result; + return .yield; + }, + .task_cancel => |v| { + m.tasks.items[vals[v].task].cancel = true; + return .yield; + }, + .task_cancelled => { + vals[inst.result.?] = .{ .boolean = m.tasks.items[m.current].cancel }; + return .yield; + }, .own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst), .intrinsic => |x| return m.intrinsic(f, vals, inst, x), .ret => |v| return .{ .ret = if (v) |x| vals[x] else .void }, @@ -466,7 +600,12 @@ const Machine = struct { }.lt); const files = try m.arena.alloc(struct { []const u8, []const u8 }, keys.len); for (keys, files) |k, *out| out.* = .{ k, m.world.files.get(k).?.items }; - return .{ .stdout = m.world.stdout.items, .stderr = m.world.stderr.items, .files = files }; + return .{ + .stdout = m.world.stdout.items, + .stderr = m.world.stderr.items, + .files = files, + .schedule = if (m.spawned) .{ .seed = m.schedule_seed, .quantum = m.quantum, .choices = m.choices } else null, + }; } /// Bytes of a `slice` value. @@ -727,7 +866,7 @@ const Machine = struct { if (m.host) |*hs| switch (try hs.accept(hd)) { .ok => |s| result = .{ .resource = s }, .err => |e| failure = e, - } else result = .{ .resource = m.world.accept(hd) orelse return .blocked }; + } else result = .{ .resource = m.world.accept(hd) orelse return .{ .wait = .{ .accept = hd } } }; } else if (is(name, "net.recv")) { const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len); const hd = resourceOf(arg(vals, x, 0)); @@ -737,7 +876,7 @@ const Machine = struct { failure = e; break :blk 0; }, - } else m.world.recv(hd, buf) orelse return .blocked; + } else m.world.recv(hd, buf) orelse return .{ .wait = .{ .recv = hd } }; fillSlice(arg(vals, x, 1), buf[0..n]); result = .{ .int = .{ .ty = .usize, .bits = n } }; } else if (is(name, "net.send_all")) { @@ -996,7 +1135,7 @@ pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.W }, // Storage and borrows cannot be returned from `@main` (spec 08 §11.3). .local, .place, .slice => try s.write(null), - .resource, .own, .region => try s.write(null), + .resource, .own, .region, .scope, .task => try s.write(null), // A capability is opaque: only its kind is shown, never its identity. .cap => { try s.beginObject(); @@ -1125,7 +1264,7 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std. .limit_exceeded => |l| { try s.write("limit_exceeded"); try s.objectField("kind"); - try s.write("fuel"); + try s.write(l.kind); try s.objectField("limit"); try s.write(l.limit); try s.objectField("steps"); @@ -1145,6 +1284,10 @@ pub fn writeOutcome(module: air.Module, outcome: Outcome, out: ?Output, w: *std. } try s.endObject(); }; + if (out) |o| if (o.schedule) |sch| { + try s.objectField("schedule"); + try s.write(sch); + }; try s.endObject(); } @@ -1317,3 +1460,30 @@ test "canonical byte strings in the run record" { try s.endArray(); try std.testing.expectEqualStrings("[\"h\u{e9}\\n\",{\"encoding\":\"base64\",\"data\":\"/w==\"},{\"encoding\":\"base64\",\"data\":\"QWpp\"}]", w.buffered()); } + +test "schedule seed: explicit value is used as is, default derives from the program seed" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const src = "module t\nair 0\nlang 0.1\nfeatures [ownership, tasks]\n" ++ + \\fn @main() -> void + \\effects [] + \\entry: + \\ %sc = task.scope.begin + \\ %t = task.spawn %sc, @noop() + \\ task.join %t + \\ task.scope.end %sc + \\ ret + \\fn @noop() -> void + \\effects [] + \\entry: + \\ ret + \\ + ; + const report = try check.checkAir(arena, "t.air", src); + var out: Output = undefined; + _ = try run(arena, report.module.?, "main", .{ .schedule_seed = 3, .output = &out }); + try std.testing.expectEqual(@as(u64, 3), out.schedule.?.seed); + _ = try run(arena, report.module.?, "main", .{ .world = .{ .seed = 3 }, .output = &out }); + try std.testing.expectEqual(@as(u64, 3 ^ 0x5343484544554c45), out.schedule.?.seed); +} diff --git a/src/main.zig b/src/main.zig index bf9947e..7273d42 100644 --- a/src/main.zig +++ b/src/main.zig @@ -26,7 +26,8 @@ const usage = \\ --grant binds capability parameter P of @main \\ (and replaces the manifest's grant for P); \\ deterministic world: --stdin TEXT, --vfs PATH=TEXT, - \\ --seed N; --profile hosted uses the real OS and + \\ --seed N; scheduler: --quantum N, --task-limit N, + \\ --schedule-seed N; --profile hosted uses the real OS and \\ writes the record only to --result-file PATH \\ report verify, then print the audit report (spec 10 §6.1) \\ codes list diagnostic codes as JSON Lines @@ -133,6 +134,13 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s try files.append(arena, .{ value[0..eq], value[eq + 1 ..] }); } else if (std.mem.eql(u8, flag, "--seed")) { options.world.seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--seed takes a non-negative integer"); + } else if (std.mem.eql(u8, flag, "--quantum")) { + options.quantum = std.fmt.parseInt(u64, value, 10) catch return usageError("--quantum takes a positive integer"); + if (options.quantum == 0) return usageError("--quantum takes a positive integer"); + } else if (std.mem.eql(u8, flag, "--task-limit")) { + options.task_limit = std.fmt.parseInt(u64, value, 10) catch return usageError("--task-limit takes a non-negative integer"); + } else if (std.mem.eql(u8, flag, "--schedule-seed")) { + options.schedule_seed = std.fmt.parseInt(u64, value, 10) catch return usageError("--schedule-seed takes a non-negative integer"); } else if (std.mem.eql(u8, flag, "--result-file")) { result_file = value; } else if (std.mem.eql(u8, flag, "--manifest")) { diff --git a/src/verifier/borrow.zig b/src/verifier/borrow.zig index fc35190..a7d1396 100644 --- a/src/verifier/borrow.zig +++ b/src/verifier/borrow.zig @@ -29,6 +29,8 @@ const Seg = union(enum) { const Mode = enum { shared, exclusive }; +const Loan = struct { task: ValueId, borrow: ValueId, root: ValueId, path: []const Seg, mode: Mode }; + /// Why a resource is no longer live (spec 06 §6.3). const Dead = enum { none, closed, moved }; @@ -65,6 +67,11 @@ const Walker = struct { live: []bool, /// How a resource stopped being live, for diagnostics. dead: []Dead, + /// Borrows lent to tasks (spec 04 §34). A loan is active while its task + /// handle is live, so it is part of the per-path state through `live`. + loans: std.ArrayList(Loan) = .empty, + /// Scope of each task handle value. + task_scope: []?ValueId, block: u32 = 0, index: u32 = 0, span: air.Span = .{ .line = 0, .col = 0 }, @@ -127,6 +134,14 @@ const Walker = struct { try w.report(code, message, who, .{ "conflicts_with", @intCast(cv) }); return; } + // Borrows lent to live tasks are accessed concurrently (spec 04 §34). + for (w.loans.items) |l| { + if (!w.live[l.task] or l.root != root) continue; + if (mode == .shared and l.mode == .shared) continue; + if (!overlap(path, l.path)) continue; + try w.report("E4101", "conflicts with a borrow lent to a live task", who, .{ "task", l.task }); + return; + } } /// Records a new owned borrow and checks it against live borrows. @@ -262,7 +277,9 @@ fn checkFunction(c: *Context, f: air.Function, types: []const air.Type) !void { .info = try c.arena.alloc(?Info, f.values.len), .live = try c.arena.alloc(bool, f.values.len), .dead = try c.arena.alloc(Dead, f.values.len), + .task_scope = try c.arena.alloc(?ValueId, f.values.len), }; + @memset(w.task_scope, null); @memset(w.info, null); @memset(w.live, false); @memset(w.dead, .none); @@ -377,6 +394,9 @@ fn step(w: *Walker, inst: air.Inst) !void { if (!w.live[v]) return w.report("E2106", "borrow ended twice", v, null); // Ended even when rejected, so one mistake yields one diagnostic. defer w.live[v] = false; + for (w.loans.items) |l| if (w.live[l.task] and (l.borrow == v or w.isAncestor(v, l.borrow))) { + return w.report("E4302", "borrow ended while it is lent to a live task", v, .{ "task", l.task }); + }; for (w.live, 0..) |is_live, cv| { if (is_live and w.info[cv] != null and w.info[cv].?.parent == v) { return w.report("E2102", "borrow ended while a borrow derived from it is live", v, .{ "child", @intCast(cv) }); @@ -397,6 +417,38 @@ fn step(w: *Walker, inst: air.Inst) !void { }; }, .own_free, .own_take => |v| try w.consume(v, .closed), + .task_scope_begin => w.live[inst.result.?] = true, + .task_spawn => |x| { + const t = inst.result.?; + w.task_scope[t] = x.scope; + for (x.args) |a| { + if (w.types[a].isBorrow()) { + if (!try w.usable(a)) continue; + const ai = w.info[a].?; + // The loan must not conflict with live borrows or loans. + try w.accessCode(ai.root, ai.path, ai.mode, a, a, "E4101", "lending a borrow that conflicts with a live borrow"); + try w.loans.append(w.c.arena, .{ .task = t, .borrow = a, .root = ai.root, .path = ai.path, .mode = ai.mode }); + } else if (w.isResource(a)) try w.consume(a, .moved); + } + w.live[t] = true; + }, + .task_join => |t| { + // Joining ends the task's loans (they are active only while `t` lives). + try w.consume(t, .closed); + if (inst.result) |r| if (w.isResource(r)) { + w.live[r] = true; + }; + }, + .task_cancel => |t| _ = try w.resourceUsable(t), + .task_scope_end => |s| { + for (w.live, 0..) |is_live, v| { + if (is_live and w.task_scope[v] != null and w.task_scope[v].? == s) { + try w.report("E4301", "scope ends while a task spawned from it is not joined", @intCast(v), .{ "scope", s }); + w.live[v] = false; // reported once, in preference to E3002 + } + } + try w.consume(s, .closed); + }, .region_reset => |v| { if (!try w.resourceUsable(v)) return; // Reset invalidates the generation: no reference may be live. diff --git a/src/verifier/budget.zig b/src/verifier/budget.zig index 1e87b4c..bf1978c 100644 --- a/src/verifier/budget.zig +++ b/src/verifier/budget.zig @@ -28,7 +28,7 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 { return switch (t) { .int => |it| it.bits() / 8, .bool => 1, - .ref, .mut, .cap, .resource, .own, .region => 8, + .ref, .mut, .cap, .resource, .own, .region, .scope, .task => 8, .own_array => 16, .slice, .slice_mut => 16, .builtin => |b| tagSize(b.variants().len), diff --git a/src/verifier/effects.zig b/src/verifier/effects.zig index 4d28906..0f48066 100644 --- a/src/verifier/effects.zig +++ b/src/verifier/effects.zig @@ -16,6 +16,20 @@ pub fn check(c: *Context) !void { if (!m.declares("effects")) return; for (m.functions) |f| { for (f.blocks) |b| for (b.insts) |inst| switch (inst.op) { + .task_spawn => |x| { + if (!contains(f.effects, "task.spawn")) try c.report("E3101", inst.span, "task.spawn requires the effect task.spawn", &.{ + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "effect", .value = .{ .str = "task.spawn" } }, + }); + const callee = m.functions[x.callee]; + for (callee.effects) |e| if (!std.mem.eql(u8, e, "unsafe") and !contains(f.effects, e)) { + try c.report("E3101", inst.span, "task function effect not declared by the spawning function", &.{ + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "callee", .value = .{ .str = callee.name } }, + .{ .name = "effect", .value = .{ .str = e } }, + }); + }; + }, .call => |x| { const callee = m.functions[x.callee]; // `unsafe` is checked by the unsafe stage, which knows about diff --git a/src/verifier/types.zig b/src/verifier/types.zig index 40efa2f..3c65144 100644 --- a/src/verifier/types.zig +++ b/src/verifier/types.zig @@ -85,7 +85,7 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons .void, .never => pos == .ret, .local => false, .ref, .mut, .slice, .slice_mut => pos != .member and pos != .borrowed, - .resource, .own, .own_array, .region => pos != .member, + .resource, .own, .own_array, .region, .scope, .task => pos != .member, else => true, }; if (!ok) try c.report("E1001", span, "type not allowed in this position", &.{ @@ -93,9 +93,9 @@ fn wellFormed(c: *Context, span: air.Span, t: Type, pos: Position, owner: []cons .{ .name = "position", .value = .{ .str = @tagName(pos) } }, .{ .name = "found", .value = .{ .str = try c.typeName(t) } }, }); - // The pointee of ref/mut may be a linear value (`mut>`); - // every other compound holds value types only. - if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut) .borrowed else .member, owner); + // The pointee of ref/mut may be a linear value (`mut>`), and + // a task may return one; every other compound holds value types only. + if (t.inner()) |inner| try wellFormed(c, span, inner, if (t == .ref or t == .mut or t == .task) .borrowed else .member, owner); } /// `local.alloc` results are checked separately: their own type is storage. @@ -210,6 +210,8 @@ fn resultType(m: air.Module, op: air.Op) ?Type { .enum_make => |x| .{ .named = x.decl }, .call => |x| m.functions[x.callee].ret, .slice_len => .{ .int = .usize }, + .task_scope_begin => .scope, + .task_cancelled => .bool, .intrinsic => |x| blk: { const reg = air.authority.intrinsics[x.index]; if (reg.fallible or reg.results.len == 0) break :blk .void; @@ -307,6 +309,80 @@ fn checkIntrinsic(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "intrinsic") } } +/// `Send` (spec 04 §35): may move to another task. +pub fn isSend(m: air.Module, t: Type) bool { + return switch (t) { + .int, .bool, .builtin, .cap, .resource, .region => true, + .own, .own_array => |inner| isSend(m, inner.*), + .ref, .slice => |inner| isShare(m, inner.*), + .mut, .slice_mut => |inner| isSend(m, inner.*), + .array => |a| isSend(m, a.elem), + .named => |i| aggregateAll(m, i, isSend), + .scope, .task, .local, .void, .never => false, + }; +} + +/// `Share` (spec 04 §35): may be observed concurrently through shared borrows. +pub fn isShare(m: air.Module, t: Type) bool { + return switch (t) { + .int, .bool, .builtin, .cap => true, + .resource, .region, .mut, .slice_mut, .scope, .task, .local, .void, .never => false, + .own, .own_array, .ref, .slice => |inner| isShare(m, inner.*), + .array => |a| isShare(m, a.elem), + .named => |i| aggregateAll(m, i, isShare), + }; +} + +fn aggregateAll(m: air.Module, i: u32, comptime pred: fn (air.Module, Type) bool) bool { + return switch (m.types[i].kind) { + .@"struct" => |fs| for (fs) |f| { + if (!pred(m, f.ty)) break false; + } else true, + .@"enum" => |vs| { + for (vs) |v| for (v.payload) |p| if (!pred(m, p)) return false; + return true; + }, + }; +} + +/// `task.spawn` (spec 04 §33.2, §35): arguments like a call, Send/Share +/// rules per argument, and a borrow-free, Send result. +fn checkSpawn(fc: *FnCtx, inst: air.Inst, x: @FieldType(air.Op, "task_spawn")) !void { + const m = fc.c.module; + const f = fc.f; + const span = inst.span; + if (fc.typeOf(x.scope) != .scope) try fc.kindError(span, x.scope, "scope"); + const callee = m.functions[x.callee]; + const tys = try fc.c.arena.alloc(Type, callee.params.len); + for (callee.params, tys) |p, *t| t.* = p.ty; + try fc.expectArgs(span, x.args, tys); + if (x.args.len == tys.len) for (x.args, tys) |a, pt| { + const shared = pt == .ref or pt == .slice; + const ok = if (shared) isShare(m, pt.inner().?) else isSend(m, pt); + if (!ok) try fc.c.report(if (shared) "E4002" else "E4001", span, if (shared) "data lent to a task through a shared borrow must be Share" else "a value moved or exclusively lent to a task must be Send", &.{ + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "task_function", .value = .{ .str = callee.name } }, + .{ .name = "argument", .value = .{ .str = try fc.c.valueName(f, a) } }, + .{ .name = "type", .value = .{ .str = try fc.c.typeName(pt) } }, + }); + }; + const r = callee.ret; + if (callee.ret_from != null or r.isBorrow()) { + try fc.c.report("E0006", span, "construct belongs to a feature the module does not declare", &.{ + .{ .name = "reason", .value = .{ .str = "feature_not_declared" } }, + .{ .name = "feature", .value = .{ .str = "task_borrow_returns" } }, + .{ .name = "construct", .value = .{ .str = "spawned function returning a borrow" } }, + }); + } else if (r.isTaskBound()) { + try fc.c.report("E1001", span, "a task result must not contain a scope or task handle", &.{.{ .name = "function", .value = .{ .str = f.name } }}); + } else if (r != .void and r != .never and !isSend(m, r)) { + try fc.c.report("E4001", span, "a task result must be Send", &.{ + .{ .name = "function", .value = .{ .str = f.name } }, + .{ .name = "task_function", .value = .{ .str = callee.name } }, + }); + } +} + fn boxed(arena: std.mem.Allocator, t: Type) !*const Type { const b = try arena.create(Type); b.* = t; @@ -328,6 +404,8 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { .borrow_index => |x| fc.ty[x.borrow] orelse return null, .slice_sub => |x| fc.ty[x.slice] orelse return null, .own_take => |v| fc.ty[v] orelse return null, + .task_join => |v| fc.ty[v] orelse return null, + .task_spawn => |x| return .{ .task = try boxed(a, m.functions[x.callee].ret) }, .slice_split => |x| fc.ty[x.slice] orelse return null, else => return null, }; @@ -336,7 +414,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { .local_load => if (t == .local) t.local.* else invalid, .borrow_ref => switch (t) { .local, .ref, .mut => .{ .ref = try boxed(a, t.inner().?) }, - .resource, .region => .{ .ref = try boxed(a, t) }, + .resource, .region, .task, .scope => .{ .ref = try boxed(a, t) }, .own => |inner| .{ .ref = inner }, .own_array => |inner| .{ .slice = inner }, .slice, .slice_mut => .{ .slice = try boxed(a, t.inner().?) }, @@ -344,7 +422,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { }, .borrow_mut => switch (t) { .local, .mut => .{ .mut = try boxed(a, t.inner().?) }, - .resource, .region => .{ .mut = try boxed(a, t) }, + .resource, .region, .task, .scope => .{ .mut = try boxed(a, t) }, .own => |inner| .{ .mut = inner }, .own_array => |inner| .{ .slice_mut = inner }, .slice_mut => .{ .slice_mut = try boxed(a, t.inner().?) }, @@ -376,6 +454,7 @@ fn derivedType(fc: *FnCtx, op: air.Op) !?Type { }, .slice_sub, .slice_split => if (t.isSlice()) t else invalid, .own_take => if (t == .own) t.own.* else invalid, + .task_join => if (t == .task) t.task.* else invalid, else => unreachable, }; } @@ -589,6 +668,17 @@ fn checkInst(fc: *FnCtx, inst: air.Inst) !void { try fc.expectOkErr(span, x.ok, x.err, .{ .slice_mut = try boxed(fc.c.arena, t) }); }, .region_reset, .region_destroy => |v| if (fc.typeOf(v) != .region) try fc.kindError(span, v, "region"), + .task_scope_begin, .task_cancelled => {}, + .task_scope_end => |v| if (fc.typeOf(v) != .scope) try fc.kindError(span, v, "scope"), + .task_cancel => |v| if (fc.typeOf(v) != .task) try fc.kindError(span, v, "task"), + .task_join => |v| { + const t = fc.typeOf(v); + if (t != .task) return fc.kindError(span, v, "task"); + const r = t.task.*; + if (inst.result != null and r == .void) try fc.c.report("E1001", span, "joining a void task must not bind a result", &.{.{ .name = "function", .value = .{ .str = f.name } }}); + if (inst.result == null and r != .void and r != .never) try fc.c.report("E1001", span, "the result of task.join must be bound", &.{.{ .name = "function", .value = .{ .str = f.name } }}); + }, + .task_spawn => |x| try checkSpawn(fc, inst, x), .cap_narrow => |x| { const t = fc.typeOf(x.cap); if (t != .cap) return fc.kindError(span, x.cap, "cap"); diff --git a/tests/conformance/phase3/accept/tasks_disjoint_halves.air b/tests/conformance/phase3/accept/tasks_disjoint_halves.air new file mode 100644 index 0000000..9372205 --- /dev/null +++ b/tests/conformance/phase3/accept/tasks_disjoint_halves.air @@ -0,0 +1,71 @@ +; Two tasks receive the disjoint halves of one buffer. +; expect: accept +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_disjoint_halves +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> array +effects [task.spawn] +entry: + %buf = local.alloc array + local.zero %buf + %m = borrow.mut %buf + %s = slice.make %m + %i0 = const.usize 0 + %i1 = const.usize 1 + %i2 = const.usize 2 + %i3 = const.usize 3 + %e0 = borrow.index %s, %i0 + %v1 = const.u64 1 + store %e0, %v1 + borrow.end %e0 + %e1 = borrow.index %s, %i1 + %v2 = const.u64 2 + store %e1, %v2 + borrow.end %e1 + %e2 = borrow.index %s, %i2 + %v3 = const.u64 3 + store %e2, %v3 + borrow.end %e2 + %e3 = borrow.index %s, %i3 + %v4 = const.u64 4 + store %e3, %v4 + borrow.end %e3 + %two = const.usize 2 + %l, %r = slice.split %s, %two + %sc = task.scope.begin + %t1 = task.spawn %sc, @square(%l) + %t2 = task.spawn %sc, @square(%r) + task.join %t1 + task.join %t2 + task.scope.end %sc + borrow.end %l + borrow.end %r + borrow.end %s + borrow.end %m + %out = local.load %buf + ret %out + +fn @square(%s: slice_mut) -> void +effects [] +entry: + %n = slice.len %s + %z = const.usize 0 + br @loop(%z) +loop(%i: usize): + %c = lt.usize %i, %n + cbr %c, @body(), @done() +body: + %e = borrow.index.proven %s, %i + %v = load %e + %sq = mul.checked.u64 %v, %v + store %e, %sq + borrow.end %e + %one = const.usize 1 + %j = add.checked.usize %i, %one + br @loop(%j) +done: + ret diff --git a/tests/conformance/phase3/reject/tasks_access_lent.air b/tests/conformance/phase3/reject/tasks_access_lent.air new file mode 100644 index 0000000..0cdbd85 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_access_lent.air @@ -0,0 +1,71 @@ +; The parent reads a buffer half it lent exclusively to a running task. +; expect: reject E4101 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_access_lent +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %buf = local.alloc array + local.zero %buf + %m = borrow.mut %buf + %s = slice.make %m + %i0 = const.usize 0 + %i1 = const.usize 1 + %i2 = const.usize 2 + %i3 = const.usize 3 + %e0 = borrow.index %s, %i0 + %v1 = const.u64 1 + store %e0, %v1 + borrow.end %e0 + %e1 = borrow.index %s, %i1 + %v2 = const.u64 2 + store %e1, %v2 + borrow.end %e1 + %e2 = borrow.index %s, %i2 + %v3 = const.u64 3 + store %e2, %v3 + borrow.end %e2 + %e3 = borrow.index %s, %i3 + %v4 = const.u64 4 + store %e3, %v4 + borrow.end %e3 + %two = const.usize 2 + %l, %r = slice.split %s, %two + %sc = task.scope.begin + %t1 = task.spawn %sc, @square(%l) + %z = const.usize 0 + %e = borrow.index %l, %z + borrow.end %e + task.join %t1 + task.scope.end %sc + borrow.end %l + borrow.end %r + borrow.end %s + borrow.end %m + ret + +fn @square(%s: slice_mut) -> void +effects [] +entry: + %n = slice.len %s + %z = const.usize 0 + br @loop(%z) +loop(%i: usize): + %c = lt.usize %i, %n + cbr %c, @body(), @done() +body: + %e = borrow.index.proven %s, %i + %v = load %e + %sq = mul.checked.u64 %v, %v + store %e, %sq + borrow.end %e + %one = const.usize 1 + %j = add.checked.usize %i, %one + br @loop(%j) +done: + ret diff --git a/tests/conformance/phase3/reject/tasks_borrow_return.air b/tests/conformance/phase3/reject/tasks_borrow_return.air new file mode 100644 index 0000000..6994581 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_borrow_return.air @@ -0,0 +1,23 @@ +; A spawned function returning a borrow needs the reserved feature task_borrow_returns. +; expect: reject E0006 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_borrow_return +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %x = local.alloc u8 + local.zero %x + %r = borrow.ref %x + %sc = task.scope.begin + %t = task.spawn %sc, @same(%r) + trap + +fn @same(%p: ref) -> ref from %p +effects [] +entry: + ret %p diff --git a/tests/conformance/phase3/reject/tasks_end_lent_borrow.air b/tests/conformance/phase3/reject/tasks_end_lent_borrow.air new file mode 100644 index 0000000..446addf --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_end_lent_borrow.air @@ -0,0 +1,68 @@ +; A borrow lent to a task is ended before the join. +; expect: reject E4302 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_end_lent_borrow +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %buf = local.alloc array + local.zero %buf + %m = borrow.mut %buf + %s = slice.make %m + %i0 = const.usize 0 + %i1 = const.usize 1 + %i2 = const.usize 2 + %i3 = const.usize 3 + %e0 = borrow.index %s, %i0 + %v1 = const.u64 1 + store %e0, %v1 + borrow.end %e0 + %e1 = borrow.index %s, %i1 + %v2 = const.u64 2 + store %e1, %v2 + borrow.end %e1 + %e2 = borrow.index %s, %i2 + %v3 = const.u64 3 + store %e2, %v3 + borrow.end %e2 + %e3 = borrow.index %s, %i3 + %v4 = const.u64 4 + store %e3, %v4 + borrow.end %e3 + %two = const.usize 2 + %l, %r = slice.split %s, %two + %sc = task.scope.begin + %t1 = task.spawn %sc, @square(%l) + borrow.end %l + task.join %t1 + task.scope.end %sc + borrow.end %r + borrow.end %s + borrow.end %m + ret + +fn @square(%s: slice_mut) -> void +effects [] +entry: + %n = slice.len %s + %z = const.usize 0 + br @loop(%z) +loop(%i: usize): + %c = lt.usize %i, %n + cbr %c, @body(), @done() +body: + %e = borrow.index.proven %s, %i + %v = load %e + %sq = mul.checked.u64 %v, %v + store %e, %sq + borrow.end %e + %one = const.usize 1 + %j = add.checked.usize %i, %one + br @loop(%j) +done: + ret diff --git a/tests/conformance/phase3/reject/tasks_handle_as_parameter.air b/tests/conformance/phase3/reject/tasks_handle_as_parameter.air new file mode 100644 index 0000000..39011ff --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_handle_as_parameter.air @@ -0,0 +1,13 @@ +; Task handles are function-bound; passing one needs the reserved feature task_transfer. +; expect: reject E0006 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_handle_as_parameter +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @f(%t: task) -> void +effects [] +entry: + trap diff --git a/tests/conformance/phase3/reject/tasks_not_send.air b/tests/conformance/phase3/reject/tasks_not_send.air new file mode 100644 index 0000000..155e4e4 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_not_send.air @@ -0,0 +1,32 @@ +; A borrow of a task handle cannot be sent to another task. +; expect: reject E4001 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_not_send +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @noop() + %tm = borrow.mut %t + %u = task.spawn %sc, @hold(%tm) + task.join %u + borrow.end %tm + %r = task.join %t + task.scope.end %sc + ret + +fn @noop() -> u8 +effects [] +entry: + %z = const.u8 0 + ret %z + +fn @hold(%x: mut>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase3/reject/tasks_not_share.air b/tests/conformance/phase3/reject/tasks_not_share.air new file mode 100644 index 0000000..57d276f --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_not_share.air @@ -0,0 +1,29 @@ +; A region is not Share: lending ref to a task is rejected. +; expect: reject E4002 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_not_share +air 0 +lang 0.1 +features [capabilities, effects, heap, ownership, regions, resources, tasks] + +fn @main(%heap: cap) -> void +effects [task.spawn, mem.alloc] +entry: + region.create %heap, ok -> @have, err -> @nomem +have(%reg: region): + %rb = borrow.ref %reg + %sc = task.scope.begin + %t = task.spawn %sc, @peek(%rb) + task.join %t + task.scope.end %sc + borrow.end %rb + region.destroy %reg + ret +nomem(%e: alloc_error): + trap + +fn @peek(%r: ref) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase3/reject/tasks_same_mut_twice.air b/tests/conformance/phase3/reject/tasks_same_mut_twice.air new file mode 100644 index 0000000..700aae9 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_same_mut_twice.air @@ -0,0 +1,70 @@ +; The same exclusive borrow is lent to two live tasks. +; expect: reject E4101 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_same_mut_twice +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %buf = local.alloc array + local.zero %buf + %m = borrow.mut %buf + %s = slice.make %m + %i0 = const.usize 0 + %i1 = const.usize 1 + %i2 = const.usize 2 + %i3 = const.usize 3 + %e0 = borrow.index %s, %i0 + %v1 = const.u64 1 + store %e0, %v1 + borrow.end %e0 + %e1 = borrow.index %s, %i1 + %v2 = const.u64 2 + store %e1, %v2 + borrow.end %e1 + %e2 = borrow.index %s, %i2 + %v3 = const.u64 3 + store %e2, %v3 + borrow.end %e2 + %e3 = borrow.index %s, %i3 + %v4 = const.u64 4 + store %e3, %v4 + borrow.end %e3 + %two = const.usize 2 + %l, %r = slice.split %s, %two + %sc = task.scope.begin + %t1 = task.spawn %sc, @square(%l) + %t2 = task.spawn %sc, @square(%l) + task.join %t1 + task.join %t2 + task.scope.end %sc + borrow.end %l + borrow.end %r + borrow.end %s + borrow.end %m + ret + +fn @square(%s: slice_mut) -> void +effects [] +entry: + %n = slice.len %s + %z = const.usize 0 + br @loop(%z) +loop(%i: usize): + %c = lt.usize %i, %n + cbr %c, @body(), @done() +body: + %e = borrow.index.proven %s, %i + %v = load %e + %sq = mul.checked.u64 %v, %v + store %e, %sq + borrow.end %e + %one = const.usize 1 + %j = add.checked.usize %i, %one + br @loop(%j) +done: + ret diff --git a/tests/conformance/phase3/reject/tasks_scope_end_unjoined.air b/tests/conformance/phase3/reject/tasks_scope_end_unjoined.air new file mode 100644 index 0000000..7bb7f89 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_scope_end_unjoined.air @@ -0,0 +1,21 @@ +; The scope ends while a task spawned from it is not joined. +; expect: reject E4301 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_scope_end_unjoined +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @noop() + task.scope.end %sc + ret + +fn @noop() -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase3/reject/tasks_spawn_without_effect.air b/tests/conformance/phase3/reject/tasks_spawn_without_effect.air new file mode 100644 index 0000000..1f963f9 --- /dev/null +++ b/tests/conformance/phase3/reject/tasks_spawn_without_effect.air @@ -0,0 +1,22 @@ +; task.spawn requires the effect task.spawn. +; expect: reject E3101 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_spawn_without_effect +air 0 +lang 0.1 +features [arrays, effects, ownership, tasks] + +fn @main() -> void +effects [] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @noop() + task.join %t + task.scope.end %sc + ret + +fn @noop() -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase3/run/tasks_cancel_request.air b/tests/conformance/phase3/run/tasks_cancel_request.air new file mode 100644 index 0000000..4c50502 --- /dev/null +++ b/tests/conformance/phase3/run/tasks_cancel_request.air @@ -0,0 +1,31 @@ +; cancel only requests: the child sees the flag, returns, and must still be joined. +; expect: run +; schedules: 10 +; result: 7 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_cancel_request +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> u8 +effects [task.spawn] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @worker() + task.cancel %t + %r = task.join %t + task.scope.end %sc + ret %r + +fn @worker() -> u8 +effects [] +entry: + br @poll() +poll: + %c = task.cancelled + cbr %c, @stop(), @poll() +stop: + %v = const.u8 7 + ret %v diff --git a/tests/conformance/phase3/run/tasks_join_deadlock.air b/tests/conformance/phase3/run/tasks_join_deadlock.air new file mode 100644 index 0000000..cb96c80 --- /dev/null +++ b/tests/conformance/phase3/run/tasks_join_deadlock.air @@ -0,0 +1,94 @@ +; Every task waits and no event can wake one: the run is blocked. +; expect: run +; grant: listen=net.listen +; blocked: no_future_event +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_join_deadlock +air 0 +lang 0.1 +features [arrays, capabilities, effects, ownership, resources, tasks] + +fn @main(%listen: cap) -> void +effects [task.spawn, net.listen] +entry: + %sc = task.scope.begin + %t = task.spawn %sc, @serve(%listen) + task.join %t + task.scope.end %sc + ret + +fn @serve(%listen: cap) -> void +effects [net.listen] +entry: + %a = local.alloc array + local.zero %a + %am = borrow.mut %a + %ai0 = const.usize 0 + %ac0 = const.u8 49 + %ae0 = borrow.index %am, %ai0 + store %ae0, %ac0 + borrow.end %ae0 + %ai1 = const.usize 1 + %ac1 = const.u8 50 + %ae1 = borrow.index %am, %ai1 + store %ae1, %ac1 + borrow.end %ae1 + %ai2 = const.usize 2 + %ac2 = const.u8 55 + %ae2 = borrow.index %am, %ai2 + store %ae2, %ac2 + borrow.end %ae2 + %ai3 = const.usize 3 + %ac3 = const.u8 46 + %ae3 = borrow.index %am, %ai3 + store %ae3, %ac3 + borrow.end %ae3 + %ai4 = const.usize 4 + %ac4 = const.u8 48 + %ae4 = borrow.index %am, %ai4 + store %ae4, %ac4 + borrow.end %ae4 + %ai5 = const.usize 5 + %ac5 = const.u8 46 + %ae5 = borrow.index %am, %ai5 + store %ae5, %ac5 + borrow.end %ae5 + %ai6 = const.usize 6 + %ac6 = const.u8 48 + %ae6 = borrow.index %am, %ai6 + store %ae6, %ac6 + borrow.end %ae6 + %ai7 = const.usize 7 + %ac7 = const.u8 46 + %ae7 = borrow.index %am, %ai7 + store %ae7, %ac7 + borrow.end %ae7 + %ai8 = const.usize 8 + %ac8 = const.u8 49 + %ae8 = borrow.index %am, %ai8 + store %ae8, %ac8 + borrow.end %ae8 + %ai9 = const.usize 9 + %ac9 = const.u8 58 + %ae9 = borrow.index %am, %ai9 + store %ae9, %ac9 + borrow.end %ae9 + %ai10 = const.usize 10 + %ac10 = const.u8 57 + %ae10 = borrow.index %am, %ai10 + store %ae10, %ac10 + borrow.end %ae10 + borrow.end %am + %ar = borrow.ref %a + %as = slice.make %ar + intrinsic net.listen(%listen, %as), ok -> @listening, err -> @fail +listening(%l: listener): + %lm = borrow.mut %l + intrinsic net.accept(%lm), ok -> @accepted, err -> @fail2 +accepted(%st: stream): + trap +fail2(%e2: io_error): + trap +fail(%e: io_error): + trap diff --git a/tests/conformance/phase3/run/tasks_limit.air b/tests/conformance/phase3/run/tasks_limit.air new file mode 100644 index 0000000..50f0bd7 --- /dev/null +++ b/tests/conformance/phase3/run/tasks_limit.air @@ -0,0 +1,28 @@ +; Spawning beyond the deterministic task limit is an environment outcome, not a trap. +; expect: run +; task_limit: 2 +; limit_exceeded: tasks +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_limit +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> void +effects [task.spawn] +entry: + %sc = task.scope.begin + %a = task.spawn %sc, @noop() + %b = task.spawn %sc, @noop() + %c = task.spawn %sc, @noop() + task.join %a + task.join %b + task.join %c + task.scope.end %sc + ret + +fn @noop() -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase3/run/tasks_parallel_square.air b/tests/conformance/phase3/run/tasks_parallel_square.air new file mode 100644 index 0000000..ad32614 --- /dev/null +++ b/tests/conformance/phase3/run/tasks_parallel_square.air @@ -0,0 +1,74 @@ +; Parallel squaring of two halves gives the same result under every explored schedule. +; expect: run +; schedules: 20 +; quantum: 3 +; result: [1,4,9,16] +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_parallel_square +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> array +effects [task.spawn] +entry: + %buf = local.alloc array + local.zero %buf + %m = borrow.mut %buf + %s = slice.make %m + %i0 = const.usize 0 + %i1 = const.usize 1 + %i2 = const.usize 2 + %i3 = const.usize 3 + %e0 = borrow.index %s, %i0 + %v1 = const.u64 1 + store %e0, %v1 + borrow.end %e0 + %e1 = borrow.index %s, %i1 + %v2 = const.u64 2 + store %e1, %v2 + borrow.end %e1 + %e2 = borrow.index %s, %i2 + %v3 = const.u64 3 + store %e2, %v3 + borrow.end %e2 + %e3 = borrow.index %s, %i3 + %v4 = const.u64 4 + store %e3, %v4 + borrow.end %e3 + %two = const.usize 2 + %l, %r = slice.split %s, %two + %sc = task.scope.begin + %t1 = task.spawn %sc, @square(%l) + %t2 = task.spawn %sc, @square(%r) + task.join %t1 + task.join %t2 + task.scope.end %sc + borrow.end %l + borrow.end %r + borrow.end %s + borrow.end %m + %out = local.load %buf + ret %out + +fn @square(%s: slice_mut) -> void +effects [] +entry: + %n = slice.len %s + %z = const.usize 0 + br @loop(%z) +loop(%i: usize): + %c = lt.usize %i, %n + cbr %c, @body(), @done() +body: + %e = borrow.index.proven %s, %i + %v = load %e + %sq = mul.checked.u64 %v, %v + store %e, %sq + borrow.end %e + %one = const.usize 1 + %j = add.checked.usize %i, %one + br @loop(%j) +done: + ret diff --git a/tests/conformance/phase3/run/tasks_shared_read.air b/tests/conformance/phase3/run/tasks_shared_read.air new file mode 100644 index 0000000..8a23dbc --- /dev/null +++ b/tests/conformance/phase3/run/tasks_shared_read.air @@ -0,0 +1,33 @@ +; The same shared borrow of Share data may be lent to two tasks. +; expect: run +; schedules: 10 +; result: 42 +; phase: 3 +; spec: docs/spec/04-concurrency-and-atomics.md +module test.tasks_shared_read +air 0 +lang 0.1 +features [arrays, ownership, tasks] + +fn @main() -> u64 +effects [task.spawn] +entry: + %x = local.alloc u64 + %v = const.u64 21 + local.store %x, %v + %r = borrow.ref %x + %sc = task.scope.begin + %t1 = task.spawn %sc, @read(%r) + %t2 = task.spawn %sc, @read(%r) + %a = task.join %t1 + %b = task.join %t2 + task.scope.end %sc + borrow.end %r + %sum = add.checked.u64 %a, %b + ret %sum + +fn @read(%p: ref) -> u64 +effects [] +entry: + %v = load %p + ret %v diff --git a/tools/conformance.zig b/tools/conformance.zig index 4f9c679..7f0b002 100644 --- a/tools/conformance.zig +++ b/tools/conformance.zig @@ -24,6 +24,8 @@ const Expect = union(enum) { not_instantiated: []const u8, /// Expected `blocked` outcome (spec 11 §8). blocked, + /// Expected `limit_exceeded` with this kind (`tasks`, `fuel`). + limit_exceeded: []const u8, }; }; @@ -36,6 +38,10 @@ const default_fuel: u64 = 1_000_000; const Header = struct { expect: Expect, fuel: u64, + /// Run with schedule seeds 0 … schedules-1 (spec 04 §36.5). + schedules: u64, + quantum: u64, + task_limit: u64, grants: []const aji.interp.Grant, world: aji.interp.WorldOptions, /// Expected captured output and written files (all optional). @@ -168,12 +174,34 @@ fn runOne(arena: std.mem.Allocator, path: []const u8, source: []const u8) !Resul /// Runs the module twice and requires byte-identical run records (spec 11) /// before comparing against the expectation. +/// Runs the module once per schedule seed; every seed must satisfy the +/// expectation (spec 04 §36.5). The program seed stays unchanged. fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header) !Result { + var seed: u64 = 0; + while (seed < header.schedules) : (seed += 1) { + const r = try runSeed(arena, module, want, header, if (header.schedules > 1) seed else null); + if (r.outcome != .pass) { + if (header.schedules == 1) return r; + return .{ .outcome = r.outcome, .detail = try std.fmt.allocPrint(arena, "schedule seed {d}: {s}", .{ seed, r.detail }) }; + } + } + return .{ .outcome = .pass }; +} + +fn runSeed(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, header: Header, schedule_seed: ?u64) !Result { var records: [2][]const u8 = undefined; var outcome: aji.interp.Outcome = undefined; var output: aji.interp.Output = undefined; for (&records) |*rec| { - outcome = aji.interp.run(arena, module, "main", .{ .fuel = header.fuel, .grants = header.grants, .world = header.world, .output = &output }) catch |err| switch (err) { + outcome = aji.interp.run(arena, module, "main", .{ + .fuel = header.fuel, + .grants = header.grants, + .world = header.world, + .output = &output, + .quantum = header.quantum, + .task_limit = header.task_limit, + .schedule_seed = schedule_seed, + }) catch |err| switch (err) { error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" }, error.DuplicateGrant => return .{ .outcome = .fail, .detail = "a parameter is granted more than once" }, else => |e| return e, @@ -190,6 +218,7 @@ fn runModule(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, .result => |json| outcome == .returned and std.mem.eql(u8, json, try valueJson(arena, module, outcome.returned)), .not_instantiated => |reason| outcome == .not_instantiated and std.mem.eql(u8, outcome.not_instantiated.reason, reason), .blocked => outcome == .blocked, + .limit_exceeded => |kind| outcome == .limit_exceeded and std.mem.eql(u8, outcome.limit_exceeded.kind, kind), }; if (ok) { if (header.stdout) |expected| if (!std.mem.eql(u8, expected, output.stdout)) @@ -286,6 +315,7 @@ fn formatExpect(e: Expect, w: *std.Io.Writer) std.Io.Writer.Error!void { .trap => |c| try w.print("run trapping {s}", .{c}), .not_instantiated => |reason| try w.print("not_instantiated ({s})", .{reason}), .blocked => try w.writeAll("blocked"), + .limit_exceeded => |k| try w.print("limit_exceeded ({s})", .{k}), }, } } @@ -297,6 +327,9 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header var run_result: ?Expect.Run = null; var phase: ?u8 = null; var fuel: u64 = default_fuel; + var schedules: u64 = 1; + var quantum: u64 = 1000; + var task_limit: u64 = 1024; var grants: std.ArrayList(aji.interp.Grant) = .empty; var world: aji.interp.WorldOptions = .{}; var vfs: std.ArrayList(struct { []const u8, []const u8 }) = .empty; @@ -343,6 +376,9 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header } else if (std.mem.eql(u8, key, "not_instantiated")) { if (run_result != null) return error.BadExpect; run_result = .{ .not_instantiated = value }; + } else if (std.mem.eql(u8, key, "limit_exceeded")) { + if (run_result != null) return error.BadExpect; + run_result = .{ .limit_exceeded = value }; } else if (std.mem.eql(u8, key, "blocked")) { if (run_result != null) return error.BadExpect; run_result = .blocked; @@ -367,6 +403,12 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header .kind = if (sep) |c| rest[0..c] else rest, .scope = if (sep) |c| rest[c + 1 ..] else null, }); + } else if (std.mem.eql(u8, key, "schedules")) { + schedules = try std.fmt.parseInt(u64, value, 10); + } else if (std.mem.eql(u8, key, "quantum")) { + quantum = try std.fmt.parseInt(u64, value, 10); + } else if (std.mem.eql(u8, key, "task_limit")) { + task_limit = try std.fmt.parseInt(u64, value, 10); } else if (std.mem.eql(u8, key, "fuel")) { fuel = try std.fmt.parseInt(u64, value, 10); } else if (std.mem.eql(u8, key, "phase")) { @@ -382,6 +424,9 @@ fn parseHeader(arena: std.mem.Allocator, source: []const u8) HeaderError!Header return .{ .expect = expect orelse return error.MissingExpect, .fuel = fuel, + .schedules = schedules, + .quantum = quantum, + .task_limit = task_limit, .grants = grants.items, .world = blk: { world.files = vfs.items;