# Browser Linux runtime

The course executes native Bytewax 0.21.1 and confluent-kafka 2.6.1 in an x86-64 Linux VM inside a Web Worker. The kernel/emulator is the open container2wasm/Bochs distribution. It preserves the Linux-in-Wasm architecture validated with JSLinux, with self-hosted assets and documented open-source components.

The base is the unmodified `amd64-python-wasi-container00..02.wasm` image distributed by [container2wasm-demo](https://github.com/ktock/container2wasm-demo/tree/8228aaa4a7c9d179cbe266a119e69f58746f1742). Its [image source](https://github.com/ktock/container2wasm-demo/blob/8228aaa4a7c9d179cbe266a119e69f58746f1742/src/amd64-python-wasi/image), [conversion script](https://github.com/ktock/container2wasm-demo/blob/8228aaa4a7c9d179cbe266a119e69f58746f1742/create-images.sh), and container2wasm 0.6.3 source/build recipe identify the upstream distribution. SHA-256 checks reject changed upstream bytes. We do not copy or serve JSLinux's unreleased x86-64 emulator.

The image's original Python is unused. `Dockerfile` builds a separate native CPython 3.12 runtime and current Debian Bookworm libraries from an exact official Python image digest. `build_bundle.py` collects each library under the SONAME requested by the dynamic loader, retains package notices and creates unchecked-hash bytecode that does not depend on WASI file timestamps. `wheels.lock.json` records exact package versions, URLs and digests.

## Build

Requires Linux x86-64, Docker, Python 3.12 and Node 24+. Runtime compilation is not performed on the learner's device.

```
python3 runtime/prepare.py
npm run build
```

The preparation script verifies/downloads the three base-image chunks and wheels, builds the Python bundle in Docker, then writes `assets/linux/manifest.json` with lengths and hashes. The same builder inputs reuse the cached local bundle. Generated binaries and wheels are excluded from git; Pages publishes the generated files as static artifacts. The full first download is about 84 MiB. Initial setup requires access to GitHub Pages, PyPI and Docker Hub; the published course runtime fetches only its own origin.

`src/linux-worker.js` compiles the base image, decompresses the Python bundle in JavaScript, and exposes its files through WASI's virtual filesystem. Linux sees that share through 9P. The dynamic loader is copied into the guest's writable filesystem to give it executable permissions; it loads the correctly named Debian libraries from the share. No guest tar extraction or package installation is needed. Compressed VM chunks are also inflated in JavaScript, reducing transfer size while retaining the verified original engine bytes.

Each source submission gets a new VM instance and writable overlay. Python reads the editor source from a virtual file. `runner.py` captures the program's Python output and sends an actual JSON result frame; absence of that frame is an error, never a worked-result fallback. Stop terminates the Worker. The worker’s host polling honors clock deadlines and keeps its empty nonblocking stdin open without reporting EOF. No SharedArrayBuffer, service worker or special hosting headers is required. A 60-second boot watchdog permits one initialization retry before Python starts; user programs are never automatically retried, and exports record initialization retries. The runner creates a private Linux user/network namespace, maps the existing guest identity and enables loopback. The base container drops NET_ADMIN and leaves loopback down; the private namespace fixes this without changing the emulator or granting capabilities outside the guest. There is no guest network bridge: Kafka sockets remain on loopback.

`recovery_drill.py` starts a real child process, observes a completed Bytewax checkpoint, sends SIGKILL and restarts the child. Files survive that process kill but disappear with the VM. `live_kafka.py` runs a separate engine process and sends each subsequent record only after the previous result is received. Both are correctness demonstrations, not production capacity tests.

## Source and component licenses

See [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). The exact upstream container2wasm build recipe is preserved in [vendor/container2wasm-v0.6.3.Dockerfile](vendor/container2wasm-v0.6.3.Dockerfile), with upstream compiler, kernel, initialization and emulator references. The upstream repository includes the patched Bochs sources in `patches/bochs/Bochs` and their license. Runtime binaries retain their component licenses; the course's prose/code license does not replace them.

For a different base image, rebuild with the upstream conversion recipe, preserve corresponding source and notices, and update all three chunk checksums only after real browser execution. Changes to `Dockerfile`, `build_bundle.py` or `wheels.lock.json` invalidate the local Python bundle. A changed bundle manifest reflects the exact generated bytes rather than promising byte-identical timestamps between independent Docker builds.

## Run latency and caching

Fresh Linux mode boots a new guest for each Run; fast mode keeps Linux ready between clean process executions. Prepared assets stay in the page worker between runs. The browser can additionally keep verified, decompressed VM/Python asset bytes in IndexedDB across chapter navigation; compiled WebAssembly modules are not persisted. The cache holds one current manifest version, can occupy a few hundred MiB, contains no editor code, guest memory or results, and is disposable. Missing, denied or quota-limited storage falls back to normal verified downloads. Clearing this site's browser data removes it. Home pages, design readings and JavaScript-disabled reading start no VM. Executable lessons can prepare and cache the runtime after rendering, subject to Save Data, visibility and memory policy. No editor code runs before Run.

The tar is indexed once per worker and only read-only file bytes are shared. Fresh Linux mode creates new inodes, file positions, WebAssembly instance and writable guest overlay. Fast mode starts new isolated processes with private writable files. Python starts with its explicit bundled import paths and `-S`; the runner avoids loading unrelated metadata/platform/process modules. Runtime identification reads the installed distribution metadata. Source programs are never automatically retried.

Run exports include preparation, guest startup, execution and total milliseconds plus the asset source (`download`, `browser-cache` or `page-memory`). These include local emulation and do not measure native or distributed service throughput.

Guest startup spans WebAssembly instantiation, Linux boot and runner initialization. Execution spans the running marker through result collection, including program imports, serialization and result collection. It is not an isolated operator timer.

## Warm Linux with isolated Python processes

`warm-session.mjs` uses feature-detected JSPI (`WebAssembly.Suspending` and `WebAssembly.promising`) to suspend the VM while it waits for the next editor command. No SharedArrayBuffer, cross-origin-isolation headers, service worker or execution backend is required. The worker stays local to the current lesson page. Navigation, Stop and Reset Linux discard it. Browsers without JSPI use the existing fresh-guest path. Prepared asset caching remains separate and never stores source, guest memory or results.

`session_runner.py` preloads only whitelisted, authored helper modules. It verifies that the controller has one native thread before forking and never creates a socket or runs a dataflow in the controller. Every experiment uses a fresh process in new user, PID, network, mount, IPC and UTS namespaces. The experiment is PID 1 in its namespace; exiting it also terminates its descendants. A private tmpfs root supplies scratch files, with read-only binds for installed code and selected device files. The writable root is limited to 32 MiB, with separate temporary shared memory.

The base container locks nested procfs mounts, so fast mode leaves `/proc` unavailable; no synthetic proc data is supplied. Fresh Linux provides the original guest filesystem for system inspection. Fast runs share the Linux kernel and immutable installed runtime, not experiment globals, environment changes, scratch files or sockets. These are local experiment boundaries rather than a multi-tenant VM isolation claim.

A capability failure before student source starts can fall back to fresh Linux. A running marker is emitted only after process/filesystem/network initialization. Source is never automatically retried after that marker. Python errors leave the controller ready for another clean process; Stop or Reset terminates the whole worker/VM.

Exports report `mode`, `session_run` for warm runs, `elapsed_ms` from click through result (including retries), and per-attempt phase times. Warm reruns have zero guest-startup time; their process-startup phase includes namespace/filesystem preparation. Execution includes the actual program, any imports not preloaded and result collection. Cold starts, deliberate protocol waits and recovery subprocesses can still take longer. These are emulation timings, not native service throughput measurements.

## Automatic background preparation

The page schedules a `prepare` command after rendering and an idle callback on executable lesson pages. The worker verifies/downloads assets, compiles Wasm, starts Linux and imports the published lesson’s trusted helper modules. `WarmSession.prepare()` resolves at the controller’s initial ready marker; it sends no run command and executes no source. The controller then suspends on stdin through JSPI, without spinning while the learner reads.

Selecting Run during initialization joins the same preparation promise, then executes the current editor source exactly once. No duplicate guest is started and background failures never fabricate a result. Save Data, 2G and devices reporting at most 2 GiB memory defer preparation until Run; hidden pages wait until visible. Stop, navigation and Restart Python cancel scheduled preparation and terminate the worker. Restart preserves drafts and completed results. Compatibility fallback is automatic; `?runtime=fresh` is a diagnostic override, not a learner-facing mode selector.

Exports retain internal `mode` and timings. `background_ready_on_click` compares the controller-ready time with the host’s click timestamp, even if a busy worker processes that message later. `background_preparation.total_ms` measures startup done in the background; `elapsed_ms` measures only the actual button-to-result wait, including any unfinished setup. The first student execution still has `session_run: 1`.
