Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

81.0 KB
Raw Blame

TL;DR

One runner service manages many BoxLite VMs and exposes their lifecycle, execution, files and telemetry.

BoxLite Runner

Memory quotas

Create and recovery memoryQuota values are GiB numbers, including exact fractions: 0.29296875 maps to 300 MiB in the runtime's WithMemory option. The conversion rejects non-integral MiB, non-finite values, values below 128 MiB, and values beyond the runtime option's unsigned 32-bit MiB range before runtime side effects. Backend and host limits still apply. Internal callers that omit memory retain the historical 128 MiB default; HTTP requests must supply at least 0.125 GiB. Cloud enforces the same 128 MiB minimum and its organization quotas. Upgrade Runners before Cloud starts sending fractional-GiB quotas; older Runners decode this field as an integer and reject them.

Nested virtualization capability

Cloud requests nesting when creating a Box. Runner captures its process BOXLITE_EXPERIMENTAL at startup and combines authorization with current Linux Intel/AMD KVM nested settings. Missing permission or unsupported hosts select an ordinary new Box. Guest privilege remains independent.

V0 /info reports nestedVirtualizationEnabled; Cloud carries the report through its authenticated V2 heartbeat. Actual creation uses the standard Go AdvancedBoxOptions.SetNestedVirtualization binding. Runtime create saves this existing option in BoxConfig. No Cloud per-box database field is added.

Start uses ordinary Box.Start(ctx) and the saved configuration. Organization allowlist changes affect future creates, never upgrade or downgrade an existing Box on stop/start. Creation replay adopts the existing choice. Local runtime compatibility checks, kernel and privileged settings retain their main behavior. A nested Box can fail to start if its host later cannot provide that capability.

There is no private Runner start bridge, start-option ABI or Runner-only SDK build tag. Runner tests cover creation/replay and optional fallback without booting VMs; real VM/L2 and cross-Runner reconstruction require separate qualification.

Cloud stages deliver process settings through BOXLITE_RUNNER_ENV.


SSH authentication evidence

Runner builds set the Go build tag boxlite_runner to read accepted SSH sessions through a private native bridge. The collector polls running Cloud boxes and drains the Guest's bounded memory queue using the Runtime's existing session. Empty or stopped boxes stay stopped. Each observation contains only a stable event ID and timestamp.

Regenerating the runner client

With Java 11 or newer available, run make generate:runner-client from the repository root after updating the committed runner Swagger schema. This generates the TypeScript client without starting the control-plane API or requiring its database configuration.

Secret recovery safety

Secret headers maps survive creation and recovery. Recovery validates all header names, templates, control bytes and host/header conflicts before destroying the existing Box; invalid saved configuration leaves its identity and stored state intact. Direct creation uses the same check, including rejecting missing, null and empty maps, with an error asking the caller to recreate the box with headers.

Upgrade every eligible runner before upgrading the API or enabling custom headers requests. Old runners silently ignore the map and use the default Authorization template; there is no capability gate to prevent mixed-version dispatch. Creation and recovery with custom headers must remain on upgraded runners, including during rollback. See the secret contract.

What this README covers

  • The runner's overall process model — what the HTTP server handles, what the background goroutines do, and how they share the embedded BoxLite runtime.
  • Every major workflow the runner exposes:
    • Box lifecycle — create / start / stop / destroy / resize / recover / network-settings / info / backup
    • Artifact management — async pull, async build, log streaming, info-or-error, removal, tag, registry inspect
    • Execution + attach — the long-lived stdio bridge (in depth, with wire protocol and reaping policy)
    • File I/O — tar-framed upload and download
    • Per-box metrics — CPU / memory / net / exec counters
    • Runner info — host CPU / memory / disk + service health
  • The background services spawned at startup — box state sync, metrics collector, v2 job poller, v2 healthcheck.
  • The complete REST surface (one consolidated table).

If you want the SDK side, see src/boxlite/src/rest/litebox.rs. If you want the formal API schema, see openapi/box.openapi.yaml.


Architecture

┌──────────────────────────────────────────────────────────────────────────┐
│                              CLIENT SIDE                                  │
│                                                                          │
│   Python / Node / Rust SDKs            NestJS API (control plane)        │
│   • interactive boxes                  • issues jobs to runner via       │
│   • /attach WebSockets                   v2 long-poll                    │
│   • file I/O, artifact ops, metrics    • collects healthchecks          │
└─────────────────────┬───────────────────────────────────┬────────────────┘
                      │                                   │
        HTTPS / WS    │                                   │ HTTP polling
        ──────────────┼───────────────────────────────────┼─────────────────
                      ▼                                   ▼
┌──────────────────────────────────────────────────────────────────────────┐
│                       RUNNER (this crate, Go)                            │
│                                                                          │
│  cmd/runner/main.go boots:                                               │
│    • api.ApiServer            HTTP/WS listener on :3003                  │
│    • BoxSyncService       every 10s, reconcile local→remote state    │
│    • metrics.Collector        rolling CPU + allocation snapshots         │
│    • v2.poller / executor     long-poll API for jobs (if ApiVersion==2)  │
│    • v2.healthcheck           push health+metrics (if ApiVersion==2)     │
│                                                                          │
│  pkg/api/controllers/ (HTTP layer)                                       │
│    box.go    Create, Start, Stop, Destroy, Resize, Recover, ...      │
│    artifact.go   PullArtifact, BuildArtifact, RemoveArtifact, ...        │
│    boxlite_exec.go         POST /exec, GET /executions/:id, ...          │
│    boxlite_exec_attach.go  GET /attach (WebSocket)                       │
│    boxlite_files.go        PUT/GET /files                                │
│    boxlite_metrics.go      GET /metrics                                  │
│    info.go, health.go      /info, /                                      │
│                                                                          │
│  pkg/services/           BoxService, BoxSyncService              │
│  pkg/boxlite/            Client (FFI wrapper), ExecManager, registry     │
│  pkg/cache/              BackupInfoCache, ArtifactErrorCache             │
│  pkg/runner/v2/          poller, executor, healthcheck                   │
│  internal/metrics/       host + per-box metrics collection               │
└───────────────────────────────────┬──────────────────────────────────────┘
                                    │ Go SDK FFI (sdks/go/)
                                    ▼
┌──────────────────────────────────────────────────────────────────────────┐
│   RUST RUNTIME (linked in-process via cgo)                               │
│                                                                          │
│   BoxliteRuntime → libkrun → VM (KVM / Hypervisor.framework)             │
│                              │                                           │
│                              ▼                                           │
│                          Guest agent over vsock                          │
│                              │                                           │
│                              ▼                                           │
│                          User process (e.g. /bin/sh)                     │
└──────────────────────────────────────────────────────────────────────────┘

The HTTP server and every background service share one boxlite.Client instance (FFI wrapper around the Rust runtime). State that needs to survive request boundaries — backup progress, artifact build/pull errors — lives in the in-process TTL caches under pkg/cache/.


Process model

cmd/runner/main.go brings up the process in this order:

  1. BoxLite runtime is initialized via boxlite.NewClient(...). This loads the Rust core, opens the BoxLite home, and is the single shared handle to the VM hypervisor. The client resolves the home the way boxlite-core would — BOXLITE_HOME_DIR, else $BOXLITE_HOME, else .boxlite under $HOME (or the passwd home when $HOME is unset) — passes it to core explicitly, and exposes it as HomeDir(), so the rest of the runner (migration staging under <home>/migrate) reads the same directory as the runtime.
  2. Service singletons are constructed and stashed on the runner.GetInstance(...) global: BoxService, BackupInfoCache, ArtifactErrorCache, metrics.Collector. Controllers later read them via runner.GetInstance(nil).
  3. Background goroutines are spawned (each one inherits the root context, so SIGTERM unwinds them cleanly):
    • BoxSyncService.StartSyncProcess — every 10 s, list local boxes, ask the API for boxes still marked STARTED upstream, and push any state mismatch to the API. One-way: local state is authoritative, the API is the replica being corrected. One exception: a box the API already shows STARTED is never told creating — a configured-but-never-booted local record folds into Creating, and reporting it stale would walk the box backwards and raise a false pending that blocks destroy. Real runtime exits (stopped, error) still push through.
    • metrics.Collector.Start — periodic CPU and allocation sampling for the /info and /metrics endpoints (see Metrics).
    • healthcheck.Service.Start and poller.Service.Start — only if BOXLITE_API_VERSION=2. These push health and pull jobs from the control plane.
  4. api.ApiServer.Start registers routes and binds the HTTP listener. Synchronous; blocks the main goroutine until SIGTERM.

On SIGTERM or interrupt, the runner stops v2 job intake and status reporting, requests a graceful VM shutdown and gives the HTTP server 5 s to drain. The outstanding job poll can finish during that shutdown. At process exit the root context is canceled and the BoxLite client closes the runtime.


Workflows

1. Box lifecycle

Path prefix: /boxes. Every endpoint here is a thin controller that calls into r.Boxlite (the Go SDK / Rust core). State transitions and crash handling live in the runtime, not the runner.

Method Path Controller Purpose
POST /boxes Create Allocate box, pull/use artifact, return runtime version
POST /boxes/:id/start Start Boot a stopped box (optional auth token + metadata)
POST /boxes/:id/stop Stop Graceful or force shutdown
POST /boxes/:id/destroy Destroy Tear down completely
POST /boxes/:id/recover Recover Bring an error box back via a named strategy
POST /boxes/:id/is-recoverable IsRecoverable Static check against common.IsRecoverable(reason)
POST /boxes/:id/network-settings UpdateNetworkSettings Set the outbound policy (outboundEnabled / outboundAllowNet)
POST /boxes/:id/backup CreateBackup Kick off async backup; updates BackupInfoCache
GET /boxes/:id Info Combined state + backup state + runtime version

Create and Recover take the outbound network policy as outboundEnabled and an outboundAllowNet entry list. outboundEnabled is required: a body without it, such as a job queued by an API that predates it, is rejected as an invalid argument before the runner mounts volumes, creates a box, or (for Recover) destroys the old one (networkSpec in pkg/boxlite/client.go).

Info is the only endpoint that fans out: it pulls live state from the runtime and backup state from BackupInfoCache, then fetches the runtime version only when the box is STARTED. See pkg/services/box.go.

CreateBackup is fire-and-forget — the runtime starts the snapshot upload asynchronously and the controller returns 201. Failures detected synchronously (e.g. the runtime rejected the request outright) write BackupStateFailed into BackupInfoCache so that subsequent Info calls surface the error reason. Per-stage progress comes from the runtime side and is also reflected in the cache.

2. Artifact management

Path prefix: /artifacts. Runtime artifacts are OCI images cached at ~/.boxlite/images/. Pull and build are async with an error-cache sidecar: the controller returns 202, a goroutine runs the operation, and the result is recorded in ArtifactErrorCache keyed by artifact ref (or destination ref if pull is mirroring).

Method Path Controller Purpose
POST /artifacts/pull PullArtifact Mirror image; optional push to destination registry
POST /artifacts/build BuildArtifact Build from Dockerfile + context hashes
GET /artifacts/exists ArtifactExists Yes/no local cache check
GET /artifacts/info GetArtifactInfo Size, entrypoint, hash — 422 if error cached
POST /artifacts/remove RemoveArtifact Delete local image + clear error cache
POST /artifacts/tag TagImage Re-tag existing local image (deprecated)
POST /artifacts/inspect InspectArtifactInRegistry Remote digest + size lookup
GET /artifacts/logs GetBuildLogs Tail build log file; follow=true polls until image exists

Why a separate error cache. Pull/build are decoupled from the request, so clients can't see failures via the HTTP response. They poll /artifacts/info, which returns 422 Unprocessable Entity with the error text when ArtifactErrorCache.GetError(ref) is set. 200 means the image is ready; 404 means neither image nor cached error exists (the operation is still in flight or was never started).

GetBuildLogs with follow=true streams the build log file and polls ImageExists() every 250 ms to detect completion, then gives the file 1 s of grace to flush before returning. There's no explicit "build done" signal from the runtime — the image appearing in the local store is the signal.

3. Execution + attach

Path prefix: /v1/boxes/:boxId/. This is the runner's flagship workflow: a long-lived bidirectional stdio channel between an SDK client and a process inside a VM. The endpoints below split create / status / kill (REST, idempotent) from stdio (/attach WebSocket, stateful).

Method Path Controller Purpose
POST exec BoxliteExec Create execution; returns {execution_id}
GET executions BoxliteListExecutions Live guest inventory, including main; never boots a stopped box
GET executions/:id/attach BoxliteExecAttach WebSocket upgrade; bidirectional stdio + control
GET executions/:id BoxliteGetExecution Status (running / completed, exit_code when done)
POST executions/:id/signal BoxliteExecSignal Send a cooperative signal (whitelist)
POST executions/:id/resize BoxliteExecResize Resize TTY (cols, rows) — TTY-only
DELETE executions/:id BoxliteExecKill Atomic kill + evict

Inventory returns the guest's real execution_id, argv, started_at (Unix milliseconds), tty, and is_main_session. Status, signal, resize, kill, and attach can recover an execution absent from the runner's local manager using that ID. Recovery keeps the API's box identifier as the ownership boundary; it does not substitute the runtime's internal box UUID.

Control recovery does not acquire guest output. The first attach claims the single SDK output reader and reconnects reuse the same bounded broadcaster; an existing reader is never stolen. A completed execution's status remains available during retention. Main uses the container ID across box restarts, so a closed cached main is replaced only when the live guest inventory reports that ID again, without reusing the old output backlog.

Call graph

Layered view: HTTP route → controller → ExecManager registry → SDK handle. Indentation = "calls".

pkg/api/controllers/boxlite_exec.go
├─ BoxliteExec(ctx)                           POST /exec
│  └─ ExecManager.Start(ctx, bx, ...)         spawns process + Wait goroutine
├─ BoxliteGetExecution(ctx)                   GET /executions/:id (status)
│  └─ ExecManager.Resolve(ctx, bx, id, boxID)  recover control; select on Done
├─ BoxliteExecKill(ctx)                       DELETE /executions/:id
│  └─ ExecManager.Kill(id)                    atomic kill + evict
├─ BoxliteExecSignal(ctx)                     POST /signal (whitelist enforced)
│  └─ ExecManager.Signal(id, sig)             execHandle.Signal
├─ BoxliteExecResize(ctx)                     POST /resize
│  └─ ExecManager.ResizeTTY(id, rows, cols)   TTY-only; 400 otherwise
pkg/api/controllers/boxlite_exec_attach.go
└─ BoxliteExecAttach(ctx)                     GET /attach   (WebSocket upgrade)
   ├─ ManagedExec.MarkConnected()             409 if slot already taken
   └─ runAttachLoop(parentCtx, conn, exec, boxId, execId)  4 goroutines, fail-fast cancel
      ├─ conn.SetReadDeadline(now + 45s)      45s = 3 × Ping interval; trips ReadMessage on dead peer
      ├─ conn.SetPongHandler(reset deadline)  each Pong pushes it out — until the loop is cancelled
      ├─ attachOutput.pump() × {1,2}          stdout 0x01 / stderr 0x02 frames (subscribed to ManagedExec broadcaster)
      ├─ readClientFrames()                   binary → stdin; text JSON → control; drains past cancel
      │  └─ handleControlFrame()              resize | signal (whitelist) | stdin_eof
      ├─ runKeepalive()                       WS Ping every 15s
      ├─ (on exec.Done) writeJSONFrame()      sends {"type":"exit",...} + Close
      ├─ awaitPeerClose(conn, readerDone)     RFC 6455 §5.5.1: hold TCP for the peer's Close, ≤ 5 s
      └─ logAttachSessionEnd()                one line per session + exec_attach_sessions_total

pkg/boxlite/exec_manager.go
├─ ExecManager (struct)                       map[id]*ManagedExec + cleanupLoop
│  ├─ Start(ctx, bx, ...)                     io.Pipe pair, bx.StartExecution
│  │  └─ go func() { handle.Wait(); ... }     records ExitCode/Err, closes Done
│  ├─ Get / WriteStdin / Signal / ResizeTTY / Kill
│  └─ cleanupLoop(30s)
│     └─ runCleanupOnce(now)                  snapshot map under RLock
│        └─ evaluateExec(e, ...)              4-stage reap policy
│           ├─ age > maxLifetime   → killAndEvict   (hard 24h cap)
│           ├─ Done && age > 5m    → evictExited    (no signal)
│           ├─ idle > reconnectGrace → escalate(SIGHUP)
│           ├─ idle > shutdownGrace  → escalate(SIGTERM)
│           └─ idle > shutdownGrace  → killAndEvict (SIGKILL)
├─ ManagedExec (struct)                       per-exec state; attachMu guards attach fields
│  ├─ MarkConnected / MarkDisconnected        single-attach slot
│  └─ AttachStdin / AttachResize / AttachSignal / AttachCloseStdin
├─ execHandle (interface)                     Signal | Kill | ResizeTTY | Wait | Close
└─ sdkExec (struct)                           adapter → *boxlite.Execution (FFI to Rust)

Execution lifecycle

An execution moves through four phases. The diagram below shows every transition and which entry point triggers each.

                 ┌─────────────────────────────────────┐
                 │ 1. CREATE                           │
                 │    POST /exec  →  execution_id      │
                 │    server spawns process in VM      │
                 │    ManagedExec inserted into map    │
                 └──────────────┬──────────────────────┘
                                │
                                ▼
                 ┌─────────────────────────────────────┐
                 │ 2. ATTACH                           │
                 │    GET /attach (WebSocket upgrade)  │
                 │    MarkConnected: claim slot or 409 │
                 │    bidirectional pump runs          │
                 └─────┬─────────────────────────┬─────┘
                       │                         │
                       │ process exits           │ WS dies
                       ▼                         ▼
          ┌──────────────────────┐    ┌──────────────────────────┐
          │ 3a. CLEAN EXIT       │    │ 3b. DETACH               │
          │  Done fires          │    │  MarkDisconnected fires  │
          │  exit frame sent     │    │  attach slot released    │
          │  WS Close (normal)   │    │  process keeps running   │
          │  evict after 5m      │    │  reap clock starts       │
          └──────────────────────┘    └────────┬─────────────────┘
                                               │
                            ┌──────────────────┼──────────────────┐
                            │ within 5 min     │ past 5 min       │
                            ▼                  ▼                  │
                 ┌─────────────────┐   ┌──────────────────────┐   │
                 │ 4a. REATTACH    │   │ 4b. REAP             │   │
                 │  GET /attach    │   │  SIGHUP → 30s        │   │
                 │  reuse same id  │   │  SIGTERM → 30s       │   │
                 │  flags reset    │   │  SIGKILL + evict     │   │
                 │  back to (2)    │   │  (or 24h hard cap)   │   │
                 └─────────────────┘   └──────────────────────┘   │
                                                                  │
                          after 5m + escalation, exec is gone ────┘
Why this shape
  • Single-attach keeps PTY semantics intact. Two clients reading from one PTY would race on stdin and split stdout output unpredictably.
  • Detach without kill lets a client survive transient connection drops (LB idle timeout, network blip) without losing the running process. Matches the E2B model.
  • Reap escalation (SIGHUP → SIGTERM → SIGKILL) mirrors the standard Unix shutdown sequence used by systemd, Kubernetes, and Docker. Cooperative processes (bash, python -i, psql) clean up on SIGHUP.
  • 24 h hard cap prevents a forgotten session from holding resources forever. Configurable.

/attach wire protocol

GET /v1/boxes/{box_id}/executions/{exec_id}/attach upgrades to a WebSocket carrying stdin, stdout, stderr, and control on one connection.

Client → Server                       Server → Client
─────────────────                     ─────────────────
Binary [stdin bytes]                  Binary [0x01 | stdout bytes]
                                      Binary [0x02 | stderr bytes]   (non-TTY only)
Text JSON {"type":"resize","cols","rows"}
Text JSON {"type":"signal","sig":N}   Text JSON {"type":"exit","exit_code":N}
Text JSON {"type":"stdin_eof"}        Text JSON {"type":"error","message":"..."}
                                      WS Ping every 15 s           ← keepalive
WS Pong (auto)                        WS Close on normal exit
WS Close (the answer to it)

Notable properties:

  • No SSE base64 bloat. Stdout/stderr are raw bytes; the only framing overhead is the 1-byte channel prefix (~0.025% on 4 KB chunks).
  • No per-keystroke HTTPS round trip. Stdin rides the same persistent connection — latency is one local-to-server WS frame, not one HTTP POST with auth handshake.
  • TTY mode merges stdout/stderr in the kernel; the server only emits the 0x01 channel. Non-TTY mode emits both.
  • Server-driven keepalive. Even with no application I/O, the server sends a WS Ping every 15 seconds, well under any reasonable intermediary's idle timeout (CloudFront default 30 s, ALB 60 s, Heroku 55 s).
  • The close is a handshake. RFC 6455 §5.5.1 lets an endpoint drop the TCP connection only once a Close has been both sent and received, so after its own the server waits for the client's — or for the client to drop the socket — bounded at 5 s. Dropping it unilaterally strands any intermediary still relaying the 101, which an external load balancer reports as a failed upgrade rather than as the clean exit it was.
  • Single-attach. A second /attach to an already-attached exec returns HTTP 409 before the WS upgrade. The slot is held until the close handshake above finishes, so it can outlive the exit frame by up to that bound, and a client that gives a connection up on its own has to close it — Close frame, then the socket — before it reconnects, or its first reconnect lands on a slot the old session still holds. The server only notices a silent client when its Pings go unanswered for 45 s; a client that reads but never answers is told apart from a dead one by the pong_timeout reason below. The SDK does both (it Pings on connect and closes before reconnecting); a client that gets a 409 should surface it as "session busy" rather than retry in a tight loop.

Attach session logs and metrics

Every attach session leaves exactly one log line when it ends, and every refused attach one more. They are what lets two sides of a disconnect be matched: the SDK logs its side of the same event (see the Rust SDK's attach_ws_pump), and the timestamps and reasons line up. Only byte counts are logged — never headers, the request URL, stdin or output.

Line Level When
boxlite exec attach session ended DEBUG for exec_done and client_close, WARN otherwise, ERROR for panic Every session, once
boxlite exec attach refused WARN Every 409
boxlite exec attach upgrade failed WARN Upgrade rejected after the slot was claimed

The session-end line carries boxId, execId, reason, the first error's text, the client's Close status code when there was one, how long the socket was up, per-stream replayed / sent / dropped bytes, whether the exit frame was sent, whether the exec had finished, and how many sessions the exec has had. On exec_done, a normal peer Close (1000) paired with a successfully sent exit frame produces no firstError or clientCloseCode. A client Close that ends a running exec still includes its close details.

reason is one of:

Reason Meaning
exec_done The exec finished; the exit frame was sent (or its drain timed out).
client_close The client sent a WebSocket Close frame.
pong_timeout No frame from the client for 45 s (3 × keepalive). On a still-running exec this means the client stopped reading.
read_error Any other read failure: a dropped socket, a reset, a killed client process. These cannot be told apart from a network cut.
write_failed An output frame or a keepalive Ping could not be written.
upgrade_failed The WebSocket upgrade itself failed.
panic A goroutine of the attach loop panicked. The slot is still released.
server_shutdown The server shut the connection down with no error reported and the exec still running.

Two counters expose the same on /metrics: exec_attach_sessions_total{reason} and exec_attach_refusals_total{reason} (slot_occupied or reaping). A healthy runner only adds to exec_done and client_close; a steady pong_timeout rate on its own is a client that stopped reading, not a network problem.

Reaping policy

The background cleanupLoop ticks every 30 s and applies the policy below to executions started through the manager. Recovered guest sessions, including main, are not subject to its orphan or maximum-lifetime policy; discovery must not turn observation into a decision to kill a guest workload. Completed recovered sessions still use the same retention period. All three timers for manager-started executions are independently configurable via environment variables.

Trigger Action Default Env var
Age since created > cap atomic kill + evict 24 h BOXLITE_MAX_SESSION_LIFETIME
Done fired ≥ 5 min ago evict (no signal) 5 min (not configurable)
!Connected and idle > grace SIGHUP 5 min BOXLITE_RECONNECT_GRACE
After SIGHUP, idle > shutdown grace SIGTERM 30 s BOXLITE_SHUTDOWN_GRACE
After SIGTERM, idle > shutdown grace SIGKILL + evict 30 s BOXLITE_SHUTDOWN_GRACE

Reattaching inside the reconnect grace resets SignaledHUP and SignaledTERM so a subsequent disconnect starts a fresh clock. Durations accept Go's time.ParseDuration syntax (e.g. 5m, 30s, 24h, 90s).

If the underlying SDK can't deliver arbitrary POSIX signals, sdkExec.Signal returns ErrSignalUnsupported; the reaper logs a warning and falls through to Kill() immediately. Exercised in exec_manager_test.go::TestExecManagerSignalUnsupportedFallsThroughToKill.

Signal whitelist

POST /signal accepts only cooperative signals. SIGKILL goes through DELETE /executions/:id instead; the signal endpoint needs the atomic kill+evict that DELETE provides.

Allowed Rejected with 400
1 (HUP), 2 (INT), 3 (QUIT), 6 (ABRT), 10 (USR1), 12 (USR2), 15 (TERM), 28 (WINCH) 9 (KILL), 17/19/23 (STOP variants), 18 (CONT), anything else

STOP/CONT are rejected because they bypass PTY line discipline (so a PTY-aware program won't notice them) and because a stopped process holds RAM forever while looking idle to the reaper — a footgun, not a feature.

4. File I/O

Method Path Controller Purpose
PUT /v1/boxes/:boxId/files?path=<dest>&overwrite=false BoxliteFileUpload Stream tar through Go/C to guest extraction
GET /v1/boxes/:boxId/files?path=<src> BoxliteFileDownload Stream guest tar as application/x-tar

Uploads default to overwrite=true. With overwrite=false, existing directories can receive new files, but an occupied file, symlink or incompatible directory entry fails with HTTP 409 (already_exists) without replacing existing contents. New entries written before a conflict can remain; uploads do not roll back. Malformed boolean values return 400. For example, an archive containing new.txt then an existing keep.txt can leave new.txt behind when keep.txt conflicts.

Uploads stream to the guest and land according to the archive's first entry, with or without a source_is_dir hint. The guest ignores that hint. REST SDK copy_into(overwrite=false) refuses safely when remote support is unknown, since older runners ignore the query parameter.

5. Per-box metrics

GET /v1/boxes/:boxId/metrics returns the JSON shape in pkg/api/controllers/boxlite_metrics.go: CPU %, memory bytes, exec counts (commands_executed_total, exec_errors_total), bytes shipped over /attach, VM create + boot durations, and network counters. All values come from r.Boxlite.BoxMetrics(ctx, boxId) and are not aggregated by the runner.

6. Runner info + Prometheus

Method Path Controller Purpose
GET / HealthCheck Liveness + version (public)
GET /info RunnerInfo Host metrics + service health + version
GET /metrics promhttp Prometheus scrape endpoint

/info combines:

  • A snapshot from metrics.Collector.Collect(ctx) — host CPU load average, CPU/mem %, summed allocated CPU/RAM across running boxes, disk usage of the BoxLite home's filesystem, artifact count, started box count.
  • runner.InspectRunnerServices(ctx) — pings the BoxLite runtime with a 2 s timeout and reports boxlite: healthy|<err>.

The Prometheus endpoint is the standard promhttp.Handler() and exposes the counters maintained in pkg/common/ (operation counts, etc.).

7. Guest SSH

Method Path Controller Purpose
POST /v1/boxes/:boxId/ssh BoxliteSSHConfigure Strict SshConfig parse → one SSH().Configure on a running box
POST /v1/boxes/:boxId/ssh/enable BoxliteSSHEnable Enable saved configuration on a running box; otherwise 409
GET /v1/boxes/:boxId/ssh BoxliteSSHStatus SshStatus; stopped boxes answer disabled from persisted state
DELETE /v1/boxes/:boxId/ssh BoxliteSSHDisable Disable on a running box; otherwise 409. Repeatable while running; never boots
  • Running-state checks. Configure on a box observed as not running answers 409 invalid_state; the API resumes a box first when its policy allows. The runner checks before and after taking the handle, as for the guest tunnel. The shared helper retains the tunnel's known race: after a runner restart, a fresh handle can still boot a box that exits after these checks. Preventing that race requires a runtime operation that cannot implicitly start a box.
  • No handle churn. Status reads a stopped or never-started box's state and returns the zero disabled status without fetching a handle (see evictBox). Enable and disable instead return 409 invalid_state; they never claim a saved-state change succeeded on an idle box. Other states, such as paused, also answer 409. The SDK prevents these mutations from starting a box even if it stops after the runner's checks.
  • Strict body. The parser matches member names exactly and rejects unknown, case-variant, duplicate, missing, and null members (ca may be null). Every rejection is the fixed 400 invalid SSH configuration, so private key material is never echoed.
  • Once. The guest restarts its listener on every accepted configure, so nothing retries it.

GCP Filestore volumes

A box mounts a Filestore volume — a Volume row whose data directory lives on a Filestore NFS instance, created through the volume API with storageBackend: "performance" and an optional instance field. It is mounted by the same managed_volume selector as bucket-backed volumes. The reference carries the instance's logical name; the API resolves the address from GCP Filestore and dispatches it to the runner with the mount, so recreating an instance under the same name reuses the same logical identity without a change to historical boxes.

Instance configuration (API side)

FILESTORE_INSTANCES is an environment variable of the API deployment — a JSON object list declaring which GCP Filestore instances a create may auto-assign to or a mount dispatch may resolve to:

FILESTORE_INSTANCES='[{"instance":"boxlite-filestore-stage","project_id":"boxlite-dev-project","zone":"us-east4-a"}]'

Validation runs when the API starts: invalid JSON, a duplicate instance, a name outside ^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$, or invalid project/zone values refuse to start the API. Until removed, an unset variable temporarily defaults to boxlite-dev-shared in boxlite-dev-project, zone us-east5-a; stage deployments instead default to boxlite-filestore-stage, zone us-east4-a. An explicit empty value disables Filestore. A volume create naming an instance outside the list fails loudly; the runner configures no instances of its own and mounts the resolved target the dispatch carries.

instance is the logical mount identity, while server and export identify the NFS target. The runner validates all three on every reference before per-call mount deduplication, requires one target per instance within a request, and rejects Filestore subpath instead of silently ignoring it.

How it mounts

  • One NFSv4.1 mount per instance is shared by every box referencing it. The runner creates it on demand and reclaims it when no box record references it. An existing mount is reused only after findmnt confirms NFSv4 and the exact server:export source; a different target fails with a mount mismatch.
  • A box binds to /mnt/boxlite-filestore-<instance>/<volume_id>. The directory is named by volume ID, so boxes sharing a volume share data. It is created with chmod 0777 — NFS permissions are real, unlike the FUSE backends' faked ones.
  • Per-instance mutexes serialize mount, record, and reclaim decisions. Create rolls back records written before a later volume or final record write fails. After a successful record rollback, it immediately reclaims any resulting unreferenced Filestore mounts, independently of scheduled cleanup and its dry-run mode. A record rollback failure skips reclaim because references cannot be verified. New mounts create the empty record directory before starting the mount command. If Create exits while mounting or directory preparation is still running, completion triggers reference-aware reclaim after the pending marker clears. Rollback reclaim uses a bounded context detached from caller cancellation. Existing mounts with no records retain the missing-records guard. Reclaim rechecks references and pending operations under the instance lock instead of stating a potentially unreachable NFS root for a recency check; start replay retains existing entries until replacements are durable.
  • Prepare failures return FILESTORE_VOLUME_PREPARE_FAILED with box, volume, and instance IDs plus the mount error. Logs do not include box environment variables, secrets, authorization headers, or job payloads.
  • Destroy unbinds only: the data directory and its data survive, exactly as a bucket survives a destroy — reachable again through the volume id. A stopped Filestore Box waiting for a restart can be deleted without resolving its configured instance; deletion cancels the waiting start intent and proceeds with runner cleanup without removing the NFS data.
  • Volume removal follows the same async path as bucket volumes — in-use refusal, then PENDING_DELETE until the manager lands the row DELETED (the name is released by the same name-deleted rename). The NFS data directory itself is left in place for ops cleanup.

Runner/API version skew

The runner declares capabilities: ["filestore"] in its healthcheck; the API persists the declaration on the runner row and refuses (loudly, at dispatch) to hand a filestore volume to a v2 runner that has not declared it. A runner binary predating capability reporting declares nothing, so during a rolling upgrade a filestore volume can only land on an upgraded runner. Upgrade order that keeps filestore creates working: runners first, API second — an upgraded runner with the old API is idle for filestore (the old API never creates filestore volumes), while the reverse order would put filestore creates on runners the API does not yet trust. Before replaying start metadata, an upgraded runner also checks the Box's persisted mount record. If an old API replica omits the Filestore reference, Start fails with FILESTORE_VOLUME_REFERENCE_MISSING before trying the object-storage fallback or starting the Box. An unreadable mount record fails with FILESTORE_VOLUME_RECORD_UNREADABLE instead of guessing that the Box has no Filestore mounts. This guard uses only the local record, not a GCP lookup or a rollout feature flag. Rolling back the runner to a binary without Filestore support remains unsupported while Filestore Boxes exist. The dispatch check re-reads the runner row instead of trusting an API replica's lookup cache. A rejection logs the Box ID, runner ID, runner version, declared capabilities and FILESTORE_CAPABILITY_MISSING; the create response carries the reason, Box ID and BOX_STATE_TRANSITION_FAILED, which the Dashboard displays with the HTTP status. The reason also reports whether the runner row exists, its state, protocol and binary versions, observed capabilities, last healthcheck time and age, and confirms that no create job was dispatched. A runner-side prepare failure adds FILESTORE_VOLUME_PREPARE_FAILED, Box/Volume/instance IDs and, when available, the mount process exit code. API job-insert failures similarly log job.create.failed with the job, runner, resource and database error code. Final reconciliation failures log box.sync.failed with the Box ID, error name and database code. Both events omit the raw database error, so logs do not include Box environment variables, secrets, authorization headers, SQL parameters or job payloads.

Troubleshooting

Start returns Filestore preparation errors, including target mismatches, before starting the box, and the START_BOX job reports that failure. Object-storage- only boxes retain the existing fallback: mount replay failures are logged and Start proceeds, so a box started while object storage is unreachable can show an empty guest directory; stop it, restore connectivity, and start it again. NFS hard mounts block I/O while the network is down.

If a later request resolves the same logical instance to another server or export, the runner rejects the target mismatch instead of binding the old share. Unmount the stale path or reboot the host before retrying.

Ops prerequisites

  • Filestore instance: zonal, NFSv4.1, 1 TiB minimum, same VPC as the runner, port 2049 open. Capacity exhaustion shows up in the box as ENOSPC.
  • Host: NFS client package (nfs-utils on RHEL-family, nfs-common on Debian-family) and util-linux for mountpoint and findmnt. No autofs; the runner mounts explicitly. The cloud boot script (runner-boot.ts) installs nfs-common on fresh hosts automatically. GCP deployments also declare the package through OS Config, so existing runner hosts converge without SSH or a rerun of the boot script.
  • Deploy order: runners before the API. The capability check refuses an old runner before dispatch. An API older than its runners simply dispatches no filestore volumes at all, which is harmless.

Background services

Box state sync

pkg/services/sandbox_sync.go. Runs every 10 s (configurable in main.go). For each local box, fetches the authoritative state from BoxLite, then asks the control-plane API for all boxes currently STARTED and not under reconciliation, and calls UpdateBoxState whenever the two disagree. One-way: local state wins.

Boxes that don't appear in the remote STARTED list are skipped — the runner does not push state for boxes the API isn't tracking.

Metrics collector

internal/metrics/collector.go runs independent sampling and logging loops:

  • CPU usage snapshot every CPUUsageSnapshotInterval (default five seconds), including the first reading after startup, regardless of host load. The ring retains the last WindowSize samples (default 60, about five minutes) for the CPU average returned by /info and healthchecks.
  • Allocated resources snapshot every AllocatedResourcesSnapshotInterval — queries Boxlite.ListInfo() and sums the CPU/RAM allocations across running boxes.
  • Resource log every minute — emits event=runner.resource.usage with cpuPercent (the maximum successful CPU sample from the last minute), current memoryPercent, diskPercent, diskUsedGiB and diskTotalGiB. Failed collection emits a warning.
  • Runtime counters every 15 seconds — refreshes aggregate runtime metrics.

For example, CPU readings of 40% and 80% within the minute produce cpuPercent=80 in the resource log; /info still returns the mean of its retained history. Each CPU reading covers a counter interval, so this is the largest sampled interval, not an instantaneous peak. The minute cutoff is inclusive. If no CPU sample falls within it, collection logs a warning instead of using older data.

Collect(ctx) reads the current values with a short timeout and is called from both /info and the v2 healthcheck. Disk numbers come from one statfs of the filesystem holding the BoxLite home (HomeDir()), which is where boxes, images and bases live: TotalDiskGiB is its size, DiskUsagePercentage its use (df's Use%), and AllocatedDiskGiB its used space (df's Used) — not a sum of the boxes' requested sizes. A filesystem reporting zero capacity is an error, so the API never receives a diskGiB of 0.

Sustained CPU incidents

internal/cpumonitor observes the same raw host CPU samples. Strictly more than 80% for five continuous minutes starts two-minute capture windows. Each window emits event=runner.cpu.high with a fresh event ID, threshold, latest host percentage and high-load start. While observations remain high, the next window starts immediately after the previous one finishes: minutes 5–7, 7–9, 9–11, and so on. Capture work can extend a window slightly; windows never overlap and missed windows are not replayed.

A reading at or below 80%, an invalid sample, or a gap of twice the configured sampling interval resets continuity. The active capture finishes, but another window requires a fresh five-minute high-load interval. A worker rechecks sample freshness before each window, so stopped host sampling cannot keep captures running. The healthcheck's smoothed average does not trigger incidents.

A separate worker samples running boxes every five seconds for the next two minutes, even after host CPU recovers. Linux uses each box's cgroup v2 cpu.stat/usage_usec to include the VM beneath the sandbox launcher. The cgroup must match the local runtime ID. macOS uses process user+system time. No guest exec is needed. Linux without a readable matching cgroup reports incomplete attribution instead of measuring only the launcher.

The largest cumulative CPU consumer is retained, using its business box ID (ListInfo.Name); ties choose the lexically first ID. For example, 240 CPU-seconds in a 120-second window means two cores on average (200% on the one-core scale). Counter replacement, restarts, exits and failed reads mark samplingComplete=false; observed totals are then lower bounds. No positive consumption produces boxId=null. The winning box's ListInfo.Image string is included in the same report. The window retains the last successful sample's image even if the box exits; no winner produces image=null, and an empty image string stays empty. Reading the image needs no additional API query, registry lookup or guest command.

The runner posts to the internal ingestion route when BOXLITE_API_URL and BOXLITE_RUNNER_TOKEN are configured. Up to 32 completed reports wait in memory. Network errors, 429 and 5xx retry every 30 seconds with a ten-second timeout; other failures and queue overflow are logged and dropped. Restart loses pending captures/reports. Deploy the migration and API before runners. This feature records evidence only; it does not stop boxes or change scheduling.

Memory incident snapshots

internal/memorymonitor uses the existing minute resource sampler. Every valid host memory reading strictly above 80% immediately scans running Boxes and reports up to five, ordered by current memory bytes descending and business Box ID ascending for ties. Consecutive high minutes produce separate events. At or below 80%, or on an invalid host reading, no scan occurs. CPU's five-minute qualification and two-minute windows are unchanged.

Host admission uses the same raw gopsutil.VirtualMemory.UsedPercent reading as the resource log, before rounding for health metrics. CPU/disk collection failures do not suppress that memory observation. /info and healthchecks do not trigger additional scans. Linux uses memory.current from the matching Box cgroup v2, including VM descendants and charged cache; swap is separate. macOS uses process RSS only when the process was created no later than BoxInfo.StartedAt and its identity remains unchanged across the read. Missing start times are unreadable. These accounting scopes differ, and Box totals need not sum to the host's used-memory value. This is evidence of large consumers, not proof of the cause of host pressure.

Each item carries boxId, the snapshot's image, and decimal-string memoryBytes. Fewer than five readable Boxes produce a shorter array, and no readable Boxes produce boxes=[]. Zero-byte readings are retained. Failed enumeration, unreadable or mismatched cgroups, process identity changes, or an expired scan mark samplingComplete=false; successful observations still report. Reads are sequential rather than an atomic host-wide snapshot. One-minute sampling can miss short memory spikes.

When API URL and Runner token are configured, completed snapshots enter a separate 32-report queue for internal ingestion. Scans have a ten-second context deadline and do not wait for network uploads. Cancellation releases the sampler even if a Linux kernel read is blocked. At most one such read remains in flight; later scans wait for its slot within their own deadline, reporting incomplete observations if it has not finished. Requests time out after ten seconds; network errors, 429, and 5xx retry after 30 seconds with the original payload and event ID. Other failures and queue overflow are logged and dropped. Missed ticks are not replayed, and process restart loses queued reports. Deploy the migration and API before Runners.

Data disk resize

internal/diskresize/ticker.go. The control plane can grow a GCP runner's Hyperdisk data disk online (disks.update); the filesystem must still be resized to use the extra capacity, and that is this runner's job. Every 10 seconds the ticker reads the block device's size from sysfs via the stable /dev/disk/by-id/google-boxlite-data symlink and compares it with the last observed size:

  • unchanged: nothing happens (steady state costs one sysfs read);
  • larger: runs resize2fs on the device, which grows the mounted ext4 filesystem online; the baseline moves only on success, so a failed resize retries next round;
  • smaller: not skipped — a smaller device still runs resize2fs, which fails and retries each round (disks cannot shrink via GCP; a disk swap is caught by the API-side stale-ref alert);
  • missing (AWS, local, or non-Linux hosts): skip, logged once at debug; disk resize is a GCP-only behavior.

The first round always runs resize2fs once: the nil baseline forces an idempotent no-op that also repairs an earlier failed resize after a runner restart. Failures log event=runner.disk.resize at warn and increment an in-process failure counter; successes log the same event at info. The disk trigger is the device size, deliberately not statfs: the ext4 metadata overhead makes statfs total permanently smaller than the device, so statfs comparison would fire resize2fs every round. RUNNER_DATA_DISK_DEVICE overrides the device path for tests and local runs; infra never injects that key.

v2 job poller + executor

Only spawned when BOXLITE_API_VERSION=2. The poller (pkg/runner/v2/poller/poller.go) first drains anything left in IN_PROGRESS from a previous run, then long-polls JobsAPI.PollJobs with (timeout, limit). HTTP 408 returns are treated as "no work yet" (normal long-poll behavior); any other error backs off 5 s and retries.

A long poll commits a claim before returning its response. During an orderly restart, the retiring runner lets an outstanding poll finish and leaves any batch received after intake closed in IN_PROGRESS for the replacement's startup scan. Jobs already running can finish locally, but the runner stops sending both COMPLETED and FAILED and cancels status requests and retries. The API keeps any result it already accepted. A job still in IN_PROGRESS can run again, even if its earlier attempt completed the local operation.

With the default 30 s poll, an idle restart may wait for the remainder of that poll. The wait ends 45 s after the stop signal and overlaps VM and HTTP shutdown. A forced kill, transport error or expired deadline can still leave a late claim.

Each job is dispatched to a goroutine and handled in pkg/runner/v2/executor/executor.go. Supported job types:

CREATE_BOX, START_BOX, STOP_BOX, DESTROY_BOX,
EXPORT_BOX, IMPORT_BOX,
ROLLBACK_EXPORT_BOX, ROLLBACK_IMPORT_BOX, DISCARD_EXPORTED_BOX
EXPORT_CHECKPOINT, UPLOAD_CHECKPOINT, IMPORT_CHECKPOINT

After the handler returns, updateJobStatus reports COMPLETED or FAILED to the API with exponential backoff. W3C trace context is extracted from the job's traceContext map so the runner's spans chain under the API-side trace.

This is the production path. The HTTP routes under /boxes/ and /artifacts/ exist for direct/SDK use; v2 turns those into pull-based job execution.

Secret credentials on CREATE_BOX

When a v2 job carries secretCredential: {token, expiresAt}, its secret definitions must omit value entirely. The runner obtains a GCP instance identity token with format=full and audience equal to SECRET_SERVER_URL, then posts the credential to /internal/v1/secrets/fetch using the identity token in both Authorization: Bearer and X-Boxlite-Runner-Identity. BOXLITE_RUNNER_ATTESTOR defaults to gcp_iit; other modes are unsupported.

The response must match the box ID and exactly the requested secret names. Its values, hosts, headers and placeholders replace the job's definitions. The runner reads at most 8 MiB of response JSON plus one byte to detect oversize responses, matching the Secret Server's 8 MiB success limit. Metadata retrieval and fetch share a five-second deadline. A freshly polled job makes at most one fetch request, without redirects or retries. A lost response may have consumed the credential. Retrieval and subsequent create failures are non-recoverable, and this MVP has no credential reissue.

On startup, an in-progress credential job can only reopen an existing local box, skipping identity and secret retrieval. If the box is absent, the runner reports failure and asks the caller to submit a new create request. This also applies if the previous process exited before dispatch. If the target disappears before the runner opens it, the job fails without creating a replacement. The original create job's skipStart option controls whether the existing box is started. Replay uses the box's persisted runtime configuration without comparing its privilege mode to the job payload.

Deploy the Jobs API with afterId support before upgrading the Runner. Startup scans GET /jobs?status=IN_PROGRESS in ascending UUID order, starting with the nil UUID and continuing after the last ID in each batch. A timeout that removes an earlier job cannot shift the next batch. After collecting the IDs, Runner reads each job again and dispatches it only if it still exists and is in progress. Transient read errors retry until shutdown. The status read and execution are separate operations. A timeout that occurs after the final read can still race with execution.

Jobs without credentials retain inline values, and START_BOX continues using runtime-local secrets. Direct HTTP create/recover still require inline values.

Credential-free v2 jobs pass inline secrets to backend validation without extra name or value restrictions. Empty names, duplicate names and empty values retain their existing semantics; host and header validation remains in the backend. Credential-bearing jobs require unique, nonempty names to match fetched secrets. If the replay lookup confirms the box is absent, the runner removes the volume ownership record written during preparation and reclaims Filestore mounts only after checking under the instance lock that no other box references them. Other lookup errors preserve the record because the box may still exist. The backend error wraps the lookup cause; credential job status retains its sanitized error. For a fetch that returns HTTP 503, job status preserves the Secret Server code store_unavailable for storage failures and attestation_unavailable for identity verifier outages.

Configure an HTTPS SECRET_SERVER_URL; HTTP is accepted only for loopback test services. Credentials, identity tokens and returned secret content stay out of errors, job status and logs. The runner releases its job payload after execution; API terminal-state credential cleanup is owned by the API credential lifecycle. This releases references and does not promise memory zeroization.

make test:apps:runner FILTER='Secret|Credential|RequireExisting' exercises fake metadata/Secret Server boundaries and the existing-box lookup through the Go SDK without a VM. The credential tests also verify that missing lookup capability, missing fetch configuration, empty instance identity and unsupported configured attestors stop creation before dispatching a credential. Collect runner coverage with make test:apps:runner GOTEST_FILTER='-covermode=atomic -coverpkg=./... -coverprofile=/tmp/runner-coverage.out'.

Portable archive storage

The checkpoint design defines the capture, transfer and recovery contracts; the transfer helper alone does not provide target recovery ownership.

EXPORT_CHECKPOINT accepts an optional kind: disk (the default when omitted) requires a stopped source, and full requires a running source and native support for exporting memory. The runner checks the state under the source operation lease; it does not start or stop the source to make it eligible. The runner does not yet advertise the memory_checkpoint capability.

Checkpoint capture separates native export from upload. EXPORT_CHECKPOINT owns the source BOX job slot; it reports an immutable archive record and never uploads. The API then releases the source and submits UPLOAD_CHECKPOINT in the checkpoint's own job slot. An upload does not hold the source's executor operation lease, so a later source start can proceed independently.

Each capture uses <BOXLITE_HOME_DIR>/work/checkpoints/<checkpoint-id>/<export-job-id>/. Its record pins the image digest that built the source disk, archive size, SHA-256 and object URI. The result carries kind when supplied, and for full it also carries memorySizeBytes from the archive manifest (a nonnegative integer, including zero). Disk results omit memorySizeBytes. Pass the export result unchanged to UPLOAD_CHECKPOINT; upload returns the same metadata. Redelivery reuses that capture; it never substitutes a fresh source export if the published file is missing or corrupt. Fixed lock files serialize duplicate deliveries across processes sharing the work directory.

The accepted checkpoint job continues waiting for native export after caller cancellation. An upload retains its archive until the API acknowledges its terminal job status; a rejected callback leaves it for replay. Cleanup removes the large archive while retaining a small record that prevents a late export job from capturing the changed source again. These rules apply to checkpoint jobs; the migration job sequence keeps its existing export/upload contract.

Checkpoint downloads stay under the fixed <BOXLITE_HOME_DIR>/work/checkpoints/<checkpoint-id>/ root, in a private .download-<import-job-id>-* directory per import attempt, including duplicate deliveries of the same job. Transfer failures, unexpected lengths, SHA-256 mismatches and link destinations are rejected and staging is removed. Runner owns these cloud metadata checks and the pinned-image/platform-identity policy; native runtime has no checkpoint-specific archive preparer.

IMPORT_CHECKPOINT downloads and verifies SHA-256, imports a candidate under an operation-specific native name, publishes its public-to-native identity mapping, and only then removes the predecessor. The candidate must be stopped with PID zero; recovery requires a stopped or failed predecessor with PID zero. Import failures retain the original Box. The request's archive carries the upload result, including kind and memorySizeBytes for a full checkpoint. An optional request-level kind must match archive.kind (which defaults to disk when omitted).

Runner streams the archive to a temporary plain tar, changing only the first manifest member's pinned image and six platform environment keys. It copies the remaining tar bytes unchanged, preserving GNU sparse members and full checkpoint memory data. The manifest's memory_checkpoint metadata is retained. Runner performs no separate disk validation or startup preflight; the existing native import owns archive extraction and validation. This adds one stream read and temporary write, without extracting disk files or recompressing them.

The download and adapted tar stay owned until native import finishes. The request carries a stable operation and monotonically increasing target sequence, independently of job attempts. The existing journal under <BOXLITE_HOME_DIR>/work/checkpoint-operations/ publishes the identity mapping with an atomic file replacement and directory synchronization. All runner lookups and BoxSync use that mapping, including after process restart; candidates and obsolete predecessors are hidden from public inventory.

Import retries first look up the deterministic candidate name, so a lost native receipt does not duplicate the import. Publication failure never removes the old Box. Cleanup failure leaves both disks and a retryable journal; retry removes the predecessor without downloading or importing again. Accepted work keeps the target lease after caller cancellation. These guarantees cover import failures and process restarts, while native disk persistence retains the existing import contract.

Ordinary create invalidates the previous checkpoint operation before changing the target. Explicit destroy durably retires the public target before native destruction, even when no import has arrived yet; all delayed checkpoint imports are then refused. Missing native targets count as successfully destroyed. Migration cleanup invalidates its previous operation while keeping the public target reusable. An accepted import can be replayed after the box starts without replacing it or reading the object again. The lease covers runner lifecycle entry points; callers directly using native runtime handles do not participate in this runner coordination.

The runner shares ArchiveStore between archive producers and consumers. The control plane chooses each object's location: gs://bucket/key uses GCS, s3://bucket/key uses S3, and a bare key uses AWS_DEFAULT_BUCKET. Malformed locations and unsupported schemes fail before export begins.

GCS uses Application Default Credentials and initializes its client on first use. Missing credentials can be retried on a later operation. S3 configuration is independent: an absent AWS_DEFAULT_BUCKET disables S3 transfers without preventing GCS transfers or runner startup. Operators must grant the runner's credentials access to the buckets selected by the control plane.

A GCS upload succeeds only after its writer commits; a failed local read cancels the upload. GCS downloads use a unique, owner-only temporary file next to the destination, then rename the complete file into place. Download or rename failures preserve the prior destination and remove the staging file. Deleting an absent object is idempotent; permission failures remain errors.

S3 retains MinIO's existing download/resume behavior. Callers must provide different local destinations for concurrent S3 downloads; close or rename failures may leave MinIO staging files. The GCS staging guarantees do not extend to S3. Callers own local archive retention and object removal.

v2 healthcheck

pkg/runner/v2/healthcheck/healthcheck.go. Periodic POST RunnerHealthcheck to the API with runner version, domain, API + proxy URLs, BoxLite ping result, and the current metrics snapshot. Failures are logged but never crash the runner — this is the control plane's view of the runner's liveness, not a self-test.

GCP runners also carry the data disk identity: when infra injects all three GCP_PROJECT_ID, GCP_ZONE and RUNNER_DATA_DISK_NAME env keys, every healthcheck includes dataDiskRef with provider, project, zone and disk name; any missing key omits the whole field, so AWS and local runners never send a partial identity. The API's disk-expansion controller uses this ref to address the right disk. Infra also injects RUNNER_DATA_DISK_TYPE (derived from the provisioned disk type, e.g. hyperdisk_balanced); the ref carries it as diskType so the API can tell expandable block disks from backends with a different resize path (e.g. Filestore). The key is optional — binaries predating it, and hosts whose infra predates it, are treated as hyperdisk_balanced by the API, which matches everything infra provisions today.


Complete REST surface

All routes are gated by Bearer <BOXLITE_RUNNER_TOKEN> except / and the Swagger UI (development only).

Method Path Purpose
GET / Health check (public)
GET /info Runner metrics + service health
GET /metrics Prometheus scrape
POST /boxes Create box
GET /boxes/:id Box info (state + backup state + runtime version)
POST /boxes/:id/start Start
POST /boxes/:id/stop Stop (graceful or force)
POST /boxes/:id/destroy Destroy
POST /boxes/:id/backup Async backup
POST /boxes/:id/recover Recover from error state
POST /boxes/:id/is-recoverable Check whether an error reason is recoverable
POST /boxes/:id/network-settings Update the outbound policy
POST /artifacts/pull Async pull (mirror + optional push)
POST /artifacts/build Async build
GET /artifacts/exists Local existence check
GET /artifacts/info Image info; 422 if cached error
POST /artifacts/remove Delete image + clear error cache
POST /artifacts/tag Re-tag (deprecated)
POST /artifacts/inspect Remote digest + size
GET /artifacts/logs Stream build log (follow=true polls until image exists)
POST /v1/boxes/:boxId/exec Create execution
GET /v1/boxes/:boxId/executions Live guest inventory (including main), without booting
GET /v1/boxes/:boxId/executions/:execId Execution status
DELETE /v1/boxes/:boxId/executions/:execId Kill + evict
GET /v1/boxes/:boxId/executions/:execId/attach WebSocket stdio + control
POST /v1/boxes/:boxId/executions/:execId/signal Cooperative signal (whitelist)
POST /v1/boxes/:boxId/executions/:execId/resize Resize TTY
PUT /v1/boxes/:boxId/files?path=<dest> Upload tar
GET /v1/boxes/:boxId/files?path=<src> Download tar
GET /v1/boxes/:boxId/metrics Per-box metrics
POST /v1/boxes/:boxId/ssh Configure guest SSH once; running boxes only
POST /v1/boxes/:boxId/ssh/enable Enable saved guest SSH configuration on a running box; otherwise 409; never boots
GET /v1/boxes/:boxId/ssh Guest SSH status; never boots
DELETE /v1/boxes/:boxId/ssh Disable guest SSH on a running box; otherwise 409; never boots

Building and running

# Build
make -C apps/runner build

# Run (uses BOXLITE_HOME_DIR for VM state)
BOXLITE_API_URL=http://localhost:3000/api \
BOXLITE_RUNNER_TOKEN=dev-secret \
API_PORT=3003 \
RUNNER_DOMAIN=localhost \
BOXLITE_HOME_DIR=/var/lib/boxlite \
  ./bin/boxlite-runner

Optional features are toggled by env vars:

  • BOXLITE_API_VERSION=2 — spawn the long-poll + healthcheck loops.
  • BOXLITE_MAX_SESSION_LIFETIME, BOXLITE_RECONNECT_GRACE, BOXLITE_SHUTDOWN_GRACE — exec reaping timers.
  • REGISTRY_PROXY_HOST, REGISTRY_PROXY_USERNAME, REGISTRY_PROXY_PASSWORD — pull an image whose registry credentials only the platform holds through the registry proxy. The password is this runner's own API key, so with a host set it defaults to BOXLITE_RUNNER_TOKEN, and the username to runner. A proxy host also listed in INSECURE_REGISTRIES is reached over HTTP.

Cloud hosts use the shared runner boot logic with cloud-specific providers; the retained AWS stack has its own bootstrap path. For local development against the Rust SDK directly, see boxlite serve at src/cli/src/commands/serve/ (Rust REST server with parity coverage).


Tests

SSH control boundary tests run without a VM using make test:apps:runner FILTER=TestSSHControlLifecycle. They verify that enable and disable reject idle boxes before fetching a handle, send one bodyless request per running-box call, and preserve every returned status field. make test:apps:runner FILTER=TestIntegrationSSHServesTheRealClient additionally requires a working VM runtime and OpenSSH: it reconnects after enable using the original trusted host key and account key. HTTP fixtures alone do not verify that the guest listener restarts.

# All runner tests
make test:apps:runner

# Just the attach + exec_manager suites
make test:apps:runner FILTER='Attach|ExecManager'

# With race detector (recommended; cleanupLoop ticker + attach goroutines)
make test:apps:runner GOTEST_FILTER='-race'

These make targets configure boxlite_dev to link the local C library. Runner uses the standard Go SDK start operation without a separate build tag.

If you hit "libboxlite.a not found" or unresolved-symbol errors:

git submodule update --init --recursive
cargo build -p boxlite-c
scripts/build/fix-go-symbols.sh target/debug/libboxlite.a

Related code

Fractional CPU allocations

Create and recovery requests accept cpuQuota as a number of cores from 0.125 to 16, in increments of 0.001. Omission retains the one-core default; explicit zero, non-finite values, and excess precision are rejected. The HTTP and v2 job paths preserve the number through the Go SDK; recovery validates it before destroying the old Box. Fractional Linux allocations use the Runtime's cgroup quota and rounded-up guest topology, with its existing best-effort membership behavior. Upgrade all Runners and matching native libraries before enabling fractional creation in the API, including migration destinations.

Cloud feature usage

SSH usage collection is disabled by default. Set BOXLITE_SSH_USAGE_ENABLED=true to enable collection and reporting at Runner startup. The setting applies only to usage telemetry.

When enabled, Runner drains accepted SSH authentication evidence only from running Cloud Boxes, using an independent native handle per read. Its background collector polls every five seconds, reads at most 64 Boxes per round with four workers, and applies a one-second deadline to each read. Larger inventories rotate between rounds. No read starts a VM. Older Guests are skipped with a diagnostic; the local SDK never uploads analytics automatically.

The shared reporter uses the existing API URL and Runner token. It enqueues locally without waiting, then sends batches over its own HTTP transport. Full queues drop observations; shutdown cancels collection before closing the native client. Invalid reporter configuration disables telemetry without stopping Runner. See collection, loss boundaries and query semantics.