interp: evaluate cache-free nominal sizes without recursion
This commit is contained in:
1 parent
c9064418bd
commit
897f538840
7 files changed
+218
-43
No files matched your search
@@ -86,3 +86,15 @@ Both verified crashing CLI inputs now finish: return equality at depth 65,536 ac
|
||||
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](runtime-value-depth-audit.md); 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.
|
||||
@@ -471,6 +471,8 @@ The [equality/printing increment](air-type-depth-audit.md#type-equality-and-prin
|
||||
|
||||
The [audit-report increment](air-type-depth-audit.md#audit-report-traversal) fixes the capability-kind collector after a verified 65,536-depth module crashes `aji report`. The collector now iterates anonymous edges and retains report contents/order. Uncached nominal/query call paths remain open; Q-059 is not resolved.
|
||||
|
||||
The [cache-free nominal size increment](air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) fixes an independently reproduced 32,768-declaration low-level query failure. Uncached queries use temporary explicit continuations, release their metadata and propagate host OutOfMemory separately from arithmetic overflow. Deep queries, 7,168 independent arithmetic comparisons, cached null/partial-cache reads and 54 cached/cache-free verified runtime outcome pairs constrain compatibility. Parsed depth-1,024/4,096 public verification/runtime programmes pass before and after; no old runtime failure at those depths is claimed. Uncached nominal property predicates and remaining public query call paths keep Q-059 open.
|
||||
|
||||
## Q-060 — Native recursion while materializing runtime values
|
||||
|
||||
The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060.
|
||||
@@ -484,3 +486,5 @@ The [sharing-preserving copy increment](runtime-value-depth-audit.md#sharing-pre
|
||||
The [runtime value-size increment](runtime-value-depth-audit.md#runtime-value-size-repair) iterates fixed-array first-element chains with constant state, preserving zero-sized leaves, checked overflow, nominal maximum payloads and the element-before-dynamic-count rule. The previously crashing 32,768-level own.new probe now returns normally with the original one-byte charge; zero authority takes the original failure edge. Deep verified fuel/collection tests, nested-quota AIR/source runs and an independent allocation-size oracle constrain compatibility. Q-060 remains open for output serialization; there is no new normative limit or trap, and Q-059's nominal-query audit remains separate.
|
||||
|
||||
The [runtime value JSON increment](runtime-value-depth-audit.md#runtime-value-json-repair) removes recursive value serialization and bypasses the outer stringify's fixed nesting table for internal payloads. Exact encoding/options, outer-container state, writer/allocation failure and deep returned-payload lifetimes are tested; the formerly failing CLI now emits a complete record in deterministic and hosted profiles. All five confirmed Q-060 failure paths have repairs, without a new limit or trap. Q-060 remains open for closing call-path checks, including the inspection-only cache-free public verification/runtime entry path and its connection to Q-059's uncached nominal queries; no verified failure on that path is claimed yet.
|
||||
|
||||
The [cache-free runtime increment](runtime-value-depth-audit.md#cache-free-runtime-size-query-path) removes the recursive accounted-size fallback available through public verification/runtime entry. All runtime size callers propagate temporary metadata OOM before authority charging, retaining quota, fuel and ownership behavior. The deep query-only failure is independently reproduced and repaired; verified library entry and cache equivalence are separately tested. Q-060 remains open for closing traversal checks and full per-step validation; no new normative limit, trap or diagnostic is introduced.
|
||||
@@ -92,3 +92,9 @@ The verified 32,768-level returned-array programme now produces the complete 65,
|
||||
Validation: all units, format checks, test-extended and the complete current set of 1,791 ordinary conformance cases pass (the prior 1,789-case full run plus the two added cases). Both added cases pass in Debug with collection before every instruction. Forty-four old/new shallow run records are byte-identical. The earlier full Debug per-step collector run ended without a completion result after 785 passing records; its missing process handle and process inventory were checked before starting a replacement full ReleaseSafe run. The replacement retains safety checks and is still in progress; neither incomplete run is counted as a full pass.
|
||||
|
||||
Q-060 remains open for a closing call-path audit. Inspection shows that the public verify wrapper returns diagnostics without replacing the caller's module with verifyModule's derived-cache result, while interp.run accepts a verified module without rebuilding those caches. Runtime nominal size queries can therefore reach the uncached fallback tracked by Q-059. Whether this yields a failure on a verified cache-free library input is unverified; the mixed codec test above is not evidence for that path. No fresh Claude review was available for this increment.
|
||||
|
||||
## Cache-free runtime size-query path
|
||||
|
||||
The [nominal size-query increment](air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) removes the recursive fallback reached by runtime size callers when a public verify caller retains its original module. A direct constructed 32,768-declaration query independently reproduces the old fallback failure and now returns one byte. Parsed, verified cache-free programmes at nominal depths 1,024 and 4,096 run successfully both before and after the repair; no old runtime failure at those depths is claimed. The distinction between query-only and fully verified inputs is retained.
|
||||
|
||||
Runtime queries now pass their host allocator and propagate temporary metadata OutOfMemory before authority charging or result publication. Temporary state is released after each query; arithmetic null, zero-sized content, maximum enum payloads and allocation failure/release rules keep their meanings. A verified quota test compares 54 cached/cache-free outcome pairs (108 runs), including exact fuel boundaries and per-instruction collection. The original verify and run APIs remain usable without derived caches. No normative, bundle, feature, code, trap or accepted-depth change is introduced. Q-060 remains open for the closing traversal audit and additional full per-step validation; Q-059's uncached nominal property queries remain separate work.
|
||||
@@ -433,4 +433,10 @@ The [Q-060 JSON increment](../design/runtime-value-depth-audit.md#runtime-value-
|
||||
|
||||
Units/format checks, test-extended and all 1,791 current ordinary conformance cases pass; the added pair also passes per-step collection in Debug. Forty-four old/new shallow records are byte-identical. The prior full Debug collector run has no completion result (785 passing records); its process disappeared, and a replacement full ReleaseSafe per-step run is in progress, retaining safety checks. No incomplete run is counted as a pass. There is no normative/bundle/feature/code change or new depth limit. Q-060's closing call-path audit and Q-059's uncached nominal queries remain open; the cache-free public runtime entry concern is inspection-only. Phase 6/contract gates remain open. No fresh Claude review was available.
|
||||
|
||||
## Cache-free nominal runtime size queries (2026-10-10)
|
||||
|
||||
The [Q-059 nominal size increment](../design/air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) replaces recursive uncached sizing with temporary explicit continuations. The internal Zig query API now takes a host allocator and propagates metadata OutOfMemory separately from arithmetic overflow; runtime callers propagate it before authority charging. Cached reads, the static metric, quota/release behavior and instruction accounting are unchanged. The old direct 32,768-declaration query aborts; the new query returns one byte. Parsed, verified cache-free programmes at nominal depths 1,024 and 4,096 run successfully before and after, retaining six instructions; no old runtime failure at those depths is claimed.
|
||||
|
||||
Units/format checks, test-extended and all 1,791 ordinary conformance cases pass. Tests compare 7,168 shallow queries with an independent arithmetic oracle, fail every temporary metadata allocation and check cached success/null and partial-cache behavior. Fifty-four cached/cache-free quota/fuel/collection pairs (108 verified runs) have identical outcomes and instruction counts. All 370 public AIR checks preserve exact old/new exit/stdout/stderr. No normative/bundle/feature/code change or depth limit is introduced. The earlier full ReleaseSafe per-step suite remains in progress; Q-059's nominal property queries, Q-060's closing audit and Phase 6/contract gates remain open. No fresh Claude review was available.
|
||||
|
||||
Both new copy cases also pass with collection before every instruction; their shallow sharing-preserving GC behavior is covered separately from the retained deep collector failure.
|
||||
@@ -367,7 +367,7 @@ test "cached predicates match uncached derivations on mixed acyclic graphs" {
|
||||
if (before) |b| try std.testing.expect(b.eql(after.?));
|
||||
}
|
||||
var memo: @import("../verifier/budget.zig").SizeMemo = .{ .arena = a };
|
||||
for ([_]usize{ 0, 1, 5, 6 }) |depth| try std.testing.expectEqual(@import("../verifier/budget.zig").accountedSize(m, t, depth), try memo.size(m, t, depth));
|
||||
for ([_]usize{ 0, 1, 5, 6 }) |depth| try std.testing.expectEqual(try @import("../verifier/budget.zig").accountedSize(a, m, t, depth), try memo.size(m, t, depth));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+85
-23
@@ -1219,7 +1219,7 @@ const Machine = struct {
|
||||
switch (inst.op) {
|
||||
.channel_make => |x| {
|
||||
const n = usize_(vals[x.cap]);
|
||||
const each = budget.accountedSize(m.module, x.elem, 0);
|
||||
const each = try budget.accountedSize(m.arena, m.module, x.elem, 0);
|
||||
const bytes: ?u64 = if (each) |e| std.math.mul(u64, n, e) catch null else null;
|
||||
const a = vals[x.mem].cap;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
@@ -1773,14 +1773,14 @@ const Machine = struct {
|
||||
while (x) |i| : (x = m.authorities.items[i].parent) m.authorities.items[i].used -= bytes;
|
||||
}
|
||||
|
||||
fn arrayBytes(m: *Machine, element: Value, n: u64) ?u64 {
|
||||
const each = m.valueBytes(element) orelse return null;
|
||||
fn arrayBytes(m: *Machine, element: Value, n: u64) std.mem.Allocator.Error!?u64 {
|
||||
const each = try m.valueBytes(element) orelse return null;
|
||||
return std.math.mul(u64, n, each) catch null;
|
||||
}
|
||||
|
||||
/// Accounted size (spec 08 §7.1) of the type of a runtime value; equal
|
||||
/// to `budget.accountedSize` of the value's static type.
|
||||
fn valueBytes(m: *Machine, initial: Value) ?u64 {
|
||||
fn valueBytes(m: *Machine, initial: Value) std.mem.Allocator.Error!?u64 {
|
||||
var v = initial;
|
||||
var factor: ?u64 = 1;
|
||||
while (v == .array) {
|
||||
@@ -1794,8 +1794,8 @@ const Machine = struct {
|
||||
const base = (switch (v) {
|
||||
.int => |x| x.ty.bits() / 8,
|
||||
.boolean => 1,
|
||||
.aggregate => |a| budget.accountedSize(m.module, .{ .named = a.decl }, 0),
|
||||
.builtin => |b| budget.accountedSize(m.module, .{ .builtin = b.which }, 0),
|
||||
.aggregate => |a| try budget.accountedSize(m.arena, m.module, .{ .named = a.decl }, 0),
|
||||
.builtin => |b| try budget.accountedSize(m.arena, m.module, .{ .builtin = b.which }, 0),
|
||||
.cap => 8,
|
||||
.iref => 16,
|
||||
else => unreachable, // only value types are allocated (spec 03 §19.2)
|
||||
@@ -1852,7 +1852,7 @@ const Machine = struct {
|
||||
inline .island_create, .arc_new => |x| {
|
||||
const v = vals[x.value];
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = if (m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null;
|
||||
const bytes = if (try m.valueBytes(v)) |b| (std.math.add(u64, b, graph_header) catch null) else null;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const g = try m.newGraph(a, bytes.?, v);
|
||||
if (inst.op == .arc_new) {
|
||||
@@ -1866,7 +1866,7 @@ const Machine = struct {
|
||||
.island_alloc => |x| {
|
||||
const g = graphOf(vals[x.island]);
|
||||
const v = vals[x.value];
|
||||
const bytes = m.valueBytes(v);
|
||||
const bytes = try m.valueBytes(v);
|
||||
if (!m.charge(g.authority, bytes)) return allocFailed(f, vals, x.err);
|
||||
g.bytes += bytes.?;
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
@@ -1930,7 +1930,7 @@ const Machine = struct {
|
||||
switch (inst.op) {
|
||||
.buffer_new => |x| {
|
||||
const capacity = usize_(vals[x.n]);
|
||||
const size = budget.accountedSize(m.module, x.ty, 0).?;
|
||||
const size = (try budget.accountedSize(m.arena, m.module, x.ty, 0)).?;
|
||||
const bytes = std.math.mul(u64, capacity, size) catch null;
|
||||
const authority_ = vals[x.cap].cap;
|
||||
if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err);
|
||||
@@ -1957,7 +1957,7 @@ const Machine = struct {
|
||||
if (try m.raceCheck(b.cell, &.{}, true)) |r| return r;
|
||||
const capacity = usize_(vals[x.n]);
|
||||
if (capacity <= b.capacity) return .{ .jump = x.ok };
|
||||
const size = budget.accountedSize(m.module, b.elem, 0).?;
|
||||
const size = (try budget.accountedSize(m.arena, m.module, b.elem, 0)).?;
|
||||
const bytes = std.math.mul(u64, capacity, size) catch null;
|
||||
const authority_ = vals[x.cap].cap;
|
||||
if (!m.charge(authority_, bytes)) return allocFailed(f, vals, x.err);
|
||||
@@ -2016,7 +2016,7 @@ const Machine = struct {
|
||||
switch (inst.op) {
|
||||
.own_pack => |x| {
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = budget.accountedSize(m.module, x.ty, 0);
|
||||
const bytes = try budget.accountedSize(m.arena, m.module, x.ty, 0);
|
||||
if (!m.charge(a, bytes)) {
|
||||
vals[f.blocks[x.err].params[1].value] = vals[x.value];
|
||||
return allocFailed(f, vals, x.err);
|
||||
@@ -2029,7 +2029,7 @@ const Machine = struct {
|
||||
},
|
||||
.own_new => |x| {
|
||||
const v = vals[x.value];
|
||||
const bytes = m.valueBytes(vals[x.value]);
|
||||
const bytes = try m.valueBytes(vals[x.value]);
|
||||
const a = vals[x.cap].cap;
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
@@ -2041,7 +2041,7 @@ const Machine = struct {
|
||||
.own_array => |x| {
|
||||
const n = usize_(vals[x.n]);
|
||||
const a = vals[x.cap].cap;
|
||||
const bytes = m.arrayBytes(vals[x.value], n);
|
||||
const bytes = try m.arrayBytes(vals[x.value], n);
|
||||
if (!m.charge(a, bytes)) return allocFailed(f, vals, x.err);
|
||||
const items = try m.heap().alloc(Value, n);
|
||||
for (items) |*it| it.* = try m.deepCopy(vals[x.value]);
|
||||
@@ -2076,7 +2076,7 @@ const Machine = struct {
|
||||
const t = air.allocTargets(inst.op).?;
|
||||
const r = placePtr(asPlace(vals[rb])).region;
|
||||
const region = &m.regions.items[r];
|
||||
const bytes = if (n) |count| m.arrayBytes(vals[value], count) else m.valueBytes(vals[value]);
|
||||
const bytes = if (n) |count| try m.arrayBytes(vals[value], count) else try m.valueBytes(vals[value]);
|
||||
if (!m.charge(region.authority, bytes)) return allocFailed(f, vals, t.err);
|
||||
region.used += bytes.?;
|
||||
const cell = try m.heap().create(Value.Cell);
|
||||
@@ -2997,10 +2997,10 @@ test "runtime value sizing agrees with static accounting through array wrappers"
|
||||
var ty = leaf.ty;
|
||||
var v = leaf.value;
|
||||
for (0..8) |depth| {
|
||||
const size = budget.accountedSize(module, ty, 0).?;
|
||||
try std.testing.expectEqual(@as(?u64, size), m.valueBytes(v));
|
||||
const size = (try budget.accountedSize(arena, module, ty, 0)).?;
|
||||
try std.testing.expectEqual(@as(?u64, size), try m.valueBytes(v));
|
||||
for ([_]u64{ 0, 1, 2, std.math.maxInt(u64) }) |count|
|
||||
try std.testing.expectEqual(@as(?u64, std.math.mul(u64, size, count) catch null), m.arrayBytes(v, count));
|
||||
try std.testing.expectEqual(@as(?u64, std.math.mul(u64, size, count) catch null), try m.arrayBytes(v, count));
|
||||
const len = depth % 3 + 1;
|
||||
const items = try arena.alloc(Value, len);
|
||||
@memset(items, v);
|
||||
@@ -3043,13 +3043,13 @@ test "runtime value sizing handles deep wrappers and zero-sized leaves without r
|
||||
overflowing = .{ .array = pair };
|
||||
}
|
||||
}
|
||||
try std.testing.expectEqual(@as(?u64, 1), m.valueBytes(one));
|
||||
try std.testing.expectEqual(@as(?u64, std.math.maxInt(u64)), m.arrayBytes(one, std.math.maxInt(u64)));
|
||||
try std.testing.expectEqual(@as(?u64, 0), m.valueBytes(zero));
|
||||
try std.testing.expectEqual(@as(?u64, 0), m.arrayBytes(zero, std.math.maxInt(u64)));
|
||||
try std.testing.expectEqual(@as(?u64, null), m.valueBytes(overflowing));
|
||||
try std.testing.expectEqual(@as(?u64, 1), try m.valueBytes(one));
|
||||
try std.testing.expectEqual(@as(?u64, std.math.maxInt(u64)), try m.arrayBytes(one, std.math.maxInt(u64)));
|
||||
try std.testing.expectEqual(@as(?u64, 0), try m.valueBytes(zero));
|
||||
try std.testing.expectEqual(@as(?u64, 0), try m.arrayBytes(zero, std.math.maxInt(u64)));
|
||||
try std.testing.expectEqual(@as(?u64, null), try m.valueBytes(overflowing));
|
||||
// A zero dynamic allocation count must not mask an overflowing element.
|
||||
try std.testing.expectEqual(@as(?u64, null), m.arrayBytes(overflowing, 0));
|
||||
try std.testing.expectEqual(@as(?u64, null), try m.arrayBytes(overflowing, 0));
|
||||
}
|
||||
|
||||
fn expectCollectorAllocationFailure(source: []Value, fail_index: usize) !bool {
|
||||
@@ -3431,6 +3431,68 @@ test "deep zero and local-load copying retain fuel boundaries with ordinary and
|
||||
}
|
||||
}
|
||||
|
||||
test "public verification and runtime entry preserve cache-free nominal quota outcomes" {
|
||||
var state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer state.deinit();
|
||||
const a = state.allocator();
|
||||
const src =
|
||||
\\module cache.free
|
||||
\\air 0
|
||||
\\lang 0.1
|
||||
\\features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]
|
||||
\\type @Empty = struct {}
|
||||
\\type @Record = struct { xs: array<u16, 3>, empty: @Empty }
|
||||
\\type @Choice = enum { none, some(@Record) }
|
||||
\\fn @main(%heap: cap<mem.alloc>) -> u8
|
||||
\\effects [mem.alloc]
|
||||
\\entry:
|
||||
\\ %p = local.alloc @Record
|
||||
\\ local.zero %p
|
||||
\\ %r = local.load %p
|
||||
\\ %v = enum.make @Choice.some(%r)
|
||||
\\ own.new %v, %heap, ok -> @have, err -> @nomem
|
||||
\\have(%o: own<@Choice>):
|
||||
\\ own.free %o
|
||||
\\ %yes = const.u8 7
|
||||
\\ ret %yes
|
||||
\\nomem(%e: alloc_error):
|
||||
\\ %no = const.u8 0
|
||||
\\ ret %no
|
||||
;
|
||||
const parsed = try air.parse.parse(a, "cache-free.air", src);
|
||||
try std.testing.expect(parsed.diagnostics.len == 0);
|
||||
const original = parsed.module.?;
|
||||
const verifier = @import("../verifier.zig");
|
||||
try std.testing.expect((try verifier.verify(a, "cache-free.air", original)).len == 0);
|
||||
try std.testing.expect(original.accounted_sizes == null and original.nominal_properties == null);
|
||||
const checked = try verifier.verifyModule(a, "cache-free.air", original);
|
||||
try std.testing.expect(checked.diagnostics.len == 0 and checked.module.accounted_sizes != null);
|
||||
for ([_]bool{ false, true }) |every_step| for ([_][]const u8{ "0", "6", "7" }) |quota| for (0..9) |fuel| {
|
||||
var records: [2][]const u8 = undefined;
|
||||
for ([_]air.Module{ original, checked.module }, 0..) |module, index| {
|
||||
var stats: MemoryStats = .{};
|
||||
const result = try run(a, module, "main", .{ .fuel = fuel, .memory = &stats, .collect_every_step = every_step, .grants = &.{.{ .parameter = "heap", .kind = "mem.alloc", .scope = quota }} });
|
||||
const success = std.mem.eql(u8, quota, "7");
|
||||
const complete: u64 = if (success) 8 else 7;
|
||||
try std.testing.expectEqual(@min(fuel, complete), stats.steps);
|
||||
if (fuel < complete) {
|
||||
try std.testing.expect(result == .limit_exceeded and result.limit_exceeded.steps == fuel);
|
||||
} else try std.testing.expect(result == .returned and result.returned.int.bits == @as(u128, if (success) 7 else 0));
|
||||
var encoded: std.Io.Writer.Allocating = .init(a);
|
||||
try writeOutcome(module, result, null, &encoded.writer);
|
||||
records[index] = encoded.written();
|
||||
}
|
||||
try std.testing.expectEqualStrings(records[0], records[1]);
|
||||
};
|
||||
var m: Machine = .{ .arena = a, .module = original, .fuel = null, .world = try .init(a, .{}) };
|
||||
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
|
||||
m.arena = failing.allocator();
|
||||
// A nominal query reads its type declaration, not the active payload.
|
||||
const value: Value = .{ .aggregate = .{ .decl = 2, .variant = 0, .fields = &.{} } };
|
||||
try std.testing.expectError(error.OutOfMemory, m.valueBytes(value));
|
||||
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
|
||||
}
|
||||
|
||||
test "deep returned payload survives per-step collection and execution heap release" {
|
||||
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
|
||||
+104
-19
@@ -25,7 +25,10 @@ pub const Limits = struct {
|
||||
/// 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 {
|
||||
/// Cached/anonymous reads allocate nothing. An uncached nominal query uses
|
||||
/// temporary continuations and propagates host allocation failure separately
|
||||
/// from arithmetic overflow; it releases metadata before returning.
|
||||
pub fn accountedSize(allocator: std.mem.Allocator, m: air.Module, t: air.Type, depth: usize) std.mem.Allocator.Error!?u64 {
|
||||
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.
|
||||
@@ -60,7 +63,15 @@ pub fn accountedSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
|
||||
current = inner.*;
|
||||
},
|
||||
else => {
|
||||
base = uncachedBaseSize(m, current, depth);
|
||||
if (current == .named) {
|
||||
// A cache-free public module needs the same explicit
|
||||
// nominal continuations as verification. Keep temporary
|
||||
// metadata separate from caller/runtime payload storage.
|
||||
var scratch: std.heap.ArenaAllocator = .init(allocator);
|
||||
defer scratch.deinit();
|
||||
var memo: SizeMemo = .{ .arena = scratch.allocator() };
|
||||
base = try memo.size(m, current, depth);
|
||||
} else base = scalarSize(current);
|
||||
break;
|
||||
},
|
||||
}
|
||||
@@ -131,7 +142,7 @@ pub const SizeMemo = struct {
|
||||
if (current_depth > m.types.len + 1) {
|
||||
result = 0;
|
||||
} else if (sizeKey(current, current_depth)) |key| {
|
||||
if (cache.values.get(key)) |value| {
|
||||
if (cache.values.get(key) orelse if (m.accounted_sizes) |shared| shared.get(key) else null) |value| {
|
||||
result = value;
|
||||
} else {
|
||||
if (current == .named) cache.evaluations += 1;
|
||||
@@ -202,21 +213,25 @@ fn scalarSize(t: air.Type) u64 {
|
||||
};
|
||||
}
|
||||
|
||||
// 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 {
|
||||
// Independent, bounded test oracle. Production queries never recurse over
|
||||
// nominal members; this derivation is used only on shallow test graphs.
|
||||
fn referenceSize(m: air.Module, t: air.Type, depth: usize) ?u64 {
|
||||
if (depth > m.types.len + 1) return 0;
|
||||
return switch (t) {
|
||||
.array => |row| std.math.mul(u64, row.len, referenceSize(m, row.elem, depth) orelse return null) catch null,
|
||||
.atomic => |inner| referenceSize(m, inner.*, depth),
|
||||
.mutex => |inner| std.math.add(u64, 8, referenceSize(m, inner.*, depth) orelse return null) catch null,
|
||||
.named => |i| switch (m.types[i].kind) {
|
||||
.@"struct" => |fs| blk: {
|
||||
var sum: u64 = 0;
|
||||
for (fs) |f| sum = std.math.add(u64, sum, accountedSize(m, f.ty, depth + 1) orelse return null) catch return null;
|
||||
for (fs) |f| sum = std.math.add(u64, sum, referenceSize(m, f.ty, depth + 1) orelse return null) catch return null;
|
||||
break :blk sum;
|
||||
},
|
||||
.@"enum" => |vs| blk: {
|
||||
var maximum: u64 = 0;
|
||||
for (vs) |v| {
|
||||
var sum: u64 = 0;
|
||||
for (v.payload) |p| sum = std.math.add(u64, sum, accountedSize(m, p, depth + 1) orelse return null) catch return null;
|
||||
for (v.payload) |p| sum = std.math.add(u64, sum, referenceSize(m, p, depth + 1) orelse return null) catch return null;
|
||||
maximum = @max(maximum, sum);
|
||||
}
|
||||
break :blk std.math.add(u64, tagSize(vs.len), maximum) catch null;
|
||||
@@ -337,6 +352,69 @@ fn checkValueSizes(c: *verifier.Context, memo: *SizeMemo) !void {
|
||||
}
|
||||
}
|
||||
|
||||
test "uncached nominal sizes preserve shallow independent arithmetic and cycle guards" {
|
||||
for (0..256) |seed| {
|
||||
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer scratch.deinit();
|
||||
const a = scratch.allocator();
|
||||
const ds = try a.alloc(air.TypeDecl, 4);
|
||||
for (ds, 0..) |*d, i| {
|
||||
const leaf = try a.create(air.Type);
|
||||
leaf.* = if (i == 3) .{ .int = .u64 } else .{ .named = @intCast(if (seed % 7 == 0) i else i + 1) };
|
||||
const array = try a.create(air.Type.Array);
|
||||
array.* = .{ .elem = leaf.*, .len = if (seed % 13 == 0) std.math.maxInt(u64) else (seed + i) % 4 };
|
||||
const choices = [_]air.Type{ leaf.*, .bool, .{ .array = array }, .{ .atomic = leaf }, .{ .mutex = leaf }, .{ .own = leaf }, .{ .iref = leaf } };
|
||||
const x = choices[(seed + 3 * i) % choices.len];
|
||||
const y = choices[(seed / choices.len + i) % choices.len];
|
||||
const fields = try a.dupe(air_module.Field, &.{ .{ .name = "x", .ty = x }, .{ .name = "y", .ty = y } });
|
||||
const variants = try a.dupe(air_module.Variant, &.{ .{ .name = "empty", .payload = &.{} }, .{ .name = "some", .payload = try a.dupe(air.Type, &.{ x, y }) } });
|
||||
d.* = .{ .name = "N", .span = .{ .line = 1, .col = 1 }, .kind = if ((seed + i) % 2 == 0) .{ .@"struct" = fields } else .{ .@"enum" = variants } };
|
||||
}
|
||||
const m: air.Module = .{ .name = "oracle", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} };
|
||||
for (0..4) |i| for (0..7) |depth| {
|
||||
const ty: air.Type = .{ .named = @intCast(i) };
|
||||
try std.testing.expectEqual(referenceSize(m, ty, depth), try accountedSize(a, m, ty, depth));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
test "deep cache-free nominal queries release continuations and separate allocation failure" {
|
||||
var scratch: std.heap.ArenaAllocator = .init(std.testing.allocator);
|
||||
defer scratch.deinit();
|
||||
const a = scratch.allocator();
|
||||
const ds = try a.alloc(air.TypeDecl, 32768);
|
||||
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 == ds.len) .{ .int = .u8 } else .{ .named = @intCast(i + 1) } }}) } };
|
||||
var m: air.Module = .{ .name = "deep", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = ds, .functions = &.{} };
|
||||
const ty: air.Type = .{ .named = 0 };
|
||||
try std.testing.expectEqual(@as(?u64, 1), try accountedSize(std.testing.allocator, m, ty, 0));
|
||||
try std.testing.expect(m.accounted_sizes == null);
|
||||
// Fail every underlying metadata allocation, then reach a successful
|
||||
// query. Null is reserved for arithmetic overflow, never host OOM.
|
||||
var fail_index: usize = 0;
|
||||
while (true) : (fail_index += 1) {
|
||||
try std.testing.expect(fail_index < 100);
|
||||
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index });
|
||||
const result = accountedSize(failing.allocator(), m, ty, 0);
|
||||
if (failing.has_induced_failure) {
|
||||
try std.testing.expectError(error.OutOfMemory, result);
|
||||
} else try std.testing.expectEqual(@as(?u64, 1), try result);
|
||||
try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes);
|
||||
if (!failing.has_induced_failure) break;
|
||||
}
|
||||
var cache: air_module.SizeCache = .{};
|
||||
try cache.put(a, .{ .index = 0, .depth = 0 }, 1);
|
||||
m.accounted_sizes = &cache;
|
||||
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
|
||||
try std.testing.expectEqual(@as(?u64, 1), try accountedSize(failing.allocator(), m, ty, 0));
|
||||
try std.testing.expect(!failing.has_induced_failure);
|
||||
// A cached overflow and a partial cache remain distinguishable from a
|
||||
// missing entry; neither the caller's table nor type storage is mutated.
|
||||
try cache.put(a, .{ .index = 0, .depth = 0 }, null);
|
||||
try std.testing.expectEqual(@as(?u64, null), try accountedSize(failing.allocator(), m, ty, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 1), try accountedSize(a, m, .{ .named = 1 }, 0));
|
||||
try std.testing.expectEqual(@as(usize, 1), cache.count());
|
||||
}
|
||||
|
||||
test "too many parameters" {
|
||||
var src: std.ArrayList(u8) = .empty;
|
||||
defer src.deinit(std.testing.allocator);
|
||||
@@ -358,7 +436,7 @@ test "accounted sizes memoize shared diamonds and cyclic depth states" {
|
||||
try std.testing.expect(memo.evaluations <= 65 * 67);
|
||||
const before = memo.evaluations;
|
||||
m.accounted_sizes = &memo.values;
|
||||
for (0..65) |i| try std.testing.expectEqual(@as(?u64, 0), accountedSize(m, .{ .named = @intCast(i) }, 0));
|
||||
for (0..65) |i| try std.testing.expectEqual(@as(?u64, 0), try accountedSize(std.testing.allocator, m, .{ .named = @intCast(i) }, 0));
|
||||
try std.testing.expectEqual(before, memo.evaluations);
|
||||
// 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 } } }) };
|
||||
@@ -394,9 +472,9 @@ test "maximum value size" {
|
||||
|
||||
test "accounted sizes" {
|
||||
const m: air.Module = .{ .name = "t", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} };
|
||||
try std.testing.expectEqual(@as(?u64, 8), accountedSize(m, .{ .int = .isize }, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 16), accountedSize(m, .{ .int = .u128 }, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 1), accountedSize(m, .bool, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 8), try accountedSize(std.testing.allocator, m, .{ .int = .isize }, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 16), try accountedSize(std.testing.allocator, m, .{ .int = .u128 }, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 1), try accountedSize(std.testing.allocator, m, .bool, 0));
|
||||
try std.testing.expectEqual(@as(u64, 1), tagSize(256));
|
||||
try std.testing.expectEqual(@as(u64, 2), tagSize(257));
|
||||
}
|
||||
@@ -418,7 +496,7 @@ test "anonymous wrapper sizes do not depend on nominal declaration count" {
|
||||
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 accountedSize(std.testing.allocator, m, t, 0));
|
||||
try std.testing.expectEqual(@as(?u64, want), try memo.size(m, t, 0));
|
||||
}
|
||||
}
|
||||
@@ -450,9 +528,9 @@ test "deep anonymous sizes use bounded native stack and cached inner queries" {
|
||||
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));
|
||||
try std.testing.expectEqual(@as(?u64, 1), try accountedSize(std.testing.allocator, m, t, 0));
|
||||
m.accounted_sizes = &memo.values;
|
||||
for (rows) |*row| try std.testing.expectEqual(@as(?u64, 1), accountedSize(m, .{ .array = row }, 0));
|
||||
for (rows) |*row| try std.testing.expectEqual(@as(?u64, 1), try accountedSize(std.testing.allocator, m, .{ .array = row }, 0));
|
||||
}
|
||||
|
||||
test "size overflow preserves zero leaves and does not hide behind outer zero" {
|
||||
@@ -468,12 +546,12 @@ test "size overflow preserves zero leaves and does not hide behind outer zero" {
|
||||
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));
|
||||
try std.testing.expectEqual(@as(?u64, 0), try accountedSize(std.testing.allocator, 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));
|
||||
try std.testing.expectEqual(@as(?u64, null), try accountedSize(std.testing.allocator, m, t, 0));
|
||||
}
|
||||
|
||||
test "deep nominal size queries use explicit continuations" {
|
||||
@@ -506,6 +584,13 @@ test "overflowing nominal continuations cache null without revisiting children"
|
||||
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);
|
||||
var shared = m;
|
||||
shared.accounted_sizes = &memo.values;
|
||||
var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = 0 });
|
||||
var reader: SizeMemo = .{ .arena = failing.allocator() };
|
||||
try std.testing.expectEqual(@as(?u64, null), try reader.size(shared, .{ .named = 0 }, 0));
|
||||
try std.testing.expectEqual(@as(usize, 0), reader.evaluations);
|
||||
try std.testing.expect(!failing.has_induced_failure);
|
||||
}
|
||||
|
||||
test "anonymous cache identities distinguish shared atomic and mutex content" {
|
||||
@@ -520,6 +605,6 @@ test "anonymous cache identities distinguish shared atomic and mutex content" {
|
||||
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));
|
||||
try std.testing.expectEqual(@as(?u64, 8), try accountedSize(std.testing.allocator, m, atom, 0));
|
||||
try std.testing.expectEqual(@as(?u64, 16), try accountedSize(std.testing.allocator, m, lock, 0));
|
||||
}
|
||||
Reference in new issue
Block a user