Files
aji/docs/design/air-type-depth-audit.md
T

23 KiB
Raw Blame History

AIR anonymous type-depth audit

Non-normative evidence for Q-059, initially at ba99ad6. This audit introduces no syntax-nesting limit, code, feature or acceptance rule. Parser repair preserves format-0 syntax and diagnostics; the verifier and other type traversals remain a separate open obligation.

Reproducer and observations

Generate a parameter type with depth d using "array<" * d + "u8" + ",1>" * d:

module type.depth
air 0
lang 0.1
features [arrays, ownership]
fn @f(%x: TYPE) -> void
effects []
entry:
 ret

Replace TYPE with the generated type and call aji check FILE.air. Each array has length one; accounted size is one byte. No runtime execution, model experiment or held-out input is involved. Tests used the ordinary 8-MiB native stack; only core-dump capture was disabled for the child. No wall-clock timeout ended a probe.

Depth Input bytes Before parser repair After parser repair
64 683 accepted, exit 0 not rerun
256 2,411 accepted, exit 0 not rerun
1,024 9,323 accepted, exit 0 accepted, exit 0
4,096 36,971 aborted, exit -6 accepted, exit 0
16,384 147,563 not run aborted, exit -6

The old 4,096-depth probe emitted no diagnostic JSON and a Zig segmentation-fault traceback before SIGABRT. It contains 3,529 parseType and 3,528 parseCompoundType frames. The new 16,384-depth failure instead contains 5,000 sizeQuery and 5,000 sizeValue frames in verifier/budget.zig. These repeated native frames and stack-dependent depth are evidence of native stack exhaustion, rather than a specified E5101 rejection. No core was captured; diagnosis uses Zig's symbolized stderr traceback. The observation confirms two recursive failure sites, not bounded behavior of every downstream traversal.

Parser repair and validation

Compound syntax is a unary chain. The parser now stores pending constructors and their inner spans in an arena-backed list, then closes/builds them from the innermost outward. File modes and capability kinds remain leaves. Feature checks still precede child parsing; member gates still precede the closing delimiter. The same constructor names, array-length checks, unknown-name behavior and error positions remain. Memory grows with the explicit input depth; no program heap allocation, ABI or language semantics changes.

Unit tests parse and inspect 32,768 array levels without recursive equality/formatting in the test. Separate 8,192-depth probes retain a single E0004 at the unknown leaf and a single E0001 at the missing outer delimiter. All unit tests, Zig format checks and 1,765/1,765 conformance cases pass. An old/new comparison over all 364 public conformance AIR files preserves exit status, stdout diagnostics and stderr exactly. A further 232 constructor/feature/error probes cover all nineteen unary/array constructors, reserved/unknown leaves, invalid file/capability names and invalid array lengths. These constrain parser compatibility; they are not proof of all input compatibility or a complete Q-059 fix.

The subsequent budget failure is verified and must be repaired without silently limiting previously permitted syntax. Iterative size evaluation, inner-type budget visiting, property/validity/equality traversals and diagnostic/canonical formatting require separate inspection. Q-059 stays open; resolving parser recursion alone does not resolve verifier processing.

Size-query repair

The next increment replaces the verifier's recursive size evaluation with explicit continuations for array/atomic/mutex wrappers, struct sums and enum payload sums/maxima. Only nominal member edges advance the original cycle-depth guard. Null overflow short-circuits remaining fields/variants and is cached at every completed ancestor, retaining the existing finite result for invalid nominal cycles. Inner-type budget visiting is iterative too.

The immutable size cache now also keys anonymous array/atomic/mutex nodes by constructor, storage identity and nominal depth. Different atomic/mutex constructors sharing one content pointer remain distinct. Every query reuses its pending stack; read-only runtime queries allocate nothing. Verification still rebuilds caller-supplied caches, including anonymous entries. Raw identities do not enter AIR, reports, diagnostics or canonical text; replacing type storage invalidates the cache.

The allocation-free fallback folds anonymous chains using a saturated affine map, retaining zero-sized leaves even when its multiplicative coefficient exceeds u64. Invalid zero array lengths cannot mask an overflowing inner segment. Nominal fallback traversal remains recursive; the memoized verifier query handles deep nominal chains explicitly. This distinction is not a claim of bounded native stack for arbitrary uncached host-side queries.

Unit cases cover 32,768 anonymous levels, 32,768 nominal declarations, zero/overflow behavior, null-result reuse, shared-content constructor identities and rebuilding a forged anonymous cache. Two AIR/source pairs additionally preserve acceptance of sixty-four huge arrays over an empty record and E5101 for the same chain over u64. All four new fixtures pass GC-before-each-step checking; the rejection adds a verified same-code twin. The existing full 1,765-case conformance snapshot and sixteen focused nested-size/heap-quota cases pass, and all 364 pre-existing AIR checks retain exact old/new outputs. The full snapshot plus four focused fixtures cover all 1,769 current conformance cases; test-extended also passes. These tests confirm the metric and cache behavior, not the whole Q-059 pipeline.

At depth 4,096 the complete check still accepts. At depth 16,384 it now reaches type validity and aborts with 8,711 wellFormed frames in verifier/types.zig, rather than sizeQuery/sizeValue. The size failure is removed; validity/property/equality/formatting and uncached nominal traversal remain open. No syntax-depth limit, semantic feature, public code or bundle text is added.

Type-validity and finite-layout repair

Type-position validation and generic-argument array-length checking now walk anonymous chains iteratively. The order of per-node checks, the transition to each inner position, and the graph-owner stop remain unchanged: graph content is checked for IslandSafe and is not rechecked as an ordinary member. Property predicates called by those checks are a separate traversal obligation.

Finite-layout checking now uses suspended DFS frames for nominal declarations, retaining field order, enum variant/payload order, empty variants and the original grey/black cycle behavior. An active declaration continues its remaining siblings after a back edge marks it black. Anonymous layout edges are iterative too. Arrays always follow their element; the original ownership/borrow wrapper set follows its content only with linear_aggregates. Graph owners and atomic cells retain their original layout boundary. No new accepted/rejected type position or cycle rule is introduced.

Unit cases cover 32,768 anonymous levels, a 32,768-declaration acyclic nominal chain, a deep anonymous self-cycle, the wrapper feature gate, graph validation's single E2111 and diagnostic order through siblings after back edges. Unit/format checks and all 1,769 conformance cases pass. All 366 public conformance AIR checks retain exact old/new exit status, stdout and stderr. An additional 48 generated mixed struct/enum cyclic graphs retain exact old/new outputs, including cycle selection and order.

The complete 4,096-depth check still accepts. At 16,384 it passes wellFormed and then aborts in Module.isLinearType: the symbolized traceback contains 10,001 isLinearType frames, no JSON diagnostics and exit -6. The probe stops there; 32,768 is not claimed to pass the complete pipeline. This confirms the next property-query failure, while equality, formatting and uncached nominal traversals also remain open. Q-059 is not resolved. No syntax-depth limit, semantic feature, public diagnostic code or bundle text is added.

Anonymous property-query repair

Whole-value linearity, Zeroable, Copy, Local, IslandSafe and endpoint/forbidden-content queries now follow their original anonymous edges iteratively. Send/Share uses an explicit query mode: Send follows ref/slice by querying Share, and Share follows mutex by querying Send. The unchanged terminal classifications and nominal-cache leaves decide acceptance. No borrow, transfer, aliasing, concurrency or runtime rule changes; predicates remain allocation-free read-only queries.

Nominal-property preparation now discovers dependencies through anonymous chains iteratively, still including phantom edges. Its monotone worklist, declaration/field order and fixed-point values are unchanged. Height and source-witness distance fold anonymous edges using their existing saturation at 65 and 34. These are property summaries, not new syntax limits; saturated chains can stop without changing the summary. Uncached nominal fallback calls remain recursive. The existing depth-64 guarded bounded predicate and depth-32 witness remain separate bounded traversals.

Unit tests cover 32,768 anonymous arrays ending in plain data, task-local state or a channel endpoint, both direct and nominal cached queries. A 32,768-handle phantom chain retains dependency/height behavior, and 65,536 alternating ref/mutex edges retain Send/Share mode changes at a non-Share region leaf. Boundary tests retain height and witness-distance saturation. Existing cyclic fixed-point, shared-diamond and mixed cached/uncached tests pass with the new loops. All unit/format checks, test-extended and all 1,769 conformance cases pass; all 366 public AIR files retain exact old/new exit status, stdout and stderr.

The original complete check now accepts depths 4,096, 16,384 and 32,768 on the ordinary 8-MiB stack, with no diagnostic output. A separate 16,384-depth return-equality check accepts, and an invalid atomic content type at the same depth returns E1001 with the complete found type rather than aborting. These observations do not prove arbitrary-depth equality/formatting or uncached nominal traversal. Q-059 remains open; no semantic feature, public diagnostic code, bundle growth or new acceptance limit is introduced.

Further probes confirm the remaining sites rather than merely inferring them from source: return equality accepts depth 32,768 but aborts at 65,536 with 10,001 Type.eql frames; invalid atomic content aborts at depth 32,768 with 9,999 printType frames. Both failing checks exit -6 without diagnostic JSON. Core capture is disabled only for the child; no timeout ends a probe. Equality and diagnostic/canonical type printing now have independently verified native-stack failures.

Type equality and printing repair

Type.eql now compares anonymous chains iteratively without allocation. Tags still differ before descent; every array length is checked before its element, and named types compare declaration indices without expanding the nominal graph. All constructor and leaf identities are unchanged.

Type printing now records anonymous suffixes in an explicit stack, then emits them from the innermost outward. Array suffixes retain their original lengths and canonical comma/space spelling; other wrappers close with >. Named declarations remain names. The internal Zig print/printType API receives a compiler allocator explicitly, with updated verifier/serializer callers; allocation and writer errors propagate. Stack storage is proportional to input nesting, deallocated after the print attempt, and adds no heap allocation to an Aji program. AIR text, diagnostic fields/codes and JSON serialization rules do not change.

Unit tests compare separate 65,536-level chains with equal types, unequal deep leaves and unequal middle array lengths; they retain each unary constructor identity. A 65,536-level varied-length type prints exactly and passes parse/print/parse/print canonical equality. Wrapper spellings, suffix-allocation failure and buffered writer failure are checked independently. Unit/format checks, test-extended and all 1,769 conformance cases pass, and all 366 public AIR checks retain exact old/new exit status, stdout and stderr.

Both verified crashing CLI inputs now finish: return equality at depth 65,536 accepts with no output, and invalid atomic content at depth 32,768 returns exactly one E1001 at the original primary position with the complete canonical found type. These are direct process outcomes on the ordinary native stack, not just isolated helper tests. Uncached nominal fallback and other type-query call paths still require audit; Q-059 remains open. No new syntax-depth limit, semantic feature, public diagnostic code or bundle text is introduced.

Audit-report traversal

Call-path inspection finds a further anonymous traversal in report.write's capability-kind collector. The verified 65,536-depth parameter module accepts checking but aji report aborts with 10,000 go frames (plus one inner frame), no JSON and exit -6. The collector now iterates inner types, preserving its nominal-name stop, scan sites, deduplication and sorted output. The complete report probe now returns an audit JSON document, and a checked deep capability parameter unit test retains sorted deduplication across declarations, parameters, return and block parameters. Unit/format checks and all 1,769 conformance cases pass; all 366 public AIR report commands preserve exact old/new exit/stdout/stderr.

The CLI retains verifyModule's size/property caches in check.Report.module; frontend constraints use properties.prepare before structural queries. Uncached nominal fallback remains present in the low-level APIs and needs its own audit. No blanket native-stack claim is made for all query paths. A separate accepted runtime zero-materialization probe exposes Q-060; compiler type repairs do not resolve runtime value traversal.

Cache-free nominal accounted-size queries

At c906441, a direct accountedSize query over a constructed chain of 32,768 single-field nominal records ending in u8 aborts with exit -6 on the ordinary 8-MiB stack. Its symbolized stderr contains 5,001 accountedSize and 5,000 uncachedBaseSize frames before the traceback limit. This is an executed low-level size-query failure, not a claim that the full verifier accepted that constructed module. A separate parsed programme with 1,024 or 4,096 uniquely named nested records passes the public verify wrapper, retains neither cache in the caller's module, then allocates/frees its one-byte contents through interp.run under fuel 8. Both old runs return normally after six instructions. No wall-clock timeout ends a probe; only child core capture is disabled.

The public size query now accepts a compiler allocator and propagates OutOfMemory separately from null arithmetic overflow. Cached entries and anonymous/scalar queries remain allocation-free. An uncached nominal leaf uses SizeMemo's explicit continuations in a temporary host arena, released before returning. Partial immutable module caches may supply child entries, including cached null; neither type storage nor caller cache is mutated. The nominal cycle guard, checked field sums, enum payload maxima/tag accounting, unary affine folding and early overflow behavior are unchanged. The recursive arithmetic derivation is retained only as a shallow independent test oracle.

All runtime size-query callers propagate metadata allocation errors before charging authority or publishing new payloads. The existing accounted-size invariant (spec 08 §7.1), verifier acceptance/priority, heap/region/graph/buffer/channel charges and release rules remain unchanged. This adds no Aji allocation, effect, fuel charge, scheduling point, code, trap, feature, semantic flag or depth limit. The internal Zig accountedSize API gains an allocator/error result; AIR/source syntax and CLI records are unchanged. The existing nominal_queries/cycle AIR/source rejection pair still expects E1003, and the valid nested_allocation_quota pair retains its precise allocation and release behavior.

Unit tests compare 7,168 shallow mixed struct/enum/wrapper queries, including invalid cycles, zero lengths and overflow, against the independent arithmetic derivation. A 32,768-declaration query now returns one byte. Every underlying metadata allocation is failed in turn, checking propagated OutOfMemory and complete temporary cleanup; cached success/overflow and partial-cache reads are checked separately. A verified enum/record/array programme runs 108 times across cached/cache-free modules, quota boundaries, fuel 0–8 and ordinary/per-instruction collection; all 54 paired records and instruction counts agree. Runtime metadata OOM remains a host error, not a budget_exceeded edge.

The repaired process-level 32,768-declaration query returns one byte, and both parsed cache-free library programmes retain their six-instruction result. All units, format checks, test-extended and all 1,791 current conformance cases pass; all 370 public conformance AIR check commands retain exact old/new exit status, stdout and stderr. Uncached nominal property predicates and their public call paths remain separate Q-059 work. No fresh Claude review was available.

Cache-free nominal property queries

At 897f538, each of nine direct queries over 32,768 nested nominal records ending in u8 aborts with exit -6 and recursive property frames on the ordinary 8-MiB stack: linearity, Zeroable, Copy, Local, Send, Share, IslandSafe, endpoint and forbidden content. These constructed resolved graphs test the query API, not acceptance by the complete verifier. Only child core capture is disabled; no timeout terminates a probe. All nine repaired probes return their expected booleans.

Public property queries now take a host allocator and propagate metadata OutOfMemory. An iterative classifier retains the original anonymous edges, Send/Share transitions and terminal rules. Cached facts and anonymous terminal paths allocate nothing. A cache-free nominal query runs the existing monotone property worklist in a temporary arena and releases it before returning; it neither mutates the caller's module nor installs a cache. Zeroable rejects an enum without preparing its payload graph. Explicit prepared queries serve internal stages whose preceding type verification supplies immutable caches and value types. Public generic-argument validation uses fallible queries where that precondition does not hold. The private derivedType helper already receives the prepared module; its fallible calls therefore read cached facts without allocating.

The preserved invariant is that ownership/transfer/aliasing decisions use the same structural facts, independently of whether the caller retained verifier caches (spec 02/03/04). Property preparation retains its fixed points, universal/existential aggregation, declaration dependencies, phantom edges and saturated summaries. Invalid recursive layouts still reject E1003. Valid source/generics/constraints_positive.aji and the nominal_queries/cycle AIR/source rejection pair remain conformance examples; raw and prepared own_array<Plain> arguments accept, while own_array<Owner> arguments retain the same E1001 envelope. Verifier rules, runtime ownership, authority, fuel and deterministic scheduling are unchanged. There is no new Aji allocation, code, trap, feature, flag, syntax limit or bundle text. Only the internal Zig allocator/error API changes.

Tests compare both raw and prepared queries against 9,216 independent shallow pre-repair derivations (18,432 comparisons). Twenty-seven deep queries cover plain, task-local and endpoint leaves with pending sibling fields. Every temporary allocation is failed in turn for all nine properties, checking OutOfMemory and complete cleanup; prepared/terminal reads succeed with an allocator that rejects its first request. Generic-argument metadata failure produces no semantic diagnostic. Units, format checks and test-extended pass. The full property-engine conformance snapshot passes all 1,791 cases; old/new CLI checks are byte-identical for all 370 AIR and 1,421 source files, as are all 506 accepted source lowerings. Final full conformance after the generic-argument call-site correction also passes all 1,791 cases, with exact corpus coverage.

Q-059 remains open for the closing public-call-path audit and source AST traversal inspection. The earlier full per-instruction collection suite is still running; no incomplete suite or unavailable Claude review is counted as a pass. Phase 6 and contract decisions remain open.

A subsequent read-only Claude review, relayed by the owner, examined the property diff against 897f538, including frontend/lower.zig. No defects were reported in the nine classifications, fixed-point preparation, cache preconditions, allocator/error lifetime or test construction. Nothing was built or run, and the expanded suite was not observed; this is code-review evidence only, not independent test confirmation or review of later source-parser work. The resultType/derivedType wording above is corrected, and query's API comment now directs repeated callers to prepare once rather than rebuilding the entire module for each nominal query.

Source type-syntax parser

At 3563560, an 82,013-byte monomorphic source file containing 16,384 nested length-one arrays aborts in typeExpr with 8,704 symbolized frames and exit -6. Depths 63, 64 and 4,096 accept. Spec 15 §15's depth-64 generic traversal guard is not a universal parser limit: specialization returns an unchanged module when there are no generic declarations or uses. Applying that guard to every parsed annotation would change existing acceptance. Only child core capture is disabled during probes; no timeout terminates them.

The source type parser now suspends array suffixes and argument lists in explicit frames, including nested static function arguments. Array lengths, argument order, wrapper classification, qualified names, cap/file paths, wrapper-arity errors and split >> positions retain their original behavior. Static function references remain argument syntax; no ordinary type synonym is added. Frame storage is released, AST argument/element storage retains the caller's arena lifetime, and host allocation errors propagate without exposing a partial AST. Spec/reference, verifier and runtime rules, diagnostics and bundles are unchanged; there is no new nesting limit, feature or semantic flag.

Unit tests inspect 32,768 mixed array/wrapper/applied-type levels with sibling arguments, 16,384 nested static function argument pairs and split-closer spans. Deep malformed input retains its leaf and wrapper-name failure positions. Failing each underlying parser arena allocation checks OutOfMemory and cleanup. All units, format checks and all 1,791 conformance cases pass, with exact corpus coverage. Hosted grammar and repair-advice suites pass 288 and 299 checks. Formatter integration passes 6,072 checks over 1,467 public files (1,412 parsed, 55 syntax errors and 782 identical AIR outputs). All 1,421 old/new source checks and 506 accepted lowerings are byte-identical; 156 additional constructor/argument/error probes retain exact outputs.

The formerly failing array input now formats successfully, producing 82,019 bytes; a second formatting pass is byte-identical. Full checking reaches a separate confirmed failure in generics.usesGenerics (20,002 symbolized frames, exit -6), without typeExpr frames. A second deep input, invalid mut slice<…>, previously aborts while speculative repair-advice parsing recurses; it now returns one E7001 at the original primary position with the exact slice_mut_type candidate. Passing parsing/formatting or this diagnostic does not establish complete checking for arbitrary source depth. Q-059 remains open for source AST traversal and closing call-path work. No fresh Claude review was available.