diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index ed07d72..d243016 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -515,6 +515,8 @@ The [runtime value JSON increment](runtime-value-depth-audit.md#runtime-value-js The [cache-free runtime increment](runtime-value-depth-audit.md#cache-free-runtime-size-query-path) removes the recursive accounted-size fallback available through public verification/runtime entry. All runtime size callers propagate temporary metadata OOM before authority charging, retaining quota, fuel and ownership behavior. The deep query-only failure is independently reproduced and repaired; verified library entry and cache equivalence are separately tested. Q-060 remains open for closing traversal checks and full per-step validation; no new normative limit, trap or diagnostic is introduced. +The [closing path/lifetime inspection](runtime-value-depth-audit.md#closing-runtime-paths-and-error-exit-cleanup) identifies and repairs a separate execution-arena leak on propagated host OOM. Failure tests across caller/result and execution/collection allocations verify complete release under ordinary/per-step collection; all 1,793 ordinary conformance cases and test-extended pass. The runtime traversal inventory is documented, with verified handle-shape preconditions for the remaining one-borrow selectors. Both full GC processes are now confirmed live by host-namespace inspection, correcting an earlier mistaken termination inference; an additional std run emits each completed record immediately. None has terminal full-pass evidence yet, so Q-060 remains open for full per-step validation. + ## Q-061 — Source expression/statement nesting and native recursion Inspection during Q-059's closing inventory finds native recursion through source expression parsing (`binary`/`unary`), expression queries (`peekType`/`useIn`) and generic expression transformation (`expression`/`walk`). The fixed generic type/instantiation guards do not establish a bound on arbitrary expression or statement nesting. **Unverified:** no expression/statement stack-exhaustion probe has been run in this audit; this entry records inspection risk, not an observed failure or a new acceptance rule. diff --git a/docs/design/runtime-value-depth-audit.md b/docs/design/runtime-value-depth-audit.md index ed9e816..5caea7e 100644 --- a/docs/design/runtime-value-depth-audit.md +++ b/docs/design/runtime-value-depth-audit.md @@ -120,3 +120,54 @@ attach for read-only stack inspection was rejected by the host's ptrace policy. Q-060 remains open until the traversal/lifetime audit and full validation have terminal evidence. Q-059's [compiler inventory](type-traversal-inventory.md) is now resolved; the earlier statements about its open query paths are historical. + +## Closing runtime paths and error-exit cleanup + +The production path inventory covers verified interpreter state, not arbitrary +fabricated host values. Arrays/aggregates have finite materialized structure; +backing-cell and closed-graph cycles use the copier's forwarding maps. + +| Path | Handling | +|---|---| +| Zero construction, storage/SSA copying | Explicit pending-sibling continuations; no recursive payload descent. | +| Collector/result copying | Forwarded shells plus jobs for cells, payloads, graph objects, paths and mutex views. Each root finishes before escaping. | +| Accounted value/type size | Array cursor and checked factor; nominal type queries use the iterative cache-free/cached path closed by Q-059. | +| Place projections, slice bytes | Flat index-path loops and byte loops. | +| Endpoint/atomic/mutex/buffer selectors | Their remaining self-calls follow at most one borrow on verified inputs: verifier operations require a direct handle or exactly a borrow of that handle. Resource/graph selectors already inspect one such place directly. | +| Task frames, channel roots, authorities | Explicit frame/root/parent loops; the existing call-depth limit is 1,024. | +| Race shadows, weak-memory views/messages | Flat entries/path copies and message loops. | +| Runtime JSON | Pending sequences inside one raw-value boundary; opaque handles are not traversed. | + +The lifetime inspection finds a separate host-error defect: `run` releases its +execution arena only after successful result copying. A verified 1,024-byte +array program, through a private allocator seam retaining the old run body, +fails at result `Copier.ensureItems`; the controlled execution backing allocator +records 259,888 allocated bytes and zero freed bytes. These are host allocator +counters, not Aji authority charges. The failing unit assertion reproduces the +missing cleanup before the repair. + +Execution-arena cleanup is now deferred on every run exit, still before output +and host cleanup and after complete returned-value copying/statistics on success. +The invariant is that returned payloads survive in the caller arena while all +execution-owned blocks are released on success or propagated host OOM. Collection +continues to discard its failed new arena; its successful replacement inherits +the same backing allocator. The private test seam exposes no public option or +semantic flag. The production allocator remains page-backed. There is no retry, +transactional collection or output rollback guarantee. + +Verifier initialization/ownership/borrow rules, runtime safe points, Aji quota +charges, effects, traps, scheduling and fuel are unchanged. The existing +zero_structure_siblings and returned_mixed_json AIR/source pairs remain valid; +read_uninitialized/copy_overlapping still reject E1010/E2101. No new diagnostic +is added: OutOfMemory remains a host error and no partial Outcome is returned. +The public run API and successful records retain backward compatibility. + +Failure tests cover every caller-arena and execution-backing request, including +result copying and fresh collection arenas, under ordinary and per-instruction +collection. All failed/completed heaps have equal allocated/freed counters; +successful arrays remain readable after heap release. Units, format checks, +test-extended and all 1,793 ordinary conformance cases pass with exact coverage. +Twenty-nine old/new deterministic/hosted CLI pairs retain exact records and +independently expected fuel boundaries/values at depths 0–32,768. The full +per-instruction runs and the focused std run remain live validation; Q-060 and +Phase 6 are not closed by these ordinary results. No fresh Claude review is claimed. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index b84ee65..4e5f728 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -514,3 +514,9 @@ Units/format checks, shallow/deep key-boundary and OOM tests, generic/static-fun Q-059 is resolved for the [compiler type-traversal inventory](../design/type-traversal-inventory.md). The final repair removes a confirmed `typeOfNoFail` failure reached through shallow field expressions; complete checks accept 16,384/65,536 nested field-array levels. The best-effort query retains its type classification and OOM-to-null contract without publishing partial output. Independent shallow/deep/allocation tests, units/format checks, all 1,793 conformance cases with exact coverage, nominal CLI integration (130 checks) and byte-identical old/new source checks/lowerings (1,423/506) pass. This closes type descent, not arbitrary expression/statement recursion (inspection-only Q-061), Q-056 policy, Q-060's unfinished full per-step GC validation or Phase 6 exit review. No normative/bundle/feature/code or acceptance-limit changes; Claude's earlier nominal-property review does not cover these later frontend increments. + +## Runtime error-exit cleanup (2026-10-10) + +The [Q-060 closing inspection](../design/runtime-value-depth-audit.md#closing-runtime-paths-and-error-exit-cleanup) repairs an execution-arena leak when host OOM interrupts execution or result copying. Deferred cleanup retains the public API, successful output lifetime, fuel, quotas and collection safe points. Exhaustive caller/heap allocator failures pass under ordinary/per-step collection; units, format checks, test-extended, all 1,793 ordinary conformance cases with exact coverage and 29 exact old/new fuel/value CLI pairs pass. + +The earlier Debug full GC process is also still live, as is ReleaseSafe; host namespace inspection corrects the previous termination inference. Conformance now flushes each completed result, and an additional focused std GC run has live progress. These are unfinished validation, not full passes. Q-060 and Phase 6 exit gates remain open; no normative/bundle/feature/code/acceptance-limit change or new Claude review is claimed. diff --git a/src/interp/machine.zig b/src/interp/machine.zig index f822750..c27fdc5 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -249,10 +249,16 @@ pub const Error = std.mem.Allocator.Error || error{ EntryNotFound, DuplicateGran /// Runs `entry`, which must take no parameters. `module` must have passed /// verification. pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, options: Options) Error!Outcome { + return runWithHeapAllocator(arena, module, entry, options, std.heap.page_allocator); +} + +// Private allocator seam for failure/cleanup tests; the public runtime always +// uses the same page-backed execution heap and exposes no allocator flag. +fn runWithHeapAllocator(arena: std.mem.Allocator, module: air.Module, entry: []const u8, options: Options, heap_allocator: std.mem.Allocator) Error!Outcome { const idx = module.functionIndex(entry) orelse return error.EntryNotFound; const f = module.functions[idx]; for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound; - var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) }; + var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world), .exec_heap = .{ .space = .init(heap_allocator) } }; if (options.hosted) |io| m.host = .{ .arena = arena, .io = io }; m.quantum = @max(options.quantum, 1); m.task_limit = options.task_limit; @@ -263,6 +269,9 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti defer if (options.output) |o| { o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} }; }; + // Error exits during execution, collection or result copying own the + // current execution arena too. It still dies before output/host cleanup. + defer m.exec_heap.space.deinit(); // Instantiation (spec 05 §10.2): every capability parameter gets exactly // one grant of its kind, and every grant names a parameter. @@ -316,7 +325,6 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti 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; } @@ -746,7 +754,7 @@ const Machine = struct { /// 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); + var next: std.heap.ArenaAllocator = .init(m.exec_heap.space.child_allocator); errdefer next.deinit(); var tmp: std.heap.ArenaAllocator = .init(std.heap.page_allocator); defer tmp.deinit(); @@ -2774,6 +2782,66 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void { const h = "module t\nair 0\nlang 0.1\nfeatures []\n"; +test "run releases execution heaps on host allocation failure" { + var fixture: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer fixture.deinit(); + const a = fixture.allocator(); + const source = "module cleanup\nair 0\nlang 0.1\nfeatures [arrays, ownership]\n" ++ + "fn @main() -> array\neffects []\nentry:\n" ++ + " %p = local.alloc array\n local.zero %p\n %v = local.load %p\n ret %v\n"; + const checked = try check.checkAir(a, "cleanup.air", source); + try std.testing.expectEqual(check.Status.accepted, checked.status); + for ([_]bool{ false, true }) |every_step| { + // Failing each caller-arena request includes failures while copying + // the returned value after execution has already allocated its heap. + var caller_index: usize = 0; + while (true) : (caller_index += 1) { + try std.testing.expect(caller_index < 256); + var caller_storage: std.heap.ArenaAllocator = .init(a); + defer caller_storage.deinit(); + var caller_fail: std.testing.FailingAllocator = .init(caller_storage.allocator(), .{ .fail_index = caller_index }); + var caller: std.heap.ArenaAllocator = .init(caller_fail.allocator()); + // This outer test arena reclaims leaked blocks even on the old + // failing implementation; counters measure the runtime's frees. + var heap_storage: std.heap.ArenaAllocator = .init(a); + defer heap_storage.deinit(); + var heap_backing: std.testing.FailingAllocator = .init(heap_storage.allocator(), .{}); + var output: Output = undefined; + const result = runWithHeapAllocator(caller.allocator(), checked.module.?, "main", .{ .fuel = 4, .collect_every_step = every_step, .output = &output }, heap_backing.allocator()); + if (caller_fail.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + const returned = (try result).returned.array; + try std.testing.expectEqual(@as(usize, 1024), returned.len); + for (returned) |value| try std.testing.expectEqual(@as(u128, 0), value.int.bits); + } + try std.testing.expectEqual(heap_backing.allocated_bytes, heap_backing.freed_bytes); + caller.deinit(); + try std.testing.expectEqual(caller_fail.allocated_bytes, caller_fail.freed_bytes); + if (!caller_fail.has_induced_failure) break; + } + // Fail every execution-heap request, including fresh collection + // arenas. Failed and completed heaps must both release all blocks. + var heap_index: usize = 0; + while (true) : (heap_index += 1) { + try std.testing.expect(heap_index < 256); + var caller: std.heap.ArenaAllocator = .init(a); + defer caller.deinit(); + var heap_storage: std.heap.ArenaAllocator = .init(a); + defer heap_storage.deinit(); + var backing: std.testing.FailingAllocator = .init(heap_storage.allocator(), .{ .fail_index = heap_index }); + const result = runWithHeapAllocator(caller.allocator(), checked.module.?, "main", .{ .fuel = 4, .collect_every_step = every_step }, backing.allocator()); + if (backing.has_induced_failure) { + try std.testing.expectError(error.OutOfMemory, result); + } else { + try std.testing.expectEqual(@as(usize, 1024), (try result).returned.array.len); + } + try std.testing.expectEqual(backing.allocated_bytes, backing.freed_bytes); + if (!backing.has_induced_failure) break; + } + } +} + test "value JSON preserves field order, escaping, whitespace options and outer stringify state" { var state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer state.deinit();