Skip to content

An open-source, faster Devin alternative

TypeScript

Make the pause hibernation tier production-ready: swap infra, billing, deploy safety

Brian Reardon79e1367231d4
diff --git a/deploy/azure/setup-azure-host.sh b/deploy/azure/setup-azure-host.sh
index 0116a9ba..ec2e900d 100755
--- a/deploy/azure/setup-azure-host.sh
+++ b/deploy/azure/setup-azure-host.sh
@@ -24,6 +24,17 @@ apt-get install -y -qq \
e2fsprogs git podman uidmap slirp4netns \
postgresql-client jq curl zstd
+# Host kernel extras — provide the zram module for the compressed-swap tier the
+# pause/hibernate reclaim uses. zram.ko lives in linux-modules-extra, which the
+# Azure base image does NOT ship by default. Install the -azure META package so
+# the extras track whatever azure kernel actually boots (the apt upgrade above
+# may bump the kernel; a versioned package would then mismatch on reboot). Fall
+# back to the currently-booted kernel's versioned package. Non-fatal: without
+# zram the disk-swap tier still carries the pause feature (just less dense).
+apt-get install -y -qq linux-modules-extra-azure \
+ || apt-get install -y -qq "linux-modules-extra-$(uname -r)" \
+ || echo "WARNING: linux-modules-extra (zram) not installed — pause tier will fall back to disk swap only"
+
# --- Docker ---
echo "Installing Docker..."
if ! command -v docker &>/dev/null; then
@@ -143,9 +154,99 @@ net.ipv4.neigh.default.gc_thresh3 = 8192
fs.file-max = 1000000
fs.inotify.max_user_watches = 524288
fs.inotify.max_user_instances = 8192
+
+# --- Memory reclaim / pause-tier tuning ---
+# The pause/hibernate tier reclaims a paused guest's RAM via explicit
+# process_madvise(MADV_PAGEOUT) into swap (zram + disk, set up below). That
+# path does not depend on swappiness — so keep swappiness LOW so the kernel's
+# *background* reclaim does not eagerly swap out the RAM of running (active)
+# guests under transient pressure and add latency. Swap stays available for the
+# explicit pageout and for genuine emergencies.
+vm.swappiness = 10
+# Each QEMU has many memory regions (base RAM, virtio-mem pool, device BARs);
+# at high VM density per host the default 65530 map limit can be hit. Raise it.
+vm.max_map_count = 1048576
EOF
sysctl --system -q
+# --- Memory density: zram compressed swap + KSM (pause-tier prerequisites) ---
+# These are the hard prerequisites for the RAM-resident "pause" hibernation
+# tier: without a swap target, process_madvise(MADV_PAGEOUT) has nowhere to
+# page a paused guest's RAM and reclaim collapses to ~1x. zram is the
+# high-priority compressed tier (idle guest pages are zero-heavy, ~3-4x); a
+# file-backed disk swap on /data is the lower-priority overflow, set up at
+# first boot by the worker cloud-init (it needs /data mounted first).
+#
+# Sizing is computed at BOOT from live RAM (the AMI builder VM is smaller than
+# the runtime worker), so this is a boot-time oneshot, not baked-in numbers.
+echo "Installing memory-tuning (zram + KSM) setup..."
+cat > /usr/local/bin/opensandbox-memory-setup.sh << 'MEMEOF'
+#!/usr/bin/env bash
+# Set up the zram compressed-swap tier and enable KSM. Sized from live RAM.
+set -euo pipefail
+
+MEM_KB=$(awk '/^MemTotal:/{print $2}' /proc/meminfo)
+MEM_BYTES=$((MEM_KB * 1024))
+
+# --- zram: high-priority compressed swap ---
+# Expose 1.5x RAM of logical swap, but hard-cap the REAL RAM zram may consume
+# at 40% of RAM (mem_limit). The 1.5x is only reachable when pages compress
+# well — which paused guests do — so this never eats more than the cap.
+DISKSIZE=$(( MEM_BYTES * 3 / 2 ))
+MEMLIMIT=$(( MEM_BYTES * 2 / 5 ))
+
+modprobe zram num_devices=1 2>/dev/null || true
+if [ ! -e /sys/block/zram0/disksize ]; then
+ echo "zram device not available — skipping zram (disk swap still applies)"
+else
+ # Idempotent: reset a previously-configured device before reconfiguring.
+ if [ "$(cat /sys/block/zram0/disksize)" != "0" ]; then
+ swapoff /dev/zram0 2>/dev/null || true
+ echo 1 > /sys/block/zram0/reset 2>/dev/null || true
+ fi
+ echo zstd > /sys/block/zram0/comp_algorithm 2>/dev/null || true
+ echo "$MEMLIMIT" > /sys/block/zram0/mem_limit
+ echo "$DISKSIZE" > /sys/block/zram0/disksize
+ mkswap -U clear /dev/zram0 >/dev/null
+ swapon --priority 100 /dev/zram0
+ echo "zram0: disksize=$DISKSIZE mem_limit=$MEMLIMIT (zstd), swap priority 100"
+fi
+
+# --- KSM: dedup identical guest pages across VMs ---
+# QEMU advises guest RAM MADV_MERGEABLE by default (machine mem-merge=on), so
+# KSM finds cross-VM duplicates (shared golden pages, zeroed regions) for extra
+# density on top of the pause tier. Best-effort — skip cleanly if unsupported.
+if [ -d /sys/kernel/mm/ksm ]; then
+ echo 1000 > /sys/kernel/mm/ksm/pages_to_scan 2>/dev/null || true
+ echo 20 > /sys/kernel/mm/ksm/sleep_millisecs 2>/dev/null || true
+ echo 1 > /sys/kernel/mm/ksm/merge_across_nodes 2>/dev/null || true
+ echo 1 > /sys/kernel/mm/ksm/run 2>/dev/null || true
+ echo "KSM enabled (pages_to_scan=1000 sleep_millisecs=20)"
+else
+ echo "KSM not supported by kernel — skipping"
+fi
+MEMEOF
+chmod +x /usr/local/bin/opensandbox-memory-setup.sh
+
+cat > /etc/systemd/system/opensandbox-memory.service << 'EOF'
+[Unit]
+Description=OpenSandbox memory density (zram swap + KSM) for the pause tier
+DefaultDependencies=no
+After=local-fs.target
+# Swap must be online and KSM enabled before the worker launches any guests.
+Before=opensandbox-worker.service swap.target shutdown.target
+Conflicts=shutdown.target
+
+[Service]
+Type=oneshot
+RemainAfterExit=yes
+ExecStart=/usr/local/bin/opensandbox-memory-setup.sh
+ExecStop=/bin/sh -c 'swapoff /dev/zram0 2>/dev/null || true; echo 1 > /sys/block/zram0/reset 2>/dev/null || true'
+
+[Install]
+WantedBy=multi-user.target
+EOF
+
# --- Directory structure ---
mkdir -p /data/sandboxes /data/firecracker/images /data/checkpoints /etc/opensandbox
@@ -222,7 +323,7 @@ WantedBy=multi-user.target
EOF
systemctl daemon-reload
-systemctl enable opensandbox-worker opensandbox-server
+systemctl enable opensandbox-worker opensandbox-server opensandbox-memory
echo "=== Azure host setup complete ==="
echo " QEMU: $(qemu-system-x86_64 --version | head -1)"
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index ae2320a1..82d6e517 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -21,6 +21,8 @@ import (
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/pkg/types"
pb "github.com/opensandbox/opensandbox/proto/worker"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
)
const (
@@ -1942,6 +1944,19 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error
// later — idle age (1h), the per-org paused cap, or memory pressure — so the
// customer only ever sees "hibernated". No checkpoint key/size to return.
if _, err := client.PauseSandbox(grpcCtx, &pb.PauseSandboxRequest{SandboxId: sandboxID}); err != nil {
+ // Version-skew fallback. This PR ships the pause tier in BOTH the control
+ // plane and the worker, but they roll independently: the CP deploys in
+ // minutes while the worker AMI takes ~30 min to build + roll. During that
+ // window a not-yet-rolled worker runs the old binary, which has no
+ // PauseSandbox RPC and returns Unimplemented. Rather than 500 the
+ // customer's hibernate, fall back to the legacy deep HibernateSandbox
+ // (which old workers do support). The customer still sees "hibernated";
+ // it's just a deep hibernate instead of a pause until the fleet rolls,
+ // after which this branch stops firing. Any other error is a real
+ // failure and surfaces as before.
+ if status.Code(err) == codes.Unimplemented {
+ return s.hibernateDeepFallback(c, session)
+ }
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "hibernate failed: " + err.Error()})
}
if _, err := s.store.SetSandboxPaused(c.Request().Context(), sandboxID); err != nil {
@@ -1956,6 +1971,46 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error
})
}
+// hibernateDeepFallback performs a legacy deep (savevm) hibernation of a running
+// sandbox. It is the version-skew path for hibernateSandboxRemote: when the
+// owning worker predates the pause tier (returns Unimplemented for PauseSandbox
+// during a CP-ahead-of-workers deploy window), we deep-hibernate instead so the
+// customer's hibernate keeps working. Mirrors the pre-pause hibernate flow
+// exactly: checkpoint record + status=hibernated. hibernation_mode stays NULL,
+// which the wake proxy treats as deep-restore — identical to every deep box
+// before this PR — so wake works correctly whether or not the fleet has rolled.
+func (s *Server) hibernateDeepFallback(c echo.Context, session *db.SandboxSession) error {
+ sandboxID := session.SandboxID
+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ if err != nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})
+ }
+ // Deep hibernate (savevm + evict) is slower than a pause — allow more time.
+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 120*time.Second)
+ defer cancel()
+
+ grpcResp, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{SandboxId: sandboxID})
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "hibernate failed: " + err.Error()})
+ }
+
+ orgID, _ := auth.GetOrgID(c)
+ _, superseded, _ := s.store.CreateHibernation(c.Request().Context(), sandboxID, orgID,
+ grpcResp.CheckpointKey, grpcResp.SizeBytes,
+ session.Region, session.Template, session.Config)
+ s.deleteSupersededHibernation(superseded)
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)
+
+ // Wake may land the box on a different worker — drop the cached route.
+ if s.sandboxAPIProxy != nil {
+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
+ }
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "sandboxID": sandboxID,
+ "status": "hibernated",
+ })
+}
+
// internalDeepHibernate promotes a specific paused sandbox to deep hibernation.
// Called by the api-edge cross-cell paused-cap enforcer (which has the org-global
// view via D1) against the cell that currently hosts the sandbox. Only acts on
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index 0418c227..d63b9390 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -702,6 +702,30 @@ func (p *AzurePool) buildUserData(opts MachineOpts) string {
sb.WriteString(" echo 'Copied retained bases from /opt/opensandbox/images/bases to /data/firecracker/images/bases'\n")
sb.WriteString("fi\n\n")
+ // Disk swap tier for the pause/hibernate RAM reclaim. The image sets up
+ // zram (high-priority compressed swap) via opensandbox-memory.service; this
+ // file-backed swap on the NVMe /data disk is the lower-priority OVERFLOW so
+ // that many paused boxes on one host don't exhaust zram's RAM cap. It lives
+ // here (cloud-init) rather than the image because it needs /data mounted
+ // first — anything written to /data at bake time is shadowed by the NVMe
+ // mount. Note: /data is XFS, which rejects fallocate'd swapfiles (unwritten
+ // extents), so the file must be fully written with dd.
+ sb.WriteString("# Disk swap overflow tier (behind zram) for the pause/hibernate reclaim\n")
+ sb.WriteString("SWAPFILE=/data/swapfile\n")
+ sb.WriteString("SWAP_GB=32\n")
+ sb.WriteString("if ! swapon --show=NAME --noheadings 2>/dev/null | grep -qx \"$SWAPFILE\"; then\n")
+ sb.WriteString(" if [ ! -f \"$SWAPFILE\" ]; then\n")
+ sb.WriteString(" dd if=/dev/zero of=\"$SWAPFILE\" bs=1M count=$((SWAP_GB*1024)) status=none\n")
+ sb.WriteString(" chmod 600 \"$SWAPFILE\"\n")
+ sb.WriteString(" mkswap \"$SWAPFILE\" >/dev/null\n")
+ sb.WriteString(" fi\n")
+ sb.WriteString(" swapon --priority 10 \"$SWAPFILE\" || echo 'swapon /data/swapfile failed (non-fatal)'\n")
+ // Persist for reboots at a LOWER priority than zram (100). systemd derives
+ // the RequiresMountsFor=/data ordering from the swapfile path, so the swap
+ // only activates after the /data XFS mount comes up.
+ sb.WriteString(" grep -q \"$SWAPFILE\" /etc/fstab 2>/dev/null || echo \"$SWAPFILE none swap sw,pri=10 0 0\" >> /etc/fstab\n")
+ sb.WriteString("fi\n\n")
+
// Write worker env file from injected WorkerSpec.
p.mu.RLock()
envContent := BuildWorkerEnv(p.spec)
diff --git a/internal/worker/usage_ticker.go b/internal/worker/usage_ticker.go
index f4b87c5f..496383d5 100644
--- a/internal/worker/usage_ticker.go
+++ b/internal/worker/usage_ticker.go
@@ -165,6 +165,7 @@ func (t *UsageTicker) tick(ctx context.Context) {
now := time.Now()
emitted := 0
skippedDead := 0
+ skippedPaused := 0
aliveIDs := make([]string, 0, len(list))
for _, sb := range list {
// Defense in depth: even if manager.List() returns a ghost entry
@@ -185,6 +186,15 @@ func (t *UsageTicker) tick(ctx context.Context) {
log.Printf("usage_ticker: %s: not alive (ghost m.vms entry?) — skipping; reaper should drain it", sb.ID)
continue
}
+ // Paused (RAM-resident hibernation tier): the VM is alive but has paged
+ // its guest RAM out and is unbilled. Skip it and drop its billing state
+ // so a later resume starts a fresh interval instead of back-billing the
+ // entire paused gap.
+ if sb.Status == types.SandboxStatusPaused {
+ skippedPaused++
+ t.dropState(sb.ID)
+ continue
+ }
aliveIDs = append(aliveIDs, sb.ID)
intervalSec, newRemainder := t.intervalSecondsFor(sb, now)
@@ -228,7 +238,7 @@ func (t *UsageTicker) tick(ctx context.Context) {
// already handled above) AND outright disappearance (destroy between
// ticks where the sandbox is gone from List entirely).
t.pruneStateNotIn(aliveIDs)
- log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d listed sandbox(es) (skipped %d as not-alive)", emitted, len(list), skippedDead)
+ log.Printf("usage_ticker: tick: emitted %d usage_tick event(s) for %d listed sandbox(es) (skipped %d as not-alive, %d as paused)", emitted, len(list), skippedDead, skippedPaused)
}
// intervalSecondsFor returns the actual elapsed time to attribute to this emit