carlos / platform Public

docs: plan for gVisor on flagship demo boxes

Four slices, from a Fable 5.2 audit of the gVisor path (2026-11-16):
1. bound the root control service (F3) and purge (F6), which apply
   today under the native sandbox;
2. demo boxes must state their sandbox explicitly, with an alert on
   intent vs effective mode and a pinned runsc argv (F2, F7);
3. measured host-side runsc containment and separate diagnostic
   streams (F4, F9);
4. the flagship flip in a #421 window, in the runbook order.
Per-demo disk bound (F5) is cut to its own design. Reviewed by Astra
(2 rounds; round 2 no P1, P2s applied).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from gvisor-flagship-demos-plan into main.
claude agent, operated by paul@keymail.dev d93fb17156e07501b0378a741987b2c3d0307ee1 parent 15b1ee6
1 file changed, +166 −0
  • docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md +166 −0

CI passed — run details

diff --git a/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md b/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md
new file mode 100644
index 000000000..6a77d2b51
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-16-gvisor-flagship-demos.md
@@ -0,0 +1,166 @@
+# gVisor on flagship demo boxes: plan (rev 2.1)
+
+**Goal:** flagship demo boxes run anonymous demo code under gVisor (runsc), not the native systemd sandbox. A demo box that isn't explicitly configured for one or the other admits no demos.
+
+**Why now:** flagship demos have been live since 2026-11-11 under the native sandbox. gVisor was built for exactly this workload and has run on the dev demo box since 2026-11-11 (v0.34.47, witness PASS). Paul agreed on 2026-11-16 that we should have a plan.
+
+**Authorities (merged on main):** `docs/superpowers/specs/2026-11-08-gvisor-demos-design.md` (rev 5.5; §4.1 sequences the default), `docs/superpowers/runbooks/gvisor-demos.md` (the dev rollout, whose checks slice 4 carries forward), `docs/superpowers/plans/2026-11-08-gvisor-demos.md`.
+
+**Evidence:** a Fable 5.2 audit of the gVisor path at 3793aa49 (2026-11-16; summary on discussion #1096; findings F1 to F10). It found no path from the payload to root, other tenants or platform state.
+
+**Review history:** round 1 (Astra) was NOT READY, with 4 P1s and 6 P2s; rev 2 answered them. Round 2 (Astra) found no P1 and 7 P2s; rev 2.1 applies those P2s without another round (AGENTS.md stopping rule 1). Both findings files are in `~/.cache/sec-review-20261116/reviews/` on docs-t1 (G-R1-astra.md and G-R2-astra.md).
+
+**Scope:** demo boxes only. Shared pools are a separate, later plan: they need networked egress under gVisor and a cost ruling.
+
+## Facts settled
+
+- **Architecture (F1):** `carlos-flagship-demo-box-1` is t4g.small, arm64 (checked 2026-11-16, profile keymail), the only witnessed architecture. The amd64 witness is owed only if an amd64 demo box is ever added.
+- **One demo box, demos only:** the flagship demo box serves nothing but demos, so a demo-triggered disk or memory exhaustion there takes down the demo service on that box, not other tenants. That is why F5 is cut to its own design below.
+- **Where the setting lives:** `CARLOS_DEMO_BOX` and the demo tuple live in each demo box's root-owned `/etc/carlos/host.env`, preserved by the same per-box mechanism as `CARLOS_FLEET` (README "demo box settings"). `CARLOS_EXEC_SANDBOX` goes in the same file through the same mechanism. Slice 2's first task finds that producer for flagship. If it lives in an infra repo, that change needs scoped approval (AGENTS.md production infrastructure rule).
+
+## Sessions and finish lines
+
+Each slice is its own branch and its own session, and each ends when that slice merges. The handoff (`amadan branch handoff`) carries this plan's review history. Slice 4 is an operation, run in a #421 window by whoever holds the release lock (8a3d302), not a build session.
+
+## Slice 1: bound the root control service's memory (F3) and purge (F6)
+
+Both apply today under the native sandbox, so this slice ships first and protects flagship now.
+
+1. **F3: build output can OOM the root control service.**
+ - **Problem:**
+ - root reads a build output of up to 32 MiB (`internal/demobuild/runner.go` `ValidateOutput`, `io.ReadAll`);
+ - it carries it as `BuildOutput.Binary []byte` (`internal/demobuild/job.go`);
+ - it JSON-encodes it, as base64, into the control response (`internal/instancectl/demo_build.go`);
+ - all of this happens inside `carlos-instance-control` (`MemoryMax=64M`), with up to 4 build slots.
+ - **Fix: bound the peak rather than re-architecting the transport.**
+ - Validate by streaming: `elf.NewFile` over the open file, and sha256 by `io.Copy`.
+ - Admit one output transfer at a time, behind a process-wide semaphore of 1 held from read through response write; other finished builds wait their turn.
+ - Raise the control service's `MemoryMax` to a measured figure covering one transfer (about 32 MiB raw, about 43 MiB base64, plus encoder buffers) on top of today's baseline. 192M is the starting estimate; the measured peak sets the final value.
+ - Keep the size, ELF-segment and digest checks unchanged.
+ - Cleanup: today `Worker.Build` runs its deferred output-dir cleanup before returning, and `handleDemoBuild` encodes afterwards from the in-memory bytes (`worker.go:272`, `demo_build.go:167-174`). Keep that ordering, since the response holds the bytes. Streaming from the file would need an explicit change of who owns the file and when it is cleaned up, which this slice does not make.
+ - **Acceptance:**
+ - The authority is the whole control service under its proposed cgroup cap on the dev demo box. Run builds at the supported concurrency (4 slots, at least one 32 MiB output) and record the cgroup's `memory.peak` and `memory.events` oom/oom_kill counts. Pass: peak under `MemoryMax`, zero OOM events.
+ - Unit tests: four concurrent finished builds serialise and all succeed, and the unit-text test pins the new `MemoryMax`.
+ - Heap sampling is a diagnostic only.
+ - **Why not stream the binary to the agent (fd passing):** it changes the client/upload contract across root and the agent, for a box class that runs only demos. It can be a follow-up if build concurrency grows.
+2. **F6: purge fails on deep or huge trees.**
+ - **Problem:** `internal/instancefs/dirs_linux.go` `removeAt` refuses depth > 64 and calls `Readdirnames(-1)`.
+ - **Fix:** an iterative removal with a fixed budget of at most 3 live directory descriptors, temporary ones included.
+ - It keeps a stack of name components, not fds. To reach a directory it walks from the purge root ONE COMPONENT AT A TIME: `openat2(parentfd, name, RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS|RESOLVE_NO_MAGICLINKS)`, then closes the parent. No joined pathname is ever passed to the kernel, so total path length (beyond PATH_MAX) does not matter. The walk is quadratic in depth, which is accepted.
+ - It reads entries in batches of 256.
+ - The name stack is bounded at 65,536 components (at most about 16 MiB of names). Past that, purge refuses with "too deep", leaves the tree, and marks the demo for operator recovery (`carlos` box verb, documented in the runbook). This is a reachable refusal, accepted; the guest has no directory-depth limit.
+ - **Tests:**
+ - a tree whose total path is over 64 KiB (long 255-byte names), and a 10,000-deep tree, both purge with `RLIMIT_NOFILE` set to 16;
+ - a 100k-entry directory purges with bounded memory;
+ - a directory swapped for a symlink between batches is not followed;
+ - an interrupted purge (error injected mid-walk) resumes and completes on retry.
+
+The census applies (`internal/demobuild`, `internal/instancefs`, `internal/instancectl` and `internal/host/units`). Release with the usual dev-first roll; the dev demo box witnesses one large build and one deep purge.
+
+## Slice 2: demo boxes must state their sandbox (F2), with an alert and a pinned argv (F7)
+
+1. **Explicit, not `auto`.**
+ - A demo box (`CARLOS_DEMO_BOX=1`) whose `CARLOS_EXEC_SANDBOX` is unset or `auto` refuses demo admission and builds, and reports `sandbox: unset on a demo box` in its status. It must state `gvisor`, or `systemd` as an explicit, visible opt-out.
+ - This replaces the design §4.1 `auto` flip. It does not depend on recognising a demo box before its configuration exists: an unconfigured box isn't a demo box and admits no demos.
+ - **Downgrade safety:** the box keeps explicit `gvisor` in host.env, so an older aware release (protocol 1) honours it, and nothing ever relies on `auto`.
+ - **Tests:** config table tests for demo box × {unset, auto, systemd, gvisor} × {aware, older floor}; the admission refusal end to end; and the status field.
+2. **Flagship sequencing (answers the "slice 2 activates early" finding).**
+ - Before slice 2 rolls to flagship, set `CARLOS_EXEC_SANDBOX=systemd` explicitly in the flagship demo box's host.env through the producer, with a backup copy kept. That makes the slice-2 roll a no-op for the mode.
+ - The roll then changes nothing until slice 4 flips that one line. Dev's demo box already says `gvisor`.
+3. **Alert.**
+ - **Expected boxes:** enumerate the demo fleet's non-detached boxes through `registry.ListFleetBoxes` (`internal/registry/fleets.go:685`), with the fleet from the console's `CARLOS_DEMO_FLEET`. Then join each box's report from `fleets/<fleet>/status/boxes/` onto those identities. A registered box with no report, an aged-out or deleted report, or a failed registry or listing read raises the alert as "unknown".
+ - **Intent:**
+ - Add a `sandbox_intent` column to demo settings (`internal/console/demo_store.go`; an additive migration, default `systemd`).
+ - It changes only through an ops-owner CLI/API door with step-up: `carlos demo sandbox-intent gvisor|systemd`, audited.
+ - Slice 4 sets it to `gvisor` when it flips.
+ - **Fires** when a box's effective sandbox differs from the intent.
+ - **Review gates:** the alert's text, and any sandbox field shown in the console, go through the UX pass and copy review before merge (AGENTS.md).
+ - **Also fires** when the report is absent, unreadable or older than 3 heartbeat intervals, when gVisor reports blocked (not Ready), and when the mode is unset.
+ - **Detached boxes** and a deliberate rollback, recorded by setting intent back to `systemd`, are quiet.
+ - "Quiet" never counts as success: slice 4's witness also requires a fresh positive report.
+ - **Tests:** rule registration, the incident lifecycle (open, resolve) and notification, through the existing alerts engine tests.
+4. **F7:** add `--platform=systrap` and an explicit `--directfs=` value (the value chosen in slice 3 step 1; until then the release's current default, written out) to the one argv constructor (`internal/execsandbox/command.go`), and to the `systemctl show` assertions derived from it.
+
+**Switch-on date:** the code is live on merge (it refuses unset demo boxes; flagship is explicit `systemd` first, so nothing changes there). The gVisor switch-on is slice 4's window. This branch must not merge until that window is booked with 8a3d302 (AGENTS.md stopping rule 5).
+
+## Slice 3: host-side runsc containment (F4) and diagnostics streams (F9)
+
+1. **F4: measure, then pin, in this order.**
+ 1. Choose the `--directfs` value (it changes which host capabilities the gofer and sentry need).
+ 2. On the disposable root runner (`root-runner`, its own approval scope), measure the minimal capability set and syscall needs for run, build, probe and the stop hooks together. The `instance-exit` hook needs `fchown`. The pinned gofer retains CHOWN, DAC_OVERRIDE, DAC_READ_SEARCH, FOWNER, FSETID and SYS_CHROOT, and runtime setup adds more: measure, don't guess.
+ 3. Pin these in every gVisor template (`carlos-instance-gvisor@`, `carlos-demo-build-gvisor@`, `carlos-instance-gvisor-probe`) AND in the shared assertion set (`internal/execsandbox/hardening.go` `GVisorHardening`, consumed by `internal/instancectl/gvisorunit.go`):
+ - `CapabilityBoundingSet=` (the measured set);
+ - `IPAddressDeny=any` (no host IP traffic expected with `--network=none`; confirmed by witness);
+ - `InaccessiblePaths=/etc/carlos` plus any other root secret path;
+ - `NoNewPrivileges=yes`, if runsc tolerates it.
+ 4. Witness the effective denial: from inside the unit's own context, an attempted host IP connect and a read of `/etc/carlos` both fail. Then witness the full dev runbook on the dev demo box (a separate approval scope from the root runner).
+2. **F9: separate the streams.**
+ - **Problem:** pinned runsc passes its own stderr through to the guest, so `StandardError=journal` would also take the app's stderr away.
+ - **Fix:** route runsc's own diagnostics with runsc's `--debug-log`/`--log` flags to a root-owned file or the journal. Keep guest stdout and stderr on the existing log socket.
+ - **Root hooks:** the `carlos instance-exit` hook and every runsc lifecycle command the unit runs (`gvisorCommands`: run, kill, delete and the probe) never inherit tenant-facing stderr. Each writes its diagnostics to the journal, through `systemd-cat` in the command line or the binary logging to the journal directly. Pick whichever needs no new unit privilege.
+ - Cap the listener (`internal/activator/loglistener.go`) before BOTH sinks: the tenant sink, which already has 1 MiB/minute and a ring (`internal/applog/sink.go`), and agent stdout, which today is uncapped. Bytes over the cap are still drained, and counted in a "dropped" line.
+ - **Tests:** guest stdout and stderr both still reach the tenant log; a runsc error doesn't, and neither does a forced `instance-exit` failure; a flood is drained and reported as dropped.
+
+Slice 3 is required before shared pools. For the demo flip, Paul decides at slice 4 whether it is required or waived.
+
+## Slice 4: flagship flip (an operation, in a #421 window)
+
+**Preconditions:**
+- Slices 1 and 2 are released and rolled to flagship, with the demo box's host.env saying `systemd` explicitly.
+- Slice 3 is released, or waived by Paul.
+- The dev witnesses the earlier rollout deferred are done on dev:
+ - the claim finished by a person under gVisor;
+ - two concurrent builds and two concurrent demos;
+ - a roll that changes the runsc pin;
+ - a rollback from gVisor to systemd.
+
+**Steps,** in the window, with Paul's go and the version from 8a3d302, in the runbook's order with the box name substituted:
+1. **Before the change:** approval recorded; the five runsc assets readable through the box's own store access; privileged acceptance on the current commit; baseline. Then native Ready and drain.
+2. **The change:** flip host.env `systemd` to `gvisor` through the producer, keeping a backup copy, then the coordinated restart of control and the agent.
+3. **After the change, the gVisor witnesses:**
+ - the Ready/probe result;
+ - the five installed member hashes;
+ - instance sandbox status;
+ - full starter build and `Worker.Initialize`;
+ - a disposable demo created, updated, woken and claimed;
+ - a fresh `X-Carlos-Version` receipt;
+ - `/proc/net/dev` read INSIDE the guest, showing loopback only;
+ - a fresh positive report of effective `gvisor`.
+
+ Only then set the console's sandbox intent to `gvisor`.
+
+Rollback is a conditional procedure, not part of the initial run (below).
+
+**Witness demos are disposable:** create, update, wake and claim a throwaway demo. Its claim and deletion are not undone by a rollback, so never use a real visitor's demo. Record the account, region, resources and cleanup in the roll log.
+
+**Rollback:** follow the runbook's rollback: drain, prove the gVisor family is gone, set host.env back to `systemd`, record the intent, restart, and check for a fresh positive `systemd` report. The alert stays quiet because intent matches.
+
+## Cut: per-demo disk bound (F5) gets its own design
+
+- **Why not a scan:** the round-1 review showed a scanned cap cannot stop exhaustion. Unlinked open files and fast writes outrun it, and stopping outside the activator's fences is unsafe (`internal/instancectl/hardening.go:539`).
+- **What a real fix needs:** an enforced boundary. That means a per-demo or aggregate demo filesystem with reserved backing space, inode limits, mount, recovery and purge handling, survival across hibernation, readability during claim export, and native/gVisor parity. That is a design, not a plan task.
+- **Interim (no new code), and what it actually covers:** the flagship demo box runs only demos, so exhaustion is a demo-service outage on that box, not another tenant's.
+ - The existing early disk alert (`internal/host/probes.go` `readDiskFrac`) measures free blocks on `/data` only.
+ - Before relying on it, confirm that the flagship demo box's alert delivery is configured, and record the evidence on #1096.
+ - **Accepted, uncovered:** `/run` tmpfs exhaustion and inode exhaustion can take the demo service down with no warning. That outage is accepted until the F5 design lands.
+ - File the design as a follow-up on #1096.
+
+## Not in this plan
+
+- Shared pools.
+- F8 (guest `noexec` parity) and F10 (fail-closed 503s during rolls); both go on the #1096 follow-up list.
+
+## Round 1 dispositions
+
+| Finding | Disposition |
+|---|---|
+| P1 F3 OOM path | Accepted. Slice 1.1 bounds the peak (one-at-a-time transfer, measured cap, heap high-water test) instead of only streaming validation. |
+| P1 F5 scan insufficient | Accepted. Cut to its own design, with the interim reasoning stated. |
+| P1 slice 2 activates early | Accepted. Explicit `systemd` goes on flagship before the roll, and the flip is the slice 4 line change. |
+| P1 F2 fresh box / downgrade | Accepted. Explicit setting required on demo boxes, `auto` not relied on, admission refused when unset. |
+| P2 alert source and unknown state | Accepted (slice 2.3). |
+| P2 F6 descriptors | Accepted (slice 1.2: 2 fds, name stack, low-NOFILE test, interruption, symlink swap). |
+| P2 F4 scope | Accepted (slice 3.1: directfs first, all templates plus shared assertions, effective-denial witness, separate approval scopes). |
+| P2 F9 streams | Accepted (slice 3.2). |
+| P2 slice 4 evidence | Accepted (runbook checks verbatim, guest-side `/proc/net/dev`, disposable demos, full rollback). |
+| P2 sessions and switch-on | Accepted (sessions section; slice 2 waits for a booked window). |