diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 727cfbe..9e40879 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -480,3 +480,5 @@ The [zero-materialization increment](runtime-value-depth-audit.md#zero-materiali The [storage/value-copy increment](runtime-value-depth-audit.md#storagevalue-copy-repair) removes recursion from deepCopy/copyAll while retaining per-occurrence payload independence, aggregate identities, shallow handles and failure publication rules. The previous 32,768-level local.load run now returns normally. An added local.store forces ordinary-threshold collection and independently confirms the remaining Copier.value/items native-stack failure, without collect-every-step instrumentation. Sharing-preserving collection/result copying, accounted-value queries and output serialization remain open; no accepted-depth or trap limit is introduced. The [sharing-preserving copy increment](runtime-value-depth-audit.md#sharing-preserving-copy-repair) removes recursive collector/result copying while retaining forwarded identities, backing storage, cycles, slice paths/ranges, buffer metadata, race shadows and mutex views. Deep verified runs now pass ordinary and per-instruction collection, with unchanged fuel boundaries and returned payload lifetimes. Follow-up CLI probes independently confirm valueBytes native-stack exhaustion on own.new and output failure at std.json.Stringify's fixed nesting stack. The latter is not yet evidence of writeValue native-stack overflow. Q-060 stays open for sizing and serialization; no normative depth limit, feature or trap is introduced. + +The [runtime value-size increment](runtime-value-depth-audit.md#runtime-value-size-repair) iterates fixed-array first-element chains with constant state, preserving zero-sized leaves, checked overflow, nominal maximum payloads and the element-before-dynamic-count rule. The previously crashing 32,768-level own.new probe now returns normally with the original one-byte charge; zero authority takes the original failure edge. Deep verified fuel/collection tests, nested-quota AIR/source runs and an independent allocation-size oracle constrain compatibility. Q-060 remains open for output serialization; there is no new normative limit or trap, and Q-059's nominal-query audit remains separate. diff --git a/docs/design/runtime-value-depth-audit.md b/docs/design/runtime-value-depth-audit.md index 7f62d43..3af0ce2 100644 --- a/docs/design/runtime-value-depth-audit.md +++ b/docs/design/runtime-value-depth-audit.md @@ -21,7 +21,7 @@ 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. -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, collection, value sizing and output serialization. Q-060 remains open for the latter two failures. +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, collection, value sizing and output serialization. Q-060 remains open for output serialization; the earlier increments record the failures that led to each repair. ## Zero-materialization repair @@ -66,3 +66,15 @@ Two follow-up failures are independently verified on the same ordinary native st - Allocating an owner for the same loaded array using own.new with fuel 16 and an eight-byte heap grant aborts with exit -6, no JSON and 10,001 valueBytes frames. The value's accounted size is one byte. This confirms native recursion in runtime value sizing after zeroing, loading and collection now complete. Q-060 remains open for valueBytes and output serialization. No normative or agent-bundle text changes in this increment. + +## Runtime value-size repair + +ValueBytes now iterates the first-element chain of fixed value arrays, composing their positive lengths into a checked factor. Scalar, capability, graph-reference, built-in enum and nominal leaf accounting remains unchanged; named types still delegate to the existing module size query. A zero-sized leaf yields zero even if the length factor overflows, matching the original inner-to-outer checked multiplication. A nonzero leaf with an overflowing factor still yields null. ArrayBytes continues to query the element before multiplying by the dynamic count, so a zero count cannot mask an overflowing element. The traversal uses constant state and allocates no temporary or payload storage. + +The invariant is equality with spec 08 §7.1's static accounted size, including nominal maximum enum payloads, zero-sized records and overflow. The existing heap/region/graph charge, failure, release and sixteen-byte graph-header rules remain unchanged (spec 03 §18–§24); authority is still explicit. Fixed value arrays have positive lengths (spec 07 §8.8), and runtime-sized backing arrays are not allocatable SSA values (spec 03 §19.2). No verifier acceptance rule changes. The existing overflowing_array_chain AIR/source rejection pair still reports E5101. The new nested_allocation_quota AIR/source run pair returns 42: twelve-byte nested content fits exactly, a second live allocation fails budget_exceeded, zero-sized content still fits, and freeing restores authority for a repeated allocation. No new code, trap, effect, feature, semantic flag, accepted-depth limit or bundle text is introduced. Fuel, instruction count, collection safe points, ownership transfer and deterministic outcomes are unchanged. + +Unit tests compare scalar/nominal/built-in/capability/iref leaves under mixed array lengths against static accounting, preserving inactive enum payload maxima. Query-only inputs cover 32,768 wrappers, overflowing factors with zero/nonzero leaves and zero dynamic counts; shared payloads compactly represent these queries without claiming verified exponential constructions. A verified 32,768-level own.new programme pins exact fuel 0–6 boundaries under ordinary and per-instruction collection. A one-byte grant takes success, a zero-byte grant takes the error edge, and both executions terminate with the original instruction counts. The formerly crashing CLI probe now returns null with grants one and eight; grant zero retains its explicit failure trap. The successful deep run and both new conformance examples pass with collection before every instruction. + +Validation: unit/format checks, test-extended and all 1,789 ordinary conformance cases pass. Ten old/new quota records for the new AIR/source pair are identical. Another 426 generated runs independently compute expected charges for scalar/record/enum contents, mixed fixed arrays, individual/repeated/zero-count owners and island/arc headers; every boundary outcome matches that oracle and the old interpreter's record. These are generated runtime robustness inputs, not model-evaluation or held-out tasks. The earlier full per-instruction collector conformance run remains additional validation in progress. + +Q-060 remains open for output serialization at the fixed std.json.Stringify nesting stack and the still-recursive writeValue traversal. Q-059's uncached nominal query audit is separate; this repair does not claim to close it. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 4e2c76c..eefe6b1 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -421,4 +421,10 @@ The [Q-060 sharing-preserving copy increment](../design/runtime-value-depth-audi Units/format checks, test-extended and all 1,787 ordinary conformance cases pass. Per-step collection passes 57 focused run cases plus 26 phase-3 run cases with stress 16; 146 old/new mixed-value and identity/schedule records are identical. The full per-step conformance run is still running at this checkpoint. Follow-up probes independently confirm valueBytes recursion on own.new and JSON output failure at std.json.Stringify's fixed nesting stack. Q-060 and Phase 6 remain open. No fresh Claude review was available. +## P6-1 runtime value-size depth repair (2026-10-09) + +The [Q-060 runtime value-size increment](../design/runtime-value-depth-audit.md#runtime-value-size-repair) replaces recursive array-value queries with a constant-state checked factor and unchanged leaf accounting. Zero-sized leaves, true overflow, maximum enum payloads and dynamic-count ordering retain their existing meanings; heap/region/graph charges and failure/release rules are unchanged. Deep verified allocation tests pin fuel 0–6 and zero/one-byte grant boundaries under ordinary/per-step collection. A nested-quota AIR/source pair checks exact charges, zero-sized contents, allocation failure and restored authority. + +Units/format checks, test-extended and all 1,789 ordinary conformance cases pass; the deep allocation and new pair also pass per-step collection. Ten new-pair quota records and 426 generated allocation-oracle runs match the old interpreter exactly. The earlier full per-step collector suite remains in progress. No normative/bundle/feature/code change or accepted-depth limit; Q-060 remains open for serialization, and Phase 6/contract gates remain open. No fresh Claude review was available. + Both new copy cases also pass with collection before every instruction; their shallow sharing-preserving GC behavior is covered separately from the retained deep collector failure. diff --git a/src/interp/machine.zig b/src/interp/machine.zig index a0a6015..79d3cfe 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -1780,17 +1780,29 @@ const Machine = struct { /// Accounted size (spec 08 §7.1) of the type of a runtime value; equal /// to `budget.accountedSize` of the value's static type. - fn valueBytes(m: *Machine, v: Value) ?u64 { - return switch (v) { + fn valueBytes(m: *Machine, initial: Value) ?u64 { + var v = initial; + var factor: ?u64 = 1; + while (v == .array) { + const items = v.array; + // Only fixed-size value arrays reach this query. Empty dynamic + // backing arrays are storage, never an allocatable SSA value. + std.debug.assert(items.len != 0); + factor = if (factor) |f| std.math.mul(u64, f, items.len) catch null else null; + v = items[0]; + } + const base = (switch (v) { .int => |x| x.ty.bits() / 8, .boolean => 1, .aggregate => |a| budget.accountedSize(m.module, .{ .named = a.decl }, 0), - .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) - }; + }) orelse return null; + // An overflowing factor times a zero-sized leaf remains zero, just + // as in the original inner-to-outer checked multiplications. + return if (base == 0) 0 else std.math.mul(u64, factor orelse return null, base) catch null; } // ------------------------------------------------------------ graphs (spec 03 §22–§24) @@ -2656,6 +2668,102 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void { const h = "module t\nair 0\nlang 0.1\nfeatures []\n"; +test "runtime value sizing agrees with static accounting through array wrappers" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const arena = state.allocator(); + const byte: air.Type = .{ .int = .u8 }; + const module: air.Module = .{ + .name = "sizes", + .format_version = 0, + .lang = .{ 0, 1 }, + .features = &.{}, + .types = &.{ + .{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }, + .{ .name = "Mixed", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{ + .{ .name = "byte", .ty = byte }, .{ .name = "flag", .ty = .bool }, .{ .name = "wide", .ty = .{ .int = .u128 } }, + } } }, + .{ .name = "Choice", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"enum" = &.{ + .{ .name = "empty", .payload = &.{} }, .{ .name = "wide", .payload = &.{.{ .int = .u128 }} }, + } } }, + }, + .functions = &.{}, + }; + var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) }; + const Leaf = struct { ty: air.Type, value: Value }; + const mixed = try arena.dupe(Value, &.{ .{ .int = .{ .ty = .u8, .bits = 9 } }, .{ .boolean = true }, .{ .int = .{ .ty = .u128, .bits = 42 } } }); + const leaves = [_]Leaf{ + .{ .ty = byte, .value = .{ .int = .{ .ty = .u8, .bits = 255 } } }, + .{ .ty = .{ .int = .usize }, .value = .{ .int = .{ .ty = .usize, .bits = 42 } } }, + .{ .ty = .{ .int = .i128 }, .value = .{ .int = .{ .ty = .i128, .bits = 0xffff } } }, + .{ .ty = .bool, .value = .{ .boolean = true } }, + .{ .ty = .{ .named = 0 }, .value = .{ .aggregate = .{ .decl = 0, .variant = 0, .fields = &.{} } } }, + .{ .ty = .{ .named = 1 }, .value = .{ .aggregate = .{ .decl = 1, .variant = 0, .fields = mixed } } }, + // Account the maximum enum payload, even for an empty active variant. + .{ .ty = .{ .named = 2 }, .value = .{ .aggregate = .{ .decl = 2, .variant = 0, .fields = &.{} } } }, + .{ .ty = .{ .builtin = .alloc_error }, .value = .{ .builtin = .{ .which = .alloc_error, .variant = 0 } } }, + .{ .ty = .{ .cap = 0 }, .value = .{ .cap = 0 } }, + .{ .ty = .{ .iref = &byte }, .value = .{ .iref = .{ .id = 7, .slot = 2 } } }, + }; + for (leaves) |leaf| { + var ty = leaf.ty; + var v = leaf.value; + for (0..8) |depth| { + const size = budget.accountedSize(module, ty, 0).?; + try std.testing.expectEqual(@as(?u64, size), m.valueBytes(v)); + for ([_]u64{ 0, 1, 2, std.math.maxInt(u64) }) |count| + try std.testing.expectEqual(@as(?u64, std.math.mul(u64, size, count) catch null), m.arrayBytes(v, count)); + const len = depth % 3 + 1; + const items = try arena.alloc(Value, len); + @memset(items, v); + v = .{ .array = items }; + const array = try arena.create(air.Type.Array); + array.* = .{ .elem = ty, .len = len }; + ty = .{ .array = array }; + } + } +} + +test "runtime value sizing handles deep wrappers and zero-sized leaves without recursion" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const arena = state.allocator(); + const module: air.Module = .{ + .name = "size.depth", + .format_version = 0, + .lang = .{ 0, 1 }, + .features = &.{}, + .functions = &.{}, + .types = &.{.{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }}, + }; + var m: Machine = .{ .arena = arena, .module = module, .fuel = null, .world = try .init(arena, .{}) }; + var one: Value = .{ .int = .{ .ty = .u8, .bits = 42 } }; + var overflowing = one; + var zero: Value = .{ .aggregate = .{ .decl = 0, .variant = 0, .fields = &.{} } }; + for (0..32768) |i| { + const unary = try arena.alloc(Value, 1); + unary[0] = one; + one = .{ .array = unary }; + // Reused payloads represent query inputs compactly, without claiming + // a verified construction of exponentially many runtime elements. + const empty = try arena.alloc(Value, 2); + @memset(empty, zero); + zero = .{ .array = empty }; + if (i < 64) { + const pair = try arena.alloc(Value, 2); + @memset(pair, overflowing); + overflowing = .{ .array = pair }; + } + } + try std.testing.expectEqual(@as(?u64, 1), m.valueBytes(one)); + try std.testing.expectEqual(@as(?u64, std.math.maxInt(u64)), m.arrayBytes(one, std.math.maxInt(u64))); + try std.testing.expectEqual(@as(?u64, 0), m.valueBytes(zero)); + try std.testing.expectEqual(@as(?u64, 0), m.arrayBytes(zero, std.math.maxInt(u64))); + try std.testing.expectEqual(@as(?u64, null), m.valueBytes(overflowing)); + // A zero dynamic allocation count must not mask an overflowing element. + try std.testing.expectEqual(@as(?u64, null), m.arrayBytes(overflowing, 0)); +} + fn expectCollectorAllocationFailure(source: []Value, fail_index: usize) !bool { var state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer state.deinit(); @@ -3060,6 +3168,48 @@ test "deep returned payload survives per-step collection and execution heap rele } } +test "deep owner allocation retains one-byte quota and exact fuel boundaries" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const 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 allocation.depth\nair 0\nlang 0.1\nfeatures [arrays, capabilities, effects, heap, ownership, resources]\n" ++ + "fn @main(%heap: cap) -> void\neffects [mem.alloc]\nentry:\n %p = local.alloc {s}\n local.zero %p\n %v = local.load %p\n" ++ + " own.new %v, %heap, ok -> @have, err -> @nomem\nhave(%o: own<{s}>):\n own.free %o\n ret\nnomem(%e: alloc_error):\n ret\n", .{ ty.items, ty.items }); + const checked = try check.checkAir(arena, "owner-depth.air", src); + try std.testing.expect(checked.status == .accepted); + for ([_]bool{ false, true }) |every_step| { + for (0..7) |fuel| { + var stats: MemoryStats = .{}; + const outcome = try run(arena, checked.module.?, "main", .{ + .fuel = fuel, + .memory = &stats, + .collect_every_step = every_step, + .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "1" }}, + }); + try std.testing.expectEqual(@as(u64, fuel), stats.steps); + if (fuel < 6) { + 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); + } + var stats: MemoryStats = .{}; + const rejected = try run(arena, checked.module.?, "main", .{ + .fuel = 6, + .memory = &stats, + .collect_every_step = every_step, + .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = "0" }}, + }); + // The error edge returns at step 5; success frees before step 6. + try std.testing.expect(rejected == .returned and stats.steps == 5); + } +} + 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/phase2/run/nested_allocation_quota.air b/tests/conformance/phase2/run/nested_allocation_quota.air new file mode 100644 index 0000000..3146541 --- /dev/null +++ b/tests/conformance/phase2/run/nested_allocation_quota.air @@ -0,0 +1,70 @@ +; expect: run +; result: 42 +; grant: heap=mem.alloc:12 +; phase: 2 +; spec: docs/spec/08-verifier.md §7.1; docs/spec/03-memory-model.md §19.2 +module runtime.nested_quota +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources] + +type @Empty = struct {} + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %c_1 = const.u16 7 + %c_2 = const.u16 14 + %c_3 = const.u16 21 + %arr_4 = array.make array(%c_1, %c_2, %c_3) + %arr_5 = array.splat array, 2> %arr_4 + own.new %arr_5, %heap, ok -> @ok_6, err -> @err_8 +ok_6(%ok_7: own, 2>>): + %s_10 = struct.make @Empty() + %arr_11 = array.splat array<@Empty, 2> %s_10 + own.new %arr_11, %heap, ok -> @ok_12, err -> @err_14 +err_8(%err_9: alloc_error): + trap +ok_12(%ok_13: own>): + own.new %arr_5, %heap, ok -> @ok_16, err -> @err_18 +err_14(%err_15: alloc_error): + trap +ok_16(%ok_17: own, 2>>): + own.free %ok_17 + trap +err_18(%err_19: alloc_error): + enum.switch alloc_error %err_19, budget_exceeded -> @case_budget_exceeded_20, out_of_memory -> @case_out_of_memory_21 +case_budget_exceeded_20: + br @endmatch_22() +case_out_of_memory_21: + trap +endmatch_22: + br @endmatch_23() +endmatch_23: + own.free %ok_13 + own.free %ok_7 + %c_24 = const.usize 2 + own.array %c_24, %arr_4, %heap, ok -> @ok_25, err -> @err_27 +ok_25(%ok_26: own_array>): + %again_29 = borrow.ref %ok_26 + %c_30 = const.usize 0 + %e_31 = borrow.index %again_29, %c_30 + %c_32 = const.usize 2 + %e_33 = borrow.index %e_31, %c_32 + %v_34 = load %e_33 + borrow.end %e_33 + borrow.end %e_31 + %c_35 = const.usize 1 + %e_36 = borrow.index %again_29, %c_35 + %c_37 = const.usize 2 + %e_38 = borrow.index %e_36, %c_37 + %v_39 = load %e_38 + borrow.end %e_38 + borrow.end %e_36 + %t_40 = add.checked.u16 %v_34, %v_39 + borrow.end %again_29 + own.free %ok_26 + %cast_41 = cast.widen.u64 %t_40 + ret %cast_41 +err_27(%err_28: alloc_error): + trap diff --git a/tests/conformance/source/runtime_values/nested_allocation_quota.aji b/tests/conformance/source/runtime_values/nested_allocation_quota.aji new file mode 100644 index 0000000..a0aec9b --- /dev/null +++ b/tests/conformance/source/runtime_values/nested_allocation_quota.aji @@ -0,0 +1,31 @@ +// expect: run +// result: 42 +// grant: heap=mem.alloc:12 +// phase: 6 +// spec: docs/spec/08-verifier.md §7.1; docs/spec/03-memory-model.md §19.2 +module runtime.nested_quota + +struct Empty {} + +fn main(heap: cap) -> u64 effects [mem.alloc] { + let row = [7u16, 14u16, 21u16]; + let rows = [row; 2]; + let first = own.new(rows, heap) or trap; + // Zero-sized contents still fit while the full twelve-byte grant is live. + let empty = [Empty {}; 2]; + let empty_owner = own.new(empty, heap) or trap; + match own.new(rows, heap) { + ok(unexpected) => { own.free(move unexpected); trap; } + err(error) => match error { + alloc_error::budget_exceeded => {}, + alloc_error::out_of_memory => { trap; }, + }, + } + own.free(move empty_owner); + own.free(move first); + // Repeated allocation uses the same element metric and restored authority. + let again = own.array(2usize, row, heap) or trap; + let answer = { ref values = again; values[0usize][2usize] + values[1usize][2usize] }; + own.free(move again); + return answer as u64; +}