Phase 2: hosted profile (P2-8a)

- src/interp/host.zig: real console, files (scope checked before any
  host call, positional reads/writes, append from file size) and TCP
  through std.Io; monotonic clock and host CSPRNG; host errors mapped
  to the closed io_error set; open handles released at the end of the
  instance
- interpreter dispatches intrinsics to the host or the deterministic
  world; never reports blocked in the hosted profile
- CLI: --profile hosted; the program owns stdout/stderr, the run record
  goes to --result-file, otherwise a human summary on stderr
- spec 11 §8.0: host error mapping table
- tests/hosted/smoke.py (file copy, scope denial, stdin->stdout, TCP
  echo on a free port) runs in CI
- works around Zig 0.17 net.Stream.read not compiling by using
  readWithControl
This commit is contained in:
dev committed 2026-10-04 14:46:40 +03:00
1 parent 008654999e
commit 36e91be84c
10 files changed
+530 -51

No files matched your search

+1
View File
@@ -18,3 +18,4 @@ jobs:
- run: zig fmt --check build.zig build.zig.zon src tools
- run: zig build test --summary all
- run: zig build conformance
- run: zig build && python3 tests/hosted/smoke.py
+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` is specified but not implemented yet. `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 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
+3 -2
View File
@@ -13,11 +13,12 @@ zig build # build ./zig-out/bin/aji
zig build test # unit tests (includes registry ↔ docs sync check)
zig build conformance # conformance suite, see tests/conformance/README.md
zig build run -- check f.air # verify a text AIR module
zig build run -- run f.air # verify and execute @main
zig build run -- run f.air # verify and execute @main (deterministic profile)
python3 tests/hosted/smoke.py # hosted profile against the real OS
zig fmt --check build.zig src tools
```
CI runs `zig fmt --check`, `zig build test` and `zig build conformance` on every push and pull request.
CI runs `zig fmt --check`, `zig build test`, `zig build conformance` and the hosted smoke tests on every push and pull request.
## Repository layout
+1 -1
View File
@@ -13,7 +13,7 @@ Non-normative. How the reference implementation is tested. Policy (what must be
| Schedule stress | via runner flags (from P3) | `zig build conformance -- --schedules=N` | randomized and systematic interleavings |
| Native parity | (from P7) | `zig build parity` | interpreter and native backend agree on the whole corpus |
Unit and conformance exist today; conformance covers accept, reject and run tests.
Unit, conformance and hosted smoke tests exist today; conformance covers accept, reject and run tests in the deterministic profile, and `tests/hosted/smoke.py` checks observable effects (files, streams, sockets) of hosted runs.
## Conformance tests
@@ -32,11 +32,11 @@ Out: tasks, threads, async I/O (P3); FFI to native code (P7).
| P2-5 | done | Capability verifier: unforgeability, narrowing, transfer rules (E3201, E3202, instantiation) | P2-1 | `src/verifier/caps.zig` | E3201, E3202 accept/reject |
| P2-6 | done | Linear resource and typestate verifier | P2-3 | `src/verifier/resource.zig` | E3001, E3002 accept/reject; leak on an error path detected |
| 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 | doing | 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-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-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 | todo | (after heap and regions, unsafe) 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-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 |
## Conformance tests to add
+19
View File
@@ -138,6 +138,25 @@ environment outcome: not_instantiated, limit_exceeded, blocked
**Result channel.** In the `hosted` profile the program owns stdout and stderr, so the run record cannot share them unambiguously. The machine-readable record goes to a separate channel: `aji run --profile hosted --result-file PATH` (a `--result-fd N` form may follow; `ajid` has its own control channel). Without `--result-file` the CLI may print a human-readable summary on stderr after the program ends; that summary is not a machine interface.
### 8.0 Host errors in the hosted profile
The `hosted` profile maps host failures to `io_error` (spec 06 §7) as follows; anything not listed is `other`, and no host error number is observable by the program:
| Host condition | `io_error` |
|---|---|
| file or path component not found, not a directory | `not_found` |
| access or permission denied, read-only file system | `permission_denied` |
| path already exists (exclusive creation) | `already_exists` |
| bad or too long path name, path is a directory | `invalid_input` |
| no space left, disk quota exceeded | `no_space` |
| broken pipe | `broken_pipe` |
| connection refused | `connection_refused` |
| connection reset by peer | `connection_reset` |
| address in use | `address_in_use` |
| address not available | `address_unavailable` |
Paths outside a capability's scope and malformed paths or addresses are rejected before any host call (`permission_denied`, `invalid_input`), exactly as in the `deterministic` profile. Host handles still open when the execution instance ends are released by the runtime; this is not observable by the program (spec 06 §6, invariant 2).
### 8.1 Deterministic random generator
The `deterministic` profile uses xoshiro256\*\* with SplitMix64 seeding. All arithmetic is on unsigned 64-bit integers, wrapping modulo 2^64; `rotl(x, k)` is `(x << k) | (x >> (64 − k))`.
+176
View File
@@ -0,0 +1,176 @@
//! The `hosted` execution profile (spec 11 §8): the real console, file
//! system and TCP, the host's monotonic clock and CSPRNG.
//!
//! Capability scopes are enforced here, before any host call: a path outside
//! the scope never reaches the operating system. Host errors are mapped to
//! the closed `io_error` set; error numbers never reach the program.
const std = @import("std");
const air = @import("../air.zig");
const world = @import("world.zig");
const Io = std.Io;
const IoError = world.Error;
pub const Handle = union(enum) {
file: struct { file: Io.File, pos: u64 },
listener: Io.net.Server,
stream: Io.net.Stream,
closed,
};
pub const Host = struct {
arena: std.mem.Allocator,
io: Io,
handles: std.ArrayList(Handle) = .empty,
fn add(h: *Host, x: Handle) !u32 {
try h.handles.append(h.arena, x);
return @intCast(h.handles.items.len - 1);
}
/// Host error to `io_error` (spec 06 §7). Unlisted errors are `other`;
/// `timed_out` is reserved for explicit timeouts and never produced here.
pub fn map(err: anyerror) IoError {
return switch (err) {
error.FileNotFound, error.NotDir => .not_found,
error.AccessDenied, error.PermissionDenied, error.ReadOnlyFileSystem => .permission_denied,
error.PathAlreadyExists => .already_exists,
error.BadPathName, error.NameTooLong, error.IsDir => .invalid_input,
error.NoSpaceLeft, error.DiskQuota => .no_space,
error.BrokenPipe => .broken_pipe,
error.ConnectionRefused => .connection_refused,
error.ConnectionResetByPeer => .connection_reset,
error.AddressInUse => .address_in_use,
error.AddressUnavailable, error.AddressNotAvailable => .address_unavailable,
else => .other,
};
}
// ------------------------------------------------------------ console
pub fn writeOut(h: *Host, err_stream: bool, bytes: []const u8) ?IoError {
const f: Io.File = if (err_stream) .stderr() else .stdout();
f.writeStreamingAll(h.io, bytes) catch |e| return map(e);
return null;
}
pub fn readIn(h: *Host, buf: []u8) union(enum) { ok: usize, err: IoError } {
const n = Io.File.stdin().readStreaming(h.io, &.{buf}) catch |e| switch (e) {
error.EndOfStream => return .{ .ok = 0 },
else => return .{ .err = map(e) },
};
return .{ .ok = n };
}
// ------------------------------------------------------------ files
pub fn open(h: *Host, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !world.Opened {
if (!world.World.validPath(path)) return .{ .err = .invalid_input };
if (!world.World.within(scope, path)) return .{ .err = .permission_denied };
const file: Io.File = switch (mode) {
.file_read => Io.Dir.openFileAbsolute(h.io, path, .{ .allow_directory = false }),
.file_write => Io.Dir.createFileAbsolute(h.io, path, .{}),
.file_append => Io.Dir.createFileAbsolute(h.io, path, .{ .truncate = false }),
else => unreachable,
} catch |e| return .{ .err = map(e) };
var pos: u64 = 0;
if (mode == .file_append) {
const st = file.stat(h.io) catch |e| {
file.close(h.io);
return .{ .err = map(e) };
};
pos = st.size;
}
return .{ .ok = try h.add(.{ .file = .{ .file = file, .pos = pos } }) };
}
pub fn fileRead(h: *Host, hd: u32, buf: []u8) union(enum) { ok: usize, err: IoError } {
const f = &h.handles.items[hd].file;
// Positional reads report end of file as 0 bytes.
const n = f.file.readPositional(h.io, &.{buf}, f.pos) catch |e| return .{ .err = map(e) };
f.pos += n;
return .{ .ok = n };
}
pub fn fileWrite(h: *Host, hd: u32, bytes: []const u8) ?IoError {
const f = &h.handles.items[hd].file;
f.file.writePositionalAll(h.io, bytes, f.pos) catch |e| return map(e);
f.pos += bytes.len;
return null;
}
pub fn sync(h: *Host, hd: u32) ?IoError {
h.handles.items[hd].file.file.sync(h.io) catch |e| return map(e);
return null;
}
pub fn close(h: *Host, hd: u32) void {
switch (h.handles.items[hd]) {
.file => |f| f.file.close(h.io),
.listener => |*l| l.deinit(h.io),
.stream => |s| s.close(h.io),
.closed => {},
}
h.handles.items[hd] = .closed;
}
// ------------------------------------------------------------ TCP
fn parseAddr(addr: []const u8) ?Io.net.IpAddress {
if (!world.World.validAddr(addr)) return null;
const colon = std.mem.lastIndexOfScalar(u8, addr, ':').?;
const port = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return null;
return Io.net.IpAddress.parseIp4(addr[0..colon], port) catch null;
}
pub fn listen(h: *Host, addr: []const u8) !world.Opened {
const a = parseAddr(addr) orelse return .{ .err = .invalid_input };
const server = a.listen(h.io, .{}) catch |e| return .{ .err = map(e) };
return .{ .ok = try h.add(.{ .listener = server }) };
}
pub fn connect(h: *Host, addr: []const u8) !world.Opened {
const a = parseAddr(addr) orelse return .{ .err = .invalid_input };
const stream = a.connect(h.io, .{ .mode = .stream }) catch |e| return .{ .err = map(e) };
return .{ .ok = try h.add(.{ .stream = stream }) };
}
pub fn accept(h: *Host, hd: u32) !world.Opened {
const stream = h.handles.items[hd].listener.accept(h.io) catch |e| return .{ .err = map(e) };
return .{ .ok = try h.add(.{ .stream = stream }) };
}
pub fn recv(h: *Host, hd: u32, buf: []u8) union(enum) { ok: usize, err: IoError } {
var bufs = [_][]u8{buf};
// `Stream.read` does not compile in Zig 0.17 (it destructures a
// struct); `readWithControl` with no control buffer is equivalent.
const r = h.handles.items[hd].stream.readWithControl(h.io, &bufs, &.{}) catch |e| return .{ .err = map(e) };
return .{ .ok = r.data_len };
}
pub fn send(h: *Host, hd: u32, bytes: []const u8) ?IoError {
var buf: [4096]u8 = undefined;
var w = h.handles.items[hd].stream.writer(h.io, &buf);
w.interface.writeAll(bytes) catch return map(w.err orelse error.Unexpected);
w.interface.flush() catch return map(w.err orelse error.Unexpected);
return null;
}
// ------------------------------------------------------------ clock and random
pub fn monotonic(h: *Host) u64 {
const t = Io.Timestamp.now(h.io, .awake);
return @intCast(@max(t.nanoseconds, 0) & std.math.maxInt(u64));
}
pub fn fill(h: *Host, buf: []u8) void {
h.io.random(buf);
}
/// Releases host handles left open when the execution instance ends
/// (spec 06 §6, invariant 2: not observable by the program).
pub fn deinit(h: *Host) void {
for (h.handles.items, 0..) |x, i| if (x != .closed) h.close(@intCast(i));
}
};
+66 -35
View File
@@ -12,6 +12,7 @@ const std = @import("std");
const air = @import("../air.zig");
const diag = @import("../diag.zig");
const world_mod = @import("world.zig");
const host_mod = @import("host.zig");
const budget = @import("../verifier/budget.zig");
pub const WorldOptions = world_mod.Options;
@@ -117,8 +118,10 @@ pub const Options = struct {
grants: []const Grant = &.{},
/// Inputs of the deterministic world (spec 11 §8).
world: WorldOptions = .{},
/// Receives the run's observable output.
/// Receives the run's observable output (deterministic profile).
output: ?*Output = null,
/// Non-null selects the `hosted` profile (spec 11 §8): real I/O through `io`.
hosted: ?std.Io = null,
};
/// Observable output of a run in the deterministic profile.
@@ -138,6 +141,8 @@ pub fn run(arena: std.mem.Allocator, module: air.Module, entry: []const u8, opti
const f = module.functions[idx];
for (f.params) |p| if (p.ty != .cap) return error.EntryNotFound;
var m: Machine = .{ .arena = arena, .module = module, .fuel = options.fuel, .world = try .init(arena, options.world) };
if (options.hosted) |io| m.host = .{ .arena = arena, .io = io };
defer if (m.host) |*hs| hs.deinit();
defer if (options.output) |o| {
o.* = m.output() catch .{ .stdout = "", .stderr = "", .files = &.{} };
};
@@ -229,6 +234,7 @@ const Machine = struct {
/// Host authority table; capabilities index into it.
authorities: std.ArrayList(Authority) = .empty,
world: world_mod.World,
host: ?host_mod.Host = null,
owners: std.AutoHashMapUnmanaged(*Value.Cell, OwnInfo) = .empty,
regions: std.ArrayList(Region) = .empty,
/// Instructions executed so far.
@@ -645,81 +651,106 @@ const Machine = struct {
return v[xx.args[i]];
}
}.at;
const W = world_mod.World;
var results: [1]Value = undefined;
var n_results: usize = 0;
var result: ?Value = null;
var failure: ?world_mod.Error = null;
const is = struct {
fn eq(a: []const u8, b: []const u8) bool {
return std.mem.eql(u8, a, b);
}
}.eq;
// `m.host` is the hosted profile; otherwise the deterministic world.
if (is(name, "clock.monotonic")) {
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = m.steps } });
const now = if (m.host) |*hs| hs.monotonic() else m.steps;
return bind(vals, inst.result, .{ .int = .{ .ty = .u64, .bits = now } });
} else if (is(name, "random.fill")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
m.world.fill(buf);
if (m.host) |*hs| hs.fill(buf) else m.world.fill(buf);
fillSlice(arg(vals, x, 1), buf);
return .next;
} else if (is(name, "io.stdout_write") or is(name, "io.stderr_write")) {
try m.world.writeOut(is(name, "io.stderr_write"), try m.bytesOf(arg(vals, x, 1)));
const bytes = try m.bytesOf(arg(vals, x, 1));
const err_stream = is(name, "io.stderr_write");
if (m.host) |*hs| failure = hs.writeOut(err_stream, bytes) else try m.world.writeOut(err_stream, bytes);
} else if (is(name, "io.stdin_read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.readIn(buf);
const n: usize = if (m.host) |*hs| switch (hs.readIn(buf)) {
.ok => |k| k,
.err => |e| blk: {
failure = e;
break :blk 0;
},
} else m.world.readIn(buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
result = .{ .int = .{ .ty = .usize, .bits = n } };
} else if (is(name, "fs.open_read") or is(name, "fs.create") or is(name, "fs.open_append")) {
const scope = m.authorities.items[arg(vals, x, 0).cap].scope;
const mode: air.authority.Resource = if (is(name, "fs.open_read")) .file_read else if (is(name, "fs.create")) .file_write else .file_append;
switch (try m.world.open(scope, try m.bytesOf(arg(vals, x, 1)), mode)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
const path = try m.bytesOf(arg(vals, x, 1));
switch (if (m.host) |*hs| try hs.open(scope, path, mode) else try m.world.open(scope, path, mode)) {
.ok => |hd| result = .{ .resource = hd },
.err => |e| failure = e,
}
} else if (is(name, "fs.read")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.fileRead(resourceOf(arg(vals, x, 0)), buf);
const hd = resourceOf(arg(vals, x, 0));
const n: usize = if (m.host) |*hs| switch (hs.fileRead(hd, buf)) {
.ok => |k| k,
.err => |e| blk: {
failure = e;
break :blk 0;
},
} else m.world.fileRead(hd, buf);
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
result = .{ .int = .{ .ty = .usize, .bits = n } };
} else if (is(name, "fs.write_all")) {
try m.world.fileWrite(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
const hd = resourceOf(arg(vals, x, 0));
const bytes = try m.bytesOf(arg(vals, x, 1));
if (m.host) |*hs| failure = hs.fileWrite(hd, bytes) else try m.world.fileWrite(hd, bytes);
} else if (is(name, "fs.sync")) {
// Durable by construction in the in-memory file system.
// The in-memory file system is durable by construction.
if (m.host) |*hs| failure = hs.sync(resourceOf(arg(vals, x, 0)));
} else if (is(name, "fs.close") or is(name, "net.close_stream") or is(name, "net.close_listener")) {
m.world.close(arg(vals, x, 0).resource);
if (m.host) |*hs| hs.close(arg(vals, x, 0).resource) else m.world.close(arg(vals, x, 0).resource);
} else if (is(name, "net.listen") or is(name, "net.connect")) {
const addr = try m.bytesOf(arg(vals, x, 1));
switch (if (is(name, "net.listen")) try m.world.listen(addr) else try m.world.connect(addr)) {
.ok => |hd| {
results[0] = .{ .resource = hd };
n_results = 1;
},
const listen = is(name, "net.listen");
const r = if (m.host) |*hs|
(if (listen) try hs.listen(addr) else try hs.connect(addr))
else
(if (listen) try m.world.listen(addr) else try m.world.connect(addr));
switch (r) {
.ok => |hd| result = .{ .resource = hd },
.err => |e| failure = e,
}
} else if (is(name, "net.accept")) {
const s = m.world.accept(resourceOf(arg(vals, x, 0))) orelse return .blocked;
results[0] = .{ .resource = s };
n_results = 1;
const hd = resourceOf(arg(vals, x, 0));
if (m.host) |*hs| switch (try hs.accept(hd)) {
.ok => |s| result = .{ .resource = s },
.err => |e| failure = e,
} else result = .{ .resource = m.world.accept(hd) orelse return .blocked };
} else if (is(name, "net.recv")) {
const buf = try m.arena.alloc(u8, arg(vals, x, 1).slice.len);
const n = m.world.recv(resourceOf(arg(vals, x, 0)), buf) orelse return .blocked;
const hd = resourceOf(arg(vals, x, 0));
const n: usize = if (m.host) |*hs| switch (hs.recv(hd, buf)) {
.ok => |k| k,
.err => |e| blk: {
failure = e;
break :blk 0;
},
} else m.world.recv(hd, buf) orelse return .blocked;
fillSlice(arg(vals, x, 1), buf[0..n]);
results[0] = .{ .int = .{ .ty = .usize, .bits = n } };
n_results = 1;
result = .{ .int = .{ .ty = .usize, .bits = n } };
} else if (is(name, "net.send_all")) {
failure = try m.world.send(resourceOf(arg(vals, x, 0)), try m.bytesOf(arg(vals, x, 1)));
const hd = resourceOf(arg(vals, x, 0));
const bytes = try m.bytesOf(arg(vals, x, 1));
failure = if (m.host) |*hs| hs.send(hd, bytes) else try m.world.send(hd, bytes);
} else unreachable; // every registered intrinsic is handled above
_ = W;
if (failure) |e| {
vals[f.blocks[x.err.?].params[0].value] = .{ .builtin = .{ .which = .io_error, .variant = @backingInt(e) } };
return .{ .jump = x.err.? };
}
for (f.blocks[x.ok.?].params, results[0..n_results]) |p, r| vals[p.value] = r;
if (result) |r| vals[f.blocks[x.ok.?].params[0].value] = r;
return .{ .jump = x.ok.? };
}
+19 -10
View File
@@ -25,8 +25,8 @@ const usage =
\\ --fuel stops after N executed instructions;
\\ --grant binds capability parameter P of @main;
\\ deterministic world: --stdin TEXT, --vfs PATH=TEXT,
\\ --seed N; --result-file PATH also writes the record;
\\ --profile hosted is not implemented yet
\\ --seed N; --profile hosted uses the real OS and
\\ writes the record only to --result-file PATH
\\ codes list diagnostic codes as JSON Lines
\\ features print supported AIR format, language version and features
\\ explain <code> show one diagnostic code
@@ -104,10 +104,8 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
try grants.append(arena, parseGrant(value) orelse return usageError("--grant takes <parameter>=<kind>[:<scope>]"));
} else if (std.mem.eql(u8, flag, "--profile")) {
if (std.mem.eql(u8, value, "hosted")) {
std.debug.print("aji: not implemented yet: hosted profile\n", .{});
return .unimplemented;
}
if (!std.mem.eql(u8, value, "deterministic")) return usageError("--profile takes deterministic or hosted");
options.hosted = io;
} else if (!std.mem.eql(u8, value, "deterministic")) return usageError("--profile takes deterministic or hosted");
} else if (std.mem.eql(u8, flag, "--stdin")) {
options.world.stdin = value;
} else if (std.mem.eql(u8, flag, "--vfs")) {
@@ -137,17 +135,28 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
if (report.status == .accepted and std.mem.eql(u8, cmd, "run")) {
const module = report.module.?;
var output: aji.interp.Output = undefined;
options.output = &output;
const hosted = options.hosted != null;
// In the hosted profile the program owns stdout and stderr: flush
// what the toolchain wrote before the program starts.
if (hosted) try out.flush() else options.output = &output;
const outcome = aji.interp.run(arena, module, "main", options) catch |err| switch (err) {
error.EntryNotFound => return usageError("module has no @main whose parameters are all capabilities"),
error.DuplicateGrant => return usageError("a parameter is granted more than once"),
else => |e| return e,
};
try aji.interp.writeOutcome(module, outcome, output, out);
try out.writeByte('\n');
const captured: ?aji.interp.Output = if (hosted) null else output;
if (!hosted) {
try aji.interp.writeOutcome(module, outcome, captured, out);
try out.writeByte('\n');
} else if (result_file == null) {
// Human summary only; the machine interface is --result-file (spec 11 §8).
var rec: std.Io.Writer.Allocating = .init(arena);
try aji.interp.writeOutcome(module, outcome, null, &rec.writer);
std.debug.print("aji: {s}\n", .{rec.written()});
}
if (result_file) |rpath| {
var rec: std.Io.Writer.Allocating = .init(arena);
try aji.interp.writeOutcome(module, outcome, output, &rec.writer);
try aji.interp.writeOutcome(module, outcome, captured, &rec.writer);
try rec.writer.writeByte('\n');
std.Io.Dir.cwd().writeFile(io, .{ .sub_path = rpath, .data = rec.written() }) catch |err| {
std.debug.print("aji: cannot write {s}: {t}\n", .{ rpath, err });
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""Hosted-profile smoke tests (spec 11 §8): run AIR programs against the real OS.
Unlike the conformance suite these runs are not deterministic (real files,
real sockets, real clock), so they check observable effects instead of run
records. Usage: python3 tests/hosted/smoke.py [path/to/aji]
"""
import json
import os
import socket
import subprocess
import sys
import tempfile
AJI = sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/aji"
HEADER = "module smoke\nair 0\nlang 0.1\nfeatures [arrays, capabilities, effects, ownership, resources]\n\n"
def text(name, s):
"""Instructions that put the bytes of `s` into local %name (entry block)."""
b = s.encode()
out = [f" %{name} = local.alloc array<u8, {len(b)}>", f" local.zero %{name}", f" %{name}_m = borrow.mut %{name}"]
for i, c in enumerate(b):
out += [f" %{name}_i{i} = const.usize {i}", f" %{name}_c{i} = const.u8 {c}",
f" %{name}_e{i} = borrow.index %{name}_m, %{name}_i{i}", f" store %{name}_e{i}, %{name}_c{i}",
f" borrow.end %{name}_e{i}"]
out += [f" borrow.end %{name}_m", f" %{name}_r = borrow.ref %{name}", f" %{name}_s = slice.make %{name}_r"]
return "\n".join(out)
def end(name):
return f" borrow.end %{name}_s\n borrow.end %{name}_r"
def run(tmp, name, program, grants, stdin=b""):
path = os.path.join(tmp, name + ".air")
with open(path, "w") as f:
f.write(HEADER + program)
result = os.path.join(tmp, name + ".json")
cmd = [AJI, "run", "--profile", "hosted", "--result-file", result, "--fuel", "10000000"]
for g in grants:
cmd += ["--grant", g]
p = subprocess.run(cmd + [path], input=stdin, capture_output=True, timeout=60)
with open(result) as f:
record = json.load(f)
return p, record
def check(cond, what):
if not cond:
print("FAIL", what)
sys.exit(1)
print("ok ", what)
def main():
with tempfile.TemporaryDirectory() as tmp:
tmp = os.path.realpath(tmp)
src_dir, dst_dir = os.path.join(tmp, "in"), os.path.join(tmp, "out")
os.makedirs(src_dir)
os.makedirs(dst_dir)
payload = b"hosted Aji copies real files.\n" * 40
with open(os.path.join(src_dir, "data.bin"), "wb") as f:
f.write(payload)
# File copy through scoped capabilities.
prog = f"""fn @main(%src: cap<fs.read>, %dst: cap<fs.write>) -> void
effects [fs.read, fs.write]
entry:
{text('ip', src_dir + '/data.bin')}
{text('op', dst_dir + '/copy.bin')}
%buf = local.alloc array<u8, 64>
local.zero %buf
intrinsic fs.open_read(%src, %ip_s), ok -> @opened_in, err -> @fail
opened_in(%in: file<read>):
intrinsic fs.create(%dst, %op_s), ok -> @opened_out, err -> @fail_in
opened_out(%out: file<write>):
%bm = borrow.mut %buf
%bs = slice.make %bm
%fi = borrow.mut %in
%fo = borrow.mut %out
br @loop()
loop:
intrinsic fs.read(%fi, %bs), ok -> @got, err -> @fail_loop
got(%n: usize):
%z = const.usize 0
%eof = eq.usize %n, %z
cbr %eof, @finish(), @write()
write:
%chunk = slice.sub %bs, %z, %n
%cr = borrow.ref %chunk
intrinsic fs.write_all(%fo, %cr), ok -> @wrote, err -> @fail_write
wrote:
borrow.end %cr
borrow.end %chunk
br @loop()
finish:
borrow.end %fo
borrow.end %fi
borrow.end %bs
borrow.end %bm
intrinsic fs.close(%in), ok -> @closed_in, err -> @fail_close_in
closed_in:
intrinsic fs.close(%out), ok -> @done, err -> @fail_close_out
done:
{end('op')}
{end('ip')}
ret
fail(%e: io_error):
trap
fail_in(%e2: io_error):
trap
fail_loop(%e3: io_error):
trap
fail_write(%e4: io_error):
trap
fail_close_in(%e5: io_error):
trap
fail_close_out(%e6: io_error):
trap
"""
p, rec = run(tmp, "copy", prog, [f"src=fs.read:{src_dir}", f"dst=fs.write:{dst_dir}"])
check(rec["status"] == "returned", f"file copy returned ({rec})")
with open(os.path.join(dst_dir, "copy.bin"), "rb") as f:
check(f.read() == payload, "copied bytes are identical")
# A path outside the scope never reaches the OS: permission_denied.
prog = f"""fn @main(%src: cap<fs.read>) -> u8
effects [fs.read]
entry:
{text('p', src_dir + '/data.bin')}
intrinsic fs.open_read(%src, %p_s), ok -> @opened, err -> @failed
opened(%f: file<read>):
trap
failed(%e: io_error):
{end('p')}
enum.switch io_error %e, permission_denied -> @denied, default -> @other()
denied:
%one = const.u8 1
ret %one
other:
%two = const.u8 2
ret %two
"""
p, rec = run(tmp, "scope", prog, [f"src=fs.read:{dst_dir}"])
check(rec.get("value") == 1, f"out-of-scope path is permission_denied ({rec})")
# stdin -> stdout through the real streams.
prog = """fn @main(%in: cap<io.read>, %out: cap<io.write>) -> void
effects [io.read, io.write]
entry:
%b = local.alloc array<u8, 32>
local.zero %b
%m = borrow.mut %b
%s = slice.make %m
intrinsic io.stdin_read(%in, %s), ok -> @got, err -> @fail
got(%n: usize):
%z = const.usize 0
%part = slice.sub %s, %z, %n
%pr = borrow.ref %part
intrinsic io.stdout_write(%out, %pr), ok -> @done, err -> @fail2
done:
borrow.end %pr
borrow.end %part
borrow.end %s
borrow.end %m
ret
fail(%e: io_error):
trap
fail2(%e2: io_error):
trap
"""
p, rec = run(tmp, "echo", prog, ["in=io.read", "out=io.write"], stdin=b"through the host")
check(p.stdout == b"through the host", f"stdin echoed to stdout ({p.stdout!r})")
# TCP echo over real sockets on a free port.
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
addr = f"127.0.0.1:{port}"
prog = f"""fn @main(%listen: cap<net.listen>, %connect: cap<net.connect>) -> array<u8, 4>
effects [net.listen, net.connect, net.read, net.write]
entry:
{text('addr', addr)}
{text('ping', 'ping')}
%buf = local.alloc array<u8, 4>
local.zero %buf
%back = local.alloc array<u8, 4>
local.zero %back
intrinsic net.listen(%listen, %addr_s), ok -> @listening, err -> @fail
listening(%l: listener):
intrinsic net.connect(%connect, %addr_s), ok -> @connected, err -> @fail1
connected(%client: stream):
%lm = borrow.mut %l
intrinsic net.accept(%lm), ok -> @accepted, err -> @fail2
accepted(%server: stream):
borrow.end %lm
%cm = borrow.mut %client
intrinsic net.send_all(%cm, %ping_s), ok -> @sent, err -> @fail3
sent:
%sm = borrow.mut %server
%bm = borrow.mut %buf
%bs = slice.make %bm
intrinsic net.recv(%sm, %bs), ok -> @received, err -> @fail4
received(%n: usize):
%z = const.usize 0
%got = slice.sub %bs, %z, %n
%gr = borrow.ref %got
intrinsic net.send_all(%sm, %gr), ok -> @echoed, err -> @fail5
echoed:
borrow.end %gr
borrow.end %got
borrow.end %bs
borrow.end %bm
borrow.end %sm
%km = borrow.mut %back
%ks = slice.make %km
intrinsic net.recv(%cm, %ks), ok -> @answer, err -> @fail6
answer(%m: usize):
borrow.end %ks
borrow.end %km
borrow.end %cm
intrinsic net.close_stream(%server), ok -> @c1, err -> @fail7
c1:
intrinsic net.close_stream(%client), ok -> @c2, err -> @fail8
c2:
intrinsic net.close_listener(%l), ok -> @c3, err -> @fail9
c3:
{end('ping')}
{end('addr')}
%r = local.load %back
ret %r
""" + "".join(f"fail{s}(%e{s}: io_error):\n trap\n" for s in ["", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
p, rec = run(tmp, "tcp", prog, ["listen=net.listen", "connect=net.connect"])
check(rec.get("value") == [112, 105, 110, 103], f"TCP echo over real sockets ({rec})")
print("hosted smoke tests passed")
if __name__ == "__main__":
main()