Phase 2: audit report (P2-10)

- spec 10 §6.1: schema of the format-0 audit report (canonical JSON)
- aji report FILE: entry capabilities, per-function effect graph with
  declared/used/unused effects (fixed point over calls, unsafe stopped
  at trusted callees), intrinsics, allocations, runtime and proven
  checks, unsafe operations; capability kinds; unsafe summary
- golden unit test; runs over the whole conformance corpus without a
  crash
This commit is contained in:
dev committed 2026-10-04 15:03:44 +03:00
1 parent 36e91be84c
commit b00bac5937
7 files changed
+312 -3

No files matched your search

+1 -1
View File
@@ -131,7 +131,7 @@ zig fmt --check build.zig build.zig.zon src tools
Toolchain: Zig 0.17.0. Workflow, layout and definition of done: `CONTRIBUTING.md`. Implementation plan and current phase: `docs/plan/README.md`. Documentation layout and where new documents go: `docs/README.md`. Unresolved spec gaps: `docs/design/open-questions.md` — log new ones there instead of guessing.
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
`aji` CLI output contract: diagnostics are JSON Lines on stdout, human notes on stderr; exit codes 0 accepted/returned, 1 rejected, 2 usage/I/O error, 3 not yet implemented, 4 trapped, 5 execution limit exceeded, 6 not instantiated, 7 blocked. `aji run [--fuel N] [--grant P=KIND[:SCOPE]]… [--stdin T] [--vfs PATH=T]… [--seed N]` runs in the deterministic profile and prints one JSON run record (with captured stdout/stderr and written files); capabilities reach a program only as named `@main` parameters. `--profile hosted` runs against the real OS; its run record goes only to `--result-file PATH` (the program owns stdout/stderr). Hosted smoke tests: `python3 tests/hosted/smoke.py`. `aji report FILE` prints the audit report (spec 10 §6.1: effect graph with used/unused effects, entry capabilities, runtime and proven checks, unsafe sites); `aji check --report unsafe` lists trusted boundaries and unsafe operations; unsafe code lives only in functions declaring `effects [unsafe]` or behind a `trusted "<obligation>"` boundary. `aji features` reports the supported AIR format, language version and features; query it before generating AIR. Never use wall-clock timeouts to end runs or tests; use fuel (spec 11 §7).
## Testing policy
+1 -1
View File
@@ -57,7 +57,7 @@ src/
runtime/ intrinsics: io, fs, net, clock, random (capability-gated)
frontend/ .aji lexer, parser, lowering, formatter (P6)
backend/llvm/ AIR → LLVM IR (P7)
report/ audit artifacts: unsafe, effects, capabilities, contracts
report.zig ✓ audit report (spec 10 §6.1)
ajid/ long-running agent protocol server (P8)
tools/
conformance.zig ✓ conformance runner
@@ -34,7 +34,7 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
| P2-7 | done | Unsafe boundary verifier (RFC 0009: assume, borrow.index.unchecked, trusted, unsafe report) | P2-3 | `src/verifier/unsafe.zig` | E6001 accept/reject |
| P2-8 | done | Runtime intrinsics in the interpreter; virtual filesystem and loopback network for the `deterministic` profile | P2-2 | `src/runtime/` | intrinsic unit tests pass under both profiles; deterministic profile output identical across runs |
| P2-9 | doing | Entry-point capability instantiation (`--grant` done; `aji.toml` `[capabilities]` pending) | P2-5 | `src/runtime/host.zig` | missing grant fails instantiation, not execution (spec 05 §6) |
| P2-10 | todo | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
| P2-10 | done | Reports: effect graph, capability requirements, unsafe sites | P2-4, P2-5, P2-7 | `src/report/` | deterministic JSON report; snapshot test |
| P2-11 | done | Reference programs: hello (real `io.write` if deferred from P0), file-copy, tcp-echo (single task) | P2-8 | `tests/programs/` | all three run; cleanup on every error path verified |
| P2-8a | done | Hosted profile: real console, files and TCP; run record through `--result-file` (spec 11 §8) | P2-8 | `src/interp/host.zig` | hello, file-copy and tcp-echo run against the real OS in CI |
| P2-12 | todo | Phase exit review | all | plan status | exit criterion passes |
@@ -95,3 +95,46 @@ The toolchain should emit an audit artifact containing:
- weak atomic sites;
- lock-order findings;
- contract status.
### 6.1 Audit report, format 0
`aji report FILE` verifies the module and, if it is accepted, prints one canonical JSON document (spec 07a "Canonical record": UTF-8, no whitespace, fixed field order). A rejected module produces its diagnostics and no report. The report is derived from the verified AIR only; it never depends on a run.
```json
{
"report": "audit",
"air": 0,
"module": "<name>",
"features": ["…"],
"entry": {"function": "main", "capabilities": [{"parameter": "out", "kind": "io.write"}]},
"functions": [
{
"name": "<function>",
"trusted": null,
"effects_declared": ["…"],
"effects_used": ["…"],
"effects_unused": ["…"],
"calls": ["<callee>", "…"],
"intrinsics": ["<intrinsic>", "…"],
"allocations": 0,
"runtime_checks": {"overflow": 0, "division": 0, "shift": 0, "cast": 0, "bounds": 0, "assert": 0, "guard": 0},
"proven_checks": {"bounds": 0},
"unsafe_operations": [{"block": "entry", "inst": 0, "op": "borrow.index.unchecked"}]
}
],
"capability_kinds": ["…"],
"unsafe": {"trusted_functions": ["…"], "unsafe_functions": ["…"], "operations": 0}
}
```
Fields:
- `entry`: `@main` and its capability parameters in order, or `null` if there is no `@main`.
- `effects_used`: the effects the function can actually perform — its intrinsics' effects, `mem.alloc` if it allocates, `unsafe` if it contains unsafe operations, and the `effects_used` of its callees — computed to a fixed point over the call graph. A `trusted` function does not propagate `unsafe` to its callers (spec 13 §6.3); its own `effects_used` does contain `unsafe`, which it discharges. `effects_unused` is `effects_declared` minus `effects_used`: declared authority the code never exercises, a candidate for removal.
- `calls`, `intrinsics`: distinct callees and intrinsic names in order of first occurrence; together with `effects_*` this is the effect graph.
- `runtime_checks`: instructions whose safety condition is checked at runtime and may trap — `overflow` (checked `add`/`sub`/`mul`, and `div`/`rem` for signed `MIN / -1`), `division` (`div`/`rem` by zero), `shift` (`shl`/`shr`), `cast` (`cast.checked`), `bounds` (`borrow.index`, `slice.sub`, `slice.split`, `slice.copy`), `assert`, `guard`.
- `proven_checks.bounds`: `borrow.index.proven` instructions, whose check the verifier eliminated.
- `capability_kinds`: distinct capability kinds appearing in any type of the module, sorted.
- All lists of names are in order of first occurrence in the module unless stated otherwise; effect lists are sorted.
Ownership/borrow proof summaries, weak atomic sites, lock-order findings and contract status are added to this document by the phases that introduce them, as new fields; existing fields keep their meaning.
+18
View File
@@ -27,6 +27,7 @@ const usage =
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
\\ --seed N; --profile hosted uses the real OS and
\\ writes the record only to --result-file PATH
\\ report <file.air> verify, then print the audit report (spec 10 §6.1)
\\ codes list diagnostic codes as JSON Lines
\\ features print supported AIR format, language version and features
\\ explain <code> show one diagnostic code
@@ -63,6 +64,23 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try out.print("aji {s} (air format {d})\n", .{ aji.version, aji.air.format_version });
return .accepted;
}
if (std.mem.eql(u8, cmd, "report")) {
if (args.len != 3) return usageError("report takes exactly one file");
const path = args[2];
const source = std.Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 << 20)) catch |err| {
std.debug.print("aji: cannot read {s}: {t}\n", .{ path, err });
return .usage;
};
const result = try aji.check.checkAir(arena, path, source);
for (result.diagnostics) |d| {
try d.writeJson(out);
try out.writeByte('\n');
}
const module = result.module orelse return .rejected;
try aji.report.write(arena, module, out);
try out.writeByte('\n');
return .accepted;
}
if (std.mem.eql(u8, cmd, "features")) {
var s: std.json.Stringify = .{ .writer = out };
try s.write(.{
+247
View File
@@ -0,0 +1,247 @@
//! Audit report (spec 10 §6.1): one canonical JSON document derived from a
//! verified module. Never depends on a run.
const std = @import("std");
const air = @import("air.zig");
const unsafe_ = @import("verifier/unsafe.zig");
const Writer = std.Io.Writer;
const Checks = struct {
overflow: u32 = 0,
division: u32 = 0,
shift: u32 = 0,
cast: u32 = 0,
bounds: u32 = 0,
assert: u32 = 0,
guard: u32 = 0,
};
const FnInfo = struct {
calls: std.ArrayList([]const u8) = .empty,
intrinsics: std.ArrayList([]const u8) = .empty,
allocations: u32 = 0,
checks: Checks = .{},
proven_bounds: u32 = 0,
unsafe_ops: std.ArrayList(struct { block: []const u8, inst: u32, op: []const u8 }) = .empty,
/// Effects performed directly (intrinsics, allocation, unsafe operations).
direct: std.ArrayList([]const u8) = .empty,
/// Fixed point of `direct` over callees.
used: std.ArrayList([]const u8) = .empty,
};
fn contains(list: []const []const u8, s: []const u8) bool {
for (list) |x| if (std.mem.eql(u8, x, s)) return true;
return false;
}
fn addOnce(arena: std.mem.Allocator, list: *std.ArrayList([]const u8), s: []const u8) !bool {
if (contains(list.items, s)) return false;
try list.append(arena, s);
return true;
}
fn lessThan(_: void, a: []const u8, b: []const u8) bool {
return std.mem.lessThan(u8, a, b);
}
fn sorted(arena: std.mem.Allocator, items: []const []const u8) ![]const []const u8 {
const out = try arena.dupe([]const u8, items);
std.mem.sort([]const u8, out, {}, lessThan);
return out;
}
fn analyze(arena: std.mem.Allocator, m: air.Module, f: air.Function) !FnInfo {
var info: FnInfo = .{};
for (f.blocks) |b| for (b.insts, 0..) |inst, ii| {
switch (inst.op) {
.call => |x| _ = try addOnce(arena, &info.calls, m.functions[x.callee].name),
.intrinsic => |x| {
const reg = air.authority.intrinsics[x.index];
_ = try addOnce(arena, &info.intrinsics, reg.name);
if (reg.effect) |e| _ = try addOnce(arena, &info.direct, e);
},
.own_new, .own_array, .region_new, .region_array, .region_create => {
info.allocations += 1;
_ = try addOnce(arena, &info.direct, "mem.alloc");
},
.arith => |x| if (x.mode == .checked) switch (x.op) {
.add, .sub, .mul => info.checks.overflow += 1,
.div, .rem => {
info.checks.division += 1;
if (x.ty.signed()) info.checks.overflow += 1;
},
},
.bit => |x| if (x.op == .shl or x.op == .shr) {
info.checks.shift += 1;
},
.cast => |x| if (x.mode == .checked) {
info.checks.cast += 1;
},
.assert => info.checks.assert += 1,
.guard => info.checks.guard += 1,
.borrow_index => |x| {
if (x.unchecked) {} else if (x.proven) info.proven_bounds += 1 else info.checks.bounds += 1;
},
.slice_sub, .slice_split, .slice_copy => info.checks.bounds += 1,
else => {},
}
if (unsafe_.unsafeOp(m, inst.op)) |what| {
// Calls of unsafe functions propagate through `effects_used`.
if (inst.op != .call) {
try info.unsafe_ops.append(arena, .{ .block = b.name, .inst = @intCast(ii), .op = what });
_ = try addOnce(arena, &info.direct, "unsafe");
}
}
};
return info;
}
pub fn write(arena: std.mem.Allocator, m: air.Module, w: *Writer) !void {
const infos = try arena.alloc(FnInfo, m.functions.len);
for (m.functions, infos) |f, *i| i.* = try analyze(arena, m, f);
// effects_used: fixed point over the call graph; a trusted function
// does not pass `unsafe` on (spec 13 §6.3).
for (infos) |*i| for (i.direct.items) |e| {
_ = try addOnce(arena, &i.used, e);
};
var changed = true;
while (changed) {
changed = false;
for (m.functions, infos) |f, *i| {
for (f.blocks) |b| for (b.insts) |inst| if (inst.op == .call) {
const callee = inst.op.call.callee;
for (infos[callee].used.items) |e| {
// A trusted callee is the boundary: `unsafe` stops there.
if (m.functions[callee].trusted != null and std.mem.eql(u8, e, "unsafe")) continue;
if (try addOnce(arena, &i.used, e)) changed = true;
}
};
}
}
var s: std.json.Stringify = .{ .writer = w };
try s.beginObject();
try s.objectField("report");
try s.write("audit");
try s.objectField("air");
try s.write(m.format_version);
try s.objectField("module");
try s.write(m.name);
try s.objectField("features");
try s.write(m.features);
try s.objectField("entry");
if (m.functionIndex("main")) |mi| {
const f = m.functions[mi];
try s.beginObject();
try s.objectField("function");
try s.write("main");
try s.objectField("capabilities");
try s.beginArray();
for (f.params) |p| if (p.ty == .cap) {
try s.write(.{ .parameter = f.values[p.value].name, .kind = air.authority.kinds[p.ty.cap].name });
};
try s.endArray();
try s.endObject();
} else try s.write(null);
try s.objectField("functions");
try s.beginArray();
for (m.functions, infos) |f, i| {
try s.beginObject();
try s.objectField("name");
try s.write(f.name);
try s.objectField("trusted");
try s.write(f.trusted);
try s.objectField("effects_declared");
try s.write(try sorted(arena, f.effects));
try s.objectField("effects_used");
try s.write(try sorted(arena, i.used.items));
var unused: std.ArrayList([]const u8) = .empty;
for (f.effects) |e| if (!contains(i.used.items, e)) try unused.append(arena, e);
try s.objectField("effects_unused");
try s.write(try sorted(arena, unused.items));
try s.objectField("calls");
try s.write(i.calls.items);
try s.objectField("intrinsics");
try s.write(i.intrinsics.items);
try s.objectField("allocations");
try s.write(i.allocations);
try s.objectField("runtime_checks");
try s.write(i.checks);
try s.objectField("proven_checks");
try s.write(.{ .bounds = i.proven_bounds });
try s.objectField("unsafe_operations");
try s.write(i.unsafe_ops.items);
try s.endObject();
}
try s.endArray();
// Capability kinds appearing in any type of the module, sorted.
var kinds: std.ArrayList([]const u8) = .empty;
const visit = struct {
fn go(arena_: std.mem.Allocator, list: *std.ArrayList([]const u8), t: air.Type) !void {
if (t == .cap) _ = try addOnce(arena_, list, air.authority.kinds[t.cap].name);
if (t.inner()) |inner| try go(arena_, list, inner);
}
}.go;
for (m.types) |d| switch (d.kind) {
.@"struct" => |fs| for (fs) |fd| try visit(arena, &kinds, fd.ty),
.@"enum" => |vs| for (vs) |v| for (v.payload) |t| try visit(arena, &kinds, t),
};
for (m.functions) |f| {
for (f.params) |p| try visit(arena, &kinds, p.ty);
try visit(arena, &kinds, f.ret);
for (f.blocks) |b| for (b.params) |p| try visit(arena, &kinds, p.ty);
}
try s.objectField("capability_kinds");
try s.write(try sorted(arena, kinds.items));
var trusted: std.ArrayList([]const u8) = .empty;
var unsafe_fns: std.ArrayList([]const u8) = .empty;
var ops: u32 = 0;
for (m.functions, infos) |f, i| {
if (f.trusted != null) try trusted.append(arena, f.name);
if (unsafe_.declaresUnsafe(f)) try unsafe_fns.append(arena, f.name);
ops += @intCast(i.unsafe_ops.items.len);
}
try s.objectField("unsafe");
try s.write(.{ .trusted_functions = trusted.items, .unsafe_functions = unsafe_fns.items, .operations = ops });
try s.endObject();
}
test "audit report" {
var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
const src =
\\module demo
\\air 0
\\lang 0.1
\\features [arrays, capabilities, effects, ownership, resources, unsafe]
\\fn @main(%out: cap<io.write>, %fs: cap<fs.read>) -> u8
\\effects [fs.read, io.write]
\\entry:
\\ %a = const.u8 1
\\ %b = add.checked.u8 %a, %a
\\ %r = call @peek(%b)
\\ ret %r
\\fn @peek(%x: u8) -> u8
\\effects []
\\trusted "only reads"
\\entry:
\\ %c = const.bool true
\\ assume %c
\\ ret %x
\\
;
const parsed = try air.parse.parse(arena, "demo.air", src);
try std.testing.expectEqual(@as(usize, 0), parsed.diagnostics.len);
var out: Writer.Allocating = .init(arena);
try write(arena, parsed.module.?, &out.writer);
try std.testing.expectEqualStrings(
\\{"report":"audit","air":0,"module":"demo","features":["arrays","capabilities","effects","ownership","resources","unsafe"],"entry":{"function":"main","capabilities":[{"parameter":"out","kind":"io.write"},{"parameter":"fs","kind":"fs.read"}]},"functions":[{"name":"main","trusted":null,"effects_declared":["fs.read","io.write"],"effects_used":[],"effects_unused":["fs.read","io.write"],"calls":["peek"],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":1,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[]},{"name":"peek","trusted":"only reads","effects_declared":[],"effects_used":["unsafe"],"effects_unused":[],"calls":[],"intrinsics":[],"allocations":0,"runtime_checks":{"overflow":0,"division":0,"shift":0,"cast":0,"bounds":0,"assert":0,"guard":0},"proven_checks":{"bounds":0},"unsafe_operations":[{"block":"entry","inst":1,"op":"assume"}]}],"capability_kinds":["fs.read","io.write"],"unsafe":{"trusted_functions":["peek"],"unsafe_functions":[],"operations":1}}
, out.written());
}
+1
View File
@@ -15,6 +15,7 @@ pub const air = @import("air.zig");
pub const verifier = @import("verifier.zig");
pub const interp = @import("interp.zig");
pub const check = @import("check.zig");
pub const report = @import("report.zig");
test {
@import("std").testing.refAllDecls(@This());