Skip to main content
· 13 min read

CubePod – E2B-compatible sandboxes with persistent rootfs on K8s

xfgong
CubePlex
CubePod – E2B-compatible sandboxes with persistent rootfs on K8s

CubePod is an open-source, persistent MicroVM execution platform for high-autonomy AI agents, now at v0.8.1.

Within the CubePlex open-source stack, CubePod serves as the execution layer ("Hands") in a decoupled "Brain and Hand" architecture alongside CubePlex (Team Agent Workspace) and CubeLoop (Async Agent Runtime). CubePod targets a specific engineering goal: running on native Kubernetes CRDs and CSI block storage, maintaining wire compatibility with official E2B SDKs, and ensuring full RootFS modifications survive node crashes and cross-node rescheduling.

The Open-Source Agent Sandbox Landscape​

Several open-source sandbox projects address isolated code execution for AI agents, each making different choices around control planes, scheduling, isolation, and persistence:

  1. E2B Runtime (e2b-dev/runtime): A Go control plane (API, client-proxy, and per-node orchestrator running on Nomad/Consul with PostgreSQL, Redis, ClickHouse, and object storage) driving Firecracker microVMs. Templates and paused sandboxes are stored as full VM snapshots (memory + disk + machine state) in object storage. Creation and resume restore these snapshots via userfaultfd lazy paging and a CoW rootfs overlay, achieving extremely fast startup and resume times.
  2. CubeSandbox (TencentCloud/CubeSandbox): A vertically integrated KVM MicroVM stack comprising CubeAPI, CubeMaster, Cubelet, CubeShim, CubeHypervisor, and XFS reflink-based CubeCoW. Even in its Kubernetes deployment (v0.6+), Kubernetes only delivers the control plane and node DaemonSets (cube-node); CubeMaster schedules KVM MicroVMs directly on host nodes rather than modeling each sandbox as a Kubernetes Pod and CRD (see OpenSandbox vs. CubeSandbox Selection).
  3. Kubernetes agent-sandbox (kubernetes-sigs/agent-sandbox): The official Kubernetes SIG Apps orchestrator providing Sandbox, SandboxTemplate, SandboxClaim, and SandboxWarmPool CRDs. It delegates isolation to CRI RuntimeClass (such as gVisor or Kata Containers) and storage to standard PVCs. It is strictly an orchestrator—it does not ship an in-sandbox execution daemon, stateful code interpreter, E2B-compatible API, or zero-trust egress secret vault.
  4. OpenSandbox (opensandbox-group/OpenSandbox): Built around a FastAPI lifecycle server (server/), OpenSandbox supports two distinct architectures on Kubernetes:
    • K8s-Native Container Workload (BatchSandbox / Pool / SandboxSnapshot or agent-sandbox provider): Each sandbox runs as a standard Kubernetes Pod with optional PVCs. On pause, a commit Job packages the container's writable rootfs into an OCI image and pushes it to a container registry; on resume, a new Pod boots from that snapshot image.
    • Fast Sandbox Integration (fast-sandbox): For template-backed requests (templateId or fsb- IDs), CompositeSandboxService routes lifecycle operations to an external FastPath gRPC control plane and sandbox.fast.io CRDs, packing multiple Firecracker microVMs inside pre-warmed Fastlet pods with P2P artifact delivery (DART), bypassing per-sandbox Kubernetes scheduler and kubelet hot paths.
PlatformControl Plane & SchedulingExecution UnitRootFS Persistence & Crash DurabilityE2B Compatibility
E2B RuntimeNomad/Consul + custom API/OrchestratorFirecracker MicroVMDiffs memory/disk to object storage only on Pause; node crash loses unpaused RootFS writesNative standard
CubeSandboxCubeMaster + node Cubelet (K8s for delivery only)Node-local KVM MicroVMNode-local full VM memory & disk snapshots (XFS reflink)Compatible
K8s agent-sandboxNative K8s CRDs (Sandbox / WarmPool)K8s Pod + RuntimeClassStandard PVCs only; no RootFS persistenceNone
OpenSandbox (K8s-Native)FastAPI Server + BatchSandbox ControllerK8s Pod + RuntimeClassCommits writable layer to OCI Registry on PauseNot compatible
OpenSandbox (FastSandbox)FastAPI + FastPath gRPC + FastletMulti-VM inside Fastlet PodTemplate & node-local state roots with checkpointingNot compatible
CubePodNative K8s CRDs (PodBox / PodWarmPool) + stateless GatewayKata MicroVM Pod (kata-clh / kata-qemu)Block-backed RootFS + RWO Block or RWX /workspace; survives node crashesCompatible

Tradeoffs in Operations, E2B Compatibility, and Node Failure Recovery​

Deploying long-lived autonomous agents in production highlights three gaps across existing approaches:

1. Custom Cluster Operations vs. Existing Kubernetes Infrastructure​

E2B delivers impressive cold-start and snapshot-resume latency, but operating a dedicated stack of Nomad, Consul, PostgreSQL, Redis, ClickHouse, object storage, and node-level orchestrator daemons adds significant operational burden. Most platform teams already run Kubernetes with established CSI storage, RBAC, monitoring, and network policies. Introducing a separate scheduling plane (E2B's Nomad stack or CubeSandbox's CubeMaster/Cubelet) forces teams to maintain parallel observability, capacity planning, and node-lifecycle tooling.

2. Data Loss on Node Crash Between Pauses​

In E2B, persistence of the root filesystem relies on diffing memory and disk and uploading the delta to object storage when pause is invoked. While a sandbox is Running—including after resuming from an earlier pause and before the next pause completes—writes to the rootfs live on that host node's local overlay. If the node crashes, loses power, or is preempted before the next pause, any unpaused RootFS modifications are lost.

Similarly, OpenSandbox's K8s-native path persists the container rootfs by running an OCI commit/push Job at pause time, which incurs tens of seconds of export latency and does not protect unpaused container writable layers against sudden node failure.

3. Ephemeral RootFS in Standard Kubernetes Containers​

When using standard Pods or agent-sandbox with a single PVC mounted at /workspace, any Pod eviction, scale-down, or cross-node reschedule discards system packages installed under /usr, /etc, and /var (apt, pip, npm, compilers, browser libraries). Conversely, coupling OS files and user code into a single volume prevents resetting a corrupted OS environment without risking /workspace data.


CubePod Design Goals and Core Tradeoffs​

Most sandbox orchestrators treat cold-start and resume latency as their primary optimization target, keeping active filesystem writes in node-local overlays or local snapshots and syncing them only on an explicit pause. For long-lived agents that operate a dedicated cloud computer over days or weeks (such as Grokbot or Cue), losing installed system packages, browser sessions, local configurations, and workspace artifacts to a sudden host failure is far more disruptive than waiting an extra second on resume.

CubePod explicitly prioritizes zero data loss over sub-100ms resume latency: in a decoupled "Brain and Hand" architecture, the agent's reasoning state and conversation history are already persisted by the external control plane (such as CubeLoop or CubePlex). During sleep, the sandbox does not need to preserve guest RAM; it only needs distributed storage guarantees that preserve full-disk state (RootFS + Workspace) across node failures.

This leads to four core design decisions:

  1. First-Class Kubernetes Primitives: Every sandbox is a PodBox CR (cubepod.io/v1alpha1) backed by a standard Kubernetes Pod running Kata Containers (kata-clh Cloud Hypervisor recommended, or kata-qemu) and persistent PVCs. cubepod-gateway is stateless HA, reading authoritative state from Kubernetes CRDs and annotations.
  2. Block-Backed RootFS & Flexible /workspace Storage: Rather than relying on node-local overlays and pause-time exports, CubePod mounts the RootFS upperdir on a volumeMode: Block PVC via virtio-blk (ext4), while /workspace supports both RWO Raw Block (exclusive high-IOPS virtio-blk) and RWX shared storage (via cubepod-volume-nfs NFSv3 or RWX PVCs for multi-sandbox sharing). Writes persist continuously to distributed storage backends (such as Longhorn V2 SPDK, Ceph RBD, OpenEBS Mayastor, or cloud EBS/NFS). If a node dies mid-execution, Kubernetes reschedules the Pod on a healthy node and re-attaches both volumes with zero disk data loss.
  3. E2B Wire Compatibility: The in-guest Rust daemon podd (:49983) and cubepod-gateway (:8080) implement E2B's REST and Connect-RPC contracts (/process.Process/*, /filesystem.Filesystem/*), allowing official e2b and e2b-code-interpreter SDKs to connect by simply setting E2B_DOMAIN.
  4. Kubernetes & Local Docker Parity: Production uses Kata + CSI Block; local development uses docker-loopback with sparse .ext4 loopback files, executing the exact same podd-init and podd binaries.

CubePod Platform Architecture Topology


Decoupled RootFS & /workspace Storage and In-Guest RootFS Pivot (podd-init)​

Standard Kubernetes mounts volumeDevices after the container's rootfs is already prepared by containerd. To mount a raw block device as the container's writable RootFS layer without patching Kubelet or writing custom containerd snapshotters, CubePod uses an In-Guest RootFS Pivot.

1. OS/Workspace Decoupling and rootfsGeneration Reset​

Storage LayerBacking VolumeGuest Mount TargetLifecycle & Isolation Semantics
Base OCI LayerStandard OCI image (ubuntu:24.04)OverlayFS lowerdir=/ (RO)Node-shared read-only cache; user images stay completely clean.
RootFS Upper10Gi CSI Raw Block PVC (rootfs-pvc)OverlayFS upperdir + workdirPersists /usr, /etc, /var (apt/pip/npm installs).
WorkspaceRWO Block PVC (exclusive) or RWX shared volume (cubepod-volume-nfs / RWX PVC)Mounted at /workspace (1000:1000)Stores project code, artifacts, and /workspace/.skills; choose exclusive high-IOPS block or multi-sandbox RWX sharing.

If an agent breaks system shared libraries or needs a base image upgrade, calling POST /sandboxes/{id}/reset-rootfs (or incrementing PodBox.spec.rootfsGeneration) instructs cubepod-controller to replace <box>-rootfs-gen<N>-pvc while re-attaching the existing /workspace volume (whether RWO Block or RWX shared) untouched.

Dual-Volume Persistence and In-Guest RootFS Pivot

2. Single-Threaded Rust podd-init and Binary Injection​

  • Zero Image Pollution: User images require no CubePod binaries baked in. cubepod-podd (< 1MB, busybox:1.37-musl) injects podd-init and podd into /opt/cubepod/bin via an initContainer emptyDir (or an optional hostPath DaemonSet introduced in v0.8.1 to skip initContainer overhead).
  • Single-Threaded PID 1 Requirement: Linux pivot_root(2) returns EINVAL if the calling process has concurrent OS threads sharing its mount namespace. Because the Go runtime spawns background threads before main(), podd-init (crates/podd-init/) is written in single-threaded Rust using direct libc::mount(2) syscalls.
  • Self-Healing Boot: podd-init isolates mount propagation, probes block devices via blkid, runs lazy mkfs.ext4 on first boot or mounts directly on wake with e2fsck -p fallback on mount failure (optimized in v0.8.1), assembles OverlayFS, mounts /workspace, bind-mounts /proc, /sys, /dev, /run, and /opt/cubepod, executes pivot_root, detaches the old root, and execvps into podd (:49983) as PID 1.

Zero-Export Suspend, PodWarmPool, and CoW Fork​

1. Zero-Export Hibernation and ~1s Cross-Node Resume​

When a sandbox hits idleTimeoutSeconds or receives a pause request, podd flushes dirty pages (sync + FIFREEZE), and the controller deletes the Kata Pod. Compute usage drops to 0 CPU / 0 RAM without pushing OCI layers or multi-GB memory dumps. Any subsequent request to cubepod-gateway flips desiredState back to Running; Kubernetes schedules a new Pod on any available node, re-attaches both PVCs, and podd-init mounts the ext4 volumes in ~1 second (accelerated in v0.8.1 via K8s Pod watches, per-box parallel reconciliation, and direct PodIP:49983/health probing).

2. PodWarmPool (< 50ms Cold Starts)​

Kubernetes prohibits mutating spec.volumes on an already-running Pod. PodWarmPool solves this by maintaining standby Kata MicroVMs that already have pre-created, thin-provisioned dual block PVCs attached and pivoted into ext4. When a creation request arrives, cubepod-controller atomically claims a standby Pod and its volumes via Kubernetes optimistic-locking CAS labels in under 50ms, then asynchronously replenishes the pool.

3. Crash-Consistent CoW Fork (spec.forkFrom)​

To support speculative sub-agent branching without affecting the parent sandbox, POST /sandboxes/{id}/fork executes a bounded quiesce-and-clone sequence in ~1 second:

[ 1. Client Issues Fork Request ] POST /sandboxes/{id}/fork
│
▼
[ 2. Quiesce Parent Filesystem ] podd invokes FIFREEZE (with 1.5s watchdog)
│
▼
[ 3. CSI Block CoW Clone ] Clones via DataSourcePVC / Snapshot
│
▼
[ 4. Immediate Parent Thaw ] Sends FITHAW to restore parent workload I/O
│
▼
[ 5. Schedule Child Pod ] Boots CUBEPOD_FORKED=1, auto-heals ext4
│
▼
[ 6. Child Sandbox Ready ] New PodBox with isolated IP & state

Zero-Trust Egress and E2B Protocol Extensions​

1. Secret Exclusion and Selective mTLS Token Swapping​

Genuine external API keys never enter sandbox environment variables, filesystems, or process memory:

Zero-Trust Egress Pipeline

  • Variables configured via secretBindings are injected as opaque reference placeholders.
  • An unprivileged cubepod-egress sidecar (UID 65532) pairs with nftables to intercept outbound HTTP (:18081), TLS (:18443), and DNS (:18053), dropping UDP 443 (QUIC bypass) and returning RCODE=5 for unauthorized DNS queries.
  • Traffic to unbound allowlisted hosts uses zero-copy TCP splicing (spliceUpstream). Only hosts bound to secrets undergo selective TLS/HTTP2 ALPN MITM (HTTP Host == TLS SNI verified), swapping placeholder tokens in flight via per-pod ECDSA P-256 mTLS against cubepod-gateway.

2. E2B Superset & Unified /volumes​

Alongside full compatibility with e2b and e2b-code-interpreter (6 stateful kernels: Python, JS, TS, R, Java, Bash), CubePod adds stateless byte-cursor log streaming (GET /commands/{pid}/logs?cursor=N), < 50ms in-memory skill archive-sync, HMAC-signed /panel/{token}/ proxying (Chromium CDP, Neko WebRTC, ttyd), and unified /volumes (type: "shared" | "block", with cubepod-volume-nfs NFSv3 transport for shared volumes across Firecracker/Kata and CAS attach-lease fencing for block /workspace in v0.8.0).


CubePod Strengths, Tradeoffs, and Scope​

Strengths​

  1. Node-Crash Durability Without Pausing: Continuous writes to distributed CSI Raw Block volumes for RootFS (and RWO Block or RWX shared storage for /workspace) mean OS and project state survive unexpected node crashes, kernel panics, or Pod evictions—not just clean pause calls.
  2. Native Kubernetes Operations: Every sandbox is a standard PodBox CR and Kata Pod scheduled by Kubernetes, inheriting existing CSI storage, RBAC, NetworkPolicy, Prometheus metrics, and Helm lifecycle management without operating Nomad/Consul or a custom VMM scheduler.
  3. Decoupled OS Reset & Clean Images: rootfsGeneration repairs broken OS packages without touching /workspace, while standard OCI images run unmodified.
  4. E2B Drop-In + Built-In Secret Exclusion: Zero-code migration for E2B SDK consumers, combined with in-pod mTLS credential swapping.

Tradeoffs and Limitations​

  1. No Guest RAM or Process State Across Pause: This is an explicit tradeoff for staying strictly Kubernetes-native without out-of-tree Kubelet or runtime patches. Native Pod-level memory checkpoint/restore depends on upstream Kubernetes Pod Checkpoint/Restore support, which is not expected to reach Alpha until Kubernetes 1.38. Until then, CubePod deletes the Pod on pause rather than bypassing Kubernetes Pod scheduling; consequently, running background processes, open sockets, and in-memory interpreter variables are lost on pause/resume. Workloads requiring live process continuation across sleep are better served by E2B or CubeSandbox's full memory snapshots.
  2. Resume Latency (~1s) vs. Local Memory-Snapshot Resume (< 100ms): PodWarmPool delivers < 50ms cold starts for new blank sandboxes, but resuming an existing Paused sandbox requires K8s scheduling, CSI volume attachment, and podd-init mounting (~1s), which is slower than E2B or CubeSandbox resuming cached local snapshots via userfaultfd/mmap.
  3. Kubernetes Infrastructure Prerequisites: Full hardware-isolated block persistence requires Kata Containers and a CSI driver supporting volumeMode: Block and snapshots (Longhorn V2 SPDK, Ceph RBD, OpenEBS, or cloud EBS). kata-clh (Cloud Hypervisor) is recommended for production; kata-fc (Firecracker) currently has a known virtio-mmio hotplug race (#120). Clusters without Kata or Block CSI fall back to volumeMode: Filesystem (without RootFS persistence).
  4. Storage Overhead for Short-Lived Stateless Tasks: Provisioning a persistent block PVC for RootFS adds unnecessary CSI attach/detach overhead for ephemeral, sub-minute tasks that do not need OS persistence; plain container pools (e.g., OpenSandbox Pool) are lighter for purely stateless workloads.

Repositories and Deployment​

CubePod is open-source under the Apache 2.0 License:

  • GitHub: cubeplexai/cubepod (current release v0.8.1)
  • Documentation: cubepod.dev
  • Enhancement Proposals (CEPs): docs/enhancements
  • Deployment: Production Helm chart at deploy/helm/cubepod (Kata + CSI Block) and single-host deploy/docker-compose (docker-loopback mode).

Open-source projects

Bring agents into your team's day-to-day work

CubePlex

A self-hosted AI agent workspace for teams to handle document, data, and cross-system work with centralized access control and execution records.

View CubePlex source

CubeLoop

A high-performance, traceable, async-native Python agent framework with production-grade persistence.

Visit CubeLoop