An open-source, faster Devin alternative
TypeScript
Fix paused/deep hibernation correctness gaps found in drain, wake, and worker-death testing
Brian Reardonc023e5f13a25
diff --git a/deploy/azure/setup-azure-host.sh b/deploy/azure/setup-azure-host.shindex ec2e900d..d24bec31 100755--- a/deploy/azure/setup-azure-host.sh+++ b/deploy/azure/setup-azure-host.sh@@ -24,13 +24,11 @@ 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).+# zram.ko lives in linux-modules-extra, which the Azure base image omits. Use the+# -azure META package so the extras track whatever kernel actually boots (the apt+# upgrade above may bump it; a versioned package would mismatch on reboot); fall+# back to the 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"@@ -156,42 +154,33 @@ fs.inotify.max_user_watches = 524288fs.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.+# Pause reclaims via explicit MADV_PAGEOUT (swappiness-independent), so keep+# swappiness low to stop background reclaim from swapping running guests' RAM.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.+# Many memory regions per QEMU × high VM density can exceed the default map cap.vm.max_map_count = 1048576EOFsysctl --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..."+# --- Memory density: zram compressed swap (pause-tier prerequisite) ---+# The pause tier reclaims a paused guest's RAM via MADV_PAGEOUT into swap; zram+# is the high-priority compressed tier, with a file-backed disk swap on /data as+# the lower-priority overflow (set up by the worker cloud-init, which needs /data+# mounted first). Sized at boot from live RAM. KSM is intentionally not enabled+# (multi-tenant side-channel). See PR/design notes for the rationale and the+# mem_limit-vs-disk-overflow density tradeoff.+echo "Installing memory-tuning (zram) 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 up the zram compressed-swap tier. Sized from live RAM.set -euo pipefailMEM_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.+# zram: 1.5x RAM of logical swap, real RAM usage hard-capped at 40% (mem_limit).+# mem_limit is the density knob — higher keeps more boxes in the fast compressed+# tier before spilling to the disk overflow.DISKSIZE=$(( MEM_BYTES * 3 / 2 ))MEMLIMIT=$(( MEM_BYTES * 2 / 5 ))@@ -211,29 +200,15 @@ elseswapon --priority 100 /dev/zram0echo "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"-fiMEMEOFchmod +x /usr/local/bin/opensandbox-memory-setup.shcat > /etc/systemd/system/opensandbox-memory.service << 'EOF'[Unit]-Description=OpenSandbox memory density (zram swap + KSM) for the pause tier+Description=OpenSandbox memory density (zram compressed swap) for the pause tierDefaultDependencies=noAfter=local-fs.target-# Swap must be online and KSM enabled before the worker launches any guests.+# Swap must be online before the worker launches any guests.Before=opensandbox-worker.service swap.target shutdown.targetConflicts=shutdown.targetdiff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 82d6e517..33a4a504 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1989,16 +1989,17 @@ func (s *Server) hibernateDeepFallback(c echo.Context, session *db.SandboxSessiogrpcCtx, cancel := context.WithTimeout(c.Request().Context(), 120*time.Second)defer cancel()- grpcResp, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{SandboxId: sandboxID})- if err != nil {+ if _, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{SandboxId: sandboxID}); 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)+ // The worker's HibernateSandbox handler writes the sandbox_hibernations+ // record (the shared chokepoint for all remote deep-hibernations), so we+ // don't create it here — doing so would double-create with the same key and+ // the superseded-cleanup would delete the live checkpoint blob. We only need+ // to flip the session status: the worker's SetSandboxDeep CASes on+ // mode='paused', which is a no-op for this running box, so status stays+ // 'running' until we set it here._ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)// Wake may land the box on a different worker — drop the cached route.@@ -2131,14 +2132,38 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W})}- hibernation, err := s.store.GetActiveHibernation(c.Request().Context(), sandboxID)+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "no active hibernation found"})+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox session not found"})}- session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)+ // Paused (RAM-resident) tier: there is no checkpoint to restore — the VM is+ // frozen on its owning worker. Resume it in place via QMP cont. A customer-+ // hibernated box is paused, and the SDK's sandbox.wake() calls this endpoint,+ // so /wake must handle the paused tier (not just deep). This mirrors the+ // proxy's on-demand resume for data-plane requests; ResumeSandbox routes+ // through the worker's router, flipping the session back to running + emitting+ // the woke event.+ if session.HibernationMode != nil && *session.HibernationMode == "paused" {+ if session.Status == "running" {+ return c.JSON(http.StatusOK, map[string]interface{}{"sandboxID": sandboxID, "status": "running"})+ }+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})+ }+ rctx, cancel := context.WithTimeout(c.Request().Context(), 30*time.Second)+ defer cancel()+ if _, err := client.ResumeSandbox(rctx, &pb.ResumeSandboxRequest{SandboxId: sandboxID}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "resume failed: " + err.Error()})+ }+ // The box never left session.WorkerID, so no route-cache invalidation.+ return c.JSON(http.StatusOK, map[string]interface{}{"sandboxID": sandboxID, "status": "running"})+ }++ hibernation, err := s.store.GetActiveHibernation(c.Request().Context(), sandboxID)if err != nil {- return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox session not found"})+ return c.JSON(http.StatusNotFound, map[string]string{"error": "no active hibernation found"})}if session.Status != "hibernated" {return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox is not hibernated"})diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex ee7de39b..d5c524ca 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -1162,6 +1162,19 @@ func (s *Scaler) replaceOneStale(ctx context.Context, region string, target *Worlog.Printf("scaler: rolling replace: %s unreachable, can't confirm empty — NOT terminating", target.ID)return}+ // Before terminating, wait for any in-flight hibernation checkpoint uploads+ // to land in S3. A deep-hibernated (drained) box — or a leftover hibernated+ // by the fallback above — drops off the sandbox count the instant its VM is+ // evicted, but its checkpoint archive uploads in a background goroutine ON+ // THIS worker. Terminating now would kill that goroutine and lose the+ // checkpoint, leaving the box permanently unwakeable. The upload goroutine+ // has its own ~5-min timeout that records uploaded_at or upload_error, so+ // this wait always resolves; on timeout we skip termination and let the next+ // tick re-attempt (by which point the upload has settled).+ if !s.waitForHibernationUploads(target.ID, drainUploadWait) {+ log.Printf("scaler: rolling replace: %s still has hibernation upload(s) in flight after %s — NOT terminating; next tick re-attempts", target.ID, drainUploadWait)+ return+ }if s.pool != nil && target.MachineID != "" {termCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)if err := s.pool.DestroyMachine(termCtx, target.MachineID); err != nil {@@ -1419,13 +1432,14 @@ func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {// Check if drain timed outif time.Since(state.StartedAt) > drainTimeout {sandboxCount := s.getDrainingWorkerSandboxCount(state.WorkerID)- if sandboxCount == 0 {+ if sandboxCount == 0 && s.hibernationUploadsSettled(state.WorkerID) {// Sandboxes expired naturally — safe to destroylog.Printf("scaler: drain timeout for worker %s but 0 sandboxes remain, destroying", state.WorkerID)s.destroyDrainedMachine(machineID)s.state.RemoveDraining(machineID)} else {- // Still has sandboxes — cancel drain, keep worker alive+ // Still has sandboxes (or in-flight hibernation uploads) — cancel+ // drain, keep worker alive rather than lose a checkpoint.log.Printf("scaler: drain timeout for worker %s (machine=%s) with %d sandboxes — cancelling drain, keeping alive",state.WorkerID, machineID, sandboxCount)s.state.RemoveDraining(machineID)@@ -1433,10 +1447,20 @@ func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {continue}- // Check if worker has 0 sandboxes+ // Check if worker has 0 sandboxes AND no hibernation uploads are still in+ // flight. A deep-hibernated (drained) box drops off the worker's sandbox+ // count the moment its VM is evicted, but its checkpoint archive uploads+ // to S3 in a background goroutine ON THE WORKER — destroying the worker+ // before that finishes loses the checkpoint and makes the box permanently+ // unwakeable. Gate teardown on the upload being settled.workers := s.registry.GetWorkersByRegion(region)for _, w := range workers {if w.MachineID == machineID && w.Current == 0 {+ if !s.hibernationUploadsSettled(state.WorkerID) {+ log.Printf("scaler: worker %s drained (0 sandboxes) but hibernation upload(s) still in flight — deferring teardown",+ state.WorkerID)+ break+ }log.Printf("scaler: worker %s fully drained (0 sandboxes), destroying machine %s",state.WorkerID, machineID)s.destroyDrainedMachine(machineID)@@ -1459,6 +1483,51 @@ func (s *Scaler) getDrainingWorkerSandboxCount(workerID string) int {return -1}+// hibernationUploadsSettled reports whether every deep-hibernated box on this+// worker has finished (or failed) its async checkpoint upload to S3. Returns+// false while any upload is still in flight, so the caller must not destroy the+// worker yet — the upload runs on the worker, and tearing it down mid-upload+// loses the checkpoint with the VM. Fails safe (false) on a query error so a+// transient DB blip can't trigger a data-losing teardown; the drainTimeout path+// bounds how long this can defer.+func (s *Scaler) hibernationUploadsSettled(workerID string) bool {+ if s.store == nil {+ return true+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ n, err := s.store.CountPendingHibernationUploads(ctx, workerID)+ if err != nil {+ log.Printf("scaler: drain: CountPendingHibernationUploads(%s) failed: %v — deferring teardown", workerID, err)+ return false+ }+ return n == 0+}++// drainUploadWait bounds how long the synchronous rolling-replace path blocks+// waiting for a drained worker's checkpoint uploads to finish before it gives up+// and defers termination to a later tick. Sized above the upload goroutine's own+// ~5-min timeout so a normal upload always completes within the window.+const drainUploadWait = 6 * time.Minute++// waitForHibernationUploads blocks until every deep-hibernated box on the worker+// has finished (or failed) its S3 upload, or the timeout elapses. Used by the+// synchronous rolling-replace teardown; the async smart-drain path instead+// re-checks hibernationUploadsSettled across reconciler ticks. Returns true if+// uploads settled, false on timeout (caller must not terminate the worker).+func (s *Scaler) waitForHibernationUploads(workerID string, timeout time.Duration) bool {+ deadline := time.Now().Add(timeout)+ for {+ if s.hibernationUploadsSettled(workerID) {+ return true+ }+ if time.Now().After(deadline) {+ return false+ }+ time.Sleep(3 * time.Second)+ }+}+// hibernateAllOnWorker attempts to hibernate all running sandboxes on a worker.// Best-effort — logs failures but doesn't block. Returns the count actually// hibernated.diff --git a/internal/db/store.go b/internal/db/store.goindex 24a9fea9..8921a20a 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -1138,8 +1138,14 @@ func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg str}defer tx.Rollback(ctx)rows, err := tx.Query(ctx,+ // Paused boxes are worker-bound: their state is RAM-resident QEMU-pause on+ // this specific worker, so a dead worker means the state is gone — reap+ // them like running boxes. Deep-hibernated boxes (mode != 'paused') have a+ // durable S3 checkpoint and wake on any worker, so they are left alone.`UPDATE sandbox_sessions SET status = 'error', migrating_to_worker = '', stopped_at = now(), error_msg = $2- WHERE worker_id = $1 AND status IN ('running', 'migrating')+ WHERE worker_id = $1+ AND (status IN ('running', 'migrating')+ OR (status = 'hibernated' AND hibernation_mode = 'paused'))RETURNING sandbox_id, org_id, worker_id`,workerID, errorMsg)if err != nil {@@ -1201,7 +1207,13 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin// on a *live* worker is left alone (it may still be mid-create); only pending// rows on a dead worker are reaped.rows, err := s.pool.Query(ctx,- `SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status IN ('running', 'pending')`)+ // Include workers that host only paused boxes: a paused box is worker-+ // bound (RAM-resident QEMU pause), so if its worker is dead the box must be+ // reaped too. Without this, a worker holding only paused boxes would never+ // be seen as "dead" and its boxes would stay stuck 'hibernated' forever.+ `SELECT DISTINCT worker_id FROM sandbox_sessions+ WHERE status IN ('running', 'pending')+ OR (status = 'hibernated' AND hibernation_mode = 'paused')`)if err != nil {return nil, err}@@ -1228,8 +1240,13 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strincontinue}upd, err := tx.Query(ctx,+ // Paused boxes are worker-bound (RAM-resident) — a dead worker loses+ // their state, so reap them like running boxes. Deep-hibernated boxes+ // (mode != 'paused') have a durable S3 checkpoint and are left alone.`UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()- WHERE worker_id = $1 AND status IN ('running', 'pending')+ WHERE worker_id = $1+ AND (status IN ('running', 'pending')+ OR (status = 'hibernated' AND hibernation_mode = 'paused'))RETURNING sandbox_id, org_id, worker_id`, workerID)if err != nil {tx.Rollback(ctx)@@ -1816,6 +1833,27 @@ func (s *Store) MarkHibernationUploadFailed(ctx context.Context, hibernationKey,return err}+// CountPendingHibernationUploads counts sandboxes still assigned to a worker+// whose active hibernation's async S3 upload has neither completed (uploaded_at)+// nor failed (upload_error) — i.e. the upload goroutine is still in flight on+// that worker. The scaler gates destroying a drained worker on this being zero:+// the upload runs ON the worker, so tearing it down mid-upload loses the+// checkpoint and the box becomes permanently unwakeable. A failed upload+// (upload_error set) is not counted — it won't finish by waiting, so it must not+// hang the drain (the loss is already recorded, loudly).+func (s *Store) CountPendingHibernationUploads(ctx context.Context, workerID string) (int, error) {+ var n int+ err := s.pool.QueryRow(ctx,+ `SELECT count(*)+ FROM sandbox_sessions ss+ JOIN sandbox_hibernations h ON h.sandbox_id = ss.sandbox_id+ WHERE ss.worker_id = $1+ AND ss.status = 'hibernated'+ AND h.restored_at IS NULL AND h.expired_at IS NULL+ AND h.uploaded_at IS NULL AND h.upload_error IS NULL`, workerID).Scan(&n)+ return n, err+}+// UpdateSandboxSessionForWake changes a hibernated session back to running on a new worker.func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWorkerID string) error {tx, err := s.pool.Begin(ctx)diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 3bf365a7..4c5318e7 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -779,6 +779,19 @@ func (s *GRPCServer) PauseSandbox(ctx context.Context, req *pb.PauseSandboxReque// ResumeSandbox restores a paused VM's vCPUs (QMP cont). Paged-out guest memory// faults back from swap lazily — instant, no savevm/loadvm restore.func (s *GRPCServer) ResumeSandbox(ctx context.Context, req *pb.ResumeSandboxRequest) (*pb.ResumeSandboxResponse, error) {+ // Route through the sandbox router so an explicit resume does the COMPLETE+ // job — QMP cont, flip the session back to running (SetSandboxResumed), emit+ // the "woke" lifecycle event for D1, and re-arm the idle timer — exactly like+ // an on-demand data-plane resume. Calling manager.Resume directly would cont+ // the vCPUs but leave the session status and D1 stale. (This RPC is the+ // explicit-/wake path for a paused box; data-plane requests already resume+ // via the router when the proxy forwards them.)+ if s.router != nil {+ if err := s.router.Route(ctx, req.SandboxId, "resume", func(context.Context) error { return nil }); err != nil {+ return nil, fmt.Errorf("failed to resume sandbox: %w", err)+ }+ return &pb.ResumeSandboxResponse{SandboxId: req.SandboxId}, nil+ }pm, ok := s.manager.(pausableManager)if !ok {return nil, fmt.Errorf("resume not supported by this worker backend")@@ -819,6 +832,30 @@ func (s *GRPCServer) HibernateSandbox(ctx context.Context, req *pb.HibernateSandif _, err := s.store.SetSandboxDeep(ctx, req.SandboxId); err != nil {log.Printf("grpc: SetSandboxDeep(%s) failed: %v", req.SandboxId, err)}++ // Record the checkpoint so wake can find it. Every REMOTE deep-hibernation+ // (paused→deep promotion, worker drain, and the CP's version-skew fallback)+ // funnels through this handler; without a sandbox_hibernations row,+ // wakeSandboxRemote's GetActiveHibernation lookup 404s and the box — though+ // savevm'd to blob — can never wake. The record must be written here (the+ // one shared chokepoint) rather than per-caller. Pull org/region/template/+ // config off the session; the worker has cell-PG access. Best-effort+ // superseded-blob cleanup bounds storage to one checkpoint per sandbox.+ if sess, serr := s.store.GetSandboxSession(ctx, req.SandboxId); serr == nil && sess != nil {+ _, superseded, herr := s.store.CreateHibernation(ctx, req.SandboxId, sess.OrgID,+ result.HibernationKey, result.SizeBytes, sess.Region, sess.Template, sess.Config)+ if herr != nil {+ log.Printf("grpc: CreateHibernation(%s) failed: %v — box will not be wakeable", req.SandboxId, herr)+ } else if superseded != "" && s.checkpointStore != nil && !strings.HasPrefix(superseded, "local://") {+ delCtx, delCancel := context.WithTimeout(context.Background(), 30*time.Second)+ if derr := s.checkpointStore.Delete(delCtx, superseded); derr != nil {+ log.Printf("grpc: delete superseded hibernation %s failed: %v", superseded, derr)+ }+ delCancel()+ }+ } else if serr != nil {+ log.Printf("grpc: GetSandboxSession(%s) for hibernation record failed: %v — box will not be wakeable", req.SandboxId, serr)+ }}// Emit hibernated lifecycle event BEFORE removing the per-sandbox SQLite.