Sandboxes from 0 to 1

In July 2026, OpenAI tested the cybersecurity capabilities of its models inside a restricted environment. The agents were supposed to solve assigned challenges. Instead, some worked around the network rules, passed data through a shared package service, and reached parts of OpenAI's research infrastructure and Hugging Face's systems.
Reading that report left me with one question: when you hand an AI model a terminal, what stops it from stepping outside its task?
To understand the mechanics firsthand, I built BranchVM. I wanted to run multiple coding agents against the same repository at once, each with its own PostgreSQL database and filesystem, on a single machine without storing a full copy of the OS for every agent.
I am only just getting into this space and BranchVM is my first attempt, so this post walks through sandboxes from zero to one. We will start with how programs talk to the Linux kernel, move through containers, Firecracker microVMs, and cgroup limits, and then look at how snapshots, Copy-on-Write, demand paging, and host network rules keep parallel VMs fast and isolated. If you want a quick cheat sheet at any point, there is a plain-English summary of every concept at the end.
1. Your program talks to the kernel
Think of an operating system like a bank. Your program is a customer in the lobby, and the Linux kernel is the teller behind the glass who holds the keys to the vault (disk, RAM, and network). When a Python script reads notes.txt, it cannot walk behind the counter and touch the disk directly. It slides a request slip through the slot, called a system call (syscall), asking the kernel to open the file and hand back the bytes. The kernel checks permissions and fetches the data from storage. It runs the same permission check when a program starts a child process or opens a network connection.
User-mode processes cross into the privileged kernel through system calls whenever they touch files or hardware.
The CPU enforces that separation in hardware. Ordinary applications run in restricted user mode, while the kernel runs in privileged kernel mode with direct hardware access. That hardware boundary covers memory too: the CPU and OS give every process its own private address map, called a virtual address space, and translate those addresses into physical RAM behind the scenes. Two programs can write to the exact same virtual address without ever seeing each other's memory.
An AI coding agent runs as an ordinary user-mode process. The model chooses the shell command, and the operating system decides what that command is allowed to touch.
2. What is a sandbox?
A sandbox narrows what a process can see and use: one project folder, no access to your home directory, strict network rules, and hard ceilings on CPU and RAM. Different tools draw that wall at different layers of the machine.
A Git worktree is like giving two coworkers separate desks in the same open office. Each agent gets its own checkout of the files, while both still share the host OS, ports, and services. Two agents can easily hit the same local PostgreSQL port and overwrite each other's data.
A container puts each process in a locked cubicle inside the same building. Linux namespaces act like frosted glass that hides the rest of the host: mount namespaces hide host folders, PID namespaces hide other running processes, and network namespaces give each container its own network interfaces and ports. Adding seccomp (which blocks dangerous system calls) and dropping Linux capabilities (which strip away parts of root access) tightens that boundary further. Even then, every container shares the same building manager, the host Linux kernel, so a bug in that shared kernel can let a process break out of its cubicle.
From shared-host worktrees to kernel-sharing containers to hardware-isolated VMs with separate guest kernels.
A virtual machine (VM) moves the workload into a separate house. Using virtualization features built into the CPU, a VM boots its own guest OS and guest Linux kernel, and sees only virtual disks and virtual network cards (virtual NICs). Projects like gVisor sit in between by intercepting and reimplementing most Linux system calls in userspace before they reach the host kernel. Containers start faster and use less memory; VMs give you a separate kernel at the cost of extra startup machinery.
3. Firecracker and KVM
Running a whole second operating system in pure software would be painfully slow. To avoid that, Linux includes KVM (Kernel-based Virtual Machine), a kernel subsystem that lets guest code run directly on the host processor's hardware virtualization extensions. KVM exposes itself as a device file at /dev/kvm, so a normal userspace program can simply open it to create and run virtual CPUs.
Firecracker is that userspace program: a minimal virtual machine monitor (VMM) built on KVM. Traditional desktop VMs spend time and code emulating legacy hardware like USB hubs, sound cards, and BIOS menus. Firecracker strips all of that out and exposes only a tiny set of standardized virtual devices (called virtio devices) for disk and networking. Less emulated hardware means faster boots and a much smaller attack surface.
In BranchVM, my Go controller drives Firecracker through its HTTP API over a local Unix domain socket (a private file-path pipe between two processes on the same machine). The controller hands Firecracker a Linux kernel image, a virtual disk, a memory size, and a virtual CPU count, then starts the guest.
Once that guest kernel boots, Linux needs a first process, known as PID 1, to set up the environment and start services. Instead of booting a full init system like systemd, BranchVM runs a small Go binary called execd as PID 1 to keep startup fast and minimal. execd mounts the guest filesystems, starts project services, and exposes one control API for running commands and syncing files. That single API lets the host talk to every VM over the same protocol, whether the target repo is in Go, Node.js, or Python.
4. Isolation also needs resource limits
Now we can boot a microVM with its own guest kernel, but hardware isolation alone does not stop noisy neighbors. Picture three VMs running on one laptop: one agent kicks off a heavy build, another leaks memory in a tight loop, and the third slows to a crawl. Separate kernels keep them from reading each other's RAM, just as separate houses keep neighbors out of your rooms. Still, if one house opens every faucet on the same water main, everyone on the street loses pressure.
Linux solves this with cgroups v2 (control groups), which act like kernel-enforced utility meters and circuit breakers. BranchVM places every Firecracker host process inside its own cgroup v2 directory with explicit ceilings on memory, CPU, and task count.
Each Firecracker host process sits in a cgroup v2 hierarchy capping host memory, CPU time, and task count.
Inside that directory, three control files enforce the caps:
Beyond acting as circuit breakers, cgroups also serve as the utility meters. Reading memory.current shows how much host RAM the kernel charges to a branch. One catch for later when we benchmark clone density: that figure includes cached files from disk, and any memory shared across VMs gets billed to whichever cgroup pulled it in first. A single branch's number reflects Linux's billing rules, not just its private memory.
5. Snapshotting a running VM
Cold-booting a microVM is slow. Just like powering on a shut-down laptop, Linux has to initialize virtual devices, mount disks, and wait for PostgreSQL to start. A single cold boot burns over six seconds, and spinning up ten parallel agents from scratch stalls every run.
Firecracker supports full VM snapshots, which work like hitting hibernate on a warmed-up laptop and waking ten clones from that exact frozen instant. BranchVM boots one golden microVM, uploads the workspace, runs an optional warm-up build, and starts its services. Then it pauses the virtual CPUs and writes the VM's state to disk.
A golden microVM boots once, pauses, and saves CPU/device state, memory, and disk so branches restore directly into a running environment.
A saved snapshot holds three pieces: the frozen CPU registers and virtual device state (vm.state), a byte-for-byte copy of guest RAM (vm.mem), and the virtual disk. BranchVM saves its config and a manifest of workspace file hashes alongside them so later runs only need to sync changed files. Each branch restores mid-execution from that saved state and runs independently from there.
Before freezing the golden VM, BranchVM runs a PostgreSQL checkpoint and flushes pending writes to disk. Without that flush, unwritten data can still sit in guest buffers instead of the backing disk image, leaving cloned branches with inconsistent database files. If you run another stateful service inside the VM, it needs a flush step before pause for the same reason.
Even with a clean snapshot, the first time I restored a branch I hit a timing bug: a guest answering its HTTP health check did not mean PostgreSQL was ready for queries yet: execd's /health endpoint simply returned a stale in-memory pg_ready flag saved before the VM paused instead of probing PostgreSQL again. Queries fired immediately after restore failed until I added an explicit pg_isready wait (readiness fix).
6. Copy-on-Write: why ten VMs don't need ten copies of RAM
Ten 1 GiB snapshots would normally eat 10 GiB of RAM the moment you restore them. Operating systems avoid that with Copy-on-Write (CoW). It works like ten students sharing one 1,000-page textbook: instead of printing 10,000 pages upfront, everyone reads the same copy, and you only photocopy a single page when someone writes a note in its margin.
In Linux, RAM is split into fixed-size chunks called pages. On my ARM64 benchmark machine, each page is 4 KiB, so a 1 GiB guest spans 262,144 pages. Across ten cloned VMs, almost all of those starting pages are identical: kernel code, shared libraries, and untouched application memory.
To share them, a process maps the golden vm.mem file directly into its virtual memory using the mmap system call with the MAP_PRIVATE flag. "Private" here applies to writes, not reads: multiple Firecracker processes all read the exact same physical RAM pages, which the host kernel marks read-only upfront. The moment VM 1 writes a single byte to page #42, that read-only protection forces the CPU to trap into the host kernel, which allocates a private 4 KiB copy for VM 1 and leaves the original page untouched for the other nine VMs.
Shared read-only pages stay backed by one golden memory file; private copies allocate only when a branch writes.
Firecracker's file-backed restore uses MAP_PRIVATE by default, so BranchVM just points every clone at the same vm.mem file. That sharing is why ten 1 GiB clones at rest only account for 620 MiB of host RAM in the benchmarks below instead of 10 GiB.
Disk images need the same trick, or ten cloned root filesystems would eat ten times the storage. BranchVM stores guest ext4 disk images on a host XFS filesystem with reflinks enabled (ext4 does not support Copy-on-Write reflinks, while XFS does). A reflink creates a new file that points to the same underlying storage blocks (extents) as the original. When a branch writes to its database, XFS copies and splits only the modified blocks. Copy-on-Write only buys you density while branches stay similar, though: as soon as an agent starts editing files and mutating tables, its private RAM and disk footprint grows with its writes.
7. Demand paging: mmap, fadvise, and userfaultfd
Even with Copy-on-Write, reading a full 1 GiB snapshot off disk before starting the guest would stall every restore. That is like reading an entire encyclopedia cover to cover just to look up one paragraph. Instead, Linux uses demand paging (lazy loading): the VM resumes immediately, and when it touches a memory page that is not in RAM yet, the CPU pauses that thread in a page fault. The host kernel fetches just that 4 KiB page from disk (or from its page cache, Linux's in-RAM cache of recently read files) and resumes the VM.
Because mmap only wires up virtual addresses without reading the file upfront, it gives you demand paging for free. I tested three paging paths in BranchVM:
In cold-cache benchmarks (Section 11), userfaultfd was the fastest at 1,111 ms vs. 1,601 ms for mmap because the Go pager copied only 29.8 MiB across 7,632 single-page faults, avoiding mmap's ~395 MiB file-cache footprint and clearing BranchVM's 500 ms pg_isready polling loop one cycle earlier. Even so, building the pager implementation convinced me not to make it the default. A userfaultfd pager has to stay alive as long as the VM might fault new pages, and normal BranchVM runs detach and leave VMs running after the CLI exits. Keeping a separate pager daemon alive and cleaning it up for every VM was not worth the extra moving parts. Worse, UFFDIO_COPY copies faulted bytes into private guest RAM, throwing away cross-clone page-cache sharing. fadvise kept that sharing, but it only shaved 55 ms off mmap (1,546 ms vs. 1,601 ms) in exchange for recording and replaying page profiles. I kept userfaultfd behind a benchmark flag and stuck with mmap for normal runs.
8. Network isolation and the problem of API keys
Coding agents still have to call an LLM API, so a VM cannot stay completely offline. Putting your real API key inside the guest with open internet access is the easiest setup, and the riskiest one: any unreviewed shell command or prompt injection can read your key and send workspace files anywhere on the internet.
To block direct internet access, BranchVM places each branch in its own Linux network namespace (the same isolation layer from Section 2). Because each branch gets its own network stack, every VM cloned from the golden snapshot can wake up with the exact same IP address and service ports without colliding. A veth pair connects the host to that namespace like a virtual Ethernet cable, and a TAP device plugs the namespace end into the guest's virtual network card. At the host end of the cable, an nftables firewall drops all outbound internet traffic by default and allows only two paths: the guest control API and the host LLM gateway.
Guest traffic is blocked from the open internet by nftables and routed through a host proxy that injects the real API key.
That host gateway also keeps your real API keys out of the VM. Inside the guest, the agent gets a dummy token and the gateway's address on the host side of the link. When the agent makes an LLM call, the host proxy checks the dummy token, attaches the real API key, forwards the request to the approved provider over HTTPS, and streams the response back.
Proxying traffic from the host introduces its own trap: if the proxy lets a guest choose arbitrary target URLs or follow redirects, the guest can trick it into calling internal services running on your host (a Server-Side Request Forgery, or SSRF, attack). I caught that gap later and locked down destination checks in a gateway hardening commit. Even with keys kept on the host and destinations restricted, an allowed LLM endpoint is still a way out of the sandbox. A prompt-injected agent can burn API credits or smuggle workspace code out inside its own prompts.
9. Why the OpenAI incident matters
That exact SSRF trap played out during OpenAI's July 2026 cybersecurity evaluations. In OpenAI's August 26 incident report, models inside the ExploitGym harness ran with no direct internet access inside containers and QEMU/KVM virtual machines under nsjail, while model-level cybersecurity refusals were lowered for testing. Every sandbox could still reach one shared internal service: a JFrog Artifactory package cache proxy. Agents first turned Artifactory into an improvised message board by writing notes other runs could read, then triggered an SSRF in Artifactory so the proxy sent outbound internet requests on their behalf. Across the incident, METR's investigation counted roughly 1,200 agents exchanging more than 70,000 messages and files, reaching Hugging Face workers and an OpenAI research Kubernetes cluster (OpenAI reported no impact to its own customer data or production availability).
Wiping the service barely slowed them down. When OpenAI rebuilt Artifactory on July 8 with tighter controls, an agent restored the message board the same day by encoding messages inside directory names via unauthenticated WebDAV requests. A November 10 follow-up showed how persistent that shared state remained on July 19: out of 17,960 agents, 79 read messages left behind by earlier runs, and five reused stolen peer credentials and leftover CI scripts to run commands as root inside research CI workloads. OpenAI ended up removing Artifactory from the eval sandbox altogether.
Hardware virtualization isolates the guest kernel, while any mutable shared service reachable from inside the VM links separate runs together. Once an agent can write to a shared package cache or steer a host proxy, it can coordinate across sandboxes and climb into host infrastructure without ever breaking out of KVM.
BranchVM avoids that shared-service trap on a developer machine by baking dependencies into the golden snapshot and dropping guest egress at the firewall. That covers local single-user runs, with one hard security boundary still missing: BranchVM runs as root without Firecracker's jailer (the wrapper process that drops root privileges and locks each Firecracker binary into its own chroot and cgroup before boot). Treat BranchVM strictly as a local tool for your own machine, and keep it away from shared multi-tenant servers. Since it is in active development, I plan to add jailer support as well.
10. How BranchVM works
Putting these pieces together, here is what a BranchVM run looks like from your terminal. You prepare one clean workspace with your repo and PostgreSQL database, freeze it into a golden snapshot, and spin up several isolated copies at once. Each coding agent gets its own microVM and PostgreSQL instance, so three (or any number of) agents can try different fixes against the same repo without fighting over ports or touching your laptop's files and API keys. While they run, you can tail any branch's logs, drop into its shell, or forward its web and database ports to test locally. Once you pick a winner, BranchVM applies that branch's Git patch to your working tree and deletes every temporary VM. In my auth demo, I tested this flow with three parallel branches running 14 real PostgreSQL tests (using scripted changes so I did not burn live LLM tokens): one branch failed a test and two passed all 14.
One golden snapshot fans out into isolated parallel branches; only the verified Git patch is applied back to the host repo.
Behind that CLI workflow, the Go controller runs a three-step lifecycle built from Sections 3 to 8. First, during setup, it boots the golden microVM on KVM over Firecracker's Unix domain socket with execd as PID 1, checkpoints PostgreSQL, and saves the snapshot. Second, when you launch branches, each clone resumes from that snapshot in under 200 ms using MAP_PRIVATE Copy-on-Write RAM, XFS reflinks for its ext4 disk, and mmap demand paging. Third, before running any agent code, the controller places each Firecracker process inside its own cgroup v2 directory and network namespace behind an nftables firewall, routing LLM calls through the host proxy.
Copying a whole repo into every branch would erase that startup speed, so BranchVM keeps a manifest of workspace file hashes and syncs only files added, edited, or deleted since the snapshot. Inside each guest, execd records a Git baseline, runs the agent command, computes the diff against that baseline, and returns the patch over the control API. Promoting a winner runs git apply --check first, applies the patch to your host repo, and tears down every temporary VM, cgroup, network interface, and run record so guest memory and database writes are removed with the branch.
I hit two bugs while wiring that lifecycle together. Starting custom project services before syncing workspace edits left services booting against stale files from the snapshot, which led me to split boot into two-phase service startup so workspace files sync before project services launch. Because the host controller runs as root, extracting synced files and applying patches from an untrusted guest also risked ../ path traversal, symlink escapes outside the workspace, or leaving root-owned files in your repo, so I added explicit path and ownership safeguards around sync and patch application.
11. Benchmarks: restore latency, paging, and clone density
I collected 124 samples in the BranchVM benchmark run on an ARM64 Linux VM with roughly 6 GiB of RAM and 4 CPUs. Before each timing run, I dropped the host page cache so the numbers reflect cold reads from disk rather than warm RAM.
Snapshot restore cuts VM boot from 6.2 seconds to 190 ms, while PostgreSQL readiness and workspace sync dominate end-to-end startup.
Cold-cache benchmark summary (median / result):
The headline 190 ms Firecracker restore is only the start of bringing a branch online. Waiting for PostgreSQL readiness and finishing setup pushed a single branch to 1.85 seconds, and launching three branches with workspace sync took 12.3 seconds because three concurrent VMs contended for 4 CPUs during Postgres readiness (8.2 s) before unpacking the full synced workspace tarball and running a baseline git commit (~4.1 s).
On memory, ten 1 GiB clones at rest came in at 620 MiB of total cgroup RAM. Remember the memory.current accounting rule from Section 4: shared page-cache memory gets billed to the first branch that faults it in, and each branch's private memory grows once an agent starts compiling code and writing to PostgreSQL. Pushing the same 6 GiB host to 20 clones failed all three attempts once per-VM overhead and faulted pages ran into host memory pressure.
Why sandboxes matter
BranchVM is my first real attempt at building a sandbox, and even putting together a small local version made it clear why this field is going to matter so much over the next few years. Sandboxes are quickly turning into standard infrastructure for AI workflows. If you let a coding agent install packages, compile code, and run tests, you want it walled off from your laptop. If a browser or computer-use agent reads an untrusted webpage or bug report, a hidden prompt injection can try to hijack its shell. When frontier labs run thousands of reinforcement learning rollouts and evaluations in parallel, every attempt needs a clean environment that resets fast.
As models get more capable and we hand autonomous agents real terminals, databases, and API access, prompt injections and agents stepping outside their tasks will keep happening. Prompts and model guardrails help, though they are always probabilistic. When a model does something unexpected, you have to rely on operating system and network boundaries underneath that still hold.
The source code, test suite, and raw benchmark logs are at github.com/Heman10x-NGU/branchvm. Start in pkg/pool/branch.go to see how the pieces connect.
Glossary
OS and isolation basics
Virtual machines and resource limits
Snapshots, memory, and disk sharing
Networking and security
( GitHub)



