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.
What boxfork is
Section titled “What boxfork is”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
boxforkcontains the daemon, the CLI and the MCP server. It also contains the helper foramd64and forarm64(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
runscruntime works. If not, the sandboxes are plain containers and the daemon says so in each sandbox record.
Map of the system
Section titled “Map of the system”The processes
Section titled “The processes”| 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. |
The clients
Section titled “The clients”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
What talks to what
Section titled “What talks to what”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 |
Map of the repository
Section titled “Map of the repository”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 |
Life of a request
Section titled “Life of a request”Steps that all requests have
Section titled “Steps that all requests have”All routes are in Server.Handler in internal/api/server.go.
Server.authreads the API key from the request. It compares the SHA-256 of the two keys in constant time.- A wrong key gets status 401. Only
GET /v1/healthneeds no key. decodereads a JSON body of a maximum ofmaxJSONBody. It refuses a field that the API does not know.- The handler calls one function of the
Manager. - If the function returns an error,
Server.writeErrselects 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.
Create a sandbox without a pool
Section titled “Create a sandbox without a pool”Source: Manager.Create and Manager.boot in internal/sandbox/manager.go.
- The client sends
POST /v1/sandboxes.Server.createcallsManager.Create. Createdoes the checks on the request: timeout, names of environment variables, image name, mounts, idle time.Createmakes a record with a new ID fromnewID. The record is not inManager.boxesat this time.- With
Manager.mulocked,Createcompares the number of sandboxes withConfig.MaxSandboxes. fromPoolfinds no waiting sandbox for this request.Createadds 1 toManager.pending, counts the volumes withholdVolumesand releases the lock.bootgets the image withEngine.EnsureImage. The engine pulls the image if it is not local.bootmakes sure withengineMountsthat each volume exists. It gets the helper binary for the architecture of the image.- For a sandbox with networking,
bootcallsEngine.EnsureNetworkand thenConfig.NetworkReady. bootcallsEngine.Create. The entrypoint is/.boxfork/guest init. The labels carry the ID of the sandbox.bootcopies the helper into the container withEngine.CopyIn. Then it callsEngine.Start.- If the daemon uses a runtime such as
runsc,bootgets the runtime of the container fromEngine.Inspect. A different runtime is an error. Manager.proberunsguest versionin the container. An answer shows that the helper works.setDNSrunsguest dnsif the sandbox has networking and the isolation is gVisor or--dnsis set.giveVolumesrunsguest ownfor the volumes that are not read-only.CreatesetsCreatedAtandExpiresAt. It puts the record inManager.boxesand writes the state file.Server.createcallsServer.unheard. If the client is gone, the daemon kills the new sandbox.- 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 networkboxforkfor 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_DEVICESisvoidfor a sandbox without a GPU. - The memory limit and the swap limit are the same value. The size of
/dev/shmis half of the memory. - The container has the security option
no-new-privileges. It does not have the capabilitiesNET_RAW,MKNODandAUDIT_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 JSONCreate a sandbox with a pool
Section titled “Create a sandbox with a pool”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.
takereturns nothing if the request has a GPU, environment variables or volumes of its own.poolLikelooks for a pool with the same image or snapshot, CPUs, memory and network value.waitinggives the waiting sandboxes of that pool, oldest first. A waiting sandbox must have theSetupmark of this daemon.fromPoolsetsclaimedon the record, adds 1 topendingand releasesManager.mu.fromPoolcallsEngine.Inspect. Then it locksManager.muagain.- If the container does not run,
fromPoolsetsdraining, callskickPoolsand tries the next waiting sandbox. - If the container runs,
handOutclearsPooland sets the metadata,CreatedAt,ExpiresAtand the idle time. handOutwrites the state file. If the write fails,handOutputs the old values back and the request fails.fromPoolcallskickPools. 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:
kickPoolsputs a signal in the channelManager.poolKick.WatchPoolswakes and callsFillPools.fillPasscallsdrainPools.drainPoolsremoves each waiting sandbox that no pool keeps.fillPasscounts the sandboxes that each pool needs. It selects a maximum ofpoolBatchjobs, one pool after the other.fillOnecallsManager.Createwith the internal fieldpoolset. A maximum ofpoolParallelcreates run at one time.- This
Createis the create without a pool, but the record gets thePoolmark and no timeout. - If the create fails,
fillOnewrites the error inLastErrorand setsretryAttopoolRetrylater.
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.
Create a sandbox with a GPU
Section titled “Create a sandbox with a GPU”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:
Createrefuses the request withgpu_unavailableif the daemon has no GPU allocator.- If the request gives no memory, the sandbox gets a minimum of 8192 MB.
- In
boot,Allocator.Allocatereads the load of the GPUs withnvidia-smi. Then it locks and selects the GPUs. Allocatedoes not select a GPU that a sandbox holds, thatnvidia-smidoes not list or that another program uses.Allocateselects a GPU with thesuspectmark only when no other GPU is free.- With the
nvidiadriver,bootgives the UUIDs to the engine and setsNVIDIA_VISIBLE_DEVICESto the UUIDs. - With the
cdidriver,bootgives the device namesnvidia.com/gpu=<index>to the engine. bootwrites the UUIDs in the labelboxfork.gpusof the container.- After the helper answers,
checkGPUsrunsguest gpus. The helper runsnvidia-smiin the sandbox. - If the sandbox sees exactly its GPUs, the sandbox gets
gpu_verifiedandAllocator.Trustclears thesuspectmark. - If the answer is wrong,
Allocator.Distrustsets thesuspectmark,discardremoves the container and the create fails. - If the sandbox has no
nvidia-smi, the helper counts the device files/dev/nvidia<number>. A wrong count fails the create. - 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.
Run a command: the first command
Section titled “Run a command: the first command”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.
Server.execcallsManager.Runwith the limitServer.MaxOutputfor each output.RuncallsrunKept.runKeptdoes not use the kept connection ifConfig.ConnectionIdleis negative.runKeptalso does not use the kept connection if the input for the command is larger thankeptStdin.runKeptcallsManager.use.keptFortakes the place inrecord.connGate. The record has no connection, thuskeptForcallsopenKept.openKeptcallsEngine.Execwith/.boxfork/guest serve. The engine starts the helper in the container.- The helper sends a
FrameHelloframe.openKeptwaits a maximum ofkeptHellofor it. openKeptmakes acmdConnand starts the goroutinecmdConn.read.keptForputs the connection inrecord.conn.cmdConn.rungives the command a number and sends oneFrameSpecframe with theRunSpecas JSON.- In the helper,
runServereads the frame.startstarts the command in a new session. - The helper sends
FrameStarted, thenFrameStdoutandFrameStderrframes, thenFrameExit. Each frame carries the number of the command. cmdConn.readadds the output to thekeptRunof that number, up to the limit. AtFrameExitit closes the channeldone.cmdConn.runreturns theResult.runKeptcalls thedonefunction ofuse.- The daemon sends status 200 and the result as JSON.
Run a command: the next commands
Section titled “Run a command: the next commands”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 commandThe kept connection ends in these cases:
SweepcallscloseIdleConnseach second.cmdConn.closeIfIdlecloses a connection that ran no command forConfig.ConnectionIdle.forgetcallsdropConnwhen the sandbox goes.keptForcloses a connection that belongs to an old container, after a suspend and a wake.- The helper does not take a frame in
keptStall.cmdConn.sendends the connection. - The helper sends a frame that is not correct.
cmdConn.readends 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:
keptForreturns no connection. One cause is a helper from an older build that has noservemode.keptForthen setsrecord.noConnIn.- The last open of a connection failed less than
keptRetryago, 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.
Run a streamed command
Section titled “Run a streamed command”Source: Manager.Exec in internal/sandbox/run.go, runCmd in internal/guest/run.go, Server.exec in internal/api/server.go.
- The client sends the exec request with
"stream": true.Server.execcallsManager.Exec. Execcallsuse. Then it callsEngine.Execwith/.boxfork/guest run.releasedconnects the close of the stream to thedonefunction ofuse.Execsends oneFrameSpecframe. In the helper,runCmdcallsstart.Server.execsends status 200 with the content typeapplication/x-ndjson.Server.execreads each event withProcess.Nextand writes it as one line of JSON. It flushes each line.- The events are
started,stdout,stderrandexit. The output data is base64 text in the JSON. - If the stream breaks after the status line, the daemon sends an event of type
error. - If the client goes away,
context.AfterFunccloses the stream. The helper then kills the process group withSIGKILL.
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.
Read a file
Section titled “Read a file”Source: internal/sandbox/files.go, internal/guest/fs.go.
- The client sends
GET /v1/sandboxes/{id}/files?path=<path>.Server.readFilecallsManager.ReadFile. fsOpcallsuse. Then it callsEngine.Execwithguest fs <spec>.- The spec is one argument: the
FSSpecas JSON in base64 (guest.EncodeFSSpec). - In the helper,
fsReadmakes sure that the path is a regular file. - The helper writes one header line, an
FSHeaderas JSON with the size and the mode. Then it writes exactly that number of bytes. - In the daemon,
answerreads the header line. It reads a maximum ofmaxAnswerbytes for this line. - An error header becomes an
FSError.Server.writeErrchanges its code to an HTTP status with the tablefsStatus. Server.readFilesetsContent-LengthandX-Boxfork-Mode. It copies the bytes to the client.FileReader.Closecloses the stream, and that calls thedonefunction ofuse.
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.
Write a file
Section titled “Write a file”- The client sends
PUT /v1/sandboxes/{id}/files?path=<path>with the bytes as the body. The parametermodeis optional. Server.writeFileputs the limitServer.MaxUploadon the body and callsManager.WriteFile.fsOpstartsguest fswith the operationwrite.WriteFilereads the body in pieces of 256 KiB. It sends each piece as aFrameStdinframe.- At the end of the body,
WriteFilesendsFrameStdinEOF. - In the helper,
fsWritewrites the pieces to a temporary file.boxfork-write-*in the directory of the target. - After
FrameStdinEOF, the helper sets the mode and renames the temporary file to the target. - 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.
Snapshot
Section titled “Snapshot”Source: Manager.snapshot in internal/sandbox/snapshot.go.
- The client sends
POST /v1/sandboxes/{id}/snapshot.Server.snapshotcallsManager.Snapshot. - With
Manager.mulocked,snapshotrefuses ifManager.noSnapshotsis set or if the limitConfig.MaxSnapshotsis full. snapshotmakes an ID with the prefixsnap_. It puts the ID inManager.trashwith the zero time and inManager.committing.snapshotwrites the state file. This write is before the engine call.snapshotlocksrecord.opMu.wakeLockedwakes the sandbox if it is suspended.Engine.Commitsaves the files of the container as the imageboxfork-snapshot:<ID>. The engine pauses the container during the commit.snapshotunlocksrecord.opMu.- On success,
snapshotremoves the ID fromtrash, adds the record toManager.snapsand writes the state file. - On failure,
snapshotsets the time of thetrashentry to the current time.emptyTrashthen 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.
- The client sends
POST /v1/sandboxes/{id}/forkwith a count.Server.forkcallsManager.Fork. Forkrefuses a count that is not from 1 toMaxFork.Forkbuilds oneCreateRequestfrom the record: CPUs, memory, network, metadata and the same volumes.- If the request does not give a GPU count, each copy gets the same number of GPUs as the original.
Forkcallssnapshotwithtemporaryset. The new snapshot record starts with one user inrefs: the fork.Forkputs the snapshot ID inManager.forks.ForkcallsManager.Createfor each copy, with a maximum offorkParallelat one time.- Each copy gets the
Forkmark in its record.GetandListdo not show a record with this mark. - After all creates,
Forkremoves the ID fromManager.forks. - If all creates were good,
Forkclears theForkmark of all copies and writes the state file one time. - If one create or the write fails,
Forkkills all copies and returns the error. unrefSnapshotremoves 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.
Pause and resume
Section titled “Pause and resume”Source: Manager.setPaused in internal/sandbox/manager.go.
- The client sends
POST /v1/sandboxes/{id}/pauseor.../resume. The handler callsManager.PauseorManager.Resume. setPausedmakes a context that is not the context of the request, with a timeout of one minute.setPausedlocksrecord.opMu.wakeLockedwakes the sandbox if it is suspended.- If the record already has the state that the client wants,
setPausedreturns the sandbox. setPausedcallsEngine.PauseorEngine.UnpausewithoutManager.mu.- If the engine returns an error,
setPausedcallsEngine.Inspect. If the container has the wanted state, the operation is good. markPausedsets the statepaused, moves the time that is left toRemainingNSand clearsExpiresAt.markResumedsets the staterunningand makes a newExpiresAtfromRemainingNS.setPausedwrites 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.
Idle suspend and wake
Section titled “Idle suspend and wake”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 (
UnsavedPathsis empty) inUseis zero- the time after
lastUsedis not less than the idle time
The suspend:
- The loop in
Manager.WatchcallsReclaimeach 2 seconds.Reclaimcollects the idle sandboxes and callssuspendfor each. suspendtries to lockrecord.opMuwithTryLock. If it cannot, it stops for this pass.suspendstops if the image of the container hasMaxLayerslayers or more.suspendrunsguest procs. The helper counts the processes, but not process 1, itself and a helper inservemode.- If the count is not zero,
suspendsetslastUsedto the current time and stops. suspendsets the statesuspended. A new command now waits inwakeforrecord.opMu.suspendcallssnapshotwithtemporaryandheldset. The engine commits the files.suspendsetsDiskto the snapshot ID, clearsContainerIDand writes the state file.suspendcallsEngine.Removefor the container.suspendcallsAllocator.Release, clears the GPUs of the record and writes the state file again.suspendremoves one user from the snapshot that was theDiskbefore.
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:
- A command, a file operation, a snapshot, a fork, a pause or a resume arrives for the suspended sandbox.
usecallswake.wakelocksrecord.opMu, and thus waits for a suspend that is in progress.wakeLockedreturns an error if an old container of the sandbox is inManager.orphans.wakeLockedcallsbootwith the image of theDisksnapshot and with the GPU request inrecord.Want.bootdoes the same steps as for a create. It usesEngine.LocalImage, thus the engine pulls nothing.wakeLockedsets the staterunning, the newContainerIDand the new GPUs. It writes the state file.- If the write fails,
wakeLockedputs the record back tosuspendedand callsdiscardfor the new container. usegoes 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: resultSource: Manager.Kill, remove, forget in internal/sandbox/manager.go.
- The client sends
DELETE /v1/sandboxes/{id}.Server.killmakes a context that is not the context of the request. Manager.KillreturnsErrNotFoundfor a waiting sandbox or a fork copy. A client cannot see these.removesetsrecord.dyingwithManager.mulocked. For a suspended sandbox, it first locksrecord.opMu.removecallsEngine.Remove. The engine kills the container and deletes it.- If the engine returns an error,
removeclearsdyingand returns the error. The sandbox stays. forgetdeletes the record fromManager.boxes, callsdropConnand writes the state file.forgetcallsAllocator.Release, unless a container of the sandbox is inManager.orphans.forgetcallsunrefSnapshotfor theSnapshotand theDiskof the record.- 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.
Timeout
Section titled “Timeout”Source: Manager.Sweep and remove in internal/sandbox/manager.go.
CreateorhandOutsetsExpiresAtfrom the timeout of the request or fromConfig.DefaultTimeout.- The client can set a new timeout with
POST /v1/sandboxes/{id}/timeout(Manager.SetTimeout). Zero means no timeout. - The loop in
Manager.WatchcallsSweepeach second. Sweepcollects the IDs with anExpiresAtthat is not in the future.SweepcallsremovewithonlyExpiredset for each ID, in the sequence of the IDs.removereadsExpiresAtagain withManager.mulocked. A timeout that the client extended a moment before stays valid.- 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.
A container that stops by itself
Section titled “A container that stops by itself”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.
States of a sandbox
Section titled “States of a sandbox”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 isrunning.Fork: the sandbox is a copy of a fork that is not complete. Its state isrunning.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, timeoutIn 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 |
Data that the daemon keeps
Section titled “Data that the daemon keeps”The records
Section titled “The records”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.
The state file
Section titled “The state file”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/boxforkfor the user root.boxforkin 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. |
Data that is only in memory
Section titled “Data that is only in memory”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. |
What the engine holds
Section titled “What the engine holds”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.
What the daemon does at its start
Section titled “What the daemon does at its start”Source: serve in cmd/boxfork/main.go, New in internal/sandbox/manager.go.
servereads the flags and the TLS files.engine.NewDockermakes the engine client, andEngine.Infomakes sure that the engine answers.sandbox.Detectselects the isolation. If the engine listsrunsc,tryRuntimestarts one trial container with it.gpu.NewAllocatorreads the GPUs one time withnvidia-smi. With zero GPUs, the daemon has no GPU allocator.loadKeyreads the API key from the fileapi-key, or makes a new key.sandbox.Newstarts.ensureDefaultVolumesmakes each default volume that does not exist.loadStatereads the state file. A file that is not correct JSON stops the start.Newcopies thediscardedIDs toManager.trash. An ID with the zero time gets the current time.Newkeeps each snapshot record, unlessEngine.LocalImagesays that its image is gone.Newkeeps each pool record, unless its snapshot is gone.Newgets the containers with the labelboxfork.managed=truefromEngine.List.Newkeeps a suspended record with no container only if itsDisksnapshot exists. It clears the GPUs of the record.- A record with the state
suspendedand a container becomesrunning. Newdrops a record if its container is gone or does not run.- For a record with GPUs,
Allocator.Restoregives the GPUs to the sandbox again. Newdrops a GPU record if the machine has no GPUs now. It also drops the record if another sandbox holds one of its GPUs.- If the record and the container disagree about pause,
markPausedormarkResumedcorrects the record. Newadds each kept sandbox as a user of itsSnapshotand itsDisksnapshot.Newremoves each boxfork container that no kept record owns.- If a removal fails, the container goes to
Manager.orphans.Restoreholds the GPUs from its labelboxfork.gpus. Newwrites the state file. ThensweepSnapshotsdeletes the temporary snapshots with no user and the images intrash.Manager.CheckNetworkmakes the networkboxforkand reads if the engine blocks traffic between sandboxes.metadataGuard.startsets the firewall rules.Manager.CheckSnapshotsdoes a snapshot of a trial container.servestartsManager.Watchand 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.
Concurrency model
Section titled “Concurrency model”The locks
Section titled “The locks”| 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 order of the locks
Section titled “The order of the locks”The code takes the locks in this order:
record.opMu,record.connGateorManager.volMuManager.mucmdConn.mu
These rules follow from the code:
- A function never waits for
record.opMu,record.connGateorManager.volMuwhile it holdsManager.mu. It first releasesManager.mu. - A function does not hold two of the locks of step 1 at the same time.
- A method of
cmdConnnever takesManager.mu. - The daemon does not hold
Manager.muwhen it calls the GPU allocator. - A background loop uses
TryLockonrecord.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.
What the daemon does outside the lock
Section titled “What the daemon does outside the lock”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:
- Lock
Manager.mu. Read the record and do the checks. - Set a mark or a count that tells the other operations about this one. Unlock.
- Call the engine.
- Lock
Manager.muagain. Make sure thatManager.boxes[id]is the same record and that it is notdying. - Write the result in the record, call
saveand 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
The background loops
Section titled “The background loops”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.
Limits and defences
Section titled “Limits and defences”Limits in the manager
Section titled “Limits in the manager”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 |
Defences
Section titled “Defences”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 inaskAs). - Each frame has a maximum size (
MaxFrame).ReadFrameandReadMuxrefuse a larger frame. cmdConn.readdrops a frame for a command number that does not exist. A frame that is not correct ends the connection.cappedkeeps only the first bytes of an output, up to the limit.- Timers (
keptHello,keptStall, the waits inaskAs) stop a wait for a helper that does not answer.
The other defences:
- Runtime.
bootreads the runtime of each new container from the engine.bootremoves a container that has a different runtime (manager.go). - GPUs. The daemon always sets
NVIDIA_VISIBLE_DEVICES. A client cannot set this variable.checkGPUsasks the sandbox which GPUs it sees. - Images.
imageReflimits the characters of an image name, because the name goes into a URL of the engine API.Createrefuses 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.
checkMountsrefuses/,/.boxfork,/proc,/sysand/dev. - Container.
Docker.Createsetsno-new-privileges, removes three capabilities and sets the limits for memory, swap and processes. - Network. The network
boxforkhas traffic between containers off.Docker.EnsureNetworkreads the option back from the engine, andboxfork infoshows the result. - Metadata service.
hostfw.Blockputs rules in theDOCKER-USERchain. The rules reject traffic from the sandbox network to the metadata addresses, but port 53 stays open (hostfw.go). - API key.
Server.authcompares in constant time.loadKeyrefuses a key file that other users can read. The Go client follows no redirect, thus the key goes to no other address. - Requests.
decoderefuses unknown fields and large bodies. - Clients that go away.
Server.unheardkills a sandbox when its client is gone before the answer. - State file.
savewrites a temporary file, callsSyncand renames. - Plain HTTP.
servewrites a warning when the API listens on an address that is not loopback without TLS.
Design decisions
Section titled “Design decisions”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/guestin each container. Each exchange is anEngine.Execof 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
/.boxforkis in each sandbox and in each snapshot.
Source: internal/guest/proto.go, boot in internal/sandbox/manager.go.
One JSON state file
Section titled “One JSON state file”- 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,Newcompares 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.
savewrites the full file and callsSyncwhile its caller holdsManager.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.
One full GPU for one sandbox
Section titled “One full GPU for one sandbox”- Choice.
Allocator.Allocategives 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_unavailablewhen 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 nameboxfork-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.gosays that the engine refuses at approximately 125 layers. The daemon stops to suspend a sandbox atMaxLayers. - Cost. A runtime can keep the file changes away from the commit.
CheckSnapshotsfinds this at the start, and the daemon then refuses snapshot, fork and suspend withunsupported. - 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,Detectusesrunscif 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
tryRuntimeandbootread the runtime back fromEngine.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
isolationwithgvisororcontainer.GET /v1/infohas 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, thussetDNSwrites 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.
One API key
Section titled “One API key”- Choice. The daemon has one API key in the file
api-key.Server.authasks for it on each route butGET /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.
Createhands 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.04sandboxes 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
Setupmark fromsetupOf. After a restart with a different build or different options,drainPoolsreplaces all waiting sandboxes. - Cost.
fromPoolasks the engine withEngine.Inspectbefore each hand-out, because a waiting sandbox can die.
Source: internal/sandbox/pool.go.
A kept connection for commands
Section titled “A kept connection for commands”- Choice. The first command of a sandbox starts the helper in
servemode. 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
keptStallandkeptHelloand 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/groupafter 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.
Where to go next
Section titled “Where to go next”Internals, one page for each part:
- internals/manager.md: the
Manager, the records and the life of a sandbox - internals/commands-and-files.md: commands and file operations
- internals/kept-connection.md: the kept connection
- internals/snapshots-and-forks.md: snapshots and forks
- internals/pools.md: pools
- internals/suspend.md: suspend and wake
- internals/volumes.md: volumes and the model cache
- internals/helper.md: the helper and its protocol
- internals/engine.md: the
Engineinterface and the Docker client - internals/network.md: the network, the name servers and the metadata service
- internals/gpu.md: the GPU allocator and the GPU check
Reference:
- reference/http-api.md: the HTTP API
- reference/cli.md: the CLI
- reference/configuration.md: the flags of
boxfork serveand the environment variables - reference/python-sdk.md: the Python SDK
- reference/mcp-and-tools.md: the MCP server and the tools
Work on the code:
- development.md: how to build and change the code
- testing.md: the tests, the test engine and the proof scripts
- security.md: what a sandbox can and cannot get to
- decisions.md: all design decisions
- performance.md: the measurements
Not proven
Section titled “Not proven”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
checkGPUsran 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
amd64helper 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.