Phase 4: islands, frozen graphs and arc through every layer (RFC 0014)

AIR: types island<T>, frozen<T>, arc<T>, iref<T>; 16 instructions
(island.create/alloc/root/borrow/freeze/destroy, frozen.root/borrow/
release, arc.from_frozen/new/clone/release/root/borrow, iref.eq); features
islands (depends on heap) and arc (depends on islands) published.
Verifier: IslandSafe/ArcSafe (E2111 at the owner type), container child
borrows (one mut access per island), Send/Share rows (island not Share),
linear owners, mem.alloc effect, element rules (recursion through iref).
Interpreter: graphs with never-reused identities, T0010 for a foreign
iref, O(1) freeze/conversion/transfer, arc counts in a trace hook
(Options.arc_events), budgets per the quota table, collector support.
.aji layer 9: types, operations, island.at/frozen.at/arc.at as borrow
places with explicit container borrows, iref ==/!=.
Frontend fix: joins carry only variables the construct assigns (and that
are read again), so an unchanged linear value is never a block argument
while borrowed.

Tests: 10 AIR (phase4), 6 .aji run + 12 rejects (layer9), the reference
program island-pipeline in .aji, equivalent to an independently
hand-written AIR program (36 on 30 schedule seeds); unit tests for the
arc count trace and O(1) transfer. Quick Reference §7 graphs (checked
excerpt of quickref/graphs.aji); coverage 61/61. Bundle growth: AIR
+7.0%, Quick Reference +0.6k, source docs +4.2k (recorded).
Spec: quota rows match the header-reserved count; idioms and iref
recursion in spec 03 §22; P4-11 (air-text.ebnf gaps) recorded.
This commit is contained in:
dev committed 2026-10-05 22:14:05 +03:00
1 parent ca84ab4348
commit c699529fec
58 files changed
+2189 -98

No files matched your search

+261 -2
View File
@@ -67,11 +67,28 @@ pub const Value = union(enum) {
/// `mutex<T>` and the `guard<T>` that holds it.
mutex: *MutexCell,
guard: *MutexCell,
/// `island<T>`, `frozen<T>`, `arc<T>`: the graph (spec 03 §22–§24). The
/// ownership mode is the static type; the graph is the same object.
graph: *Graph,
/// `iref<T>`: graph identity and slot; opaque to programs.
iref: struct { id: u64, slot: u32 },
/// 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 };
/// A graph: object cells addressed by slot, an identity never reused in
/// the execution, the authority it charges and the bytes it holds.
pub const Graph = struct {
id: u64,
objects: std.ArrayList(*Cell) = .empty,
authority: u32,
bytes: u64,
/// `arc` handles alive (0 while unique: island or frozen).
count: u64 = 0,
frozen: bool = false,
};
pub const Aggregate = struct {
decl: u32,
/// Active variant for enums; 0 for structs.
@@ -148,9 +165,16 @@ pub const MemoryStats = struct {
peak_live: usize = 0,
/// Largest execution heap before a collection, in heap bytes.
peak_heap: usize = 0,
/// Instructions executed.
steps: u64 = 0,
};
/// One `arc` count change (spec 03 §24: every change appears in the trace).
pub const ArcEvent = struct { op: enum { new, from_frozen, clone, release }, graph: u64, count: u64 };
pub const Options = struct {
/// Trace mode for `arc` counts: every change is appended (spec 11 §2).
arc_events: ?*std.ArrayList(ArcEvent) = null,
/// Filled with execution-heap statistics when set.
memory: ?*MemoryStats = null,
/// Collect before every instruction (tests: a missed root then fails).
@@ -237,6 +261,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
}
m.exec_heap.every_step = options.collect_every_step;
m.arc_events = options.arc_events;
if (options.collect_threshold) |t| {
m.exec_heap.floor = t;
m.exec_heap.threshold = t;
@@ -251,6 +276,7 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
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());
m.exec_heap.stats.steps = m.steps;
if (options.memory) |st| st.* = m.exec_heap.stats;
m.exec_heap.space.deinit();
return result;
@@ -264,6 +290,7 @@ const Copier = struct {
cells: std.AutoHashMapUnmanaged(*Value.Cell, *Value.Cell) = .empty,
mutexes: std.AutoHashMapUnmanaged(*Value.MutexCell, *Value.MutexCell) = .empty,
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty,
fn value(c: *Copier, v: Value) std.mem.Allocator.Error!Value {
return switch (v) {
@@ -275,7 +302,8 @@ const Copier = struct {
.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,
.graph => |g| .{ .graph = try c.graph(g) },
.int, .boolean, .void, .cap, .resource, .region, .scope, .task, .builtin, .shield, .sender, .receiver, .iref => v,
};
}
@@ -308,6 +336,17 @@ const Copier = struct {
return n;
}
fn graph(c: *Copier, old: *Value.Graph) std.mem.Allocator.Error!*Value.Graph {
if (c.graphs.get(old)) |n| return n;
const n = try c.to.create(Value.Graph);
try c.graphs.put(c.tmp, old, n);
n.* = old.*;
n.objects = .empty;
try n.objects.ensureTotalCapacity(c.to, old.objects.items.len);
for (old.objects.items) |cl| n.objects.appendAssumeCapacity(try c.cell(cl));
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) };
}
@@ -323,6 +362,7 @@ const TrapKind = enum {
call_depth,
out_of_bounds,
unsafe_precondition,
foreign_iref,
fn code(k: TrapKind) *const diag.Code {
return switch (k) {
@@ -335,6 +375,7 @@ const TrapKind = enum {
.call_depth => diag.lookup("T0007").?,
.out_of_bounds => diag.lookup("T0008").?,
.unsafe_precondition => diag.lookup("T0009").?,
.foreign_iref => diag.lookup("T0010").?,
};
}
};
@@ -422,6 +463,9 @@ pub const Heap = struct {
const Machine = struct {
arena: std.mem.Allocator,
exec_heap: Heap = .{},
/// Next graph identity; identities are never reused (spec 03 §22).
next_graph: u64 = 1,
arc_events: ?*std.ArrayList(ArcEvent) = null,
module: air.Module,
fuel: ?u64,
tasks: std.ArrayList(Task) = .empty,
@@ -750,6 +794,7 @@ const Machine = struct {
.channel_make, .channel_dup, .channel_send, .channel_recv, .channel_close_sender, .channel_close_receiver, .select => return m.execChannel(f, vals, inst),
.mutex_make, .mutex_take, .mutex_lock, .mutex_borrow, .mutex_unlock => return m.execMutex(f, vals, inst),
.own_new, .own_array, .own_take, .own_free, .region_create, .region_new, .region_array, .region_reset, .region_destroy => return m.execAlloc(f, vals, {}, inst),
.island_create, .island_alloc, .island_root, .island_borrow, .island_freeze, .island_destroy, .frozen_root, .frozen_borrow, .frozen_release, .arc_from_frozen, .arc_new, .arc_clone, .arc_release, .arc_root, .arc_borrow, .iref_eq => return m.execGraph(f, vals, inst),
.intrinsic => |x| return m.intrinsic(f, vals, inst, x),
.ret => |v| return .{ .ret = if (v) |x| vals[x] else .void },
.trap => return .{ .trap = .explicit },
@@ -1259,10 +1304,124 @@ const Machine = struct {
.array => |items| std.math.mul(u64, items.len, m.valueBytes(items[0]) orelse return null) catch null,
.builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0),
.cap => 8,
.iref => 16,
else => unreachable, // only value types are allocated (spec 03 §19.2)
};
}
// ------------------------------------------------------------ graphs (spec 03 §22–§24)
/// A graph's header, charged once at creation; it includes room for an
/// `arc` count, so converting to an `arc` charges nothing (spec 03 §24).
const graph_header = 16;
/// The graph behind an owner or a borrow of one.
fn graphOf(v: Value) *Value.Graph {
return switch (v) {
.graph => |g| g,
.place => |p| placePtr(p).graph,
else => unreachable,
};
}
fn arcEvent(m: *Machine, op: @FieldType(ArcEvent, "op"), g: *Value.Graph) !void {
if (m.arc_events) |list| try list.append(m.arena, .{ .op = op, .graph = g.id, .count = g.count });
}
fn newGraph(m: *Machine, a: u32, bytes: u64, root: Value) !*Value.Graph {
const g = try m.heap().create(Value.Graph);
g.* = .{ .id = m.next_graph, .authority = a, .bytes = bytes };
m.next_graph += 1;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(root), .ty = .void };
try g.objects.append(m.heap(), cell);
return g;
}
/// Frees a graph's objects and returns its bytes to its authority.
fn releaseGraph(m: *Machine, g: *Value.Graph) void {
m.uncharge(g.authority, g.bytes);
g.bytes = 0;
g.objects = .empty;
}
/// The object an `iref` names in graph `g`, or `T0010`.
fn objectOf(g: *Value.Graph, r: Value) ?*Value.Cell {
if (r.iref.id != g.id or r.iref.slot >= g.objects.items.len) return null;
return g.objects.items[r.iref.slot];
}
fn execGraph(m: *Machine, f: air.Function, vals: []Value, inst: air.Inst) !Step {
switch (inst.op) {
inline .island_create, .arc_new => |x| {
const v = vals[x.value];
const a = vals[x.cap].cap;
const bytes = if (m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null;
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
const g = try m.newGraph(a, bytes.?, v);
if (inst.op == .arc_new) {
g.frozen = true;
g.count = 1;
try m.arcEvent(.new, g);
}
vals[f.blocks[x.ok].params[0].value] = .{ .graph = g };
return .{ .jump = x.ok };
},
.island_alloc => |x| {
const g = graphOf(vals[x.island]);
const v = vals[x.value];
const bytes = m.valueBytes(v);
if (!m.charge(g.authority, bytes)) return allocFailed(f, vals, x.err);
g.bytes += bytes.?;
const cell = try m.heap().create(Value.Cell);
cell.* = .{ .value = try m.deepCopy(v), .ty = .void };
try g.objects.append(m.heap(), cell);
vals[f.blocks[x.ok].params[0].value] = .{ .iref = .{ .id = g.id, .slot = @intCast(g.objects.items.len - 1) } };
return .{ .jump = x.ok };
},
.island_root, .frozen_root, .arc_root => |v| return bind(vals, inst.result, .{ .iref = .{ .id = graphOf(vals[v]).id, .slot = 0 } }),
inline .island_borrow, .frozen_borrow, .arc_borrow => |x| {
const g = graphOf(vals[x.owner]);
const cell = objectOf(g, vals[x.iref]) orelse return .{ .trap = .foreign_iref };
return bind(vals, inst.result, .{ .place = .{ .cell = cell, .path = &.{} } });
},
.island_freeze => |v| {
const g = vals[v].graph;
g.frozen = true;
return bind(vals, inst.result, .{ .graph = g });
},
.island_destroy, .frozen_release => |v| {
m.releaseGraph(vals[v].graph);
return .next;
},
.arc_from_frozen => |v| {
const g = vals[v].graph;
g.count = 1;
try m.arcEvent(.from_frozen, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_clone => |v| {
const g = graphOf(vals[v]);
g.count += 1;
try m.arcEvent(.clone, g);
return bind(vals, inst.result, .{ .graph = g });
},
.arc_release => |v| {
const g = vals[v].graph;
g.count -= 1;
try m.arcEvent(.release, g);
if (g.count == 0) m.releaseGraph(g);
return .next;
},
.iref_eq => |x| {
const a = vals[x.a].iref;
const b = vals[x.b].iref;
return bind(vals, inst.result, .{ .boolean = a.id == b.id and a.slot == b.slot });
},
else => unreachable,
}
}
fn allocFailed(f: air.Function, vals: []Value, err: u32) Step {
vals[f.blocks[err].params[0].value] = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } };
return .{ .jump = err };
@@ -1698,7 +1857,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, .scope, .task, .shield, .sender, .receiver, .mutex, .guard => try s.write(null),
.resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref => try s.write(null),
// A capability is opaque: only its kind is shown, never its identity.
.cap => {
try s.beginObject();
@@ -2159,3 +2318,103 @@ test "execution memory is bounded by live state, not by the iteration count" {
try std.testing.expect(large.peak_heap <= 3 * floor + 64 * 1024);
}
}
test "arc count changes appear in the trace, and the last release frees the graph" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src =
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc]
\\{
\\ let isl = island.create(7u64, heap) or trap;
\\ let a = arc.from_frozen(island.freeze(move isl));
\\ let b = arc.clone(a);
\\ arc.release(move a);
\\ var v: u64 = 0;
\\ {
\\ ref br = b;
\\ let r = arc.root(br);
\\ ref x = arc.at(br, r);
\\ v = *x;
\\ }
\\ arc.release(move b);
\\ // The budget (16 + 8 bytes) is free again: the same graph fits once more.
\\ let again = arc.new(5u64, heap) or trap;
\\ arc.release(move again);
\\ v
\\}
;
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 events: std.ArrayList(ArcEvent) = .empty;
const outcome = try run(arena, report.module.?, "main", .{
.grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "24" }},
.arc_events = &events,
});
try std.testing.expect(outcome == .returned);
try std.testing.expectEqual(@as(u128, 7), outcome.returned.int.bits);
const Op = @FieldType(ArcEvent, "op");
const want = [_]struct { Op, u64 }{ .{ .from_frozen, 1 }, .{ .clone, 2 }, .{ .release, 1 }, .{ .release, 0 }, .{ .new, 1 }, .{ .release, 0 } };
try std.testing.expectEqual(want.len, events.items.len);
for (want, events.items) |w, e| {
try std.testing.expectEqual(w[0], e.op);
try std.testing.expectEqual(w[1], e.count);
}
// One graph identity through island → frozen → arc; the second graph is new.
try std.testing.expectEqual(events.items[0].graph, events.items[3].graph);
try std.testing.expect(events.items[4].graph != events.items[0].graph);
}
// Transfer is O(1) in the graph size (spec 03 §22): moving an island through
// a channel K times costs the same number of instructions for a graph of 10
// nodes as for one of 1000.
fn transferSteps(nodes: u64, sends: u64) !u64 {
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,
\\module t
\\fn main(heap: cap<mem.alloc>) -> u64
\\effects [mem.alloc, task.wait]
\\{{
\\ var isl: island<u64> = island.create(0u64, heap) or trap;
\\ {{
\\ mut g = isl;
\\ for i in 0..{d}u64 {{ let r = island.alloc(g, i) or trap; }}
\\ }}
\\ match channel.make<island<u64>>(1, heap) {{
\\ ok(tx, rx) => {{
\\ for k in 0..{d}u64 {{
\\ channel.send(tx, move isl) or trap;
\\ isl = channel.recv(rx) or trap;
\\ }}
\\ channel.close_sender(move tx);
\\ channel.close_receiver(move rx) or trap;
\\ }}
\\ err(e) => {{ trap; }}
\\ }}
\\ island.destroy(move isl);
\\ 0
\\}}
, .{ nodes, sends });
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 = "1000000" }}, .memory = &stats });
try std.testing.expect(outcome == .returned);
return stats.steps;
}
test "moving an island costs the same for any graph size" {
const small = try transferSteps(10, 10) - try transferSteps(10, 0);
const large = try transferSteps(1000, 10) - try transferSteps(1000, 0);
try std.testing.expectEqual(small, large);
}