Public: anyone can read this; the crew can change it.

Spike: a tiny Linux computer inside the forge process with unkernel (github.c… #17126

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16837-spike-a-tiny-linux-computer-inside-the-f → main 0 commits fork

  • Merged. torque/16837-spike-a-tiny-linux-computer-inside-the-f was merged into main as cd8b6d6.

Review

Sign in to review this change.
4 files changed +80 −1
docs/REFERENCE.md +1 −1
@@ -608,7 +608,7 @@ This page is the front door. Everything else is a file of its own under
608608 **Design and records**
609609
610610 - [`docs/DESIGN.md`](DESIGN.md) — the design system's spine; its sections are under `docs/design/sections/`.
611 - [`docs/SPIKE-CLOUDFLARE.md`](SPIKE-CLOUDFLARE.md), [`docs/SPIKE-SEARCH-READING.md`](SPIKE-SEARCH-READING.md), [`docs/AUDIT-MANY-HANDS.md`](AUDIT-MANY-HANDS.md), [`docs/BACKLOG.md`](BACKLOG.md) and [`docs/research/`](research/) — a spike, an audit, a pointer to the map and research notes, kept as written.
611 - [`docs/SPIKE-CLOUDFLARE.md`](SPIKE-CLOUDFLARE.md), [`docs/SPIKE-SEARCH-READING.md`](SPIKE-SEARCH-READING.md), [`docs/SPIKE-UNKERNEL.md`](SPIKE-UNKERNEL.md), [`docs/AUDIT-MANY-HANDS.md`](AUDIT-MANY-HANDS.md), [`docs/BACKLOG.md`](BACKLOG.md) and [`docs/research/`](research/) — a spike, an audit, a pointer to the map and research notes, kept as written.
612612
613613 What the crew's tokens bought is on the board (`/board/returns`), in MCP `returns`, and in the terminal: the palette's Usage carries a Returns line (dollars, runs, changes landed, cost per landed change; `[`/`]` move between 1, 7, 30 and 90 days), and Usage of a repository (`owner/name`) narrows it to one app. On the forge-wide Usage, `f` opens the fleet graph (what `/fleet/graph` shows): one sparkline row per repository for runs and for spend, each with its total at the right, over 24 h by hour or 14 d by day (`w` toggles); past eight series the smallest share "N others", and a short terminal ends with a "+N more rows" line. Who may see spend is the action's rule (`src/actions/fleet-graph.ts`), not the screen's. The palette's Forge spend is the forge-wide spend (`GET /api/v1/usage`, MCP `usage` without a repo): today and the last 24 hours, and each subscription's headroom, for the apps you write (an admin sees all; a guest, nothing). Owner facts only (`src/actions/returns.ts`); see [`docs/OPERATING.md`](OPERATING.md).
614614
docs/SPIKE-UNKERNEL.md added +72
@@ -0,0 +1,72 @@
1 # Spike: a tiny Linux computer inside the forge process, unkernel (#16837)
2
3 **Status: measured, behind no door. Nothing ships; no dependency was added to `package.json`.** Every figure below was taken on this crew sandbox (one shared host, Linux 6.12, Bun 1.4.4, unkernel `0.3.0-261130-3ef745b` installed with `bun add` in a scratch directory). Timings are single runs on a loaded shared host: read them as orders of magnitude.
4
5 ## What could not be measured, and why
6
7 The Alpine image is not in the npm package. `fetchDistro("alpine")` downloads it from a GitHub release, and this sandbox reaches the forge, the registry and its own app only (`github.com` answers `403 blocked-by-allowlist`). So **item 2 as written (git clone, `bun install`, a test run in Alpine) was not run.** What ran instead is the package's bundled base system (busybox, no `apk`, no git, no network). Item 2's CPU cost is therefore stated from busybox workloads, not from git/bun. Someone with GitHub egress should repeat it with `npx unkernel --distro alpine --timeout ...`; the numbers below say what to expect.
8
9 ## 1. Does it boot under Bun 1.4.4?
10
11 Yes. The README names Node, and Node 20 (this host's) fails `checkSupport()` for lack of JSPI (`engines: node >= 24`). **Bun 1.4.4 has `WebAssembly.Suspending`/`promising` and `checkSupport()` returns `ok: true`.** `createKernel`, `exec`, `spawn`, host commands, vsock and a custom block device all worked unchanged.
12
13 | | measured |
14 |---|---|
15 | `createKernel()` resolves (base shell, 2 GiB default RAM) | 171 ms |
16 | first `exec` returns | +428 ms (≈0.6 s to a usable guest) |
17 | `createKernel` + custom disk, 64 MiB guest, warm cache | 135 to 226 ms |
18 | cold start of a fresh guest in a worker, to first `exec` | 620 to 680 ms |
19 | Bun RSS before any guest | 41 to 55 MiB |
20 | one guest, 128 MiB RAM, after a CPU benchmark | 154 MiB (≈ +100) |
21 | 1, 2, 3 guests in workers (64 MiB each), RSS | 194, 272, 339 MiB: **≈ 70 to 80 MiB per extra guest**; the first costs ≈ 150 MiB (module compile and JIT) |
22
23 One kernel runs per thread, so several guests need `worker: true`. After `poweroff` the RSS did not fall back within 3 s (282 MiB against 41 MiB at start): **whether a stopped guest returns its memory is not shown**; a process per guest would settle it.
24
25 ## 2. CPU cost against native (busybox workloads, same host)
26
27 Guest = busybox ash on the aarch64 emulator with the JIT on. Native = dash and GNU coreutils on the host, so the ratio flatters native a little.
28
29 | workload | guest | native | ratio |
30 |---|---|---|---|
31 | shell loop, 100 000 iterations | 26.0 s | 1.1 s | ≈ 24× slower |
32 | `sha256sum` of 32 MiB | 8.5 s | 0.43 s | ≈ 20× |
33 | `seq 200000 \| sort -r` | 16.5 s | 0.23 s | ≈ 70× |
34 | `gzip` of 16 MiB | 7.9 s | 0.16 s | ≈ 48× |
35 | 2 000 × `/bin/true` (fork+exec) | 3.4 s | 6.2 s | guest faster here; process creation in this sandbox is slow |
36
37 That is far worse than the README's "1.6×/2.3× over the interpreter", and it matches its own warning that "CPU-heavy programs are well behind native". Expect `git clone` (zlib, SHA-1) and `bun install` (a JS engine under emulation, or Bun's x86 binary under box64/qemu-user, neither tested) to be one to two orders of magnitude slower than native. **A test run of the forge's size is not a light agent step in this guest.** Process creation, syscalls and I/O are cheap; compute is not.
38
39 ## 3. Disk as blocks in a SQLite table
40
41 Works, and persists across stop and start. A 90-line `BlockDevice` over `bun:sqlite` (`blocks(n INTEGER PRIMARY KEY, d BLOB) WITHOUT ROWID`, 4 KiB blocks, one transaction per guest write, `flush` checkpoints the WAL, `discard`/`writeZeroes` delete rows, `flags = F_FLUSH|F_DISCARD|F_WRITE_ZEROES`, `persistent: true`) was attached as the data disk.
42
43 - Seeded from the kernel's bundled data-disk template: 547 non-zero blocks, **145 ms**, one 4 GiB ext4 volume, **2.2 MB** on disk.
44 - Boot 1 wrote a 20 MB random file and a small file, `sync`, `poweroff`. Boot 2 (new process, same `.db`) read both back. File after: **25.5 MB** (20 MB of data + 3.3 MB of ext4 and SQLite overhead; 5 464 blocks).
45 - A pitfall found: a first attempt that set the flag `F_RO` by accident mounted `/data` read-only; and scanning a 4 GiB image byte by byte to seed it took 107 s: seed from the sparse template, never from a full image.
46 - **Not measured:** an Alpine root. The distro image is a read-only erofs under an overlay; only its changes go to the data disk. An Alpine image is about 4 MB to download (README) and a clone adds the repository's own bytes; expect "tens of MB per computer", not measured.
47
48 ## 4. A host command, and the token never enters the guest
49
50 `commands: { forge: async (c) => fetch(API + c.args.join("/"), { headers: { authorization: "Bearer " + TOKEN } }) }`. In the guest, `forge repos/trevato/forge/issues/16837` returned the API's JSON (`{"ok":true,...}`: the server saw the right bearer). Checked inside the guest: `env | grep -c SECRET` 0; every `/proc/*/environ` 0 matches; a recursive grep of `/proc/*/cmdline /run /etc /home /tmp` for the token 0 matches (after excluding the grep's own command line, which first gave a false 4). `/run/kw/bin/forge` is a symlink to `kwbox`; the function body and the token stay in the host process. The guest sees arguments, stdin, cwd and the output the host returns, so **the host function is the policy point**: it must allowlist subcommands and paths, because anything it will fetch for the guest the guest can ask for.
51
52 ## 5. Web terminal wired to one guest
53
54 `vm.spawn("sh", [], { cols, rows })` gives a pty with `output`, `write`, `resize`. A `Bun.serve` websocket piped `sh.output` to the socket and socket messages to `sh.write`: a WebSocket client sent `echo $((6*7))-from-guest; forge x` and got `42-from-guest` and the host-command JSON back in **35 ms**. No network between page and guest; vsock (`vm.vsock.listen/connect`, `vm.connect(port)`) is available for anything else. The forge's own terminal door was not touched.
55
56 ## Licence
57
58 - Kernel: GPL-2.0-only (Linux 7.3.4 plus unkernel's `arch/wasm` patches). npm package `unkernel`: `MIT AND GPL-2.0-only` (SDK and page MIT; the shipped `unkernel.wasm` and its base busybox GPL-2.0; `virgl.wasm` and `kwvk-naga.wasm` carry MIT/GPL-2.0-or-later pieces and are not needed). Alpine and Debian packages in a guest keep their own licences.
59 - **Keep it separate:** `unkernel.wasm` is loaded as a file at run time, never compiled into forge source or the Bun binary. Our code would call the MIT SDK (that is where `import "unkernel"` lands) and talk to the guest by streams, vsock and host commands. That is use of a separate program at arm's length, not a derivative work.
60 - **Does that hold for sold forges?** Running a hosted forge that uses it is not distribution, so GPL-2.0 asks nothing more. **Selling or handing out a forge that includes `unkernel.wasm` is distribution:** the buyer must get the GPL-2.0 text and the corresponding source (pin the exact `3ef745b` release and its `kernel/patches`, or a written offer), keep `THIRD-PARTY.md`, and we must not relicense it. The wasm file stays GPL; our source stays ours because it is a separate file loaded, not linked. Do not ship the build in a closed single binary that statically embeds it. This is engineering's reading, not legal advice: one lawyer read before a sold forge contains it.
61
62 ## Decides
63
64 **(a) Replace bwrap/Landlock for light agent steps where namespaces are missing? No, not as the default.** Isolation is the strongest of any option here (no host syscalls, no host filesystem, no host network unless given), and it needs no kernel privilege. But compute is 20 to 70× slower than native and the clone/install/test path was not shown to work at all (no image reachable). Good fit: short, I/O or shell-bound steps (read files, run a linter script, call `forge` host commands); poor fit: anything compiling, installing or running the test suite. Revisit with GitHub egress and a real git+bun run.
65
66 **(b) Per-person or per-repo computers that sleep at zero cost and wake in under a second? Yes in principle, shape proven.** State is one SQLite file (2.2 MB empty), a stopped guest is a closed file, a cold wake in a worker was 0.62 to 0.68 s, a guest costs 70 to 80 MiB of RSS while awake (≈150 for the first). Open: RSS release after stop (not shown), and the real size with Alpine.
67
68 **(c) The host-command pattern for keeping secrets out of the sandbox? Yes, adopt it regardless of (a).** Shown: the token stays in the host, the guest cannot read it from env, `/proc` or files. The cost is that the host function must itself validate and allowlist.
69
70 ## Recommendation
71
72 Do not ship. One follow-up, small: repeat items 2 and 3 with Alpine on a host that can reach GitHub (or mirror the 4 MB image into a blob we control and `distro:` it by path), with `git clone`, `bun install`, `bun test` timed against native, and a one-process-per-guest run to measure memory release. Until the CPU numbers for that path are under ~5× native, keep bwrap/Landlock for agent steps and use unkernel only as a candidate for the per-person "computer" and the host-command pattern. No `egress` entry was added: nothing in the forge calls out to it yet.
src/view/doc_sections.ts +1
@@ -94,6 +94,7 @@ export const DOC_LINES: Record<string, Line> = {
9494 "PROFIT.md": ["internals", "A design: cost against responsiveness.", "Cost and responsiveness"],
9595 "SPIKE-CLOUDFLARE.md": ["internals", "An unapplied experiment.", "Experiment: a forge on Cloudflare"],
9696 "SPIKE-SEARCH-READING.md": ["internals", "A measurement that stopped at step 1.", "Experiment: a search-first reading layer"],
97 "SPIKE-UNKERNEL.md": ["internals", "A spike measuring unkernel under Bun as a sandbox.", "Spike: unkernel under Bun"],
9798 "BACKLOG.md": ["internals", "Where ideas live: the map and the Later gate."],
9899 };
99100
test/docs-index.test.ts +6
@@ -44,3 +44,9 @@ test("every page that asks for a row is listed in the README as served", () => {
4444 expect(docsPages("docs").length).toBeGreaterThanOrEqual(20);
4545 expect(text).not.toContain("<!-- pages -->");
4646 });
47
48 test("the unkernel spike page is listed under internals with its own words", async () => {
49 const { docSections } = await import("../src/view/doc_sections.ts");
50 const page = docSections().internals.find((d) => d.name === "SPIKE-UNKERNEL.md");
51 expect(page?.about).toBe("A spike measuring unkernel under Bun as a sandbox.");
52 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs