diff --git a/.gitignore b/.gitignore index 7c71e49bc..7917f024b 100755 --- a/.gitignore +++ b/.gitignore @@ -193,6 +193,8 @@ pm-stack/aggregator/events.json /zig-out/ pkgs/id/examples/zig-sdk/.zig-cache/ pkgs/id/examples/zig-sdk/zig-out/ +pkgs/id/examples/zig-counter/.zig-cache/ +pkgs/id/examples/zig-counter/zig-out/ # mcpx tooling run from the checkout writes its schema cache in-tree # (.cache/mcpx/schemas-.json); untracked, it made pm-git-sync's diff --git a/pkgs/id/examples/zig-counter/README.md b/pkgs/id/examples/zig-counter/README.md new file mode 100644 index 000000000..0e56c6c84 --- /dev/null +++ b/pkgs/id/examples/zig-counter/README.md @@ -0,0 +1,40 @@ +# Zig counter world + +A tiny pure Zig world program for `id`'s multiplayer service — the +F12.8 (#12596) twin of `../roc-counter` and `../rust-counter`, built +on the Zig guest SDK in `../zig-sdk`. The host owns the authoritative +state; guests send `inc`, and every participant sees the returned +`count=N` presentation. It demonstrates the SDK's screen helper (the +same boxed 20x3 screen JSON as the Roc and Rust programs), the +`records` export encoded with the SDK's json helper, and +snapshot/restore. + +## Build + +Requires the pinned Zig 0.16.0 (enforced by +`../zig-sdk/zig-toolchain.sh`): + +```sh +ZIG=/path/to/zig ./build.sh # or put Zig 0.16.0 on PATH first +``` + +`build.sh` runs the host tests, builds the wasm32-freestanding +module, and refreshes the checked-in `counter.wasm`, which the host's +F12.7 conformance suite (`pkgs/id/crates/id-worlds/src/sandbox.rs`) +can load as the `zig-counter` fixture — no Zig toolchain is needed +to run the suite. + +## Run a hosted world + +```sh +id serve --world --world-admin-token "$WORLD_ADMIN" --world-module counter.wasm +``` + +The module has no Wasm imports and exports the full Plaza ABI v1 +surface (see `../roc-world/ABI.md`): `memory`, `plaza_alloc`, +`plaza_free`, `plaza_init`, `plaza_update`, `plaza_view`, +`plaza_layout`, `plaza_records`, `plaza_wants`, `plaza_snapshot`, +`plaza_restore`, `plaza_out_len`, `plaza_abi_version`, and the +`plaza_error_ptr`/`plaza_error_len` diagnostic pair. Adding +`zig-counter` to the conformance suite's module list is the +remaining F12.7 step on #12596. diff --git a/pkgs/id/examples/zig-counter/build.sh b/pkgs/id/examples/zig-counter/build.sh new file mode 100755 index 000000000..fb19df47c --- /dev/null +++ b/pkgs/id/examples/zig-counter/build.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Build the Zig counter guest (#12596) and refresh the checked-in +# module the host conformance suite loads. Runs the host tests, +# builds the wasm32-freestanding module with the pinned Zig (the +# version guard is ../zig-sdk/zig-toolchain.sh), and copies the +# result to counter.wasm. +# +# Usage: build.sh +# Accepts no positional arguments. +set -euo pipefail + +usage() { + echo "Usage: build.sh" >&2 +} + +if [[ $# -ne 0 ]]; then + usage + echo "Error: unaccounted argument(s): $*" >&2 + exit 1 +fi + +cd "$(dirname "${BASH_SOURCE[0]}")" + +ID_ZIG_BIN="${ZIG:-zig}" + +if ! command -v "$ID_ZIG_BIN" >/dev/null 2>&1; then + echo "zig-counter build: the pinned Zig compiler is not on PATH." >&2 + echo "zig-counter build: install Zig $(cat ../../nix/zig-version) (see pkgs/id/nix/zig-version) or set ZIG=/path/to/zig." >&2 + exit 1 +fi + +bash ../zig-sdk/zig-toolchain.sh +"$ID_ZIG_BIN" build test +"$ID_ZIG_BIN" build +cp zig-out/bin/counter.wasm counter.wasm +echo "wrote counter.wasm" diff --git a/pkgs/id/examples/zig-counter/build.zig b/pkgs/id/examples/zig-counter/build.zig new file mode 100644 index 000000000..998ef8155 --- /dev/null +++ b/pkgs/id/examples/zig-counter/build.zig @@ -0,0 +1,58 @@ +const std = @import("std"); + +fn sdkModule( + b: *std.Build, + target: std.Build.ResolvedTarget, + optimize: std.builtin.OptimizeMode, +) *std.Build.Module { + const dep = b.dependency("zig_sdk", .{ + .target = target, + .optimize = optimize, + }); + return dep.module("zig-sdk"); +} + +pub fn build(b: *std.Build) void { + const optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseSmall }); + const wasm_target = b.resolveTargetQuery(.{ + .cpu_arch = .wasm32, + .os_tag = .freestanding, + .abi = .none, + }); + + // The guest module: an import-free wasm32-freestanding executable + // with no entry point; the `plaza_*` exports in src/main.zig are + // the whole surface, and linear memory is exported for the host. + const guest_mod = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = wasm_target, + .optimize = optimize, + .strip = true, + }); + guest_mod.addImport("zig-sdk", sdkModule(b, wasm_target, optimize)); + + const guest = b.addExecutable(.{ + .name = "counter", + .root_module = guest_mod, + }); + guest.entry = .disabled; + guest.export_memory = true; + // Without an entry point the linker would GC the `plaza_*` + // exports as unreferenced; rdynamic roots every global symbol + // (the export fns are the only public globals in the module). + guest.rdynamic = true; + b.installArtifact(guest); + + // Host tests for the world program (the rust-counter suite's + // mirror): the pure logic plus the screen/json documents. + const host_mod = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = b.graph.host, + }); + host_mod.addImport("zig-sdk", sdkModule(b, b.graph.host, .Debug)); + + const test_step = b.step("test", "Run the Zig counter world tests"); + const unit_tests = b.addTest(.{ .root_module = host_mod }); + const run = b.addRunArtifact(unit_tests); + test_step.dependOn(&run.step); +} diff --git a/pkgs/id/examples/zig-counter/build.zig.zon b/pkgs/id/examples/zig-counter/build.zig.zon new file mode 100644 index 000000000..26b84ed1b --- /dev/null +++ b/pkgs/id/examples/zig-counter/build.zig.zon @@ -0,0 +1,10 @@ +.{ + .name = .zig_counter, + .version = "0.0.1", + .minimum_zig_version = "0.16.0", + .dependencies = .{ + .zig_sdk = .{ .path = "../zig-sdk" }, + }, + .fingerprint = 0xb2b2d220e523eae3, + .paths = .{ "build.zig", "build.zig.zon", "src" }, +} diff --git a/pkgs/id/examples/zig-counter/counter.wasm b/pkgs/id/examples/zig-counter/counter.wasm new file mode 100755 index 000000000..a16df443a Binary files /dev/null and b/pkgs/id/examples/zig-counter/counter.wasm differ diff --git a/pkgs/id/examples/zig-counter/src/main.zig b/pkgs/id/examples/zig-counter/src/main.zig new file mode 100644 index 000000000..255e864de --- /dev/null +++ b/pkgs/id/examples/zig-counter/src/main.zig @@ -0,0 +1,274 @@ +//! Zig counter world — the playable example for the Zig guest SDK +//! (#12596), twin of `examples/roc-counter/main.roc` and +//! `examples/rust-counter` on the Plaza ABI v1 contract documented in +//! `../roc-world/ABI.md`: +//! +//! - `init` ignores the seed; the model is `{ count: i64 }` starting +//! at 0. +//! - `update` increments on a trimmed `inc` event, like the Roc +//! program (events are matched after a text trim, so `" inc "` +//! counts too). +//! - `view` renders the boxed 20x3 screen through the SDK's screen +//! helper; `layout` widens the box to 30 columns at width >= 30. +//! - `records` publishes `{"count":N}`, encoded with the SDK's json +//! helper; `wants` is the empty document. +//! - `snapshot` is the decimal count; `restore` parses it back and +//! is total (invalid text restores count 0), so +//! `restore(snapshot(m))` behaves exactly like `m`. +//! +//! The pure program (`init`/`update`/`view`/`layout`/`records`/ +//! `wants`/`snapshot`/`restore`) is host-testable; the `plaza_*` +//! exports below are the byte-level glue, mirroring the Rust SDK's +//! `plaza_guest!` plumbing: a leaked model pointer the host hands +//! back, one shared output slot released by the next output call, +//! and `plaza_alloc`/`plaza_free` over the guest allocator. + +const std = @import("std"); +const builtin = @import("builtin"); +const sdk = @import("zig-sdk"); +const screen = sdk.screen; +const json = sdk.json; + +/// The guest allocator: the wasm heap inside a guest module, the +/// page allocator in host test runs (the program logic is exercised +/// natively there; the exports' pointer widths are a wasm32 affair). +const guest_allocator: std.mem.Allocator = if (builtin.target.cpu.arch == .wasm32) + std.heap.wasm_allocator +else + std.heap.page_allocator; + +// ---- the world program -------------------------------------------------- + +pub const Model = struct { + count: i64, +}; + +pub fn init(seed: u64) Model { + _ = seed; + return .{ .count = 0 }; +} + +fn isTrimByte(byte: u8) bool { + return byte == ' ' or byte == '\t' or byte == '\n' or byte == '\r'; +} + +/// Byte trim matching `RocText.trim` / the Rust SDK's `text::trim` +/// (space, tab, LF, CR at both ends). +pub fn trim(bytes: []const u8) []const u8 { + var start: usize = 0; + var end: usize = bytes.len; + while (start < end and isTrimByte(bytes[start])) start += 1; + while (end > start and isTrimByte(bytes[end - 1])) end -= 1; + return bytes[start..end]; +} + +pub fn update(model: Model, participant: u32, event: []const u8) Model { + _ = participant; + if (std.mem.eql(u8, trim(event), "inc")) { + return .{ .count = model.count + 1 }; + } + return model; +} + +fn render(alloc: std.mem.Allocator, model: Model, width: u64, height: u64) ![]u8 { + var scr = try screen.Screen.init(alloc, width, height); + defer scr.deinit(alloc); + scr.boxed(0, 0, width, height, "counter"); + var label_buf: [32]u8 = undefined; + const label = try std.fmt.bufPrint(&label_buf, "count={d}", .{model.count}); + scr.putText(2, 1, label, .{}); + return scr.renderJson(alloc); +} + +pub fn view(alloc: std.mem.Allocator, model: Model) ![]u8 { + return render(alloc, model, 20, 3); +} + +/// Reflow: a wide viewport gets a wider box, a short one keeps +/// three rows (the Roc program's layout, verbatim). +pub fn layout(alloc: std.mem.Allocator, model: Model, width: u64, height: u64) ![]u8 { + _ = height; + const w: u64 = if (width >= 30) 30 else 20; + return render(alloc, model, w, 3); +} + +/// Structured data the host stores and replicates: a JSON object of +/// records, built and encoded with the SDK's json helper. +pub fn records(alloc: std.mem.Allocator, model: Model) ![]u8 { + var lexeme_buf: [24]u8 = undefined; + const lexeme = try std.fmt.bufPrint(&lexeme_buf, "{d}", .{model.count}); + var fields = [_]json.Value.Field{ + .{ .key = "count", .value = .{ .number = lexeme } }, + }; + return json.encode(alloc, .{ .object = fields[0..] }); +} + +/// This program wants nothing from the server. +pub fn wants(alloc: std.mem.Allocator) ![]u8 { + return alloc.dupe(u8, "{}"); +} + +pub fn snapshot(alloc: std.mem.Allocator, model: Model) ![]u8 { + return std.fmt.allocPrint(alloc, "{d}", .{model.count}); +} + +pub fn restore(bytes: []const u8) Model { + const count = std.fmt.parseInt(i64, trim(bytes), 10) catch 0; + return .{ .count = count }; +} + +// ---- Plaza ABI v1 glue ---------------------------------------------------- + +/// The one shared output slot (ABI.md): the host reads and copies +/// the range immediately; the next output-producing call releases +/// the previous buffer. +var output: []u8 = &.{}; + +fn setOutput(bytes: []u8) i32 { + if (output.len > 0) guest_allocator.free(output); + output = bytes; + return @intCast(@intFromPtr(output.ptr)); +} + +fn leakModel(model: Model) i32 { + const ptr = guest_allocator.create(Model) catch @trap(); + ptr.* = model; + return @intCast(@intFromPtr(ptr)); +} + +fn modelRef(model_ptr: i32) *Model { + return @ptrFromInt(@as(usize, @intCast(model_ptr))); +} + +fn inputBytes(ptr: i32, len: i32) []const u8 { + const n: usize = @intCast(@max(len, 0)); + if (n == 0) return ""; + const p: [*]const u8 = @ptrFromInt(@as(usize, @intCast(ptr))); + return p[0..n]; +} + +export fn plaza_abi_version() i32 { + return 1; +} + +export fn plaza_alloc(len: i32) i32 { + const n: usize = @intCast(@max(len, 1)); + const slice = guest_allocator.alloc(u8, n) catch @trap(); + return @intCast(@intFromPtr(slice.ptr)); +} + +export fn plaza_free(ptr: i32, len: i32) void { + if (ptr == 0) return; + const n: usize = @intCast(@max(len, 1)); + const p: [*]u8 = @ptrFromInt(@as(usize, @intCast(ptr))); + guest_allocator.free(p[0..n]); +} + +export fn plaza_init(seed: i64) i32 { + return leakModel(init(@bitCast(seed))); +} + +export fn plaza_update(model_ptr: i32, participant: i32, event_ptr: i32, event_len: i32) i32 { + const model = modelRef(model_ptr); + const next = update(model.*, @bitCast(participant), inputBytes(event_ptr, event_len)); + guest_allocator.destroy(model); + return leakModel(next); +} + +export fn plaza_view(model_ptr: i32) i32 { + return setOutput(view(guest_allocator, modelRef(model_ptr).*) catch @trap()); +} + +export fn plaza_layout(model_ptr: i32, width: i64, height: i64) i32 { + return setOutput(layout(guest_allocator, modelRef(model_ptr).*, @bitCast(width), @bitCast(height)) catch @trap()); +} + +export fn plaza_records(model_ptr: i32) i32 { + return setOutput(records(guest_allocator, modelRef(model_ptr).*) catch @trap()); +} + +export fn plaza_wants(model_ptr: i32) i32 { + _ = model_ptr; + return setOutput(wants(guest_allocator) catch @trap()); +} + +export fn plaza_snapshot(model_ptr: i32) i32 { + return setOutput(snapshot(guest_allocator, modelRef(model_ptr).*) catch @trap()); +} + +export fn plaza_restore(snapshot_ptr: i32, snapshot_len: i32) i32 { + return leakModel(restore(inputBytes(snapshot_ptr, snapshot_len))); +} + +export fn plaza_out_len() i32 { + return @intCast(output.len); +} + +export fn plaza_error_ptr() i32 { + // No crash has been captured: the diagnostic pair reads as an + // empty message (length 0), which ABI.md permits at rest. Like + // the Rust SDK, the pointer is the current output slot. + return @intCast(@intFromPtr(output.ptr)); +} + +export fn plaza_error_len() i32 { + return 0; +} + +// ---- tests (mirrors of the rust-counter test suite) ----------------------- + +test "counter matches the roc program" { + const alloc = std.testing.allocator; + var model = init(7); + try std.testing.expectEqual(@as(i64, 0), model.count); + model = update(model, 1, "inc"); + try std.testing.expectEqual(@as(i64, 1), model.count); + model = update(model, 1, " inc \n"); + try std.testing.expectEqual(@as(i64, 2), model.count); + model = update(model, 1, "dec"); + try std.testing.expectEqual(@as(i64, 2), model.count); + + const view_doc = try view(alloc, model); + defer alloc.free(view_doc); + try std.testing.expect(std.mem.indexOf(u8, view_doc, "count=2") != null); + + const records_doc = try records(alloc, model); + defer alloc.free(records_doc); + try std.testing.expectEqualStrings("{\"count\":2}", records_doc); + + const wants_doc = try wants(alloc); + defer alloc.free(wants_doc); + try std.testing.expectEqualStrings("{}", wants_doc); + + // Snapshot/restore round-trips byte-identically, and restore is + // total on invalid text. + const snap = try snapshot(alloc, model); + defer alloc.free(snap); + try std.testing.expectEqualStrings("2", snap); + const restored = restore(snap); + const snap_again = try snapshot(alloc, restored); + defer alloc.free(snap_again); + try std.testing.expectEqualStrings(snap, snap_again); + try std.testing.expectEqual(@as(i64, 0), restore("junk").count); + try std.testing.expectEqual(@as(i64, 0), restore("").count); +} + +test "view is the boxed screen document" { + const alloc = std.testing.allocator; + const doc = try view(alloc, .{ .count = 1 }); + defer alloc.free(doc); + try std.testing.expectEqualStrings( + "{\"kind\":\"screen\",\"version\":1,\"width\":20,\"height\":3,\"rows\":[\"+-counter----------+\",\"| count=1 |\",\"+------------------+\"],\"styles\":[[],[],[]]}", + doc, + ); +} + +test "layout widens the box at width 30" { + const alloc = std.testing.allocator; + const wide = try layout(alloc, .{ .count = 1 }, 30, 3); + defer alloc.free(wide); + try std.testing.expect(std.mem.indexOf(u8, wide, "\"width\":30") != null); + const narrow = try layout(alloc, .{ .count = 1 }, 29, 3); + defer alloc.free(narrow); + try std.testing.expect(std.mem.indexOf(u8, narrow, "\"width\":20") != null); +} diff --git a/pkgs/id/examples/zig-sdk/README.md b/pkgs/id/examples/zig-sdk/README.md index e83c8c3bb..19cd28209 100644 --- a/pkgs/id/examples/zig-sdk/README.md +++ b/pkgs/id/examples/zig-sdk/README.md @@ -8,8 +8,10 @@ example world. Slice 1 landed the SDK skeleton plus the two pure helpers everything else builds on (`json`, `grid`); slice 2 adds `screen` and `cap`, so -all four helpers are in. The playable example and the conformance run -are the follow-up slices on #12596. +all four helpers are in. Slice 3 adds the playable example world, +[`../zig-counter/`](../zig-counter/) — the counter twin of +`../roc-counter/` and `../rust-counter/` — leaving the conformance +run as the follow-up slice on #12596. ## Layout @@ -53,17 +55,19 @@ ZIG=/path/to/zig ./zig-sdk-test.sh # or put Zig 0.16.0 on PATH first This runs the version guard, `zig fmt --check`, the `zig test` suites in `src/` (mirrors of the Roc `expect` cases, including the -64-depth and 64 KiB limit cases in `json`), and a -`wasm32-freestanding` build proving the SDK compiles for the guest -target. No Roc toolchain, Rust toolchain, or laptop is needed. +64-depth and 64 KiB limit cases in `json`), a `wasm32-freestanding` +build proving the SDK compiles for the guest target, and the +`../zig-counter/` example's host tests plus guest-module build. No +Roc toolchain, Rust toolchain, or laptop is needed. ## What remains on #12596 -1. A playable example world (e.g. `zig-counter`, mirroring - `../roc-counter/`) exporting the Plaza ABI v1 surface from - `../roc-world/ABI.md`. -2. A conformance run of that example against the F12.7 suite, and - wiring `zig-sdk-test.sh` into the `roc-test` just recipe once the +1. A conformance run of the `../zig-counter/` example against the + F12.7 suite: add `zig-counter` (its checked-in `counter.wasm`) to + the module list in `pkgs/id/crates/id-worlds/src/sandbox.rs` and + record the passing run where the Phase 12 exit audit (#12231) can + cite it. +2. Wiring `zig-sdk-test.sh` into the `roc-test` just recipe once the nix-provided Zig version is confirmed to be 0.16.0 (the nix `zig` package version was not verified in this slice, so the wiring is deliberately left out rather than risk breaking diff --git a/pkgs/id/examples/zig-sdk/zig-sdk-test.sh b/pkgs/id/examples/zig-sdk/zig-sdk-test.sh index ab490f029..186c25041 100755 --- a/pkgs/id/examples/zig-sdk/zig-sdk-test.sh +++ b/pkgs/id/examples/zig-sdk/zig-sdk-test.sh @@ -1,8 +1,10 @@ #!/usr/bin/env bash # Tests for the Zig guest SDK (#12596): the json, grid, screen, and cap # helpers with `zig test`, plus a wasm32-freestanding build proving the -# SDK compiles for the guest target. Run from anywhere; the pinned Zig -# version is enforced by zig-toolchain.sh before anything builds. +# SDK compiles for the guest target — and the zig-counter example world +# built on the SDK (host tests plus its guest-module build). Run from +# anywhere; the pinned Zig version is enforced by zig-toolchain.sh +# before anything builds. # # Usage: zig-sdk-test.sh # Accepts no positional arguments. @@ -32,4 +34,15 @@ bash zig-toolchain.sh "$ID_ZIG_BIN" fmt --check src build.zig "$ID_ZIG_BIN" build test "$ID_ZIG_BIN" build -Dtarget=wasm32-freestanding -echo "✓ Zig SDK tests passed (json + grid + screen + cap; wasm32-freestanding build OK)" + +# The playable example world built on the SDK: its host tests, plus a +# guest build proving the example module compiles and links for +# wasm32-freestanding (build.sh in that directory additionally +# refreshes the checked-in counter.wasm). +cd ../zig-counter +"$ID_ZIG_BIN" fmt --check src build.zig +"$ID_ZIG_BIN" build test +"$ID_ZIG_BIN" build +cd ../zig-sdk + +echo "✓ Zig SDK tests passed (json + grid + screen + cap; wasm32-freestanding build OK; zig-counter example tests + guest build OK)"