Fix two toolchain defects found by the M checkpoint
A. Interpreter memory grew with the number of executed steps (one arena, never reclaimed): block and call arguments, frames, frame storage, value copies, place paths, channel buffers and per-step scratch now live in a collectable execution heap. Between instructions, past a threshold, the live state is copied into a fresh heap (sharing preserved) and the old one released. Long-lived state (module, world, authority, task, channel and region tables, the result) stays in the caller's arena. The guarded value of a mutex is a separate cell (no interior pointers). Nothing observable changes: fuel, schedule, PRNG, values, traps and run records are the same. - test: five loop shapes x 100k/1M/4M iterations, measured with the interpreter's own heap counters: live state after a collection does not grow with the iteration count; the heap stays under a fixed bound - conformance --collect-every-step: the second run of every run test collects before every instruction; records must be byte-identical (passes, also with --stress 20) B. A void function whose body ends in an if/if-else/match/block/void call lowered to `ret %` (malformed AIR, reported as E0001): it now lowers to `ret`. Seven fall-through tests (six failed before). Also: files_opened counts reads by relative path and file name; P6A-11 (malformed generated AIR as an internal compiler diagnostic) and Q-023 (ref of a whole array as an argument) recorded.
This commit is contained in:
1 parent
4aa9183e78
commit
222c0c884c
15 files changed
+573
-48
No files matched your search
@@ -156,3 +156,7 @@ Parameter names are preserved by lowering and are the binding points for grants
|
||||
A byte string lowers to one `local.zero`, then a borrow, index, store and end per non-zero byte, because format 0 has no byte-array constant. In the Layer 6 programs this makes up most of the AIR (`hello`: `mechanical_air_eliminated` 0.94). The metric then measures a representation cost of format 0 more than the mechanics an agent would otherwise write. Options for P6A-9: report the metric both with and without byte-string materialization, or count each byte string as one AIR construct. A byte-array constant in AIR would be a format change (spec 07 §8.7) and is out of scope for 6A.
|
||||
|
||||
**Resolved (owner decision):** report both. `mechanical_air_eliminated_raw` counts all AIR actually generated and stays the main engineering metric. `mechanical_air_eliminated_normalized` counts each byte-string materialization as one logical constant operation, under one fixed rule for every program (spec 15 §11).
|
||||
|
||||
## Q-023 — `ref` of a whole array passed to a `ref<[T; N]>` parameter
|
||||
|
||||
In `.aji` a borrow of a whole array written as an argument (`f(ref a)`, `a: [u64; 4]`) is always lowered as a slice (`slice<u64>`), so a function declared with a parameter `ref<[u64; 4]>` cannot be called with `ref a` (`E7005`). Spec 15 §5 says that binding a borrow of a whole array (`ref r = a;`) gives a slice. It does not say what an argument borrow gives, so the frontend's choice is not specified. Options: the argument borrow follows the parameter type (array borrow for `ref<[T; N]>`, slice for `slice<T>`), which is a small amount of inference from a known signature; or keep slices only and state it in spec 15. Found while writing the interpreter memory test; not urgent.
|
||||
@@ -33,6 +33,7 @@ Targets and the evaluation order are in `README.md`. Phase 6A is specified by RF
|
||||
| P6A-8 | done | Source Reference Bundle (directory, `QUICK.md` front door, AIR reference only under `air/`), harness profile `aji_source` with per-group documentation metrics, Quick Reference examples checked against conformance programs, raw and normalized size metrics | P6A-6 | `docs/agent/source-bundle.txt`, `tools/eval/languages/aji_source.json` | bundle measured; every Quick Reference example is an excerpt of a checked program |
|
||||
| P6A-9 | todo | Dev regression on tasks M and C: the frozen `Aji/AIR` runs vs new `Aji/source` runs, same agents (all three native agents) | P6A-8 | results note | criteria below reported |
|
||||
| P6A-10 | todo | Phase 6A exit review | all | plan status | targets reported |
|
||||
| P6A-11 | todo | Malformed generated AIR is a compiler bug: when a `.aji` module passed the frontend but its AIR fails to parse or is structurally invalid, report an internal compiler diagnostic (with the source construct), not the AIR parse error mapped back (found by the M checkpoint: void fall-through lowered to `ret %`) | P6A-4 | `src/check.zig`, error registry | a test that injects malformed lowering gets the internal diagnostic |
|
||||
|
||||
### P6A-9 criteria (owner decision, fixed before the runs)
|
||||
|
||||
|
||||
+10
-2
@@ -526,7 +526,7 @@ const Lowerer = struct {
|
||||
}
|
||||
if (tail) |v| {
|
||||
try l.checkTy(f.body.tail.?.span, v.ty, sig.ret);
|
||||
try l.term(try l.fmt("ret %{s}", .{v.name}), f.body.tail.?.span);
|
||||
try l.term(try l.retText(v), f.body.tail.?.span);
|
||||
} else if (sig.ret == .void) {
|
||||
try l.term("ret", f.body.span);
|
||||
} else return l.fail("E7006", f.body.span, "the function can end without returning a value", &.{.{ .name = "function", .value = f.name }});
|
||||
@@ -561,6 +561,14 @@ const Lowerer = struct {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ret %v`, or `ret` for a void value: a void function whose body ends
|
||||
/// in an `if`, `match`, loop, block or void call falls through with
|
||||
/// nothing to return (spec 15 §4).
|
||||
fn retText(l: *Lowerer, v: Value) Error![]const u8 {
|
||||
if (v.ty == .void) return "ret";
|
||||
return l.fmt("ret %{s}", .{v.name});
|
||||
}
|
||||
|
||||
fn freshName(l: *Lowerer, base: []const u8) Error![]const u8 {
|
||||
while (true) {
|
||||
l.counter += 1;
|
||||
@@ -813,7 +821,7 @@ const Lowerer = struct {
|
||||
try l.checkTy(x.span, v.ty, l.ret);
|
||||
if (l.cur != null) {
|
||||
try l.endScopes(0, s.span);
|
||||
try l.term(try l.fmt("ret %{s}", .{v.name}), s.span);
|
||||
try l.term(try l.retText(v), s.span);
|
||||
}
|
||||
} else {
|
||||
if (l.ret != .void) return l.fail("E7005", s.span, "`return` without a value in a function that returns one", &.{.{ .name = "expected", .value = l.tyText(l.ret) }});
|
||||
|
||||
+310
-41
@@ -5,8 +5,21 @@
|
||||
//! - deterministic: no host time, randomness or address-dependent behavior;
|
||||
//! - traps are values (`Outcome.trapped`), never host panics or unwinding.
|
||||
//!
|
||||
//! Target description: `air64` (spec 09 §9). All memory comes from the arena
|
||||
//! passed to `run` and is released by the caller as a whole.
|
||||
//! Target description: `air64` (spec 09 §9).
|
||||
//!
|
||||
//! Memory: use is bounded by the program's live state, not by the number
|
||||
//! of instructions executed.
|
||||
//! - long-lived state comes from the arena passed to `run` and is released
|
||||
//! by the caller: the module, the world, the authority, task, channel and
|
||||
//! region tables, and the result;
|
||||
//! - execution state lives in a collectable heap: frames, block and call
|
||||
//! arguments, frame storage and heap cells, aggregate and array payloads,
|
||||
//! place paths, channel buffers, per-instruction scratch. Between
|
||||
//! instructions, when the heap has grown past a threshold, the live part
|
||||
//! is copied into a fresh heap (`collect`) and the old one is released.
|
||||
//! Copying preserves sharing, and nothing observable depends on
|
||||
//! addresses, so collection never changes fuel, scheduling, PRNG draws,
|
||||
//! values, traps or the run record.
|
||||
|
||||
const std = @import("std");
|
||||
const air = @import("../air.zig");
|
||||
@@ -55,7 +68,9 @@ pub const Value = union(enum) {
|
||||
mutex: *MutexCell,
|
||||
guard: *MutexCell,
|
||||
|
||||
pub const MutexCell = struct { locked: bool, cell: Cell };
|
||||
/// The guarded value is a separate cell, so a place borrowed through a
|
||||
/// guard points at an ordinary cell.
|
||||
pub const MutexCell = struct { locked: bool, cell: *Cell };
|
||||
|
||||
pub const Aggregate = struct {
|
||||
decl: u32,
|
||||
@@ -124,7 +139,22 @@ pub const Authority = struct {
|
||||
/// A region: its authority and the bytes charged by its current generation.
|
||||
pub const Region = struct { authority: u32, used: u64 };
|
||||
|
||||
const OwnInfo = struct { authority: u32, bytes: u64 };
|
||||
|
||||
/// Execution-heap statistics (`Options.memory`), for tests and tooling.
|
||||
pub const MemoryStats = struct {
|
||||
collections: u64 = 0,
|
||||
/// Largest live execution state after a collection, in heap bytes.
|
||||
peak_live: usize = 0,
|
||||
/// Largest execution heap before a collection, in heap bytes.
|
||||
peak_heap: usize = 0,
|
||||
};
|
||||
|
||||
pub const Options = struct {
|
||||
/// Filled with execution-heap statistics when set.
|
||||
memory: ?*MemoryStats = null,
|
||||
/// Collect before every instruction (tests: a missed root then fails).
|
||||
collect_every_step: bool = false,
|
||||
/// Maximum number of instructions to execute (spec 11 §7.1); null means unlimited.
|
||||
fuel: ?u64 = null,
|
||||
/// Capability grants for the parameters of the entry function.
|
||||
@@ -203,9 +233,79 @@ 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 m.runProgram(idx, args);
|
||||
m.exec_heap.every_step = options.collect_every_step;
|
||||
const outcome = try m.runProgram(idx, args);
|
||||
// The result outlives the execution heap.
|
||||
var result = outcome;
|
||||
if (outcome == .returned) {
|
||||
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer tmp.deinit();
|
||||
var c: Copier = .{ .to = arena, .tmp = tmp.allocator() };
|
||||
result = .{ .returned = try c.value(outcome.returned) };
|
||||
}
|
||||
m.exec_heap.stats.peak_heap = @max(m.exec_heap.stats.peak_heap, m.exec_heap.space.queryCapacity());
|
||||
if (options.memory) |st| st.* = m.exec_heap.stats;
|
||||
m.exec_heap.space.deinit();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Copies values into another heap, preserving sharing: a cell, a mutex or
|
||||
/// a payload reached twice is copied once.
|
||||
const Copier = struct {
|
||||
to: std.mem.Allocator,
|
||||
tmp: std.mem.Allocator,
|
||||
cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty,
|
||||
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
|
||||
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
|
||||
|
||||
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
|
||||
return switch (v) {
|
||||
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try c.items(a.fields) } },
|
||||
.array => |xs| .{ .array = try c.items(xs) },
|
||||
.local => |cl| .{ .local = try c.cell(cl) },
|
||||
.own => |cl| .{ .own = try c.cell(cl) },
|
||||
.place => |p| .{ .place = try c.place(p) },
|
||||
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
|
||||
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
|
||||
.guard => |mc| .{ .guard = try c.mutex(mc) },
|
||||
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver => v,
|
||||
};
|
||||
}
|
||||
|
||||
fn items(c: *Copier, xs: []Value) std.mem.Allocator.Error![]Value {
|
||||
if (xs.len == 0) return &.{};
|
||||
if (c.payloads.get(xs.ptr)) |n| {
|
||||
std.debug.assert(n.len == xs.len);
|
||||
return n;
|
||||
}
|
||||
const out = try c.to.alloc(Value, xs.len);
|
||||
try c.payloads.put(c.tmp, xs.ptr, out);
|
||||
for (xs, out) |x, *o| o.* = try c.value(x);
|
||||
return out;
|
||||
}
|
||||
|
||||
fn cell(c: *Copier, old: *Value.Cell) std.mem.Allocator.Error!*Value.Cell {
|
||||
if (c.cells.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.Cell);
|
||||
try c.cells.put(c.tmp, old, n);
|
||||
n.* = .{ .value = .void, .ty = old.ty };
|
||||
n.value = try c.value(old.value);
|
||||
return n;
|
||||
}
|
||||
|
||||
fn mutex(c: *Copier, old: *Value.MutexCell) std.mem.Allocator.Error!*Value.MutexCell {
|
||||
if (c.mutexes.get(old)) |n| return n;
|
||||
const n = try c.to.create(Value.MutexCell);
|
||||
try c.mutexes.put(c.tmp, old, n);
|
||||
n.* = .{ .locked = old.locked, .cell = try c.cell(old.cell) };
|
||||
return n;
|
||||
}
|
||||
|
||||
fn place(c: *Copier, p: Value.Place) std.mem.Allocator.Error!Value.Place {
|
||||
return .{ .cell = try c.cell(p.cell), .path = if (p.path.len == 0) &.{} else try c.to.dupe(u32, p.path) };
|
||||
}
|
||||
};
|
||||
|
||||
const TrapKind = enum {
|
||||
explicit,
|
||||
assert,
|
||||
@@ -300,8 +400,19 @@ const Task = struct {
|
||||
delivered: ?struct { arm: u32, value: Value } = null,
|
||||
};
|
||||
|
||||
/// Execution heap: collected between instructions (see the file comment).
|
||||
const Heap = struct {
|
||||
space: std.heap.ArenaAllocator = .init(std.heap.page_allocator),
|
||||
threshold: usize = min_threshold,
|
||||
every_step: bool = false,
|
||||
stats: MemoryStats = .{},
|
||||
|
||||
const min_threshold = 4 << 20;
|
||||
};
|
||||
|
||||
const Machine = struct {
|
||||
arena: std.mem.Allocator,
|
||||
exec_heap: Heap = .{},
|
||||
module: air.Module,
|
||||
fuel: ?u64,
|
||||
tasks: std.ArrayList(Task) = .empty,
|
||||
@@ -335,6 +446,8 @@ const Machine = struct {
|
||||
try m.tasks.append(m.arena, .{});
|
||||
try m.pushFrame(0, fn_index, args);
|
||||
while (true) {
|
||||
// Safe point: between instructions no Zig local holds heap values.
|
||||
if (m.exec_heap.every_step or m.exec_heap.space.queryCapacity() > m.exec_heap.threshold) try m.collect();
|
||||
const t = &m.tasks.items[m.current];
|
||||
if (t.state != .runnable) {
|
||||
if (try m.schedule()) |o| return o;
|
||||
@@ -405,9 +518,58 @@ const Machine = struct {
|
||||
}
|
||||
}
|
||||
|
||||
fn heap(m: *Machine) std.mem.Allocator {
|
||||
return m.exec_heap.space.allocator();
|
||||
}
|
||||
|
||||
/// Copies the live execution state into a fresh heap and releases the
|
||||
/// old one. Roots: every task's frames, result and delivered value; the
|
||||
/// channels' buffered values and offers; the heap cells of live owners.
|
||||
fn collect(m: *Machine) std.mem.Allocator.Error!void {
|
||||
const before = m.exec_heap.space.queryCapacity();
|
||||
var next: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
errdefer next.deinit();
|
||||
var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
|
||||
defer tmp.deinit();
|
||||
var c: Copier = .{ .to = next.allocator(), .tmp = tmp.allocator() };
|
||||
for (m.tasks.items) |*t| {
|
||||
for (t.frames.items) |*fr| fr.vals = try c.items(fr.vals);
|
||||
t.result = try c.value(t.result);
|
||||
if (t.delivered) |*d| d.value = try c.value(d.value);
|
||||
}
|
||||
for (m.channels.items) |*ch| {
|
||||
var buf: std.ArrayList(Value) = .empty;
|
||||
try buf.ensureTotalCapacity(c.to, ch.buf.items.len - ch.head);
|
||||
for (ch.buf.items[ch.head..]) |v| buf.appendAssumeCapacity(try c.value(v));
|
||||
ch.buf = buf;
|
||||
ch.head = 0;
|
||||
var offers: std.ArrayList(Offer) = .empty;
|
||||
try offers.ensureTotalCapacity(c.to, ch.send_offers.items.len);
|
||||
for (ch.send_offers.items) |o| offers.appendAssumeCapacity(.{ .task = o.task, .arm = o.arm, .value = try c.value(o.value) });
|
||||
ch.send_offers = offers;
|
||||
if (ch.recv_offer) |*o| o.value = try c.value(o.value);
|
||||
}
|
||||
var owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty;
|
||||
try owners.ensureTotalCapacity(c.to, m.owners.count());
|
||||
var it = m.owners.iterator();
|
||||
while (it.next()) |e| owners.putAssumeCapacityNoClobber(try c.cell(e.key_ptr.*), e.value_ptr.*);
|
||||
m.owners = owners;
|
||||
|
||||
m.exec_heap.space.deinit();
|
||||
m.exec_heap.space = next;
|
||||
const live = m.exec_heap.space.queryCapacity();
|
||||
const st = &m.exec_heap.stats;
|
||||
st.collections += 1;
|
||||
st.peak_heap = @max(st.peak_heap, before);
|
||||
st.peak_live = @max(st.peak_live, live);
|
||||
m.exec_heap.threshold = @max(Heap.min_threshold, 2 * live);
|
||||
}
|
||||
|
||||
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);
|
||||
const vals = try m.heap().alloc(Value, f.values.len);
|
||||
// Slots not yet defined are read by `collect`: they start as void.
|
||||
@memset(vals, .void);
|
||||
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 });
|
||||
}
|
||||
@@ -434,7 +596,7 @@ const Machine = struct {
|
||||
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));
|
||||
for (m.tasks.items, 0..) |t, i| if (t.state == .runnable) try runnable.append(m.heap(), @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.
|
||||
@@ -663,7 +825,7 @@ const Machine = struct {
|
||||
/// Performs an `ok`-ready send.
|
||||
fn doSend(m: *Machine, id: u32, v: Value) !void {
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity > 0) return c.buf.append(m.arena, try m.deepCopy(v));
|
||||
if (c.capacity > 0) return c.buf.append(m.heap(), try m.deepCopy(v));
|
||||
const o = c.recv_offer.?;
|
||||
m.deliver(o, try m.deepCopy(v));
|
||||
}
|
||||
@@ -782,7 +944,7 @@ const Machine = struct {
|
||||
return .{ .jump_yield = x.cancelled };
|
||||
}
|
||||
const c = &m.channels.items[id];
|
||||
if (c.capacity == 0) try c.send_offers.append(m.arena, .{ .task = self, .arm = 0, .value = v });
|
||||
if (c.capacity == 0) try c.send_offers.append(m.heap(), .{ .task = self, .arm = 0, .value = v });
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
}
|
||||
@@ -819,9 +981,9 @@ const Machine = struct {
|
||||
fn execSelect(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select")) !Step {
|
||||
const self = m.current;
|
||||
const t = &m.tasks.items[self];
|
||||
const ids = try m.arena.alloc(air.ValueId, x.arms.len);
|
||||
const ids = try m.heap().alloc(air.ValueId, x.arms.len);
|
||||
const vs = air.Op.selectValues(x.arms, ids);
|
||||
const v_vals = try m.arena.alloc(Value, vs.len);
|
||||
const v_vals = try m.heap().alloc(Value, vs.len);
|
||||
for (vs, v_vals) |v, *o| o.* = vals[v];
|
||||
if (t.delivered) |d| {
|
||||
t.delivered = null;
|
||||
@@ -832,7 +994,7 @@ const Machine = struct {
|
||||
for (x.arms, 0..) |arm, i| {
|
||||
const ch = endpointOf(vals[arm.endpoint]);
|
||||
const st = if (arm.value == null) m.recvState(ch) else m.sendState(ch);
|
||||
if (st != .none) try ready_arms.append(m.arena, .{ @intCast(i), st });
|
||||
if (st != .none) try ready_arms.append(m.heap(), .{ @intCast(i), st });
|
||||
}
|
||||
if (ready_arms.items.len == 0) {
|
||||
if (cancelObservable(t)) {
|
||||
@@ -843,7 +1005,7 @@ const Machine = struct {
|
||||
const c = &m.channels.items[endpointOf(vals[arm.endpoint])];
|
||||
if (c.capacity != 0) continue;
|
||||
if (arm.value) |v| {
|
||||
try c.send_offers.append(m.arena, .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
try c.send_offers.append(m.heap(), .{ .task = self, .arm = @intCast(i), .value = vals[v] });
|
||||
} else c.recv_offer = .{ .task = self, .arm = @intCast(i) };
|
||||
}
|
||||
return .{ .wait = .op };
|
||||
@@ -873,8 +1035,8 @@ const Machine = struct {
|
||||
fn selectOk(m: *Machine, f: air.Function, vals: []Value, x: @FieldType(air.Op, "select"), i: u32, received: Value, vs: []const air.ValueId, v_vals: []const Value) !Step {
|
||||
const arm = x.arms[i];
|
||||
var params: std.ArrayList(Value) = .empty;
|
||||
if (arm.value == null) try params.append(m.arena, received);
|
||||
for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.arena, val);
|
||||
if (arm.value == null) try params.append(m.heap(), received);
|
||||
for (vs, v_vals) |v, val| if (arm.value == null or arm.value.? != v) try params.append(m.heap(), val);
|
||||
setParams(f, vals, arm.ok, params.items);
|
||||
return .{ .jump_yield = arm.ok };
|
||||
}
|
||||
@@ -882,8 +1044,10 @@ const Machine = struct {
|
||||
fn execMutex(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
|
||||
switch (inst.op) {
|
||||
.mutex_make => |v| {
|
||||
const mc = try m.arena.create(Value.MutexCell);
|
||||
mc.* = .{ .locked = false, .cell = .{ .value = try m.deepCopy(vals[v]), .ty = .void } };
|
||||
const mc = try m.heap().create(Value.MutexCell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = try m.deepCopy(vals[v]), .ty = .void };
|
||||
mc.* = .{ .locked = false, .cell = cell };
|
||||
return bind(vals, inst.result, .{ .mutex = mc });
|
||||
},
|
||||
.mutex_take => |v| return bind(vals, inst.result, vals[v].mutex.cell.value),
|
||||
@@ -897,7 +1061,7 @@ const Machine = struct {
|
||||
if (cancelObservable(&m.tasks.items[m.current])) return .{ .jump_yield = x.cancelled };
|
||||
return .{ .wait = .op };
|
||||
},
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = &vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_borrow => |g| return bind(vals, inst.result, .{ .place = .{ .cell = vals[g].guard.cell, .path = &.{} } }),
|
||||
.mutex_unlock => |g| {
|
||||
vals[g].guard.locked = false;
|
||||
return .yield;
|
||||
@@ -932,7 +1096,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn copyAll(m: *Machine, items: []const Value) std.mem.Allocator.Error![]Value {
|
||||
const out = try m.arena.alloc(Value, items.len);
|
||||
const out = try m.heap().alloc(Value, items.len);
|
||||
for (items, out) |x, *o| o.* = try m.deepCopy(x);
|
||||
return out;
|
||||
}
|
||||
@@ -942,13 +1106,13 @@ const Machine = struct {
|
||||
.int => |it| .{ .int = .{ .ty = it, .bits = 0 } },
|
||||
.bool => .{ .boolean = false },
|
||||
.array => |a| blk: {
|
||||
const items = try m.arena.alloc(Value, a.len);
|
||||
const items = try m.heap().alloc(Value, a.len);
|
||||
for (items) |*x| x.* = try m.zeroValue(a.elem);
|
||||
break :blk .{ .array = items };
|
||||
},
|
||||
.named => |i| blk: {
|
||||
const fields = m.module.types[i].kind.@"struct";
|
||||
const out = try m.arena.alloc(Value, fields.len);
|
||||
const out = try m.heap().alloc(Value, fields.len);
|
||||
for (fields, out) |fd, *o| o.* = try m.zeroValue(fd.ty);
|
||||
break :blk .{ .aggregate = .{ .decl = i, .variant = 0, .fields = out } };
|
||||
},
|
||||
@@ -967,7 +1131,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn extend(m: *Machine, p: Value.Place, i: u64) !Value.Place {
|
||||
const path = try m.arena.alloc(u32, p.path.len + 1);
|
||||
const path = try m.heap().alloc(u32, p.path.len + 1);
|
||||
@memcpy(path[0..p.path.len], p.path);
|
||||
path[p.path.len] = @intCast(i);
|
||||
return .{ .cell = p.cell, .path = path };
|
||||
@@ -1004,7 +1168,7 @@ const Machine = struct {
|
||||
fn bytesOf(m: *Machine, v: Value) ![]u8 {
|
||||
const s = v.slice;
|
||||
const items = placePtr(s.place).array[s.start..][0..s.len];
|
||||
const out = try m.arena.alloc(u8, items.len);
|
||||
const out = try m.heap().alloc(u8, items.len);
|
||||
for (items, out) |x, *o| o.* = @truncate(x.int.bits);
|
||||
return out;
|
||||
}
|
||||
@@ -1045,7 +1209,7 @@ const Machine = struct {
|
||||
vals[f.blocks[x.err].params[0].value] = .{ .builtin = .{ .which = .cap_error, .variant = r } };
|
||||
return .{ .jump = x.err };
|
||||
}
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = path });
|
||||
try m.authorities.append(m.arena, .{ .kind = a.kind, .scope = try m.arena.dupe(u8, path) });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .cap = @intCast(m.authorities.items.len - 1) };
|
||||
return .{ .jump = x.ok };
|
||||
}
|
||||
@@ -1096,8 +1260,6 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
/// Owner cells remember their charge and authority for `own.free`.
|
||||
const OwnInfo = struct { authority: u32, bytes: u64 };
|
||||
|
||||
fn execAlloc(m: *Machine, f: air.Function, vals: []Value, types_of: anytype, inst: air.Inst) !Step {
|
||||
_ = types_of;
|
||||
switch (inst.op) {
|
||||
@@ -1106,9 +1268,9 @@ const Machine = struct {
|
||||
const bytes = m.valueBytes(vals[x.value]);
|
||||
const a = vals[x.cap].cap;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
@@ -1117,11 +1279,11 @@ const Machine = struct {
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = m.arrayBytes(vals[x.value], n);
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const items = try m.arena.alloc(Value, n);
|
||||
const items = try m.heap().alloc(Value, n);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
try m.owners.put(m.arena, cell, .{ .authority = a, .bytes = bytes.? });
|
||||
try m.owners.put(m.heap(), cell, .{ .authority = a, .bytes = bytes.? });
|
||||
vals[f.blocks[x.ok].params[0].value] = .{ .own = cell };
|
||||
return .{ .jump = x.ok };
|
||||
},
|
||||
@@ -1153,9 +1315,9 @@ const Machine = struct {
|
||||
const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]);
|
||||
if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err);
|
||||
region.used += bytes.?;
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
if (n) |count| {
|
||||
const items = try m.arena.alloc(Value, count);
|
||||
const items = try m.heap().alloc(Value, count);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[value]);
|
||||
cell.* = .{ .value = .{ .array = items }, .ty = .void };
|
||||
vals[f.blocks[t.ok].params[0].value] = .{ .slice = .{ .place = .{ .cell = cell, .path = &.{} }, .start = 0, .len = count } };
|
||||
@@ -1194,7 +1356,7 @@ const Machine = struct {
|
||||
const now = if (m.host) |*hs| hs.monotonic() else m.steps;
|
||||
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = now } });
|
||||
} else if (is(name, "random.fill")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
if (m.host) |*hs| hs.fill(buf) else m.world.fill(buf);
|
||||
fillSlice(arg(vals, x, 1), buf);
|
||||
return .next;
|
||||
@@ -1203,7 +1365,7 @@ const Machine = struct {
|
||||
const err_stream = is(name, "io.stderr_write");
|
||||
if (m.host) |*hs| failure = hs.writeOut(err_stream, bytes) else try m.world.writeOut(err_stream, bytes);
|
||||
} else if (is(name, "io.stdin_read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const n: usize = if (m.host) |*hs| switch (hs.readIn(buf)) {
|
||||
.ok => |k| k,
|
||||
.err => |e| blk: {
|
||||
@@ -1222,7 +1384,7 @@ const Machine = struct {
|
||||
.err => |e| failure = e,
|
||||
}
|
||||
} else if (is(name, "fs.read")) {
|
||||
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const hd = resourceOf(arg(vals, x, 0));
|
||||
const n: usize = if (m.host) |*hs| switch (hs.fileRead(hd, buf)) {
|
||||
.ok => |k| k,
|
||||
@@ -1260,7 +1422,7 @@ const Machine = struct {
|
||||
.err => |e| failure = e,
|
||||
} 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 buf = try m.heap().alloc(u8, arg(vals, x, 1).slice.len);
|
||||
const hd = resourceOf(arg(vals, x, 0));
|
||||
const n: usize = if (m.host) |*hs| switch (hs.recv(hd, buf)) {
|
||||
.ok => |k| k,
|
||||
@@ -1292,7 +1454,7 @@ const Machine = struct {
|
||||
fn execMemory(m: *Machine, vals: []Value, inst: air.Inst) std.mem.Allocator.Error!Step {
|
||||
switch (inst.op) {
|
||||
.local_alloc => |t| {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .void, .ty = t };
|
||||
return bind(vals, inst.result, .{ .local = cell });
|
||||
},
|
||||
@@ -1315,12 +1477,12 @@ const Machine = struct {
|
||||
else => .{ .place = .{ .cell = cell, .path = &.{} } },
|
||||
},
|
||||
.region => |r| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .region = r }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
.resource => |hd| blk: {
|
||||
const cell = try m.arena.create(Value.Cell);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
cell.* = .{ .value = .{ .resource = hd }, .ty = .void };
|
||||
break :blk .{ .place = .{ .cell = cell, .path = &.{} } };
|
||||
},
|
||||
@@ -1334,7 +1496,7 @@ const Machine = struct {
|
||||
return .next;
|
||||
},
|
||||
.array_splat => |x| {
|
||||
const items = try m.arena.alloc(Value, x.ty.array.len);
|
||||
const items = try m.heap().alloc(Value, x.ty.array.len);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
return bind(vals, inst.result, .{ .array = items });
|
||||
},
|
||||
@@ -1392,7 +1554,7 @@ const Machine = struct {
|
||||
}
|
||||
|
||||
fn gatherMut(m: *Machine, vals: []const Value, ids: []const air.ValueId) ![]Value {
|
||||
const out = try m.arena.alloc(Value, ids.len);
|
||||
const out = try m.heap().alloc(Value, ids.len);
|
||||
for (ids, out) |id, *o| o.* = vals[id];
|
||||
return out;
|
||||
}
|
||||
@@ -1879,3 +2041,110 @@ test "schedule seed: explicit value is used as is, default derives from the prog
|
||||
_ = try run(arena, report.module.?, "main", .{ .world = .{ .seed = 3 }, .output = &out });
|
||||
try std.testing.expectEqual(@as(u64, 3 ^ 0x5343484544554c45), out.schedule.?.seed);
|
||||
}
|
||||
|
||||
// Memory use is bounded by live state, not by the number of instructions
|
||||
// executed. Measured with the interpreter's own heap counters,
|
||||
// not host RSS: for each loop shape, the live execution state after a
|
||||
// collection must not grow with the iteration count, and the heap stays
|
||||
// under a fixed bound.
|
||||
fn memoryOf(comptime body: []const u8, n: u64) !MemoryStats {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const arena = arena_state.allocator();
|
||||
const src = try std.fmt.allocPrint(arena, body, .{n});
|
||||
const report = try check.checkFile(arena, "t.aji", src);
|
||||
if (report.status != .accepted) {
|
||||
for (report.diagnostics) |d| std.debug.print("{s} {s}\n", .{ d.code.id, d.message });
|
||||
return error.NotAccepted;
|
||||
}
|
||||
var stats: MemoryStats = .{};
|
||||
const outcome = try run(arena, report.module.?, "main", .{ .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "4096" }}, .memory = &stats });
|
||||
try std.testing.expect(outcome == .returned);
|
||||
return stats;
|
||||
}
|
||||
|
||||
const loop_shapes = [_][]const u8{
|
||||
// scalar state carried in block arguments
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{ s = s +% i; i = i + 1; }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
// element access through borrows (places and paths)
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var a: [u64; 8] = zero;
|
||||
\\ var i: u64 = 0;
|
||||
\\ while i < {d} {{ a[i as! usize % 8] = a[(i as! usize + 1) % 8] +% i; i = i + 1; }}
|
||||
\\ a[0]
|
||||
\\}}
|
||||
,
|
||||
// a call per iteration (frames)
|
||||
\\module t
|
||||
\\fn step(x: u64, b: slice<u64>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ x +% b[x as! usize % 4]
|
||||
\\}}
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var b: [u64; 4] = [3; 4];
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{ s = step(s, ref b); i = i + 1; }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
// aggregate and array values built and copied every iteration
|
||||
\\module t
|
||||
\\struct P {{ a: u64, b: [u64; 4] }}
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects []
|
||||
\\{{
|
||||
\\ var p: P = P {{ a: 0, b: [1; 4] }};
|
||||
\\ var i: u64 = 0;
|
||||
\\ while i < {d} {{ p = P {{ a: p.a +% i, b: [i; 4] }}; i = i + 1; }}
|
||||
\\ p.a
|
||||
\\}}
|
||||
,
|
||||
// heap allocation and free every iteration
|
||||
\\module t
|
||||
\\fn main(heap: cap<mem.alloc>) -> u64
|
||||
\\effects [mem.alloc]
|
||||
\\{{
|
||||
\\ var i: u64 = 0;
|
||||
\\ var s: u64 = 0;
|
||||
\\ while i < {d} {{
|
||||
\\ let o = own.new(i, heap) or trap;
|
||||
\\ s = s +% own.take(move o);
|
||||
\\ i = i + 1;
|
||||
\\ }}
|
||||
\\ s
|
||||
\\}}
|
||||
,
|
||||
};
|
||||
|
||||
test "execution memory is bounded by live state, not by the iteration count" {
|
||||
inline for (loop_shapes, 0..) |shape, k| {
|
||||
const small = try memoryOf(shape, 100_000);
|
||||
const mid = try memoryOf(shape, 1_000_000);
|
||||
const large = try memoryOf(shape, 4_000_000);
|
||||
errdefer std.debug.print("shape {d}: live {d}/{d}/{d} heap {d}/{d}/{d} collections {d}/{d}/{d}\n", .{
|
||||
k, small.peak_live, mid.peak_live, large.peak_live, small.peak_heap, mid.peak_heap, large.peak_heap,
|
||||
small.collections, mid.collections, large.collections,
|
||||
});
|
||||
try std.testing.expect(large.collections > 0);
|
||||
// Steady state: the live state of 4M iterations is the live state of 1M.
|
||||
try std.testing.expect(large.peak_live <= mid.peak_live + 64 * 1024);
|
||||
// The heap is bounded by a constant (collection threshold plus one growth step).
|
||||
try std.testing.expect(large.peak_heap <= 3 * Heap.min_threshold);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// A void function ending in a nested block falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 12
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.block_tail
|
||||
|
||||
fn f(c: mut<u64>) -> void
|
||||
effects []
|
||||
{
|
||||
{
|
||||
let d = 2u64;
|
||||
*c = *c + d;
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c);
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// A void function ending in an `if`/`else` statement falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 21
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.if_else
|
||||
|
||||
fn f(c: mut<u64>, x: u64) -> void
|
||||
effects []
|
||||
{
|
||||
if x == 2 { *c = *c + 10; } else { *c = *c + 1; }
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c, 2);
|
||||
f(mut c, 3);
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// A void function ending in an `if` statement whose branch returns falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 13
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.if_with_return
|
||||
|
||||
fn f(c: mut<u64>, x: u64) -> void
|
||||
effects []
|
||||
{
|
||||
*c = *c + 1;
|
||||
if x == 2 { return; }
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c, 1);
|
||||
f(mut c, 2);
|
||||
f(mut c, 3);
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
module demo.if_with_return
|
||||
air 0
|
||||
lang 0.1
|
||||
features [effects, ownership]
|
||||
|
||||
fn @f(%c: mut<u64>, %x: u64) -> void
|
||||
effects []
|
||||
entry:
|
||||
%v_1 = load %c
|
||||
%c_2 = const.u64 1
|
||||
%t_3 = add.checked.u64 %v_1, %c_2
|
||||
store %c, %t_3
|
||||
%c_4 = const.u64 2
|
||||
%cmp_5 = eq.u64 %x, %c_4
|
||||
cbr %cmp_5, @then_6(), @else_7()
|
||||
then_6:
|
||||
ret
|
||||
else_7:
|
||||
br @endif_8()
|
||||
endif_8:
|
||||
ret
|
||||
|
||||
fn @main() -> u64
|
||||
effects []
|
||||
entry:
|
||||
%c_1 = local.alloc u64
|
||||
%c_2 = const.u64 10
|
||||
local.store %c_1, %c_2
|
||||
%c_3 = borrow.mut %c_1
|
||||
%c_4 = const.u64 1
|
||||
call @f(%c_3, %c_4)
|
||||
borrow.end %c_3
|
||||
%c_5 = borrow.mut %c_1
|
||||
%c_6 = const.u64 2
|
||||
call @f(%c_5, %c_6)
|
||||
borrow.end %c_5
|
||||
%c_7 = borrow.mut %c_1
|
||||
%c_8 = const.u64 3
|
||||
call @f(%c_7, %c_8)
|
||||
borrow.end %c_7
|
||||
%c_9 = local.load %c_1
|
||||
ret %c_9
|
||||
@@ -0,0 +1,23 @@
|
||||
// A void function ending in a `loop` left by `break` falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 13
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.loop_tail
|
||||
|
||||
fn f(c: mut<u64>) -> void
|
||||
effects []
|
||||
{
|
||||
loop {
|
||||
*c = *c + 1;
|
||||
if *c > 12 { break; }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c);
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// A void function ending in a `match` statement with void arms falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 17
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.match_tail
|
||||
|
||||
enum Op {
|
||||
Inc,
|
||||
Add(u64),
|
||||
}
|
||||
|
||||
fn f(c: mut<u64>, op: Op) -> void
|
||||
effects []
|
||||
{
|
||||
match op {
|
||||
Op::Inc => { *c = *c + 1; }
|
||||
Op::Add(n) => { *c = *c + n; }
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c, Op::Inc);
|
||||
f(mut c, Op::Add(6));
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// A void function whose tail is a call of a void function falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 11
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.void_call_tail
|
||||
|
||||
fn g(c: mut<u64>) -> void
|
||||
effects []
|
||||
{
|
||||
*c = *c + 1;
|
||||
}
|
||||
|
||||
fn f(c: mut<u64>) -> void
|
||||
effects []
|
||||
{
|
||||
g(c)
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c);
|
||||
c
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// A void function ending in a `while` loop falls through to `ret`.
|
||||
// expect: run
|
||||
// result: 15
|
||||
// phase: 6
|
||||
// spec: docs/spec/15-source-language.md
|
||||
module demo.while_tail
|
||||
|
||||
fn f(c: mut<u64>, n: u64) -> void
|
||||
effects []
|
||||
{
|
||||
var i: u64 = 0;
|
||||
while i < n { *c = *c + 1; i = i + 1; }
|
||||
}
|
||||
|
||||
fn main() -> u64
|
||||
effects []
|
||||
{
|
||||
var c: u64 = 10;
|
||||
f(mut c, 5);
|
||||
c
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Conformance suite runner. Format: tests/conformance/README.md.
|
||||
//!
|
||||
//! usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>]
|
||||
//! usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>] [--collect-every-step]
|
||||
//!
|
||||
//! `--stress N` (P3-12): every test with a `schedules:` header runs schedule
|
||||
//! seeds 0 … N-1 under each quantum of `stress_quanta` and its own quantum,
|
||||
@@ -65,7 +65,7 @@ pub fn main(init: std.process.Init) !void {
|
||||
const args = try init.minimal.args.toSlice(arena);
|
||||
|
||||
if (args.len < 2) {
|
||||
std.debug.print("usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>]\n", .{});
|
||||
std.debug.print("usage: aji-conformance <dir> [--json] [--filter <substring>] [--stress <seeds>] [--collect-every-step]\n", .{});
|
||||
std.process.exit(2);
|
||||
}
|
||||
const root = args[1];
|
||||
@@ -78,6 +78,8 @@ pub fn main(init: std.process.Init) !void {
|
||||
} else if (std.mem.eql(u8, args[i], "--filter") and i + 1 < args.len) {
|
||||
i += 1;
|
||||
filter = args[i];
|
||||
} else if (std.mem.eql(u8, args[i], "--collect-every-step")) {
|
||||
collect_every_step = true;
|
||||
} else if (std.mem.eql(u8, args[i], "--stress") and i + 1 < args.len) {
|
||||
i += 1;
|
||||
stress_seeds = std.fmt.parseInt(u64, args[i], 10) catch {
|
||||
@@ -134,6 +136,9 @@ pub fn main(init: std.process.Init) !void {
|
||||
|
||||
/// Seeds per quantum under `--stress`; null runs each test's `schedules:`.
|
||||
var stress_seeds: ?u64 = null;
|
||||
/// The second of the two runs of every `run` test collects the execution
|
||||
/// heap before every instruction; the run records must still be identical.
|
||||
var collect_every_step = false;
|
||||
|
||||
/// Quanta of the stress mode: forced yield after every instruction, short
|
||||
/// and odd slices (spec 04 §36.3); the test's own quantum is added.
|
||||
@@ -310,7 +315,7 @@ fn runSeed(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, h
|
||||
var records: [2][]const u8 = undefined;
|
||||
var outcome: aji.interp.Outcome = undefined;
|
||||
var output: aji.interp.Output = undefined;
|
||||
for (&records) |*rec| {
|
||||
for (&records, 0..) |*rec, k| {
|
||||
outcome = aji.interp.run(arena, module, "main", .{
|
||||
.fuel = header.fuel,
|
||||
.grants = header.grants,
|
||||
@@ -318,6 +323,7 @@ fn runSeed(arena: std.mem.Allocator, module: aji.air.Module, want: Expect.Run, h
|
||||
.output = &output,
|
||||
.quantum = header.quantum,
|
||||
.task_limit = header.task_limit,
|
||||
.collect_every_step = collect_every_step and k == 1,
|
||||
.schedule_seed = schedule_seed,
|
||||
}) catch |err| switch (err) {
|
||||
error.EntryNotFound => return .{ .outcome = .fail, .detail = "module has no @main whose parameters are all capabilities" },
|
||||
|
||||
@@ -20,7 +20,9 @@
|
||||
read_tokens_by_group tokens of the group's lines the agent saw
|
||||
coverage_by_section per file: fraction of its distinctive lines
|
||||
(in no other file of the mount) seen
|
||||
files_opened files whose /docs path occurs in a tool input
|
||||
files_opened files named in a tool input: by /docs path, by
|
||||
path relative to /docs, or by file name as a
|
||||
whole token (`cd /docs/language; cat syntax.md`)
|
||||
unique_docs_read how many files were opened
|
||||
|
||||
The gap between them shows where context is amplified: rereading the same
|
||||
@@ -112,6 +114,15 @@ def _doc_files(docs):
|
||||
return sorted(out)
|
||||
|
||||
|
||||
def _named(rel, inputs):
|
||||
"""Whether a tool input names the file: `/docs/<rel>`, `<rel>`, or its
|
||||
file name as a whole token."""
|
||||
for name in {rel, os.path.basename(rel)}:
|
||||
if re.search(r"(?<![\w.-])" + re.escape(name) + r"(?![\w.-])", inputs):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _group_of(rel, groups):
|
||||
for g, prefixes in groups.items():
|
||||
for pre in prefixes:
|
||||
@@ -145,7 +156,7 @@ def doc_metrics(tool_events, docs, groups, seen, count):
|
||||
for rel, _ in files:
|
||||
mine = own.get(rel, set())
|
||||
coverage[rel] = round(len(mine & seen) / len(mine), 4) if mine else 0.0
|
||||
if "/docs/" + rel in inputs:
|
||||
if _named(rel, inputs):
|
||||
opened.append(rel)
|
||||
g = _group_of(rel, groups)
|
||||
size[g] = size.get(g, 0) + count(texts[rel])
|
||||
|
||||
@@ -275,6 +275,24 @@ class CheckpointTest(unittest.TestCase):
|
||||
self.assertEqual(b["other"], 5) # effects and capabilities are not dropped
|
||||
|
||||
|
||||
class DocsReadTest(unittest.TestCase):
|
||||
def test_files_opened_by_relative_path(self):
|
||||
from ajieval import context
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
os.makedirs(os.path.join(d, "language"))
|
||||
for rel in ("QUICK.md", "language/syntax.md", "language/types.md", "language/memory.md"):
|
||||
with open(os.path.join(d, rel), "w") as f:
|
||||
f.write(f"only in {rel}\n")
|
||||
events = [('{"command": "cat /docs/QUICK.md"}', "only in QUICK.md"),
|
||||
('{"command": "cd /docs/language && cat syntax.md"}', "only in language/syntax.md"),
|
||||
('{"command": "cat language/types.md"}', "only in language/types.md"),
|
||||
('{"command": "cat mysyntax.md types.mdx"}', "")]
|
||||
seen = {o for _, o in events if o}
|
||||
m = context.doc_metrics(events, [("", d)], {}, seen, len)
|
||||
self.assertEqual(m["files_opened"], ["QUICK.md", "language/syntax.md", "language/types.md"])
|
||||
self.assertEqual(m["coverage_by_section"]["language/memory.md"], 0.0)
|
||||
|
||||
|
||||
class CyclesTest(unittest.TestCase):
|
||||
def test_repair_cycles_from_commands(self):
|
||||
from ajieval import native
|
||||
|
||||
Reference in new issue
Block a user