> ## Documentation Index
> Fetch the complete documentation index at: https://axe-engine.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Design decisions

> How AXE works, the decisions behind it, and what it leaves out on purpose.

This document explains why AXE is built the way it is: the problem it solves, what it leaves out, the decisions that shape the code, and the alternatives that lost.

## What problem AXE solves

Every sandbox platform needs something inside the sandbox that runs commands, streams their output and moves files for the agent or orchestrator outside. Each platform writes its own:

* E2B's `envd` (Go, Connect-RPC over TCP); CubeSandbox reimplements its protocol in Rust.
* The Kata agent (Rust, ttrpc over vsock).
* microsandbox's `agentd` (Rust, CBOR frames over virtio-serial).
* Alibaba OpenSandbox's `execd` (Go, REST, SSE and WebSocket).
* Kubernetes Agent Sandbox's `sandboxd` (Go, gRPC plus REST), specified by KEP-539.2.
* Agent Substrate's `ate-env-guest` (Go, gRPC over h2c).

They share the same core: spawn with argv, env, cwd and an optional PTY; stdout and stderr ending in an exit; stdin, resize and signals; list and reattach; timeouts; basic file operations; health; reaping; limits. AXE implements that core once, as a library and a daemon a provider can adopt, and holds it to these requirements:

* **A process's lifetime does not depend on its client.** Clients disconnect on every snapshot, so a process keeps running and its output stays replayable, with lossless backpressure for readers that ask for it.
* **Snapshots are a normal event.** Platforms snapshot whole sandboxes (gVisor `runsc checkpoint`, Firecracker and Cloud Hypervisor snapshots), every client connection drops, and clocks jump in platform-specific ways. Timers must not fire early or late because of it.
* **Path confinement holds against concurrent changes.** Sandboxed code can swap a directory for a symlink at any moment, so no path is checked and then reopened by name.
* **Every buffer is bounded, and identities never collide.** Output, captures and tables have limits, and process ids are never reused.

## Scope

AXE is the execution layer, not the sandbox platform. It does not provision, isolate, schedule, orchestrate, snapshot, or route traffic to sandboxes; whatever runs it keeps those jobs. The engine assumes no deployment topology. It can be linked into a host agent, run as a sandbox guest's PID 1, or sit in a sidecar. axed is one way to deploy it, not the boundary of the design.

AXE has four parts, in dependency order:

* `axe`, the engine. It supervises processes, keeps their output, tracks lifecycle across suspends, confines filesystem access, watches directories and applies limits. It has no network or protocol code and can be embedded directly.
* `axe.v1`, the native API (`proto/axe/v1`), served by `axed/src/native`. It is self-contained and imports no other project's types.
* Adapters (`axed/src/adapters`), thin translations of other projects' protocols onto the engine. Kubernetes Agent Sandbox and Agent Substrate have one each. An adapter maps wire formats and error codes; semantics live in the engine.
* `axed` and `axectl`, the daemon and CLI.

AXE deliberately does not build these. They belong to the provider, a higher layer, or an ordinary process:

* Code interpreters and Jupyter contexts. A kernel is a process.
* Persistent shell sessions with command injection. Detached processes with PTYs replace them without shell-parsing hazards.
* git, LSP, computer use, content search and replace. These are processes too.
* Port scanning, proxies, tunnels and localhost rebinding. Ingress is the platform's job.
* Guest plumbing: network setup, hotplug, mounts, CA bundles, filesystem freeze, memory compaction.
* Polling watcher APIs. A stream with overflow-and-rescan is cheaper.
* Unbounded on-disk output spools.
* Survival across an axed restart, and live binary upgrade. In the common deployment axed is the sandbox's PID 1, and when PID 1 exits the kernel kills the whole PID namespace, so per-process shims would cost memory for a case that cannot occur there. Durability here means surviving client disconnects and sandbox snapshots, the failures that happen in practice.
* TLS. axed expects pod isolation, NetworkPolicy, a mesh, vsock or a Unix socket in front of it, and offers bearer-token auth per listener.

## Decisions

### The engine is the product; protocols are adapters

The engine defines the semantics, `axe.v1` is self-contained, and sandboxd's protocol is an adapter that can be switched off (`--agent-sandbox=false`). A native API built on sandboxd's message types would have made Kubernetes Agent Sandbox an architectural dependency. Its semantics, such as a `Start` stream owning its process, are adapter behavior. Native `Run` offers the same lifetime explicitly (`detach: false`), and native `Start` is detached.

Two adapters exist: Kubernetes Agent Sandbox (sandboxd) and Agent Substrate's guest API (`ateenv.v1alpha`). The second needed nothing from the engine but per-stream offsets on output chunks, which confirms the engine is protocol-neutral rather than shaped around sandboxd.

### One output log per process, addressed by byte offset

Each process has one log holding stdout and stderr interleaved in write order. Every byte has an absolute offset. A client that reconnects passes the offset after the last byte it saw and gets exactly the rest, or a gap event naming the range that was evicted. The log keeps the newest `--retain` bytes (default 1 MiB). Memory grows only with actual output, and pumps read into a per-thread scratch buffer, so an idle process holds no output buffer at all. Retention bounds memory, not just payload: small writes to one stream join the newest chunk, and a log keeps at most one chunk per 128 bytes of retention, so a process that writes a byte at a time, even alternating stdout and stderr, cannot make its log cost much more than its retention.

A reader is either lossless or lossy. A lossless reader pins the bytes it has not read. When the log is full, the writer waits, the pipe fills, and the process blocks on `write`. That is the backpressure a terminal gives, and attached runs use it so they never drop output. A lossy reader never slows the process and gets gap events instead. With no lossless readers attached, a detached process never blocks on output.

Every process reserves its retention from a global budget (`--output-budget`) and a slot from a process cap until it is forgotten. A new process evicts the oldest finished records to fit and is refused when running processes fill the budget, so output memory is bounded however many processes clients start.

The alternative was a bounded channel per subscriber. It would duplicate every byte per reader and cannot replay history to a late reader.

### Identities never collide, and retries are safe

A process id is 128 random bits, never reused. The Agent Sandbox adapter addresses processes by small integers instead, because its protocol does. An optional name is unique among running processes and, after a process exits, still refers to the most recent one with that name. An optional request id makes `Start` idempotent. Repeating it returns the first process. Stdin writes can name the offset they start at, so a retried write is acknowledged rather than repeated. These matter because the transport resets on every VM snapshot, and a retried call must not start a second process or repeat input.

Ids belong to one daemon instance. `instance_id` (also random) names the in-memory process table. It survives memory snapshots, because the processes do, and changes on a cold boot, including a platform's fallback from a memory snapshot to a disk-only restore. A client can always tell a process from before a cold boot from a new one.

### Suspend and restore are detected, not announced

Platforms snapshot sandboxes without calling into the guest (Agent Substrate does exactly this), so AXE cannot rely on hooks. `axe::lifecycle` samples three clocks every second. gVisor hides suspended time from `CLOCK_MONOTONIC` but not from `CLOCK_BOOTTIME`. A VMM that catches the guest up advances both, so the sampler appears to have overslept. An old VMM leaves the clock frozen until NTP steps it. Each pattern beyond a threshold counts as a resume, increments `generation`, and records the gap.

Timeouts measure running time: monotonic time minus detected freezes. A timer that fires rechecks the clocks before killing, so a timer woken by a VM resume does not kill on the spot. A sandbox suspended for an hour does not kill its jobs on wake, and timeouts mean the same thing on every platform. Detection is backed by explicit hooks for platforms that have them: `System.Configure` takes wall time and entropy after a restore and can record a resume, and `System.Freeze` freezes every process tree through its cgroup as a quiesce point. The cost of a false positive, a scheduler stall longer than 5 seconds, is one extra generation and a timeout extended by the stall.

### One thread owns `wait`

AXE reaps every child with `wait4(-1)` from a dedicated thread. As PID 1 it must collect orphans; otherwise it registers as a child subreaper so orphaned grandchildren come back to it. Mixing a global reaper with per-child waiting races, so nothing else waits. A spawn holds the reaper's lock only to register its child, not while starting it. A child reaped before it is registered, because it exited at once, leaves its exit behind for the registration, for as long as a spawn that started earlier is still pending; after that it counts as an orphan. The child's pidfd comes from `clone` itself, so it can never name a process that reused the pid; on kernels that hand out no pidfd with the child, the spawn holds the lock throughout and opens the pidfd before the pid can be freed. Signals and kills that must use a raw pid or process group id take the same lock and check that the leader is not yet reaped, so they cannot reach a process that reused the pid. The thread blocks in `waitid(WNOWAIT)` instead of handling `SIGCHLD`, so the reaper works under any async runtime, and each child's `rusage` comes for free from `wait4`. With no children it looks again every second: as PID 1 it inherits processes it never spawned, such as orphans of a `docker exec`, and nothing announces those.

AXE starts processes with its own `clone`, the way `posix_spawn` does: the child shares the daemon's memory and the daemon waits until it has called `execve`, so no address space is duplicated. Between the two the child only makes raw system calls on values prepared beforehand: install stdio, set the user, directory, session or process group and rlimits, and try each `PATH` entry as `execvp` would. On Linux 5.7 and later, `clone3` starts the child directly in its cgroup (`CLONE_INTO_CGROUP`) and hands back its pidfd. Where `clone3` is refused, by an older kernel, a seccomp profile that blocks it, or gVisor, plain `clone` is used and the child writes itself into `cgroup.procs`. axed raises its own soft descriptor limit at startup, and children get the original back through that rlimit, as Go's `os/exec` does.

### Paths resolve one component at a time

`axe::fs::Root` walks each request path with `openat(O_PATH | O_NOFOLLOW)` against directory descriptors it already holds and expands symlinks itself. Absolute symlinks that point inside the root are followed, so trees made by ordinary tools work. Resolution can never leave the root, and nothing is reopened by name after the check, so a symlink swap cannot redirect an operation. `openat2(RESOLVE_BENEATH)` was the other candidate. It needs Linux 5.6 and rejects every absolute symlink, which would break `/workspace/a -> /workspace/b` links that sandboxd accepts.

Uploads go to an `O_TMPFILE` in the target directory and are linked into place on commit. A reader never sees a half-written file, and a create-only write is a single `linkat` that fails with `EEXIST` if someone else won. The native `Files.Write` stream commits only on an explicit final message. A client that vanishes mid-upload can look like a clean end of stream to the server, and proxies can do the same, so a clean close alone must not commit.

### Transports are listeners, not code paths

Containers and gVisor reach their guest daemon over TCP. Kata and Firecracker guests without networking use vsock. A provider's supervisor or a bind-mounted host socket uses a Unix socket. Socket activation and pre-bound sockets arrive as inherited descriptors. axed serves the same gRPC services on any number of `--listen` endpoints at once and binds them all before serving any. Each endpoint has its own auth policy: TCP always requires the token when one is configured, while vsock, Unix sockets and inherited descriptors may opt out, because there the channel is the trust boundary.

### Cgroups when delegated, process groups otherwise

With a writable cgroup v2 subtree, axed moves itself into an `axed` leaf, enables the `cpu`, `memory` and `pids` controllers, and gives every process its own cgroup. That gives a kill that reaches every descendant (`cgroup.kill`), memory, CPU and task limits for the whole tree, OOM detection, freezing, and accounting that includes reparented grandchildren. Kernels before 5.14 have no `cgroup.kill`. There the kill freezes the cgroup so nothing forks behind it, kills each task listed in `cgroup.procs`, and thaws it. Memory limits also set `memory.swap.max=0`; without it the kernel swaps past `memory.max` instead of enforcing it. Without delegation, AXE kills the process group plus every descendant it can find through `/proc`, and maps limits to rlimits. CPU limits and freezing need cgroups and are refused otherwise. axed refuses to take over a cgroup shared with other processes unless it is PID 1.

### Untrusted code cannot take the daemon down

axed often runs as PID 1 next to code it must assume is hostile, and its release build aborts on panic, so a crash ends the sandbox. Everything sandboxed code controls is treated as input:

* **No reachable panics.** File times before 1970 or after 9999 are reported, not unwrapped. Directory walks (list, copy, recursive remove, recursive watches, process descendants) use explicit stacks, so a tree thousands of levels deep cannot overflow the stack, and path resolution refuses paths more than 256 directories deep, because it holds a descriptor per level.
* **No blocking on swapped files.** Copies open sources non-blocking and recheck the type after opening, so a file swapped for a FIFO is refused, not read forever. Watches are added through the descriptor resolution produced, never by reopening a path.
* **Nothing leaks into children.** At startup axed marks every inherited descriptor close-on-exec, so a supervised process cannot accept on an `fd://` listener or read anything else axed was handed.
* **Clients cannot exhaust descriptors.** Half the descriptor limit is set aside for client connections and split evenly among the listeners and the REST port, so clients of one listener cannot lock out another; excess connections wait in the kernel backlog. A gRPC connection must deliver the HTTP/2 preface and its first frame within 10 seconds, counted in bytes so trickling does not help, and HTTP/2 keepalive covers it after that. REST runs on hyper's header-read timeout, set by `--http-idle-timeout`, which starts each time a connection waits for a request. The timeout closes idle keep-alive connections and trickled headers but never a request being processed. Writes stuck that long and uploads stalled that long also close the connection. Concurrent watches share one limit across protocols.
* **Buffered output is bounded twice.** Retained output draws from `--output-budget`; unary `Exec`, `Execute` and `ExecuteWithLimits` responses, which must be buffered whole, draw from a second budget, `--capture-budget`. When output does not fit, `Exec` and `ExecuteWithLimits` keep a prefix and report truncation instead of waiting, and the plain Agent Sandbox `Execute`, which has no truncation fields, fails with `RESOURCE_EXHAUSTED`.
* **Exits clean up everything.** When a process that is not kept exits, whatever it left running dies with its cgroup (or process group), and the cgroup is removed. The Agent Sandbox adapter is the exception, because sandboxd leaves background jobs running: there a cgroup stays until it empties, and shutdown kills what is left. Cgroup removal happens on the blocking pool after the registry lock is released, so cleanup never stalls spawning.

### Errors map once, at the edge

The engine returns typed errors (`NotFound`, `PermissionDenied`, `Conflict`, and others) and raw I/O errors with context. `axed` maps them to gRPC codes, and the Agent Sandbox adapter to sandboxd's REST `{"code", "message"}` bodies, mostly in one place, `errors.rs`, including errno mapping such as `ENOSPC` to 507.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.