diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index b89bb33..9458b96 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -473,4 +473,6 @@ The [audit-report increment](air-type-depth-audit.md#audit-report-traversal) fix ## Q-060 — Native recursion while materializing runtime values -The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. Recursive copying, value sizing, marking and serialization are additional audit candidates, with their failure paths unverified. Compiler type repairs in Q-059 do not resolve Q-060. +The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060. + +The [zero-materialization increment](runtime-value-depth-audit.md#zero-materialization-repair) removes recursion from zeroValue while preserving payload shape/order, whole-local publication and instruction accounting. Deep unit tests cover 32,768 anonymous/nominal levels and pending siblings; the original run now returns normally. Follow-up probes independently verify native-stack failures in deepCopy/copyAll on local.load and Copier.value/items with collection before every instruction. Those are remaining Q-060 work, not a new acceptance limit; value sizing and output serialization remain audit candidates. diff --git a/docs/design/runtime-value-depth-audit.md b/docs/design/runtime-value-depth-audit.md index c31979f..add9121 100644 --- a/docs/design/runtime-value-depth-audit.md +++ b/docs/design/runtime-value-depth-audit.md @@ -21,4 +21,21 @@ Every array length is one. The accounted value/frame size is one byte, and `aji This confirms native recursion in zeroValue on a verified input. An iterative fix must retain zero initialization, value shape, heap/root lifetimes, allocation failure handling, collection safety and instruction/fuel accounting. A new accepted-depth limit or trap would require a normative decision; none is added by compiler-side repairs. -Source inspection also finds recursion in deepCopy/copyAll and valueBytes. Those failure paths are **unverified**: no deep-value input reached them in this probe. Runtime marking and output serialization also need inspection before claiming complete bounded native-stack behavior. Q-060 remains open. +At the initial baseline, deepCopy/copyAll, valueBytes and collection/serialization were inspection candidates only: the zero-materialization failure prevented probing them. The executed results below supersede that status for copying and collection. valueBytes and output serialization still need depth probes before claiming complete bounded native-stack behavior. Q-060 remains open. + +## Zero-materialization repair + +The implementation now fills zeroable arrays and named structs in the original preorder, using explicit continuations only for pending siblings. Single-child edges need no continuation. Result payloads remain in the execution heap; temporary traversal metadata uses a separate host arena and is released before the next instruction safe point. A partially built value is not published to the local cell if an allocation fails. + +The preserved invariant is complete initialization without aliasing independent array/struct payloads. Spec 07a's local.zero verifier rule (zeroable type, no live borrow) and spec 08 §13's whole-local initialization remain unchanged. All leaves have the same integer type/zero bits or false boolean, and aggregate declaration/variant identities and field/element order are unchanged. No runtime rule, Aji allocation authority, opcode, effect, feature, diagnostic code, trap, accepted-depth limit or fuel/scheduler event is introduced. Existing enum/capability zero rejects remain E1001 in AIR and E7006/zero_not_zeroable in source; the public zero_enum/capability_not_zeroable cases and their source analogues remain rejection examples. + +Unit tests traverse 32,768 single-element arrays and a 32,768-declaration chain with heterogeneous pending siblings, empty-record leaves and three-byte arrays. A constrained payload allocator fails after allocating the root and proves that the old local value survives the failed instruction. The new zero_structure_siblings AIR/source pair checks complete mixed zeroing followed by a write and unchanged independent fields. Forty generated shallow mixed-type runs produce byte-identical old/new records. + +An additional verified deep-program unit test pins fuel 0/1/2 as exact limit records and fuel 3 as successful completion, with matching instruction counts at the ordinary collection threshold. + +The original 32,768-level input now returns `{"status":"returned","value":null}` under fuel 8 at the ordinary collection threshold. This is not a claim that all deep runtime paths work. Two follow-up probes are independently confirmed: + +- With collection before every instruction, the same program aborts without JSON inside Copier.value/items (4,997/4,998 symbolized frames). Its ordinary run succeeds, isolating the collector's recursive payload copy from zero construction. +- Adding `%v = local.load %a` immediately after zeroing aborts without JSON inside deepCopy/copyAll (4,998 frames each), under the same fuel 8. Storage-to-SSA copying still requires its own iterative traversal. + +Both probes retain the ordinary native stack limit and disable only child core capture, with no wall-clock termination. Evidence comes from the runner exit status and Zig's symbolized stderr, not a saved core dump. Q-060 stays open for copying, sharing-preserving collection/result copying, accounted-value queries and output serialization. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index fe18021..188172a 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -404,3 +404,9 @@ The exclusivity/lifetime invariants, verifier transfer rules, explicit borrow cr Validation: units/format checks and all 1,783 conformance cases pass; independent source-error collection passes 234 CLI checks. The six original trigger/exclusion diagnostics retain their complete envelopes after removing only the new candidate field. Old/new comparison of 1,410 pre-existing source files preserves every diagnostic envelope after removing only the two new registered candidates, and all 501 accepted lowerings remain byte-identical. Advice is additionally emitted for the existing std/implicit_borrow rejection; its E7005 facts are unchanged. No fresh Claude review was available. P6-12 still awaits external development-run measurements. + +## P6-1 runtime value-depth repair (2026-10-09) + +The [Q-060 zero-materialization increment](../design/runtime-value-depth-audit.md#zero-materialization-repair) fills zeroable values iteratively, retaining field/element order, declaration identities, independent payloads, whole-local publication, allocator errors and fuel/scheduling. Unit cases cover 32,768 array/nominal levels with pending siblings and an allocation failure; a mixed AIR/source run pair checks initialization and subsequent writes. The original fuel-8 probe now returns normally and forty shallow mixed-type old/new records are identical. Follow-up probes independently confirm recursive local-load copying and sharing-preserving collection failures. Q-060 and Phase 6 remain open; no normative/bundle/feature/code change or new depth limit. No fresh Claude review was available. + +Validation: all units/format checks, test-extended and 1,785/1,785 conformance cases pass; both new mixed-type cases also pass with collection before every instruction. A verified 32,768-level unit probe pins exact fuel 0–3 boundaries and instruction counts. Source/AIR semantics and bundle size are unchanged; the separate deep collector/copy failures are retained in Q-060. diff --git a/src/interp/machine.zig b/src/interp/machine.zig index dca42d7..8bdc1b5 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -1514,23 +1514,55 @@ const Machine = struct { return out; } - fn zeroValue(m: *Machine, t: air.Type) std.mem.Allocator.Error!Value { - return switch (t) { - .int => |it| .{ .int = .{ .ty = it, .bits = 0 } }, - .bool => .{ .boolean = false }, - .array => |a| blk: { - 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.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 } }; - }, - else => unreachable, // verified zeroable - }; + fn zeroValue(m: *Machine, initial: air.Type) std.mem.Allocator.Error!Value { + // Payloads live in the execution heap; traversal state is temporary + // host bookkeeping, discarded before the instruction's safe point. + // Only pending siblings need a continuation, not single-child edges. + const ZeroFrame = struct { ty: air.Type, out: []Value, next: usize }; + var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer tmp.deinit(); + var frames: std.ArrayList(ZeroFrame) = .empty; + var result: Value = undefined; + var out = &result; + var ty = initial; + while (true) { + switch (ty) { + .int => |it| out.* = .{ .int = .{ .ty = it, .bits = 0 } }, + .bool => out.* = .{ .boolean = false }, + .array => |a| { + const items = try m.heap().alloc(Value, a.len); + out.* = .{ .array = items }; + if (items.len != 0) { + if (items.len > 1) try frames.append(tmp.allocator(), .{ .ty = ty, .out = items, .next = 1 }); + ty = a.elem; + out = &items[0]; + continue; + } + }, + .named => |i| { + const fields = m.module.types[i].kind.@"struct"; + const items = try m.heap().alloc(Value, fields.len); + out.* = .{ .aggregate = .{ .decl = i, .variant = 0, .fields = items } }; + if (items.len != 0) { + if (items.len > 1) try frames.append(tmp.allocator(), .{ .ty = ty, .out = items, .next = 1 }); + ty = fields[0].ty; + out = &items[0]; + continue; + } + }, + else => unreachable, // verified zeroable + } + if (frames.items.len == 0) return result; + const f = &frames.items[frames.items.len - 1]; + out = &f.out[f.next]; + ty = switch (f.ty) { + .array => |a| a.elem, + .named => |i| m.module.types[i].kind.@"struct"[f.next].ty, + else => unreachable, + }; + f.next += 1; + if (f.next == f.out.len) _ = frames.pop(); + } } fn placePtr(p: Value.Place) *Value { @@ -2535,6 +2567,103 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void { const h = "module t\nair 0\nlang 0.1\nfeatures []\n"; +test "zero construction handles deep arrays and named structures with pending siblings" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const depth = 32768; + const chain = try arena.alloc(air.Type, depth + 1); + const arrays = try arena.alloc(air.Type.Array, depth); + chain[0] = .{ .int = .u8 }; + for (chain[1..], arrays, 1..) |*ty, *a, i| { + a.* = .{ .elem = chain[i - 1], .len = 1 }; + ty.* = .{ .array = a }; + } + var module: air.Module = .{ .name = "zero", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) }; + m.exec_heap.space = .init(std.testing.allocator); + defer m.exec_heap.space.deinit(); + var v = try m.zeroValue(chain[depth]); + for (0..depth) |_| { + try std.testing.expect(v == .array and v.array.len == 1); + v = v.array[0]; + } + try std.testing.expect(v == .int and v.int.ty == .u8 and v.int.bits == 0); + + // Each frame has heterogeneous siblings after its deep first field; + // the leaf also covers an empty record and a multi-element array. + const declarations = try arena.alloc(air.TypeDecl, depth + 1); + const three_bytes: air.Type.Array = .{ .elem = chain[0], .len = 3 }; + declarations[0] = .{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }; + for (declarations[1..], 1..) |*decl, i| { + const fields = try arena.alloc(@import("../air/module.zig").Field, 3); + fields[0] = .{ .name = "child", .ty = .{ .named = @intCast(i - 1) } }; + fields[1] = .{ .name = "flag", .ty = .bool }; + fields[2] = .{ .name = "bytes", .ty = .{ .array = &three_bytes } }; + decl.* = .{ .name = "Node", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = fields } }; + } + module.types = declarations; + m.module = module; + v = try m.zeroValue(.{ .named = depth }); + var i: usize = depth; + while (i != 0) : (i -= 1) { + try std.testing.expect(v == .aggregate and v.aggregate.decl == i and v.aggregate.variant == 0); + const fields = v.aggregate.fields; + try std.testing.expectEqual(@as(usize, 3), fields.len); + try std.testing.expect(fields[1] == .boolean and !fields[1].boolean); + try std.testing.expectEqual(@as(usize, 3), fields[2].array.len); + for (fields[2].array) |x| try std.testing.expect(x.int.ty == .u8 and x.int.bits == 0); + v = fields[0]; + } + try std.testing.expect(v.aggregate.decl == 0 and v.aggregate.fields.len == 0); +} + +test "failed zero construction does not publish a partially initialized local" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const byte: air.Type = .{ .int = .u8 }; + const inner: air.Type = .{ .array = &.{ .elem = byte, .len = 16 } }; + const ty: air.Type = .{ .array = &.{ .elem = inner, .len = 1 } }; + const module: air.Module = .{ .name = "zero", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) }; + var buf: [512]u8 = undefined; + var fixed: std.heap.FixedBufferAllocator = .init(&buf); + m.exec_heap.space = .init(fixed.allocator()); + defer m.exec_heap.space.deinit(); + var cell: Value.Cell = .{ .value = .{ .boolean = true }, .ty = ty }; + var vals = [_]Value{.{ .local = &cell }}; + const inst: air.Inst = .{ .span = .{ .line = 1, .col = 1 }, .result = null, .op = .{ .local_zero = 0 } }; + try std.testing.expectError(error.OutOfMemory, m.execMemory(&vals, inst)); + try std.testing.expect(fixed.end_index != 0); // root allocated, child failed + try std.testing.expect(cell.value == .boolean and cell.value.boolean); +} + +test "deep zero materialization is one instruction under the ordinary collection threshold" { + var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var src: std.ArrayList(u8) = .empty; + try src.appendSlice(arena, "module zero.fuel\nair 0\nlang 0.1\nfeatures [arrays, ownership]\nfn @main() -> void\neffects []\nentry:\n %p = local.alloc "); + for (0..32768) |_| try src.appendSlice(arena, "array<"); + try src.appendSlice(arena, "u8"); + for (0..32768) |_| try src.appendSlice(arena, ",1>"); + try src.appendSlice(arena, "\n local.zero %p\n ret\n"); + const checked = try check.checkAir(arena, "zero-fuel.air", src.items); + try std.testing.expect(checked.status == .accepted); + for (0..4) |fuel| { + var stats: MemoryStats = .{}; + const outcome = try run(arena, checked.module.?, "main", .{ .fuel = fuel, .memory = &stats }); + try std.testing.expectEqual(@as(u64, fuel), stats.steps); + if (fuel < 3) { + 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); + } +} + fn main1(comptime ret: []const u8, comptime insts: []const u8) []const u8 { return h ++ "fn @main() -> " ++ ret ++ "\neffects []\nentry:\n" ++ insts; } diff --git a/tests/conformance/phase1/run/zero_structure_siblings.air b/tests/conformance/phase1/run/zero_structure_siblings.air new file mode 100644 index 0000000..91504f7 --- /dev/null +++ b/tests/conformance/phase1/run/zero_structure_siblings.air @@ -0,0 +1,163 @@ +; expect: run +; result: 42 +; phase: 1 +; spec: docs/spec/07a-air-instructions.md §2 +module runtime.siblings +air 0 +lang 0.1 +features [arrays, effects, ownership] + +type @Empty = struct {} +type @Pair = struct { flag: bool, values: array } +type @Nest = struct { empty: @Empty, pairs: array<@Pair, 2>, tail: u16 } + +fn @main() -> u16 +effects [] +entry: + %n_1 = local.alloc @Nest + local.zero %n_1 + %n_2 = borrow.ref %n_1 + %pairs_3 = borrow.field @Nest.pairs, %n_2 + %c_4 = const.usize 0 + %e_5 = borrow.index %pairs_3, %c_4 + %v_6 = load %e_5 + borrow.end %e_5 + borrow.end %pairs_3 + borrow.end %n_2 + %flag_7 = struct.get @Pair.flag, %v_6 + %c_8 = const.bool true + cbr %flag_7, @or_end_10(%c_8), @or_rhs_9() +or_rhs_9: + %n_12 = borrow.ref %n_1 + %pairs_13 = borrow.field @Nest.pairs, %n_12 + %c_14 = const.usize 1 + %e_15 = borrow.index %pairs_13, %c_14 + %v_16 = load %e_15 + borrow.end %e_15 + borrow.end %pairs_13 + borrow.end %n_12 + %flag_17 = struct.get @Pair.flag, %v_16 + br @or_end_10(%flag_17) +or_end_10(%or_11: bool): + cbr %or_11, @then_18(), @else_19() +then_18: + %c_20 = const.u16 1 + ret %c_20 +else_19: + br @endif_21() +endif_21: + %n_22 = borrow.ref %n_1 + %pairs_23 = borrow.field @Nest.pairs, %n_22 + %c_24 = const.usize 0 + %e_25 = borrow.index %pairs_23, %c_24 + %values_26 = borrow.field @Pair.values, %e_25 + %c_27 = const.usize 0 + %e_28 = borrow.index %values_26, %c_27 + %v_29 = load %e_28 + borrow.end %e_28 + borrow.end %values_26 + borrow.end %e_25 + borrow.end %pairs_23 + borrow.end %n_22 + %n_30 = borrow.ref %n_1 + %pairs_31 = borrow.field @Nest.pairs, %n_30 + %c_32 = const.usize 0 + %e_33 = borrow.index %pairs_31, %c_32 + %values_34 = borrow.field @Pair.values, %e_33 + %c_35 = const.usize 1 + %e_36 = borrow.index %values_34, %c_35 + %v_37 = load %e_36 + borrow.end %e_36 + borrow.end %values_34 + borrow.end %e_33 + borrow.end %pairs_31 + borrow.end %n_30 + %t_38 = add.checked.u16 %v_29, %v_37 + %n_39 = borrow.ref %n_1 + %pairs_40 = borrow.field @Nest.pairs, %n_39 + %c_41 = const.usize 0 + %e_42 = borrow.index %pairs_40, %c_41 + %values_43 = borrow.field @Pair.values, %e_42 + %c_44 = const.usize 2 + %e_45 = borrow.index %values_43, %c_44 + %v_46 = load %e_45 + borrow.end %e_45 + borrow.end %values_43 + borrow.end %e_42 + borrow.end %pairs_40 + borrow.end %n_39 + %t_47 = add.checked.u16 %t_38, %v_46 + %n_48 = borrow.ref %n_1 + %pairs_49 = borrow.field @Nest.pairs, %n_48 + %c_50 = const.usize 1 + %e_51 = borrow.index %pairs_49, %c_50 + %values_52 = borrow.field @Pair.values, %e_51 + %c_53 = const.usize 0 + %e_54 = borrow.index %values_52, %c_53 + %v_55 = load %e_54 + borrow.end %e_54 + borrow.end %values_52 + borrow.end %e_51 + borrow.end %pairs_49 + borrow.end %n_48 + %t_56 = add.checked.u16 %t_47, %v_55 + %n_57 = borrow.ref %n_1 + %pairs_58 = borrow.field @Nest.pairs, %n_57 + %c_59 = const.usize 1 + %e_60 = borrow.index %pairs_58, %c_59 + %values_61 = borrow.field @Pair.values, %e_60 + %c_62 = const.usize 1 + %e_63 = borrow.index %values_61, %c_62 + %v_64 = load %e_63 + borrow.end %e_63 + borrow.end %values_61 + borrow.end %e_60 + borrow.end %pairs_58 + borrow.end %n_57 + %t_65 = add.checked.u16 %t_56, %v_64 + %n_66 = borrow.ref %n_1 + %pairs_67 = borrow.field @Nest.pairs, %n_66 + %c_68 = const.usize 1 + %e_69 = borrow.index %pairs_67, %c_68 + %values_70 = borrow.field @Pair.values, %e_69 + %c_71 = const.usize 2 + %e_72 = borrow.index %values_70, %c_71 + %v_73 = load %e_72 + borrow.end %e_72 + borrow.end %values_70 + borrow.end %e_69 + borrow.end %pairs_67 + borrow.end %n_66 + %t_74 = add.checked.u16 %t_65, %v_73 + %n_75 = local.load %n_1 + %tail_76 = struct.get @Nest.tail, %n_75 + %t_77 = add.checked.u16 %t_74, %tail_76 + %c_78 = const.u16 42 + %n_79 = borrow.mut %n_1 + %pairs_80 = borrow.field @Nest.pairs, %n_79 + %c_81 = const.usize 0 + %e_82 = borrow.index %pairs_80, %c_81 + %values_83 = borrow.field @Pair.values, %e_82 + %c_84 = const.usize 1 + %e_85 = borrow.index %values_83, %c_84 + store %e_85, %c_78 + borrow.end %e_85 + borrow.end %values_83 + borrow.end %e_82 + borrow.end %pairs_80 + borrow.end %n_79 + %n_86 = borrow.ref %n_1 + %pairs_87 = borrow.field @Nest.pairs, %n_86 + %c_88 = const.usize 0 + %e_89 = borrow.index %pairs_87, %c_88 + %values_90 = borrow.field @Pair.values, %e_89 + %c_91 = const.usize 1 + %e_92 = borrow.index %values_90, %c_91 + %v_93 = load %e_92 + borrow.end %e_92 + borrow.end %values_90 + borrow.end %e_89 + borrow.end %pairs_87 + borrow.end %n_86 + %t_94 = add.checked.u16 %t_77, %v_93 + ret %t_94 diff --git a/tests/conformance/source/runtime_values/zero_structure_siblings.aji b/tests/conformance/source/runtime_values/zero_structure_siblings.aji new file mode 100644 index 0000000..5c0d1e2 --- /dev/null +++ b/tests/conformance/source/runtime_values/zero_structure_siblings.aji @@ -0,0 +1,18 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/07a-air-instructions.md §2; docs/spec/15-source-language.md §4 +// equivalent: phase1/run/zero_structure_siblings.air +module runtime.siblings +struct Empty {} +struct Pair { flag: bool, values: [u16; 3] } +struct Nest { empty: Empty, pairs: [Pair; 2], tail: u16 } +fn main() -> u16 effects [] { + var n: Nest = zero; + if n.pairs[0usize].flag or n.pairs[1usize].flag { return 1; } + let sum = n.pairs[0usize].values[0usize] + n.pairs[0usize].values[1usize] + + n.pairs[0usize].values[2usize] + n.pairs[1usize].values[0usize] + + n.pairs[1usize].values[1usize] + n.pairs[1usize].values[2usize] + n.tail; + n.pairs[0usize].values[1usize] = 42; + return sum + n.pairs[0usize].values[1usize]; +}