Skip to content

An open-source, faster Devin alternative

TypeScript

more tests

Brian Reardon4bdfad78aa05
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 5fbf2aba..4089b414 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -285,17 +285,32 @@ func main() {
}
}
- // Stale migration recovery — reset sandboxes stuck in 'migrating' state
- if opts.Store != nil {
+ // Background maintenance tasks
+ if opts.Store != nil && redisRegistry != nil {
go func() {
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
for range ticker.C {
- recovered, err := opts.Store.RecoverStaleMigrations(context.Background(), 10*time.Minute)
+ ctx := context.Background()
+
+ // Stale migration recovery
+ recovered, err := opts.Store.RecoverStaleMigrations(ctx, 60*time.Second)
if err != nil {
- log.Printf("stale-migration-recovery: error: %v", err)
+ log.Printf("maintenance: stale migration recovery error: %v", err)
} else if recovered > 0 {
- log.Printf("stale-migration-recovery: reverted %d stale migrations", recovered)
+ log.Printf("maintenance: reverted %d stale migrations", recovered)
+ }
+
+ // DB/worker reconciliation: mark sandboxes on dead workers as error
+ liveWorkers := make(map[string]bool)
+ for _, w := range redisRegistry.GetAllWorkers() {
+ liveWorkers[w.ID] = true
+ }
+ orphaned, err := opts.Store.MarkOrphanedSandboxes(ctx, liveWorkers)
+ if err != nil {
+ log.Printf("maintenance: orphan reconciliation error: %v", err)
+ } else if orphaned > 0 {
+ log.Printf("maintenance: marked %d sandboxes as error (worker lost)", orphaned)
}
}
}()
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 43176023..3c908508 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -578,6 +578,10 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
s.cleanupPreviewURLs(c.Request().Context(), sandboxID)
+ if s.sandboxAPIProxy != nil {
+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
+ }
+
return c.NoContent(http.StatusNoContent)
}
@@ -1263,6 +1267,10 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error
session.Region, session.Template, session.Config)
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "hibernated", nil)
+ if s.sandboxAPIProxy != nil {
+ s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
+ }
+
resp := map[string]interface{}{
"sandboxID": sandboxID,
"status": "hibernated",
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index d2639334..48e96b82 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -8,6 +8,7 @@ import (
"log"
"strings"
"sync"
+ "time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
@@ -186,10 +187,28 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machi
}, nil)
if err != nil {
log.Printf("azure: VM %s BeginCreateOrUpdate error detail: %+v", vmName, err)
+ // Clean up orphaned NIC
+ go func() {
+ cleanCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if delPoller, delErr := p.nicClient.BeginDelete(cleanCtx, p.cfg.ResourceGroup, nicName, nil); delErr == nil {
+ delPoller.PollUntilDone(cleanCtx, nil)
+ log.Printf("azure: cleaned up orphaned NIC %s", nicName)
+ }
+ }()
return nil, fmt.Errorf("azure: create VM %s failed: %w", vmName, err)
}
vmResp, err := vmPoller.PollUntilDone(ctx, nil)
if err != nil {
+ // Clean up orphaned NIC on poll failure too
+ go func() {
+ cleanCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if delPoller, delErr := p.nicClient.BeginDelete(cleanCtx, p.cfg.ResourceGroup, nicName, nil); delErr == nil {
+ delPoller.PollUntilDone(cleanCtx, nil)
+ log.Printf("azure: cleaned up orphaned NIC %s after poll failure", nicName)
+ }
+ }()
return nil, fmt.Errorf("azure: VM %s poll failed: %w", vmName, err)
}
log.Printf("azure: VM %s created successfully", vmName)
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index d073e069..c9ca03f2 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -778,13 +778,20 @@ func (s *Scaler) checkDrainingWorkers(ctx context.Context, region string) {
continue
}
- // Check if drain timed out — do NOT hibernate or destroy.
- // Sandboxes must be preserved. Cancel the drain and let the worker
- // keep running. The sandboxes will naturally expire or be manually cleaned up.
+ // Check if drain timed out
if time.Since(state.startedAt) > drainTimeout {
- log.Printf("scaler: drain timeout for worker %s (machine=%s) after %s — cancelling drain, keeping worker alive with %d sandboxes",
- state.workerID, machineID, drainTimeout, s.getDrainingWorkerSandboxCount(state.workerID))
- delete(s.draining, machineID)
+ sandboxCount := s.getDrainingWorkerSandboxCount(state.workerID)
+ if sandboxCount == 0 {
+ // Sandboxes expired naturally — safe to destroy
+ log.Printf("scaler: drain timeout for worker %s but 0 sandboxes remain, destroying", state.workerID)
+ s.destroyDrainedMachine(machineID)
+ delete(s.draining, machineID)
+ } else {
+ // Still has sandboxes — cancel drain, keep worker alive
+ log.Printf("scaler: drain timeout for worker %s (machine=%s) with %d sandboxes — cancelling drain, keeping alive",
+ state.workerID, machineID, sandboxCount)
+ delete(s.draining, machineID)
+ }
continue
}
diff --git a/internal/db/store.go b/internal/db/store.go
index cd93f05e..7d9a6403 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -533,6 +533,37 @@ func (s *Store) RecoverStaleMigrations(ctx context.Context, maxAge time.Duration
return int(tag.RowsAffected()), nil
}
+// MarkOrphanedSandboxes marks running sandboxes on dead workers as error.
+// liveWorkers is the set of worker IDs currently registered.
+func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[string]bool) (int, error) {
+ // Get all distinct worker_ids with running sandboxes
+ rows, err := s.pool.Query(ctx,
+ `SELECT DISTINCT worker_id FROM sandbox_sessions WHERE status = 'running'`)
+ if err != nil {
+ return 0, err
+ }
+ defer rows.Close()
+
+ total := 0
+ for rows.Next() {
+ var workerID string
+ if err := rows.Scan(&workerID); err != nil {
+ continue
+ }
+ if liveWorkers[workerID] {
+ continue
+ }
+ // Worker not in registry — mark its sandboxes as error
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()
+ WHERE worker_id = $1 AND status = 'running'`, workerID)
+ if err == nil {
+ total += int(tag.RowsAffected())
+ }
+ }
+ return total, nil
+}
+
func (s *Store) GetSandboxSession(ctx context.Context, sandboxID string) (*SandboxSession, error) {
session := &SandboxSession{}
err := s.pool.QueryRow(ctx,
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
index 7797ff02..d03b5872 100644
--- a/internal/proxy/sandbox_api_proxy.go
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -39,7 +39,7 @@ type routeCacheEntry struct {
expiresAt time.Time
}
-const routeCacheTTL = 10 * time.Second
+const routeCacheTTL = 3 * time.Second
func newProxyRouteCache() *proxyRouteCache {
return &proxyRouteCache{entries: make(map[string]*routeCacheEntry)}
diff --git a/scripts/qemu-tests/32-stress-all.sh b/scripts/qemu-tests/32-stress-all.sh
new file mode 100755
index 00000000..82ee014b
--- /dev/null
+++ b/scripts/qemu-tests/32-stress-all.sh
@@ -0,0 +1,308 @@
+#!/usr/bin/env bash
+# 32-stress-all.sh — Comprehensive stress test covering all system features
+#
+# 20 worst-case scenarios testing: autoscaling, migration, failover,
+# state machine, route cache, resource pressure, and recovery.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+declare -a ALL_SANDBOXES=()
+
+cleanup_all() {
+ echo ""
+ echo "=== Cleanup: ${#ALL_SANDBOXES[@]} sandboxes ==="
+ for sb in "${ALL_SANDBOXES[@]+"${ALL_SANDBOXES[@]}"}"; do
+ destroy_sandbox "$sb" &
+ done
+ wait 2>/dev/null || true
+ echo "Done"
+}
+trap cleanup_all EXIT INT TERM
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+worker_count() { get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null || echo "0"; }
+
+# Destroy all tracked sandboxes mid-test to avoid accumulation
+flush_sandboxes() {
+ for sb in "${ALL_SANDBOXES[@]+"${ALL_SANDBOXES[@]}"}"; do
+ [ -n "$sb" ] && destroy_sandbox "$sb" >/dev/null 2>&1 &
+ done
+ wait 2>/dev/null || true
+ ALL_SANDBOXES=()
+}
+
+create_sb() {
+ local result=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ local sb=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ if [ -n "$sb" ] && [ "$sb" != "" ]; then
+ ALL_SANDBOXES+=("$sb")
+ echo "$sb"
+ fi
+}
+
+exec_check() {
+ local sb="$1"
+ local out=$(exec_stdout "$sb" "echo" "ok" 2>/dev/null)
+ [ "$out" = "ok" ]
+}
+
+# ============================================================
+h "Test 1: Basic create + exec + destroy"
+SB=$(create_sb)
+exec_check "$SB" && pass "Create + exec" || fail "Create + exec"
+destroy_sandbox "$SB"
+ALL_SANDBOXES=("${ALL_SANDBOXES[@]/$SB}")
+
+# ============================================================
+h "Test 2: Migration under load (sandbox survives, others unaffected)"
+SB1=$(create_sb); SB2=$(create_sb); SB3=$(create_sb)
+exec_check "$SB1" && exec_check "$SB2" && exec_check "$SB3" || fail "Pre-migration exec"
+SRC=$(api "$API_URL/api/sandboxes/$SB1" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC']" 2>/dev/null | head -1)
+if [ -n "$TGT" ]; then
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB1/migrate" -d "{\"targetWorker\":\"$TGT\"}" >/dev/null 2>&1
+ exec_check "$SB1" && pass "Migrated sandbox responsive" || fail "Migrated sandbox unresponsive"
+ exec_check "$SB2" && pass "Non-migrated sandbox unaffected" || fail "Non-migrated sandbox affected"
+else
+ skip "No target worker for migration"
+fi
+
+# ============================================================
+h "Test 3: Migration state blocks exec (503 during migration)"
+# We can't easily catch the 503 mid-flight since migration is <1s.
+# Instead verify the state machine by checking DB status transitions.
+SB4=$(create_sb)
+BEFORE=$(api "$API_URL/api/sandboxes/$SB4" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)
+[ "$BEFORE" = "running" ] && pass "Status is 'running' before migration" || fail "Status: $BEFORE"
+
+# ============================================================
+h "Test 4: Route cache invalidation (exec after migration routes correctly)"
+SB5=$(create_sb)
+# Warm the route cache with an exec
+exec_check "$SB5"
+SRC5=$(api "$API_URL/api/sandboxes/$SB5" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT5=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC5']" 2>/dev/null | head -1)
+if [ -n "$TGT5" ]; then
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB5/migrate" -d "{\"targetWorker\":\"$TGT5\"}" >/dev/null 2>&1
+ # Exec immediately — cache should be invalidated
+ exec_check "$SB5" && pass "Route cache invalidated after migration" || fail "Route cache stale"
+else
+ skip "No target worker"
+fi
+
+# ============================================================
+h "Test 5: Burst creation (20 sandboxes in parallel)"
+BURST_DIR=$(mktemp -d)
+for i in $(seq 1 20); do
+ (
+ result=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ sb=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ [ -n "$sb" ] && echo "$sb" > "$BURST_DIR/$i"
+ ) &
+done
+wait
+BURST_OK=$(ls "$BURST_DIR" 2>/dev/null | wc -l | tr -d ' ')
+# Track for cleanup
+for f in "$BURST_DIR"/*; do [ -f "$f" ] && ALL_SANDBOXES+=("$(cat "$f")"); done
+rm -rf "$BURST_DIR"
+[ "$BURST_OK" -ge 15 ] && pass "Burst: $BURST_OK/20 created" || fail "Burst: only $BURST_OK/20"
+
+# ============================================================
+h "Test 6: Rapid create/destroy cycle (leak test)"
+WORKERS_BEFORE=$(worker_count)
+for i in $(seq 1 10); do
+ sb=$(create_sb)
+ [ -n "$sb" ] && destroy_sandbox "$sb"
+done
+WORKERS_AFTER=$(worker_count)
+[ "$WORKERS_AFTER" -le $((WORKERS_BEFORE + 1)) ] && pass "No worker leak after rapid create/destroy" || fail "Workers grew: $WORKERS_BEFORE → $WORKERS_AFTER"
+
+flush_sandboxes
+sleep 2
+
+# ============================================================
+h "Test 7: Write data, migrate, verify data survives"
+SB7=$(create_sb)
+exec_run "$SB7" "sh" "-c" "echo persist-test-$(date +%s) > /workspace/data.txt" >/dev/null 2>&1
+BEFORE_DATA=$(exec_stdout "$SB7" "cat" "/workspace/data.txt" 2>/dev/null)
+SRC7=$(api "$API_URL/api/sandboxes/$SB7" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT7=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC7']" 2>/dev/null | head -1)
+if [ -n "$TGT7" ]; then
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB7/migrate" -d "{\"targetWorker\":\"$TGT7\"}" >/dev/null 2>&1
+ AFTER_DATA=$(exec_stdout "$SB7" "cat" "/workspace/data.txt" 2>/dev/null)
+ [ "$BEFORE_DATA" = "$AFTER_DATA" ] && pass "Data survived migration: $AFTER_DATA" || fail "Data lost: before=$BEFORE_DATA after=$AFTER_DATA"
+else
+ skip "No target worker"
+fi
+
+# ============================================================
+h "Test 8: Double migration rejected"
+SB8=$(create_sb)
+SRC8=$(api "$API_URL/api/sandboxes/$SB8" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT8=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC8']" 2>/dev/null | head -1)
+if [ -n "$TGT8" ]; then
+ # Start migration and immediately try another
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB8/migrate" -d "{\"targetWorker\":\"$TGT8\"}" >/dev/null 2>&1 &
+ sleep 0.1
+ DOUBLE=$(api -X POST "$API_URL/api/sandboxes/$SB8/migrate" -d "{\"targetWorker\":\"$SRC8\"}" 2>/dev/null)
+ wait
+ echo "$DOUBLE" | grep -qi "migrating\|not running\|must be running" && pass "Double migration rejected" || skip "Double migration timing — migration too fast to catch"
+else
+ skip "No target worker"
+fi
+
+# ============================================================
+h "Test 9: Control plane restart (sandboxes survive)"
+SB9=$(create_sb)
+exec_check "$SB9" || fail "Pre-restart exec"
+# We can't restart the CP from here without az run-command which is slow.
+# Instead verify the sandbox is in the DB and accessible.
+STATUS9=$(api "$API_URL/api/sandboxes/$SB9" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)
+[ "$STATUS9" = "running" ] && pass "Sandbox persisted in DB" || fail "Sandbox status: $STATUS9"
+
+# ============================================================
+h "Test 10: Exec timeout doesn't affect other sandboxes"
+SB10A=$(create_sb); SB10B=$(create_sb)
+# Start a long exec on A
+exec_run "$SB10A" "sleep" "10" >/dev/null 2>&1 &
+LONG_PID=$!
+# Immediately exec on B — should work fine
+exec_check "$SB10B" && pass "Exec on B unaffected by long exec on A" || fail "Exec on B blocked"
+kill $LONG_PID 2>/dev/null; wait $LONG_PID 2>/dev/null || true
+
+# ============================================================
+h "Test 11: Memory scaling (4GB → 8GB → 4GB)"
+SB11=$(create_sb)
+SCALE_UP=$(api -X PUT "$API_URL/api/sandboxes/$SB11/limits" -d '{"memoryMB":8192,"cpuPercent":200}' 2>/dev/null)
+echo "$SCALE_UP" | grep -q "ok" && pass "Scale up to 8GB" || fail "Scale up: $SCALE_UP"
+sleep 1
+MEM=$(exec_stdout "$SB11" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+[ -n "$MEM" ] && [ "$MEM" -gt 7000 ] && pass "Memory at ${MEM}MB" || fail "Memory: ${MEM}MB (expected >7000)"
+SCALE_DOWN=$(api -X PUT "$API_URL/api/sandboxes/$SB11/limits" -d '{"memoryMB":4096,"cpuPercent":100}' 2>/dev/null)
+echo "$SCALE_DOWN" | grep -q "ok" && pass "Scale down to 4GB" || fail "Scale down: $SCALE_DOWN"
+
+# ============================================================
+h "Test 12: Sandbox survives heavy CPU load"
+SB12=$(create_sb)
+# Fire-and-forget CPU stress in background, then verify sandbox still responsive
+exec_run "$SB12" "sh" "-c" "for i in 1 2 3 4; do (while true; do :; done) & done; sleep 5; kill 0 2>/dev/null; true" >/dev/null 2>&1 &
+STRESS_PID=$!
+sleep 2
+# While stress is running, sandbox should still accept exec
+exec_check "$SB12" && pass "Sandbox survived CPU stress" || fail "Sandbox dead after CPU stress"
+kill $STRESS_PID 2>/dev/null; wait $STRESS_PID 2>/dev/null || true
+
+# ============================================================
+h "Test 13: Sandbox survives memory pressure"
+SB13=$(create_sb)
+api -X PUT "$API_URL/api/sandboxes/$SB13/limits" -d '{"memoryMB":4096,"cpuPercent":100}' >/dev/null 2>&1
+sleep 1
+TIMEOUT=60 exec_run "$SB13" "python3" "-c" "x=bytearray(2*1024*1024*1024); print(len(x))" >/dev/null 2>&1
+exec_check "$SB13" && pass "Sandbox survived memory pressure" || fail "Sandbox dead after memory pressure"
+
+flush_sandboxes
+sleep 2
+
+# ============================================================
+h "Test 14: Multiple sandboxes on same worker all respond"
+declare -a BATCH=()
+for i in $(seq 1 8); do
+ sb=$(create_sb)
+ [ -n "$sb" ] && BATCH+=("$sb")
+done
+OK=0
+for sb in "${BATCH[@]}"; do
+ exec_check "$sb" && OK=$((OK+1))
+done
+[ "$OK" -eq "${#BATCH[@]}" ] && pass "All ${#BATCH[@]} sandboxes responsive" || fail "Only $OK/${#BATCH[@]} responsive"
+
+# ============================================================
+h "Test 15: Migrate sandbox back and forth"
+SB15=$(create_sb)
+W1=$(api "$API_URL/api/sandboxes/$SB15" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+W2=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$W1']" 2>/dev/null | head -1)
+if [ -n "$W2" ]; then
+ # Migrate to W2
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB15/migrate" -d "{\"targetWorker\":\"$W2\"}" >/dev/null 2>&1
+ exec_check "$SB15" || fail "Dead after first migration"
+ # Migrate back to W1
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB15/migrate" -d "{\"targetWorker\":\"$W1\"}" >/dev/null 2>&1
+ exec_check "$SB15" && pass "Sandbox survived round-trip migration" || fail "Dead after round-trip"
+else
+ skip "No target worker"
+fi
+
+# ============================================================
+h "Test 16: PID 1 and init survive migration"
+SB16=$(create_sb)
+# Check PID 1 exists before migration
+PID1_BEFORE=$(exec_stdout "$SB16" "cat" "/proc/1/status" 2>/dev/null | head -1)
+SRC16=$(api "$API_URL/api/sandboxes/$SB16" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT16=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC16']" 2>/dev/null | head -1)
+if [ -n "$TGT16" ]; then
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB16/migrate" -d "{\"targetWorker\":\"$TGT16\"}" >/dev/null 2>&1
+ PID1_AFTER=$(exec_stdout "$SB16" "cat" "/proc/1/status" 2>/dev/null | head -1)
+ UPTIME=$(exec_stdout "$SB16" "cat" "/proc/uptime" 2>/dev/null | awk '{print $1}')
+ [ -n "$PID1_AFTER" ] && pass "PID 1 alive after migration (uptime: ${UPTIME}s)" || fail "PID 1 dead after migration"
+else
+ skip "No target worker"
+fi
+
+# ============================================================
+h "Test 17: Filesystem writes persist across migration"
+SB17=$(create_sb)
+exec_run "$SB17" "sh" "-c" "dd if=/dev/urandom of=/workspace/bigfile.bin bs=1M count=10 2>/dev/null" >/dev/null 2>&1
+HASH_BEFORE=$(exec_stdout "$SB17" "md5sum" "/workspace/bigfile.bin" 2>/dev/null | awk '{print $1}')
+SRC17=$(api "$API_URL/api/sandboxes/$SB17" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+TGT17=$(get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin) if w['worker_id']!='$SRC17']" 2>/dev/null | head -1)
+if [ -n "$TGT17" ]; then
+ TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB17/migrate" -d "{\"targetWorker\":\"$TGT17\"}" >/dev/null 2>&1
+ HASH_AFTER=$(exec_stdout "$SB17" "md5sum" "/workspace/bigfile.bin" 2>/dev/null | awk '{print $1}')
+ [ "$HASH_BEFORE" = "$HASH_AFTER" ] && pass "10MB file hash matches after migration" || fail "Hash mismatch: $HASH_BEFORE vs $HASH_AFTER"
+else
+ skip "No target worker"
+fi
+
+flush_sandboxes
+sleep 2
+
+# ============================================================
+h "Test 18: Network connectivity inside sandbox"
+SB18=$(create_sb)
+PING=$(exec_stdout "$SB18" "python3" "-c" "import urllib.request; print(urllib.request.urlopen('http://ifconfig.me', timeout=5).read().decode().strip())" 2>/dev/null)
+[ -n "$PING" ] && pass "Sandbox has internet: $PING" || skip "No internet (may be expected)"
+
+# ============================================================
+h "Test 19: Sandbox metadata endpoint"
+SB19=$(create_sb)
+META=$(exec_stdout "$SB19" "curl" "-s" "http://169.254.169.254/v1/status" 2>/dev/null)
+echo "$META" | grep -q "sandboxId" && pass "Metadata endpoint works" || fail "Metadata: $META"
+
+# ============================================================
+h "Test 20: Destroy during exec (graceful)"
+SB20=$(create_sb)
+# Start a long exec
+exec_run "$SB20" "sleep" "30" >/dev/null 2>&1 &
+EXEC_PID=$!
+sleep 1
+# Destroy while exec is running
+destroy_sandbox "$SB20"
+ALL_SANDBOXES=("${ALL_SANDBOXES[@]/$SB20}")
+wait $EXEC_PID 2>/dev/null || true
+pass "Destroy during exec completed without hang"
+
+# ============================================================
+h "Final state"
+echo "Workers:"
+get_workers | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(f' {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]}')
+" 2>/dev/null
+echo "Sandboxes to clean: ${#ALL_SANDBOXES[@]}"
+
+summary
diff --git a/scripts/qemu-tests/33-pressure-tests.sh b/scripts/qemu-tests/33-pressure-tests.sh
new file mode 100755
index 00000000..69fe3520
--- /dev/null
+++ b/scripts/qemu-tests/33-pressure-tests.sh
@@ -0,0 +1,542 @@
+#!/usr/bin/env bash
+# 33-pressure-tests.sh — Push workers to RAM, disk, and CPU pressure limits
+#
+# Tests the scaler's response to resource pressure:
+# - Scale-up triggers (70% CPU/mem, 60% disk)
+# - Evacuation triggers (80% CPU/mem, 70% disk)
+# - Emergency hibernation (95% CPU/mem, 90% disk)
+# - Hard rejection (90% CPU/mem in routing)
+# - Mix-and-match combinations
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+declare -a ALL_SANDBOXES=()
+
+cleanup_all() {
+ echo ""
+ echo "=== Cleanup: ${#ALL_SANDBOXES[@]} sandboxes ==="
+ for sb in "${ALL_SANDBOXES[@]+"${ALL_SANDBOXES[@]}"}"; do
+ [ -n "$sb" ] && destroy_sandbox "$sb" &
+ done
+ wait 2>/dev/null || true
+ echo "Done"
+}
+trap cleanup_all EXIT INT TERM
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+
+worker_stats() {
+ get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+for w in workers:
+ print(f' {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]} cpu={w[\"cpu_pct\"]:.0f}% mem={w[\"mem_pct\"]:.0f}% disk={w[\"disk_pct\"]:.0f}%')
+" 2>/dev/null
+}
+
+create_sb() {
+ local result
+ result=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ local sb
+ sb=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)
+ if [ -n "$sb" ] && [ "$sb" != "" ]; then
+ echo "$sb"
+ fi
+}
+
+# Track sandbox for cleanup (must call in parent shell, not subshell)
+track_sb() {
+ ALL_SANDBOXES+=("$1")
+}
+
+exec_check() {
+ local sb="$1"
+ local out
+ out=$(exec_stdout "$sb" "echo" "ok" 2>/dev/null)
+ [ "$out" = "ok" ]
+}
+
+flush_sandboxes() {
+ echo " Cleaning up all sandboxes..."
+ local sbs
+ sbs=$(api "$API_URL/api/sandboxes" 2>/dev/null | python3 -c "
+import sys, json
+for s in json.load(sys.stdin):
+ print(s.get('sandboxID', ''))
+" 2>/dev/null || true)
+ local count=0
+ for sb in $sbs; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & count=$((count+1)); }
+ done
+ wait 2>/dev/null || true
+ ALL_SANDBOXES=()
+ echo " Destroyed $count sandboxes"
+ sleep 5
+}
+
+# Wait for worker stats to update (heartbeats every 10s)
+wait_stats() {
+ local msg="${1:-Waiting for stats update}"
+ echo " $msg (15s for heartbeat)..."
+ sleep 15
+}
+
+# Get a specific worker's stat
+worker_stat() {
+ local worker_id="$1" field="$2"
+ get_workers | python3 -c "
+import sys, json
+for w in json.load(sys.stdin):
+ if w['worker_id'] == '$worker_id':
+ print(f'{w[\"$field\"]:.1f}')
+ break
+" 2>/dev/null
+}
+
+# Pick one specific worker to target (the one with fewer sandboxes)
+pick_target_worker() {
+ get_workers | python3 -c "
+import sys, json
+workers = sorted(json.load(sys.stdin), key=lambda w: w['current'])
+print(workers[0]['worker_id'])
+" 2>/dev/null
+}
+
+# Get worker HTTP addr for a sandbox
+sandbox_worker() {
+ local sb="$1"
+ api "$API_URL/api/sandboxes/$sb" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null
+}
+
+echo "=== Resource Pressure Tests ==="
+echo "Starting state:"
+worker_stats
+
+# ============================================================
+# TEST 1: RAM PRESSURE
+# ============================================================
+h "Test 1: RAM pressure — scale sandboxes until memory triggers scaler response"
+
+# Create sandboxes on a target worker and scale them up to consume memory
+TARGET=$(pick_target_worker)
+echo " Target worker: $TARGET"
+echo " Strategy: Create 6 sandboxes, scale each to 8GB → ~48GB committed on 64GB host"
+
+declare -a RAM_SBS=()
+for i in $(seq 1 6); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ RAM_SBS+=("$sb")
+ echo " Created $sb (#$i)"
+ fi
+done
+
+echo " Scaling all to 8GB..."
+SCALE_OK=0
+for sb in "${RAM_SBS[@]}"; do
+ result=$(api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":8192,"cpuPercent":200}' 2>/dev/null)
+ if echo "$result" | grep -q "ok"; then
+ SCALE_OK=$((SCALE_OK+1))
+ else
+ echo " Scale failed for $sb: $result"
+ fi
+done
+echo " Scaled $SCALE_OK/${#RAM_SBS[@]} to 8GB"
+
+echo " Allocating 6GB inside each VM to create real memory pressure..."
+for sb in "${RAM_SBS[@]}"; do
+ TIMEOUT=30 exec_run "$sb" "sh" "-c" "python3 -c 'x=bytearray(6*1024*1024*1024); import time; time.sleep(120)' &" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+wait_stats "Waiting for memory pressure to register"
+echo " Worker stats after RAM pressure:"
+worker_stats
+
+# Check that the system responded — mem should be high on at least one worker
+MAX_MEM=$(get_workers | python3 -c "
+import sys, json
+workers = json.load(sys.stdin)
+print(f'{max(w[\"mem_pct\"] for w in workers):.0f}')
+" 2>/dev/null)
+echo " Peak memory: ${MAX_MEM}%"
+[ "${MAX_MEM:-0}" -gt 10 ] && pass "RAM pressure visible: peak ${MAX_MEM}%" || fail "RAM pressure not visible (peak ${MAX_MEM}%)"
+
+# Verify sandboxes are still responsive under memory pressure
+RESPONSIVE=0
+for sb in "${RAM_SBS[@]}"; do
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+[ "$RESPONSIVE" -eq "${#RAM_SBS[@]}" ] && pass "All $RESPONSIVE sandboxes responsive under RAM pressure" || fail "Only $RESPONSIVE/${#RAM_SBS[@]} responsive"
+
+# Try to scale one more to 16GB — should hit insufficient_capacity on a full worker
+echo " Attempting to scale one sandbox to 16GB (should stress committed memory)..."
+BIG_RESULT=$(api -X PUT "$API_URL/api/sandboxes/${RAM_SBS[0]}/limits" -d '{"memoryMB":16384,"cpuPercent":200}' 2>/dev/null)
+echo " Result: $BIG_RESULT"
+if echo "$BIG_RESULT" | grep -qi "insufficient_capacity\|migrat"; then
+ pass "System detected insufficient capacity and responded"
+elif echo "$BIG_RESULT" | grep -q "ok"; then
+ pass "Scale to 16GB succeeded (worker had room)"
+else
+ fail "Unexpected response: $BIG_RESULT"
+fi
+
+# New sandbox creation should still work (routes to less-loaded worker)
+NEW_SB=$(create_sb)
+if [ -n "$NEW_SB" ]; then
+ exec_check "$NEW_SB" && pass "New sandbox created and responsive under RAM pressure" || fail "New sandbox unresponsive"
+else
+ fail "Could not create sandbox under RAM pressure"
+fi
+
+flush_sandboxes
+
+# ============================================================
+# TEST 2: DISK PRESSURE
+# ============================================================
+h "Test 2: Disk pressure — fill sandbox disks until worker disk_pct rises"
+
+# Create sandboxes and write large files to consume disk
+# Workers have NVMe temp disk mounted at /data — sandboxes live there
+echo " Strategy: Create 4 sandboxes, write 5GB each → 20GB disk consumed"
+
+declare -a DISK_SBS=()
+for i in $(seq 1 4); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ DISK_SBS+=("$sb")
+ echo " Created $sb (#$i)"
+ fi
+done
+
+echo " Baseline disk stats:"
+worker_stats
+
+echo " Writing 5GB files in each sandbox (parallel)..."
+for sb in "${DISK_SBS[@]}"; do
+ TIMEOUT=120 exec_run "$sb" "sh" "-c" "dd if=/dev/zero of=/workspace/bigfile bs=1M count=5120 2>/dev/null" >/dev/null 2>&1 &
+done
+echo " Waiting for writes to complete..."
+wait 2>/dev/null || true
+
+wait_stats "Waiting for disk pressure to register"
+echo " Worker stats after disk writes:"
+worker_stats
+
+DISK_BEFORE=$(get_workers | python3 -c "
+import sys, json
+print(max(w['disk_pct'] for w in json.load(sys.stdin)))
+" 2>/dev/null)
+echo " Peak disk usage: ${DISK_BEFORE}%"
+
+# Verify sandboxes still work
+RESPONSIVE=0
+for sb in "${DISK_SBS[@]}"; do
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+[ "$RESPONSIVE" -eq "${#DISK_SBS[@]}" ] && pass "All sandboxes responsive under disk pressure (peak ${DISK_BEFORE}%)" || fail "Only $RESPONSIVE/${#DISK_SBS[@]} responsive"
+
+# Write even more to push disk higher
+echo " Writing 10GB more per sandbox..."
+for sb in "${DISK_SBS[@]}"; do
+ TIMEOUT=180 exec_run "$sb" "sh" "-c" "dd if=/dev/zero of=/workspace/bigfile2 bs=1M count=10240 2>/dev/null" >/dev/null 2>&1 &
+done
+echo " Waiting for writes..."
+wait 2>/dev/null || true
+
+wait_stats "Waiting for higher disk pressure"
+echo " Worker stats after heavy disk writes:"
+worker_stats
+
+DISK_AFTER=$(get_workers | python3 -c "
+import sys, json
+print(max(w['disk_pct'] for w in json.load(sys.stdin)))
+" 2>/dev/null)
+echo " Peak disk usage: ${DISK_AFTER}%"
+
+# Check if disk grew
+GREW=$(python3 -c "print('yes' if float('${DISK_AFTER}') > float('${DISK_BEFORE}') else 'no')" 2>/dev/null)
+[ "$GREW" = "yes" ] && pass "Disk pressure increased: ${DISK_BEFORE}% → ${DISK_AFTER}%" || skip "Disk pressure unchanged (writes may be in tmpfs)"
+
+# New sandbox should still be creatable
+NEW_SB2=$(create_sb)
+if [ -n "$NEW_SB2" ]; then
+ exec_check "$NEW_SB2" && pass "New sandbox works under disk pressure" || fail "New sandbox broken under disk pressure"
+else
+ fail "Cannot create sandbox under disk pressure"
+fi
+
+flush_sandboxes
+
+# ============================================================
+# TEST 3: CPU PRESSURE
+# ============================================================
+h "Test 3: CPU pressure — pin all CPUs with busy loops"
+
+echo " Strategy: Create 4 sandboxes with 400% CPU each, run busy loops"
+
+declare -a CPU_SBS=()
+for i in $(seq 1 4); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ CPU_SBS+=("$sb")
+ # Scale CPU to 400% (4 vCPUs worth)
+ api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":1024,"cpuPercent":400}' >/dev/null 2>&1
+ echo " Created $sb (#$i) at 400% CPU"
+ fi
+done
+
+echo " Baseline CPU stats:"
+worker_stats
+
+echo " Starting CPU burn in all sandboxes..."
+for sb in "${CPU_SBS[@]}"; do
+ # Fire and forget: 8 busy loops per sandbox (runs for 60s then auto-dies)
+ TIMEOUT=10 exec_run "$sb" "sh" "-c" "for i in 1 2 3 4 5 6 7 8; do (timeout 60 sh -c 'while :; do :; done') & done" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+wait_stats "Waiting for CPU pressure to register"
+echo " Worker stats under CPU burn:"
+worker_stats
+
+PEAK_CPU=$(get_workers | python3 -c "
+import sys, json
+print(max(w['cpu_pct'] for w in json.load(sys.stdin)))
+" 2>/dev/null)
+echo " Peak CPU: ${PEAK_CPU}%"
+
+[ "$(python3 -c "print('yes' if float('${PEAK_CPU}') > 30 else 'no')")" = "yes" ] && pass "CPU pressure visible: peak ${PEAK_CPU}%" || skip "CPU pressure low (cgroup limits may cap it)"
+
+# Verify sandboxes still respond even under CPU pressure
+RESPONSIVE=0
+for sb in "${CPU_SBS[@]}"; do
+ TIMEOUT=15 exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+[ "$RESPONSIVE" -eq "${#CPU_SBS[@]}" ] && pass "All sandboxes responsive under CPU pressure" || fail "Only $RESPONSIVE/${#CPU_SBS[@]} responsive under CPU burn"
+
+# Create a new sandbox — should still work (routes to less-loaded worker)
+NEW_SB3=$(create_sb)
+if [ -n "$NEW_SB3" ]; then
+ exec_check "$NEW_SB3" && pass "New sandbox works under CPU pressure" || fail "New sandbox broken under CPU pressure"
+else
+ fail "Cannot create sandbox under CPU pressure"
+fi
+
+echo " Letting CPU burn continue for scaler to react (30s)..."
+sleep 30
+echo " Worker stats after scaler reaction time:"
+worker_stats
+
+flush_sandboxes
+
+# ============================================================
+# TEST 4: RAM + CPU COMBINED
+# ============================================================
+h "Test 4: Combined RAM + CPU pressure"
+
+echo " Strategy: 4 sandboxes at 8GB + 400% CPU + busy loops"
+
+declare -a COMBO1_SBS=()
+for i in $(seq 1 4); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ COMBO1_SBS+=("$sb")
+ api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":8192,"cpuPercent":400}' >/dev/null 2>&1
+ echo " Created $sb: 8GB + 400% CPU"
+ fi
+done
+
+# Start CPU burn
+for sb in "${COMBO1_SBS[@]}"; do
+ TIMEOUT=10 exec_run "$sb" "sh" "-c" "for i in 1 2 3 4 5 6 7 8; do (timeout 60 sh -c 'while :; do :; done') & done" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+# Also allocate memory inside the VMs to make it real pressure (not just committed)
+for sb in "${COMBO1_SBS[@]}"; do
+ TIMEOUT=30 exec_run "$sb" "sh" "-c" "python3 -c \"x=bytearray(4*1024*1024*1024)\" &" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+wait_stats "Waiting for combined pressure"
+echo " Worker stats under RAM + CPU pressure:"
+worker_stats
+
+PEAK_CPU=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"cpu_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+PEAK_MEM=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"mem_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+echo " Peak: CPU=${PEAK_CPU}% MEM=${PEAK_MEM}%"
+
+# All sandboxes should still respond (exec goes through even under pressure)
+RESPONSIVE=0
+for sb in "${COMBO1_SBS[@]}"; do
+ TIMEOUT=15 exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+[ "$RESPONSIVE" -ge 3 ] && pass "≥3/${#COMBO1_SBS[@]} responsive under RAM+CPU pressure (cpu=${PEAK_CPU}% mem=${PEAK_MEM}%)" || fail "Only $RESPONSIVE/${#COMBO1_SBS[@]} responsive"
+
+# New sandbox should still be possible
+NEW_SB4=$(create_sb)
+if [ -n "$NEW_SB4" ]; then
+ exec_check "$NEW_SB4" && pass "New sandbox works under combined pressure" || fail "New sandbox broken"
+else
+ skip "Could not create sandbox (system at capacity — acceptable)"
+fi
+
+flush_sandboxes
+
+# ============================================================
+# TEST 5: DISK + RAM COMBINED
+# ============================================================
+h "Test 5: Combined Disk + RAM pressure"
+
+echo " Strategy: 4 sandboxes at 8GB, each writing 10GB to disk"
+
+declare -a COMBO2_SBS=()
+for i in $(seq 1 4); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ COMBO2_SBS+=("$sb")
+ api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":8192,"cpuPercent":200}' >/dev/null 2>&1
+ echo " Created $sb: 8GB RAM"
+ fi
+done
+
+# Write 10GB per sandbox
+echo " Writing 10GB per sandbox (parallel)..."
+for sb in "${COMBO2_SBS[@]}"; do
+ TIMEOUT=180 exec_run "$sb" "sh" "-c" "dd if=/dev/zero of=/workspace/bigfile bs=1M count=10240 2>/dev/null" >/dev/null 2>&1 &
+done
+echo " Waiting for disk writes..."
+wait 2>/dev/null || true
+
+wait_stats "Waiting for disk + RAM pressure"
+echo " Worker stats under Disk + RAM pressure:"
+worker_stats
+
+PEAK_MEM=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"mem_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+PEAK_DISK=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"disk_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+echo " Peak: MEM=${PEAK_MEM}% DISK=${PEAK_DISK}%"
+
+RESPONSIVE=0
+for sb in "${COMBO2_SBS[@]}"; do
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+[ "$RESPONSIVE" -eq "${#COMBO2_SBS[@]}" ] && pass "All sandboxes responsive under Disk+RAM pressure (mem=${PEAK_MEM}% disk=${PEAK_DISK}%)" || fail "Only $RESPONSIVE/${#COMBO2_SBS[@]} responsive"
+
+flush_sandboxes
+
+# ============================================================
+# TEST 6: ALL THREE — RAM + CPU + DISK
+# ============================================================
+h "Test 6: Triple pressure — RAM + CPU + Disk simultaneously"
+
+echo " Strategy: 6 sandboxes, 8GB each, CPU burn, 10GB disk writes"
+echo " This is the worst case — everything under pressure at once"
+
+declare -a TRIPLE_SBS=()
+for i in $(seq 1 6); do
+ sb=$(create_sb)
+ if [ -n "$sb" ]; then
+ TRIPLE_SBS+=("$sb")
+ api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":8192,"cpuPercent":400}' >/dev/null 2>&1
+ echo " Created $sb (#$i): 8GB + 400% CPU"
+ fi
+done
+
+# Start everything simultaneously
+echo " Launching all pressure vectors..."
+for sb in "${TRIPLE_SBS[@]}"; do
+ # CPU burn
+ TIMEOUT=10 exec_run "$sb" "sh" "-c" "for i in 1 2 3 4 5 6 7 8; do (timeout 90 sh -c 'while :; do :; done') & done" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+for sb in "${TRIPLE_SBS[@]}"; do
+ # Disk writes (fire and forget)
+ TIMEOUT=10 exec_run "$sb" "sh" "-c" "dd if=/dev/zero of=/workspace/bigfile bs=1M count=10240 &" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+for sb in "${TRIPLE_SBS[@]}"; do
+ # Memory allocation
+ TIMEOUT=10 exec_run "$sb" "sh" "-c" "python3 -c 'x=bytearray(4*1024*1024*1024)' &" >/dev/null 2>&1 || true &
+done
+wait 2>/dev/null || true
+
+echo " All pressure applied. Waiting for system response..."
+wait_stats "Waiting for triple pressure stats"
+echo " Worker stats under TRIPLE pressure:"
+worker_stats
+
+PEAK_CPU=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"cpu_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+PEAK_MEM=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"mem_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+PEAK_DISK=$(get_workers | python3 -c "import sys,json; print(f'{max(w[\"disk_pct\"] for w in json.load(sys.stdin)):.0f}')" 2>/dev/null)
+echo " Peak: CPU=${PEAK_CPU}% MEM=${PEAK_MEM}% DISK=${PEAK_DISK}%"
+
+# The key question: can we still use the system?
+RESPONSIVE=0
+for sb in "${TRIPLE_SBS[@]}"; do
+ TIMEOUT=20 exec_check "$sb" && RESPONSIVE=$((RESPONSIVE+1))
+done
+echo " $RESPONSIVE/${#TRIPLE_SBS[@]} sandboxes still responsive"
+[ "$RESPONSIVE" -ge 4 ] && pass "System usable under triple pressure ($RESPONSIVE/${#TRIPLE_SBS[@]} responsive)" || fail "System degraded: only $RESPONSIVE/${#TRIPLE_SBS[@]} responsive"
+
+# Can we still create a new sandbox?
+NEW_SB6=$(create_sb)
+if [ -n "$NEW_SB6" ]; then
+ TIMEOUT=20 exec_check "$NEW_SB6" && pass "New sandbox works under triple pressure" || fail "New sandbox broken under triple pressure"
+else
+ skip "Cannot create sandbox under triple pressure (may be expected)"
+fi
+
+# Wait for scaler to potentially react
+echo " Giving scaler 45s to respond to pressure..."
+sleep 45
+echo " Worker stats after scaler reaction:"
+worker_stats
+
+WORKERS_NOW=$(get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+echo " Workers now: $WORKERS_NOW"
+[ "${WORKERS_NOW:-0}" -ge 2 ] && pass "System survived triple pressure with $WORKERS_NOW workers" || fail "Workers lost during triple pressure"
+
+# Check if scaler launched more workers or evacuated
+[ "${WORKERS_NOW:-0}" -gt 2 ] && pass "Scaler launched additional worker(s) in response to pressure" || skip "Scaler did not scale up (pressure may be within bounds)"
+
+flush_sandboxes
+
+# ============================================================
+# TEST 7: RECOVERY — System returns to normal after pressure removed
+# ============================================================
+h "Test 7: Recovery — verify system returns to healthy state after pressure"
+
+echo " All pressure sandboxes destroyed. Waiting for recovery..."
+sleep 15
+echo " Worker stats after recovery:"
+worker_stats
+
+# Create and verify fresh sandboxes
+RECOVERY_OK=0
+for i in $(seq 1 4); do
+ sb=$(create_sb)
+ if [ -n "$sb" ] && exec_check "$sb"; then
+ RECOVERY_OK=$((RECOVERY_OK+1))
+ fi
+done
+[ "$RECOVERY_OK" -eq 4 ] && pass "Full recovery: 4/4 new sandboxes work" || fail "Incomplete recovery: $RECOVERY_OK/4"
+
+echo ""
+echo " Final worker state:"
+worker_stats
+
+flush_sandboxes
+
+# ============================================================
+h "Final Summary"
+echo ""
+worker_stats
+echo ""
+summary
diff --git a/scripts/qemu-tests/34-ping-pong.sh b/scripts/qemu-tests/34-ping-pong.sh
new file mode 100755
index 00000000..9cf3ab7a
--- /dev/null
+++ b/scripts/qemu-tests/34-ping-pong.sh
@@ -0,0 +1,106 @@
+#!/usr/bin/env bash
+# 34-ping-pong.sh — Migrate a sandbox back and forth 20 times between two workers
+#
+# Verifies: migration reliability, data persistence, route cache invalidation,
+# agent reconnection, and that the sandbox stays fully responsive throughout.
+
+source "$(dirname "$0")/common.sh"
+
+SB=""
+cleanup() { [ -n "$SB" ] && destroy_sandbox "$SB"; }
+trap cleanup EXIT INT TERM
+
+# Get workers
+WORKERS=$(api "$API_URL/api/workers" 2>/dev/null)
+W1=$(echo "$WORKERS" | python3 -c "import sys,json; print(json.load(sys.stdin)[0]['worker_id'])" 2>/dev/null)
+W2=$(echo "$WORKERS" | python3 -c "import sys,json; print(json.load(sys.stdin)[1]['worker_id'])" 2>/dev/null)
+
+if [ -z "$W1" ] || [ -z "$W2" ]; then
+ echo "Need 2 workers. Found: $WORKERS"
+ exit 1
+fi
+
+echo "Workers: $W1 ↔ $W2"
+echo ""
+
+# Create sandbox
+h "Setup"
+SB=$(create_sandbox 0)
+echo " Sandbox: $SB"
+
+# Write a marker file we'll verify after every migration
+exec_run "$SB" "sh" "-c" "echo ping-pong-marker-12345 > /workspace/marker.txt" >/dev/null 2>&1
+MARKER=$(exec_stdout "$SB" "cat" "/workspace/marker.txt" 2>/dev/null)
+echo " Marker: $MARKER"
+
+# Figure out which worker it's on now
+CURRENT=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+echo " Starting on: $CURRENT"
+
+h "Ping Pong — 20 migrations"
+
+PASS_COUNT=0
+FAIL_COUNT=0
+
+for i in $(seq 1 20); do
+ # Pick target (the other worker)
+ if [ "$CURRENT" = "$W1" ]; then
+ TARGET="$W2"
+ else
+ TARGET="$W1"
+ fi
+
+ printf " %2d. %s → %s ... " "$i" "$CURRENT" "$TARGET"
+
+ # Migrate
+ START=$(python3 -c "import time; print(int(time.time()*1000))")
+ RESULT=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB/migrate" -d "{\"targetWorker\":\"$TARGET\"}" 2>/dev/null)
+ END=$(python3 -c "import time; print(int(time.time()*1000))")
+ DURATION=$((END - START))
+
+ # Check for errors
+ if echo "$RESULT" | grep -qi "error"; then
+ printf "\033[31mFAIL\033[0m migration error: %s\n" "$RESULT"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify exec works
+ OUT=$(exec_stdout "$SB" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" != "alive" ]; then
+ printf "\033[31mFAIL\033[0m exec returned: %s (%dms)\n" "$OUT" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify marker file survived
+ CHECK=$(exec_stdout "$SB" "cat" "/workspace/marker.txt" 2>/dev/null)
+ if [ "$CHECK" != "$MARKER" ]; then
+ printf "\033[31mFAIL\033[0m marker lost: got '%s' (%dms)\n" "$CHECK" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify it's on the expected worker now
+ NEW_WORKER=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+ if [ "$NEW_WORKER" != "$TARGET" ]; then
+ printf "\033[31mFAIL\033[0m worker mismatch: expected %s got %s (%dms)\n" "$TARGET" "$NEW_WORKER" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ printf "\033[32m✓\033[0m %dms\n" "$DURATION"
+ PASS_COUNT=$((PASS_COUNT + 1))
+ CURRENT="$TARGET"
+done
+
+echo ""
+h "Results"
+echo " $PASS_COUNT/20 successful migrations"
+echo " $FAIL_COUNT/20 failures"
+
+PASS=0; FAIL=0; SKIP=0
+[ "$PASS_COUNT" -eq 20 ] && pass "All 20 ping-pong migrations succeeded" || fail "$FAIL_COUNT/20 migrations failed"
+[ "$FAIL_COUNT" -eq 0 ] && pass "Sandbox stayed alive through all migrations" || fail "Sandbox died or lost data"
+
+summary
diff --git a/scripts/qemu-tests/35-ping-pong-random.sh b/scripts/qemu-tests/35-ping-pong-random.sh
new file mode 100755
index 00000000..aa13aaa7
--- /dev/null
+++ b/scripts/qemu-tests/35-ping-pong-random.sh
@@ -0,0 +1,131 @@
+#!/usr/bin/env bash
+# 35-ping-pong-random.sh — Migrate a sandbox 20 times to a random worker each time
+#
+# With 5+ workers, each migration picks a different random target.
+# Verifies: multi-worker migration, data persistence, agent reconnection.
+
+source "$(dirname "$0")/common.sh"
+
+ROUNDS="${1:-20}"
+SB=""
+cleanup() { [ -n "$SB" ] && destroy_sandbox "$SB"; }
+trap cleanup EXIT INT TERM
+
+# Get workers
+WORKERS_JSON=$(api "$API_URL/api/workers" 2>/dev/null)
+WORKER_COUNT=$(echo "$WORKERS_JSON" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+WORKER_IDS=$(echo "$WORKERS_JSON" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(w['worker_id'])
+" 2>/dev/null)
+
+echo "Workers ($WORKER_COUNT):"
+echo "$WORKERS_JSON" | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(f' {w[\"worker_id\"]} ({w[\"current\"]}/{w[\"capacity\"]})')
+" 2>/dev/null
+
+if [ "$WORKER_COUNT" -lt 2 ]; then
+ echo "Need at least 2 workers."
+ exit 1
+fi
+
+# Create sandbox
+h "Setup"
+SB=$(create_sandbox 0)
+echo " Sandbox: $SB"
+
+exec_run "$SB" "sh" "-c" "echo random-ping-pong-$(date +%s) > /workspace/marker.txt" >/dev/null 2>&1
+MARKER=$(exec_stdout "$SB" "cat" "/workspace/marker.txt" 2>/dev/null)
+echo " Marker: $MARKER"
+
+CURRENT=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+echo " Starting on: $CURRENT"
+
+h "Random Ping Pong — $ROUNDS migrations across $WORKER_COUNT workers"
+
+PASS_COUNT=0
+FAIL_COUNT=0
+VISIT_LOG=$(mktemp)
+
+for i in $(seq 1 "$ROUNDS"); do
+ # Pick random target from live workers (refreshed each round) that isn't the current
+ LIVE_IDS=$(api "$API_URL/api/workers" 2>/dev/null | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin)]" 2>/dev/null)
+ TARGET=$(echo "$LIVE_IDS" | grep -v "^${CURRENT}$" | sort -R | head -1)
+ if [ -z "$TARGET" ]; then
+ printf " %2d. SKIP — no live target available\n" "$i"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ printf " %2d. %s → %s ... " "$i" "${CURRENT##*-}" "${TARGET##*-}"
+
+ START=$(python3 -c "import time; print(int(time.time()*1000))")
+ RESULT=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB/migrate" -d "{\"targetWorker\":\"$TARGET\"}" 2>/dev/null)
+ END=$(python3 -c "import time; print(int(time.time()*1000))")
+ DURATION=$((END - START))
+
+ if echo "$RESULT" | grep -qi "error"; then
+ ERR_MSG=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)
+ printf "\033[31mFAIL\033[0m %s\n" "$ERR_MSG"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ # Update CURRENT in case sandbox moved or is still on source
+ ACTUAL=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+ [ -n "$ACTUAL" ] && CURRENT="$ACTUAL"
+ continue
+ fi
+
+ # Verify exec
+ OUT=$(exec_stdout "$SB" "echo" "alive" 2>/dev/null)
+ if [ "$OUT" != "alive" ]; then
+ printf "\033[31mFAIL\033[0m exec='%s' (%dms)\n" "$OUT" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify marker
+ CHECK=$(exec_stdout "$SB" "cat" "/workspace/marker.txt" 2>/dev/null)
+ if [ "$CHECK" != "$MARKER" ]; then
+ printf "\033[31mFAIL\033[0m marker lost (%dms)\n" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify worker assignment
+ NEW_WORKER=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null)
+ if [ "$NEW_WORKER" != "$TARGET" ]; then
+ printf "\033[31mFAIL\033[0m wrong worker: %s (%dms)\n" "${NEW_WORKER##*-}" "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ printf "\033[32m✓\033[0m %dms\n" "$DURATION"
+ PASS_COUNT=$((PASS_COUNT + 1))
+ echo "$TARGET" >> "$VISIT_LOG"
+ CURRENT="$TARGET"
+done
+
+echo ""
+h "Results"
+echo " $PASS_COUNT/$ROUNDS successful, $FAIL_COUNT failed"
+echo ""
+echo " Worker visit distribution:"
+UNIQUE_VISITED=0
+if [ -s "$VISIT_LOG" ]; then
+ for wid in $(sort -u "$VISIT_LOG"); do
+ count=$(grep -c "^${wid}$" "$VISIT_LOG" 2>/dev/null || echo "0")
+ count=$((count + 0)) # ensure numeric
+ bar=$(printf '%*s' "$count" '' | tr ' ' '█')
+ printf " %s %2d %s\n" "${wid##*-}" "$count" "$bar"
+ UNIQUE_VISITED=$((UNIQUE_VISITED + 1))
+ done
+fi
+rm -f "$VISIT_LOG"
+
+PASS=0; FAIL=0; SKIP=0
+[ "$PASS_COUNT" -eq "$ROUNDS" ] && pass "All $ROUNDS random migrations succeeded" || fail "$FAIL_COUNT/$ROUNDS failed"
+[ "$UNIQUE_VISITED" -ge 3 ] && pass "Visited $UNIQUE_VISITED unique workers" || fail "Only visited $UNIQUE_VISITED workers"
+
+summary
diff --git a/scripts/qemu-tests/36-advanced-scenarios.sh b/scripts/qemu-tests/36-advanced-scenarios.sh
new file mode 100755
index 00000000..d4f49381
--- /dev/null
+++ b/scripts/qemu-tests/36-advanced-scenarios.sh
@@ -0,0 +1,570 @@
+#!/usr/bin/env bash
+# 36-advanced-scenarios.sh — Advanced scenario tests
+#
+# 12 tests covering: hibernation, worker death, concurrent migrations,
+# migration during I/O, scale-triggered migration, concurrent exec,
+# sandbox timeout, DNS resolution, scaler drain, port forwarding,
+# large sandbox migration, and checkpoint/restore.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+flush_sandboxes() {
+ local sbs
+ sbs=$(api "$API_URL/api/sandboxes" 2>/dev/null | python3 -c "
+import sys, json
+for s in json.load(sys.stdin):
+ if s.get('status') in ('running','migrating','creating'):
+ print(s.get('sandboxID', ''))
+" 2>/dev/null || true)
+ local count=0
+ for sb in $sbs; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & count=$((count+1)); }
+ done
+ wait 2>/dev/null || true
+ [ "$count" -gt 0 ] && echo " (cleaned $count sandboxes)" && sleep 3
+}
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+
+worker_ids() {
+ get_workers | python3 -c "import sys,json; [print(w['worker_id']) for w in json.load(sys.stdin)]" 2>/dev/null
+}
+
+pick_other_worker() {
+ local current="$1"
+ worker_ids | grep -v "^${current}$" | head -1
+}
+
+sandbox_worker() {
+ api "$API_URL/api/sandboxes/$1" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID',''))" 2>/dev/null
+}
+
+sandbox_status() {
+ api "$API_URL/api/sandboxes/$1" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null
+}
+
+create_sb() {
+ local timeout="${1:-0}"
+ local result
+ result=$(api -X POST "$API_URL/api/sandboxes" -d "{\"timeout\":$timeout}" 2>/dev/null || echo '{}')
+ echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null
+}
+
+exec_ok() {
+ local out
+ out=$(exec_stdout "$1" "echo" "ok" 2>/dev/null)
+ [ "$out" = "ok" ]
+}
+
+echo "=== Advanced Scenario Tests ==="
+echo "Workers:"
+get_workers | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(f' {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]}')
+" 2>/dev/null
+
+# ============================================================
+h "Test 1: Hibernate + wake — state survives cold storage"
+
+SB1=$(create_sb)
+echo " Created: $SB1"
+exec_run "$SB1" "sh" "-c" "echo hibernate-marker-42 > /workspace/state.txt" >/dev/null 2>&1
+exec_run "$SB1" "sh" "-c" "echo 'count=100' > /workspace/counter.txt" >/dev/null 2>&1
+DATA_BEFORE=$(exec_stdout "$SB1" "cat" "/workspace/state.txt" 2>/dev/null)
+echo " Data before hibernate: $DATA_BEFORE"
+
+echo " Hibernating..."
+HIB_RESULT=$(TIMEOUT=120 api -X POST "$API_URL/api/sandboxes/$SB1/hibernate" 2>/dev/null)
+echo " Hibernate result: $HIB_RESULT"
+HIB_STATUS=$(sandbox_status "$SB1")
+echo " Status after hibernate: $HIB_STATUS"
+
+if [ "$HIB_STATUS" = "hibernated" ]; then
+ pass "Sandbox hibernated successfully"
+
+ echo " Waking..."
+ WAKE_RESULT=$(TIMEOUT=120 api -X POST "$API_URL/api/sandboxes/$SB1/wake" -d '{"timeout":300}' 2>/dev/null)
+ echo " Wake result: $(echo "$WAKE_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'status={d.get(\"status\",\"?\")}')" 2>/dev/null)"
+
+ sleep 2
+ WAKE_STATUS=$(sandbox_status "$SB1")
+ if [ "$WAKE_STATUS" = "running" ]; then
+ pass "Sandbox woke up (status=running)"
+
+ DATA_AFTER=$(exec_stdout "$SB1" "cat" "/workspace/state.txt" 2>/dev/null)
+ [ "$DATA_AFTER" = "$DATA_BEFORE" ] && pass "Data survived hibernate+wake: $DATA_AFTER" || fail "Data lost: before=$DATA_BEFORE after=$DATA_AFTER"
+
+ COUNTER=$(exec_stdout "$SB1" "cat" "/workspace/counter.txt" 2>/dev/null)
+ [ "$COUNTER" = "count=100" ] && pass "Counter file intact" || fail "Counter file: $COUNTER"
+ else
+ fail "Sandbox didn't wake: status=$WAKE_STATUS"
+ fi
+else
+ if echo "$HIB_RESULT" | grep -qi "error"; then
+ skip "Hibernation not available (S3 checkpoint store may not be configured)"
+ else
+ fail "Unexpected hibernate status: $HIB_STATUS"
+ fi
+fi
+destroy_sandbox "$SB1" 2>/dev/null
+
+# ============================================================
+h "Test 2: Worker death — orphan detection marks sandboxes as error"
+
+# Create sandboxes, note their worker, then we'll check what happens when
+# a worker disappears (we can't kill workers, but we can verify the
+# reconciliation logic by checking that sandboxes on dead workers get marked)
+SB2=$(create_sb)
+echo " Created: $SB2"
+W2=$(sandbox_worker "$SB2")
+echo " On worker: $W2"
+exec_ok "$SB2" && pass "Sandbox responsive before worker test" || fail "Sandbox not responsive"
+
+# We can verify the orphan detection is running by checking maintenance logs
+# For now, verify that a sandbox whose worker vanishes from the registry
+# eventually gets marked. We'll create a sandbox, then check that the
+# system tracks worker liveness properly.
+LIVE_WORKERS=$(worker_ids | wc -l | tr -d ' ')
+echo " Live workers: $LIVE_WORKERS"
+[ "$LIVE_WORKERS" -ge 2 ] && pass "Worker registry tracking $LIVE_WORKERS workers" || fail "Only $LIVE_WORKERS workers"
+
+# Verify that if we query a sandbox on a known worker, it's accessible
+exec_ok "$SB2" && pass "Sandbox on live worker is accessible" || fail "Sandbox on live worker not accessible"
+destroy_sandbox "$SB2" 2>/dev/null
+
+# ============================================================
+h "Test 3: Concurrent migrations — 5 sandboxes migrating simultaneously"
+
+echo " Creating 5 sandboxes..."
+SB3_LIST=""
+for i in $(seq 1 5); do
+ sb=$(create_sb)
+ [ -n "$sb" ] && SB3_LIST="$SB3_LIST $sb"
+done
+SB3_COUNT=$(echo $SB3_LIST | wc -w | tr -d ' ')
+echo " Created $SB3_COUNT sandboxes"
+
+# Write unique markers
+IDX=0
+for sb in $SB3_LIST; do
+ IDX=$((IDX+1))
+ exec_run "$sb" "sh" "-c" "echo concurrent-$IDX > /workspace/id.txt" >/dev/null 2>&1
+done
+
+# Migrate all 5 simultaneously
+echo " Migrating all 5 simultaneously..."
+MIGRATE_PIDS=""
+MIGRATE_RESULTS=$(mktemp)
+IDX=0
+for sb in $SB3_LIST; do
+ IDX=$((IDX+1))
+ SRC=$(sandbox_worker "$sb")
+ TGT=$(pick_other_worker "$SRC")
+ if [ -n "$TGT" ]; then
+ (
+ START=$(python3 -c "import time; print(int(time.time()*1000))")
+ RESULT=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$sb/migrate" -d "{\"targetWorker\":\"$TGT\"}" 2>/dev/null)
+ END=$(python3 -c "import time; print(int(time.time()*1000))")
+ DUR=$((END-START))
+ if echo "$RESULT" | grep -qi "error"; then
+ echo "FAIL $sb ${DUR}ms $(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)" >> "$MIGRATE_RESULTS"
+ else
+ echo "OK $sb ${DUR}ms" >> "$MIGRATE_RESULTS"
+ fi
+ ) &
+ fi
+done
+wait 2>/dev/null || true
+
+OK_COUNT=$(grep -c "^OK" "$MIGRATE_RESULTS" 2>/dev/null || echo 0)
+FAIL_MIGRATE=$(grep -c "^FAIL" "$MIGRATE_RESULTS" 2>/dev/null || echo 0)
+echo " Results: $OK_COUNT OK, $FAIL_MIGRATE failed"
+cat "$MIGRATE_RESULTS" | while read line; do echo " $line"; done
+rm -f "$MIGRATE_RESULTS"
+
+[ "$OK_COUNT" -ge 3 ] && pass "≥3/5 concurrent migrations succeeded ($OK_COUNT/5)" || fail "Only $OK_COUNT/5 concurrent migrations"
+
+# Verify all are still responsive and markers intact
+ALIVE=0
+MARKERS_OK=0
+IDX=0
+for sb in $SB3_LIST; do
+ IDX=$((IDX+1))
+ exec_ok "$sb" && ALIVE=$((ALIVE+1))
+ M=$(exec_stdout "$sb" "cat" "/workspace/id.txt" 2>/dev/null)
+ [ "$M" = "concurrent-$IDX" ] && MARKERS_OK=$((MARKERS_OK+1))
+done
+[ "$ALIVE" -eq "$SB3_COUNT" ] && pass "All $ALIVE sandboxes responsive after concurrent migration" || fail "Only $ALIVE/$SB3_COUNT responsive"
+[ "$MARKERS_OK" -eq "$SB3_COUNT" ] && pass "All markers intact after concurrent migration" || fail "Only $MARKERS_OK/$SB3_COUNT markers intact"
+
+for sb in $SB3_LIST; do destroy_sandbox "$sb" >/dev/null 2>&1 & done
+wait 2>/dev/null || true
+
+# ============================================================
+h "Test 4: Migration during active I/O — sandbox writing large file during migration"
+
+SB4=$(create_sb)
+echo " Created: $SB4"
+
+# Start a long-running write (50MB in small chunks) — fire and forget
+TIMEOUT=10 exec_run "$SB4" "sh" "-c" "dd if=/dev/urandom of=/workspace/bigwrite.bin bs=4096 count=12800 2>/dev/null &" >/dev/null 2>&1 || true
+echo " Started 50MB background write"
+sleep 1
+
+# Migrate while write is in progress
+SRC4=$(sandbox_worker "$SB4")
+TGT4=$(pick_other_worker "$SRC4")
+echo " Migrating $SRC4 → $TGT4 during active I/O..."
+START4=$(python3 -c "import time; print(int(time.time()*1000))")
+MIG4=$(TIMEOUT=180 api -X POST "$API_URL/api/sandboxes/$SB4/migrate" -d "{\"targetWorker\":\"$TGT4\"}" 2>/dev/null)
+END4=$(python3 -c "import time; print(int(time.time()*1000))")
+DUR4=$((END4-START4))
+
+if echo "$MIG4" | grep -qi "error"; then
+ fail "Migration during I/O failed: $(echo "$MIG4" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)"
+else
+ pass "Migration during active I/O completed (${DUR4}ms)"
+fi
+
+# Verify sandbox still works
+exec_ok "$SB4" && pass "Sandbox responsive after I/O migration" || fail "Sandbox dead after I/O migration"
+
+# Wait for write to finish, check file exists
+sleep 5
+SIZE=$(exec_stdout "$SB4" "sh" "-c" "ls -la /workspace/bigwrite.bin 2>/dev/null | awk '{print \$5}'" 2>/dev/null)
+echo " File size after migration: ${SIZE:-missing} bytes"
+[ -n "$SIZE" ] && [ "$SIZE" -gt 0 ] 2>/dev/null && pass "File written during migration exists (${SIZE} bytes)" || skip "File may have been in-flight"
+destroy_sandbox "$SB4" 2>/dev/null
+
+# ============================================================
+h "Test 5: Scale-triggered auto-migration"
+
+SB5=$(create_sb)
+echo " Created: $SB5"
+W5=$(sandbox_worker "$SB5")
+echo " On worker: $W5"
+
+# Scale to 4GB first
+api -X PUT "$API_URL/api/sandboxes/$SB5/limits" -d '{"memoryMB":4096,"cpuPercent":200}' >/dev/null 2>&1
+echo " Scaled to 4GB"
+
+# Now try to scale to something very large that should trigger auto-migration
+# The worker has ~64GB, 20% reserve = ~51GB usable. If we scale high enough
+# and the worker is loaded, it should trigger insufficient_capacity → auto-migrate
+echo " Attempting scale to 16GB (may trigger auto-migration)..."
+SCALE_RESULT=$(TIMEOUT=180 api -X PUT "$API_URL/api/sandboxes/$SB5/limits" -d '{"memoryMB":16384,"cpuPercent":400}' 2>/dev/null)
+echo " Result: $SCALE_RESULT"
+
+W5_AFTER=$(sandbox_worker "$SB5")
+if echo "$SCALE_RESULT" | grep -q "ok"; then
+ pass "Scale to 16GB succeeded"
+ if [ "$W5_AFTER" != "$W5" ]; then
+ pass "Sandbox auto-migrated to accommodate scale ($W5 → $W5_AFTER)"
+ else
+ pass "Scale completed on same worker (had capacity)"
+ fi
+ # Verify memory actually increased
+ MEM=$(exec_stdout "$SB5" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+ echo " Actual memory: ${MEM}MB"
+ [ -n "$MEM" ] && [ "$MEM" -gt 14000 ] && pass "Memory confirmed at ${MEM}MB" || fail "Memory only ${MEM}MB"
+elif echo "$SCALE_RESULT" | grep -qi "insufficient_capacity\|migrat"; then
+ pass "System correctly detected insufficient capacity"
+else
+ fail "Unexpected scale result: $SCALE_RESULT"
+fi
+
+exec_ok "$SB5" && pass "Sandbox responsive after scale attempt" || fail "Sandbox dead after scale"
+destroy_sandbox "$SB5" 2>/dev/null
+
+# ============================================================
+h "Test 6: Concurrent exec — 10 parallel exec calls to one sandbox"
+
+SB6=$(create_sb)
+echo " Created: $SB6"
+
+# Write a file the execs will read
+exec_run "$SB6" "sh" "-c" "seq 1 1000 > /workspace/numbers.txt" >/dev/null 2>&1
+
+echo " Firing 10 parallel exec calls..."
+EXEC_DIR=$(mktemp -d)
+for i in $(seq 1 10); do
+ (
+ OUT=$(exec_stdout "$SB6" "wc" "-l" "/workspace/numbers.txt" 2>/dev/null | awk '{print $1}')
+ echo "$OUT" > "$EXEC_DIR/$i"
+ ) &
+done
+wait 2>/dev/null || true
+
+EXEC_OK=0
+for f in "$EXEC_DIR"/*; do
+ [ -f "$f" ] || continue
+ VAL=$(cat "$f" | tr -d ' ')
+ [ "$VAL" = "1000" ] && EXEC_OK=$((EXEC_OK+1))
+done
+rm -rf "$EXEC_DIR"
+
+echo " $EXEC_OK/10 returned correct result"
+[ "$EXEC_OK" -ge 8 ] && pass "Concurrent exec: $EXEC_OK/10 correct" || fail "Concurrent exec: only $EXEC_OK/10 correct"
+
+# Also verify sequential exec still works after the burst
+exec_ok "$SB6" && pass "Sequential exec works after concurrent burst" || fail "Sandbox broken after concurrent exec"
+destroy_sandbox "$SB6" 2>/dev/null
+
+# ============================================================
+h "Test 7: Sandbox timeout/expiry — auto-destroy after timeout"
+
+echo " Creating sandbox with 15s timeout..."
+SB7=$(create_sb 15)
+echo " Created: $SB7"
+exec_ok "$SB7" && pass "Sandbox alive at t=0" || fail "Sandbox dead at creation"
+
+echo " Waiting 10s (should still be alive — timeout resets on exec)..."
+sleep 10
+exec_ok "$SB7" && pass "Sandbox alive at t=10s (timeout reset by exec)" || fail "Sandbox died early"
+
+echo " Waiting 20s with no interaction..."
+sleep 20
+STATUS7=$(sandbox_status "$SB7")
+echo " Status after 20s idle: $STATUS7"
+if [ "$STATUS7" = "hibernated" ] || [ "$STATUS7" = "stopped" ] || [ "$STATUS7" = "" ]; then
+ pass "Sandbox expired after idle timeout (status=$STATUS7)"
+else
+ # Try exec — if it fails, it's been cleaned up
+ if exec_ok "$SB7" 2>/dev/null; then
+ skip "Sandbox still alive (timeout may be longer than expected)"
+ else
+ pass "Sandbox unreachable after timeout"
+ fi
+fi
+destroy_sandbox "$SB7" 2>/dev/null
+
+# ============================================================
+h "Test 8: DNS resolution inside sandbox"
+
+SB8=$(create_sb)
+echo " Created: $SB8"
+
+# Test DNS resolution via Python (more portable than dig/nslookup)
+DNS_RESULT=$(exec_stdout "$SB8" "python3" "-c" "import socket; print(socket.getaddrinfo('google.com', 80)[0][4][0])" 2>/dev/null)
+echo " Resolved google.com → $DNS_RESULT"
+[ -n "$DNS_RESULT" ] && pass "DNS resolution works: google.com → $DNS_RESULT" || fail "DNS resolution failed"
+
+# Test multiple domains
+DNS2=$(exec_stdout "$SB8" "python3" "-c" "import socket; print(socket.getaddrinfo('github.com', 443)[0][4][0])" 2>/dev/null)
+[ -n "$DNS2" ] && pass "DNS: github.com → $DNS2" || fail "DNS failed for github.com"
+
+# Verify /etc/resolv.conf has nameservers
+RESOLV=$(exec_stdout "$SB8" "cat" "/etc/resolv.conf" 2>/dev/null)
+echo "$RESOLV" | grep -q "nameserver" && pass "resolv.conf has nameservers" || fail "resolv.conf missing nameservers"
+
+destroy_sandbox "$SB8" 2>/dev/null
+
+# ============================================================
+h "Test 9: Scaler drain — sandboxes survive worker drain"
+
+# This test verifies that when the scaler decides to drain a worker,
+# sandboxes on it get migrated (not killed). We can't force a drain
+# directly, but we can verify the current state is consistent.
+echo " Checking all running sandboxes are on live workers..."
+ALL_SBS=$(api "$API_URL/api/sandboxes" 2>/dev/null | python3 -c "
+import sys, json
+for s in json.load(sys.stdin):
+ if s.get('status') == 'running':
+ print(f'{s[\"sandboxID\"]} {s.get(\"workerID\",\"unknown\")}')
+" 2>/dev/null)
+LIVE=$(worker_ids)
+ORPHANED=0
+TOTAL_RUNNING=0
+while read -r line; do
+ [ -z "$line" ] && continue
+ SB_ID=$(echo "$line" | awk '{print $1}')
+ WK_ID=$(echo "$line" | awk '{print $2}')
+ TOTAL_RUNNING=$((TOTAL_RUNNING+1))
+ if ! echo "$LIVE" | grep -q "^${WK_ID}$"; then
+ echo " ORPHAN: $SB_ID on dead worker $WK_ID"
+ ORPHANED=$((ORPHANED+1))
+ fi
+done <<< "$ALL_SBS"
+echo " $TOTAL_RUNNING running sandboxes, $ORPHANED orphaned"
+[ "$ORPHANED" -eq 0 ] && pass "No orphaned sandboxes on dead workers" || fail "$ORPHANED sandboxes on dead workers"
+
+# Create sandboxes spread across workers, verify they're tracked
+SB9A=$(create_sb); SB9B=$(create_sb); SB9C=$(create_sb)
+W9A=$(sandbox_worker "$SB9A"); W9B=$(sandbox_worker "$SB9B"); W9C=$(sandbox_worker "$SB9C")
+UNIQUE_WORKERS=$(echo -e "$W9A\n$W9B\n$W9C" | sort -u | wc -l | tr -d ' ')
+echo " 3 sandboxes spread across $UNIQUE_WORKERS worker(s)"
+exec_ok "$SB9A" && exec_ok "$SB9B" && exec_ok "$SB9C" && pass "All 3 sandboxes responsive" || fail "Some sandboxes unresponsive"
+destroy_sandbox "$SB9A" 2>/dev/null; destroy_sandbox "$SB9B" 2>/dev/null; destroy_sandbox "$SB9C" 2>/dev/null
+
+# ============================================================
+h "Test 10: Port forwarding — web server inside sandbox"
+
+SB10=$(create_sb)
+echo " Created: $SB10"
+
+# Start a simple HTTP server on port 8000 inside the sandbox
+TIMEOUT=10 exec_run "$SB10" "sh" "-c" "python3 -m http.server 8000 --directory /workspace &" >/dev/null 2>&1 || true
+sleep 2
+
+# Write a test file
+exec_run "$SB10" "sh" "-c" "echo 'hello from sandbox' > /workspace/index.html" >/dev/null 2>&1
+
+# Try to create a preview URL
+echo " Creating preview URL on port 8000..."
+PREVIEW_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB10/preview" -d '{"port":8000}' 2>/dev/null)
+echo " Preview result: $PREVIEW_RESULT"
+
+HOSTNAME=$(echo "$PREVIEW_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('hostname',''))" 2>/dev/null)
+if [ -n "$HOSTNAME" ] && [ "$HOSTNAME" != "" ]; then
+ pass "Preview URL created: $HOSTNAME"
+
+ # Try to access via the control plane proxy (direct IP, Host header)
+ HTTP_RESULT=$(curl -sk --max-time 5 --connect-timeout 3 -H "Host: $HOSTNAME" "http://20.114.60.29:8080/index.html" 2>/dev/null)
+ if echo "$HTTP_RESULT" | grep -q "hello from sandbox"; then
+ pass "Web server accessible via preview URL"
+ else
+ skip "Preview URL created but not routable from test client"
+ fi
+else
+ if echo "$PREVIEW_RESULT" | grep -qi "error"; then
+ skip "Preview URLs not available: $(echo "$PREVIEW_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)"
+ else
+ skip "No hostname returned"
+ fi
+fi
+destroy_sandbox "$SB10" 2>/dev/null
+
+# ============================================================
+h "Test 11: Large sandbox migration (16GB + 400% CPU)"
+
+SB11=$(create_sb)
+echo " Created: $SB11"
+
+echo " Scaling to 16GB + 400% CPU..."
+SCALE11=$(api -X PUT "$API_URL/api/sandboxes/$SB11/limits" -d '{"memoryMB":16384,"cpuPercent":400}' 2>/dev/null)
+if echo "$SCALE11" | grep -q "ok"; then
+ pass "Scaled to 16GB"
+
+ # Allocate some real memory
+ TIMEOUT=30 exec_run "$SB11" "sh" "-c" "python3 -c 'x=bytearray(8*1024*1024*1024)' &" >/dev/null 2>&1 || true
+ sleep 3
+
+ SRC11=$(sandbox_worker "$SB11")
+ TGT11=$(pick_other_worker "$SRC11")
+ if [ -n "$TGT11" ]; then
+ echo " Migrating 16GB sandbox $SRC11 → $TGT11..."
+ START11=$(python3 -c "import time; print(int(time.time()*1000))")
+ MIG11=$(TIMEOUT=300 api -X POST "$API_URL/api/sandboxes/$SB11/migrate" -d "{\"targetWorker\":\"$TGT11\"}" 2>/dev/null)
+ END11=$(python3 -c "import time; print(int(time.time()*1000))")
+ DUR11=$((END11-START11))
+
+ if echo "$MIG11" | grep -qi "error"; then
+ fail "Large sandbox migration failed: $(echo "$MIG11" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)"
+ else
+ pass "16GB sandbox migrated in ${DUR11}ms"
+ fi
+
+ exec_ok "$SB11" && pass "Large sandbox responsive after migration" || fail "Large sandbox dead after migration"
+
+ MEM11=$(exec_stdout "$SB11" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+ echo " Memory after migration: ${MEM11}MB"
+ [ -n "$MEM11" ] && [ "$MEM11" -gt 14000 ] && pass "Memory preserved at ${MEM11}MB" || fail "Memory: ${MEM11}MB"
+ else
+ skip "No target worker for large migration"
+ fi
+elif echo "$SCALE11" | grep -qi "insufficient_capacity\|migrat"; then
+ # It may have auto-migrated
+ W11=$(sandbox_worker "$SB11")
+ echo " Auto-migration may have occurred, now on: $W11"
+ exec_ok "$SB11" && pass "Sandbox responsive after auto-migration" || fail "Sandbox dead"
+else
+ fail "Scale to 16GB failed: $SCALE11"
+fi
+destroy_sandbox "$SB11" 2>/dev/null
+
+# ============================================================
+h "Test 12: Checkpoint + restore — named snapshot"
+
+SB12=$(create_sb)
+echo " Created: $SB12"
+
+# Write state
+exec_run "$SB12" "sh" "-c" "echo version-1 > /workspace/version.txt && seq 1 1000 > /workspace/data.txt" >/dev/null 2>&1
+V1=$(exec_stdout "$SB12" "cat" "/workspace/version.txt" 2>/dev/null)
+echo " State v1: $V1"
+
+# Create checkpoint
+echo " Creating checkpoint 'snap-v1'..."
+CP_RESULT=$(TIMEOUT=120 api -X POST "$API_URL/api/sandboxes/$SB12/checkpoints" -d '{"name":"snap-v1"}' 2>/dev/null)
+echo " Checkpoint result: $CP_RESULT"
+CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
+
+if [ -n "$CP_ID" ] && [ "$CP_ID" != "" ]; then
+ pass "Checkpoint created: $CP_ID"
+
+ # Modify state
+ exec_run "$SB12" "sh" "-c" "echo version-2 > /workspace/version.txt && rm /workspace/data.txt" >/dev/null 2>&1
+ V2=$(exec_stdout "$SB12" "cat" "/workspace/version.txt" 2>/dev/null)
+ echo " State changed to: $V2"
+
+ # Wait for checkpoint to be ready
+ echo " Waiting for checkpoint to be ready..."
+ for i in $(seq 1 12); do
+ CP_LIST=$(api "$API_URL/api/sandboxes/$SB12/checkpoints" 2>/dev/null)
+ CP_STATUS=$(echo "$CP_LIST" | python3 -c "
+import sys, json
+for cp in json.load(sys.stdin):
+ if cp.get('id') == '$CP_ID':
+ print(cp.get('status', ''))
+ break
+" 2>/dev/null)
+ [ "$CP_STATUS" = "ready" ] && break
+ sleep 5
+ done
+ echo " Checkpoint status: $CP_STATUS"
+
+ if [ "$CP_STATUS" = "ready" ]; then
+ # Restore to checkpoint
+ echo " Restoring to snap-v1..."
+ RESTORE=$(TIMEOUT=120 api -X POST "$API_URL/api/sandboxes/$SB12/checkpoints/$CP_ID/restore" 2>/dev/null)
+ echo " Restore result: $RESTORE"
+ sleep 3
+
+ V_AFTER=$(exec_stdout "$SB12" "cat" "/workspace/version.txt" 2>/dev/null)
+ echo " State after restore: $V_AFTER"
+ [ "$V_AFTER" = "version-1" ] && pass "Restored to checkpoint: version-1" || fail "Restore failed: got $V_AFTER"
+
+ DATA_EXISTS=$(exec_stdout "$SB12" "wc" "-l" "/workspace/data.txt" 2>/dev/null | awk '{print $1}')
+ [ "$DATA_EXISTS" = "1000" ] && pass "Deleted file restored (1000 lines)" || fail "Deleted file not restored: $DATA_EXISTS"
+ else
+ skip "Checkpoint not ready after 60s (status=$CP_STATUS)"
+ fi
+
+ # Clean up checkpoint
+ api -X DELETE "$API_URL/api/sandboxes/$SB12/checkpoints/$CP_ID" >/dev/null 2>&1
+else
+ if echo "$CP_RESULT" | grep -qi "error"; then
+ skip "Checkpoints not available: $(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)"
+ else
+ fail "No checkpoint ID returned"
+ fi
+fi
+destroy_sandbox "$SB12" 2>/dev/null
+
+# ============================================================
+h "Final Summary"
+flush_sandboxes
+echo ""
+echo "Workers:"
+get_workers | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(f' {w[\"worker_id\"]}: {w[\"current\"]}/{w[\"capacity\"]} cpu={w[\"cpu_pct\"]:.0f}% mem={w[\"mem_pct\"]:.0f}%')
+" 2>/dev/null
+echo ""
+summary