Skip to content

Architecture of boxfork

This page describes the full system. It is for a new contributor who does not know the code. The page gives you:

  • the processes and the clients, and what talks to what
  • the packages of the repository
  • the path of each type of request through the code, with the function names
  • the states of a sandbox
  • the data that the daemon keeps, and the locks that protect the data
  • the limits in the code
  • the design decisions, with their reasons and their costs

Each statement about behavior comes from the code in the repository. A link gives the source file for each mechanism. The pages in Where to go next give more detail for each part.

The project runs sandboxes for AI agents on one Linux machine. A sandbox is an isolated Linux environment in which a client runs commands. One sandbox is one container. A client can do these operations on a sandbox:

  • create it, from an image or from a snapshot
  • run commands in it
  • read and write its files
  • snapshot it and fork it
  • pause it and resume it
  • kill it

The design has these aims:

  • One binary. The file boxfork contains the daemon, the CLI and the MCP server. It also contains the helper for amd64 and for arm64 (internal/guestbin/guestbin.go). The Go module uses only the standard library (go.mod).
  • One machine. One daemon owns all sandboxes of one engine. At its start, a daemon removes each boxfork container that its state file does not know. Thus two daemons cannot use one engine.
  • No database. The daemon keeps its records in memory and in one JSON file. The engine keeps the containers, the images and the volumes, with labels that identify them.
  • CPU and GPU sandboxes. A sandbox gets zero or more full GPUs. The GPU allocator gives each GPU to a maximum of one sandbox.
  • Snapshot and fork of files only. A snapshot is an image that the engine makes from the files of a container. A snapshot does not contain processes or memory.
  • Any Linux machine with Docker. The daemon speaks the Docker Engine API through a Unix socket or through TCP (internal/engine/docker.go). An engine that serves the same API, such as Podman, also works.
  • gVisor when it is installed. At its start, the daemon makes sure that the runsc runtime works. If not, the sandboxes are plain containers and the daemon says so in each sandbox record.
Process What starts it What it does
daemon The command boxfork serve (serve in cmd/boxfork/main.go) Serves the HTTP API. Keeps the records. Controls the engine. Runs the background loops.
engine Not a part of boxfork Runs the containers. Keeps the images, the snapshots, the volumes and the network of the sandboxes.
container Engine.Create and Engine.Start, called from Manager.boot One container for each sandbox. Its name is boxfork- and the ID of the sandbox.
first process The entrypoint of the container: /.boxfork/guest init runInit collects the exit status of each child process that lost its parent. It stops on SIGTERM or SIGINT. It does nothing else.
helper for one operation Engine.Exec, one call for each operation Does one operation and stops. See the table of modes below.
helper in serve mode Engine.Exec, called from openKept Serves the kept connection. It starts each command that the daemon sends as a frame. It stops when the daemon closes the connection.
MCP server The command boxfork mcp, which the agent starts Speaks the Model Context Protocol on its standard input and output. It is a client of the daemon.

The daemon never opens a network connection to a sandbox. Each exchange between the daemon and a sandbox goes through Engine.Exec. The engine starts the helper in the container and connects the standard input and output of the helper to the daemon. The package comment in internal/guest/proto.go gives this rule.

The helper is one program, /.boxfork/guest, with these modes (internal/guest/main.go):

Mode Caller in the daemon Purpose
init Entrypoint of each container First process of the sandbox.
run Manager.Exec One command, with frames in the two directions. Used for a streamed command.
serve openKept Many commands on the kept connection.
fs <spec> Manager.fsOp, helperFS One file operation: read, write, stat, list, mkdir, remove or rename.
version Manager.probe One line. Shows that the helper answers in a new container.
gpus Manager.checkGPUs One line: the GPUs that the sandbox sees.
dns [server...] Manager.setDNS, as user 0 Writes name servers in /etc/resolv.conf of the sandbox.
own [path...] Manager.giveVolumes, as user 0 Gives an empty new volume to the user of the sandbox.
procs Manager.suspend One line: the number of processes that run in the sandbox.
dial <port> No caller Connects standard input and output to a TCP port in the sandbox. The daemon does not use this mode at this time.

All clients use the same HTTP API (internal/api/server.go).

Client Source How it calls the daemon
CLI cmd/boxfork/cli.go, internal/client/client.go Each command, such as boxfork create, is one or more HTTP requests through client.Client. The command boxfork exec always asks for a streamed command (Client.ExecStream).
Python SDK sdk/python/src/boxfork HTTP with the standard library of Python. Sandbox.run asks for a streamed command only when the caller gives a callback for the output.
TypeScript SDK sdk/typescript/src HTTP. It does not have the pool calls.
MCP server internal/mcp/server.go, internal/mcp/session.go Session.Call sends each tool call to POST /v1/tools/{name} through Client.CallTool.
tool kit sdk/python/src/boxfork/toolkit.py, sdk/typescript/src/toolkit.ts Gets the tool definitions from GET /v1/tools. Sends each tool call to POST /v1/tools/{name}.
plain HTTP Your code Each program that has the API key can call the API.

The nine tools have one definition, in internal/tools/tools.go. The daemon does a tool call in its own process: Server.callTool calls Kit.Call, and Kit.Call calls the Manager. Thus the MCP server and the tool kit contain no sandbox logic. They contain only the rules of a session:

  • one sandbox for the agent
  • a limit on the number of sandboxes
  • the removal of the sandboxes at the end
flowchart LR
AGENT["Agent or model"]
subgraph CLIENTS["Clients"]
CLI["CLI"]
PY["Python SDK"]
TS["TypeScript SDK"]
MCP["MCP server: boxfork mcp"]
KIT["Tool kit of an SDK"]
CODE["Your code"]
end
subgraph DAEMON["Daemon: boxfork serve"]
API["api.Server"]
TOOLS["tools.Kit"]
MGR["sandbox.Manager"]
ALLOC["gpu.Allocator"]
GUARD["metadataGuard and hostfw"]
STATE[("state.json")]
end
subgraph ENGINE["Engine: Docker or Podman"]
ENG["Docker Engine API"]
IMG[("Images and snapshots")]
VOL[("Volumes")]
subgraph BOX["Container of one sandbox"]
INIT["First process: guest init"]
SERVE["guest serve: kept connection"]
ONE["guest run or guest fs: one operation"]
CMD["Commands of the client"]
end
end
AGENT -->|"MCP on stdin and stdout"| MCP
AGENT -->|"tool calls"| KIT
CLI -->|"HTTP and API key"| API
PY -->|"HTTP and API key"| API
TS -->|"HTTP and API key"| API
MCP -->|"HTTP and API key"| API
KIT -->|"HTTP and API key"| API
CODE -->|"HTTP and API key"| API
API --> MGR
API --> TOOLS
TOOLS --> MGR
MGR --> ALLOC
MGR --> STATE
MGR -->|"HTTP on a Unix socket or TCP"| ENG
ALLOC -->|"nvidia-smi"| GPUS["GPUs of the machine"]
GUARD -->|"iptables"| FW["Firewall of the machine"]
ENG --> IMG
ENG --> VOL
ENG -->|"exec with stdin and stdout"| SERVE
ENG -->|"exec with stdin and stdout"| ONE
SERVE --> CMD
ONE --> CMD
From To Transport Source
client daemon HTTP or HTTPS. The API key is in Authorization: Bearer or in X-API-Key. Server.auth in internal/api/server.go
agent MCP server One JSON-RPC message for each line, on standard input and output. Server.Serve in internal/mcp/server.go
daemon engine HTTP of the Docker Engine API. The default address is unix:///var/run/docker.sock. NewDocker in internal/engine/docker.go
daemon helper The connection of one Engine.Exec: frames or lines on standard input and output. internal/guest/proto.go
daemon GPUs The command nvidia-smi on the machine of the daemon. NvidiaSMI in internal/gpu/gpu.go
daemon firewall The commands iptables and ip6tables on the machine of the daemon. internal/hostfw/hostfw.go
sandbox internet The bridge network boxfork of the engine, if the sandbox has networking. Docker.EnsureNetwork

The Go module is boxfork. All Go packages are below cmd/ and internal/.

Path What it does What it uses
cmd/boxfork The binary. main.go has serve, which starts the daemon. cli.go has the CLI commands and runMCP. metadata.go has metadataGuard, which sets the firewall rules again and again. api, client, engine, gpu, guestbin, hostfw, mcp, sandbox
cmd/boxfork-guest The main function of the helper. It calls guest.Main. guest
cmd/boxfork-testserver Serves the real API on the test engine, for the tests of the SDKs. Its sandboxes are not isolated. apitest
internal/api The HTTP API: routes, API key, JSON bodies, error codes. It changes each request to a call of the Manager. gpu, guest, sandbox, tools
internal/apitest Builds a daemon on the test engine, with a clock that a test can move and GPUs that are not real. api, engine, enginetest, gpu, sandbox, tools
internal/client The Go client of the HTTP API. The CLI and the MCP server use it. It finds the address and the API key. api, gpu, sandbox, tools
internal/engine engine.go has the Engine interface: all that the daemon needs from an engine. docker.go has Docker, which speaks the Docker Engine API. Standard library only
internal/engine/enginetest The test engine Fake: an engine in memory. An exec runs the real helper code in the test process. engine, guest
internal/gpu NvidiaSMI reads the GPUs. Allocator is the GPU allocator. Standard library only
internal/guest The helper: all its modes and the frame protocol. The daemon imports this package for the frame types. Standard library only
internal/guestbin Embeds the two helper binaries in the daemon binary. For returns the binary for an architecture. Standard library only
internal/hostfw Block writes the firewall rules that keep sandboxes away from the metadata service of a cloud. Unblock removes them. Standard library only
internal/mcp Server speaks MCP. Session has the rules for one agent. sandbox, tools
internal/sandbox The core. Manager owns the records, the pools, the snapshots and the kept connections. See the table of files below. engine, gpu, guest
internal/tools The nine tools for a model: names, JSON Schema and the code that does each call (Kit). gpu, guest, sandbox
sdk/python The Python SDK: Sandbox, Snapshot, Volume, Pool, Toolkit. It has no dependencies. New features come here first. The HTTP API
sdk/typescript The TypeScript SDK. It does not have the pool calls. The HTTP API
scripts/install.sh The installer for a Linux machine. scripts/install_test.sh does tests on it with stand-ins. A POSIX shell
scripts/cloud-startup.sh Installs boxfork at the first start of a new cloud machine. install.sh
scripts/proof The proof scripts pool.sh and conn.sh. They do checks and time measurements through the HTTP API on a real engine. curl, a daemon that runs
scripts/ste_check.py The checker for the rules of STYLE.md. Python
Makefile make guest builds the two helper binaries. make build builds the daemon. make test runs all tests. make dist makes a release. Go 1.26
Dockerfile Builds the daemon as a container image. Go 1.26

The package internal/sandbox has one file for each part:

File Contents
manager.go Config, Manager, record, Detect, New, Create, boot, Kill, remove, forget, setPaused, Sweep, Reconcile, Watch
run.go Exec, Process, Run: commands on a connection of their own
kept.go cmdConn, openKept, keptFor, runKept: the kept connection
files.go fsOp, ReadFile, WriteFile and the other file operations
snapshot.go snapshot, Fork, DeleteSnapshot, emptyTrash, CheckSnapshots
suspend.go use, wake, Reclaim, suspend
pool.go SetPool, take, fromPool, drainPools, FillPools
volume.go Mount, checkMounts, CreateVolume, DeleteVolume
state.go stateFile, loadState, save

All routes are in Server.Handler in internal/api/server.go.

  1. Server.auth reads the API key from the request. It compares the SHA-256 of the two keys in constant time.
  2. A wrong key gets status 401. Only GET /v1/health needs no key.
  3. decode reads a JSON body of a maximum of maxJSONBody. It refuses a field that the API does not know.
  4. The handler calls one function of the Manager.
  5. If the function returns an error, Server.writeErr selects the HTTP status and the error code from the error type.

Each function of the Manager that needs a container starts with Manager.use (internal/sandbox/suspend.go). use finds the record and refuses a paused sandbox with ErrPaused. use wakes a suspended sandbox. Then it adds 1 to record.inUse and returns a done function. The caller calls done at the end of the operation, and done sets record.lastUsed. A sandbox with inUse above zero is not idle.

Source: Manager.Create and Manager.boot in internal/sandbox/manager.go.

  1. The client sends POST /v1/sandboxes. Server.create calls Manager.Create.
  2. Create does the checks on the request: timeout, names of environment variables, image name, mounts, idle time.
  3. Create makes a record with a new ID from newID. The record is not in Manager.boxes at this time.
  4. With Manager.mu locked, Create compares the number of sandboxes with Config.MaxSandboxes.
  5. fromPool finds no waiting sandbox for this request.
  6. Create adds 1 to Manager.pending, counts the volumes with holdVolumes and releases the lock.
  7. boot gets the image with Engine.EnsureImage. The engine pulls the image if it is not local.
  8. boot makes sure with engineMounts that each volume exists. It gets the helper binary for the architecture of the image.
  9. For a sandbox with networking, boot calls Engine.EnsureNetwork and then Config.NetworkReady.
  10. boot calls Engine.Create. The entrypoint is /.boxfork/guest init. The labels carry the ID of the sandbox.
  11. boot copies the helper into the container with Engine.CopyIn. Then it calls Engine.Start.
  12. If the daemon uses a runtime such as runsc, boot gets the runtime of the container from Engine.Inspect. A different runtime is an error.
  13. Manager.probe runs guest version in the container. An answer shows that the helper works.
  14. setDNS runs guest dns if the sandbox has networking and the isolation is gVisor or --dns is set.
  15. giveVolumes runs guest own for the volumes that are not read-only.
  16. Create sets CreatedAt and ExpiresAt. It puts the record in Manager.boxes and writes the state file.
  17. Server.create calls Server.unheard. If the client is gone, the daemon kills the new sandbox.
  18. The daemon sends status 201 and the sandbox as JSON.

If a step of boot fails, Manager.discard removes the container and releases the GPUs. If the write of the state file fails, Create removes the record from Manager.boxes and calls discard. Thus a failed create leaves nothing.

The container of a sandbox always has these properties (Docker.Create in internal/engine/docker.go):

  • The network is none, or the bridge network boxfork for a sandbox with networking.
  • The entrypoint is the helper and the command list is empty. The entrypoint and the command of the image do not run.
  • The environment variable NVIDIA_VISIBLE_DEVICES is void for a sandbox without a GPU.
  • The memory limit and the swap limit are the same value. The size of /dev/shm is half of the memory.
  • The container has the security option no-new-privileges. It does not have the capabilities NET_RAW, MKNOD and AUDIT_WRITE.
sequenceDiagram
participant C as Client
participant A as api.Server
participant M as sandbox.Manager
participant S as State file
participant E as Engine
participant H as Helper
C->>A: POST /v1/sandboxes
A->>M: Create
M->>M: checks, lock, limit, fromPool
alt a waiting sandbox agrees
M->>E: Inspect the container
E-->>M: it runs
M->>S: handOut and save
else no pool, or the pool is empty
M->>E: EnsureImage, EnsureNetwork
M->>E: Create, CopyIn helper, Start
E->>H: start guest init as first process
M->>E: Exec guest version
E->>H: start helper
H-->>M: version line
M->>S: save the new record
end
M-->>A: Sandbox
A-->>C: 201 and the sandbox as JSON

Source: take, fromPool in internal/sandbox/pool.go and handOut in internal/sandbox/manager.go.

Steps 1 to 4 are the same as without a pool.

  1. take returns nothing if the request has a GPU, environment variables or volumes of its own.
  2. poolLike looks for a pool with the same image or snapshot, CPUs, memory and network value.
  3. waiting gives the waiting sandboxes of that pool, oldest first. A waiting sandbox must have the Setup mark of this daemon.
  4. fromPool sets claimed on the record, adds 1 to pending and releases Manager.mu.
  5. fromPool calls Engine.Inspect. Then it locks Manager.mu again.
  6. If the container does not run, fromPool sets draining, calls kickPools and tries the next waiting sandbox.
  7. If the container runs, handOut clears Pool and sets the metadata, CreatedAt, ExpiresAt and the idle time.
  8. handOut writes the state file. If the write fails, handOut puts the old values back and the request fails.
  9. fromPool calls kickPools. The request continues at step 17 of the list above.

The engine starts nothing in these steps. The time of the sandbox starts when the daemon hands it out, because a waiting sandbox has no timeout.

The pool loop fills the pool again:

  1. kickPools puts a signal in the channel Manager.poolKick. WatchPools wakes and calls FillPools.
  2. fillPass calls drainPools. drainPools removes each waiting sandbox that no pool keeps.
  3. fillPass counts the sandboxes that each pool needs. It selects a maximum of poolBatch jobs, one pool after the other.
  4. fillOne calls Manager.Create with the internal field pool set. A maximum of poolParallel creates run at one time.
  5. This Create is the create without a pool, but the record gets the Pool mark and no timeout.
  6. If the create fails, fillOne writes the error in LastError and sets retryAt to poolRetry later.

These times are from the test machine (Docker with gVisor, 20 rounds each). A create took a median of 139 ms without a pool and 1.5 ms from a pool. On the test machine, the pool was full again 143 ms after a client took a sandbox.

Source: boot and checkGPUs in internal/sandbox/manager.go, Allocator in internal/gpu/gpu.go.

A request with a GPU never gets a waiting sandbox. The steps are those of a create without a pool, with these additions:

  1. Create refuses the request with gpu_unavailable if the daemon has no GPU allocator.
  2. If the request gives no memory, the sandbox gets a minimum of 8192 MB.
  3. In boot, Allocator.Allocate reads the load of the GPUs with nvidia-smi. Then it locks and selects the GPUs.
  4. Allocate does not select a GPU that a sandbox holds, that nvidia-smi does not list or that another program uses.
  5. Allocate selects a GPU with the suspect mark only when no other GPU is free.
  6. With the nvidia driver, boot gives the UUIDs to the engine and sets NVIDIA_VISIBLE_DEVICES to the UUIDs.
  7. With the cdi driver, boot gives the device names nvidia.com/gpu=<index> to the engine.
  8. boot writes the UUIDs in the label boxfork.gpus of the container.
  9. After the helper answers, checkGPUs runs guest gpus. The helper runs nvidia-smi in the sandbox.
  10. If the sandbox sees exactly its GPUs, the sandbox gets gpu_verified and Allocator.Trust clears the suspect mark.
  11. If the answer is wrong, Allocator.Distrust sets the suspect mark, discard removes the container and the create fails.
  12. If the sandbox has no nvidia-smi, the helper counts the device files /dev/nvidia<number>. A wrong count fails the create.
  13. A correct count gives a sandbox without gpu_verified. With --gpu-check require, the create fails also in this case.

The daemon releases a GPU only after the engine removed the container. If the engine cannot remove a container, the daemon puts the container in Manager.orphans. The GPUs stay with the owner until retryOrphans removes the container.

Source: internal/sandbox/kept.go, runServe in internal/guest/run.go.

This path is for a command that the daemon answers in one piece. The request is POST /v1/sandboxes/{id}/exec without "stream": true.

  1. Server.exec calls Manager.Run with the limit Server.MaxOutput for each output.
  2. Run calls runKept. runKept does not use the kept connection if Config.ConnectionIdle is negative.
  3. runKept also does not use the kept connection if the input for the command is larger than keptStdin.
  4. runKept calls Manager.use.
  5. keptFor takes the place in record.connGate. The record has no connection, thus keptFor calls openKept.
  6. openKept calls Engine.Exec with /.boxfork/guest serve. The engine starts the helper in the container.
  7. The helper sends a FrameHello frame. openKept waits a maximum of keptHello for it.
  8. openKept makes a cmdConn and starts the goroutine cmdConn.read. keptFor puts the connection in record.conn.
  9. cmdConn.run gives the command a number and sends one FrameSpec frame with the RunSpec as JSON.
  10. In the helper, runServe reads the frame. start starts the command in a new session.
  11. The helper sends FrameStarted, then FrameStdout and FrameStderr frames, then FrameExit. Each frame carries the number of the command.
  12. cmdConn.read adds the output to the keptRun of that number, up to the limit. At FrameExit it closes the channel done.
  13. cmdConn.run returns the Result. runKept calls the done function of use.
  14. The daemon sends status 200 and the result as JSON.

The steps are the same, but steps 6 to 8 do not occur. keptFor finds a connection in record.conn that cmdConn.usable accepts, and returns it. The daemon sends one frame, and the helper starts the command. The engine starts no process. Many commands can run at the same time on one kept connection, because each frame carries the number of its command.

On the test machine (Docker with gVisor, 30 rounds each), the first command in a sandbox took a median of 17 ms. The next commands took a median of 4 ms. A command on a connection of its own took a median of 13 ms.

sequenceDiagram
participant C as Client
participant M as sandbox.Manager
participant K as cmdConn
participant E as Engine
participant H as Helper in serve mode
C->>M: exec, not streamed (Run, runKept)
M->>M: use, then keptFor
opt the record has no usable connection
M->>E: Exec guest serve
E->>H: start helper
H-->>K: FrameHello
end
M->>K: run
K->>H: FrameSpec with number n
H->>H: start the command
H-->>K: FrameStarted n
H-->>K: FrameStdout n, FrameStderr n
H-->>K: FrameExit n
K-->>M: Result
M-->>C: 200 and the result as JSON
Note over K,H: The connection stays open for the next command
Note over M,K: Sweep closes it after ConnectionIdle without a command

The kept connection ends in these cases:

  • Sweep calls closeIdleConns each second. cmdConn.closeIfIdle closes a connection that ran no command for Config.ConnectionIdle.
  • forget calls dropConn when the sandbox goes.
  • keptFor closes a connection that belongs to an old container, after a suspend and a wake.
  • The helper does not take a frame in keptStall. cmdConn.send ends the connection.
  • The helper sends a frame that is not correct. cmdConn.read ends the connection.

A program in the sandbox can stop the helper. In that case the helper sends nothing for a new command. After keptStall, cmdConn.run returns an error, retires the connection and sends FrameClose for the command. A retired connection gets no new command, and the next command opens a new connection. Time in which the engine freezes the sandbox, for a snapshot or a pause, does not count. See internals/kept-connection.md.

The daemon uses a connection of its own for a command in these cases:

  • keptFor returns no connection. One cause is a helper from an older build that has no serve mode. keptFor then sets record.noConnIn.
  • The last open of a connection failed less than keptRetry ago, or the engine freezes the sandbox now.
  • The connection ended two times before the helper got the command.
  • The kept connection is off, or the input is too large.

Manager.Run then calls Manager.Exec, the same function that a streamed command uses, and collects the output.

Source: Manager.Exec in internal/sandbox/run.go, runCmd in internal/guest/run.go, Server.exec in internal/api/server.go.

  1. The client sends the exec request with "stream": true. Server.exec calls Manager.Exec.
  2. Exec calls use. Then it calls Engine.Exec with /.boxfork/guest run.
  3. released connects the close of the stream to the done function of use.
  4. Exec sends one FrameSpec frame. In the helper, runCmd calls start.
  5. Server.exec sends status 200 with the content type application/x-ndjson.
  6. Server.exec reads each event with Process.Next and writes it as one line of JSON. It flushes each line.
  7. The events are started, stdout, stderr and exit. The output data is base64 text in the JSON.
  8. If the stream breaks after the status line, the daemon sends an event of type error.
  9. If the client goes away, context.AfterFunc closes the stream. The helper then kills the process group with SIGKILL.

The daemon does not limit the output of a streamed command. The command stops at its end, at its own timeout (RunSpec.TimeoutMS) or when the client closes the connection.

Source: internal/sandbox/files.go, internal/guest/fs.go.

  1. The client sends GET /v1/sandboxes/{id}/files?path=<path>. Server.readFile calls Manager.ReadFile.
  2. fsOp calls use. Then it calls Engine.Exec with guest fs <spec>.
  3. The spec is one argument: the FSSpec as JSON in base64 (guest.EncodeFSSpec).
  4. In the helper, fsRead makes sure that the path is a regular file.
  5. The helper writes one header line, an FSHeader as JSON with the size and the mode. Then it writes exactly that number of bytes.
  6. In the daemon, answer reads the header line. It reads a maximum of maxAnswer bytes for this line.
  7. An error header becomes an FSError. Server.writeErr changes its code to an HTTP status with the table fsStatus.
  8. Server.readFile sets Content-Length and X-Boxfork-Mode. It copies the bytes to the client.
  9. FileReader.Close closes the stream, and that calls the done function of use.

If the copy stops early, the client gets fewer bytes than Content-Length. This is how the client knows that the file is not complete.

  1. The client sends PUT /v1/sandboxes/{id}/files?path=<path> with the bytes as the body. The parameter mode is optional.
  2. Server.writeFile puts the limit Server.MaxUpload on the body and calls Manager.WriteFile.
  3. fsOp starts guest fs with the operation write.
  4. WriteFile reads the body in pieces of 256 KiB. It sends each piece as a FrameStdin frame.
  5. At the end of the body, WriteFile sends FrameStdinEOF.
  6. In the helper, fsWrite writes the pieces to a temporary file .boxfork-write-* in the directory of the target.
  7. After FrameStdinEOF, the helper sets the mode and renames the temporary file to the target.
  8. The helper answers with a header line that has the size. The daemon returns the path and the size as JSON.

A file appears complete or not at all. If the body stops before FrameStdinEOF, the helper removes the temporary file.

The other file operations (Stat, ListDir, Mkdir, Remove, Rename) use Manager.simple. simple starts guest fs, reads the header line and closes the stream. All file operations use a connection of their own, not the kept connection.

Source: Manager.snapshot in internal/sandbox/snapshot.go.

  1. The client sends POST /v1/sandboxes/{id}/snapshot. Server.snapshot calls Manager.Snapshot.
  2. With Manager.mu locked, snapshot refuses if Manager.noSnapshots is set or if the limit Config.MaxSnapshots is full.
  3. snapshot makes an ID with the prefix snap_. It puts the ID in Manager.trash with the zero time and in Manager.committing.
  4. snapshot writes the state file. This write is before the engine call.
  5. snapshot locks record.opMu. wakeLocked wakes the sandbox if it is suspended.
  6. Engine.Commit saves the files of the container as the image boxfork-snapshot:<ID>. The engine pauses the container during the commit.
  7. snapshot unlocks record.opMu.
  8. On success, snapshot removes the ID from trash, adds the record to Manager.snaps and writes the state file.
  9. On failure, snapshot sets the time of the trash entry to the current time. emptyTrash then deletes the image.

Step 3 is a defence against lost files. If the daemon stops during the commit, the next start finds the ID in discarded and deletes the image. The engine can complete a commit after the daemon stopped to wait. Thus emptyTrash deletes the image again on each pass for trashGrace (one hour).

The context of the commit is not the context of the request (context.WithoutCancel), and it has a timeout of 15 minutes. The snapshot record lists the paths that are not in the snapshot (excluded):

  • the directories that the image keeps in volumes of its own
  • the paths where the sandbox has volumes mounted

Source: Manager.Fork in internal/sandbox/snapshot.go.

  1. The client sends POST /v1/sandboxes/{id}/fork with a count. Server.fork calls Manager.Fork.
  2. Fork refuses a count that is not from 1 to MaxFork.
  3. Fork builds one CreateRequest from the record: CPUs, memory, network, metadata and the same volumes.
  4. If the request does not give a GPU count, each copy gets the same number of GPUs as the original.
  5. Fork calls snapshot with temporary set. The new snapshot record starts with one user in refs: the fork.
  6. Fork puts the snapshot ID in Manager.forks.
  7. Fork calls Manager.Create for each copy, with a maximum of forkParallel at one time.
  8. Each copy gets the Fork mark in its record. Get and List do not show a record with this mark.
  9. After all creates, Fork removes the ID from Manager.forks.
  10. If all creates were good, Fork clears the Fork mark of all copies and writes the state file one time.
  11. If one create or the write fails, Fork kills all copies and returns the error.
  12. unrefSnapshot removes the user that the fork held. The daemon deletes a temporary snapshot that has no user.

The result is all copies or no copy. If the daemon stops during a fork, the copies have the Fork mark in the state file. After the start, Manager.forks is empty, and Sweep removes each record that has a Fork mark with no fork in progress.

The copies have the files of the original, but not its processes. The copies mount the same volumes as the original, not copies of the volumes. The temporary snapshot stays until the last copy goes.

Source: Manager.setPaused in internal/sandbox/manager.go.

  1. The client sends POST /v1/sandboxes/{id}/pause or .../resume. The handler calls Manager.Pause or Manager.Resume.
  2. setPaused makes a context that is not the context of the request, with a timeout of one minute.
  3. setPaused locks record.opMu. wakeLocked wakes the sandbox if it is suspended.
  4. If the record already has the state that the client wants, setPaused returns the sandbox.
  5. setPaused calls Engine.Pause or Engine.Unpause without Manager.mu.
  6. If the engine returns an error, setPaused calls Engine.Inspect. If the container has the wanted state, the operation is good.
  7. markPaused sets the state paused, moves the time that is left to RemainingNS and clears ExpiresAt.
  8. markResumed sets the state running and makes a new ExpiresAt from RemainingNS.
  9. setPaused writes the state file.

The timeout clock stops while a sandbox is paused. A paused sandbox refuses commands and file operations with the error code sandbox_paused. A resume of a suspended sandbox wakes it. Thus a client can use a resume to make a suspended sandbox ready before its next command.

Source: internal/sandbox/suspend.go.

A sandbox has an idle time in SuspendAfterSeconds. Zero means that the daemon never suspends the sandbox. The value comes from the create request, or from --gpu-idle-suspend for a sandbox with a GPU. Manager.idle says that a sandbox is idle when all of these are true:

  • the idle time is above zero and the state is running
  • the image keeps no directory in a volume of its own (UnsavedPaths is empty)
  • inUse is zero
  • the time after lastUsed is not less than the idle time

The suspend:

  1. The loop in Manager.Watch calls Reclaim each 2 seconds. Reclaim collects the idle sandboxes and calls suspend for each.
  2. suspend tries to lock record.opMu with TryLock. If it cannot, it stops for this pass.
  3. suspend stops if the image of the container has MaxLayers layers or more.
  4. suspend runs guest procs. The helper counts the processes, but not process 1, itself and a helper in serve mode.
  5. If the count is not zero, suspend sets lastUsed to the current time and stops.
  6. suspend sets the state suspended. A new command now waits in wake for record.opMu.
  7. suspend calls snapshot with temporary and held set. The engine commits the files.
  8. suspend sets Disk to the snapshot ID, clears ContainerID and writes the state file.
  9. suspend calls Engine.Remove for the container.
  10. suspend calls Allocator.Release, clears the GPUs of the record and writes the state file again.
  11. suspend removes one user from the snapshot that was the Disk before.

The write in step 8 is before the removal in step 9. If the daemon stops between the two steps, the next start finds a suspended record and removes the container as a leftover. If a step before step 9 fails, the sandbox continues to run in its container. If the removal in step 9 fails, the sandbox stays suspended and the container goes to Manager.orphans.

The wake:

  1. A command, a file operation, a snapshot, a fork, a pause or a resume arrives for the suspended sandbox.
  2. use calls wake. wake locks record.opMu, and thus waits for a suspend that is in progress.
  3. wakeLocked returns an error if an old container of the sandbox is in Manager.orphans.
  4. wakeLocked calls boot with the image of the Disk snapshot and with the GPU request in record.Want.
  5. boot does the same steps as for a create. It uses Engine.LocalImage, thus the engine pulls nothing.
  6. wakeLocked sets the state running, the new ContainerID and the new GPUs. It writes the state file.
  7. If the write fails, wakeLocked puts the record back to suspended and calls discard for the new container.
  8. use goes around its loop again and now finds a sandbox that runs.

A wake keeps the ID, the files and the volumes of the sandbox. A wake does not keep the processes. The sandbox can get different GPUs, or no wake at all if no GPU is free (gpu_unavailable). If a volume of the sandbox is gone, the wake fails with sandbox_stuck and the sandbox stays suspended.

sequenceDiagram
participant C as Client
participant M as sandbox.Manager
participant S as State file
participant E as Engine
participant G as gpu.Allocator
Note over M: Reclaim, each 2 seconds
M->>M: idle and TryLock opMu
M->>E: Exec guest procs
E-->>M: 0
M->>M: state = suspended
M->>E: Commit to a temporary snapshot
M->>S: save Disk, no ContainerID
M->>E: Remove the container
M->>G: Release the GPUs
M->>S: save
Note over C,M: Later
C->>M: exec
M->>M: use, wake, lock opMu
M->>G: Allocate
M->>E: Create from the snapshot image, CopyIn, Start
M->>E: Exec guest version
M->>S: save state = running, new ContainerID
M->>E: Exec for the command
M-->>C: result

Source: Manager.Kill, remove, forget in internal/sandbox/manager.go.

  1. The client sends DELETE /v1/sandboxes/{id}. Server.kill makes a context that is not the context of the request.
  2. Manager.Kill returns ErrNotFound for a waiting sandbox or a fork copy. A client cannot see these.
  3. remove sets record.dying with Manager.mu locked. For a suspended sandbox, it first locks record.opMu.
  4. remove calls Engine.Remove. The engine kills the container and deletes it.
  5. If the engine returns an error, remove clears dying and returns the error. The sandbox stays.
  6. forget deletes the record from Manager.boxes, calls dropConn and writes the state file.
  7. forget calls Allocator.Release, unless a container of the sandbox is in Manager.orphans.
  8. forget calls unrefSnapshot for the Snapshot and the Disk of the record.
  9. The daemon sends status 204.

A command that runs in the sandbox loses its connection when the container goes. Manager.cutOff changes this error to ErrNotFound, because the record is gone or has dying set.

Source: Manager.Sweep and remove in internal/sandbox/manager.go.

  1. Create or handOut sets ExpiresAt from the timeout of the request or from Config.DefaultTimeout.
  2. The client can set a new timeout with POST /v1/sandboxes/{id}/timeout (Manager.SetTimeout). Zero means no timeout.
  3. The loop in Manager.Watch calls Sweep each second.
  4. Sweep collects the IDs with an ExpiresAt that is not in the future.
  5. Sweep calls remove with onlyExpired set for each ID, in the sequence of the IDs.
  6. remove reads ExpiresAt again with Manager.mu locked. A timeout that the client extended a moment before stays valid.
  7. The other steps are those of a kill.

A paused sandbox has no ExpiresAt, thus it does not time out. A suspended sandbox keeps its ExpiresAt, thus it can time out. A waiting sandbox has no timeout.

Source: Manager.Reconcile, reap and syncPaused in internal/sandbox/manager.go.

The engine can kill a container, for example when the container uses too much memory. Reconcile runs each 20 seconds and compares the records with Engine.List. For a record with no container that runs, reap asks Engine.Inspect again, removes the container and calls forget. For a record that disagrees with its container about pause, syncPaused corrects the record. A command or a pause can also find the loss earlier: engineErr calls forget when the engine says that the container does not exist.

The field State of a record has three values: running, paused and suspended (internal/sandbox/manager.go). A record can also have marks that hide it from the clients:

  • Pool: the sandbox is a waiting sandbox. Its state is running.
  • Fork: the sandbox is a copy of a fork that is not complete. Its state is running.
  • dying: the daemon removes the container at this moment. This mark is only in memory.
stateDiagram-v2
[*] --> running: Create
[*] --> waiting: fillOne
[*] --> copy: Fork starts
waiting --> running: handOut
waiting --> [*]: drainPools
copy --> running: Fork completes
copy --> [*]: Fork fails or Sweep
running --> paused: Pause
paused --> running: Resume
running --> suspended: suspend
suspended --> running: wakeLocked
running --> [*]: Kill, timeout, reap
paused --> [*]: Kill, reap
suspended --> [*]: Kill, timeout

In the diagram, waiting is running with the Pool mark and copy is running with the Fork mark.

From To Who causes it Function
none running A client creates a sandbox and no waiting sandbox agrees. Manager.Create, boot
none running with Pool The pool loop fills a pool. fillOne, Manager.Create
running with Pool running A client creates a sandbox that agrees with the pool. fromPool, handOut
running with Pool removed The pool is gone or too large, the Setup mark is old, or the container does not run. drainPools, remove
none running with Fork A client forks a sandbox. Manager.Fork, Manager.Create
running with Fork running All copies of the fork exist. Manager.Fork
running with Fork removed One copy failed, or the daemon stopped during the fork. Manager.Fork, Sweep, remove
running paused A client pauses the sandbox. Manager.Pause, setPaused, markPaused
paused running A client resumes the sandbox. Manager.Resume, setPaused, markResumed
running or paused the state of the container The record and the engine disagree about pause. The engine wins. syncPaused, and New at the start
running suspended The reclaim loop finds the sandbox idle with no processes. Reclaim, suspend
suspended running A client uses the sandbox: command, file operation, snapshot, fork, pause or resume. use, wake, wakeLocked
suspended paused A client pauses a suspended sandbox. The daemon wakes it and then pauses it. setPaused
suspended with a container running The daemon stopped during a suspend, before the record lost its container. New
running, paused or suspended removed A client kills the sandbox. Manager.Kill, remove, forget
running or suspended removed The timeout is over. Sweep, remove
running or paused removed The container stopped or is gone. Reconcile, reap, engineErr, forget
running removed The client went away before it got the ID of its new sandbox. Server.unheard
all removed At the start, the container of the record is gone, or its GPUs belong to another sandbox. New

The Manager keeps three maps of records in memory (internal/sandbox/manager.go). The state file has a copy of the fields that have a JSON name.

Record Map Fields in the state file Fields only in memory
sandbox (record) Manager.boxes The public Sandbox fields: id, image, state, isolation, cpus, memory_mb, gpus, network, metadata, created_at, gpu_verified, suspend_after_seconds, unsaved_paths, volumes, snapshot, expires_at. The internal fields: container_id, fork, pool, setup, remaining_ns, disk, gpu_request, layers. dying, draining, claimed, suspendAsked, tooDeep, inUse, lastUsed, conn, noConnIn, openFailed, frozen, thawedAt, and the locks opMu and connGate
snapshot (snapRecord) Manager.snaps id, sandbox_id, image, metadata, created_at, temporary, excluded_paths refs, dying
pool (poolRecord) Manager.pools id, image, snapshot, size, cpus, memory_mb, network, created_at, ready, last_error filling, retryAt, dying

The daemon keeps no record for a volume. The engine keeps the volumes, and the daemon finds them by their labels (internal/sandbox/volume.go). Thus a lost state file loses no volume.

A record does not contain the environment variables of a sandbox, because they can be secrets. The daemon gives the variables to the engine at the create and does not keep them.

Source: internal/sandbox/state.go.

The state file is state.json in the data directory of the daemon. The data directory is the value of --data-dir. client.DefaultDataDir gives the default:

  • the value of BOXFORK_DATA_DIR, if it is set
  • /var/lib/boxfork for the user root
  • .boxfork in the home directory for other users

The file is one JSON object (stateFile) with these fields:

Field Contents
version The number 1. loadState does not read this number at this time.
sandboxes All sandbox records, in the sequence of their IDs. Waiting sandboxes and fork copies are in this list.
snapshots All snapshot records, temporary snapshots also.
pools All pool records.
discarded The map Manager.trash: snapshot IDs with images that the daemon must delete, each with a time. The zero time means that a commit was in progress.

Manager.save writes the full file each time. The caller holds Manager.mu, thus the file always shows one consistent set of records. save writes a temporary file .state-* in the same directory, calls Sync, and renames it to state.json. After a crash, the file is the old version or the new version, never a part of one. save makes the directory with mode 0700.

The daemon writes the state file after each change of a field that is in the file. The table shows each caller of save and what occurs if the write fails.

Caller When If the write fails
New At the end of the start The daemon does not start.
Create After boot, when the record goes into Manager.boxes The record is removed, discard removes the container and the create fails.
handOut A waiting sandbox goes to a client The record gets its old values and the create fails.
wakeLocked After the new container runs The record goes back to suspended, discard removes the new container and the wake fails.
suspend, first write Before the removal of the container The sandbox continues to run. The new snapshot loses its user.
suspend, second write After the release of the GPUs The daemon writes an error in its log. Memory is correct.
snapshot, first write Before the commit The snapshot fails. The engine saved nothing.
snapshot, second write After the commit The snapshot fails. The ID goes to trash and emptyTrash deletes the image.
Fork When all copies lose their Fork mark The copies get the mark back, the daemon kills them and the fork fails.
SetPool, resize, DeletePool A pool changes The change is undone in memory and the request fails.
forget, setPaused, SetTimeout, syncPaused, dropSnapshot, forgetLostSnapshot, emptyTrash, checkSnapshots The change is already real in the engine or has no undo The daemon writes an error in its log and continues. Memory is correct, and the next good write puts the file in line.

The daemon builds this data again after a start, or the data is not necessary after a start.

Data Where After a start
Manager.pending, snapsPending, volPending, volDeleting Counts and marks for operations in progress Empty. No operation is in progress.
Manager.forks Forks in progress Empty. Sweep removes the copies that have a Fork mark.
Manager.committing Commits in progress Empty. The IDs are in discarded with the zero time, and New gives them the current time.
Manager.orphans Containers that the engine did not remove, with the owner of their GPUs Empty. New finds these containers again by their labels.
Manager.noSnapshots The reason why snapshots do not work, or empty CheckSnapshots does the check again.
Manager.setup The mark from setupOf New calculates it again.
record.inUse, record.lastUsed Use of a sandbox Each sandbox counts as used at the moment of the start.
record.conn The kept connection No connection. The next command opens one.
snapRecord.refs The number of users of a snapshot New counts the sandboxes that use each snapshot.
Allocator.owner Which sandbox holds which GPU New calls Allocator.Restore for each GPU record.
Allocator.suspect GPUs that a sandbox did not see Empty.
metadataGuard.blocked, tried The result of the last firewall pass metadataGuard.start sets the rules again.

The daemon marks all that it makes in the engine.

Object Name Labels and options Source
container of a sandbox boxfork-<sandbox ID> boxfork.managed=true, boxfork.id=<sandbox ID>, boxfork.gpus=<UUIDs with commas> (empty without GPUs) boot
trial container for the runtime boxfork-probe-<ID> boxfork.managed=true, boxfork.id=probe tryRuntime
trial containers for the snapshot check boxfork-check-<ID> boxfork.managed=true, boxfork.id=check, boxfork.gpus= checkSnapshots
snapshot image boxfork-snapshot:<snapshot ID without snap_> The daemon sets no label on an image. The code comments in New and boot say that an image from a commit carries the labels of its container. snapshotRef, Engine.Commit
volume boxfork-vol-<name> boxfork.managed=true, boxfork.volume=<name> createVolume
network boxfork boxfork.managed=true, driver bridge, option com.docker.network.bridge.enable_icc=false Docker.EnsureNetwork

boot sets all three labels on each container. The reason is the snapshot image: a copy must not get the GPU label of the original.

The daemon does not trust the label filter of the engine. Docker.List and Docker.Volumes examine the labels again. New removes only a container that carries the label and a name that starts with boxfork-. engineVolume accepts only a volume with the two labels and the correct name.

Source: serve in cmd/boxfork/main.go, New in internal/sandbox/manager.go.

  1. serve reads the flags and the TLS files. engine.NewDocker makes the engine client, and Engine.Info makes sure that the engine answers.
  2. sandbox.Detect selects the isolation. If the engine lists runsc, tryRuntime starts one trial container with it.
  3. gpu.NewAllocator reads the GPUs one time with nvidia-smi. With zero GPUs, the daemon has no GPU allocator.
  4. loadKey reads the API key from the file api-key, or makes a new key.
  5. sandbox.New starts. ensureDefaultVolumes makes each default volume that does not exist.
  6. loadState reads the state file. A file that is not correct JSON stops the start.
  7. New copies the discarded IDs to Manager.trash. An ID with the zero time gets the current time.
  8. New keeps each snapshot record, unless Engine.LocalImage says that its image is gone.
  9. New keeps each pool record, unless its snapshot is gone.
  10. New gets the containers with the label boxfork.managed=true from Engine.List.
  11. New keeps a suspended record with no container only if its Disk snapshot exists. It clears the GPUs of the record.
  12. A record with the state suspended and a container becomes running.
  13. New drops a record if its container is gone or does not run.
  14. For a record with GPUs, Allocator.Restore gives the GPUs to the sandbox again.
  15. New drops a GPU record if the machine has no GPUs now. It also drops the record if another sandbox holds one of its GPUs.
  16. If the record and the container disagree about pause, markPaused or markResumed corrects the record.
  17. New adds each kept sandbox as a user of its Snapshot and its Disk snapshot.
  18. New removes each boxfork container that no kept record owns.
  19. If a removal fails, the container goes to Manager.orphans. Restore holds the GPUs from its label boxfork.gpus.
  20. New writes the state file. Then sweepSnapshots deletes the temporary snapshots with no user and the images in trash.
  21. Manager.CheckNetwork makes the network boxfork and reads if the engine blocks traffic between sandboxes.
  22. metadataGuard.start sets the firewall rules. Manager.CheckSnapshots does a snapshot of a trial container.
  23. serve starts Manager.Watch and then the HTTP server.

The daemon drops a record when it removes the record from the list that it keeps. The dropped record is not in the state file that step 20 writes.

When the daemon gets SIGINT or SIGTERM, serve stops the HTTP server with a limit of 5 seconds. The daemon does not stop the sandboxes. The next start finds them again with the steps above.

The daemon does not list the images of the engine at its start. If you delete the state file, the containers go at the next start, the volumes stay and the snapshot images stay in the engine. The daemon then does not know those images.

Lock Where What it protects
Manager.mu manager.go The maps boxes, snaps, pools, orphans, trash, committing, forks, volPending, volDeleting. The counts pending and snapsPending. The field noSnapshots. All fields of each record. The write of the state file.
record.opMu manager.go One operation at a time on the container of one sandbox: pause, resume, commit, suspend, wake, and the kill of a suspended sandbox.
record.connGate kept.go The open of the kept connection of one sandbox. One request opens the connection and the others wait, each until its context ends. It is a channel with one place.
Manager.volMu volume.go One create or delete of a volume at a time.
cmdConn.mu kept.go The commands on one kept connection (runs, next), idleAt, retired, and the close of the channel ended.
MuxWriter.mu, FrameWriter.mu proto.go One frame at a time on one stream.
Allocator.mu gpu.go The maps owner and suspect.
metadataGuard.mu metadata.go One pass over the firewall rules at a time.
demux.mu docker.go The buffer for the error output of one exec.
Session.mu, Session.ownMu session.go The sandboxes of one MCP session, and the start of the own sandbox of the session. These locks are in the MCP server process.

Manager.dnsWarned is a sync.Once: the daemon writes the warning about name servers one time.

The code takes the locks in this order:

  1. record.opMu, record.connGate or Manager.volMu
  2. Manager.mu
  3. cmdConn.mu

These rules follow from the code:

  • A function never waits for record.opMu, record.connGate or Manager.volMu while it holds Manager.mu. It first releases Manager.mu.
  • A function does not hold two of the locks of step 1 at the same time.
  • A method of cmdConn never takes Manager.mu.
  • The daemon does not hold Manager.mu when it calls the GPU allocator.
  • A background loop uses TryLock on record.opMu. If an operation holds the lock, the loop tries again on its next pass.

The functions suspend, reap, syncPaused and remove with onlyExpired use TryLock. Thus a long commit on one sandbox cannot stop the timeouts of the other sandboxes.

The daemon makes no engine call and no helper exchange while it holds Manager.mu. An engine call can take a long time: a pull or a commit can take minutes. If the daemon held the lock for that time, all other requests waited.

The pattern is the same in each operation:

  1. Lock Manager.mu. Read the record and do the checks.
  2. Set a mark or a count that tells the other operations about this one. Unlock.
  3. Call the engine.
  4. Lock Manager.mu again. Make sure that Manager.boxes[id] is the same record and that it is not dying.
  5. Write the result in the record, call save and unlock.

The marks and counts of step 2 are:

Mark or count Set by Effect on other operations
Manager.pending Create, fromPool Counts against MaxSandboxes before the record exists.
record.dying remove The record is hidden. No operation starts on it.
record.claimed fromPool No other request gets this waiting sandbox, and drainPools does not remove it.
record.draining drainPools, fromPool, fillOne waiting does not return this sandbox.
record.inUse use idle returns false.
record.Fork and Manager.forks Fork The copies are hidden, and Sweep does not remove them during the fork.
snapRecord.refs refSnapshot, snapshot DeleteSnapshot refuses with in_use.
snapRecord.dying, poolRecord.dying DeleteSnapshot, unrefSnapshot, DeletePool The object is hidden during its deletion.
Manager.snapsPending snapshot Counts against MaxSnapshots during the commit.
Manager.committing snapshot, checkSnapshots emptyTrash does not delete an image that the engine writes at this moment.
Manager.volPending holdVolumes DeleteVolume refuses a volume that a new sandbox mounts.
Manager.volDeleting DeleteVolume holdVolumes refuses a volume that the daemon deletes.
poolRecord.filling fillPass The pool loop does not start too many sandboxes. DeletePool of a snapshot pool waits for zero.

The one input or output operation with Manager.mu held is the write of the state file. The reason is that the file must show the same set of records that memory shows. The cost is in One JSON state file.

Some operations must complete after the client goes away. These operations use context.WithoutCancel and a timeout of their own:

  • kill, in Server.kill
  • pause and resume, in setPaused
  • wake, in wakeLocked
  • commit, in snapshot
  • the removal of a container after a failed create, in discard
  • the deletion of a pool, in Server.deletePool
  • the open of the kept connection, in openKept

serve starts Manager.Watch in one goroutine (internal/sandbox/manager.go). Watch starts two more goroutines and then runs the sweep in its own loop.

Loop Period Function Work
sweep 1 second Manager.Sweep closeIdleConns closes idle kept connections. Removes fork copies with no fork in progress. Kills the sandboxes with a timeout that is over.
reconcile 20 seconds Manager.Reconcile retryOrphans tries the failed removals again. sweepSnapshots deletes temporary snapshots with no user and calls emptyTrash. reap and syncPaused put the records in line with the engine.
reclaim 2 seconds Manager.Reclaim Suspends the idle sandboxes.
pools A signal from kickPools, or 10 seconds Manager.WatchPools, FillPools drainPools removes waiting sandboxes that no pool keeps. fillOne starts the sandboxes that a pool needs.
metadata 30 seconds metadataGuard.watch, again Sets the firewall rules again. Other software can clear them, and the network can get a new address range.
kept connection No period: one goroutine for each connection cmdConn.read Reads the frames of the helper and gives them to their commands.

The sweep and the reconcile run in the same goroutine, thus they never run at the same time. The reclaim has a goroutine of its own, because a suspend saves files and can take a long time. The pool loop has a goroutine of its own, because the start of a sandbox takes time. The comments in Manager.Watch give these reasons.

The HTTP server of Go starts one goroutine for each request. Fork runs a maximum of forkParallel creates at one time. fillPass runs a maximum of poolParallel creates at one time.

Source: internal/sandbox.

Limit Name Value
Default image Config.DefaultImage, --default-image ubuntu:24.04
Default timeout of a sandbox Config.DefaultTimeout, --default-timeout 5 minutes
Maximum timeout of a sandbox Config.MaxTimeout, --max-timeout 0: no limit
Default CPUs Config.DefaultCPUs 2
Default memory Config.DefaultMemoryMB 1024 MB, and 8192 MB for a sandbox with a GPU
Processes in one sandbox Config.PidsLimit 4096
Size of /dev/shm ShmMB in boot Half of the memory
Maximum number of sandboxes Config.MaxSandboxes, --max-sandboxes 0: no limit. Waiting sandboxes do not count.
Maximum number of kept snapshots Config.MaxSnapshots, --max-snapshots 0: no limit. Temporary snapshots do not count.
Maximum number of volumes Config.MaxVolumes, --max-volumes 0: no limit
Waiting sandboxes in all pools DefaultMaxPooled, --max-pooled 64. The flag value 0 means that the daemon keeps none.
Minimum idle time before a suspend MinSuspendAfter 10 seconds
Layers of an image that the daemon still suspends MaxLayers 100
Copies in one fork MaxFork 64
Creates at one time in one fork forkParallel 8
Time that the daemon continues to delete a failed snapshot image trashGrace 1 hour
Creates at one time for the pools poolParallel 4
Creates in one pass of the pool loop poolBatch 8
Wait after a failed create for a pool poolRetry 30 seconds
Volumes that one sandbox mounts MaxMounts 16
Length of a volume name volumeName 63 characters: lower-case letters, digits, ., _, -
Idle time of the kept connection DefaultConnectionIdle, --connection-idle 1 minute. The flag value 0 means no kept connection.
Input of a command on the kept connection keptStdin 1 MiB. A larger input uses a connection of its own.
Wait for the first frame of the helper in serve mode keptHello 15 seconds
Wait for the helper to take a frame or to answer a command keptStall 10 seconds
Answer line of a file operation maxAnswer 32 MiB
Answer line of version, gpus, dns, own, procs askAs 16 KiB
Wait for version, dns, own, procs probe, setDNS, giveVolumes, suspend 30 seconds
Wait for gpus checkGPUs 45 seconds
One piece of input or of an upload Process.Write, WriteFile, cmdConn.run 256 KiB
Time for a pause or a resume setPaused 1 minute
Time for a wake wakeLocked 5 minutes
Time for a commit snapshot 15 minutes
Time for the removal of a container after a failed create discard 30 seconds
Time for the removal of the container in a suspend suspend 1 minute
Time for the deletion of a snapshot image DeleteSnapshot, sweepSnapshots 2 minutes
Time for the deletion of a temporary snapshot after a kill unrefSnapshot 30 seconds
Time for the removal of the copies of a failed fork Fork 2 minutes
Trial containers tryRuntime, checkSnapshots 1 CPU, 256 MB, 64 processes, no network

Limits in the API, the daemon command and the clients

Section titled “Limits in the API, the daemon command and the clients”

Source: internal/api/server.go, cmd/boxfork/main.go, cmd/boxfork/cli.go, internal/client/client.go.

Limit Name Value
JSON body of a request maxJSONBody 8 MiB
Each output of a command that is not streamed Server.MaxOutput 4 MiB. The result then has truncated set.
One file upload Server.MaxUpload 4 GiB
A duration in a request seconds A maximum of 100 years. A positive value is a minimum of 1 millisecond.
File mode of an upload Server.writeFile Octal, from 1 to 7777
Time for a kill after the client goes away Server.kill, Server.unheard 1 minute
Time for the deletion of a pool Server.deletePool 2 minutes
Length of the API key loadKey A new key is abx_ and 48 hexadecimal characters. A key of fewer than 16 characters is an error.
Mode of the API key file loadKey 0600. A file that other users can read is an error.
Time to read the headers of a request ReadHeaderTimeout in serve 10 seconds
Idle time of an HTTP connection IdleTimeout in serve 2 minutes
Time for the stop of the HTTP server serve 5 seconds
Minimum TLS version tlsConfig, pinned TLS 1.2
Memory in use above which a free GPU counts as busy --gpu-busy-mb 512 MB
Period of the firewall pass guard.watch in serve 30 seconds
Idle time of a sandbox of an MCP session --idle-timeout of boxfork mcp 30 minutes
Sandboxes of one MCP session --max-sandboxes of boxfork mcp 16
Time to remove the sandboxes at the end of an MCP session runMCP 30 seconds
Error body that the Go client reads Client.request 1 MiB

Limits in the engine client, the helper, the tools and the MCP server

Section titled “Limits in the engine client, the helper, the tools and the MCP server”

Source: internal/engine/docker.go, internal/guest, internal/tools/tools.go, internal/mcp/server.go, internal/hostfw/hostfw.go.

Limit Name Value
Error output that the daemon keeps from one exec maxStderr 16 KiB
Error body that the daemon reads from the engine apiError 64 KiB
Time for the start of an exec, when the context has no deadline Docker.Exec 30 seconds
Idle connections to the engine MaxIdleConnsPerHost, IdleConnTimeout 16 connections, 60 seconds
Payload of one frame guest.MaxFrame 4 MiB
Time that the helper collects output after the exit of a command drainGrace 300 milliseconds
Queue of input pieces for one command in the helper stdinQ in start 1024 pieces. In serve mode, the helper kills a command with a full queue.
File with no size, for example in /proc maxSizeless 16 MiB
Time for nvidia-smi in the sandbox gpuQuery 20 seconds
Name servers in /etc/resolv.conf maxNameServers 3
Size of /etc/resolv.conf that the helper reads maxResolv 64 KiB
Length of a one-line reason from the helper oneLine 300 characters
Signal number ParseSignal From 1 to 64
Output of one stream that a tool gives to a model modelChars 12000 characters. The function middle cuts the middle of a longer output.
Output of one stream that a tool keeps captureBytes 2 MiB
Timeout of the tool sandbox_exec defaultExec, maxExec 2 minutes by default, 30 minutes maximum
File size that the tool sandbox_read_file returns readBytes, maxReadBytes 256 KiB by default, 4 MiB maximum
One MCP message maxLine 9 MiB
Time for calls in progress after the agent closes its input grace 5 seconds
Wait for the lock of iptables -w 5 in hostfw 5 seconds

The helper runs in the sandbox, and a program in the sandbox can replace it or stop it. Thus the daemon does not trust what the helper sends:

  • Each answer line has a maximum size (maxAnswer, 16 KiB in askAs).
  • Each frame has a maximum size (MaxFrame). ReadFrame and ReadMux refuse a larger frame.
  • cmdConn.read drops a frame for a command number that does not exist. A frame that is not correct ends the connection.
  • capped keeps only the first bytes of an output, up to the limit.
  • Timers (keptHello, keptStall, the waits in askAs) stop a wait for a helper that does not answer.

The other defences:

  • Runtime. boot reads the runtime of each new container from the engine. boot removes a container that has a different runtime (manager.go).
  • GPUs. The daemon always sets NVIDIA_VISIBLE_DEVICES. A client cannot set this variable. checkGPUs asks the sandbox which GPUs it sees.
  • Images. imageRef limits the characters of an image name, because the name goes into a URL of the engine API. Create refuses the name of a snapshot image.
  • Mounts. A mount is always a volume of the engine with the boxfork labels, never a directory of the machine. checkMounts refuses /, /.boxfork, /proc, /sys and /dev.
  • Container. Docker.Create sets no-new-privileges, removes three capabilities and sets the limits for memory, swap and processes.
  • Network. The network boxfork has traffic between containers off. Docker.EnsureNetwork reads the option back from the engine, and boxfork info shows the result.
  • Metadata service. hostfw.Block puts rules in the DOCKER-USER chain. The rules reject traffic from the sandbox network to the metadata addresses, but port 53 stays open (hostfw.go).
  • API key. Server.auth compares in constant time. loadKey refuses a key file that other users can read. The Go client follows no redirect, thus the key goes to no other address.
  • Requests. decode refuses unknown fields and large bodies.
  • Clients that go away. Server.unheard kills a sandbox when its client is gone before the answer.
  • State file. save writes a temporary file, calls Sync and renames.
  • Plain HTTP. serve writes a warning when the API listens on an address that is not loopback without TLS.

Each decision has three parts: the choice, the reason and the cost. The page docs/decisions.md has the full list.

A helper through the exec of the engine, and no network connection into the sandbox

Section titled “A helper through the exec of the engine, and no network connection into the sandbox”
  • Choice. The daemon puts one static binary at /.boxfork/guest in each container. Each exchange is an Engine.Exec of this binary, with frames or lines on standard input and output.
  • Reason. A sandbox with the network off works the same as one with the network on. The sandbox has no open port for the daemon. An idle sandbox runs only its first process. The helper needs nothing from the image.
  • Cost. Each exec is a new process that the engine starts. On the test machine, a command on a connection of its own took a median of 13 ms.
  • Cost. The helper runs where the client code runs, thus the daemon cannot trust its answers. All the size limits and timers in Defences come from this.
  • Cost. The entrypoint of the image does not run, because the helper is the entrypoint. The directory /.boxfork is in each sandbox and in each snapshot.

Source: internal/guest/proto.go, boot in internal/sandbox/manager.go.

  • Choice. The daemon keeps all records in memory and writes them to one file, state.json, on each change. The engine is the second source: at the start, New compares the file with the containers.
  • Reason. The system is one daemon on one machine. A file needs no install and no service. A rename makes each write atomic. A person can read the file.
  • Cost. save writes the full file and calls Sync while its caller holds Manager.mu. All requests that need the lock wait for the disk. The cost grows with the number of records.
  • Cost. Two daemons cannot share the file or the engine.
  • Cost. The file has no history. If the file is lost, the sandboxes and the knowledge of the snapshots are lost.

Source: internal/sandbox/state.go.

  • Choice. Allocator.Allocate gives a GPU to one sandbox only. It is all the GPUs of the request or none.
  • Reason. The package comment in internal/gpu/gpu.go gives the reason. Two programs that share a GPU have no isolation of memory or of faults between them.
  • Cost. The machine runs a maximum of one GPU sandbox for each GPU. A request fails with gpu_unavailable when no GPU is free.
  • Cost. An idle sandbox holds its GPU. The idle suspend exists to release such a GPU, and it is off by default.

Snapshots as images of the engine, files only

Section titled “Snapshots as images of the engine, files only”
  • Choice. A snapshot is the result of Engine.Commit: a local image with the name boxfork-snapshot:<ID>. A fork and a suspend use the same mechanism with a temporary snapshot.
  • Reason. Each engine with the Docker API has the commit. The engine shares the layers that did not change between the copies. The daemon needs no storage system of its own.
  • Cost. A snapshot has no processes and no memory. A wake or a fork starts with the files only.
  • Cost. The directories that an image keeps in volumes of its own are not in a snapshot. The daemon never suspends a sandbox that has such a directory with no volume mounted on it.
  • Cost. Each suspend adds one layer. A code comment in suspend.go says that the engine refuses at approximately 125 layers. The daemon stops to suspend a sandbox at MaxLayers.
  • Cost. A runtime can keep the file changes away from the commit. CheckSnapshots finds this at the start, and the daemon then refuses snapshot, fork and suspend with unsupported.
  • Cost. The engine pauses the container during the commit.

Source: internal/sandbox/snapshot.go, internal/sandbox/suspend.go.

gVisor first, and a plain container as a marked fallback

Section titled “gVisor first, and a plain container as a marked fallback”
  • Choice. With --isolation auto, Detect uses runsc if a trial container really runs with it. If not, the sandboxes are plain containers. With --isolation gvisor, the daemon does not start without gVisor.
  • Reason. The daemon must work on each Linux machine with Docker. gVisor is not installed on each machine.
  • Reason for the trial. An engine can list a runtime that is not installed, or can run the container with a different runtime. Thus tryRuntime and boot read the runtime back from Engine.Inspect.
  • Cost. A plain container shares the kernel of the machine. It is safe only for code that you trust.
  • Mark of the fallback. Each sandbox has the field isolation with gvisor or container. GET /v1/info has the same field. The daemon writes a warning at its start.
  • Cost under gVisor. The sandbox cannot get to the name server of the engine at 127.0.0.11, thus setDNS writes other name servers. The runtime also needs the correct overlay option for snapshots.

Source: Detect and tryRuntime in internal/sandbox/manager.go, internal/guest/resolv.go.

  • Choice. The daemon has one API key in the file api-key. Server.auth asks for it on each route but GET /v1/health.
  • Reason. The daemon serves one owner on one machine. One key needs no user store.
  • Cost. Each client with the key sees and controls all sandboxes. The API has no limits or records for each client.
  • Cost. The limits of an MCP session are in the client process (Session.room). They are not a defence against a client that has the key.

Source: loadKey in cmd/boxfork/main.go, Server.auth in internal/api/server.go.

A pool hands out sandboxes that already run

Section titled “A pool hands out sandboxes that already run”
  • Choice. A pool keeps a number of started sandboxes for one image or snapshot and one size. Create hands out a waiting sandbox when the request agrees exactly.
  • Reason. The time of a create is the time that the engine needs to start a container. On the test machine, a create took a median of 139 ms without a pool and 1.5 ms from a pool.
  • Cost. A waiting sandbox uses memory. On the test machine under gVisor, eight waiting ubuntu:24.04 sandboxes took approximately 11 MiB each by the count of Docker.
  • Cost. A request with a GPU, with environment variables or with volumes of its own never gets a waiting sandbox. The image name must be the same text as in the pool.
  • Cost. A waiting sandbox comes from the image as it was at its start. It also carries the Setup mark from setupOf. After a restart with a different build or different options, drainPools replaces all waiting sandboxes.
  • Cost. fromPool asks the engine with Engine.Inspect before each hand-out, because a waiting sandbox can die.

Source: internal/sandbox/pool.go.

  • Choice. The first command of a sandbox starts the helper in serve mode. The daemon keeps that connection and sends each next command as one frame.
  • Reason. Most of the time of a command was the exec of the engine. On the test machine, the next commands took a median of 4 ms, and 13 ms on a connection of their own.
  • Cost. While the connection is open, the helper holds approximately 15 MB of the memory of the sandbox on the test machine. Thus the daemon closes the connection after ConnectionIdle.
  • Cost. One connection carries many commands. A helper that stops can block all of them. The timers keptStall and keptHello and the retire behavior exist for this.
  • Cost. The user and the groups of each command come from the helper when the connection opens. A change to /etc/group after that is not seen until a new connection opens.
  • Cost. The maximum input of a command is keptStdin, because the helper holds it in memory and must not wait.
  • Cost. Only commands that the daemon answers in one piece use the kept connection. Streamed commands and file operations do not.

Source: internal/sandbox/kept.go, runServe in internal/guest/run.go.

Internals, one page for each part:

Reference:

Work on the code:

These statements tell you what nobody ran.

  • NVIDIA hardware. Nobody ran the daemon on a machine with an NVIDIA GPU. The GPU allocator, the two GPU drivers and checkGPUs ran only with stand-ins: the test engine and the GPUs that are not real in internal/apitest/apitest.go.
  • x86_64. Nobody ran the daemon or the amd64 helper on an x86_64 machine.
  • Cloud accounts. Nobody ran the installer, the first-start script or the metadata rules on a real AWS account or a real Google Cloud project.
  • Real engines. The runs on a real engine were on Docker with gVisor on arm64, in a nested virtual machine, and on Podman.
  • Unit tests. The unit tests use the test engine. The test engine does not isolate anything: a command runs as a process of the test.
  • Measurements. All times and sizes on this page are from one test machine. They are not a promise for a different machine.

ROADMAP.md lists more items that are not proven.