diff --git a/docs/design/contract-accounting-and-status.md b/docs/design/contract-accounting-and-status.md index 0cb5da0..9c3afa2 100644 --- a/docs/design/contract-accounting-and-status.md +++ b/docs/design/contract-accounting-and-status.md @@ -35,7 +35,7 @@ Pending callback/return values remain ordinary SSA values, bounded by `max_value All descriptors MUST be available before SSA inference: clause bindings name original parameters, the snapshot or result; parameter/result types come from the enclosing header, snapshot type from its helper header, and make explicitly names `checked`. Callback result types come from callback signatures. Budget calculation never dereferences an absent parameter or assumes predicate validity. Malformed bindings wait for their later stage; size and Copy/root-shape queries must be total on recursive/invalid types, with cycle detection and memoization, without invoking full type verification. Existing size accounting supplies the size-query precedent; the current recursive linearity query is not a safe pre-types substitute. An arbitrary body SSA binding is forbidden. Accounted size of checked is size(R); predicate identity contributes no runtime member. -For this budget query, seed the existing intrinsically linear kinds and propagate linearity backwards through array elements, nominal struct/enum members and checked's representation R to a least fixed point. Predicate identity contributes no edge. An invalid member cycle with no reachable linear leaf is non-linear (Copy for accounting); one reaching an owner or another linear leaf is linear. Direct borrow/root bindings remain in-place. This matches ordinary linearity on valid types and supplies a deterministic value on cycles, without accepting them. Preserve the existing accounted-size depth cutoff on invalid graphs rather than replacing a whole cyclic type's size with zero. Required candidate vectors include both kinds of cycle next to the frame limit: budget excess still reports E5101 first; otherwise the invalid cycle reaches the ordinary type rejection. These vectors are not among the fourteen executed baselines. +For this budget query, seed the existing intrinsically linear kinds and propagate linearity backwards through array elements, nominal struct/enum members and checked's representation R to a least fixed point. Predicate identity contributes no edge. An invalid member cycle with no reachable linear leaf is non-linear (Copy for accounting); one reaching an owner or another linear leaf is linear. Direct borrow/root bindings remain in-place. This matches ordinary linearity on valid types and supplies a deterministic value on cycles, without accepting them. Use the corrected nominal-edge size-depth convention ([Q-058](open-questions.md#q-058--finite-anonymous-types-truncated-by-the-size-cycle-guard)); anonymous checked representation edges preserve that depth. Keep invalid-graph queries bounded rather than replacing a whole cyclic type's size with zero. Required candidate vectors include both kinds of cycle next to the frame limit: budget excess still reports E5101 first; otherwise the invalid cycle reaches the ordinary type rejection. These vectors are not among the fourteen executed baselines. Two sequential clauses each materializing 600,000 bytes fit when L=S=0. One clause materializing both needs 1,200,000 and rejects. Snapshot 600,000 plus locals 500,000 rejects even with no temporary place. This rule does not infer lifetime reuse between arbitrary locals. diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 5ca59ba..9c269b2 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -432,3 +432,17 @@ These are specified observation limits, not new verifier bugs. A shared linear s Decide the required source/AIR observation surface. Candidate directions include a shared-view variant operation yielding borrowed payloads and an explicit shared content view through `ref>`; neither is adopted here. Any new primitive requires a registered feature, its full AIR contract, ordinary alias/loan/lifetime enforcement, deterministic behavior, format compatibility and vertical source/Quick Reference/conformance coverage. Do not enable consumption, hidden owner copies or unrestricted partial moves to make predicates expressible. 2026-10-09: [RFC 0040](../rfcs/0040-shared-enum-and-owner-views.md) Draft proposes selective `enum.view` edges and shared `own.view` for scalar and array owners, with explicit source `match ref place`. Single-ingress arm blocks create only the chosen edge's dependent views; no general borrow joins or variant proofs are assumed. A current-language probe confirms that a dormant 65-payload variant is legal, while its value match rejects E5101; selecting no payloads or one would avoid that limit in the candidate. Complete unknown `enum.view` spellings currently report E0004 alone, not E0006 for their borrowed parameters. Isolated `own.view` reports E0004; a used result adds E5001, retaining Q-055's dependent-error gate. This is not adoption, implementation or complete contract coverage. + +## Q-058 — Finite anonymous types truncated by the size cycle guard + +The checked-property audit independently reproduced three accepted modules at `03614c9` that violate spec 08 §7.1/§11.5: a 1,049,600-byte nested-array parameter, a 1,048,576-byte nested-array local plus one byte, and a 1-GiB nested-array parameter with an unrelated nominal declaration. The budget query counted anonymous wrapper edges toward a cutoff based on the number of nominal declarations, truncating finite content to zero. Claude independently identified the same defect. These are implementation failures against existing mandatory limits, not an unresolved size policy. + +**Resolved:** only nominal struct-field/enum-payload edges advance the bounded cycle-query depth; array/atomic/mutex size edges preserve it. Finite valid types therefore follow the existing checked sum/product metric regardless of unrelated declarations. Memo keys and the published runtime cache use the same nominal-depth convention; invalid cycles still terminate within V × (V + 2) nominal states. No new feature, diagnostic code, configurable limit or semantic rule is introduced. + +Compatibility impact is explicit: oversized values/frames formerly accepted now reject E5101; valid nested content previously undercharged can select allocation failure under a tight grant. A named 32-byte nested-array record is rejected by a 31-byte heap grant and accepted by a 32-byte grant. Invalid cyclic layouts with large array multiplicities can now exceed max_value_size in the budget stage and report E5101 before E1003; the cyclic-wrapper regression pins that transition with finite found = 4,294,967,297. Diagnostic collection and source-position ordering remain unchanged. AIR and source boundary/rejection cases, runtime quota cases and cached/uncached size tests cover the correction. This fix is separate from adopting or implementing RFC 0039. + +## Q-059 — AIR type-syntax nesting and native recursion + +Source inspection during Q-058 finds recursive `parseType` in `src/air/parse.zig` without an explicit syntax-nesting bound. Size/property traversals also use native recursion over finite anonymous type syntax. **Unverified:** no parser stack-exhaustion reproducer has been run; syntactic finiteness alone does not establish a bound on native stack use. + +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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index 25ba878..389a2f8 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -355,3 +355,5 @@ The [accounting/status candidate](../design/contract-accounting-and-status.md) p The [proof/report refinement](../design/contract-proof-and-report.md) closes the candidate's opcode/node cost conventions and function/value row grammar, with deterministic fallback precedence and source metadata distinguished from AIR-derived truth. Fifteen research vectors and a finite independent truth oracle confirm their stated costs/results; five current-language CLI probes confirm canonical report equivalence, run independence, eligible scalar/view operations and the limit-vector structure (runs use fuel 10,000). A report component vector pins field order and site totals across four statuses. Claude independently checked the cost derivations, status/field ordering and feasibility; review corrected a target-width assumption and clarified unreachable origins and assumed-call accounting. These are design evidence, not implemented contract conformance. Module-claim metadata, source clause elaboration, diagnostic collection, owner adoption and full vertical delivery remain open; RFC 0039 stays Draft and P6-6 remains doing. The [module/source candidate](../design/contract-source-and-module-state.md) develops persistent caller-owned module state without globals or visibility, separate boundary-only relations, narrow checked-type bindings, explicit operations and clause elaboration. Claude's review identified namespace hijacking and old/capture ambiguities; the reserved type.checked prefix preserves accepted checked modules/types, and eager old/document matching is explicit. Nineteen current-language baselines verify names/static applications, namespace collisions and reserved bindings, complete source rejections, Copy/linear/checked witness shapes and flat/tree record packing (runs use fuel 10,000). These constrain the proposal and do not implement contracts. Rooted-state owner selection, checked properties/ABI/positions, mangling/inventory schema, source/diagnostic/dispatch integration and vertical validation remain gates; RFC 0039 stays Draft and full P6-6 remains doing. + +The property/type-position audit exposed a pre-existing accounted-size defect ([Q-058](../design/open-questions.md#q-058--finite-anonymous-types-truncated-by-the-size-cycle-guard)): anonymous array/atomic/mutex edges incorrectly consumed a nominal-cycle depth budget. Corrected finite type sizes now enforce existing value/frame and allocation quotas. AIR/source boundary and rejection fixtures, a named-record heap quota pair and cached/uncached/cyclic unit checks cover the fix; a separate unverified native-recursion concern is recorded as Q-059. This correction adds no contract syntax, feature or adoption decision; checked properties and the remaining full P6-6 gates stay open. diff --git a/src/verifier/budget.zig b/src/verifier/budget.zig index 355184b..a99ce66 100644 --- a/src/verifier/budget.zig +++ b/src/verifier/budget.zig @@ -34,8 +34,8 @@ pub const SizeMemo = struct { values: air_module.SizeCache = .{}, evaluations: usize = 0, - // Preserve the legacy depth cutoff exactly: at most V * (V + 2) - // nominal/depth states, rather than exponentially many shared paths. + // Count nominal member edges, not finite anonymous wrappers: at most + // V * (V + 2) nominal/depth states, rather than shared-path expansion. pub fn size(cache: *SizeMemo, m: air.Module, t: air.Type, depth: usize) std.mem.Allocator.Error!?u64 { return sizeQuery(m, t, depth, cache); @@ -43,6 +43,8 @@ pub const SizeMemo = struct { }; 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) { @@ -64,13 +66,13 @@ fn sizeValue(m: air.Module, t: air.Type, depth: usize, memo: ?*SizeMemo) std.mem .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 + 1, memo)), - .mutex => |inner| std.math.add(u64, 8, (try sizeQuery(m, inner.*, depth + 1, memo)) orelse return null) catch null, + .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, .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 + 1, memo)) orelse return null) catch null, + .array => |a| std.math.mul(u64, a.len, (try sizeQuery(m, a.elem, depth, memo)) orelse return null) catch null, .named => |i| switch (m.types[i].kind) { .@"struct" => |fs| blk: { var sum: u64 = 0; @@ -222,7 +224,7 @@ test "accounted sizes memoize shared diamonds and cyclic depth states" { m.accounted_sizes = &memo.values; for (0..65) |i| try std.testing.expectEqual(@as(?u64, 0), accountedSize(m, .{ .named = @intCast(i) }, 0)); try std.testing.expectEqual(before, memo.evaluations); - // A cyclic, branching size query keeps the legacy depth cutoff exactly. + // A cyclic, branching size query keeps the nominal depth guard bounded. ds[64].kind = .{ .@"struct" = try a.dupe(air_module.Field, &.{ .{ .name = "a", .ty = .{ .named = 0 } }, .{ .name = "b", .ty = .{ .named = 0 } } }) }; m.accounted_sizes = null; var cyclic: SizeMemo = .{ .arena = a }; @@ -262,3 +264,37 @@ test "accounted sizes" { try std.testing.expectEqual(@as(u64, 1), tagSize(256)); try std.testing.expectEqual(@as(u64, 2), tagSize(257)); } + +test "anonymous wrapper sizes do not depend on nominal declaration count" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const leaf: air.Type = .{ .int = .u64 }; + const row: air.Type.Array = .{ .elem = leaf, .len = 2 }; + const rows: air.Type.Array = .{ .elem = .{ .array = &row }, .len = 2 }; + const matrix: air.Type = .{ .array = &rows }; + const cell: air.Type = .{ .atomic = &leaf }; + const cells: air.Type.Array = .{ .elem = cell, .len = 4 }; + const wrapped: air.Type = .{ .mutex = &matrix }; + const ds = try a.alloc(air.TypeDecl, 4); + for (ds) |*d| d.* = .{ .name = "Unused", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }; + for (0..5) |n| { + const m: air.Module = .{ .name = "t", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds[0..n], .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + for ([_]air.Type{ matrix, .{ .array = &cells }, wrapped }, [_]u64{ 32, 32, 40 }) |t, want| { + try std.testing.expectEqual(@as(?u64, want), accountedSize(m, t, 0)); + try std.testing.expectEqual(@as(?u64, want), try memo.size(m, t, 0)); + } + } +} + +test "cyclic nominal layouts through anonymous wrappers stay bounded" { + var scratch = std.heap.ArenaAllocator.init(std.testing.allocator); + defer scratch.deinit(); + const a = scratch.allocator(); + const row: air.Type.Array = .{ .elem = .{ .named = 0 }, .len = 2 }; + const m: air.Module = .{ .name = "t", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{.{ .name = "Cycle", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{.{ .name = "children", .ty = .{ .array = &row } }} } }}, .functions = &.{} }; + var memo: SizeMemo = .{ .arena = a }; + 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)); +} diff --git a/tests/conformance/phase1/accept/nested_size_boundary.air b/tests/conformance/phase1/accept/nested_size_boundary.air new file mode 100644 index 0000000..b928ee3 --- /dev/null +++ b/tests/conformance/phase1/accept/nested_size_boundary.air @@ -0,0 +1,13 @@ +; Anonymous nested arrays account exactly one MiB. +; expect: accept +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, ownership] + +fn @f(%x: array, 1024>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase1/reject/nested_size_cycle_overflow.air b/tests/conformance/phase1/reject/nested_size_cycle_overflow.air new file mode 100644 index 0000000..4712cfa --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_cycle_overflow.air @@ -0,0 +1,13 @@ +; Budget arithmetic on an invalid cycle stays bounded and reports excess value size first. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md §7.1; docs/spec/07-air.md §8.6 +module test.nested_size_cycle +air 0 +lang 0.1 +features [arrays, ownership] +type @A = struct { n: u8, x: array<@A, 4294967296> } +fn @f() -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase1/reject/nested_size_frame.air b/tests/conformance/phase1/reject/nested_size_frame.air new file mode 100644 index 0000000..497ca8a --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_frame.air @@ -0,0 +1,15 @@ +; Each local fits; one extra byte exceeds the frame limit. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, ownership] + +fn @f() -> void +effects [] +entry: + %a = local.alloc array, 1024> + %b = local.alloc u8 + ret diff --git a/tests/conformance/phase1/reject/nested_size_gib.air b/tests/conformance/phase1/reject/nested_size_gib.air new file mode 100644 index 0000000..1846cec --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_gib.air @@ -0,0 +1,14 @@ +; An unrelated nominal declaration cannot hide a one-GiB anonymous value. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, ownership] + +type @Unused = struct { n: u8 } +fn @f(%x: array, 1024>, 1024>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase1/reject/nested_size_mutex.air b/tests/conformance/phase1/reject/nested_size_mutex.air new file mode 100644 index 0000000..4b513b0 --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_mutex.air @@ -0,0 +1,13 @@ +; Mutex accounting includes its array content even without nominal declarations. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, cancellation, capabilities, effects, ownership, resources, sync, tasks] + +fn @f(%x: mutex>) -> mutex> +effects [] +entry: + ret %x diff --git a/tests/conformance/phase1/reject/nested_size_overflow.air b/tests/conformance/phase1/reject/nested_size_overflow.air new file mode 100644 index 0000000..8f3a59b --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_overflow.air @@ -0,0 +1,13 @@ +; Anonymous nested-array size overflows checked u64 arithmetic. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, ownership] + +fn @f(%x: array, 4294967296>, 1>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase1/reject/nested_size_value.air b/tests/conformance/phase1/reject/nested_size_value.air new file mode 100644 index 0000000..fd454f7 --- /dev/null +++ b/tests/conformance/phase1/reject/nested_size_value.air @@ -0,0 +1,13 @@ +; Finite anonymous nesting must not truncate an oversized value. +; expect: reject E5101 +; phase: 1 +; spec: docs/spec/08-verifier.md +module test.nested_size +air 0 +lang 0.1 +features [arrays, ownership] + +fn @f(%x: array, 1025>) -> void +effects [] +entry: + ret diff --git a/tests/conformance/phase2/run/nested_size_heap_31.air b/tests/conformance/phase2/run/nested_size_heap_31.air new file mode 100644 index 0000000..7aed099 --- /dev/null +++ b/tests/conformance/phase2/run/nested_size_heap_31.air @@ -0,0 +1,29 @@ +; The nested array requires exactly 32 accounted bytes. +; expect: run +; result: 0 +; grant: heap=mem.alloc:31 +; fuel: 100 +; phase: 2 +; spec: docs/spec/03-memory-model.md §19; docs/spec/08-verifier.md §7.1 +module test.nested_heap_size +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, ownership, resources] + +type @Record = struct { data: array, 2> } + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %v = const.u64 7 + %inner = array.splat array %v + %outer = array.splat array, 2> %inner + %record = struct.make @Record(%outer) + own.new %record, %heap, ok -> @ok, err -> @err +ok(%owned: own<@Record>): + own.free %owned + %yes = const.u64 1 + ret %yes +err(%e: alloc_error): + %no = const.u64 0 + ret %no diff --git a/tests/conformance/phase2/run/nested_size_heap_32.air b/tests/conformance/phase2/run/nested_size_heap_32.air new file mode 100644 index 0000000..8092955 --- /dev/null +++ b/tests/conformance/phase2/run/nested_size_heap_32.air @@ -0,0 +1,29 @@ +; The nested array requires exactly 32 accounted bytes. +; expect: run +; result: 1 +; grant: heap=mem.alloc:32 +; fuel: 100 +; phase: 2 +; spec: docs/spec/03-memory-model.md §19; docs/spec/08-verifier.md §7.1 +module test.nested_heap_size +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, ownership, resources] + +type @Record = struct { data: array, 2> } + +fn @main(%heap: cap) -> u64 +effects [mem.alloc] +entry: + %v = const.u64 7 + %inner = array.splat array %v + %outer = array.splat array, 2> %inner + %record = struct.make @Record(%outer) + own.new %record, %heap, ok -> @ok, err -> @err +ok(%owned: own<@Record>): + own.free %owned + %yes = const.u64 1 + ret %yes +err(%e: alloc_error): + %no = const.u64 0 + ret %no diff --git a/tests/conformance/source/size_limits/nested_size_1024.aji b/tests/conformance/source/size_limits/nested_size_1024.aji new file mode 100644 index 0000000..b144144 --- /dev/null +++ b/tests/conformance/source/size_limits/nested_size_1024.aji @@ -0,0 +1,7 @@ +// Anonymous nested arrays retain exact value-size accounting. +// expect: accept +// phase: 6 +// spec: docs/spec/08-verifier.md §7.1; docs/spec/15-source-language.md §10 +module nested_size +fn unused(data: [[u8; 1024]; 1024]) -> void effects [] {} +fn main() -> void effects [] {} diff --git a/tests/conformance/source/size_limits/nested_size_1025.aji b/tests/conformance/source/size_limits/nested_size_1025.aji new file mode 100644 index 0000000..b6012a8 --- /dev/null +++ b/tests/conformance/source/size_limits/nested_size_1025.aji @@ -0,0 +1,7 @@ +// Anonymous nested arrays retain exact value-size accounting. +// expect: reject E5101 +// phase: 6 +// spec: docs/spec/08-verifier.md §7.1; docs/spec/15-source-language.md §10 +module nested_size +fn unused(data: [[u8; 1024]; 1025]) -> void effects [] {} +fn main() -> void effects [] {} diff --git a/tests/hosted/source_nominal_queries.py b/tests/hosted/source_nominal_queries.py index 7d3ceed..6b61e32 100644 --- a/tests/hosted/source_nominal_queries.py +++ b/tests/hosted/source_nominal_queries.py @@ -33,7 +33,7 @@ with tempfile.TemporaryDirectory(prefix='aji-nominal-queries-') as directory: records = [json.loads(line) for line in diagnostics.splitlines()] assert all(d['file'] == str(source) for d in records), records if source.stem == 'cycle': - assert (records[0]['code'], records[0]['type'], records[0]['line']) == ('E1003', 'N0', 5) + assert (records[0]['code'], records[0]['type'], records[0]['line']) == ('E1003', 'N0', 6) elif source.stem == 'constraint_depth': assert records[0]['reason'] == 'implementation_limit' elif source.stem == 'diamond_21_u64':