Edge-Served Browser Sandbox Prototype · 1-Page Wasm VM (64 KiB)

Ephemeral Fuel-Metered WebAssembly VM with OPFS Snapshot Rollback

Problem & Hypothesis: Unbounded guest loops can lock up a browser tab, and aborting mid-run leaves half-mutated state behind. Fuel-metered .wasm linear memory paired with binary Origin Private File System (OPFS) checkpoints provides sub-millisecond deterministic halt via WebAssembly.RuntimeError and byte-exact rollback inside a standard browser tab.

Confirm signal

Runaway loops trap via WebAssembly.RuntimeError at the exact fuel limit, and rolling back to a pre-run OPFS checkpoint leaves zero residual mutated bytes in the hex diff.

Falsify signal

Checkpoint serialization to OPFS exceeds acceptable turn latency on larger linear memories, or host-import calls stall before the fuel counter decrements.

What to try first

Click 1. Checkpoint & Run 200 Steps (Fuel 5000), then click 2. Trigger Fuel Trap (500 / 50) to observe budget exhaustion and 3. Rollback from OPFS to restore the pre-trap snapshot.

3 Things To Try

Execute these three steps in sequence to verify clean checkpointing, fuel exhaustion trapping, and byte-for-byte OPFS rollback.

  1. Step 1 Ready

    Save Clean Checkpoint & Run 200 Steps (Fuel 5000)

    Saves a baseline vm-ckpt-*.bin snapshot in OPFS, executes run_steps(200, 5000, 0) inside the Worker, and inspects the 200-byte hex diff.

  2. Step 2 Ready

    Trigger Deterministic Fuel Trap (500 Steps with Fuel 50)

    Saves a pre-trap checkpoint, then executes run_steps(500, 50, 0). The kernel mutates 50 bytes, hits fuel === 0, and aborts via WebAssembly.RuntimeError.

  3. Step 3 Ready

    One-Click OPFS Rollback

    Reads the clean pre-trap vm-ckpt-*.bin snapshot from OPFS and restores exact pre-trap bytes into WebAssembly.Memory in milliseconds (0-byte delta).

Live VM Telemetry & Execution Controls

Initializing Dedicated Worker and probing OPFS availability...

INITIALIZING
Linear Memory SHA-256
—
Worker Elapsed Time
—
Snapshot Persistence
—
Remaining Fuel
—
Last Op Delta (Bytes)
—
Active Checkpoint Delta
—

Workload & Fuel Parameters

Presets: loading…

Saved Snapshots (vm-ckpt-*.bin)

0 files
Snapshot File SHA-256 Store Actions
No checkpoints saved yet. Save one or run Step 1.

256-Byte Linear Memory Window

Inspecting 256 bytes of the 65,536-byte Wasm page; changed offsets highlight against the selected checkpoint.

Hex Diff & Wire Inspector

Live byte-level diffs, Worker postMessage frames, HTTP preset payloads, and generated .wasm kernel disassembly.

Live Memory Hex Diff & Window Dump
Awaiting first VM run… Ranges: none
Initializing VM memory diff view…
Dedicated Worker postMessage & GET /api/presets Wire Log
Waiting for Worker initialization and /api/presets fetch…
Generated .wasm Binary Kernel & WAT Listing
Compiling binary .wasm module in Dedicated Worker…

Core Concepts

1. The Problem

Unbounded Loops & Partial State

Running unverified WebAssembly or script workloads on the main thread risks freezing UI frames via infinite loops. Worse, aborting mid-execution leaves linear memory partially mutated with no clean revert boundary.

2. The Goal

Bounded Execution & Fast Rollback

Isolate guest execution off the main thread in a Dedicated Worker with a strict 1-page (65,536-byte) memory ceiling, deterministic fuel exhaustion via WebAssembly.RuntimeError, and millisecond snapshot recovery.

3. How It Works

Fuel Counter + OPFS Binary Checkpoints

buildFuelWasmModule() emits a valid .wasm binary whose run_steps loop checks fuel <= 0 before each write. Snapshots persist as vm-ckpt-*.bin inside OPFS (or an in-Worker Map when third-party iframes restrict storage).

Runtime Isolation & Rollback Architecture

Boundary flow from host tab controls through Dedicated Worker execution, fuel trap handling, and binary OPFS snapshot diffing.

Storage & Iframe Isolation Behavior

Inside a first-party origin, the Dedicated Worker opens navigator.storage.getDirectory() and writes 64 KiB checkpoints via FileSystemSyncAccessHandle (or createWritable()).

If embedded inside a restricted third-party iframe where OPFS throws SecurityError or NotAllowedError, the worker automatically routes vm-ckpt-*.bin snapshots to its isolated in-Worker Map and reports the fallback mode in telemetry.

Browser Ephemeral VM Runtime Flow Four-stage pipeline: Host Tab UI sends commands via postMessage to the Dedicated VM Worker, which executes the fuel-metered .wasm module and persists or restores 64 KiB snapshots via OPFS and byte-diff comparison. 1. HOST TAB (UI) Main Thread • Preset fetch (/api/presets) • Pure DOM node rendering • Never blocked by guest loop CSP: wasm-unsafe-eval postMsg 2. DEDICATED WORKER public/vm-worker.js • Off-thread isolation boundary • Catches RuntimeError traps • Computes SHA-256 memHash try { run_steps } catch (e) exec 3. .WASM + FUEL METER 1-Page Linear Memory • memory: 1 page (65,536 B) • run_steps(n, fuel, offset) • fuel <= 0 → unreachable mutate_cell(offset, byte) sync 4. OPFS + BYTE DIFF Binary Snapshots • vm-ckpt-*.bin (64 KiB) • computeMemoryDiff() • restoreMemoryBytes() Map fallback in iframes rollback: restore exact pre-trap bytes into WebAssembly.Memory
Figure 1: Dedicated Worker execution isolates fuel-metered WebAssembly traps from the host tab and persists 64 KiB binary checkpoints in OPFS for deterministic byte rollback.
How This Is Set Up

Fuel-Metered Wasm Worker & OPFS Checkpoint Wiring

Replacing unbounded main-thread JavaScript execution with a Dedicated Worker WebAssembly instance whose execution fuel traps deterministically and whose linear memory restores from OPFS binary checkpoints.

Unbounded main-thread loop (blocks & corrupts)
// Running guest loops on the main thread shares host state with no CPU meter
const sharedState = { ledger: [100, 200] };

try {
  runGuestLoop(sharedState); // Infinite loop locks UI; partial writes survive abort
} catch (err) {
  // sharedState.ledger remains partially mutated with no byte-level snapshot
}
Fuel-metered Wasm Worker + OPFS rollback
// Dedicated Worker hosts 64 KiB .wasm memory + OPFS SyncAccessHandle checkpoints
const vm = new Worker("/vm-worker.js", { type: "module" });

vm.postMessage({ requestId: 1, action: "saveCheckpoint", label: "clean-base" });
vm.postMessage({
  requestId: 2,
  action: "runWorkload",
  kind: "run_steps",
  steps: 500,
  fuelLimit: 50, // traps with WebAssembly.RuntimeError (unreachable) at fuel == 0
});
// Restore linear memory deterministically from vm-ckpt-001-clean-base.bin
vm.postMessage({ requestId: 3, action: "restoreCheckpoint", filename: "vm-ckpt-001-clean-base.bin" });
Complete Page Setup: Presets, Worker RPC & OPFS SyncAccessHandle I/O

End-to-end wiring from public/index.html, public/lib/vm-snapshots.js, public/app.js, public/vm-worker.js, and src/worker.ts: the page sends fuel-limited workloads to a module Dedicated Worker that executes a generated 1-page WebAssembly binary and reads/writes raw 64 KiB vm-ckpt-*.bin snapshots via OPFS FileSystemSyncAccessHandle.

<!-- 1. Page HTML Setup (public/index.html) -->
<form id="workload-form">
  <select id="input-kind"><option value="run_steps">run_steps</option></select>
  <input id="input-steps" type="number" value="200">
  <input id="input-fuel" type="number" value="5000">
  <input id="input-offset" type="number" value="0">
</form>
<tbody id="checkpoint-tbody"></tbody>
<div id="memory-byte-grid" class="byte-grid"></div>
<script type="module" src="/app.js"></script>

// 2. Concrete Fuel Presets & Checkpoint Binary Format (public/lib/vm-snapshots.js & public/vm-worker.js)
export const WASM_PAGE_SIZE = 65536;
export const VM_PRESETS = Object.freeze([
  Object.freeze({ id: "counter-fill", name: "Counter Fill (200 steps, fuel 5000)", kind: "run_steps", steps: 200, fuelLimit: 5000, offset: 0, expectedOutcome: "completed" }),
  Object.freeze({ id: "fuel-trap", name: "Fuel-Exhaustion Trap (500 steps, fuel 50)", kind: "run_steps", steps: 500, fuelLimit: 50, offset: 0, expectedOutcome: "trap" }),
  Object.freeze({ id: "string-patch", name: "String Buffer Patch (offset 0x0100)", kind: "patch_bytes", steps: 24, fuelLimit: 256, offset: 256, payloadText: "VM_STATE:PATCHED_OK_2026", expectedOutcome: "completed" }),
]);
// Binary format: raw 65,536-byte WebAssembly.Memory dump in OPFS file `vm-ckpt-001-<tag>.bin` + SHA-256 hashMemoryBytes()

// 3. Host Bootstrap, Dedicated Worker SyncAccessHandle OPFS Checkpoint/Restore & Edge Headers
const worker = new Worker("/vm-worker.js", { type: "module" });
worker.postMessage({ requestId: 1, action: "runWorkload", kind: "run_steps", steps: 500, fuelLimit: 50, offset: 0 });
// public/vm-worker.js — instantiate generated .wasm kernel & persist via SyncAccessHandle:
const compiled = await WebAssembly.instantiate(buildFuelWasmModule());
const memory = compiled.instance.exports.memory;
const rootDir = await navigator.storage.getDirectory();
const handle = await rootDir.getFileHandle("vm-ckpt-001-clean-base.bin", { create: true });
const access = await handle.createSyncAccessHandle();
try {
  access.truncate(0);
  access.write(captureMemoryBytes(memory), { at: 0 });
  access.flush();
} finally { access.close(); }
// Restore path: access.read(out, { at: 0 }) -> restoreMemoryBytes(memory, out);
// src/worker.ts emits CSP `script-src 'self' 'wasm-unsafe-eval'; worker-src 'self' blob:` + GET /api/presets
Core Plumbing Required Today (Wasm Kernel Execution & Snapshot Diffing)
// public/lib/vm-snapshots.js — exported .wasm kernel + linear memory snapshot helpers
const wasmBytes = buildFuelWasmModule(); // exports: memory (65536 B), run_steps, mutate_cell
const { instance } = await WebAssembly.instantiate(wasmBytes);

// public/vm-worker.js — fuel-metered execution + OPFS FileSystemSyncAccessHandle I/O
try {
  remainingFuel = instance.exports.run_steps(steps, fuelLimit, offset);
} catch (err) {
  trapped = err instanceof WebAssembly.RuntimeError; // unreachable on fuel == 0
}
const access = await fileHandle.createSyncAccessHandle();
access.truncate(0);
access.write(captureMemoryBytes(instance.exports.memory), { at: 0 });
access.flush();
access.close();
What disappears

Unmetered main-thread dynamic script execution, shared mutable JS object heaps across untrusted tasks, and manual ad-hoc cleanup after partial failures.

What becomes explicit

Instruction fuel budgets compiled into .wasm bytecode (run_steps(steps, fuelLimit, offset)), deterministic traps, SHA-256 memory digests, and byte-exact OPFS snapshots (vm-ckpt-*.bin).

Platform gaps remaining

WebAssembly offers no built-in runtime instruction-interrupt timer without guest instrumentation or fuel counters, and cross-origin restricted iframes fall back to an in-Worker Map when OPFS sync handles are blocked.