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<T> (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)
This commit is contained in:
1 parent
2289917af3
commit
ab5814a7bb
31 files changed
+1252
-94
No files matched your search
+233
-63
@@ -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<T>` (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<u8>` 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);
|
||||
}
|
||||
Reference in new issue
Block a user