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

14 KiB

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.