Files
aji/docs/design/runtime-value-depth-audit.md
T

25 KiB
Raw Blame History

Runtime value-depth audit

Non-normative evidence at 53030ef, separate from Q-059's compiler type traversals. No acceptance limit or runtime rule is proposed here.

Generate TYPE as "array<" * 32768 + "u8" + ",1>" * 32768:

module depth.zero
air 0
lang 0.1
features [arrays, ownership]
fn @main() -> void
effects []
entry:
 %a = local.alloc TYPE
 local.zero %a
 ret

Every array length is one. The accounted value/frame size is one byte, and aji check accepts with no output. aji run --fuel 8 aborts with exit -6, no JSON run record and a symbolized traceback containing 9,997 zeroValue frames. The input has three instructions; the failure occurs inside materialization, not because fuel is exhausted. Tests use the ordinary 8-MiB native stack; only child core capture is disabled. No timeout ends the run.

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. All five confirmed failure paths now have iterative repairs. Q-060 remains open for the closing call-path audit; the earlier increments record the failures that led to each repair.

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.

Storage/value-copy repair

DeepCopy now visits aggregate/array payloads in the original preorder using explicit pending-sibling continuations. CopyAll keeps its root-list order and invokes that traversal for each root. Every occurrence gets a fresh payload, even when the input reuses one payload more than once. Aggregate declaration/variant identity and scalar bits/types are preserved; owner, mutex, graph and other identity leaves remain shallow, just as before. This is distinct from the collector, which must preserve sharing. Temporary traversal storage is released before the next instruction safe point; allocation failure does not publish a partial local.store value.

The invariant is unchanged storage/SSA value independence, alongside unchanged ownership identity and explicit loan rules. Spec 07a's local.store/local.load/load/store rules and spec 08's type/initialization/borrow checks are unchanged. The mixed Copy-record/enum/array AIR/source pair copies into and out of local storage, changes one repeated row without affecting the other, restores from a snapshot, and checks that a later store does not mutate the snapshot. Existing read_uninitialized and copy_overlapping AIR cases remain rejected with E1010/E2101; there is no new rejection or diagnostic code. Aji authority/effects, deterministic instruction/fuel counts, accepted syntax/types and runtime traps remain unchanged. No new limit or bundle text is introduced.

Unit tests copy 32,768 alternating array/aggregate levels with pending siblings, empty payloads, variant identities and signed integer bits. They mutate one of two complete copies, independently test reused source payloads within one value, preserve explicit owner/mutex/graph identities, and force a mid-copy payload allocation failure while retaining complete old local storage. A verified deep programme pins exact fuel 0–4 boundaries: local.load still consumes one instruction. Forty-two mixed-type old/new runs have identical records.

The previously crashing 32,768-level zero/local.load/ret programme now returns normally under fuel 8 at the ordinary collection threshold. Adding local.store back to the same local forces an ordinary threshold collection and aborts without JSON in Copier.value/items (4,997/4,998 symbolized frames, zero deepCopy frames). This confirms the next failure without collection instrumentation. The collector/result copier, accounted-value queries and output serialization remain Q-060 work.

Sharing-preserving copy repair

The collector and run-result copier now use explicit continuation jobs for payload elements, cell values, graph objects, projection paths and mutex views. Each shell enters its existing forwarding map before descendants are visited. Completed roots therefore retain shared cells/payloads, SSA-backed storage, slice ranges, buffer identity/capacity, mutex/guard identity and graph cycles. Metadata, race shadows and weak-memory views are copied before the old execution heap is released. Result copying uses the same traversal. Unlike storage/value copying, repeated references intentionally resolve to the same new object. Temporary jobs/maps remain in the caller's temporary arena, while payloads remain in the destination heap; the original depth-first destination allocation order is retained.

The invariant is that all reachable execution state survives collection with identical identity relationships and values, and every externally returned root has completed copying. The original verifier type/ownership/initialization/loan rules and runtime safe points are unchanged. The positive mixed Copy-record/enum/array AIR/source examples still return 42; read_uninitialized and copy_overlapping remain E1010/E2101 rejection examples. No new diagnostic, effect, Aji allocation charge, feature, trap, accepted-depth limit, runtime rule, fuel step or schedule event is added. A failed copier is discarded and its arenas released; this does not introduce transactional collection or retry guarantees.

Unit tests free the old heap before inspecting forwarded backing cycles, shared payloads, places/slices, buffers, mutex guards/views, graph cycles and race-shadow paths/epochs. An allocator probe fails every copier allocation request in turn and checks propagated OutOfMemory and arena cleanup. Separate internal-representation tests traverse 32,768 payload/cell levels with siblings; these are not claimed as typed source programs. Verified deep-program tests pin exact fuel 0–5 boundaries, ordinary threshold collection, per-instruction collection, and returned payloads after the execution heap is freed. The formerly crashing deep CLI store programme now returns null, and the original zero programme also passes with per-instruction collection.

Validation: unit/format checks, test-extended and all 1,787 ordinary conformance cases pass. Per-instruction collection additionally passes 57 focused run cases across phases 1/2/4/5 and source runtime_values, plus all 26 phase-3 run cases with stress 16 (each applicable schedule quantum). Old/new records match exactly for 42 mixed-value runs and 104 runs across mutex/channel/graph/buffer/atomic fixtures and eight schedule seeds. The full per-instruction conformance run is additional validation, still running at this checkpoint.

Two follow-up failures are independently verified on the same ordinary native stack, disabling only child core capture:

  • Returning the 32,768-level array succeeds through interpretation/result copying in unit tests, but CLI output aborts with exit -6 and no JSON. The trace starts at std.json.Stringify's fixed 256-level nesting stack (BitStack index 32, length 32) and contains 256 writeValue frames. This is a serialization failure, not a demonstrated native-stack overflow in writeValue; its recursion still needs removal or independent audit.
  • 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.

Runtime value JSON repair

WriteValue now emits the complete value through a raw-value boundary in the outer std.json.Stringify. An explicit pending-sequence stack traverses arrays, record fields and enum payloads; the outer stringify never stores their nesting in its fixed 256-level table. Field order, variant/payload shape, decimal integer representation, escaping, whitespace and opaque handles retain their existing encoding (spec 07a, Run result). The public writer API and diagnostic schema are unchanged.

The invariant is byte-identical encoding of existing runtime values without traversing opaque identity handles or mutating returned payloads. Traversal metadata lives in a temporary host arena, released on success and failure; it adds no Aji allocation, authority, effect, fuel charge or collection point. Writer errors propagate as before; metadata allocation failure uses the existing WriteFailed interface. No recovery after partial output is promised. The CLI still buffers a complete run record before publishing it. Verifier rules are unchanged: the new returned_mixed_json AIR/source pair returns an enum containing records, nested arrays, signed integers and empty values; the existing source borrow_returns/main_return rejection retains E7006. No new rejection, trap, feature, depth limit or normative/bundle text is introduced.

Unit tests compare exact bytes with the ordinary Zig encoder in 112 combinations of whitespace, Unicode escaping, string-array, nonportable-number and optional-field options, wrapped between other fields in an outer object. Existing Aji raw decimal integers are preserved even when string mode for nonportable numbers is selected. A codec-only 32,768-level mixed record/variant/array value checks pending siblings and empty leaves against independently constructed bytes; it is not claimed as an executed source programme. Allocation failures check temporary-arena cleanup, and fixed-capacity writers fail at every byte boundary with the exact expected prefix. Another test fills the outer stringify's 256-level table, writes a nested runtime value and then continues and closes the outer containers.

The verified 32,768-level returned-array programme now produces the complete 65,568-byte CLI record, including its newline, in both deterministic and hosted profiles under fuel 8. Unit tests write its outcome after execution-heap release under ordinary and per-instruction collection. Hosted tests also compare both new shallow examples with the old CLI, using fuel rather than wall-clock termination.

Validation: all units, format checks, test-extended and the complete current set of 1,791 ordinary conformance cases pass (the prior 1,789-case full run plus the two added cases). Both added cases pass in Debug with collection before every instruction. Forty-four old/new shallow run records are byte-identical. At this checkpoint the earlier Debug per-step run had no completion result after 785 passing records and its process handle was missing; a namespace-limited process check failed to identify it before a replacement ReleaseSafe run was started. The later host-process inspection below corrects the mistaken inference that the Debug run had ended. Neither incomplete run is counted as a full pass.

Q-060 remains open for a closing call-path audit. Inspection shows that the public verify wrapper returns diagnostics without replacing the caller's module with verifyModule's derived-cache result, while interp.run accepts a verified module without rebuilding those caches. Runtime nominal size queries can therefore reach the uncached fallback tracked by Q-059. Whether this yields a failure on a verified cache-free library input is unverified; the mixed codec test above is not evidence for that path. No fresh Claude review was available for this increment.

Cache-free runtime size-query path

The nominal size-query increment removes the recursive fallback reached by runtime size callers when a public verify caller retains its original module. A direct constructed 32,768-declaration query independently reproduces the old fallback failure and now returns one byte. Parsed, verified cache-free programmes at nominal depths 1,024 and 4,096 run successfully both before and after the repair; no old runtime failure at those depths is claimed. The distinction between query-only and fully verified inputs is retained.

Runtime queries now pass their host allocator and propagate temporary metadata OutOfMemory before authority charging or result publication. Temporary state is released after each query; arithmetic null, zero-sized content, maximum enum payloads and allocation failure/release rules keep their meanings. A verified quota test compares 54 cached/cache-free outcome pairs (108 runs), including exact fuel boundaries and per-instruction collection. The original verify and run APIs remain usable without derived caches. No normative, bundle, feature, code, trap or accepted-depth change is introduced. Q-060 remains open for the closing traversal audit and additional full per-step validation; Q-059's uncached nominal property queries remain separate work.

Live-process and progress-output correction (2026-10-10)

Host-namespace inspection identifies both full per-step runs as live: Debug PID 376545 writes collector-gc-conformance.jsonl (1,612 complete passing records at inspection), and ReleaseSafe PID 458411 writes value-json-gc-safe-conformance.jsonl (1,610). /proc inside the command sandbox cannot see these host PIDs, although the approved ps command lists them. A missing tool handle plus that namespace-limited check was insufficient evidence of termination. Neither process was stopped or restarted in this audit.

The conformance runner's 4-KiB stdout buffer can also retain completed records and leave an unrelated final record partially visible while later cases run. It now flushes after each completed case, preserving record bytes/order and exit status while exposing progress promptly. A separate current ReleaseSafe source/std per-step run uses this writer; it is additional focused validation, not a restart or a full-suite pass. No wall-clock timeout ends any run. A GDB 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 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.

Per-step validation observation (2026-10-11)

Host inspection now confirms Debug PID 376545 and the additional source/std PID 1456454 are still running. ReleaseSafe PID 458411 is absent. Its value-json-gc-safe-conformance.jsonl has 1,789 complete distinct passing records, without duplicates, but its terminal exit status is unavailable. Compared with the current 1,793-file corpus, it lacks the AIR/source returned_mixed_json pair and source generic identity-growth 31/63 cases. value-json-gc-safe-current-observation.json records that comparison.

Two current ReleaseSafe --collect-every-step filtered runs complete with exit 0 and exactly those four passing cases, no missing/extra/duplicate or nonpassing records (gc-current-missing-cases.audit.json). The generic growth cases are verifier rejections, not additional runtime executions. This supplies current focused coverage of the absent cases; it does not establish terminal success for the historical run or a full current-binary GC suite pass. No live run was restarted or stopped and no wall-clock timeout ended a test. Q-060 and the Phase 6 full-validation gate remain open.