diff --git a/doc/2026-10-17T15-30-00Z_feature_world_perf_budgets/2026-10-17T15-30-00Z_feature_world_perf_budgets.md b/doc/2026-10-17T15-30-00Z_feature_world_perf_budgets/2026-10-17T15-30-00Z_feature_world_perf_budgets.md new file mode 100644 index 000000000..eb4af6805 --- /dev/null +++ b/doc/2026-10-17T15-30-00Z_feature_world_perf_budgets/2026-10-17T15-30-00Z_feature_world_perf_budgets.md @@ -0,0 +1,181 @@ +# Per-call resource metrics and performance budgets + +See the [Phase 11 foundations plan](../../.opencode/plans/phase-11-foundations.md) and the [Phase 9 plan](../../.opencode/plans/phase-9-portable-platform.md). + +## Intent + +Fuel is the platform's main performance ceiling for guests: every guest call +runs on a fresh `SandboxLimits::fuel` (10M by default) and traps, poisoning the +world, when it runs out. Nobody could see how close a guest was to that line +without hand instrumentation. Territory's styled view uses about 7.1M to 7.8M +of the 10M, and that was found by hand. This slice makes the cost + +1. **measurable** from the host (`WorldInstance::metrics`), +2. **visible to authors** offline (`id world measure`), and +3. **guarded** against regressions in CI (`checked_in_examples_stay_within_fuel_budgets`). + +## What is measured + +`WorldInstance` records the fuel each guest call spent, in a fixed array keyed +by `GuestCall { Init, Update, View, Layout, Records, Wants, Snapshot, Restore }`. +Each `CallStats` holds `calls`, `fuel_total`, `fuel_max`, and `fuel_last`. + +- Every call already resets fuel with `set_fuel(limits.fuel)` first, so fuel + spent is `limits.fuel - get_fuel()` afterwards. It is read once the whole + call is done, so it includes the input allocation, the guest `free`, and the + `plaza_out_len` read around the main export. +- A trapped call is recorded too. The diagnostic getters (`plaza_error_ptr`, + `plaza_error_len`) refill the store to 10_000, so `guest_error_suffix` + captures the trap's fuel first. A call that ran out of fuel leaves the store + at zero and so records the full limit. +- **Init** covers the module start function plus `plaza_init`; both run on the + one budget set at instantiation. It is recorded when the instance is built. +- **Layout** is the `plaza_layout` call. A guest with no layout export makes + `layout_at` fall back to `view`, which is then counted as **View**. +- Calls refused before reaching the guest (a poisoned world, an oversized + message, an absent optional export) are not recorded. +- The trait-level `snapshot` verifies the snapshot on a probe instance. The + live instance records its own `snapshot` and `records` calls; the probe's + calls are not added to it. +- Metrics live in memory on the instance. They are never journaled, never on + the wire, and never part of a snapshot, so they cannot affect replay or + determinism. Recording is a few integer updates: no lock, no allocation. + +## `id world measure` + +``` +id world measure --module FILE.wasm [--seed N] [--input HEX]... [--width W --height H] +``` + +Offline and gated on the `sandbox` feature. It compiles the module with the +default limits and instantiates it. It then runs `view`, `layout_at(W, H)` if +both `--width` and `--height` are given, `records`, `wants`, and `snapshot`. +Then each `--input` runs as participant 1 through `update`, with a `view` after +each. It prints one JSON object: `module_bytes`, `fuel_limit`, `calls` (per +kind: `calls`, `fuel_total`, `fuel_max`), `worst_call`, and +`worst_call_percent_of_limit`. Kinds that never ran are omitted. It exits +nonzero only for a compile failure, a malformed `--input`, or a trap. + +The reads run before the inputs, so they show the cost at the initial state. +Use `--input` to see how update cost and later views grow with state. + +## How budgets are set + +`FUEL_BUDGETS` in `src/sandbox.rs` has one row per (example, call kind). The +test drives each example through a fixed script (`drive_*` in the test +module), then runs `view`, `layout_at(40, 20)`, `records`, `wants`, and +`snapshot` at the final state, and restores the snapshot on a fresh instance. +The observed value is the worst single call of that kind. A budget is the +measured baseline plus 25 percent, rounded up to the next 100_000. The test also +requires every example module to be at most 1 MiB, and fails on a call that +has no budget row, so a new export cannot slip in unguarded. + +On failure the message names the example and call, the actual fuel, and the +budget, then says: _re-baseline deliberately: update the table and say why in +the commit_. + +### Baseline (fuel) + +| Example | init | update | view | layout | records | wants | snapshot | restore | +| ----------- | ----: | -----: | --------: | --------: | ------: | ------: | -------: | ------: | +| roc-counter | 1,215 | 3,759 | 1,327 | 1,337 | 1,866 | 733 | 874 | 3,238 | +| tic-tac-toe | 1,242 | 7,839 | 5,329 | 6,265 | 7,347 | 1,664 | 769 | 14,204 | +| roc-screen | 1,215 | 11,491 | 257,078 | 1,192,583 | 2,795 | 733 | 870 | 3,243 | +| roc-grid | 1,242 | 5,035 | 981,969 | 981,300 | 1,664 | 737 | 1,143 | 5,688 | +| roc-chat | 1,271 | 89,763 | 5,997 | 6,949 | 23,438 | 42,766 | 4,767 | 7,884 | +| lounge | 1,271 | 69,255 | 5,550 | 6,502 | 71,278 | 194,873 | 70,261 | 33,299 | +| territory | 1,255 | 64,520 | 7,798,929 | 7,798,260 | 56,536 | 2,444 | 7,794 | 21,745 | + +Fuel counts Wasm instructions, so these numbers do not depend on the host or +on a debug or release build. They are exact for these module bytes and scripts. + +### Headroom against the 10M default + +Each example's worst call as a percent of the limit: + +| Example | Worst call | Fuel | % of 10M | +| ------------- | ---------- | ------------: | -------: | +| roc-counter | update | 3,759 | 0.04 | +| tic-tac-toe | restore | 14,204 | 0.14 | +| roc-screen | layout | 1,192,583 | 11.93 | +| roc-grid | view | 981,969 | 9.82 | +| roc-chat | update | 89,763 | 0.90 | +| lounge | wants | 194,873 | 1.95 | +| **territory** | **view** | **7,798,929** | **78.0** | + +**Above 50 percent: territory only.** An empty territory board costs 6.54M for +a view (65 percent); the script's two seats and a few claimed cells take it to +7.80M. A hand run with one seat and one cell gave 7.1M (71 percent). + +**Territory's view exceeds the default limit at six or more seats**, which its +own `max_seats = 8` allows. Measured in a scratch test with every seat joined +and active, view fuel was: + +| Seats | 1 | 2 | 4 | 6 | 8 | +| --------- | ----: | ----: | ----: | ----------: | ----------: | +| View fuel | 7.33M | 8.10M | 9.74M | out of fuel | out of fuel | + +Each seat adds about 0.8M, and claimed cells add little (16 cells per seat +moved the 2-seat view by 0.03M). A view that runs out of fuel traps and poisons +the world, so a full territory world is broken under the default profile today. +This slice records the problem; it does not fix it (non-goals below). The +`FUEL_BUDGETS` row guards the two-seat baseline, so it will not catch this by +itself. + +## How to re-baseline + +Re-baseline when a guest or the platform legitimately changes cost: + +1. Rebuild the example module as usual. +2. Run `cargo test --lib -- --ignored print_fuel_baseline --nocapture` from + `pkgs/id`. It prints one `FUEL_BUDGETS` row per call kind, with the new + budget and the measured baseline in a comment. +3. Paste the rows over `FUEL_BUDGETS` and update the baseline table above. +4. Say why in the commit message. A rise without a reason is the regression the + test exists to catch. + +## Limits + +- Budgets are 25 percent over a scripted state, not a worst case. Cost grows + with state, as territory shows, so a pass does not mean a world cannot run + out of fuel. +- Rounding up to 100_000 makes budgets for tiny calls loose: any call under + 80,000 fuel has a 100,000 budget, and 100,000 is 1 percent of the limit. They + guard against order-of-magnitude regressions only. +- A budget near the limit guards little. A budget cannot exceed what the guest + can spend, which is the limit, and territory's 9.8M budget sits close to it. +- Metrics are per instance and in memory. A restarted or replaced world starts + from zero, and nothing aggregates across worlds. +- Only guest fuel is measured. Host-side time (JSON parsing, compression, the + network) and guest memory are not. + +## Non-goals + +No wire change and no `stats` frame change; no host-side metrics endpoint; no +change to the default limits; no optimisation of the guests. + +## Follow-ups + +- **Host-side metrics endpoint.** Expose `WorldInstance::metrics` through the + world host (and `id world stats`) so a live world's headroom is visible, next + to the execution profile it already prints. +- **Fix territory's fuel use.** The view costs about 6.5M on an empty board + and 0.8M per seat. Options: a cheaper render path, or a higher world + profile for it. Either needs its own decision. +- **Look at the shared screen code.** The two grid-like views cost heavily for + what they draw: roc-grid's view is 0.98M and roc-screen's layout is 1.19M. + Hypothesis, unmeasured: the cost is mostly in the shared `Screen` rendering + rather than in each app. Measure with `id world measure` before changing it. +- **Crowded-state budgets.** Add a second territory script with all eight + seats once the view fits, so the budget covers the worst case. +- **Warn on high usage.** Have `id world install` or `compile` run the + measurement and warn when a call uses more than half the profile's fuel. +- **Per-world budgets.** Compare against a world's own execution profile + rather than the 10M default. + +## References + +- [Phase 11 foundations plan](../../.opencode/plans/phase-11-foundations.md) +- [Phase 9 plan](../../.opencode/plans/phase-9-portable-platform.md) +- `src/sandbox.rs`: `GuestCall`, `CallStats`, `CallMetrics`, `FUEL_BUDGETS`, `print_fuel_baseline` +- `src/commands/world.rs`: `measure_module`; `src/cli.rs`: `WorldCommand::Measure` diff --git a/pkgs/id/src/cli.rs b/pkgs/id/src/cli.rs index d7a11cd8b..51f014210 100644 --- a/pkgs/id/src/cli.rs +++ b/pkgs/id/src/cli.rs @@ -1651,6 +1651,32 @@ pub enum WorldCommand { #[arg(long, default_value = "world")] name: String, }, + /// Measure a compiled `.wasm` world program's fuel use, offline. + /// + /// Compiles the module with the default limits, runs `view`, then + /// `layout` (with `--width`/`--height`), `records`, `wants`, and + /// `snapshot`, then each `--input` as participant 1 followed by a `view`. + /// Prints one JSON object with, per call kind, the calls made, total and + /// worst fuel, and the worst call as a percent of the fuel limit. Exits + /// nonzero only if the module fails to compile or a call traps. + #[cfg(feature = "sandbox")] + Measure { + /// Wasm module built for the `id` Roc world ABI. + #[arg(long)] + module: PathBuf, + /// Deterministic seed supplied to the guest initializer. + #[arg(long, default_value_t = 1)] + seed: u64, + /// Event to apply as participant 1, hex-encoded (repeatable, in order). + #[arg(long = "input", value_name = "HEX")] + inputs: Vec, + /// Viewport width for the `layout` call (needs `--height`). + #[arg(long, requires = "height")] + width: Option, + /// Viewport height for the `layout` call (needs `--width`). + #[arg(long, requires = "width")] + height: Option, + }, /// Tail a world's recent events (bounded by retention and a deadline). Logs { /// The host's node ID (64 hex characters). @@ -3846,6 +3872,34 @@ mod tests { }, other => panic!("unexpected: {other:?}"), } + #[cfg(feature = "sandbox")] + { + let cli = Cli::parse_from([ + "id", "world", "measure", "--module", "a.wasm", "--input", "ff", "--input", "00", + "--width", "40", "--height", "20", + ]); + match cli.command { + Some(Command::World(cmd)) => match *cmd { + WorldCommand::Measure { + inputs, + width, + height, + seed, + .. + } => { + assert_eq!(inputs, ["ff", "00"]); + assert_eq!((width, height, seed), (Some(40), Some(20), 1)); + } + other => panic!("unexpected: {other:?}"), + }, + other => panic!("unexpected: {other:?}"), + } + // A width alone has no viewport to lay out. + assert!( + Cli::try_parse_from(["id", "world", "measure", "--module", "a", "--width", "9"]) + .is_err() + ); + } let node = "a".repeat(64); let cli = Cli::parse_from(["id", "world", "stats", &node, "--capability", "c"]); assert!(matches!( diff --git a/pkgs/id/src/commands/world.rs b/pkgs/id/src/commands/world.rs index 7e3512d14..69a4a921d 100644 --- a/pkgs/id/src/commands/world.rs +++ b/pkgs/id/src/commands/world.rs @@ -392,6 +392,20 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { Ok(()) } WorldCommand::New { dir, name } => scaffold_world(&dir, &name), + #[cfg(feature = "sandbox")] + WorldCommand::Measure { + module, + seed, + inputs, + width, + height, + } => { + let wasm = std::fs::read(&module) + .with_context(|| format!("read Wasm module {}", module.display()))?; + let report = measure_module(&wasm, seed, &inputs, width.zip(height))?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) + } WorldCommand::Logs { node, capability, @@ -542,6 +556,72 @@ pub async fn cmd_world(command: WorldCommand) -> Result<()> { } } +/// Drive a module through the calls `id world measure` reports on and return +/// the JSON report. +/// +/// # Errors +/// +/// A module that fails to compile, a malformed `--input`, or a call that traps. +#[cfg(feature = "sandbox")] +fn measure_module( + wasm: &[u8], + seed: u64, + inputs: &[String], + viewport: Option<(u16, u16)>, +) -> Result { + use crate::sandbox::{GuestCall, Sandbox, SandboxLimits}; + + let events = inputs + .iter() + .map(|hex| { + crate::world_session::decode_hex(hex) + .with_context(|| format!("`{hex}` is not an even-length hex string")) + }) + .collect::>>()?; + let limits = SandboxLimits::default(); + let sandbox = Sandbox::compile(wasm, limits)?; + let mut world = sandbox.instantiate(seed)?; + world.view()?; + if let Some((width, height)) = viewport { + world.layout_at(width, height)?; + } + world.records()?; + world.wants()?; + world.snapshot()?; + for event in &events { + world.update(1, event)?; + world.view()?; + } + + let mut calls = serde_json::Map::new(); + let mut worst = (GuestCall::Init, 0); + for (call, stats) in world.metrics().iter() { + if stats.calls == 0 { + continue; + } + if stats.fuel_max > worst.1 { + worst = (call, stats.fuel_max); + } + calls.insert( + call.name().to_owned(), + serde_json::json!({ + "calls": stats.calls, + "fuel_total": stats.fuel_total, + "fuel_max": stats.fuel_max, + }), + ); + } + #[allow(clippy::cast_precision_loss)] + let worst_percent = worst.1 as f64 * 100.0 / limits.fuel as f64; + Ok(serde_json::json!({ + "module_bytes": wasm.len(), + "fuel_limit": limits.fuel, + "calls": calls, + "worst_call": worst.0.name(), + "worst_call_percent_of_limit": (worst_percent * 100.0).round() / 100.0, + })) +} + /// Scaffold a Roc world app in `dir`. /// /// The directory must be absent or empty. Writes `main.roc`, `build.sh` @@ -840,4 +920,30 @@ mod tests { let bad = dir.path().join("bad"); assert!(scaffold_world(&bad, "../escape").is_err()); } + + #[cfg(feature = "sandbox")] + #[test] + fn measure_reports_fuel_per_call_kind_for_a_checked_in_module() { + let wasm = include_bytes!("../../examples/roc-counter/counter.wasm"); + let report = + super::measure_module(wasm, 7, &["696e63".to_owned()], Some((40, 20))).unwrap(); + assert_eq!(report["module_bytes"], wasm.len()); + assert_eq!(report["fuel_limit"], 10_000_000); + let calls = &report["calls"]; + // The initial view plus one after the input. + assert_eq!(calls["view"]["calls"], 2); + for kind in ["init", "update", "layout", "records", "wants", "snapshot"] { + assert_eq!(calls[kind]["calls"], 1, "{kind}: {report}"); + assert!(calls[kind]["fuel_max"].as_u64().unwrap() > 0, "{kind}"); + } + assert!(calls.get("restore").is_none(), "{report}"); + assert!(report["worst_call_percent_of_limit"].as_f64().unwrap() < 1.0); + + // Without a viewport there is no layout call; bad hex is refused + // before the module runs. + let report = super::measure_module(wasm, 7, &[], None).unwrap(); + assert!(report["calls"].get("layout").is_none()); + assert!(super::measure_module(wasm, 7, &["zz".to_owned()], None).is_err()); + assert!(super::measure_module(b"not wasm", 7, &[], None).is_err()); + } } diff --git a/pkgs/id/src/sandbox.rs b/pkgs/id/src/sandbox.rs index e1146d54f..dec828b14 100644 --- a/pkgs/id/src/sandbox.rs +++ b/pkgs/id/src/sandbox.rs @@ -39,6 +39,113 @@ impl Default for SandboxLimits { } } +/// One kind of guest invocation, as counted by [`CallMetrics`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GuestCall { + /// Module start function plus `plaza_init`, run once at instantiation. + Init, + /// `plaza_update`, including the input allocation and free around it. + Update, + /// `plaza_view`; also the fallback of [`WorldInstance::layout_at`] when + /// the guest exports no `plaza_layout`. + View, + /// `plaza_layout`. + Layout, + /// `plaza_records`. + Records, + /// `plaza_wants`. + Wants, + /// `plaza_snapshot`. + Snapshot, + /// `plaza_restore`, including the snapshot allocation and free around it. + Restore, +} + +impl GuestCall { + /// Every call kind, in the order metrics are reported. + pub const ALL: [Self; 8] = [ + Self::Init, + Self::Update, + Self::View, + Self::Layout, + Self::Records, + Self::Wants, + Self::Snapshot, + Self::Restore, + ]; + + /// Stable lowercase name used in reports. + pub const fn name(self) -> &'static str { + match self { + Self::Init => "init", + Self::Update => "update", + Self::View => "view", + Self::Layout => "layout", + Self::Records => "records", + Self::Wants => "wants", + Self::Snapshot => "snapshot", + Self::Restore => "restore", + } + } + + const fn index(self) -> usize { + match self { + Self::Init => 0, + Self::Update => 1, + Self::View => 2, + Self::Layout => 3, + Self::Records => 4, + Self::Wants => 5, + Self::Snapshot => 6, + Self::Restore => 7, + } + } +} + +/// Fuel spent by one kind of guest call over a world instance's lifetime. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CallStats { + /// Calls made, including ones that trapped. + pub calls: u64, + /// Fuel spent across all calls. + pub fuel_total: u64, + /// Most fuel any single call spent. + pub fuel_max: u64, + /// Fuel the most recent call spent. + pub fuel_last: u64, +} + +/// Per-call-kind fuel statistics for one [`WorldInstance`]. +/// +/// A fixed array indexed by [`GuestCall`]: recording a call allocates and +/// locks nothing. In-memory only; never journaled, sent, or snapshotted. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CallMetrics { + stats: [CallStats; GuestCall::ALL.len()], +} + +impl CallMetrics { + /// Statistics for `call`; all zero if it was never made. + pub const fn get(&self, call: GuestCall) -> CallStats { + self.stats[call.index()] + } + + /// Every call kind with its statistics, in [`GuestCall::ALL`] order. + pub fn iter(&self) -> impl Iterator + '_ { + GuestCall::ALL + .into_iter() + .map(|call| (call, self.get(call))) + } + + fn record(&mut self, call: GuestCall, fuel: u64) { + let stats = &mut self.stats[call.index()]; + stats.calls = stats.calls.saturating_add(1); + stats.fuel_total = stats.fuel_total.saturating_add(fuel); + stats.fuel_max = stats.fuel_max.max(fuel); + stats.fuel_last = fuel; + } +} + /// Validated, compiled, import-free Wasm module. #[derive(Clone, Debug)] pub struct Sandbox { @@ -256,10 +363,16 @@ impl Sandbox { let model = init.call(&mut store, seed.cast_signed()).map_err(|e| { anyhow::anyhow!("guest `plaza_init` failed (trap or fuel exhausted): {e}") })?; + // One budget covers the start function and `plaza_init`: both ran + // on the fuel set above. + let mut metrics = CallMetrics::default(); + metrics.record(GuestCall::Init, fuel_spent(&store, self.limits.fuel)); Ok(WorldInstance { runner: self.clone(), seed, limits: self.limits, + metrics, + trap_fuel: None, store, memory, alloc, @@ -286,6 +399,10 @@ pub struct WorldInstance { runner: Sandbox, seed: u64, limits: SandboxLimits, + metrics: CallMetrics, + /// Fuel a trapped call had spent, captured before the diagnostic getters + /// refill the store; taken by [`Self::settle`]. + trap_fuel: Option, store: Store, memory: Memory, alloc: TypedFunc, @@ -312,7 +429,34 @@ impl std::fmt::Debug for WorldInstance { } } +/// Fuel the store has spent since it was last set to `limit`. A call that +/// exhausted its fuel leaves the store at zero, which reads as the full limit. +fn fuel_spent(store: &Store, limit: u64) -> u64 { + limit.saturating_sub(store.get_fuel().unwrap_or(limit)) +} + impl WorldInstance { + /// Fuel statistics per guest call kind since this instance was created. + /// In-memory only: never journaled, sent on the wire, or snapshotted. + pub const fn metrics(&self) -> &CallMetrics { + &self.metrics + } + + /// Fuel the most recent `call` spent; zero if it has not run. + pub const fn last_fuel(&self, call: GuestCall) -> u64 { + self.metrics.get(call).fuel_last + } + + /// Record the fuel the call that just finished spent. Runs after every + /// call that reached the guest, whether it succeeded or trapped. + fn settle(&mut self, call: GuestCall) { + let spent = self + .trap_fuel + .take() + .unwrap_or_else(|| fuel_spent(&self.store, self.limits.fuel)); + self.metrics.record(call, spent); + } + /// Apply one event from `participant`. The model pointer is committed /// only if guest update succeeds. pub fn update(&mut self, participant: u64, event: &[u8]) -> Result<()> { @@ -325,6 +469,7 @@ impl WorldInstance { // defensively so a hostile caller can never wrap the guest argument. let participant = i32::try_from(participant).unwrap_or(i32::MAX); let result = self.update_inner(participant, event); + self.settle(GuestCall::Update); if result.is_err() { self.poisoned = true; } @@ -365,6 +510,7 @@ impl WorldInstance { "world guest is poisoned after a previous failure" ); let result = self.view_inner(); + self.settle(GuestCall::View); if result.is_err() { self.poisoned = true; } @@ -396,9 +542,23 @@ impl WorldInstance { !self.poisoned, "world guest is poisoned after a previous failure" ); - let Some(layout) = self.layout.as_ref() else { + let Some(layout) = self.layout.clone() else { return self.view(); }; + let result = self.layout_inner(&layout, width, height); + self.settle(GuestCall::Layout); + if result.is_err() { + self.poisoned = true; + } + result + } + + fn layout_inner( + &mut self, + layout: &TypedFunc<(i32, i64, i64), i32>, + width: u16, + height: u16, + ) -> Result> { self.store .set_fuel(self.limits.fuel) .map_err(|e| anyhow::anyhow!("reset guest fuel: {e}"))?; @@ -410,7 +570,6 @@ impl WorldInstance { let output_ptr = match rendered { Ok(ptr) => ptr, Err(e) => { - self.poisoned = true; return Err(anyhow::anyhow!( "guest `plaza_layout` failed (trap or fuel exhausted): {e}{}", self.guest_error_suffix() @@ -430,6 +589,7 @@ impl WorldInstance { return Ok(None); }; let result = self.records_inner(&records); + self.settle(GuestCall::Records); if result.is_err() { self.poisoned = true; } @@ -459,6 +619,7 @@ impl WorldInstance { return Ok(None); }; let result = self.wants_inner(&wants); + self.settle(GuestCall::Wants); if result.is_err() { self.poisoned = true; } @@ -489,6 +650,7 @@ impl WorldInstance { return Ok(None); }; let result = self.snapshot_inner(&snapshot); + self.settle(GuestCall::Snapshot); if result.is_err() { self.poisoned = true; } @@ -522,6 +684,7 @@ impl WorldInstance { }; self.check_message_size(snapshot)?; let result = self.restore_inner(&restore, snapshot); + self.settle(GuestCall::Restore); if result.is_err() { self.poisoned = true; } @@ -629,6 +792,8 @@ impl WorldInstance { /// Read optional diagnostic exports after a guest trap. This invokes only /// no-argument, guest-local getters; no host capability is introduced. fn guest_error_suffix(&mut self) -> String { + // The trap left its fuel in the store; read it before the refill below. + self.trap_fuel = Some(fuel_spent(&self.store, self.limits.fuel)); let (Some(ptr_fn), Some(len_fn)) = (&self.error_ptr, &self.error_len) else { return String::new(); }; @@ -1525,4 +1690,374 @@ mod tests { assert!(error.contains("memory.grow") || error.contains("failed")); assert!(world.view().unwrap_err().to_string().contains("poisoned")); } + + #[test] + fn metrics_count_each_call_kind_and_track_max_and_last() { + let runner = compile(ECHO, SandboxLimits::default()).unwrap(); + let mut world = runner.instantiate(0).unwrap(); + // Instantiation already ran `plaza_init`; nothing else has run. + assert_eq!(world.metrics().get(GuestCall::Init).calls, 1); + assert!(world.last_fuel(GuestCall::Init) > 0); + assert_eq!(world.metrics().get(GuestCall::View), CallStats::default()); + + world.view().unwrap(); + world.view().unwrap(); + world.update(1, b"event").unwrap(); + let view = world.metrics().get(GuestCall::View); + assert_eq!(view.calls, 2); + assert_eq!(view.fuel_total, view.fuel_last * 2); + assert_eq!(view.fuel_max, view.fuel_last); + assert!(view.fuel_last > 0); + assert_eq!(world.metrics().get(GuestCall::Update).calls, 1); + // Optional exports that are absent never reach the guest. + assert_eq!(world.records().unwrap(), None); + assert_eq!(world.metrics().get(GuestCall::Records).calls, 0); + assert_eq!( + world + .metrics() + .iter() + .map(|(call, _)| call) + .collect::>(), + GuestCall::ALL + ); + } + + #[test] + fn metrics_record_the_full_limit_for_a_call_that_exhausted_its_fuel() { + let loop_module = r#" + (module + (memory (export "memory") 1 1) + (func (export "plaza_alloc") (param i32) (result i32) (i32.const 0)) + (func (export "plaza_free") (param i32 i32)) + (func (export "plaza_init") (param i64) (result i32) (i32.const 0)) + (func (export "plaza_update") (param i32 i32 i32 i32) (result i32) (i32.const 0)) + (func (export "plaza_view") (param i32) (result i32) (i32.const 0) + (loop $again (br $again))) + (func (export "plaza_out_len") (result i32) (i32.const 0))) + "#; + let mut world = compile( + loop_module, + SandboxLimits { + fuel: 1_000, + ..SandboxLimits::default() + }, + ) + .unwrap() + .instantiate(0) + .unwrap(); + world.view().unwrap_err(); + assert_eq!(world.last_fuel(GuestCall::View), 1_000); + // A poisoned world refuses the call before the guest runs. + world.view().unwrap_err(); + assert_eq!(world.metrics().get(GuestCall::View).calls, 1); + } + + #[test] + fn metrics_survive_a_trap_with_guest_diagnostics() { + // The diagnostic getters refill the store; the trap's fuel must be + // read before that. + let diagnostic_module = r#" + (module + (memory (export "memory") 1 1) + (func (export "plaza_alloc") (param i32) (result i32) (i32.const 0)) + (func (export "plaza_free") (param i32 i32)) + (func (export "plaza_init") (param i64) (result i32) (i32.const 0)) + (func (export "plaza_update") (param i32 i32 i32 i32) (result i32) unreachable) + (func (export "plaza_view") (param i32) (result i32) (i32.const 0)) + (func (export "plaza_out_len") (result i32) (i32.const 0)) + (func (export "plaza_error_ptr") (result i32) (i32.const 0)) + (func (export "plaza_error_len") (result i32) (i32.const 0))) + "#; + let mut world = compile(diagnostic_module, SandboxLimits::default()) + .unwrap() + .instantiate(0) + .unwrap(); + world.update(1, b"event").unwrap_err(); + let spent = world.last_fuel(GuestCall::Update); + assert!(spent > 0 && spent < 1_000, "{spent}"); + } + + /// A checked-in example and the scripted session that exercises it. + struct Example { + name: &'static str, + wasm: &'static [u8], + drive: fn(&mut WorldInstance), + } + + fn host_event(world: &mut WorldInstance, json: &str) { + world.update(0, json.as_bytes()).unwrap(); + } + + fn drive_counter(world: &mut WorldInstance) { + world.update(1, b"inc").unwrap(); + world.update(1, b"inc").unwrap(); + } + + fn drive_tic_tac_toe(world: &mut WorldInstance) { + for (participant, cell) in [(1u64, "0"), (2, "3"), (1, "1"), (2, "4"), (1, "2")] { + world.update(participant, cell.as_bytes()).unwrap(); + } + } + + fn drive_screen(world: &mut WorldInstance) { + world.update(1, b"+").unwrap(); + world.update(1, b"+").unwrap(); + } + + fn drive_grid(world: &mut WorldInstance) { + world.update(1, b"set").unwrap(); + } + + fn drive_chat(world: &mut WorldInstance) { + for key in [&b"h"[..], b"i", b"\r"] { + world.update(1, key).unwrap(); + } + host_event( + world, + r#"{"cap":"result","id":"r0","ok":true,"value":{"sequence":1}}"#, + ); + for key in [&b"h"[..], b"i", b"s", b"t", b"\r"] { + world.update(1, key).unwrap(); + } + host_event( + world, + r#"{"cap":"result","id":"r1","ok":true,"value":{"lines":[{"sequence":1,"participant":1,"text":"hi"}]}}"#, + ); + } + + fn drive_lounge(world: &mut WorldInstance) { + host_event( + world, + r#"{"cap":"players","event":"joined","participant":{"id":1,"name":"ann"}}"#, + ); + host_event( + world, + r#"{"cap":"result","id":"r0","ok":false,"error":"cap_denied"}"#, + ); + host_event(world, r#"{"cap":"time.tick"}"#); + host_event( + world, + r#"{"cap":"result","id":"r2","ok":true,"value":{"now":5000}}"#, + ); + } + + fn drive_territory(world: &mut WorldInstance) { + let joined = |id: u64, name: &str| { + format!( + r#"{{"cap":"players","event":"joined","participant":{{"id":{id},"name":"{name}"}}}}"# + ) + }; + host_event(world, &joined(1, "ann")); + host_event(world, &joined(2, "bob")); + // The opening of a two-player game: each seat has claimed a few + // cells. A crowded late game costs more; see the record's headroom + // section. + for (participant, moves) in [(1u64, "l "), (2, " "), (2, "l "), (2, "hj "), (1, "j ")] { + world.update(participant, moves.as_bytes()).unwrap(); + } + } + + fn examples() -> [Example; 7] { + [ + Example { + name: "roc-counter", + wasm: include_bytes!("../examples/roc-counter/counter.wasm"), + drive: drive_counter, + }, + Example { + name: "tic-tac-toe", + wasm: include_bytes!("../examples/tic-tac-toe/tic-tac-toe.wasm"), + drive: drive_tic_tac_toe, + }, + Example { + name: "roc-screen", + wasm: include_bytes!("../examples/roc-screen/roc-screen.wasm"), + drive: drive_screen, + }, + Example { + name: "roc-grid", + wasm: include_bytes!("../examples/roc-grid/roc-grid.wasm"), + drive: drive_grid, + }, + Example { + name: "roc-chat", + wasm: include_bytes!("../examples/roc-chat/roc-chat.wasm"), + drive: drive_chat, + }, + Example { + name: "lounge", + wasm: include_bytes!("../examples/lounge/lounge.wasm"), + drive: drive_lounge, + }, + Example { + name: "territory", + wasm: include_bytes!("../examples/territory/territory.wasm"), + drive: drive_territory, + }, + ] + } + + /// Worst single-call fuel per call kind for one example's scripted + /// session: init, the driven updates, then every read at the final state, + /// and a restore of the snapshot on a fresh instance. Kinds the module + /// does not export are absent. + fn measure_example(example: &Example) -> Vec<(GuestCall, u64)> { + let runner = Sandbox::compile(example.wasm, SandboxLimits::default()).unwrap(); + let mut live = runner.instantiate(7).unwrap(); + (example.drive)(&mut live); + live.view().unwrap(); + live.layout_at(40, 20).unwrap(); + live.records().unwrap(); + live.wants().unwrap(); + let snapshot = live.snapshot().unwrap(); + let mut restored = runner.instantiate(7).unwrap(); + if let Some(snapshot) = snapshot { + restored.restore(&snapshot).unwrap(); + } + GuestCall::ALL + .into_iter() + .filter_map(|call| { + let max = live + .metrics() + .get(call) + .fuel_max + .max(restored.metrics().get(call).fuel_max); + let ran = live.metrics().get(call).calls + restored.metrics().get(call).calls > 0; + ran.then_some((call, max)) + }) + .collect() + } + + /// Baseline plus 25 percent, rounded up to the next `100_000`. + fn budget_for(baseline: u64) -> u64 { + (baseline * 5).div_ceil(4).div_ceil(100_000) * 100_000 + } + + /// `1234567` as `1_234_567`, the way the table is written. + fn grouped(number: u64) -> String { + let digits = number.to_string(); + let mut out = String::new(); + for (i, digit) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push('_'); + } + out.push(digit); + } + out + } + + /// Prints the budget table for the current guests, ready to paste into + /// `FUEL_BUDGETS`: + /// `cargo test --lib -- --ignored print_fuel_baseline --nocapture`. + #[test] + #[ignore = "prints the baseline to re-baseline FUEL_BUDGETS by hand"] + fn print_fuel_baseline() { + for example in examples() { + for (call, fuel) in measure_example(&example) { + println!( + " (\"{}\", GuestCall::{call:?}, {}), // baseline {fuel}", + example.name, + grouped(budget_for(fuel)) + ); + } + } + } + + /// Per-call fuel budgets: the measured baseline plus 25 percent, rounded + /// up to the next `100_000`. Regenerate with `print_fuel_baseline`. + const FUEL_BUDGETS: &[(&str, GuestCall, u64)] = &[ + ("roc-counter", GuestCall::Init, 100_000), // baseline 1215 + ("roc-counter", GuestCall::Update, 100_000), // baseline 3759 + ("roc-counter", GuestCall::View, 100_000), // baseline 1327 + ("roc-counter", GuestCall::Layout, 100_000), // baseline 1337 + ("roc-counter", GuestCall::Records, 100_000), // baseline 1866 + ("roc-counter", GuestCall::Wants, 100_000), // baseline 733 + ("roc-counter", GuestCall::Snapshot, 100_000), // baseline 874 + ("roc-counter", GuestCall::Restore, 100_000), // baseline 3238 + ("tic-tac-toe", GuestCall::Init, 100_000), // baseline 1242 + ("tic-tac-toe", GuestCall::Update, 100_000), // baseline 7839 + ("tic-tac-toe", GuestCall::View, 100_000), // baseline 5329 + ("tic-tac-toe", GuestCall::Layout, 100_000), // baseline 6265 + ("tic-tac-toe", GuestCall::Records, 100_000), // baseline 7347 + ("tic-tac-toe", GuestCall::Wants, 100_000), // baseline 1664 + ("tic-tac-toe", GuestCall::Snapshot, 100_000), // baseline 769 + ("tic-tac-toe", GuestCall::Restore, 100_000), // baseline 14204 + ("roc-screen", GuestCall::Init, 100_000), // baseline 1215 + ("roc-screen", GuestCall::Update, 100_000), // baseline 11491 + ("roc-screen", GuestCall::View, 400_000), // baseline 257078 + ("roc-screen", GuestCall::Layout, 1_500_000), // baseline 1192583 + ("roc-screen", GuestCall::Records, 100_000), // baseline 2795 + ("roc-screen", GuestCall::Wants, 100_000), // baseline 733 + ("roc-screen", GuestCall::Snapshot, 100_000), // baseline 870 + ("roc-screen", GuestCall::Restore, 100_000), // baseline 3243 + ("roc-grid", GuestCall::Init, 100_000), // baseline 1242 + ("roc-grid", GuestCall::Update, 100_000), // baseline 5035 + ("roc-grid", GuestCall::View, 1_300_000), // baseline 981969 + ("roc-grid", GuestCall::Layout, 1_300_000), // baseline 981300 + ("roc-grid", GuestCall::Records, 100_000), // baseline 1664 + ("roc-grid", GuestCall::Wants, 100_000), // baseline 737 + ("roc-grid", GuestCall::Snapshot, 100_000), // baseline 1143 + ("roc-grid", GuestCall::Restore, 100_000), // baseline 5688 + ("roc-chat", GuestCall::Init, 100_000), // baseline 1271 + ("roc-chat", GuestCall::Update, 200_000), // baseline 89763 + ("roc-chat", GuestCall::View, 100_000), // baseline 5997 + ("roc-chat", GuestCall::Layout, 100_000), // baseline 6949 + ("roc-chat", GuestCall::Records, 100_000), // baseline 23438 + ("roc-chat", GuestCall::Wants, 100_000), // baseline 42766 + ("roc-chat", GuestCall::Snapshot, 100_000), // baseline 4767 + ("roc-chat", GuestCall::Restore, 100_000), // baseline 7884 + ("lounge", GuestCall::Init, 100_000), // baseline 1271 + ("lounge", GuestCall::Update, 100_000), // baseline 69255 + ("lounge", GuestCall::View, 100_000), // baseline 5550 + ("lounge", GuestCall::Layout, 100_000), // baseline 6502 + ("lounge", GuestCall::Records, 100_000), // baseline 71278 + ("lounge", GuestCall::Wants, 300_000), // baseline 194873 + ("lounge", GuestCall::Snapshot, 100_000), // baseline 70261 + ("lounge", GuestCall::Restore, 100_000), // baseline 33299 + ("territory", GuestCall::Init, 100_000), // baseline 1255 + ("territory", GuestCall::Update, 100_000), // baseline 64520 + ("territory", GuestCall::View, 9_800_000), // baseline 7798929 + ("territory", GuestCall::Layout, 9_800_000), // baseline 7798260 + ("territory", GuestCall::Records, 100_000), // baseline 56536 + ("territory", GuestCall::Wants, 100_000), // baseline 2444 + ("territory", GuestCall::Snapshot, 100_000), // baseline 7794 + ("territory", GuestCall::Restore, 100_000), // baseline 21745 + ]; + + #[test] + fn checked_in_examples_stay_within_fuel_budgets() { + let mut failures = Vec::new(); + for example in examples() { + assert!( + example.wasm.len() <= 1024 * 1024, + "{} is {} bytes, over the 1 MiB module budget", + example.name, + example.wasm.len() + ); + for (call, actual) in measure_example(&example) { + let budget = FUEL_BUDGETS + .iter() + .find(|(name, kind, _)| *name == example.name && *kind == call) + .map(|(_, _, budget)| *budget); + match budget { + Some(budget) if actual <= budget => {} + Some(budget) => failures.push(format!( + "{} {}: used {actual} fuel, budget {budget}", + example.name, + call.name() + )), + None => failures.push(format!( + "{} {}: used {actual} fuel, no budget in FUEL_BUDGETS", + example.name, + call.name() + )), + } + } + } + assert!( + failures.is_empty(), + "fuel budgets exceeded:\n{}\nre-baseline deliberately: update the table and say why in the commit", + failures.join("\n") + ); + } }