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

+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 });