From c9064418bd01bb6f506dfd5f979e6ea59ae849cd Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sat, 10 Oct 2026 00:01:40 +0300 Subject: [PATCH] interp: serialize runtime values without recursive JSON nesting --- docs/design/open-questions.md | 2 + docs/design/runtime-value-depth-audit.md | 16 +- docs/plan/phase-6-source-language.md | 6 + src/interp/machine.zig | 406 +++++++++++++++--- .../phase1/run/returned_mixed_json.air | 32 ++ .../runtime_values/returned_mixed_json.aji | 15 + 6 files changed, 422 insertions(+), 55 deletions(-) create mode 100644 tests/conformance/phase1/run/returned_mixed_json.air create mode 100644 tests/conformance/source/runtime_values/returned_mixed_json.aji diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 9e40879..f7340db 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -482,3 +482,5 @@ The [storage/value-copy increment](runtime-value-depth-audit.md#storagevalue-cop The [sharing-preserving copy increment](runtime-value-depth-audit.md#sharing-preserving-copy-repair) removes recursive collector/result copying while retaining forwarded identities, backing storage, cycles, slice paths/ranges, buffer metadata, race shadows and mutex views. Deep verified runs now pass ordinary and per-instruction collection, with unchanged fuel boundaries and returned payload lifetimes. Follow-up CLI probes independently confirm valueBytes native-stack exhaustion on own.new and output failure at std.json.Stringify's fixed nesting stack. The latter is not yet evidence of writeValue native-stack overflow. Q-060 stays open for sizing and serialization; no normative depth limit, feature or trap is introduced. 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. diff --git a/docs/design/runtime-value-depth-audit.md b/docs/design/runtime-value-depth-audit.md index 3af0ce2..d56ccfb 100644 --- a/docs/design/runtime-value-depth-audit.md +++ b/docs/design/runtime-value-depth-audit.md @@ -21,7 +21,7 @@ Every array length is one. The accounted value/frame size is one byte, and `aji This confirms native recursion in zeroValue on a verified input. An iterative fix must retain zero initialization, value shape, heap/root lifetimes, allocation failure handling, collection safety and instruction/fuel accounting. A new accepted-depth limit or trap would require a normative decision; none is added by compiler-side repairs. -At the initial baseline, deepCopy/copyAll, valueBytes and collection/serialization were inspection candidates only: the zero-materialization failure prevented probing them. The executed results below supersede that status for copying, collection, value sizing and output serialization. Q-060 remains open for output serialization; the earlier increments record the failures that led to each repair. +At the initial baseline, deepCopy/copyAll, valueBytes and collection/serialization were inspection candidates only: the zero-materialization failure prevented probing them. The executed results below supersede that status for copying, collection, value sizing and output serialization. All five confirmed failure paths now have iterative repairs. Q-060 remains open for the closing call-path audit; the earlier increments record the failures that led to each repair. ## Zero-materialization repair @@ -78,3 +78,17 @@ Unit tests compare scalar/nominal/built-in/capability/iref leaves under mixed ar Validation: unit/format checks, test-extended and all 1,789 ordinary conformance cases pass. Ten old/new quota records for the new AIR/source pair are identical. Another 426 generated runs independently compute expected charges for scalar/record/enum contents, mixed fixed arrays, individual/repeated/zero-count owners and island/arc headers; every boundary outcome matches that oracle and the old interpreter's record. These are generated runtime robustness inputs, not model-evaluation or held-out tasks. The earlier full per-instruction collector conformance run remains additional validation in progress. Q-060 remains open for output serialization at the fixed std.json.Stringify nesting stack and the still-recursive writeValue traversal. Q-059's uncached nominal query audit is separate; this repair does not claim to close it. + +## Runtime value JSON repair + +WriteValue now emits the complete value through a raw-value boundary in the outer std.json.Stringify. An explicit pending-sequence stack traverses arrays, record fields and enum payloads; the outer stringify never stores their nesting in its fixed 256-level table. Field order, variant/payload shape, decimal integer representation, escaping, whitespace and opaque handles retain their existing encoding (spec 07a, Run result). The public writer API and diagnostic schema are unchanged. + +The invariant is byte-identical encoding of existing runtime values without traversing opaque identity handles or mutating returned payloads. Traversal metadata lives in a temporary host arena, released on success and failure; it adds no Aji allocation, authority, effect, fuel charge or collection point. Writer errors propagate as before; metadata allocation failure uses the existing WriteFailed interface. No recovery after partial output is promised. The CLI still buffers a complete run record before publishing it. Verifier rules are unchanged: the new returned_mixed_json AIR/source pair returns an enum containing records, nested arrays, signed integers and empty values; the existing source borrow_returns/main_return rejection retains E7006. No new rejection, trap, feature, depth limit or normative/bundle text is introduced. + +Unit tests compare exact bytes with the ordinary Zig encoder in 112 combinations of whitespace, Unicode escaping, string-array, nonportable-number and optional-field options, wrapped between other fields in an outer object. Existing Aji raw decimal integers are preserved even when string mode for nonportable numbers is selected. A codec-only 32,768-level mixed record/variant/array value checks pending siblings and empty leaves against independently constructed bytes; it is not claimed as an executed source programme. Allocation failures check temporary-arena cleanup, and fixed-capacity writers fail at every byte boundary with the exact expected prefix. Another test fills the outer stringify's 256-level table, writes a nested runtime value and then continues and closes the outer containers. + +The verified 32,768-level returned-array programme now produces the complete 65,568-byte CLI record, including its newline, in both deterministic and hosted profiles under fuel 8. Unit tests write its outcome after execution-heap release under ordinary and per-instruction collection. Hosted tests also compare both new shallow examples with the old CLI, using fuel rather than wall-clock termination. + +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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index eefe6b1..1e75b66 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -427,4 +427,10 @@ The [Q-060 runtime value-size increment](../design/runtime-value-depth-audit.md# Units/format checks, test-extended and all 1,789 ordinary conformance cases pass; the deep allocation and new pair also pass per-step collection. Ten new-pair quota records and 426 generated allocation-oracle runs match the old interpreter exactly. The earlier full per-step collector suite remains in progress. No normative/bundle/feature/code change or accepted-depth limit; Q-060 remains open for serialization, and Phase 6/contract gates remain open. No fresh Claude review was available. +## Runtime value JSON serialization (2026-10-10) + +The [Q-060 JSON increment](../design/runtime-value-depth-audit.md#runtime-value-json-repair) emits nested values through explicit sequence continuations and one outer raw-value boundary, preserving field order, escaping, whitespace/options, integer bytes and opaque handles. Host traversal metadata is released on error or completion; Aji authority, payload ownership, fuel, collection and verifier rules are unchanged. Tests cover 112 option combinations, mixed 32,768-level codec values, outer nesting at the stringify boundary and writer/allocation failures. A new AIR/source enum/record/array result pair pins the existing run-record shape, and the original deep verified return now produces a complete record in deterministic and hosted profiles. + +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. + 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. diff --git a/src/interp/machine.zig b/src/interp/machine.zig index 79d3cfe..44c2c06 100644 --- a/src/interp/machine.zig +++ b/src/interp/machine.zig @@ -2463,62 +2463,168 @@ fn cast(mode: air.CastMode, from: air.IntType, to: air.IntType, bits: u128) Trap // ---------------------------------------------------------------- run records (spec 07a "Run result") pub fn writeValue(module: air.Module, v: Value, s: *std.json.Stringify) std.Io.Writer.Error!void { - switch (v) { - .int => |x| switch (x.ty) { - inline else => |t| try s.print("{d}", .{decode(air.IntType.Zig(t), x.bits)}), - }, - .boolean => |b| try s.write(b), - .void => try s.write(null), - .array => |items| { - try s.beginArray(); - for (items) |x| try writeValue(module, x, s); - try s.endArray(); - }, - // Storage and borrows cannot be returned from `@main` (spec 08 §11.3). - .local, .place, .slice => try s.write(null), - .resource, .own, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try s.write(null), - // A capability is opaque: only its kind is shown, never its identity. - .cap => { - try s.beginObject(); - try s.objectField("capability"); - try s.write("opaque"); - try s.endObject(); - }, - .builtin => |b| { - try s.beginObject(); - try s.objectField("variant"); - try s.write(b.which.variants()[b.variant]); - try s.objectField("payload"); - try s.beginArray(); - try s.endArray(); - try s.endObject(); - }, - .aggregate => |agg| { - const d = module.types[agg.decl]; - switch (d.kind) { - .@"struct" => |fields| { - try s.beginObject(); - for (fields, agg.fields) |fd, fv| { - try s.objectField(fd.name); - try writeValue(module, fv, s); - } - try s.endObject(); - }, - .@"enum" => |variants| { - try s.beginObject(); - try s.objectField("variant"); - try s.write(variants[agg.variant].name); - try s.objectField("payload"); - try s.beginArray(); - for (agg.fields) |fv| try writeValue(module, fv, s); - try s.endArray(); - try s.endObject(); - }, - } - }, - } + return writeValueWithAllocator(module, v, s, std.heap.page_allocator); } +fn writeValueWithAllocator(module: air.Module, v: Value, s: *std.json.Stringify, gpa: std.mem.Allocator) std.Io.Writer.Error!void { + var tmp: std.heap.ArenaAllocator = .init(gpa); + defer tmp.deinit(); + var json: ValueJson = .{ .module = module, .writer = s.writer, .options = s.options, .level = s.indent_level, .arena = tmp.allocator() }; + // The outer stringify handles one complete value, while its fixed nesting + // stack never sees the value's internal arrays/records/payloads. + try s.beginWriteRaw(); + try json.write(v); + s.endWriteRaw(); +} + +const ValueJson = struct { + module: air.Module, + writer: *std.Io.Writer, + options: std.json.Stringify.Options, + level: usize, + arena: std.mem.Allocator, + pending: std.ArrayList(Sequence) = .empty, + + const Kind = enum { array, object, enum_payload }; + const Fields = @FieldType(@FieldType(air.TypeDecl, "kind"), "struct"); + const Sequence = struct { values: []const Value, fields: ?Fields, next: usize, kind: Kind }; + + fn indent(j: *ValueJson) std.Io.Writer.Error!void { + var char: u8 = ' '; + const count = switch (j.options.whitespace) { + .minified => return, + .indent_1 => j.level, + .indent_2 => 2 * j.level, + .indent_3 => 3 * j.level, + .indent_4 => 4 * j.level, + .indent_8 => 8 * j.level, + .indent_tab => blk: { + char = '\t'; + break :blk j.level; + }, + }; + try j.writer.writeByte('\n'); + try j.writer.splatByteAll(char, count); + } + + fn field(j: *ValueJson, name: []const u8) std.Io.Writer.Error!void { + try std.json.Stringify.encodeJsonString(name, j.options, j.writer); + try j.writer.writeByte(':'); + if (j.options.whitespace != .minified) try j.writer.writeByte(' '); + } + + fn string(j: *ValueJson, bytes: []const u8) std.Io.Writer.Error!void { + if (!j.options.emit_strings_as_arrays and std.unicode.utf8ValidateSlice(bytes)) + return std.json.Stringify.encodeJsonString(bytes, j.options, j.writer); + try j.writer.writeByte('['); + j.level += 1; + for (bytes, 0..) |byte, i| { + if (i != 0) try j.writer.writeByte(','); + try j.indent(); + try j.writer.print("{d}", .{byte}); + } + j.level -= 1; + if (bytes.len != 0) try j.indent(); + try j.writer.writeByte(']'); + } + + fn element(j: *ValueJson, frame: Sequence, i: usize) std.Io.Writer.Error!void { + if (i != 0) try j.writer.writeByte(','); + try j.indent(); + if (frame.fields) |fields| try j.field(fields[i].name); + } + + fn close(j: *ValueJson, kind: Kind, nonempty: bool) std.Io.Writer.Error!void { + j.level -= 1; + if (nonempty) try j.indent(); + try j.writer.writeByte(if (kind == .object) '}' else ']'); + if (kind == .enum_payload) { + j.level -= 1; + try j.indent(); // variant and payload make the enum object nonempty + try j.writer.writeByte('}'); + } + } + + fn sequence(j: *ValueJson, values: []const Value, fields: ?Fields, kind: Kind) std.Io.Writer.Error!?Value { + if (fields) |names| std.debug.assert(names.len == values.len); + try j.writer.writeByte(if (kind == .object) '{' else '['); + j.level += 1; + if (values.len == 0) { + try j.close(kind, false); + return null; + } + const frame: Sequence = .{ .values = values, .fields = fields, .next = 1, .kind = kind }; + j.pending.append(j.arena, frame) catch return error.WriteFailed; + try j.element(frame, 0); + return values[0]; + } + + fn variant(j: *ValueJson, name: []const u8, payload: []const Value) std.Io.Writer.Error!?Value { + try j.writer.writeByte('{'); + j.level += 1; + try j.indent(); + try j.field("variant"); + try j.string(name); + try j.writer.writeByte(','); + try j.indent(); + try j.field("payload"); + return j.sequence(payload, null, .enum_payload); + } + + fn write(j: *ValueJson, initial: Value) std.Io.Writer.Error!void { + var v = initial; + next: while (true) { + switch (v) { + .int => |x| switch (x.ty) { + // As before, Aji integers are raw decimal numbers, including + // wide integers when nonportable-number string mode is set. + inline else => |t| try j.writer.print("{d}", .{decode(air.IntType.Zig(t), x.bits)}), + }, + .boolean => |b| try j.writer.writeAll(if (b) "true" else "false"), + .array => |items| if (try j.sequence(items, null, .array)) |child| { + v = child; + continue :next; + }, + .aggregate => |agg| { + const decl = j.module.types[agg.decl]; + const child = switch (decl.kind) { + .@"struct" => |fields| try j.sequence(agg.fields, fields, .object), + .@"enum" => |variants| try j.variant(variants[agg.variant].name, agg.fields), + }; + if (child) |value| { + v = value; + continue :next; + } + }, + .builtin => |b| _ = try j.variant(b.which.variants()[b.variant], &.{}), + .cap => { + try j.writer.writeByte('{'); + j.level += 1; + try j.indent(); + try j.field("capability"); + try j.string("opaque"); + try j.close(.object, true); + }, + // Storage/borrows cannot be returned from @main (spec 08 §11.3). + // Runtime identity handles remain opaque, exactly as before. + .void, .local, .place, .slice, .resource, .own, .buffer, .region, .scope, .task, .shield, .sender, .receiver, .mutex, .guard, .graph, .iref, .atomic => try j.writer.writeAll("null"), + } + while (j.pending.pop()) |frame| { + if (frame.next < frame.values.len) { + try j.element(frame, frame.next); + var remaining = frame; + remaining.next += 1; + j.pending.append(j.arena, remaining) catch return error.WriteFailed; + v = frame.values[frame.next]; + continue :next; + } + try j.close(frame.kind, true); + } + return; + } + } +}; + /// Byte strings in the run record (spec 07a "Run result"): a JSON string /// when the bytes are valid UTF-8, otherwise {"encoding":"base64","data":…}. fn writeText(s: *std.json.Stringify, bytes: []const u8) std.Io.Writer.Error!void { @@ -2668,6 +2774,188 @@ fn expectRunFuel(src: []const u8, expected: []const u8, fuel: ?u64) !void { const h = "module t\nair 0\nlang 0.1\nfeatures []\n"; +test "value JSON preserves field order, escaping, whitespace options and outer stringify state" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const arena = state.allocator(); + const module: air.Module = .{ + .name = "json.options", + .format_version = 0, + .lang = .{ 0, 1 }, + .features = &.{}, + .functions = &.{}, + .types = &.{ + .{ .name = "Record", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{ + .{ .name = "na\nmé\"", .ty = .{ .array = &.{ .elem = .{ .int = .u16 }, .len = 3 } } }, + .{ .name = "ok", .ty = .bool }, + } } }, + .{ .name = "Choice", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"enum" = &.{.{ .name = "some\n☃", .payload = &.{ .{ .named = 0 }, .{ .array = &.{ .elem = .bool, .len = 2 } } } }} } }, + .{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }, + }, + }; + const numbers = try arena.dupe(Value, &.{ .{ .int = .{ .ty = .u16, .bits = 7 } }, .{ .int = .{ .ty = .u16, .bits = 14 } }, .{ .int = .{ .ty = .u16, .bits = 21 } } }); + const record = try arena.dupe(Value, &.{ .{ .array = numbers }, .{ .boolean = true } }); + const flags = try arena.dupe(Value, &.{ .{ .boolean = false }, .{ .boolean = true } }); + const payload = try arena.dupe(Value, &.{ .{ .aggregate = .{ .decl = 0, .variant = 0, .fields = record } }, .{ .array = flags } }); + const values = try arena.dupe(Value, &.{ + .{ .aggregate = .{ .decl = 1, .variant = 0, .fields = payload } }, + .{ .aggregate = .{ .decl = 2, .variant = 0, .fields = &.{} } }, + .{ .array = &.{} }, + .{ .builtin = .{ .which = .alloc_error, .variant = 0 } }, + .{ .cap = 42 }, + .void, + .{ .int = .{ .ty = .i128, .bits = std.math.maxInt(u128) } }, + .{ .int = .{ .ty = .u128, .bits = std.math.maxInt(u128) } }, + }); + const expected = .{ + .{ .variant = "some\n☃", .payload = .{ .{ .@"na\nmé\"" = [_]u16{ 7, 14, 21 }, .ok = true }, [_]bool{ false, true } } }, + @as(struct {}, .{}), + [_]u16{}, + .{ .variant = "budget_exceeded", .payload = [_]u16{} }, + .{ .capability = "opaque" }, + null, + @as(i128, -1), + std.math.maxInt(u128), + }; + const Whitespace = @FieldType(std.json.Stringify.Options, "whitespace"); + for (std.meta.tags(Whitespace)) |whitespace| for (0..16) |bits| { + const options: std.json.Stringify.Options = .{ + .whitespace = whitespace, + .escape_unicode = bits & 1 != 0, + .emit_strings_as_arrays = bits & 2 != 0, + .emit_nonportable_numbers_as_strings = bits & 4 != 0, + .emit_null_optional_fields = bits & 8 != 0, + }; + var actual: std.Io.Writer.Allocating = .init(arena); + var s: std.json.Stringify = .{ .writer = &actual.writer, .options = options }; + try s.beginObject(); + try s.objectField("before"); + try s.write(true); + try s.objectField("result"); + try writeValue(module, .{ .array = values }, &s); + try s.objectField("after"); + try s.write(false); + try s.endObject(); + var reference: std.Io.Writer.Allocating = .init(arena); + // The existing Aji codec prints integer values directly; wide-number + // string mode affects neither signed nor unsigned Aji integers. + var expected_options = options; + expected_options.emit_nonportable_numbers_as_strings = false; + var r: std.json.Stringify = .{ .writer = &reference.writer, .options = expected_options }; + try r.beginObject(); + try r.objectField("before"); + try r.write(true); + try r.objectField("result"); + try r.write(expected); + try r.objectField("after"); + try r.write(false); + try r.endObject(); + try std.testing.expectEqualStrings(reference.written(), actual.written()); + try std.testing.expectEqual(@as(usize, 0), s.indent_level); + }; +} + +test "value JSON handles deep mixed records, variants, arrays and pending siblings" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const arena = state.allocator(); + const depth = 32768; + const types = try arena.alloc(air.TypeDecl, depth + 1); + types[0] = .{ .name = "Empty", .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = &.{} } }; + var ty: air.Type = .{ .named = 0 }; + var root: Value = .{ .aggregate = .{ .decl = 0, .variant = 0, .fields = &.{} } }; + for (1..depth + 1) |i| { + const fields = try arena.alloc(Value, 2); + fields[0] = root; + const name = try std.fmt.allocPrint(arena, "T{d}", .{i}); + if (i % 2 == 0) { + const names = try arena.alloc(std.meta.Elem(ValueJson.Fields), 2); + names[0] = .{ .name = "child", .ty = ty }; + names[1] = .{ .name = "tag", .ty = .{ .int = .u8 } }; + types[i] = .{ .name = name, .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"struct" = names } }; + fields[1] = .{ .int = .{ .ty = .u8, .bits = 7 } }; + } else { + const payload = try arena.dupe(air.Type, &.{ ty, .bool }); + const variants = try arena.alloc(std.meta.Elem(@FieldType(@FieldType(air.TypeDecl, "kind"), "enum")), 1); + variants[0] = .{ .name = "wrap", .payload = payload }; + types[i] = .{ .name = name, .span = .{ .line = 1, .col = 1 }, .kind = .{ .@"enum" = variants } }; + fields[1] = .{ .boolean = false }; + } + root = .{ .aggregate = .{ .decl = @intCast(i), .variant = 0, .fields = fields } }; + ty = .{ .named = @intCast(i) }; + if (i % 3 == 0) { + const values = try arena.dupe(Value, &.{root}); + root = .{ .array = values }; + const array = try arena.create(air.Type.Array); + array.* = .{ .elem = ty, .len = 1 }; + ty = .{ .array = array }; + } + } + const module: air.Module = .{ .name = "json.depth", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = types, .functions = &.{} }; + var expected: std.Io.Writer.Allocating = .init(arena); + var i: usize = depth; + while (i != 0) : (i -= 1) { + if (i % 3 == 0) try expected.writer.writeByte('['); + try expected.writer.writeAll(if (i % 2 == 0) "{\"child\":" else "{\"variant\":\"wrap\",\"payload\":["); + } + try expected.writer.writeAll("{}"); + for (1..depth + 1) |level| { + try expected.writer.writeAll(if (level % 2 == 0) ",\"tag\":7}" else ",false]}"); + if (level % 3 == 0) try expected.writer.writeByte(']'); + } + var actual: std.Io.Writer.Allocating = .init(arena); + var s: std.json.Stringify = .{ .writer = &actual.writer }; + try writeValue(module, root, &s); + try std.testing.expectEqualStrings(expected.written(), actual.written()); + // Fail the first and a subsequent metadata allocation; temporary state + // must be released, and no host allocation failure becomes an Aji trap. + for ([_]usize{ 0, 1 }) |fail_index| { + var failing: std.testing.FailingAllocator = .init(std.testing.allocator, .{ .fail_index = fail_index }); + var partial: std.Io.Writer.Allocating = .init(arena); + var p: std.json.Stringify = .{ .writer = &partial.writer }; + try std.testing.expectError(error.WriteFailed, writeValueWithAllocator(module, root, &p, failing.allocator())); + try std.testing.expect(failing.has_induced_failure); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); + } + try std.testing.expect(root.aggregate.fields[1].int.bits == 7); +} + +test "value JSON propagates writer failure at every byte boundary" { + const module: air.Module = .{ .name = "json.fail", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var fields = [_]Value{ .{ .builtin = .{ .which = .alloc_error, .variant = 0 } }, .{ .cap = 8 }, .{ .boolean = false } }; + const expected = "[{\"variant\":\"budget_exceeded\",\"payload\":[]},{\"capability\":\"opaque\"},false]"; + var bytes: [expected.len]u8 = undefined; + for (0..expected.len) |limit| { + var w: std.Io.Writer = .fixed(bytes[0..limit]); + var s: std.json.Stringify = .{ .writer = &w }; + try std.testing.expectError(error.WriteFailed, writeValue(module, .{ .array = &fields }, &s)); + try std.testing.expectEqualStrings(expected[0..limit], w.buffered()); + } + var w: std.Io.Writer = .fixed(&bytes); + var s: std.json.Stringify = .{ .writer = &w }; + try writeValue(module, .{ .array = &fields }, &s); + try std.testing.expectEqualStrings(expected, w.buffered()); +} + +test "value JSON retains outer containers at the stringify nesting boundary" { + var state: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer state.deinit(); + const arena = state.allocator(); + const module: air.Module = .{ .name = "json.outer", .format_version = 0, .lang = .{ 0, 1 }, .features = &.{}, .types = &.{}, .functions = &.{} }; + var leaf = [_]Value{.{ .int = .{ .ty = .u8, .bits = 42 } }}; + var actual: std.Io.Writer.Allocating = .init(arena); + var s: std.json.Stringify = .{ .writer = &actual.writer }; + for (0..256) |_| try s.beginArray(); + try writeValue(module, .{ .array = &leaf }, &s); + try s.write(false); + for (0..256) |_| try s.endArray(); + var expected: std.Io.Writer.Allocating = .init(arena); + try expected.writer.splatByteAll('[', 256); + try expected.writer.writeAll("[42],false"); + try expected.writer.splatByteAll(']', 256); + try std.testing.expectEqualStrings(expected.written(), actual.written()); +} + test "runtime value sizing agrees with static accounting through array wrappers" { var state: std.heap.ArenaAllocator = .init(std.testing.allocator); defer state.deinit(); @@ -3165,6 +3453,16 @@ test "deep returned payload survives per-step collection and execution heap rele v = v.array[0]; } try std.testing.expect(v.int.ty == .u8 and v.int.bits == 0); + var encoded: std.Io.Writer.Allocating = .init(arena); + try writeOutcome(checked.module.?, outcome, null, &encoded.writer); + const prefix = "{\"status\":\"returned\",\"value\":"; + const text = encoded.written(); + try std.testing.expectEqual(prefix.len + 2 * 32768 + 2, text.len); + try std.testing.expectEqualStrings(prefix, text[0..prefix.len]); + for (text[prefix.len..][0..32768]) |byte| try std.testing.expect(byte == '['); + try std.testing.expect(text[prefix.len + 32768] == '0'); + for (text[prefix.len + 32769 ..][0..32768]) |byte| try std.testing.expect(byte == ']'); + try std.testing.expect(text[text.len - 1] == '}'); } } diff --git a/tests/conformance/phase1/run/returned_mixed_json.air b/tests/conformance/phase1/run/returned_mixed_json.air new file mode 100644 index 0000000..eaf96c8 --- /dev/null +++ b/tests/conformance/phase1/run/returned_mixed_json.air @@ -0,0 +1,32 @@ +; expect: run +; result: {"variant":"full","payload":[{"negative":-1,"flags":[false,true],"rows":[[7,14,21],[7,14,21]],"empty":{}},[0,255]]} +; phase: 1 +; spec: docs/spec/07a-air-instructions.md Run result +module runtime.returned_json +air 0 +lang 0.1 +features [arrays, capabilities, effects, linear_aggregates, ownership, resources] + +type @Empty = struct {} +type @Record = struct { negative: i128, flags: array, rows: array, 2>, empty: @Empty } +type @Choice = enum { empty, full(@Record, array) } + +fn @main() -> @Choice +effects [] +entry: + %c_1 = const.u16 7 + %c_2 = const.u16 14 + %c_3 = const.u16 21 + %arr_4 = array.make array(%c_1, %c_2, %c_3) + %c_5 = const.i128 -1 + %c_6 = const.bool false + %c_7 = const.bool true + %arr_8 = array.make array(%c_6, %c_7) + %arr_9 = array.splat array, 2> %arr_4 + %s_10 = struct.make @Empty() + %s_11 = struct.make @Record(%c_5, %arr_8, %arr_9, %s_10) + %c_12 = const.u8 0 + %c_13 = const.u8 255 + %arr_14 = array.make array(%c_12, %c_13) + %e_15 = enum.make @Choice.full(%s_11, %arr_14) + ret %e_15 diff --git a/tests/conformance/source/runtime_values/returned_mixed_json.aji b/tests/conformance/source/runtime_values/returned_mixed_json.aji new file mode 100644 index 0000000..0f16706 --- /dev/null +++ b/tests/conformance/source/runtime_values/returned_mixed_json.aji @@ -0,0 +1,15 @@ +// expect: run +// result: {"variant":"full","payload":[{"negative":-1,"flags":[false,true],"rows":[[7,14,21],[7,14,21]],"empty":{}},[0,255]]} +// phase: 6 +// spec: docs/spec/07a-air-instructions.md Run result; docs/spec/15-source-language.md §5 +module runtime.returned_json + +struct Empty {} +struct Record { negative: i128, flags: [bool; 2], rows: [[u16; 3]; 2], empty: Empty } +enum Choice { empty, full(Record, [u8; 2]) } + +fn main() -> Choice effects [] { + let row = [7u16, 14u16, 21u16]; + let record = Record { negative: -1i128, flags: [false, true], rows: [row; 2], empty: Empty {} }; + return Choice::full(record, [0u8, 255u8]); +}