From 3906ce5a9be211dcf52f77696b8bd45087e0e34f Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Fri, 9 Oct 2026 19:28:03 +0300 Subject: [PATCH] verifier: evaluate type sizes with explicit continuations --- docs/design/air-type-depth-audit.md | 12 + docs/design/open-questions.md | 2 + docs/plan/phase-6-source-language.md | 2 + src/air/module.zig | 7 +- src/verifier.zig | 6 + src/verifier/budget.zig | 331 +++++++++++++++--- .../phase1/accept/zero_size_array_chain.air | 13 + .../phase1/reject/overflowing_array_chain.air | 12 + tests/conformance/reject-twins.json | 6 + .../size_limits/overflowing_array_chain.aji | 8 + .../size_limits/zero_size_array_chain.aji | 8 + 11 files changed, 353 insertions(+), 54 deletions(-) create mode 100644 tests/conformance/phase1/accept/zero_size_array_chain.air create mode 100644 tests/conformance/phase1/reject/overflowing_array_chain.air create mode 100644 tests/conformance/source/size_limits/overflowing_array_chain.aji create mode 100644 tests/conformance/source/size_limits/zero_size_array_chain.aji diff --git a/docs/design/air-type-depth-audit.md b/docs/design/air-type-depth-audit.md index 8eba278..241094b 100644 --- a/docs/design/air-type-depth-audit.md +++ b/docs/design/air-type-depth-audit.md @@ -36,3 +36,15 @@ Compound syntax is a unary chain. The parser now stores pending constructors and 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. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 1c0510e..f3f8d30 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -460,3 +460,5 @@ Source inspection during Q-058 finds recursive `parseType` in `src/air/parse.zig 2026-10-09 [executed audit](air-type-depth-audit.md): a 36,971-byte input with 4,096 length-one nested arrays aborts with a traceback containing thousands of parseType/parseCompoundType frames, rather than a diagnostic. The iterative parser repair accepts that input and unit-tests 32,768 levels, preserving old/new output on 364 public AIR files and constructor/error probes. A subsequent 16,384-depth check still aborts in verifier sizeQuery/sizeValue; that remaining failure is now verified. The original unverified note describes the state before these probes. No syntax-depth acceptance limit is introduced; Q-059 remains open for size, property, validity, equality and formatting traversal audits. Audit parser and subsequent type traversals before claiming bounded processing for arbitrary AIR type syntax. Iterative traversal could preserve accepted syntax; imposing a new acceptance limit instead needs normative spec 08 resource rules and fixed diagnostic facts. Q-058 does not add such a limit or claim to resolve this separate issue. + +The [size-query increment](air-type-depth-audit.md#size-query-repair) removes recursive verifier sizing and inner-budget visiting, preserves nominal-depth/overflow/zero semantics, and adds immutable anonymous-node cache entries. Unit queries handle 32,768 anonymous and nominal levels; AIR/source zero/overflow fixtures and exact old/new output comparisons constrain compatibility. A repeated 16,384-depth CLI probe now aborts in verifier wellFormed, confirming the next native-recursion failure. Uncached nominal fallback, validity, properties, equality and formatting are still open; Q-059 is not resolved and no new input acceptance limit is introduced. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 60c4b63..6fa3696 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -341,6 +341,8 @@ The final size row is now explicitly classified as `source_early`, retaining its The [Q-059 type-depth audit](../design/air-type-depth-audit.md) confirms a parser native-stack failure on a 37-KB, 4,096-depth AIR parameter type. Pending anonymous constructors now use an explicit arena-backed stack, preserving grammar, feature/member-gate order and diagnostic positions. Unit tests parse 32,768 levels and check deep unknown/malformed leaves; all unit/format checks and 1,765/1,765 conformance cases pass, and 364 public AIR checks preserve exact old/new outputs. The old crashing input now accepts. A 16,384-depth check still fails in the verifier's recursive size evaluation, so Q-059 remains open. No normative/bundle/feature/code change or new acceptance limit; no fresh Claude review was available. +The [Q-059 size-query increment](../design/air-type-depth-audit.md#size-query-repair) gives verifier sizing explicit continuations, iterates inner-budget visits and caches anonymous wrapper identities without changing size arithmetic or nominal cycle depth. Unit cases cover 32,768 anonymous/nominal levels, zero leaves, overflow/null caching, constructor identity and forged-cache rebuilding. The existing full 1,765-case snapshot, four new AIR/source zero/overflow fixtures and sixteen focused GC/quota cases pass; together the full/focused runs cover all 1,769 current conformance cases. Unit/format checks and test-extended pass, and 364 pre-existing AIR checks preserve exact old/new output. The new rejection twin brings P6-7 to 97/206, with zero pending, 45 source-error analogues, one source-early analogue and 63 AIR-only cases. A 16,384-depth probe now reaches the next failure in wellFormed; Q-059 and the phase stay open. No normative/bundle/feature or diagnostic code change, and no new syntax-depth limit; no fresh Claude review was available. + Spec 15's initial Phase 6A limits now point to its existing extensions. Its introductory diagnostic rule follows §10 and construct-specific codes; widening reports source E7005 while AIR retains E1002, including the corrected Quick Reference entry. Multi-result bindings include complete unpacking, byte escapes agree with the later exact list, and grammar comments locate graph access in §8. Old incremental limits link buffers/borrow returns to §17/§19. No grammar production, semantic rule or implementation changes. Six existing public fixtures confirm the reported code and deterministic successful AIR; Claude independently audited the corrections. The reference bundle rebuilds; source growth is +50/+47/+58 tokens across the three tokenizers, with unchanged Quick Reference token counts, AIR and std (docs/agent/README.md). P6-1/P6-5 remain open for their unimplemented surfaces. ## P6-6 contract spec gate (2026-10-09) diff --git a/src/air/module.zig b/src/air/module.zig index 2f203ae..c56d5b4 100644 --- a/src/air/module.zig +++ b/src/air/module.zig @@ -491,7 +491,12 @@ pub const NominalProperties = packed struct(u32) { padding: u10 = 0, }; -pub const SizeKey = struct { index: u32, depth: usize }; +pub const SizeKey = struct { + index: u32 = 0, + depth: usize, + kind: enum { named, array, atomic, mutex } = .named, + address: usize = 0, +}; pub const SizeCache = std.AutoHashMapUnmanaged(SizeKey, ?u64); pub const Module = struct { diff --git a/src/verifier.zig b/src/verifier.zig index 0f76578..4e49db4 100644 --- a/src/verifier.zig +++ b/src/verifier.zig @@ -157,4 +157,10 @@ test "verification rebuilds caller-supplied property and size caches" { large.accounted_sizes = &sizes; const rejected = try verifyModule(a, "t.air", large); try std.testing.expectEqualStrings("E5101", rejected.diagnostics[0].code.id); + var anonymous = (try air.parse.parse(a, "t.air", test_header ++ "fn @f(%x: array) -> void\neffects []\nentry:\n ret\n")).module.?; + const array = anonymous.functions[0].params[0].ty.array; + try sizes.put(a, .{ .depth = 0, .kind = .array, .address = @intFromPtr(array) }, 0); + anonymous.accounted_sizes = &sizes; + const anonymous_rejected = try verifyModule(a, "t.air", anonymous); + try std.testing.expectEqualStrings("E5101", anonymous_rejected.diagnostics[0].code.id); } diff --git a/src/verifier/budget.zig b/src/verifier/budget.zig index a99ce66..acb7fc6 100644 --- a/src/verifier/budget.zig +++ b/src/verifier/budget.zig @@ -21,75 +21,208 @@ pub const Limits = struct { }; /// Accounted size in bytes (spec 08 §7.1): a platform-independent metric, -/// not a layout. Null if the computation overflows. Recursive aggregates are -/// reported later (E1003) and count as 0 here; `void`, `never` and storage +/// not a layout. Null if the computation overflows. The nominal depth guard +/// cuts invalid cycles at zero; earlier fields retain their contribution. +/// Finite-layout validation reports E1003 later. `void`, `never` and storage /// types are not materializable and count as 0. pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 { - // Read-only cache lookup never allocates; the uncached path remains an oracle. - return sizeQuery(m, t, depth, null) catch unreachable; + if (depth > m.types.len + 1) return 0; + // Compose unary wrappers as a saturated affine map. A saturated factor + // times a zero-sized leaf is still zero; do not call it an overflow. + var current = t; + var factor: ?u64 = 1; + var offset: ?u64 = 0; + var fixed: ?u64 = null; + var base: ?u64 = undefined; + while (true) { + if (sizeKey(current, depth)) |key| if (m.accounted_sizes) |cache| { + if (cache.get(key)) |value| { + base = value; + break; + } + }; + switch (current) { + .array => |a| { + if (a.len == 0) { + // Even an invalid outer zero length cannot mask an + // overflowing inner query. Check each reset segment. + const value = offset orelse return null; + if (fixed == null) fixed = value; + factor = 1; + offset = 0; + } else factor = if (factor) |f| std.math.mul(u64, f, a.len) catch null else null; + current = a.elem; + }, + .atomic => |inner| current = inner.*, + .mutex => |inner| { + const add = if (factor) |f| std.math.mul(u64, f, 8) catch null else null; + offset = if (offset != null and add != null) std.math.add(u64, offset.?, add.?) catch null else null; + current = inner.*; + }, + else => { + base = uncachedBaseSize(m, current, depth); + break; + }, + } + } + const value = base orelse return null; + const product = if (value == 0) 0 else std.math.mul(u64, factor orelse return null, value) catch return null; + const result = std.math.add(u64, product, offset orelse return null) catch return null; + return fixed orelse result; } +fn sizeKey(t: air.Type, depth: usize) ?air_module.SizeKey { + return switch (t) { + .named => |i| .{ .index = i, .depth = depth }, + .array => |a| .{ .depth = depth, .kind = .array, .address = @intFromPtr(a) }, + .atomic => |a| .{ .depth = depth, .kind = .atomic, .address = @intFromPtr(a) }, + .mutex => |a| .{ .depth = depth, .kind = .mutex, .address = @intFromPtr(a) }, + else => null, + }; +} + +const SizeFrame = struct { + ty: air.Type, + depth: usize, + next: usize = 0, + variant: usize = 0, + sum: u64 = 0, + maximum: u64 = 0, + + fn child(f: *SizeFrame, m: air.Module) ?air.Type { + return switch (m.types[f.ty.named].kind) { + .@"struct" => |fs| if (f.next < fs.len) fs[f.next].ty else null, + .@"enum" => |vs| blk: { + while (f.variant < vs.len) { + if (f.next < vs[f.variant].payload.len) break :blk vs[f.variant].payload[f.next]; + f.maximum = @max(f.maximum, f.sum); + f.variant += 1; + f.next = 0; + f.sum = 0; + } + break :blk null; + }, + }; + } + + fn total(f: SizeFrame, m: air.Module) ?u64 { + return switch (m.types[f.ty.named].kind) { + .@"struct" => f.sum, + .@"enum" => |vs| std.math.add(u64, tagSize(vs.len), f.maximum) catch null, + }; + } +}; + pub const SizeMemo = struct { arena: std.mem.Allocator, values: air_module.SizeCache = .{}, evaluations: usize = 0, + pending: std.ArrayList(SizeFrame) = .empty, - // Count nominal member edges, not finite anonymous wrappers: at most - // V * (V + 2) nominal/depth states, rather than shared-path expansion. - + // Nominal member edges alone advance the cycle guard. Anonymous cache + // identities also keep repeated inner-budget/runtime queries linear. pub fn size(cache: *SizeMemo, m: air.Module, t: air.Type, depth: usize) std.mem.Allocator.Error!?u64 { - return sizeQuery(m, t, depth, cache); + cache.pending.clearRetainingCapacity(); + defer cache.pending.clearRetainingCapacity(); + var current = t; + var current_depth = depth; + var result: ?u64 = undefined; + descend: while (true) { + if (current_depth > m.types.len + 1) { + result = 0; + } else if (sizeKey(current, current_depth)) |key| { + if (cache.values.get(key)) |value| { + result = value; + } else { + if (current == .named) cache.evaluations += 1; + try cache.pending.append(cache.arena, .{ .ty = current, .depth = current_depth }); + switch (current) { + .array => |a| { + current = a.elem; + continue :descend; + }, + .atomic, .mutex => |inner| { + current = inner.*; + continue :descend; + }, + .named => { + const frame = &cache.pending.items[cache.pending.items.len - 1]; + if (frame.child(m)) |child| { + current = child; + current_depth += 1; + continue :descend; + } + result = frame.total(m); + _ = cache.pending.pop(); + try cache.values.put(cache.arena, key, result); + }, + else => unreachable, + } + } + } else result = scalarSize(current); + while (cache.pending.items.len != 0) { + const frame = &cache.pending.items[cache.pending.items.len - 1]; + switch (frame.ty) { + .array => |a| result = if (result) |value| std.math.mul(u64, a.len, value) catch null else null, + .atomic => {}, + .mutex => result = if (result) |value| std.math.add(u64, 8, value) catch null else null, + .named => { + const sum = if (result) |value| std.math.add(u64, frame.sum, value) catch null else null; + if (sum) |value| { + frame.sum = value; + frame.next += 1; + if (frame.child(m)) |child| { + current = child; + current_depth = frame.depth + 1; + continue :descend; + } + result = frame.total(m); + } else result = null; + }, + else => unreachable, + } + const completed = cache.pending.pop().?; + try cache.values.put(cache.arena, sizeKey(completed.ty, completed.depth).?, result); + } + return result; + } } }; -fn sizeQuery(m: air.Module, t: air.Type, depth: usize, memo: ?*SizeMemo) std.mem.Allocator.Error!?u64 { - // Only nominal members advance this cycle guard. Array/atomic/mutex - // nesting is finite syntax and must never truncate a valid value's size. - if (depth > m.types.len + 1) return 0; - const key: air_module.SizeKey = .{ .index = if (t == .named) t.named else 0, .depth = depth }; - if (t == .named) { - if (memo) |cache| { - if (cache.values.get(key)) |value| return value; - cache.evaluations += 1; - } else if (m.accounted_sizes) |cache| { - if (cache.get(key)) |value| return value; - } - } - const result = try sizeValue(m, t, depth, memo); - if (t == .named) if (memo) |cache| try cache.values.put(cache.arena, key, result); - return result; -} - -fn sizeValue(m: air.Module, t: air.Type, depth: usize, memo: ?*SizeMemo) std.mem.Allocator.Error!?u64 { +fn scalarSize(t: air.Type) u64 { return switch (t) { .int => |it| it.bits() / 8, .bool => 1, .ref, .mut, .cap, .resource, .own, .region, .scope, .task, .shield, .sender, .receiver, .guard, .island, .frozen, .arc => 8, - .iref => 16, - .atomic => |inner| (try sizeQuery(m, inner.*, depth, memo)), - .mutex => |inner| std.math.add(u64, 8, (try sizeQuery(m, inner.*, depth, memo)) orelse return null) catch null, - .own_array => 16, + .iref, .own_array, .slice, .slice_mut => 16, .buffer => 24, - .slice, .slice_mut => 16, .builtin => |b| tagSize(b.variants().len), - .array => |a| std.math.mul(u64, a.len, (try sizeQuery(m, a.elem, depth, memo)) orelse return null) catch null, + .void, .never, .local => 0, + .array, .atomic, .mutex, .named => unreachable, + }; +} + +// The allocation-free fallback remains an independent arithmetic oracle. +// Only nominal members recurse; anonymous syntax is folded by accountedSize. +fn uncachedBaseSize(m: air.Module, t: air.Type, depth: usize) ?u64 { + return switch (t) { .named => |i| switch (m.types[i].kind) { .@"struct" => |fs| blk: { var sum: u64 = 0; - for (fs) |f| sum = std.math.add(u64, sum, (try sizeQuery(m, f.ty, depth + 1, memo)) orelse return null) catch return null; + for (fs) |f| sum = std.math.add(u64, sum, accountedSize(m, f.ty, depth + 1) orelse return null) catch return null; break :blk sum; }, .@"enum" => |vs| blk: { - var max: u64 = 0; + var maximum: u64 = 0; for (vs) |v| { var sum: u64 = 0; - for (v.payload) |p| sum = std.math.add(u64, sum, (try sizeQuery(m, p, depth + 1, memo)) orelse return null) catch return null; - max = @max(max, sum); + for (v.payload) |p| sum = std.math.add(u64, sum, accountedSize(m, p, depth + 1) orelse return null) catch return null; + maximum = @max(maximum, sum); } - break :blk std.math.add(u64, tagSize(vs.len), max) catch null; + break :blk std.math.add(u64, tagSize(vs.len), maximum) catch null; }, }, - .void, .never, .local => 0, + else => scalarSize(t), }; } @@ -163,23 +296,26 @@ const ValueSizes = struct { memo: *SizeMemo, reported: std.StringHashMapUnmanaged(void) = .empty, - fn visit(v: *ValueSizes, span: air.Span, t: air.Type) !void { + fn visit(v: *ValueSizes, span: air.Span, first: air.Type) !void { const m = v.c.module; - if (t != .local and t != .void and t != .never) { - const size = try v.memo.size(m, t, 0); - if (size == null or size.? > Limits.value_size) { - const name = try v.c.typeName(t); - const gop = try v.reported.getOrPut(v.c.arena, name); - if (!gop.found_existing) try v.c.report("E5101", span, "value type exceeds max_value_size", &.{ - .{ .name = "limit", .value = .{ .str = "value size bytes" } }, - .{ .name = "max", .value = .{ .int = Limits.value_size } }, - .{ .name = "type", .value = .{ .str = name } }, - if (size) |n| .{ .name = "found", .value = .{ .int = std.math.cast(i64, n) orelse std.math.maxInt(i64) } } else .{ .name = "found", .value = .{ .str = "overflow" } }, - }); - return; // inner types of an oversized type are not reported again + var t = first; + while (true) { + if (t != .local and t != .void and t != .never) { + const size = try v.memo.size(m, t, 0); + if (size == null or size.? > Limits.value_size) { + const name = try v.c.typeName(t); + const gop = try v.reported.getOrPut(v.c.arena, name); + if (!gop.found_existing) try v.c.report("E5101", span, "value type exceeds max_value_size", &.{ + .{ .name = "limit", .value = .{ .str = "value size bytes" } }, + .{ .name = "max", .value = .{ .int = Limits.value_size } }, + .{ .name = "type", .value = .{ .str = name } }, + if (size) |n| .{ .name = "found", .value = .{ .int = std.math.cast(i64, n) orelse std.math.maxInt(i64) } } else .{ .name = "found", .value = .{ .str = "overflow" } }, + }); + return; // inner types of an oversized type are not reported again + } } + t = t.inner() orelse return; } - if (t.inner()) |inner| try v.visit(span, inner); } }; @@ -298,3 +434,92 @@ test "cyclic nominal layouts through anonymous wrappers stay bounded" { try std.testing.expectEqual(@as(?u64, 0), try memo.size(m, .{ .named = 0 }, 0)); try std.testing.expect(memo.evaluations <= m.types.len * (m.types.len + 2)); } + +test "deep anonymous sizes use bounded native stack and cached inner queries" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const depth = 32_768; + const rows = try a.alloc(air.Type.Array, depth); + var t: air.Type = .{ .int = .u8 }; + for (rows) |*row| { + row.* = .{ .elem = t, .len = 1 }; + t = .{ .array = row }; + } + var m: air.Module = .{ .name = "deep", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, 1), try memo.size(m, t, 0)); + try std.testing.expectEqual(@as(usize, depth), memo.values.count()); + try std.testing.expectEqual(@as(?u64, 1), accountedSize(m, t, 0)); + m.accounted_sizes = &memo.values; + for (rows) |*row| try std.testing.expectEqual(@as(?u64, 1), accountedSize(m, .{ .array = row }, 0)); +} + +test "size overflow preserves zero leaves and does not hide behind outer zero" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const rows = try a.alloc(air.Type.Array, 64); + var t: air.Type = .{ .named = 0 }; + for (rows) |*row| { + row.* = .{ .elem = t, .len = 4_294_967_296 }; + t = .{ .array = row }; + } + const m: air.Module = .{ .name = "zero", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{.{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }}, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, 0), try memo.size(m, t, 0)); + try std.testing.expectEqual(@as(?u64, 0), accountedSize(m, t, 0)); + rows[0].elem = .{ .int = .u64 }; + rows[63].len = 0; // Invalid syntax still cannot mask an inner overflow. + var overflow: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, null), try overflow.size(m, t, 0)); + try std.testing.expectEqual(@as(?u64, null), accountedSize(m, t, 0)); +} + +test "deep nominal size queries use explicit continuations" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const count = 32_768; + const ds = try a.alloc(air.TypeDecl, count); + for (ds, 0..) |*d, i| d.* = .{ .name = "N", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = try a.dupe(air_module.Field, &.{.{ .name = "x", .ty = if (i + 1 == count) .{ .int = .u8 } else .{ .named = @intCast(i + 1) } }}) } }; + const m: air.Module = .{ .name = "chain", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, 1), try memo.size(m, .{ .named = 0 }, 0)); + try std.testing.expectEqual(@as(usize, count), memo.evaluations); +} + +test "overflowing nominal continuations cache null without revisiting children" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const row: air.Type.Array = .{ .elem = .{ .int = .u64 }, .len = std.math.maxInt(u64) }; + const ds = [_]air.TypeDecl{ + .{ .name = "Outer", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"enum" = &.{.{ .name = "Value", .payload = &.{.{ .named = 1 }} }} } }, + .{ .name = "Inner", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "x", .ty = .{ .array = &row } }} } }, + }; + const m: air.Module = .{ .name = "overflow", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &ds, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, null), try memo.size(m, .{ .named = 0 }, 0)); + try std.testing.expect(memo.values.contains(.{ .index = 0, .depth = 0 })); + try std.testing.expect(memo.values.contains(.{ .index = 1, .depth = 1 })); + const before = memo.evaluations; + try std.testing.expectEqual(@as(?u64, null), try memo.size(m, .{ .named = 0 }, 0)); + try std.testing.expectEqual(before, memo.evaluations); +} + +test "anonymous cache identities distinguish shared atomic and mutex content" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const leaf: air.Type = .{ .int = .u64 }; + const atom: air.Type = .{ .atomic = &leaf }; + const lock: air.Type = .{ .mutex = &leaf }; + var m: air.Module = .{ .name = "cache", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + try std.testing.expectEqual(@as(?u64, 8), try memo.size(m, atom, 0)); + try std.testing.expectEqual(@as(?u64, 16), try memo.size(m, lock, 0)); + m.accounted_sizes = &memo.values; + try std.testing.expectEqual(@as(?u64, 8), accountedSize(m, atom, 0)); + try std.testing.expectEqual(@as(?u64, 16), accountedSize(m, lock, 0)); +} diff --git a/tests/conformance/phase1/accept/zero_size_array_chain.air b/tests/conformance/phase1/accept/zero_size_array_chain.air new file mode 100644 index 0000000..0b1e798 --- /dev/null +++ b/tests/conformance/phase1/accept/zero_size_array_chain.air @@ -0,0 +1,13 @@ +; Saturated size factors must preserve zero leaves and real overflow. +; expect: accept +; phase: 1 +; spec: docs/spec/08-verifier.md §7.1 +module test.zero_size_array_chain +air 0 +lang 0.1 +features [arrays, ownership] +type @Empty = struct {} +fn @f(%x: array,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase1/reject/overflowing_array_chain.air b/tests/conformance/phase1/reject/overflowing_array_chain.air new file mode 100644 index 0000000..163ea89 --- /dev/null +++ b/tests/conformance/phase1/reject/overflowing_array_chain.air @@ -0,0 +1,12 @@ +; Saturated size factors must preserve zero leaves and real overflow. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md §7.1 +module test.overflowing_array_chain +air 0 +lang 0.1 +features [arrays, ownership] +fn @f(%x: array,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>,4294967296>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/reject-twins.json b/tests/conformance/reject-twins.json index cf8c216..80b8754 100644 --- a/tests/conformance/reject-twins.json +++ b/tests/conformance/reject-twins.json @@ -1795,6 +1795,12 @@ "source/size_limits/nested_size_cycle.aji": "b549c862021856f209331a024ba419bf49cf3deb48989bb24c9147ae38e5fc6f" } } + }, + "phase1/reject/overflowing_array_chain.air": { + "kind": "same_code", + "site": "function", + "spec": "docs/spec/08-verifier.md \u00a77.1", + "rule": "Both parameters have 64 nested arrays of length 4294967296 and a u64 leaf, preserving E5101 value size bytes/max/type/found=overflow. No zero-sized leaf or arithmetic-factor saturation may mask the real overflow." } } } diff --git a/tests/conformance/source/size_limits/overflowing_array_chain.aji b/tests/conformance/source/size_limits/overflowing_array_chain.aji new file mode 100644 index 0000000..14a1ad5 --- /dev/null +++ b/tests/conformance/source/size_limits/overflowing_array_chain.aji @@ -0,0 +1,8 @@ +// Preserve zero-sized leaves and real overflow through many array wrappers. +// expect: reject E5101 +// phase: 6 +// spec: docs/spec/08-verifier.md §7.1; docs/spec/15-source-language.md §10 +// AIR twin: phase1/reject/overflowing_array_chain.air +module test.overflowing_array_chain +fn unused(data: [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[u64; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]) -> void effects [] {} // diagnostic here: fn unused +fn main() -> void effects [] {} diff --git a/tests/conformance/source/size_limits/zero_size_array_chain.aji b/tests/conformance/source/size_limits/zero_size_array_chain.aji new file mode 100644 index 0000000..4b7897e --- /dev/null +++ b/tests/conformance/source/size_limits/zero_size_array_chain.aji @@ -0,0 +1,8 @@ +// Preserve zero-sized leaves and real overflow through many array wrappers. +// expect: accept +// phase: 6 +// spec: docs/spec/08-verifier.md §7.1; docs/spec/15-source-language.md §10 +module test.zero_size_array_chain +struct Empty {} +fn unused(data: [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[Empty; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]; 4294967296]) -> void effects [] {} +fn main() -> void effects [] {}