An open-source, faster Devin alternative
TypeScript
autosave
Brian Reardonb5969e9b4087
diff --git a/.gitignore b/.gitignoreindex 3cd1694a..8011319f 100644--- a/.gitignore+++ b/.gitignore@@ -29,8 +29,7 @@ node_modules/dist/# Compiled binaries-bin/opensandbox-server-bin/opensandbox-worker+bin/opensandbox-*opensandbox-worker# Worker env (secrets)diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 675ac34b..8fc7482b 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -8,6 +8,7 @@ import ("os/signal""path/filepath""syscall"+ "time""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/config"@@ -147,6 +148,14 @@ func main() {} else {defer store.Close()log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")++ // Startup reconciliation: mark stale "running" sessions from a previous crash+ hibernated, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)+ if err != nil {+ log.Printf("opensandbox-worker: warning: session reconciliation failed: %v", err)+ } else if hibernated+stopped > 0 {+ log.Printf("opensandbox-worker: reconciled stale sessions: %d hibernated, %d stopped", hibernated, stopped)+ }}}@@ -160,6 +169,12 @@ func main() {log.Printf("opensandbox-worker: sandbox %s auto-hibernated (key=%s, size=%d bytes)",sandboxID, result.CheckpointKey, result.SizeBytes)if store != nil {+ // Create checkpoint record so wake-on-request can find it+ session, err := store.GetSandboxSession(context.Background(), sandboxID)+ if err == nil {+ _, _ = store.CreateCheckpoint(context.Background(), sandboxID, session.OrgID,+ result.CheckpointKey, result.SizeBytes, session.Region, session.Template, session.Config)+ }_ = store.UpdateSandboxSessionStatus(context.Background(), sandboxID, "hibernated", nil)}},@@ -262,13 +277,63 @@ func main() {}}+ // Start periodic workspace autosave for crash recovery+ var autosaver *worker.WorkspaceAutosaver+ if checkpointStore != nil && store != nil {+ autosaver = worker.NewWorkspaceAutosaver(mgr, fcMgr, checkpointStore, store, cfg.WorkerID, cfg.Region, 5*time.Minute)+ autosaver.Start()+ }+quit := make(chan os.Signal, 1)signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)<-quit- log.Println("opensandbox-worker: shutting down...")+ log.Println("opensandbox-worker: graceful shutdown starting...")++ // 1. Stop accepting new workgrpcServer.Stop()if err := httpServer.Close(); err != nil {log.Printf("error closing HTTP server: %v", err)}++ // Stop autosaver before hibernating+ if autosaver != nil {+ autosaver.Stop()+ }++ // 2. Hibernate all running sandboxes for seamless resume+ if checkpointStore != nil {+ vms, _ := mgr.List(context.Background())+ if len(vms) > 0 {+ log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))+ shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ results := fcMgr.HibernateAll(shutCtx, checkpointStore)+ cancel()++ for _, r := range results {+ if r.Err != nil {+ log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)+ if store != nil {+ errMsg := "hibernate failed on shutdown: " + r.Err.Error()+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)+ }+ continue+ }+ log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.CheckpointKey)+ if store != nil {+ session, err := store.GetSandboxSession(context.Background(), r.SandboxID)+ if err == nil {+ _, _ = store.CreateCheckpoint(context.Background(), r.SandboxID, session.OrgID,+ r.CheckpointKey, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)+ }+ }+ }++ // 3. Wait for async S3 uploads to complete+ log.Println("opensandbox-worker: waiting for S3 uploads...")+ fcMgr.WaitUploads(3 * time.Minute)+ log.Println("opensandbox-worker: graceful shutdown complete")+ }+ }}diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.shindex 067f59fc..0959ffcf 100755--- a/deploy/ec2/setup-instance.sh+++ b/deploy/ec2/setup-instance.sh@@ -103,37 +103,68 @@ sudo cp /tmp/deploy-ec2/caddy.service /etc/systemd/system/caddy.service 2>/dev/n# NVMe instance storage (XFS with reflink for instant rootfs copies)# -------------------------------------------------------------------echo "==> Installing NVMe boot service..."-sudo apt-get install -y xfsprogs nvme-cli+sudo apt-get install -y xfsprogs nvme-cli mdadmsudo tee /usr/local/bin/opensandbox-nvme-setup.sh > /dev/null << 'NVME'#!/usr/bin/env bashset -euo pipefail-MOUNT_POINT="/data"+MOUNT_POINT="/data/sandboxes"mkdir -p "$MOUNT_POINT"if mountpoint -q "$MOUNT_POINT"; thenecho "opensandbox-nvme: $MOUNT_POINT already mounted"exit 0fi-NVME_DEV=""-for dev in /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1; do- if [ -b "$dev" ]; then- NVME_DEV="$dev"- break- fi++# Find the root EBS device so we can exclude it.+ROOT_DEV=$(lsblk -no PKNAME $(findmnt -n -o SOURCE /) | head -1)++# Collect all NVMe instance store devices (skip the root EBS volume).+NVME_DEVS=()+for dev in /dev/nvme0n1 /dev/nvme1n1 /dev/nvme2n1 /dev/nvme3n1 /dev/nvme4n1; do+ [ -b "$dev" ] || continue+ # Skip if this is the root device+ [ "$(basename "$dev")" = "$ROOT_DEV" ] && continue+ NVME_DEVS+=("$dev")done-if [ -z "$NVME_DEV" ]; then++if [ ${#NVME_DEVS[@]} -eq 0 ]; thenecho "opensandbox-nvme: no NVMe instance storage found, using root disk"mkdir -p "$MOUNT_POINT/sandboxes" "$MOUNT_POINT/firecracker/images" "$MOUNT_POINT/checkpoints"exit 0fi-echo "opensandbox-nvme: formatting $NVME_DEV as XFS with reflink + project quotas"-mkfs.xfs -f -m reflink=1 "$NVME_DEV"-mount -o prjquota "$NVME_DEV" "$MOUNT_POINT"++echo "opensandbox-nvme: found ${#NVME_DEVS[@]} NVMe instance store device(s): ${NVME_DEVS[*]}"++if [ ${#NVME_DEVS[@]} -eq 1 ]; then+ # Single drive — format and mount directly+ DEV="${NVME_DEVS[0]}"+ echo "opensandbox-nvme: formatting $DEV as XFS with project quotas"+ mkfs.xfs -f "$DEV"+ mount -o prjquota "$DEV" "$MOUNT_POINT"+else+ # Multiple drives — RAID-0 for maximum throughput + capacity+ echo "opensandbox-nvme: creating RAID-0 across ${#NVME_DEVS[@]} devices"+ mdadm --create /dev/md0 --level=0 --raid-devices=${#NVME_DEVS[@]} "${NVME_DEVS[@]}" --force --run+ echo "opensandbox-nvme: formatting /dev/md0 as XFS with project quotas"+ mkfs.xfs -f /dev/md0+ mount -o prjquota /dev/md0 "$MOUNT_POINT"+fi+# Create directory structuremkdir -p "$MOUNT_POINT/sandboxes"mkdir -p "$MOUNT_POINT/firecracker/images"mkdir -p "$MOUNT_POINT/checkpoints"-echo "opensandbox-nvme: mounted $NVME_DEV at $MOUNT_POINT"++# Copy Firecracker assets from EBS to NVMe if available+SRC="/opt/opensandbox/firecracker"+DST="$MOUNT_POINT/firecracker"+if [ -d "$SRC" ] && [ ! -f "$DST/vmlinux-arm64" ]; then+ echo "opensandbox-nvme: copying Firecracker assets from $SRC to $DST"+ cp "$SRC/vmlinux-arm64" "$DST/"+ cp "$SRC/images/"* "$DST/images/"+ echo "opensandbox-nvme: assets copied ($(du -sh "$DST" | cut -f1))"+fi+echo "opensandbox-nvme: mounted at $MOUNT_POINT ($(df -h "$MOUNT_POINT" | tail -1 | awk '{print $2}') total)"NVMEsudo chmod +x /usr/local/bin/opensandbox-nvme-setup.sh@@ -252,6 +283,10 @@ Environment=OPENSANDBOX_KERNEL_PATH=/data/firecracker/vmlinux-arm64Environment=OPENSANDBOX_IMAGES_DIR=/data/firecracker/imagesEnvironment=OPENSANDBOX_SECRETS_ARN=arn:aws:secretsmanager:us-east-2:739940681129:secret:opensandbox/worker-vtN2EzEnvironmentFile=/etc/opensandbox/worker-identity.env+# Only signal the main process on stop (not Firecracker children)+# so graceful shutdown can hibernate VMs before they are killed+KillMode=process+TimeoutStopSec=300# Raise limits for many concurrent VMsLimitNOFILE=1000000LimitNPROC=65536diff --git a/internal/config/config.go b/internal/config/config.goindex 49f6d1d6..fff2e174 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -66,7 +66,7 @@ type Config struct {ECRRepository string // e.g. "opensandbox-templates"// Sandbox resource defaults (overridable per-sandbox via API)- DefaultSandboxMemoryMB int // default RAM per sandbox (MB), default 512+ DefaultSandboxMemoryMB int // default RAM per sandbox (MB), default 1024DefaultSandboxCPUs int // default vCPUs per sandbox, default 1DefaultSandboxDiskMB int // default disk quota per sandbox (MB), 0 = no quota@@ -142,7 +142,7 @@ func Load() (*Config, error) {ECRRegistry: os.Getenv("OPENSANDBOX_ECR_REGISTRY"),ECRRepository: envOrDefault("OPENSANDBOX_ECR_REPOSITORY", "opensandbox-templates"),- DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 512),+ DefaultSandboxMemoryMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_MEMORY_MB", 1024),DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex a91c99e3..aff06d83 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -262,15 +262,16 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {log.Printf("redis_registry: gRPC connection initiated to worker %s at %s", workerID, grpcAddr)}-// GetLeastLoadedWorker returns the worker with the most remaining capacity.-// If region is non-empty, only workers in that region are considered.+// GetLeastLoadedWorker returns the worker with the best combination of remaining capacity+// and resource headroom. Workers under heavy resource pressure (CPU > 90% or mem > 90%)+// are skipped. If region is non-empty, only workers in that region are considered.// If no workers match the region, falls back to all workers.func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry, pb.SandboxWorkerClient, error) {r.mu.RLock()defer r.mu.RUnlock()var best *WorkerEntry- bestRemaining := -1+ bestScore := -1.0// First pass: try workers in the requested regionfor _, w := range r.workers {@@ -281,9 +282,16 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,if remaining <= 0 {continue}- if remaining > bestRemaining {+ // Skip workers under heavy resource pressure+ if w.CPUPct > 90 || w.MemPct > 90 {+ continue+ }+ // Score: remaining capacity weighted by resource headroom+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0+ score := float64(remaining) * resourceScore+ if score > bestScore {best = w- bestRemaining = remaining+ bestScore = score}}@@ -294,9 +302,14 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,if remaining <= 0 {continue}- if remaining > bestRemaining {+ if w.CPUPct > 90 || w.MemPct > 90 {+ continue+ }+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0+ score := float64(remaining) * resourceScore+ if score > bestScore {best = w- bestRemaining = remaining+ bestScore = score}}}@@ -402,6 +415,20 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {return result}+// RegionResourcePressure returns the maximum CPU and memory usage across all workers in a region (satisfies ScalerRegistry).+func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem float64) {+ workers := r.GetWorkersByRegion(region)+ for _, w := range workers {+ if w.CPUPct > maxCPU {+ maxCPU = w.CPUPct+ }+ if w.MemPct > maxMem {+ maxMem = w.MemPct+ }+ }+ return maxCPU, maxMem+}+// RegionUtilization returns the average utilization for a region (satisfies ScalerRegistry).func (r *RedisWorkerRegistry) RegionUtilization(region string) float64 {workers := r.GetWorkersByRegion(region)diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 4cd53f0d..fa6b6789 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -2,6 +2,7 @@ package controlplaneimport ("context"+ "fmt""log""sync""time"@@ -15,6 +16,10 @@ const (minWorkersPerRegion = 1maxWorkersPerRegion = 10 // Hard cap to prevent runaway launchespendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register++ // Resource-based scaling thresholds (applied per-worker, trigger on ANY worker exceeding)+ resourceCPUThreshold = 80.0 // Scale up if any worker CPU > 80%+ resourceMemThreshold = 85.0 // Scale up if any worker memory > 85%)// ScalerRegistry is the interface the Scaler uses to query worker state.@@ -23,6 +28,7 @@ type ScalerRegistry interface {Regions() []stringGetWorkersByRegion(region string) []*WorkerInfoRegionUtilization(region string) float64+ RegionResourcePressure(region string) (maxCPU, maxMem float64)}// ScalerConfig configures the autoscaler.@@ -114,23 +120,41 @@ func (s *Scaler) evaluate() {func (s *Scaler) evaluateRegion(ctx context.Context, region string) {workers := s.registry.GetWorkersByRegion(region)utilization := s.registry.RegionUtilization(region)+ maxCPU, maxMem := s.registry.RegionResourcePressure(region)// Expire stale pending launchess.expirePending(region)+ // Determine if we need to scale up: count-based OR resource-based+ needsScaleUp := false+ reason := ""+if utilization > scaleUpThreshold {+ needsScaleUp = true+ reason = fmt.Sprintf("utilization %.1f%% > %.0f%%", utilization*100, scaleUpThreshold*100)+ }+ if !needsScaleUp && maxCPU > resourceCPUThreshold {+ needsScaleUp = true+ reason = fmt.Sprintf("CPU pressure %.1f%% > %.0f%%", maxCPU, resourceCPUThreshold)+ }+ if !needsScaleUp && maxMem > resourceMemThreshold {+ needsScaleUp = true+ reason = fmt.Sprintf("memory pressure %.1f%% > %.0f%%", maxMem, resourceMemThreshold)+ }++ if needsScaleUp {// Check cooldown before scaling upif last, ok := s.lastScaleUp[region]; ok && time.Since(last) < s.cooldown {- log.Printf("scaler: region %s needs scale-up but cooldown active (%s remaining)",- region, s.cooldown-time.Since(last))+ log.Printf("scaler: region %s needs scale-up (%s) but cooldown active (%s remaining)",+ region, reason, s.cooldown-time.Since(last))return}// Don't scale up if there are already pending (unregistered) workerspending := s.pending[region]if len(pending) > 0 {- log.Printf("scaler: region %s needs scale-up but %d worker(s) still pending registration",- region, len(pending))+ log.Printf("scaler: region %s needs scale-up (%s) but %d worker(s) still pending registration",+ region, reason, len(pending))return}@@ -141,7 +165,8 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {return}- log.Printf("scaler: region %s utilization %.1f%% > %.0f%%, scaling up", region, utilization*100, scaleUpThreshold*100)+ log.Printf("scaler: region %s %s, scaling up (cpu=%.1f%% mem=%.1f%% util=%.1f%%)",+ region, reason, maxCPU, maxMem, utilization*100)s.scaleUp(ctx, region)} else if utilization < scaleDownThreshold && len(workers) > minWorkersPerRegion {log.Printf("scaler: region %s utilization %.1f%% < %.0f%%, scaling down", region, utilization*100, scaleDownThreshold*100)diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.goindex 308bf32d..c646e7b6 100644--- a/internal/controlplane/worker_registry.go+++ b/internal/controlplane/worker_registry.go@@ -107,7 +107,8 @@ func (r *WorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {return result}-// GetLeastLoadedWorker returns the worker with the most remaining capacity in a region.+// GetLeastLoadedWorker returns the worker with the best combination of remaining capacity+// and resource headroom in a region. Workers under heavy resource pressure are skipped.func (r *WorkerRegistry) GetLeastLoadedWorker(region string) *WorkerInfo {workers := r.GetWorkersByRegion(region)if len(workers) == 0 {@@ -115,10 +116,22 @@ func (r *WorkerRegistry) GetLeastLoadedWorker(region string) *WorkerInfo {}var best *WorkerInfo+ bestScore := -1.0for _, w := range workers {remaining := w.Capacity - w.Current- if best == nil || remaining > (best.Capacity-best.Current) {+ if remaining <= 0 {+ continue+ }+ // Skip workers under heavy resource pressure+ if w.CPUPct > 90 || w.MemPct > 90 {+ continue+ }+ // Score: remaining capacity weighted by resource headroom+ resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0+ score := float64(remaining) * resourceScore+ if score > bestScore {best = w+ bestScore = score}}return best@@ -161,6 +174,21 @@ func (r *WorkerRegistry) RegionUtilization(region string) float64 {return float64(totalCur) / float64(totalCap)}+// RegionResourcePressure returns the maximum CPU and memory usage across all workers in a region.+// Used by the scaler to detect resource pressure even when count-based utilization is low.+func (r *WorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem float64) {+ workers := r.GetWorkersByRegion(region)+ for _, w := range workers {+ if w.CPUPct > maxCPU {+ maxCPU = w.CPUPct+ }+ if w.MemPct > maxMem {+ maxMem = w.MemPct+ }+ }+ return maxCPU, maxMem+}+// Regions returns all known regions.func (r *WorkerRegistry) Regions() []string {r.mu.RLock()diff --git a/internal/db/store.go b/internal/db/store.goindex 8dd0a67e..7f053e76 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -597,6 +597,56 @@ func (s *Store) UpdateSandboxSessionForWake(ctx context.Context, sandboxID, newWreturn err}+// ReconcileWorkerSessions marks stale "running" sessions for a worker on startup.+// Sessions with an active checkpoint are set to "hibernated" (recoverable via wake-on-request).+// Sessions without a checkpoint are set to "stopped" (VM is gone, no recovery possible).+// Returns the count of sessions transitioned to each state.+func (s *Store) ReconcileWorkerSessions(ctx context.Context, workerID string) (hibernated, stopped int, err error) {+ // First: mark sessions that have an active checkpoint as "hibernated"+ res1, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET status = 'hibernated'+ WHERE worker_id = $1 AND status = 'running'+ AND sandbox_id IN (+ SELECT sandbox_id FROM sandbox_checkpoints+ WHERE restored_at IS NULL AND expired_at IS NULL+ )`, workerID)+ if err != nil {+ return 0, 0, fmt.Errorf("failed to reconcile hibernated sessions: %w", err)+ }++ // Second: mark remaining "running" sessions as "stopped"+ res2, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET status = 'stopped', stopped_at = now(),+ error_msg = 'worker restarted'+ WHERE worker_id = $1 AND status = 'running'`, workerID)+ if err != nil {+ return int(res1.RowsAffected()), 0, fmt.Errorf("failed to reconcile stopped sessions: %w", err)+ }++ return int(res1.RowsAffected()), int(res2.RowsAffected()), nil+}++// UpsertWorkspaceBackup creates or updates a workspace-only backup record for a sandbox.+// Uses checkpoint_key prefix "workspace-backups/" to distinguish from full hibernation checkpoints.+// Only one workspace backup is kept per sandbox (previous is overwritten).+func (s *Store) UpsertWorkspaceBackup(ctx context.Context, sandboxID string, orgID uuid.UUID, backupKey string, sizeBytes int64, region, template string, sandboxConfig json.RawMessage) error {+ // Expire any existing workspace backups for this sandbox+ _, _ = s.pool.Exec(ctx,+ `UPDATE sandbox_checkpoints SET expired_at = now()+ WHERE sandbox_id = $1 AND checkpoint_key LIKE 'workspace-backups/%'+ AND expired_at IS NULL AND restored_at IS NULL`, sandboxID)++ // Insert the new backup+ _, err := s.pool.Exec(ctx,+ `INSERT INTO sandbox_checkpoints (sandbox_id, org_id, checkpoint_key, size_bytes, region, template, sandbox_config)+ VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ sandboxID, orgID, backupKey, sizeBytes, region, template, sandboxConfig)+ if err != nil {+ return fmt.Errorf("failed to upsert workspace backup: %w", err)+ }+ return nil+}+// --- Template operations ---// DBTemplate represents a template record in the database.diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.goindex c9d4d20d..f56668a7 100644--- a/internal/firecracker/manager.go+++ b/internal/firecracker/manager.go@@ -66,9 +66,10 @@ type Manager struct {cfg Configsubnets *SubnetAllocator- mu sync.RWMutex- vms map[string]*VMInstance- nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)+ mu sync.RWMutex+ vms map[string]*VMInstance+ nextCID uint32 // next guest CID to assign (starts at 3, 0-2 are reserved)+ uploadWg sync.WaitGroup // tracks in-flight async S3 uploads}// NewManager creates a new Firecracker-backed sandbox manager.@@ -502,6 +503,69 @@ func (m *Manager) Close() {log.Printf("firecracker: manager closed, %d VMs destroyed", len(vms))}+// WaitUploads blocks until all in-flight async S3 uploads complete,+// or the timeout expires.+func (m *Manager) WaitUploads(timeout time.Duration) {+ done := make(chan struct{})+ go func() {+ m.uploadWg.Wait()+ close(done)+ }()+ select {+ case <-done:+ log.Println("firecracker: all S3 uploads complete")+ case <-time.After(timeout):+ log.Printf("firecracker: timed out waiting for S3 uploads after %s", timeout)+ }+}++// HibernateAllResult holds the result of a single VM hibernation during HibernateAll.+type HibernateAllResult struct {+ SandboxID string+ CheckpointKey string+ Err error+}++// HibernateAll hibernates all running VMs concurrently.+// The local snapshot (syncfs + pause + dump) is fast (~200ms per VM) and runs in parallel.+// S3 uploads happen asynchronously and are tracked by uploadWg.+func (m *Manager) HibernateAll(ctx context.Context, checkpointStore *storage.CheckpointStore) []HibernateAllResult {+ m.mu.RLock()+ ids := make([]string, 0, len(m.vms))+ for id := range m.vms {+ ids = append(ids, id)+ }+ m.mu.RUnlock()++ if len(ids) == 0 {+ return nil+ }++ var results []HibernateAllResult+ var resultsMu sync.Mutex+ var wg sync.WaitGroup++ for _, id := range ids {+ wg.Add(1)+ go func(sandboxID string) {+ defer wg.Done()+ result, err := m.Hibernate(ctx, sandboxID, checkpointStore)++ resultsMu.Lock()+ defer resultsMu.Unlock()+ if err != nil {+ log.Printf("firecracker: HibernateAll: %s failed: %v", sandboxID, err)+ results = append(results, HibernateAllResult{SandboxID: sandboxID, Err: err})+ } else {+ results = append(results, HibernateAllResult{SandboxID: sandboxID, CheckpointKey: result.CheckpointKey})+ }+ }(id)+ }++ wg.Wait()+ return results+}+// Exec runs a command in the VM via the agent.func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {vm, err := m.getVM(sandboxID)@@ -739,3 +803,24 @@ func (m *Manager) GetAgent(sandboxID string) (*AgentClient, error) {}return vm.agent, nil}++// GetWorkspacePath returns the host path to a sandbox's workspace.ext4 drive.+func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return "", err+ }+ return filepath.Join(vm.sandboxDir, "workspace.ext4"), nil+}++// SyncFS flushes filesystem buffers inside the VM via the agent.+func (m *Manager) SyncFS(ctx context.Context, sandboxID string) error {+ vm, err := m.getVM(sandboxID)+ if err != nil {+ return err+ }+ if vm.agent == nil {+ return fmt.Errorf("no agent connection for %s", sandboxID)+ }+ return vm.agent.SyncFS(ctx)+}diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.goindex c4d5ef88..0c6e6e9a 100644--- a/internal/firecracker/snapshot.go+++ b/internal/firecracker/snapshot.go@@ -150,7 +150,9 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// The rootfs is NOT archived — it's recreated from the template on wake.sandboxDir := vm.sandboxDirsandboxID := vm.ID+ m.uploadWg.Add(1)go func() {+ defer m.uploadWg.Done()t1 := time.Now()archivePath := filepath.Join(sandboxDir, "checkpoint.tar.zst")diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.goindex 0ad70e98..3828e98e 100644--- a/internal/proxy/controlplane_proxy.go+++ b/internal/proxy/controlplane_proxy.go@@ -1,6 +1,7 @@package proxyimport (+ "context""fmt""io""log"@@ -15,6 +16,7 @@ import ("github.com/labstack/echo/v4""github.com/opensandbox/opensandbox/internal/controlplane""github.com/opensandbox/opensandbox/internal/db"+ pb "github.com/opensandbox/opensandbox/proto/worker")// ControlPlaneProxy routes subdomain requests to the correct worker.@@ -72,6 +74,8 @@ func (p *ControlPlaneProxy) extractSandboxID(host string) (string, bool) {}// doProxy looks up the worker that owns this sandbox and reverse-proxies to it.+// If the sandbox is hibernated, it triggers a wake-on-request: picks the least+// loaded worker, wakes the sandbox via gRPC, updates the DB, then proxies.func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {ctx := c.Request().Context()@@ -83,11 +87,38 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {})}+ // If the sandbox is hibernated, wake it on-demand before proxying+ if session.Status == "hibernated" {+ worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)+ if err != nil {+ log.Printf("cp-proxy: wake-on-request failed for sandbox %s: %v", sandboxID, err)+ return c.JSON(http.StatusBadGateway, map[string]string{+ "error": fmt.Sprintf("sandbox %s: wake failed: %v", sandboxID, err),+ })+ }++ log.Printf("cp-proxy: wake-on-request succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)++ if isWebSocketUpgrade(c.Request()) {+ return p.doWebSocket(c, sandboxID, workerURL)+ }+ return p.doHTTP(c, sandboxID, workerURL)+ }++ // If the sandbox is stopped/error, return a clear message+ if session.Status == "stopped" || session.Status == "error" {+ return c.JSON(http.StatusGone, map[string]string{+ "error": fmt.Sprintf("sandbox %s has been stopped", sandboxID),+ })+ }++ // Session says "running" — check if the worker is still available.+ // If the worker is gone (e.g., scaled down, restarted), try to recover:+ // check for a checkpoint and wake, or mark as stopped.worker := p.registry.GetWorker(session.WorkerID)if worker == nil {- return c.JSON(http.StatusBadGateway, map[string]string{- "error": fmt.Sprintf("worker %s not available", session.WorkerID),- })+ log.Printf("cp-proxy: sandbox %s session says running on worker %s, but worker not in registry", sandboxID, session.WorkerID)+ return p.tryRecoverOrFail(c, ctx, sandboxID, session)}workerURL := worker.HTTPAddr@@ -107,7 +138,89 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {return p.doHTTP(c, sandboxID, workerURL)}+// tryRecoverOrFail handles the case where a sandbox session says "running" but+// the worker is no longer available. It checks if there's a checkpoint to wake+// from (sandbox may have been hibernated but session not updated). If a checkpoint+// exists, it wakes the sandbox on a new worker. Otherwise, it marks the session+// as stopped and returns a clear error.+func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession) error {+ // Check if there's a checkpoint we can wake from+ checkpoint, err := p.store.GetActiveCheckpoint(ctx, sandboxID)+ if err == nil && checkpoint != nil {+ log.Printf("cp-proxy: sandbox %s has active checkpoint, attempting recovery wake", sandboxID)+ worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)+ if err != nil {+ log.Printf("cp-proxy: recovery wake failed for sandbox %s: %v", sandboxID, err)+ return c.JSON(http.StatusBadGateway, map[string]string{+ "error": fmt.Sprintf("sandbox %s: recovery wake failed: %v", sandboxID, err),+ })+ }++ log.Printf("cp-proxy: recovery wake succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)++ if isWebSocketUpgrade(c.Request()) {+ return p.doWebSocket(c, sandboxID, workerURL)+ }+ return p.doHTTP(c, sandboxID, workerURL)+ }++ // No checkpoint — sandbox is truly gone. Mark session as stopped.+ log.Printf("cp-proxy: sandbox %s has no checkpoint and worker is gone, marking stopped", sandboxID)+ errMsg := "worker lost, sandbox not recoverable"+ _ = p.store.UpdateSandboxSessionStatus(ctx, sandboxID, "stopped", &errMsg)++ return c.JSON(http.StatusGone, map[string]string{+ "error": fmt.Sprintf("sandbox %s is no longer available (worker was lost)", sandboxID),+ })+}++// wakeHibernatedSandbox wakes a hibernated sandbox on-demand when its subdomain+// is accessed. It picks the least loaded worker, sends a WakeSandbox gRPC call,+// and updates the DB. Returns the worker entry and its HTTP address for proxying.+func (p *ControlPlaneProxy) wakeHibernatedSandbox(ctx context.Context, sandboxID string) (*controlplane.WorkerEntry, string, error) {+ // Look up the active checkpoint+ checkpoint, err := p.store.GetActiveCheckpoint(ctx, sandboxID)+ if err != nil {+ return nil, "", fmt.Errorf("no active checkpoint: %w", err)+ }++ // Pick the least loaded worker in the same region+ region := checkpoint.Region+ worker, grpcClient, err := p.registry.GetLeastLoadedWorker(region)+ if err != nil {+ return nil, "", fmt.Errorf("no workers available in region %s: %w", region, err)+ }++ log.Printf("cp-proxy: waking sandbox %s on worker %s (region=%s)", sandboxID, worker.ID, region)++ // Wake via gRPC with a generous timeout (cold boot + S3 download)+ grpcCtx, cancel := context.WithTimeout(ctx, 90*time.Second)+ defer cancel()++ _, err = grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{+ SandboxId: sandboxID,+ CheckpointKey: checkpoint.CheckpointKey,+ Timeout: 300, // default 5 min timeout after wake+ })+ if err != nil {+ return nil, "", fmt.Errorf("gRPC WakeSandbox failed: %w", err)+ }++ // Update DB: mark checkpoint restored, update session to running on new worker+ _ = p.store.MarkCheckpointRestored(ctx, sandboxID)+ _ = p.store.UpdateSandboxSessionForWake(ctx, sandboxID, worker.ID)++ workerURL := worker.HTTPAddr+ if workerURL == "" {+ return nil, "", fmt.Errorf("worker %s has no HTTP address", worker.ID)+ }++ return worker, workerURL, nil+}+// doHTTP reverse-proxies a normal HTTP request to the worker.+// If the worker returns a "not found" error for the sandbox (e.g., after worker restart),+// it marks the session as stopped so future requests get a clean 410.func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string) error {target, err := url.Parse(workerURL)if err != nil {@@ -151,6 +264,21 @@ func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string)})}+ // If the worker returned a 502 with "not found", the sandbox was lost+ // (e.g., worker restarted). Mark the session as stopped so future+ // requests get a clean 410 Gone instead of a confusing 502.+ if rec.statusCode == http.StatusBadGateway {+ body := rec.body.String()+ if strings.Contains(body, "not found") || strings.Contains(body, "not available") {+ log.Printf("cp-proxy: sandbox %s not found on worker, marking session stopped", sandboxID)+ errMsg := "sandbox lost on worker"+ _ = p.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", &errMsg)+ return c.JSON(http.StatusGone, map[string]string{+ "error": fmt.Sprintf("sandbox %s is no longer available", sandboxID),+ })+ }+ }+rec.writeTo(c.Response())return nil}diff --git a/internal/worker/autosave.go b/internal/worker/autosave.gonew file mode 100644index 00000000..3ed53bb7--- /dev/null+++ b/internal/worker/autosave.go@@ -0,0 +1,185 @@+package worker++import (+ "context"+ "fmt"+ "log"+ "os"+ "sync"+ "time"++ fc "github.com/opensandbox/opensandbox/internal/firecracker"+ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/storage"+)++// WorkspaceAutosaver periodically backs up workspace drives to S3.+// On hard kill recovery, a sandbox can cold-boot from template + latest+// workspace backup (processes lost, but user files in /workspace are safe).+type WorkspaceAutosaver struct {+ manager sandbox.Manager+ fcMgr *fc.Manager+ checkpointStore *storage.CheckpointStore+ store *db.Store+ workerID string+ region string+ interval time.Duration+ concurrency int+ stop chan struct{}+ done chan struct{}+}++// NewWorkspaceAutosaver creates a new autosaver.+func NewWorkspaceAutosaver(+ mgr sandbox.Manager,+ fcMgr *fc.Manager,+ checkpointStore *storage.CheckpointStore,+ store *db.Store,+ workerID string,+ region string,+ interval time.Duration,+) *WorkspaceAutosaver {+ return &WorkspaceAutosaver{+ manager: mgr,+ fcMgr: fcMgr,+ checkpointStore: checkpointStore,+ store: store,+ workerID: workerID,+ region: region,+ interval: interval,+ concurrency: 10,+ stop: make(chan struct{}),+ done: make(chan struct{}),+ }+}++// Start begins the periodic backup loop.+func (a *WorkspaceAutosaver) Start() {+ go a.loop()+ log.Printf("autosave: started (interval=%s, concurrency=%d)", a.interval, a.concurrency)+}++// Stop signals the loop to exit and waits for it to finish.+func (a *WorkspaceAutosaver) Stop() {+ close(a.stop)+ <-a.done+ log.Println("autosave: stopped")+}++func (a *WorkspaceAutosaver) loop() {+ defer close(a.done)+ ticker := time.NewTicker(a.interval)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ a.backupAll()+ case <-a.stop:+ return+ }+ }+}++func (a *WorkspaceAutosaver) backupAll() {+ sandboxes, err := a.manager.List(context.Background())+ if err != nil {+ log.Printf("autosave: failed to list sandboxes: %v", err)+ return+ }+ if len(sandboxes) == 0 {+ return+ }++ log.Printf("autosave: backing up %d sandboxes", len(sandboxes))+ t0 := time.Now()++ sem := make(chan struct{}, a.concurrency)+ var wg sync.WaitGroup+ var successCount, failCount int32+ var mu sync.Mutex++ for _, sb := range sandboxes {+ select {+ case <-a.stop:+ log.Printf("autosave: interrupted, skipping remaining backups")+ break+ default:+ }++ wg.Add(1)+ sem <- struct{}{}+ go func(sandboxID string) {+ defer wg.Done()+ defer func() { <-sem }()++ if err := a.backupOne(sandboxID); err != nil {+ log.Printf("autosave: backup failed for %s: %v", sandboxID, err)+ mu.Lock()+ failCount+++ mu.Unlock()+ } else {+ mu.Lock()+ successCount+++ mu.Unlock()+ }+ }(sb.ID)+ }++ wg.Wait()+ log.Printf("autosave: completed in %dms (%d ok, %d failed)",+ time.Since(t0).Milliseconds(), successCount, failCount)+}++func (a *WorkspaceAutosaver) backupOne(sandboxID string) error {+ // 1. SyncFS — flush disk buffers (VM keeps running)+ syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ if err := a.fcMgr.SyncFS(syncCtx, sandboxID); err != nil {+ return fmt.Errorf("syncfs: %w", err)+ }++ // 2. Get workspace path+ wsPath, err := a.fcMgr.GetWorkspacePath(sandboxID)+ if err != nil {+ return fmt.Errorf("workspace path: %w", err)+ }++ // Check file exists and get size+ info, err := os.Stat(wsPath)+ if err != nil {+ return fmt.Errorf("stat workspace: %w", err)+ }++ // 3. Upload workspace.ext4 directly to S3 (no archiving needed for workspace-only backup)+ backupKey := fmt.Sprintf("workspace-backups/%s/%d.ext4", sandboxID, time.Now().Unix())+ uploadCtx, uploadCancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer uploadCancel()++ if _, err := a.checkpointStore.Upload(uploadCtx, backupKey, wsPath); err != nil {+ return fmt.Errorf("s3 upload: %w", err)+ }++ // 4. Update DB with backup record+ if a.store != nil {+ session, err := a.store.GetSandboxSession(context.Background(), sandboxID)+ if err != nil {+ log.Printf("autosave: warning: no session for %s, skipping DB record: %v", sandboxID, err)+ return nil+ }+ if err := a.store.UpsertWorkspaceBackup(+ context.Background(),+ sandboxID,+ session.OrgID,+ backupKey,+ info.Size(),+ a.region,+ session.Template,+ session.Config,+ ); err != nil {+ log.Printf("autosave: warning: failed to record backup for %s: %v", sandboxID, err)+ }+ }++ return nil+}diff --git a/internal/worker/stats.go b/internal/worker/stats.goindex 636f6214..61c59657 100644--- a/internal/worker/stats.go+++ b/internal/worker/stats.go@@ -6,6 +6,8 @@ import ("runtime""strconv""strings"+ "sync"+ "time")// SystemStats returns current CPU and memory usage percentages.@@ -57,25 +59,67 @@ func parseMeminfoKB(line string) uint64 {return val}+// CPU delta tracking for accurate current-load measurement.+// Without delta tracking, /proc/stat gives cumulative averages since boot.+var (+ cpuPrevTotal uint64+ cpuPrevIdle uint64+ cpuMu sync.Mutex+)+func linuxCPUPercent() float64 {- // Read /proc/stat for aggregate CPU time+ cpuMu.Lock()+ defer cpuMu.Unlock()++ total1, idle1 := readProcStat()+ if total1 == 0 {+ return 0.0+ }++ if cpuPrevTotal > 0 {+ // Delta from previous call (typically ~10s ago from heartbeat interval)+ dTotal := total1 - cpuPrevTotal+ dIdle := idle1 - cpuPrevIdle+ cpuPrevTotal = total1+ cpuPrevIdle = idle1+ if dTotal == 0 {+ return 0.0+ }+ return float64(dTotal-dIdle) / float64(dTotal) * 100.0+ }++ // First call: take two samples 500ms apart to get an initial reading+ time.Sleep(500 * time.Millisecond)+ total2, idle2 := readProcStat()+ cpuPrevTotal = total2+ cpuPrevIdle = idle2++ dTotal := total2 - total1+ dIdle := idle2 - idle1+ if dTotal == 0 {+ return 0.0+ }+ return float64(dTotal-dIdle) / float64(dTotal) * 100.0+}++// readProcStat reads the aggregate CPU line from /proc/stat and returns total and idle jiffies.+func readProcStat() (total, idle uint64) {f, err := os.Open("/proc/stat")if err != nil {- return 0.0+ return 0, 0}defer f.Close()scanner := bufio.NewScanner(f)if !scanner.Scan() {- return 0.0+ return 0, 0}line := scanner.Text() // "cpu user nice system idle iowait irq softirq steal"fields := strings.Fields(line)if len(fields) < 5 || fields[0] != "cpu" {- return 0.0+ return 0, 0}- var total, idle uint64for i := 1; i < len(fields); i++ {val, _ := strconv.ParseUint(fields[i], 10, 64)total += val@@ -83,8 +127,5 @@ func linuxCPUPercent() float64 {idle = val}}- if total == 0 {- return 0.0- }- return float64(total-idle) / float64(total) * 100.0+ return total, idle}diff --git a/scripts/test-400-concurrent.sh b/scripts/test-400-concurrent.shnew file mode 100755index 00000000..3f31268b--- /dev/null+++ b/scripts/test-400-concurrent.sh@@ -0,0 +1,298 @@+#!/usr/bin/env bash+set -uo pipefail++# 400-Concurrent Sandbox Load Test+#+# Fires ALL sandbox creates simultaneously — no batching, no mercy.+# Tests real-world worst case: 400 customers show up at once.+#+# Usage: ./scripts/test-400-concurrent.sh [server-url] [api-key] [count]++SERVER="${1:-http://3.135.246.117:8080}"+API_KEY="${2:-osb_600b1a9ba2e515c6e54141588da39204d5123cb4b1a28da22b7bd92b88be1534}"+TOTAL="${3:-400}"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+CYAN='\033[0;36m'+BOLD='\033[1m'+NC='\033[0m'++header() { echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; echo -e "${BOLD}${CYAN} $1${NC}"; echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; }+info() { echo -e "${YELLOW}→${NC} $1"; }+ok() { echo -e "${GREEN}✓${NC} $1"; }+fail() { echo -e "${RED}✗${NC} $1"; }++# Temp dir for results+WORK=$(mktemp -d)+trap "rm -rf $WORK" EXIT++header "CONCURRENT SANDBOX LOAD TEST"+echo -e "Server: ${SERVER}"+echo -e "API Key: ${API_KEY:0:12}..."+echo -e "Target: ${BOLD}${TOTAL} sandboxes — all at once${NC}"+echo -e "Config: 1 vCPU, 1024 MB RAM each"+echo ""++# ─────────────────────────────────────────────────────────+# Phase 1: Fire all creates simultaneously+# ─────────────────────────────────────────────────────────+header "PHASE 1: Launching ${TOTAL} sandboxes simultaneously"++create_one() {+ local idx=$1+ local out="${WORK}/create-${idx}.txt"+ local t0=$(python3 -c 'import time; print(int(time.time()*1000))')++ local resp+ resp=$(curl -s -w "\n%{http_code}" -X POST "${SERVER}/api/sandboxes" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d '{"templateID":"base","timeout":600,"cpuCount":1,"memoryMB":1024}' \+ --max-time 180 2>/dev/null) || true++ local t1=$(python3 -c 'import time; print(int(time.time()*1000))')+ local ms=$((t1 - t0))++ local body http_code+ body=$(echo "$resp" | sed '$d')+ http_code=$(echo "$resp" | tail -1)++ if [[ "$http_code" -ge 200 && "$http_code" -lt 300 ]] 2>/dev/null; then+ local sid+ sid=$(echo "$body" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null) || true+ echo "${sid:-},${ms},ok" > "$out"+ else+ echo ",${ms},fail:${http_code}" > "$out"+ fi+}++export -f create_one+export SERVER API_KEY WORK++info "Firing ${TOTAL} create requests..."+T_START=$(python3 -c 'import time; print(int(time.time()*1000))')++# Launch ALL at once+pids=()+for i in $(seq 1 $TOTAL); do+ create_one $i &+ pids+=($!)+done++info "${#pids[@]} background creates launched, waiting for all to complete..."++# Progress monitor in background+(+ while true; do+ sleep 10+ done_count=$(ls ${WORK}/create-*.txt 2>/dev/null | wc -l | tr -d ' ')+ ok_count=$(grep -l ',ok$' ${WORK}/create-*.txt 2>/dev/null | wc -l | tr -d ' ') || true+ fail_count=$(grep -l ',fail' ${WORK}/create-*.txt 2>/dev/null | wc -l | tr -d ' ') || true+ echo -e " ... ${done_count}/${TOTAL} done (${ok_count} ok, ${fail_count} failed)"+ if [[ "$done_count" -ge "$TOTAL" ]] 2>/dev/null; then break; fi+ done+) &+MONITOR_PID=$!++# Wait for all creates+for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+done++kill $MONITOR_PID 2>/dev/null || true+wait $MONITOR_PID 2>/dev/null || true++T_END=$(python3 -c 'import time; print(int(time.time()*1000))')+WALL_MS=$((T_END - T_START))+WALL_SECS=$(python3 -c "print(f'{$WALL_MS/1000:.1f}')")++# Collect results+SANDBOX_IDS=()+CREATE_TIMES=()+SUCCESS=0+FAIL=0++for f in ${WORK}/create-*.txt; do+ [[ -f "$f" ]] || continue+ line=$(cat "$f")+ id=$(echo "$line" | cut -d, -f1)+ ms=$(echo "$line" | cut -d, -f2)+ status=$(echo "$line" | cut -d, -f3)+ CREATE_TIMES+=("$ms")+ if [[ "$status" == "ok" && -n "$id" ]]; then+ SANDBOX_IDS+=("$id")+ SUCCESS=$((SUCCESS + 1))+ else+ FAIL=$((FAIL + 1))+ fi+done++echo ""+ok "Created: ${SUCCESS}/${TOTAL} sandboxes in ${WALL_SECS}s wall time"+if [[ $FAIL -gt 0 ]]; then+ fail "Failed: ${FAIL}"+ # Show a few failure reasons+ grep ',fail' ${WORK}/create-*.txt 2>/dev/null | head -5 | while read line; do+ echo -e " ${RED}${line}${NC}"+ done+fi++# Timing stats+if [[ ${#CREATE_TIMES[@]} -gt 0 ]]; then+ SORTED=($(printf '%s\n' "${CREATE_TIMES[@]}" | sort -n))+ NUM=${#SORTED[@]}+ MIN_C=${SORTED[0]}+ MAX_C=${SORTED[$((NUM - 1))]}+ MED_C=${SORTED[$((NUM / 2))]}+ P95_C=${SORTED[$((NUM * 95 / 100))]}+ SUM=0; for t in "${SORTED[@]}"; do SUM=$((SUM + t)); done+ AVG_C=$((SUM / NUM))++ echo ""+ echo -e " Create latency (per-request):"+ echo -e " Min: ${MIN_C}ms"+ echo -e " Median: ${MED_C}ms"+ echo -e " Avg: ${AVG_C}ms"+ echo -e " P95: ${P95_C}ms"+ echo -e " Max: ${MAX_C}ms"+ echo -e " Wall: ${WALL_MS}ms"+fi++if [[ $SUCCESS -eq 0 ]]; then+ fail "No sandboxes created — aborting"+ exit 1+fi++# ─────────────────────────────────────────────────────────+# Phase 2: Execute a command on ALL sandboxes+# ─────────────────────────────────────────────────────────+header "PHASE 2: Execute command on all ${SUCCESS} sandboxes simultaneously"++exec_one() {+ local sid=$1+ local out="${WORK}/exec-${sid}.txt"+ local t0=$(python3 -c 'import time; print(int(time.time()*1000))')++ local resp+ resp=$(curl -s -w "\n%{http_code}" -X POST "${SERVER}/api/sandboxes/${sid}/commands" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d '{"cmd":"echo","args":["alive"]}' \+ --max-time 30 2>/dev/null) || true++ local t1=$(python3 -c 'import time; print(int(time.time()*1000))')+ local ms=$((t1 - t0))+ local http_code=$(echo "$resp" | tail -1)++ if [[ "$http_code" == "200" ]] 2>/dev/null; then+ echo "${ms},ok" > "$out"+ else+ echo "${ms},fail:${http_code}" > "$out"+ fi+}++export -f exec_one++info "Firing ${SUCCESS} exec requests..."+T_EXEC_START=$(python3 -c 'import time; print(int(time.time()*1000))')++pids=()+for sid in "${SANDBOX_IDS[@]}"; do+ exec_one "$sid" &+ pids+=($!)+done++for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+done++T_EXEC_END=$(python3 -c 'import time; print(int(time.time()*1000))')+EXEC_WALL=$((T_EXEC_END - T_EXEC_START))++EXEC_OK=0+EXEC_FAIL=0+EXEC_TIMES=()+for sid in "${SANDBOX_IDS[@]}"; do+ line=$(cat "${WORK}/exec-${sid}.txt" 2>/dev/null) || line="0,missing"+ ms=$(echo "$line" | cut -d, -f1)+ st=$(echo "$line" | cut -d, -f2)+ EXEC_TIMES+=("$ms")+ if [[ "$st" == "ok" ]]; then EXEC_OK=$((EXEC_OK + 1)); else EXEC_FAIL=$((EXEC_FAIL + 1)); fi+done++ok "Exec: ${EXEC_OK}/${SUCCESS} succeeded (wall: ${EXEC_WALL}ms)"+if [[ $EXEC_FAIL -gt 0 ]]; then fail "Exec failed: ${EXEC_FAIL}"; fi++if [[ ${#EXEC_TIMES[@]} -gt 0 ]]; then+ SORTED_E=($(printf '%s\n' "${EXEC_TIMES[@]}" | sort -n))+ NUM_E=${#SORTED_E[@]}+ echo -e " Exec latency:"+ echo -e " Min: ${SORTED_E[0]}ms"+ echo -e " Median: ${SORTED_E[$((NUM_E / 2))]}ms"+ echo -e " P95: ${SORTED_E[$((NUM_E * 95 / 100))]}ms"+ echo -e " Max: ${SORTED_E[$((NUM_E - 1))]}ms"+fi++# ─────────────────────────────────────────────────────────+# Phase 3: Worker resource usage snapshot+# ─────────────────────────────────────────────────────────+header "PHASE 3: Worker resource usage with ${SUCCESS} active sandboxes"++ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=10 [email protected] \+ "echo '=== Memory ===' && free -g && echo '' && \+ echo '=== Firecracker VMs ===' && ps aux | grep 'firecracker --api-sock' | grep -v grep | wc -l && echo '' && \+ echo '=== TAP devices ===' && ip link show | grep fc-tap | wc -l && echo '' && \+ echo '=== CPU load ===' && uptime && echo '' && \+ echo '=== Disk ===' && df -h /data" 2>/dev/null || fail "Could not SSH to worker"++# ─────────────────────────────────────────────────────────+# Phase 4: Destroy all sandboxes simultaneously+# ─────────────────────────────────────────────────────────+header "PHASE 4: Destroying ${SUCCESS} sandboxes simultaneously"++T_DEL_START=$(python3 -c 'import time; print(int(time.time()*1000))')++pids=()+for sid in "${SANDBOX_IDS[@]}"; do+ curl -s -X DELETE "${SERVER}/api/sandboxes/${sid}" \+ -H "X-API-Key: ${API_KEY}" --max-time 30 > /dev/null 2>&1 &+ pids+=($!)+done++for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+done++T_DEL_END=$(python3 -c 'import time; print(int(time.time()*1000))')+DEL_MS=$((T_DEL_END - T_DEL_START))++ok "All ${SUCCESS} sandboxes deleted in $((DEL_MS/1000))s"++sleep 5++info "Post-cleanup worker state:"+ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=10 [email protected] \+ "echo 'Firecracker VMs:' && ps aux | grep 'firecracker --api-sock' | grep -v grep | wc -l && \+ echo 'Memory:' && free -g | head -2" 2>/dev/null || true++# ─────────────────────────────────────────────────────────+header "RESULTS SUMMARY"+echo ""+echo -e " ${BOLD}Target:${NC} ${TOTAL} sandboxes"+echo -e " ${BOLD}Created:${NC} ${GREEN}${SUCCESS}${NC} (${FAIL} failed)"+echo -e " ${BOLD}Exec success:${NC} ${GREEN}${EXEC_OK}${NC}/${SUCCESS}"+echo -e " ${BOLD}Create wall time:${NC} ${WALL_SECS}s"+echo -e " ${BOLD}Delete wall time:${NC} $((DEL_MS/1000))s"+if [[ ${#CREATE_TIMES[@]} -gt 0 ]]; then+ echo -e " ${BOLD}Create latency:${NC} min=${MIN_C}ms med=${MED_C}ms avg=${AVG_C}ms p95=${P95_C}ms max=${MAX_C}ms"+fi+echo ""+if [[ $SUCCESS -ge $TOTAL ]]; then+ echo -e " ${BOLD}${GREEN}✓ ALL ${TOTAL} SANDBOXES CREATED AND EXECUTED SUCCESSFULLY${NC}"+else+ echo -e " ${BOLD}${RED}✗ Only ${SUCCESS}/${TOTAL} sandboxes created${NC}"+fi+echo ""diff --git a/scripts/test-noisy-neighbor.sh b/scripts/test-noisy-neighbor.shnew file mode 100755index 00000000..ff846923--- /dev/null+++ b/scripts/test-noisy-neighbor.sh@@ -0,0 +1,337 @@+#!/usr/bin/env bash+set -uo pipefail++# Noisy Neighbor / Resource Pressure Autoscaling Test+#+# Proves that the scaler detects CPU/memory pressure (not just sandbox count)+# and spawns a new worker even when count-based utilization is low.+#+# Flow:+# 1. Create ~50 sandboxes (well below 400 capacity, ~12.5% count util)+# 2. Inject CPU + memory load into each sandbox+# 3. Watch worker CPU/memory climb via /workers endpoint+# 4. Wait for scaler to spawn a new worker based on resource pressure+# 5. Create a new sandbox and verify it routes to the healthy worker+# 6. Cleanup+#+# Usage: ./scripts/test-noisy-neighbor.sh [server-url] [api-key] [count]++SERVER="${1:-http://3.135.246.117:8080}"+API_KEY="${2:-osb_600b1a9ba2e515c6e54141588da39204d5123cb4b1a28da22b7bd92b88be1534}"+TOTAL="${3:-60}"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+CYAN='\033[0;36m'+BOLD='\033[1m'+NC='\033[0m'++header() { echo -e "\n${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; echo -e "${BOLD}${CYAN} $1${NC}"; echo -e "${BOLD}${CYAN}═══════════════════════════════════════════════════════════${NC}"; }+info() { echo -e "${YELLOW}→${NC} $1"; }+ok() { echo -e "${GREEN}✓${NC} $1"; }+fail() { echo -e "${RED}✗${NC} $1"; }++api() {+ local method="$1" path="$2"+ shift 2+ curl -s -w "\n%{http_code}" -X "$method" "${SERVER}/api${path}" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" "$@"+}++api_body() {+ local method="$1" path="$2"+ shift 2+ curl -s -X "$method" "${SERVER}/api${path}" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" "$@"+}++SANDBOX_IDS=()++cleanup() {+ header "CLEANUP"+ if [[ ${#SANDBOX_IDS[@]} -gt 0 ]]; then+ info "Destroying ${#SANDBOX_IDS[@]} sandboxes..."+ local pids=()+ for sid in "${SANDBOX_IDS[@]}"; do+ curl -s -X DELETE "${SERVER}/api/sandboxes/${sid}" \+ -H "X-API-Key: ${API_KEY}" --max-time 10 > /dev/null 2>&1 &+ pids+=($!)+ done+ for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+ done+ ok "All sandboxes destroyed"+ SANDBOX_IDS=()+ fi+ ok "Done"+}+trap cleanup EXIT++worker_count() {+ api_body GET /workers | python3 -c "+import sys,json+d=json.load(sys.stdin)+print(len(d) if isinstance(d,list) else 0)" 2>/dev/null+}++worker_table() {+ api_body GET /workers | python3 -c "+import sys,json+d=json.load(sys.stdin)+if not isinstance(d,list):+ print(' (no workers)')+ sys.exit()+for w in d:+ u = w['current']/w['capacity']*100 if w['capacity']>0 else 0+ print(f\" {w['worker_id'][:12]}... cpu={w.get('cpu_pct',0):.1f}% mem={w.get('mem_pct',0):.1f}% sandboxes={w['current']}/{w['capacity']} ({u:.0f}%)\")" 2>/dev/null+}++worker_ids() {+ api_body GET /workers | python3 -c "+import sys,json+d=json.load(sys.stdin)+if isinstance(d,list):+ for w in d: print(w['worker_id'])" 2>/dev/null+}++worker_resources() {+ api_body GET /workers | python3 -c "+import sys,json+d=json.load(sys.stdin)+if not isinstance(d,list): sys.exit(1)+for w in d:+ print(f\"cpu={w.get('cpu_pct',0):.1f} mem={w.get('mem_pct',0):.1f}\")" 2>/dev/null+}++# ─────────────────────────────────────────────────────────+header "NOISY NEIGHBOR / RESOURCE PRESSURE TEST"+echo -e "Server: ${SERVER}"+echo -e "API Key: ${API_KEY:0:12}..."+echo -e "Target: ${BOLD}${TOTAL} noisy sandboxes${NC}"+echo ""++# ─────────────────────────────────────────────────────────+header "PHASE 1: Baseline"+info "Checking initial worker state..."+for attempt in $(seq 1 12); do+ INITIAL_WORKERS=$(worker_count)+ if [[ "$INITIAL_WORKERS" -gt 0 ]] 2>/dev/null; then break; fi+ sleep 5+done+INITIAL_WORKER_ID=$(worker_ids | head -1)+if [[ -z "$INITIAL_WORKER_ID" ]]; then+ fail "No workers found after 60s"+ exit 1+fi+ok "Workers: $INITIAL_WORKERS Initial: ${INITIAL_WORKER_ID:0:12}..."+worker_table++# ─────────────────────────────────────────────────────────+header "PHASE 2: Create ${TOTAL} sandboxes"+info "Creating ${TOTAL} sandboxes (will be ~${TOTAL}/400 = $(python3 -c "print(f'{${TOTAL}/400*100:.0f}')")% count utilization)..."++WORK=$(mktemp -d)+trap "rm -rf $WORK; cleanup" EXIT++create_one() {+ local idx=$1+ local resp+ resp=$(curl -s -w "\n%{http_code}" -X POST "${SERVER}/api/sandboxes" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d '{"templateID":"base","timeout":900,"cpuCount":1,"memoryMB":1024}' \+ --max-time 120 2>/dev/null) || true++ local body http_code+ body=$(echo "$resp" | sed '$d')+ http_code=$(echo "$resp" | tail -1)++ if [[ "$http_code" -ge 200 && "$http_code" -lt 300 ]] 2>/dev/null; then+ local sid+ sid=$(echo "$body" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null) || true+ echo "$sid" > "${WORK}/create-${idx}.txt"+ else+ echo "FAIL:${http_code}" > "${WORK}/create-${idx}.txt"+ fi+}++export -f create_one+export SERVER API_KEY WORK++# Fire all creates simultaneously+pids=()+for i in $(seq 1 $TOTAL); do+ create_one $i &+ pids+=($!)+done++info "Waiting for ${#pids[@]} creates to complete..."+for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+done++# Collect results+SUCCESS=0+FAIL_COUNT=0+for f in ${WORK}/create-*.txt; do+ [[ -f "$f" ]] || continue+ sid=$(cat "$f")+ if [[ "$sid" == FAIL:* ]]; then+ FAIL_COUNT=$((FAIL_COUNT + 1))+ elif [[ -n "$sid" ]]; then+ SANDBOX_IDS+=("$sid")+ SUCCESS=$((SUCCESS + 1))+ fi+done++ok "Created: ${SUCCESS}/${TOTAL} sandboxes"+if [[ $FAIL_COUNT -gt 0 ]]; then+ fail "Failed: ${FAIL_COUNT}"+fi+worker_table++if [[ $SUCCESS -lt 10 ]]; then+ fail "Too few sandboxes created ($SUCCESS) — aborting"+ exit 1+fi++# ─────────────────────────────────────────────────────────+header "PHASE 3: Inject CPU load into all ${SUCCESS} sandboxes"+info "Running CPU burn (yes >/dev/null) in each sandbox..."+info "Each sandbox pins 1 vCPU at 100% — ${SUCCESS} sandboxes on 64 vCPU host = ~$(python3 -c "print(f'{min(${SUCCESS}/64*100,100):.0f}')")% CPU"++# CPU burn: `yes >/dev/null` pins 1 vCPU at 100%+# No python3 in base image, so we use pure bash/coreutils+LOAD_CMD='{"cmd":"bash","args":["-c","nohup bash -c \"yes >/dev/null\" </dev/null &>/dev/null & echo started"]}'++inject_one() {+ local sid=$1+ curl -s -X POST "${SERVER}/api/sandboxes/${sid}/commands" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d "$LOAD_CMD" \+ --max-time 30 > /dev/null 2>&1+}++export -f inject_one+export LOAD_CMD++pids=()+for sid in "${SANDBOX_IDS[@]}"; do+ inject_one "$sid" &+ pids+=($!)+done++info "Waiting for ${#pids[@]} load injections..."+for pid in "${pids[@]}"; do+ wait $pid 2>/dev/null || true+done++ok "Load injected into all sandboxes"+info "Waiting 15s for load to ramp up and heartbeats to report..."+sleep 15+worker_table++# ─────────────────────────────────────────────────────────+header "PHASE 4: Monitor resource pressure + wait for scale-up"+info "Polling every 15s for resource pressure and new workers..."+info "Scaler triggers at CPU > 80% or memory > 85%"+info "Scale-up cooldown is 5 min, so may take up to ~7 min..."++SCALED=0+for i in $(seq 15 15 600); do+ sleep 15++ # Show current state+ echo ""+ echo -e " ${BOLD}[${i}s]${NC}"+ worker_table++ # Check if a new worker appeared+ CURRENT_WORKERS=$(worker_count)+ if [[ "$CURRENT_WORKERS" -gt "$INITIAL_WORKERS" ]] 2>/dev/null; then+ echo ""+ ok "NEW WORKER DETECTED at ${i}s!"+ NEW_WORKER_ID=$(worker_ids | grep -v "$INITIAL_WORKER_ID" | head -1)+ ok "New worker: ${NEW_WORKER_ID:0:12}..."+ worker_table+ SCALED=1+ break+ fi++ if [[ "$i" -ge 600 ]]; then+ echo ""+ fail "Timed out after 10 min — no new worker spawned"+ info "Checking server logs for scaler activity..."+ # Try to fetch recent scaler logs+ ssh -i ~/.ssh/opensandbox-digger.pem -o StrictHostKeyChecking=no -o ConnectTimeout=5 \+ "sudo journalctl -u opensandbox-server --no-pager -n 30 --grep scaler" 2>/dev/null || true+ exit 1+ fi+done++# ─────────────────────────────────────────────────────────+if [[ $SCALED -eq 1 ]]; then+ header "PHASE 5: Verify new sandbox routes to healthy worker"+ info "Creating a new sandbox — should route to the new (unloaded) worker..."++ RESP=$(curl -s -w "\n%{http_code}" -X POST "${SERVER}/api/sandboxes" \+ -H "X-API-Key: ${API_KEY}" \+ -H "Content-Type: application/json" \+ -d '{"templateID":"base","timeout":300,"cpuCount":1,"memoryMB":1024}' \+ --max-time 120)++ BODY=$(echo "$RESP" | sed '$d')+ HTTP_CODE=$(echo "$RESP" | tail -1)++ if [[ "$HTTP_CODE" -ge 200 && "$HTTP_CODE" -lt 300 ]] 2>/dev/null; then+ NEW_SID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])" 2>/dev/null)+ SANDBOX_IDS+=("$NEW_SID")++ # Check which worker it landed on+ DISCOVER=$(api_body GET "/sandboxes/${NEW_SID}")+ PLACED_WORKER=$(echo "$DISCOVER" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)++ if [[ "$PLACED_WORKER" == "$NEW_WORKER_ID" ]]; then+ ok "New sandbox $NEW_SID → NEW worker ${PLACED_WORKER:0:12}... (resource-aware routing works!)"+ elif [[ "$PLACED_WORKER" != "$INITIAL_WORKER_ID" ]]; then+ ok "New sandbox $NEW_SID → worker ${PLACED_WORKER:0:12}... (not the overloaded one)"+ else+ fail "New sandbox $NEW_SID → OVERLOADED worker ${PLACED_WORKER:0:12}... (routing not resource-aware?)"+ fi++ # Verify exec works on new worker+ EXEC_RESP=$(api_body POST "/sandboxes/${NEW_SID}/commands" -d '{"cmd":"echo","args":["hello from healthy worker"]}')+ STDOUT=$(echo "$EXEC_RESP" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)+ if [[ "$STDOUT" == "hello from healthy worker" ]]; then+ ok "Exec on new worker succeeded"+ else+ fail "Exec on new worker failed: $EXEC_RESP"+ fi+ else+ fail "Could not create verification sandbox: HTTP $HTTP_CODE"+ fi+fi++# ─────────────────────────────────────────────────────────+header "RESULTS SUMMARY"+echo ""+echo -e " ${BOLD}Noisy sandboxes:${NC} ${SUCCESS}"+echo -e " ${BOLD}Initial workers:${NC} ${INITIAL_WORKERS}"+echo -e " ${BOLD}Final workers:${NC} $(worker_count)"+echo -e " ${BOLD}Scale-up triggered:${NC} $([ $SCALED -eq 1 ] && echo -e "${GREEN}YES${NC}" || echo -e "${RED}NO${NC}")"+echo ""+worker_table+echo ""+if [[ $SCALED -eq 1 ]]; then+ echo -e " ${BOLD}${GREEN}✓ RESOURCE-PRESSURE AUTOSCALING WORKS${NC}"+else+ echo -e " ${BOLD}${RED}✗ SCALE-UP NOT TRIGGERED${NC}"+fi+echo ""+info "Cleanup will destroy all ${#SANDBOX_IDS[@]} sandboxes..."