interp: trace collector values with explicit continuations

This commit is contained in:
dev committed 2026-10-09 22:31:05 +03:00
1 parent afc40f8502
commit f92817b127
4 files changed
+286 -19

No files matched your search

+260 -18
View File
@@ -355,16 +355,52 @@ const Copier = struct {
payloads: std.AutoHashMapUnmanaged([*]Value, []Value) = .empty,
graphs: std.AutoHashMapUnmanaged(*Value.Graph, *Value.Graph) = .empty,
buffers: std.AutoHashMapUnmanaged(*Value.Buffer, *Value.Buffer) = .empty,
pending: std.ArrayList(CopyJob) = .empty,
const CopyJob = union(enum) {
value: struct { source: Value, out: *Value },
items: struct { source: []Value, out: []Value, next: usize },
graph: struct { source: *Value.Graph, out: *Value.Graph, next: usize },
mutex_view: struct { source: *Value.MutexCell, out: *Value.MutexCell },
path: struct { source: []const u32, out: *[]const u32 },
};
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) },
var out: Value = undefined;
try c.copyValue(v, &out);
try c.finish();
return out;
}
fn items(c: *Copier, xs: []Value) std.mem.Allocator.Error![]Value {
const out = try c.ensureItems(xs);
try c.finish();
return out;
}
fn cell(c: *Copier, old: *Value.Cell) std.mem.Allocator.Error!*Value.Cell {
const out = try c.ensureCell(old);
try c.finish();
return out;
}
/// Shells enter their forwarding map before descendants are queued.
/// All pending work finishes before a root escapes to the machine.
fn copyValue(c: *Copier, v: Value, out: *Value) std.mem.Allocator.Error!void {
out.* = switch (v) {
.aggregate => |a| .{ .aggregate = .{ .decl = a.decl, .variant = a.variant, .fields = try c.ensureItems(a.fields) } },
.array => |xs| .{ .array = try c.ensureItems(xs) },
.local => |cl| .{ .local = try c.ensureCell(cl) },
.own => |cl| .{ .own = try c.ensureCell(cl) },
.buffer => |b| .{ .buffer = try c.buffer(b) },
.place => |p| .{ .place = try c.place(p) },
.slice => |sl| .{ .slice = .{ .place = try c.place(sl.place), .start = sl.start, .len = sl.len } },
.place => |p| {
out.* = .{ .place = .{ .cell = undefined, .path = &.{} } };
return c.place(p, &out.place);
},
.slice => |sl| {
out.* = .{ .slice = .{ .place = .{ .cell = undefined, .path = &.{} }, .start = sl.start, .len = sl.len } };
return c.place(sl.place, &out.slice.place);
},
.mutex => |mc| .{ .mutex = try c.mutex(mc) },
.guard => |mc| .{ .guard = try c.mutex(mc) },
.graph => |g| .{ .graph = try c.graph(g) },
@@ -372,7 +408,7 @@ const Copier = struct {
};
}
fn items(c: *Copier, xs: []Value) std.mem.Allocator.Error![]Value {
fn ensureItems(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);
@@ -380,18 +416,20 @@ const Copier = struct {
}
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);
try c.pending.append(c.tmp, .{ .items = .{ .source = xs, .out = out, .next = 0 } });
return out;
}
fn cell(c: *Copier, old: *Value.Cell) std.mem.Allocator.Error!*Value.Cell {
fn ensureCell(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, .shadow = if (old.shadow) |sh| try sh.copy(c.to) else null };
n.owner_array = old.owner_array;
if (old.backing) |b| n.backing = .{ .values = try c.items(b.values), .index = b.index };
n.value = try c.value(old.value);
// LIFO: finish backing slots before the cell value, retaining DFS
// allocation order and allowing a backing slot to point at this shell.
try c.pending.append(c.tmp, .{ .value = .{ .source = old.value, .out = &n.value } });
if (old.backing) |b| n.backing = .{ .values = try c.ensureItems(b.values), .index = b.index };
return n;
}
@@ -399,7 +437,7 @@ const Copier = struct {
if (c.buffers.get(old)) |n| return n;
const n = try c.to.create(Value.Buffer);
try c.buffers.put(c.tmp, old, n);
n.* = .{ .cell = try c.cell(old.cell), .capacity = old.capacity, .elem = old.elem };
n.* = .{ .cell = try c.ensureCell(old.cell), .capacity = old.capacity, .elem = old.elem };
return n;
}
@@ -407,7 +445,8 @@ const Copier = struct {
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), .view = try old.view.copy(c.to) };
try c.pending.append(c.tmp, .{ .mutex_view = .{ .source = old, .out = n } });
n.* = .{ .locked = old.locked, .cell = try c.ensureCell(old.cell) };
return n;
}
@@ -418,12 +457,29 @@ const Copier = struct {
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));
if (old.objects.items.len != 0) try c.pending.append(c.tmp, .{ .graph = .{ .source = old, .out = n, .next = 0 } });
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) };
fn place(c: *Copier, p: Value.Place, out: *Value.Place) std.mem.Allocator.Error!void {
if (p.path.len != 0) try c.pending.append(c.tmp, .{ .path = .{ .source = p.path, .out = &out.path } });
out.cell = try c.ensureCell(p.cell);
}
fn finish(c: *Copier) std.mem.Allocator.Error!void {
while (c.pending.pop()) |job| switch (job) {
.value => |v| try c.copyValue(v.source, v.out),
.items => |it| {
if (it.next + 1 < it.source.len) try c.pending.append(c.tmp, .{ .items = .{ .source = it.source, .out = it.out, .next = it.next + 1 } });
try c.copyValue(it.source[it.next], &it.out[it.next]);
},
.graph => |g| {
if (g.next + 1 < g.source.objects.items.len) try c.pending.append(c.tmp, .{ .graph = .{ .source = g.source, .out = g.out, .next = g.next + 1 } });
g.out.objects.appendAssumeCapacity(try c.ensureCell(g.source.objects.items[g.next]));
},
.mutex_view => |mc| mc.out.view = try mc.source.view.copy(c.to),
.path => |p| p.out.* = try c.to.dupe(u32, p.source),
};
}
};
@@ -2600,6 +2656,145 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void {
const h = "module t\nair 0\nlang 0.1\nfeatures []\n";
fn expectCollectorAllocationFailure(source: []Value, fail_index: usize) !bool {
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer state.deinit();
// Fail copier requests, rather than address-dependent arena growth.
// One disposable arena owns both destination and temporary allocations.
var failing: std.testing.FailingAllocator = .init(state.allocator(), .{ .fail_index = fail_index });
var c: Copier = .{ .to = failing.allocator(), .tmp = failing.allocator() };
const copied = c.items(source) catch |err| {
try std.testing.expect(err == error.OutOfMemory and failing.has_induced_failure);
return true;
};
try std.testing.expect(!failing.has_induced_failure);
try std.testing.expect(c.pending.items.len == 0);
try std.testing.expect(copied[0].local.backing.?.values.ptr == copied.ptr);
try std.testing.expect(copied[4].own.value.array.ptr == copied[1].array.ptr);
try std.testing.expect(copied[5].mutex == copied[6].guard);
try std.testing.expect(copied[7].graph.objects.items[1].value.graph == copied[7].graph);
try std.testing.expect(copied[8].buffer == copied[9].buffer);
return false;
}
test "collector forwarding preserves backing cycles and shared object identities after releasing the old heap" {
var old_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer old_state.deinit();
var next_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer next_state.deinit();
var tmp_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer tmp_state.deinit();
const old = old_state.allocator();
const payload = try old.alloc(Value, 3);
payload[0] = .{ .int = .{ .ty = .u8, .bits = 42 } };
payload[1] = .{ .boolean = true };
payload[2] = .{ .int = .{ .ty = .u8, .bits = 7 } };
const slots = try old.alloc(Value, 11);
const backing = try old.create(Value.Cell);
backing.* = .{ .value = .void, .ty = .void, .backing = .{ .values = slots, .index = 1 } };
const owner = try old.create(Value.Cell);
const shadow = try old.create(race.Shadow);
shadow.* = .{};
const path = try old.dupe(u32, &.{1});
var reads: std.ArrayList(race.Epoch) = .empty;
try reads.append(old, .{ .task = 2, .clock = 9 });
try shadow.entries.append(old, .{ .path = path, .write = .{ .task = 1, .clock = 4 }, .reads = reads });
owner.* = .{ .value = .{ .array = payload }, .ty = .void, .owner_array = true, .shadow = shadow };
const mutex = try old.create(Value.MutexCell);
mutex.* = .{ .locked = true, .cell = owner, .view = try (weak.View{}).with(17, 5, old) };
const graph = try old.create(Value.Graph);
graph.* = .{ .id = 8, .authority = 2, .bytes = 64, .count = 3, .frozen = true };
const cycle = try old.create(Value.Cell);
cycle.* = .{ .value = .{ .graph = graph }, .ty = .void };
try graph.objects.appendSlice(old, &.{ owner, cycle });
const buffer = try old.create(Value.Buffer);
buffer.* = .{ .cell = owner, .capacity = 8, .elem = .{ .int = .u8 } };
slots[0] = .{ .local = backing };
slots[1] = .{ .array = payload };
slots[2] = .{ .place = .{ .cell = backing, .path = path } };
slots[3] = .{ .slice = .{ .place = .{ .cell = backing, .path = &.{} }, .start = 1, .len = 2 } };
slots[4] = .{ .own = owner };
slots[5] = .{ .mutex = mutex };
slots[6] = .{ .guard = mutex };
slots[7] = .{ .graph = graph };
slots[8] = .{ .buffer = buffer };
slots[9] = .{ .buffer = buffer };
slots[10] = .{ .iref = .{ .id = 8, .slot = 0 } };
// The arena releases all shells, maps and jobs after any failed allocation.
// A failed copier is discarded, rather than retried or published.
var fail_index: usize = 0;
while (try expectCollectorAllocationFailure(slots, fail_index)) : (fail_index += 1) {}
try std.testing.expect(fail_index != 0);
try std.testing.expect(slots[0].local == backing and slots[4].own == owner and payload[1].boolean);
var c: Copier = .{ .to = next_state.allocator(), .tmp = tmp_state.allocator() };
const copied = try c.items(slots);
try std.testing.expect(c.pending.items.len == 0);
try std.testing.expect(copied.ptr != slots.ptr and copied[0].local != backing and copied[4].own != owner);
try std.testing.expect(copied[2].place.path.ptr != path.ptr);
try std.testing.expect(copied[5].mutex.view.entries.ptr != mutex.view.entries.ptr);
try std.testing.expect(copied[4].own.shadow.? != shadow);
// Repeated roots must resolve to the already completed forwarded object.
try std.testing.expect((try c.cell(owner)) == copied[4].own);
old_state.deinit();
old_state = .init(std.testing.allocator);
try std.testing.expect(copied[0].local.backing.?.values.ptr == copied.ptr);
try std.testing.expectEqual(@as(u32, 1), copied[0].local.backing.?.index);
try std.testing.expect(copied[2].place.cell == copied[0].local and copied[2].place.path[0] == 1);
try std.testing.expect(copied[3].slice.place.cell == copied[0].local and copied[3].slice.start == 1 and copied[3].slice.len == 2);
try std.testing.expect(copied[4].own.owner_array and copied[4].own.value.array.ptr == copied[1].array.ptr);
try std.testing.expect(copied[5].mutex == copied[6].guard and copied[5].mutex.cell == copied[4].own and copied[5].mutex.locked);
try std.testing.expectEqual(@as(u64, 5), copied[5].mutex.view.get(17));
const g = copied[7].graph;
try std.testing.expect(g.id == 8 and g.authority == 2 and g.bytes == 64 and g.count == 3 and g.frozen);
try std.testing.expect(g.objects.items.len == 2 and g.objects.items[0] == copied[4].own and g.objects.items[1].value.graph == g);
try std.testing.expect(copied[8].buffer == copied[9].buffer and copied[8].buffer.cell == copied[4].own);
try std.testing.expect(copied[8].buffer.capacity == 8 and copied[8].buffer.elem.int == .u8);
try std.testing.expect(copied[10].iref.id == 8 and copied[10].iref.slot == 0);
const sh = copied[4].own.shadow.?;
try std.testing.expect(sh.entries.items.len == 1 and sh.entries.items[0].path[0] == 1);
try std.testing.expect(sh.entries.items[0].write.?.task == 1 and sh.entries.items[0].write.?.clock == 4);
try std.testing.expect(sh.entries.items[0].reads.items[0].task == 2 and sh.entries.items[0].reads.items[0].clock == 9);
Machine.placePtr(copied[2].place).* = .{ .boolean = false };
try std.testing.expect(!copied[1].array[1].boolean and !copied[4].own.value.array[1].boolean);
}
test "collector copying uses no native recursion for deep payload and cell chains" {
var old_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer old_state.deinit();
var next_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer next_state.deinit();
var tmp_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer tmp_state.deinit();
const old = old_state.allocator();
const depth = 32768;
var root: Value = .{ .int = .{ .ty = .u8, .bits = 42 } };
var cell_root: Value = .{ .boolean = true };
for (0..depth) |i| {
const fields = try old.alloc(Value, 2);
fields[0] = root;
fields[1] = .{ .int = .{ .ty = .u32, .bits = i } };
root = if (i % 2 == 0) .{ .array = fields } else .{ .aggregate = .{ .decl = @intCast(i), .variant = 2, .fields = fields } };
const cl = try old.create(Value.Cell);
cl.* = .{ .value = cell_root, .ty = .void };
cell_root = .{ .own = cl };
}
var c: Copier = .{ .to = next_state.allocator(), .tmp = tmp_state.allocator() };
var copied = try c.value(root);
var cells = try c.value(cell_root);
old_state.deinit();
old_state = .init(std.testing.allocator);
var i: usize = depth;
while (i != 0) {
i -= 1;
const fields = if (i % 2 == 0) copied.array else copied.aggregate.fields;
if (i % 2 != 0) try std.testing.expect(copied.aggregate.decl == i and copied.aggregate.variant == 2);
try std.testing.expect(fields.len == 2 and fields[1].int.bits == i);
copied = fields[0];
cells = cells.own.value;
}
try std.testing.expect(copied.int.bits == 42 and cells.boolean);
}
test "deep copying preserves metadata and separates every payload occurrence" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
@@ -2777,7 +2972,7 @@ test "failed zero construction does not publish a partially initialized local" {
try std.testing.expect(cell.value == .boolean and cell.value.boolean);
}
test "deep zero and local-load copying count as single instructions at the ordinary collection threshold" {
test "deep zero and local-load copying retain fuel boundaries with ordinary and per-step collection" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
@@ -2816,6 +3011,53 @@ test "deep zero and local-load copying count as single instructions at the ordin
try std.testing.expectEqualStrings("fuel", outcome.limit_exceeded.kind);
} else try std.testing.expect(outcome == .returned and outcome.returned == .void);
}
var gc_stats: MemoryStats = .{};
const collected = try run(arena, copying.module.?, "main", .{ .fuel = 4, .memory = &gc_stats, .collect_every_step = true });
try std.testing.expect(collected == .returned and collected.returned == .void);
try std.testing.expect(gc_stats.steps == 4 and gc_stats.collections >= 4);
src.items.len = body_start;
try src.appendSlice(arena, "\n local.zero %p\n %v = local.load %p\n local.store %p, %v\n ret\n");
const storing = try check.checkAir(arena, "store-fuel.air", src.items);
try std.testing.expect(storing.status == .accepted);
for (0..6) |fuel| {
var stats: MemoryStats = .{};
const outcome = try run(arena, storing.module.?, "main", .{ .fuel = fuel, .memory = &stats });
try std.testing.expectEqual(@as(u64, fuel), stats.steps);
if (fuel < 5) {
try std.testing.expect(outcome == .limit_exceeded);
try std.testing.expectEqual(@as(u64, fuel), outcome.limit_exceeded.steps);
try std.testing.expectEqual(@as(u64, fuel), outcome.limit_exceeded.limit);
try std.testing.expectEqualStrings("fuel", outcome.limit_exceeded.kind);
} else {
try std.testing.expect(outcome == .returned and outcome.returned == .void);
try std.testing.expect(stats.collections != 0);
}
}
}
test "deep returned payload survives per-step collection and execution heap release" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
var ty: std.ArrayList(u8) = .empty;
for (0..32768) |_| try ty.appendSlice(arena, "array<");
try ty.appendSlice(arena, "u8");
for (0..32768) |_| try ty.appendSlice(arena, ",1>");
const src = try std.fmt.allocPrint(arena, "module result.depth\nair 0\nlang 0.1\nfeatures [arrays, ownership]\nfn @main() -> {s}\neffects []\nentry:\n %p = local.alloc {s}\n local.zero %p\n %v = local.load %p\n ret %v\n", .{ ty.items, ty.items });
const checked = try check.checkAir(arena, "result-depth.air", src);
try std.testing.expect(checked.status == .accepted);
for ([_]bool{ false, true }) |every_step| {
var stats: MemoryStats = .{};
const outcome = try run(arena, checked.module.?, "main", .{ .fuel = 4, .memory = &stats, .collect_every_step = every_step });
try std.testing.expect(outcome == .returned and stats.steps == 4);
if (every_step) try std.testing.expect(stats.collections >= 4);
var v = outcome.returned;
for (0..32768) |_| {
try std.testing.expect(v == .array and v.array.len == 1);
v = v.array[0];
}
try std.testing.expect(v.int.ty == .u8 and v.int.bits == 0);
}
}
fn main1(comptime ret: []const u8, comptime insts: []const u8) []const u8 {