Skip to content

An open-source, faster Devin alternative

TypeScript

more tests

Brian Reardon6f922c8c96eb
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 76f18a35..2c42d4c3 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -146,6 +146,7 @@ func main() {
redisRegistry.Start()
defer redisRegistry.Stop()
opts.WorkerRegistry = redisRegistry
+ redisRegistry.SetIdleReserve(cfg.IdleReserveWorkers)
opts.RedisClient = redisRegistry.RedisClient()
log.Println("opensandbox: Redis worker registry started")
diff --git a/internal/api/admin_events.go b/internal/api/admin_events.go
new file mode 100644
index 00000000..ce6a6bc2
--- /dev/null
+++ b/internal/api/admin_events.go
@@ -0,0 +1,212 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/labstack/echo/v4"
+)
+
+// AdminEvent represents a real-time event for the admin dashboard.
+type AdminEvent struct {
+ Time string `json:"time"`
+ Type string `json:"type"` // "create", "destroy", "scale", "migrate", "error", "scaler"
+ Sandbox string `json:"sandbox"` // sandbox ID
+ Worker string `json:"worker"` // worker ID
+ Detail string `json:"detail"` // human-readable detail
+}
+
+// AdminEventBus broadcasts events to connected SSE clients.
+type AdminEventBus struct {
+ mu sync.RWMutex
+ clients map[chan AdminEvent]struct{}
+ history []AdminEvent // last 200 events
+}
+
+// NewAdminEventBus creates a new event bus.
+func NewAdminEventBus() *AdminEventBus {
+ return &AdminEventBus{
+ clients: make(map[chan AdminEvent]struct{}),
+ }
+}
+
+// Publish sends an event to all connected clients and stores in history.
+func (b *AdminEventBus) Publish(eventType, sandboxID, workerID, detail string) {
+ evt := AdminEvent{
+ Time: time.Now().Format("15:04:05"),
+ Type: eventType,
+ Sandbox: sandboxID,
+ Worker: workerID,
+ Detail: detail,
+ }
+
+ b.mu.Lock()
+ b.history = append(b.history, evt)
+ if len(b.history) > 2000 {
+ b.history = b.history[len(b.history)-2000:]
+ }
+ // Copy clients under lock
+ clients := make([]chan AdminEvent, 0, len(b.clients))
+ for ch := range b.clients {
+ clients = append(clients, ch)
+ }
+ b.mu.Unlock()
+
+ // Send non-blocking to each client
+ for _, ch := range clients {
+ select {
+ case ch <- evt:
+ default:
+ // Client too slow, skip
+ }
+ }
+}
+
+// subscribe returns a channel that receives events and a cleanup function.
+func (b *AdminEventBus) subscribe() (chan AdminEvent, func()) {
+ ch := make(chan AdminEvent, 50)
+ b.mu.Lock()
+ b.clients[ch] = struct{}{}
+ b.mu.Unlock()
+ return ch, func() {
+ b.mu.Lock()
+ delete(b.clients, ch)
+ b.mu.Unlock()
+ close(ch)
+ }
+}
+
+// History returns the last N events.
+func (b *AdminEventBus) History() []AdminEvent {
+ b.mu.RLock()
+ defer b.mu.RUnlock()
+ result := make([]AdminEvent, len(b.history))
+ copy(result, b.history)
+ return result
+}
+
+// adminEventsSSE streams events to the admin dashboard via Server-Sent Events.
+func (s *Server) adminEventsSSE(c echo.Context) error {
+ if s.adminEvents == nil {
+ return c.String(http.StatusServiceUnavailable, "event bus not initialized")
+ }
+
+ c.Response().Header().Set("Content-Type", "text/event-stream")
+ c.Response().Header().Set("Cache-Control", "no-cache")
+ c.Response().Header().Set("Connection", "keep-alive")
+ c.Response().WriteHeader(http.StatusOK)
+ c.Response().Flush()
+
+ // Send history first
+ for _, evt := range s.adminEvents.History() {
+ data, _ := json.Marshal(evt)
+ fmt.Fprintf(c.Response(), "data: %s\n\n", data)
+ }
+ c.Response().Flush()
+
+ // Subscribe to new events
+ ch, cleanup := s.adminEvents.subscribe()
+ defer cleanup()
+
+ for {
+ select {
+ case evt, ok := <-ch:
+ if !ok {
+ return nil
+ }
+ data, _ := json.Marshal(evt)
+ fmt.Fprintf(c.Response(), "data: %s\n\n", data)
+ c.Response().Flush()
+ case <-c.Request().Context().Done():
+ return nil
+ }
+ }
+}
+
+// adminEventsHistory returns recent events as JSON (for initial page load).
+func (s *Server) adminEventsHistory(c echo.Context) error {
+ if s.adminEvents == nil {
+ return c.JSON(http.StatusOK, []AdminEvent{})
+ }
+ return c.JSON(http.StatusOK, s.adminEvents.History())
+}
+
+// emitEvent publishes an event to the admin dashboard if the event bus is initialized.
+func (s *Server) emitEvent(eventType, sandboxID, workerID, detail string) {
+ if s.adminEvents != nil {
+ s.adminEvents.Publish(eventType, sandboxID, workerID, detail)
+ }
+}
+
+// adminReport generates a summary report from the event history.
+func (s *Server) adminReport(c echo.Context) error {
+ if s.adminEvents == nil {
+ return c.JSON(http.StatusOK, map[string]string{"error": "no events"})
+ }
+ events := s.adminEvents.History()
+
+ creates := 0
+ destroys := 0
+ scales := 0
+ scaleFails := 0
+ migrations := 0
+ migrationDetails := []map[string]string{}
+ errors := 0
+
+ for _, e := range events {
+ switch e.Type {
+ case "create":
+ creates++
+ case "destroy":
+ destroys++
+ case "scale":
+ scales++
+ case "migrate":
+ migrations++
+ migrationDetails = append(migrationDetails, map[string]string{
+ "time": e.Time,
+ "sandbox": e.Sandbox,
+ "worker": e.Worker,
+ "detail": e.Detail,
+ })
+ case "error":
+ errors++
+ if strings.Contains(e.Detail, "scale") {
+ scaleFails++
+ }
+ }
+ }
+
+ // Get current worker state
+ workers := []map[string]interface{}{}
+ if s.workerRegistry != nil {
+ for _, w := range s.workerRegistry.GetAllWorkers() {
+ workers = append(workers, map[string]interface{}{
+ "id": w.ID[len(w.ID)-8:],
+ "current": w.Current,
+ "cpu_pct": w.CPUPct,
+ "mem_pct": w.MemPct,
+ "disk_pct": w.DiskPct,
+ })
+ }
+ }
+
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "total_events": len(events),
+ "creates": creates,
+ "destroys": destroys,
+ "scales": scales,
+ "scale_fails": scaleFails,
+ "migrations": map[string]interface{}{
+ "total": migrations,
+ "succeeded": migrations, // all logged migrations are successes (failures logged as errors)
+ "details": migrationDetails,
+ },
+ "errors": errors,
+ "workers": workers,
+ })
+}
diff --git a/internal/api/admin_status.go b/internal/api/admin_status.go
new file mode 100644
index 00000000..38323dcc
--- /dev/null
+++ b/internal/api/admin_status.go
@@ -0,0 +1,232 @@
+package api
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+)
+
+// adminStatusPage serves a self-contained HTML dashboard showing real-time
+// worker status, sandbox counts, and system health. Auto-refreshes every 2s.
+// Protected by API key auth (same as /api/workers).
+func (s *Server) adminStatusPage(c echo.Context) error {
+ apiKey := c.Request().Header.Get("X-API-Key")
+ if apiKey == "" {
+ apiKey = c.QueryParam("key")
+ }
+
+ return c.HTML(http.StatusOK, adminHTML)
+}
+
+const adminHTML = `<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>OpenSandbox — Admin Status</title>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body { background: #08080c; color: #e0e0e0; font-family: 'JetBrains Mono', 'SF Mono', monospace; font-size: 13px; padding: 20px; }
+ h1 { font-size: 18px; color: #818cf8; margin-bottom: 4px; }
+ .subtitle { color: #666; font-size: 12px; margin-bottom: 20px; }
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin-bottom: 20px; }
+ .stat { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.06); border-radius: 8px; padding: 16px; }
+ .stat .label { color: #888; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; }
+ .stat .value { font-size: 28px; font-weight: bold; margin-top: 4px; }
+ .stat .value.green { color: #34d399; }
+ .stat .value.blue { color: #60a5fa; }
+ .stat .value.amber { color: #fbbf24; }
+ .stat .value.red { color: #f87171; }
+ table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
+ th { text-align: left; color: #888; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; padding: 8px 12px; border-bottom: 1px solid rgba(255,255,255,0.06); }
+ td { padding: 8px 12px; border-bottom: 1px solid rgba(255,255,255,0.03); }
+ tr:hover td { background: rgba(255,255,255,0.02); }
+ .bar-bg { background: rgba(255,255,255,0.05); border-radius: 4px; height: 8px; width: 100px; display: inline-block; vertical-align: middle; }
+ .bar-fill { height: 8px; border-radius: 4px; transition: width 0.5s; }
+ .bar-fill.cpu { background: #818cf8; }
+ .bar-fill.mem { background: #34d399; }
+ .bar-fill.disk { background: #fbbf24; }
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 11px; }
+ .badge.ready { background: rgba(52,211,153,0.15); color: #34d399; }
+ .badge.not-ready { background: rgba(248,113,113,0.15); color: #f87171; }
+ .badge.leader { background: rgba(129,140,248,0.15); color: #818cf8; }
+ .log { background: rgba(255,255,255,0.02); border: 1px solid rgba(255,255,255,0.04); border-radius: 8px; padding: 12px; max-height: 300px; overflow-y: auto; font-size: 12px; color: #aaa; }
+ .log .entry { padding: 2px 0; }
+ .log .time { color: #666; }
+ .section { margin-bottom: 24px; }
+ .section h2 { font-size: 14px; color: #ccc; margin-bottom: 8px; }
+ #status-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; animation: pulse 2s infinite; }
+ @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.3; } }
+ .connected { background: #34d399; }
+ .disconnected { background: #f87171; }
+</style>
+</head>
+<body>
+<h1>OpenSandbox Admin Status</h1>
+<div class="subtitle"><span id="status-dot" class="connected"></span><span id="connection">Connected</span> — refreshing every 2s</div>
+
+<div class="grid" id="stats"></div>
+
+<div class="section">
+ <h2>Workers</h2>
+ <table>
+ <thead><tr><th>Worker</th><th>Machine</th><th>Sandboxes</th><th>CPU</th><th>Memory</th><th>Disk</th><th>Version</th></tr></thead>
+ <tbody id="workers"></tbody>
+ </table>
+</div>
+
+<div class="section" style="display:flex;gap:12px;align-items:center">
+ <h2>Activity Log</h2>
+ <button onclick="generateReport()" style="background:rgba(129,140,248,0.15);color:#818cf8;border:1px solid rgba(129,140,248,0.3);padding:4px 12px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:12px">Generate Report</button>
+ <button onclick="clearLog()" style="background:rgba(255,255,255,0.05);color:#888;border:1px solid rgba(255,255,255,0.1);padding:4px 12px;border-radius:4px;cursor:pointer;font-family:inherit;font-size:12px">Clear</button>
+</div>
+<div class="log" id="log"></div>
+
+<script>
+const API_KEY = new URLSearchParams(window.location.search).get('key') || '';
+const BASE = window.location.origin;
+let prevWorkerCount = -1;
+let prevSandboxCount = -1;
+
+function bar(pct, cls) {
+ return '<div class="bar-bg"><div class="bar-fill ' + cls + '" style="width:' + Math.min(pct, 100) + '%"></div></div> ' + pct.toFixed(0) + '%';
+}
+
+const typeColors = {
+ create: '#34d399', destroy: '#f87171', scale: '#fbbf24',
+ migrate: '#818cf8', error: '#f87171', scaler: '#60a5fa'
+};
+const typeIcons = {
+ create: '+', destroy: 'x', scale: '~',
+ migrate: '→', error: '!', scaler: '⚙'
+};
+
+function addLog(msg, type) {
+ const log = document.getElementById('log');
+ const now = new Date().toLocaleTimeString();
+ const color = typeColors[type] || '#aaa';
+ const icon = typeIcons[type] || '•';
+ const el = document.createElement('div');
+ el.className = 'entry';
+ el.innerHTML = '<span class="time">' + now + '</span> ' +
+ '<span style="color:' + color + ';font-weight:bold">[' + icon + ']</span> ' + msg;
+ log.insertBefore(el, log.firstChild);
+ while (log.children.length > 200) log.removeChild(log.lastChild);
+}
+
+async function refresh() {
+ try {
+ const [workersResp, readyResp] = await Promise.all([
+ fetch(BASE + '/api/workers', { headers: { 'X-API-Key': API_KEY } }),
+ fetch(BASE + '/readyz')
+ ]);
+
+ const workers = await workersResp.json();
+ const ready = await readyResp.json();
+
+ document.getElementById('status-dot').className = 'connected';
+ document.getElementById('connection').textContent = 'Connected';
+
+ // Use worker-reported counts (more accurate than DB query during bursts)
+ const totalSandboxes = workers.reduce((s, w) => s + w.current, 0);
+ const totalCapacity = workers.reduce((s, w) => s + w.capacity, 0);
+ const maxCPU = workers.length ? Math.max(...workers.map(w => w.cpu_pct)) : 0;
+ const maxMem = workers.length ? Math.max(...workers.map(w => w.mem_pct)) : 0;
+
+ // Stats cards
+ document.getElementById('stats').innerHTML =
+ '<div class="stat"><div class="label">Workers</div><div class="value blue">' + workers.length + '</div></div>' +
+ '<div class="stat"><div class="label">Sandboxes</div><div class="value green">' + totalSandboxes + '</div></div>' +
+ '<div class="stat"><div class="label">Peak CPU</div><div class="value ' + (maxCPU > 80 ? 'red' : maxCPU > 50 ? 'amber' : 'green') + '">' + maxCPU.toFixed(0) + '%</div></div>' +
+ '<div class="stat"><div class="label">Peak Memory</div><div class="value ' + (maxMem > 80 ? 'red' : maxMem > 50 ? 'amber' : 'green') + '">' + maxMem.toFixed(0) + '%</div></div>' +
+ '<div class="stat"><div class="label">Readiness</div><div class="value"><span class="badge ' + (ready.status === 'ready' ? 'ready' : 'not-ready') + '">' + ready.status + '</span></div></div>';
+
+ // Workers table
+ const tbody = document.getElementById('workers');
+ tbody.innerHTML = workers.sort((a, b) => b.current - a.current).map(w =>
+ '<tr>' +
+ '<td>' + w.worker_id.slice(-12) + '</td>' +
+ '<td style="color:#666">' + (w.machine_id || '-').slice(-12) + '</td>' +
+ '<td><strong>' + w.current + '</strong></td>' +
+ '<td>' + bar(w.cpu_pct, 'cpu') + '</td>' +
+ '<td>' + bar(w.mem_pct, 'mem') + '</td>' +
+ '<td>' + bar(w.disk_pct, 'disk') + '</td>' +
+ '<td style="color:#666">' + (w.worker_version || 'dev') + '</td>' +
+ '</tr>'
+ ).join('');
+
+ // Log worker/sandbox count changes
+ if (prevWorkerCount >= 0 && workers.length !== prevWorkerCount) {
+ addLog(workers.length > prevWorkerCount
+ ? 'Worker scaled up: ' + prevWorkerCount + ' → ' + workers.length
+ : 'Worker scaled down: ' + prevWorkerCount + ' → ' + workers.length, 'scaler');
+ }
+ if (prevSandboxCount >= 0 && totalSandboxes !== prevSandboxCount) {
+ const delta = totalSandboxes - prevSandboxCount;
+ addLog((delta > 0 ? '+' : '') + delta + ' sandboxes (' + totalSandboxes + ' total)', delta > 0 ? 'create' : 'destroy');
+ }
+ prevWorkerCount = workers.length;
+ prevSandboxCount = totalSandboxes;
+
+ } catch (e) {
+ document.getElementById('status-dot').className = 'disconnected';
+ document.getElementById('connection').textContent = 'Disconnected: ' + e.message;
+ }
+}
+
+function clearLog() {
+ document.getElementById('log').innerHTML = '';
+}
+
+async function generateReport() {
+ try {
+ const resp = await fetch(BASE + '/admin/report', { headers: { 'X-API-Key': API_KEY } });
+ const r = await resp.json();
+
+ addLog('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'scaler');
+ addLog('<strong>REPORT</strong>', 'scaler');
+ addLog('Events: ' + r.total_events + ' | Creates: ' + r.creates + ' | Destroys: ' + r.destroys, 'create');
+ addLog('Scales: ' + r.scales + ' | Migrations: ' + r.migrations.total, 'scale');
+
+ if (r.migrations.details && r.migrations.details.length > 0) {
+ addLog('<strong>Migrations (' + r.migrations.total + ')</strong>:', 'migrate');
+ r.migrations.details.forEach(function(m) {
+ addLog(m.sandbox.slice(-8) + ' → ' + m.worker.slice(-8) + ': ' + m.detail, 'migrate');
+ });
+ addLog('All ' + r.migrations.total + ' migrations succeeded', 'migrate');
+ } else {
+ addLog('No migrations triggered', 'scale');
+ }
+
+ if (r.workers) {
+ addLog('<strong>Workers:</strong>', 'scaler');
+ r.workers.sort(function(a,b) { return b.current - a.current; }).forEach(function(w) {
+ const bar = w.current > 0 ? '█'.repeat(Math.min(w.current, 40)) : '·';
+ addLog(w.id + ' ' + bar + ' ' + w.current + ' sb cpu=' + w.cpu_pct.toFixed(0) + '% mem=' + w.mem_pct.toFixed(0) + '%', 'scaler');
+ });
+ }
+ addLog('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'scaler');
+ } catch(e) {
+ addLog('Report failed: ' + e.message, 'error');
+ }
+}
+
+refresh();
+setInterval(refresh, 2000);
+
+// Connect to SSE event stream for real-time events
+const evtSource = new EventSource(BASE + '/admin/events');
+evtSource.onmessage = function(e) {
+ try {
+ const evt = JSON.parse(e.data);
+ let msg = evt.detail;
+ if (evt.sandbox) msg = '<span style="color:#888">' + evt.sandbox.slice(-8) + '</span> ' + msg;
+ addLog(msg, evt.type);
+ } catch(err) {}
+};
+evtSource.onerror = function() {
+ // Will auto-reconnect
+};
+</script>
+</body>
+</html>`
diff --git a/internal/api/router.go b/internal/api/router.go
index 631cc657..6b98cf44 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -53,6 +53,7 @@ type Server struct {
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
stripeClient *billing.StripeClient // nil if Stripe not configured
redisClient *redis.Client // nil if Redis not configured (for health checks)
+ adminEvents *AdminEventBus // real-time event bus for admin dashboard
ready int32 // atomic: 1 = ready, 0 = not ready
}
@@ -114,6 +115,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.sandboxAPIProxy = opts.SandboxAPIProxy
s.stripeClient = opts.StripeClient
s.redisClient = opts.RedisClient
+ s.adminEvents = NewAdminEventBus()
// Wire up readiness waiting so the proxy blocks until async creates finish
if s.sandboxAPIProxy != nil {
@@ -156,6 +158,23 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
return c.JSON(http.StatusOK, map[string]string{"status": "alive"})
})
e.GET("/readyz", s.readinessCheck)
+ // Admin routes — accept API key via header or ?key= query param
+ admin := e.Group("/admin", func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ key := c.Request().Header.Get("X-API-Key")
+ if key == "" {
+ key = c.QueryParam("key")
+ }
+ if key == "" || key != apiKey {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "invalid API key"})
+ }
+ return next(c)
+ }
+ })
+ admin.GET("/status", s.adminStatusPage)
+ admin.GET("/events", s.adminEventsSSE)
+ admin.GET("/events/history", s.adminEventsHistory)
+ admin.GET("/report", s.adminReport)
// Signed URL endpoints (self-authenticated via HMAC, no API key required)
e.GET("/api/sandboxes/:id/files/download", s.signedDownload)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 71621516..608af0dc 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -419,6 +419,8 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
}
}
+ s.emitEvent("create", grpcResp.SandboxId, worker.ID, fmt.Sprintf("created on %s", worker.ID[len(worker.ID)-8:]))
+
resp := map[string]interface{}{
"sandboxID": grpcResp.SandboxId,
"token": token,
@@ -599,6 +601,8 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)
}
+ s.emitEvent("destroy", sandboxID, session.WorkerID, "destroyed")
+
return c.NoContent(http.StatusNoContent)
}
@@ -815,6 +819,7 @@ func (s *Server) migrateSandbox(c echo.Context) error {
elapsed := time.Since(t0).Milliseconds()
log.Printf("migrate %s: complete in %dms (source=%s target=%s)", id, elapsed, session.WorkerID, req.TargetWorker)
+ s.emitEvent("migrate", id, req.TargetWorker, fmt.Sprintf("migrated from %s in %dms", session.WorkerID[len(session.WorkerID)-8:], elapsed))
return c.JSON(http.StatusOK, map[string]interface{}{
"sandboxID": id,
@@ -1066,6 +1071,11 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32
})
}
+ if migrated {
+ s.emitEvent("migrate", sandboxID, workerID, fmt.Sprintf("auto-migrated for scale to %dMB", requestedMemMB))
+ }
+ s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))
+
return c.JSON(http.StatusOK, map[string]interface{}{
"sandboxID": sandboxID,
"workerID": workerID,
@@ -1087,15 +1097,17 @@ func (s *Server) findScaleMigrationTarget(sourceWorkerID string, requestedMemMB
if w.ID == sourceWorkerID {
continue
}
- if w.CPUPct > 80 || w.MemPct > 60 {
- continue // need plenty of headroom for a big sandbox
+ if w.CPUPct > 90 || w.MemPct > 85 {
+ continue // worker under heavy pressure
}
- remaining := w.Capacity - w.Current
- if remaining <= 0 {
- continue // worker is full, can't take a migrated sandbox
+ // Check committed memory — the target needs enough room for the requested size.
+ reserveMB := w.TotalMemoryMB / 5 // 20% for OS
+ availableMB := w.TotalMemoryMB - w.CommittedMemoryMB - reserveMB
+ if availableMB < requestedMemMB {
+ continue
}
- // Score: prefer emptier workers (more room for the big sandbox)
- score := float64(remaining) * (100.0 - w.MemPct) / 100.0
+ // Score: more available memory = better target
+ score := float64(availableMB - requestedMemMB)
if score > bestScore {
best = w
bestScore = score
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index fb2075ca..bb8179c1 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -40,12 +40,20 @@ type WorkerEntry struct {
// backed by Redis pub/sub for real-time updates and periodic SCAN for reconciliation.
// It also maintains a persistent gRPC connection pool to workers.
type RedisWorkerRegistry struct {
- rdb *redis.Client
- mu sync.RWMutex
- workers map[string]*WorkerEntry // in-memory hot cache
- conns map[string]*grpc.ClientConn // persistent gRPC connections
- clients map[string]pb.SandboxWorkerClient // cached gRPC clients
- stop chan struct{}
+ rdb *redis.Client
+ mu sync.RWMutex
+ workers map[string]*WorkerEntry // in-memory hot cache
+ conns map[string]*grpc.ClientConn // persistent gRPC connections
+ clients map[string]pb.SandboxWorkerClient // cached gRPC clients
+ idleReserve int // target idle workers to protect from routing
+ stop chan struct{}
+}
+
+// SetIdleReserve configures how many idle workers to protect from normal routing.
+func (r *RedisWorkerRegistry) SetIdleReserve(n int) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.idleReserve = n
}
// RedisClient returns the underlying Redis client (for health checks, shared state, etc.).
@@ -314,14 +322,28 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
var best *WorkerEntry
bestScore := -1.0
- // Bin-pack strategy: fill active workers before touching idle reserves.
- // This keeps idle workers as headroom for burst absorption and avoids
- // thrashing between scale-up (headroom) and scale-down (low utilization).
+ // Count idle workers to decide whether to protect reserves
+ idleCount := 0
+ for _, w := range r.workers {
+ if (region == "" || w.Region == region) && w.Current == 0 {
+ idleCount++
+ }
+ }
+ protectReserves := idleCount <= r.idleReserve
+
+ // Bin-pack strategy: fill active workers to capacity, then overflow active
+ // workers (if reserves need protection), then use idle reserves, then
+ // over-provision across all workers.
+ //
+ // Priority (when reserves are protected):
+ // 1. Active worker with capacity → score 100+
+ // 2. Over-capacity active worker → score 1-10
+ // 3. Idle reserve worker → score 0.1 (only when no active option)
//
- // Priority order:
- // 1. Most-loaded worker that still has capacity (pack tightly)
- // 2. Idle worker (dip into reserve only when active workers are full)
- // 3. Over-capacity worker (absorb overflow while new workers boot)
+ // Priority (when surplus idle workers exist):
+ // 1. Active worker with capacity → score 100+
+ // 2. Idle worker (surplus, safe to use) → score 50
+ // 3. Over-capacity active worker → score 1-10
scoreWorker := func(w *WorkerEntry) float64 {
if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
return -1 // skip
@@ -330,18 +352,29 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0
if remaining <= 0 {
- // Over capacity: last resort
- return 0.01 * resourceScore
+ if w.Current == 0 {
+ return -1 // shouldn't happen but guard
+ }
+ // Over capacity: spread evenly among overloaded workers
+ overBy := float64(w.Current - w.Capacity)
+ if protectReserves {
+ // Score 1-10: above idle reserves (0.1) so we overflow active
+ // workers before touching reserves
+ return 10.0 * resourceScore / (1.0 + overBy)
+ }
+ return 0.01 * resourceScore / (1.0 + overBy)
}
if w.Current == 0 {
- // Idle/reserve: prefer active workers over idle ones.
- // Score between 0.1 and 1.0 so it ranks below any active worker.
- return 0.1 * resourceScore
+ if protectReserves {
+ // Reserves protected: score very low so active workers (including
+ // over-capacity) get used first. Only used as absolute last resort.
+ return 0.001 * resourceScore
+ }
+ // Surplus idle workers: safe to use, score below active but above over-capacity
+ return 50.0 * resourceScore
}
- // Active with capacity: higher current = higher score (bin-pack).
- // Add remaining as a tiebreaker so we don't overflow a nearly-full worker
- // when another active worker has more room.
- return float64(w.Current)*10.0 + float64(remaining)*resourceScore
+ // Active with capacity: highest priority (bin-pack).
+ return 100.0 + float64(w.Current)*10.0 + float64(remaining)*resourceScore
}
// First pass: try workers in the requested region
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index d2a19e8a..21425ed8 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -942,10 +942,12 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
// Memory layout: base memory + virtio-mem pool for hotplug scaling.
// The virtio-mem backend allocates lazily (only requested-size is committed),
// but maxmem must exceed base+pool for QEMU to accept the device.
- // Pool size = 15GB covers scaling from 1GB base up to 16GB total.
- // For migrations requesting >16GB, we use the full requested amount as base
- // (no virtio-mem needed since the source already has the memory hotplugged).
- virtioMemPoolMB := 15360 // 15GB — enough for 1GB->16GB scaling
+ // Pool = 16GB - base, so any sandbox can scale up to 16GB total regardless of base.
+ // Round up to 128MB block alignment.
+ virtioMemPoolMB := ((16384 - memMB + 127) / 128) * 128
+ if virtioMemPoolMB < 1024 {
+ virtioMemPoolMB = 1024 // minimum 1GB pool
+ }
maxMemMB := memMB + virtioMemPoolMB
return []string{
diff --git a/scripts/qemu-tests/38-chaos-200.sh b/scripts/qemu-tests/38-chaos-200.sh
new file mode 100755
index 00000000..6d540efc
--- /dev/null
+++ b/scripts/qemu-tests/38-chaos-200.sh
@@ -0,0 +1,260 @@
+#!/usr/bin/env bash
+# 38-chaos-200.sh — 200-sandbox chaos test with random scaling
+#
+# Creates 200 sandboxes in waves, randomly scales memory/disk on each,
+# randomly destroys some, creates replacements, checks responsiveness throughout.
+# Tests autoscaler under real-world chaotic load.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+TARGET=${1:-200}
+WAVES=5
+PER_WAVE=$((TARGET / WAVES))
+CHAOS_ROUNDS=10
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+worker_summary() {
+ get_workers | python3 -c "
+import sys,json
+w = json.load(sys.stdin)
+total = sum(x['current'] for x in w)
+print(f'{len(w)} workers, {total} sandboxes')
+for x in w:
+ print(f' {x[\"worker_id\"][-8:]}: {x[\"current\"]}/{x[\"capacity\"]} cpu={x[\"cpu_pct\"]:.0f}% mem={x[\"mem_pct\"]:.0f}%')
+" 2>/dev/null
+}
+
+create_one() {
+ local result
+ result=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null
+}
+
+exec_check() {
+ local out
+ out=$(exec_stdout "$1" "echo" "ok" 2>/dev/null)
+ [ "$out" = "ok" ]
+}
+
+SANDBOX_FILE=$(mktemp)
+STATS_FILE=$(mktemp)
+echo "0 0 0 0" > "$STATS_FILE" # created failed responsive unresponsive
+
+update_stat() {
+ local idx=$1 delta=$2
+ awk -v i="$idx" -v d="$delta" '{$i=$i+d; print}' "$STATS_FILE" > "${STATS_FILE}.tmp"
+ mv "${STATS_FILE}.tmp" "$STATS_FILE"
+}
+
+cleanup() {
+ echo ""
+ echo "=== Cleanup ==="
+ local count=0
+ while read -r sb; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & count=$((count+1)); }
+ # Throttle parallel deletes
+ [ $((count % 20)) -eq 0 ] && wait 2>/dev/null
+ done < "$SANDBOX_FILE"
+ wait 2>/dev/null
+ echo "Destroyed $count sandboxes"
+ rm -f "$SANDBOX_FILE" "$STATS_FILE"
+}
+trap cleanup EXIT INT TERM
+
+echo "=== 200-Sandbox Chaos Test ==="
+echo "Target: $TARGET sandboxes in $WAVES waves of $PER_WAVE"
+echo ""
+echo "Starting state:"
+worker_summary
+echo ""
+
+# ============================================================
+h "Phase 1: Ramp up to $TARGET sandboxes"
+
+TOTAL_CREATED=0
+TOTAL_FAILED=0
+
+for wave in $(seq 1 $WAVES); do
+ echo " Wave $wave/$WAVES: creating $PER_WAVE sandboxes..."
+ WAVE_OK=0
+ WAVE_DIR=$(mktemp -d)
+
+ for i in $(seq 1 $PER_WAVE); do
+ (
+ sb=$(create_one)
+ if [ -n "$sb" ] && [ "$sb" != "" ] && [ "$sb" != "null" ]; then
+ echo "$sb" > "$WAVE_DIR/$i"
+ fi
+ ) &
+ # Limit concurrency to 10 at a time
+ [ $((i % 10)) -eq 0 ] && wait 2>/dev/null
+ done
+ wait 2>/dev/null
+
+ for f in "$WAVE_DIR"/*; do
+ [ -f "$f" ] || continue
+ sb=$(cat "$f")
+ echo "$sb" >> "$SANDBOX_FILE"
+ WAVE_OK=$((WAVE_OK + 1))
+ done
+ rm -rf "$WAVE_DIR"
+
+ TOTAL_CREATED=$((TOTAL_CREATED + WAVE_OK))
+ TOTAL_FAILED=$((TOTAL_FAILED + PER_WAVE - WAVE_OK))
+ echo " Created: $WAVE_OK/$PER_WAVE (total: $TOTAL_CREATED, failed: $TOTAL_FAILED)"
+ echo " $(worker_summary | head -1)"
+
+ # Brief pause between waves for scaler to react
+ sleep 5
+done
+
+echo ""
+[ "$TOTAL_CREATED" -ge $((TARGET * 80 / 100)) ] && pass "Created $TOTAL_CREATED/$TARGET sandboxes (≥80%)" || fail "Only $TOTAL_CREATED/$TARGET created"
+
+echo ""
+echo "Worker state after ramp:"
+worker_summary
+
+# ============================================================
+h "Phase 2: Responsiveness check (sample 20)"
+
+echo " Checking 20 random sandboxes..."
+RESPONSIVE=0
+SAMPLE=$(sort -R < "$SANDBOX_FILE" | head -20)
+for sb in $SAMPLE; do
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE + 1))
+done
+echo " $RESPONSIVE/20 responsive"
+[ "$RESPONSIVE" -ge 18 ] && pass "≥90% responsive under load ($RESPONSIVE/20)" || fail "Only $RESPONSIVE/20 responsive"
+
+# ============================================================
+h "Phase 3: Chaos — random scale + destroy + create ($CHAOS_ROUNDS rounds)"
+
+MEM_OPTIONS="512 1024 2048 4096"
+SCALES_OK=0
+SCALES_FAIL=0
+DESTROYS=0
+CREATES=0
+
+for round in $(seq 1 $CHAOS_ROUNDS); do
+ echo " Round $round/$CHAOS_ROUNDS"
+
+ # Pick 5 random sandboxes to scale memory
+ SCALE_TARGETS=$(sort -R < "$SANDBOX_FILE" | head -5)
+ for sb in $SCALE_TARGETS; do
+ [ -z "$sb" ] && continue
+ MEM=$(echo $MEM_OPTIONS | tr ' ' '\n' | sort -R | head -1)
+ result=$(api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d "{\"memoryMB\":$MEM,\"cpuPercent\":100}" 2>/dev/null)
+ if echo "$result" | grep -q "ok"; then
+ SCALES_OK=$((SCALES_OK + 1))
+ else
+ SCALES_FAIL=$((SCALES_FAIL + 1))
+ fi
+ done
+
+ # Pick 5 different random sandboxes to destroy
+ DESTROY_TARGETS=$(sort -R < "$SANDBOX_FILE" | head -5)
+ for sb in $DESTROY_TARGETS; do
+ [ -z "$sb" ] && continue
+ destroy_sandbox "$sb" >/dev/null 2>&1
+ grep -v "^${sb}$" "$SANDBOX_FILE" > "${SANDBOX_FILE}.tmp" 2>/dev/null
+ mv "${SANDBOX_FILE}.tmp" "$SANDBOX_FILE"
+ DESTROYS=$((DESTROYS + 1))
+ done
+
+ # Create 5 replacements (parallel for speed)
+ WAVE_DIR=$(mktemp -d)
+ for i in $(seq 1 5); do
+ (
+ sb=$(create_one)
+ [ -n "$sb" ] && [ "$sb" != "null" ] && echo "$sb" > "$WAVE_DIR/$i"
+ ) &
+ done
+ wait 2>/dev/null
+ for f in "$WAVE_DIR"/*; do
+ [ -f "$f" ] && cat "$f" >> "$SANDBOX_FILE"
+ done
+ rm -rf "$WAVE_DIR"
+ CREATES=$((CREATES + 5))
+
+ # Brief status
+ SB_NOW=$(wc -l < "$SANDBOX_FILE" | tr -d ' ')
+ WC=$(get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+ echo " sandboxes=$SB_NOW workers=$WC scales=$SCALES_OK destroys=$DESTROYS"
+
+ sleep 2
+done
+
+echo ""
+pass "Chaos complete: $SCALES_OK scales, $SCALES_FAIL scale failures, $DESTROYS destroys, $CREATES creates"
+
+# ============================================================
+h "Phase 4: Post-chaos responsiveness (sample 30)"
+
+echo " Checking 30 random sandboxes..."
+RESPONSIVE=0
+TOTAL_CHECK=0
+SAMPLE=$(sort -R < "$SANDBOX_FILE" | head -30)
+for sb in $SAMPLE; do
+ [ -z "$sb" ] && continue
+ TOTAL_CHECK=$((TOTAL_CHECK + 1))
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE + 1))
+done
+echo " $RESPONSIVE/$TOTAL_CHECK responsive"
+[ "$RESPONSIVE" -ge $((TOTAL_CHECK * 85 / 100)) ] && pass "≥85% responsive after chaos ($RESPONSIVE/$TOTAL_CHECK)" || fail "Only $RESPONSIVE/$TOTAL_CHECK responsive"
+
+# ============================================================
+h "Phase 5: Drain — destroy all sandboxes and watch scale-down"
+
+echo "Worker state before drain:"
+worker_summary
+
+SB_COUNT=$(wc -l < "$SANDBOX_FILE" | tr -d ' ')
+echo " Destroying $SB_COUNT sandboxes..."
+BATCH=0
+while read -r sb; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & BATCH=$((BATCH + 1)); }
+ if [ $((BATCH % 20)) -eq 0 ]; then
+ wait 2>/dev/null
+ fi
+done < "$SANDBOX_FILE"
+wait 2>/dev/null
+> "$SANDBOX_FILE" # clear tracking
+
+echo " All destroyed. Watching scaler drain workers (2 min max)..."
+for i in $(seq 1 8); do
+ sleep 15
+ WC=$(get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+ TOTAL_SB=$(get_workers | python3 -c "import sys,json; print(sum(w['current'] for w in json.load(sys.stdin)))" 2>/dev/null)
+ echo " $(date +%H:%M:%S) — $WC workers, $TOTAL_SB sandboxes"
+done
+
+echo ""
+echo "Final state:"
+worker_summary
+
+# ============================================================
+h "Phase 6: Verify system healthy after chaos"
+
+SB_FINAL=$(create_one)
+if [ -n "$SB_FINAL" ]; then
+ sleep 2
+ exec_check "$SB_FINAL" && pass "System healthy: sandbox created and responsive after chaos" || fail "Post-chaos sandbox unresponsive"
+ destroy_sandbox "$SB_FINAL" >/dev/null 2>&1
+else
+ fail "Cannot create sandbox after chaos"
+fi
+
+echo ""
+echo "=== Stats ==="
+echo " Peak sandboxes: ~$TOTAL_CREATED"
+echo " Chaos rounds: $CHAOS_ROUNDS"
+echo " Memory scales: $SCALES_OK ok, $SCALES_FAIL failed"
+echo " Random destroys: $DESTROYS"
+echo " Random creates: $CREATES"
+echo ""
+summary
diff --git a/scripts/qemu-tests/39-extended-chaos.sh b/scripts/qemu-tests/39-extended-chaos.sh
new file mode 100755
index 00000000..01c46ae2
--- /dev/null
+++ b/scripts/qemu-tests/39-extended-chaos.sh
@@ -0,0 +1,291 @@
+#!/usr/bin/env bash
+# 39-extended-chaos.sh — Extended chaos test with aggressive resource mutations
+#
+# 200 sandboxes, 20 chaos rounds over ~10 minutes.
+# Each round: random memory scales (512MB-16GB), disk fills (1-5GB),
+# random destroys, random creates, responsiveness checks.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+TARGET=${1:-200}
+WAVES=5
+PER_WAVE=$((TARGET / WAVES))
+CHAOS_ROUNDS=20
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+worker_summary() {
+ get_workers | python3 -c "
+import sys,json
+w = json.load(sys.stdin)
+total = sum(x['current'] for x in w)
+print(f'{len(w)} workers, {total} sandboxes')
+for x in w:
+ print(f' {x[\"worker_id\"][-8:]}: {x[\"current\"]} cpu={x[\"cpu_pct\"]:.0f}% mem={x[\"mem_pct\"]:.0f}% disk={x[\"disk_pct\"]:.0f}%')
+" 2>/dev/null
+}
+
+create_one() {
+ local result
+ result=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":0}' 2>/dev/null || echo '{}')
+ echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null
+}
+
+exec_check() {
+ local out
+ out=$(exec_stdout "$1" "echo" "ok" 2>/dev/null)
+ [ "$out" = "ok" ]
+}
+
+SANDBOX_FILE=$(mktemp)
+
+cleanup() {
+ echo ""
+ echo "=== Cleanup ==="
+ local count=0
+ while read -r sb; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & count=$((count+1)); }
+ [ $((count % 30)) -eq 0 ] && wait 2>/dev/null
+ done < "$SANDBOX_FILE"
+ wait 2>/dev/null
+ echo "Destroyed $count sandboxes"
+ rm -f "$SANDBOX_FILE"
+}
+trap cleanup EXIT INT TERM
+
+echo "=== Extended Chaos Test ==="
+echo "Target: $TARGET sandboxes, $CHAOS_ROUNDS chaos rounds"
+echo ""
+echo "Starting state:"
+worker_summary
+echo ""
+
+# ============================================================
+h "Phase 1: Ramp up to $TARGET sandboxes"
+
+TOTAL_CREATED=0
+for wave in $(seq 1 $WAVES); do
+ echo " Wave $wave/$WAVES: creating $PER_WAVE..."
+ WAVE_OK=0
+ WAVE_DIR=$(mktemp -d)
+ for i in $(seq 1 $PER_WAVE); do
+ (
+ sb=$(create_one)
+ [ -n "$sb" ] && [ "$sb" != "null" ] && echo "$sb" > "$WAVE_DIR/$i"
+ ) &
+ [ $((i % 10)) -eq 0 ] && wait 2>/dev/null
+ done
+ wait 2>/dev/null
+ for f in "$WAVE_DIR"/*; do
+ [ -f "$f" ] && { cat "$f" >> "$SANDBOX_FILE"; WAVE_OK=$((WAVE_OK + 1)); }
+ done
+ rm -rf "$WAVE_DIR"
+ TOTAL_CREATED=$((TOTAL_CREATED + WAVE_OK))
+ echo " $WAVE_OK created (total: $TOTAL_CREATED) — $(worker_summary | head -1)"
+ sleep 3
+done
+
+echo ""
+[ "$TOTAL_CREATED" -ge $((TARGET * 80 / 100)) ] && pass "Ramp: $TOTAL_CREATED/$TARGET created" || fail "Only $TOTAL_CREATED/$TARGET"
+
+echo ""
+echo "Post-ramp state:"
+worker_summary
+
+# ============================================================
+h "Phase 2: Initial responsiveness (sample 30)"
+
+RESPONSIVE=0
+for sb in $(sort -R < "$SANDBOX_FILE" | head -30); do
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE + 1))
+done
+echo " $RESPONSIVE/30 responsive"
+[ "$RESPONSIVE" -ge 27 ] && pass "≥90% responsive ($RESPONSIVE/30)" || fail "$RESPONSIVE/30"
+
+# ============================================================
+h "Phase 3: Extended chaos ($CHAOS_ROUNDS rounds)"
+
+MEM_OPTIONS="4096 8192 16384"
+DISK_SIZES="1024 2048 5120" # MB to write
+
+SCALES_OK=0
+SCALES_FAIL=0
+DESTROYS=0
+CREATES=0
+DISK_WRITES=0
+CHECKS_OK=0
+CHECKS_FAIL=0
+
+for round in $(seq 1 $CHAOS_ROUNDS); do
+ SB_COUNT=$(wc -l < "$SANDBOX_FILE" | tr -d ' ')
+ WC=$(get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+ printf " Round %2d/%d [sb=%s w=%s] " "$round" "$CHAOS_ROUNDS" "$SB_COUNT" "$WC"
+
+ # --- Action 1: Scale memory on 3 random sandboxes ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -3); do
+ [ -z "$sb" ] && continue
+ MEM=$(echo $MEM_OPTIONS | tr ' ' '\n' | sort -R | head -1)
+ result=$(TIMEOUT=60 api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d "{\"memoryMB\":$MEM,\"cpuPercent\":200}" 2>/dev/null)
+ if echo "$result" | grep -q "ok"; then
+ SCALES_OK=$((SCALES_OK + 1))
+ else
+ SCALES_FAIL=$((SCALES_FAIL + 1))
+ fi
+ done
+
+ # --- Action 2: Write random data to disk on 2 sandboxes ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -2); do
+ [ -z "$sb" ] && continue
+ SIZE_MB=$(echo $DISK_SIZES | tr ' ' '\n' | sort -R | head -1)
+ TIMEOUT=60 exec_run "$sb" "sh" "-c" "dd if=/dev/urandom of=/workspace/chaos-$(date +%s).bin bs=1M count=$SIZE_MB 2>/dev/null &" >/dev/null 2>&1 || true
+ DISK_WRITES=$((DISK_WRITES + 1))
+ done
+
+ # --- Action 3: Destroy 5 random sandboxes ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -5); do
+ [ -z "$sb" ] && continue
+ destroy_sandbox "$sb" >/dev/null 2>&1
+ grep -v "^${sb}$" "$SANDBOX_FILE" > "${SANDBOX_FILE}.tmp" 2>/dev/null
+ mv "${SANDBOX_FILE}.tmp" "$SANDBOX_FILE"
+ DESTROYS=$((DESTROYS + 1))
+ done
+
+ # --- Action 4: Create 5 replacements ---
+ WAVE_DIR=$(mktemp -d)
+ for i in $(seq 1 5); do
+ (
+ sb=$(create_one)
+ [ -n "$sb" ] && [ "$sb" != "null" ] && echo "$sb" > "$WAVE_DIR/$i"
+ ) &
+ done
+ wait 2>/dev/null
+ for f in "$WAVE_DIR"/*; do
+ [ -f "$f" ] && { cat "$f" >> "$SANDBOX_FILE"; CREATES=$((CREATES + 1)); }
+ done
+ rm -rf "$WAVE_DIR"
+
+ # --- Action 5: Spot-check 3 random sandboxes ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -3); do
+ [ -z "$sb" ] && continue
+ if exec_check "$sb"; then
+ CHECKS_OK=$((CHECKS_OK + 1))
+ else
+ CHECKS_FAIL=$((CHECKS_FAIL + 1))
+ fi
+ done
+
+ printf "scales=%d/%d disk=%d destroy=%d create=%d checks=%d/%d\n" \
+ "$SCALES_OK" "$((SCALES_OK + SCALES_FAIL))" "$DISK_WRITES" "$DESTROYS" "$CREATES" \
+ "$CHECKS_OK" "$((CHECKS_OK + CHECKS_FAIL))"
+
+ sleep 5
+done
+
+echo ""
+[ "$CHECKS_FAIL" -le $((CHECKS_OK / 10)) ] && pass "Chaos checks: $CHECKS_OK ok, $CHECKS_FAIL failed (≤10% failure)" || fail "Too many failures: $CHECKS_FAIL/$((CHECKS_OK + CHECKS_FAIL))"
+pass "Chaos survived: $SCALES_OK scales, $DISK_WRITES disk writes, $DESTROYS destroys, $CREATES creates"
+
+# ============================================================
+h "Phase 4: Post-chaos state"
+
+echo ""
+worker_summary
+echo ""
+
+SB_COUNT=$(wc -l < "$SANDBOX_FILE" | tr -d ' ')
+echo "Tracked sandboxes: $SB_COUNT"
+
+# ============================================================
+h "Phase 5: Post-chaos deep responsiveness (sample 50)"
+
+RESPONSIVE=0
+TOTAL_CHECK=0
+for sb in $(sort -R < "$SANDBOX_FILE" | head -50); do
+ [ -z "$sb" ] && continue
+ TOTAL_CHECK=$((TOTAL_CHECK + 1))
+ exec_check "$sb" && RESPONSIVE=$((RESPONSIVE + 1))
+done
+echo " $RESPONSIVE/$TOTAL_CHECK responsive"
+[ "$RESPONSIVE" -ge $((TOTAL_CHECK * 85 / 100)) ] && pass "≥85% responsive after extended chaos ($RESPONSIVE/$TOTAL_CHECK)" || fail "$RESPONSIVE/$TOTAL_CHECK"
+
+# ============================================================
+h "Phase 6: Drain and recovery"
+
+echo "Destroying all sandboxes..."
+BATCH=0
+while read -r sb; do
+ [ -n "$sb" ] && { destroy_sandbox "$sb" >/dev/null 2>&1 & BATCH=$((BATCH + 1)); }
+ [ $((BATCH % 30)) -eq 0 ] && wait 2>/dev/null
+done < "$SANDBOX_FILE"
+wait 2>/dev/null
+> "$SANDBOX_FILE"
+
+echo "Watching workers (3 min)..."
+for i in $(seq 1 12); do
+ sleep 15
+ WC=$(get_workers | python3 -c "import sys,json; w=json.load(sys.stdin); print(f'{len(w)} workers, {sum(x[\"current\"] for x in w)} sb, peak_cpu={max(x[\"cpu_pct\"] for x in w):.0f}% peak_mem={max(x[\"mem_pct\"] for x in w):.0f}%')" 2>/dev/null)
+ echo " $(date +%H:%M:%S) — $WC"
+done
+
+echo ""
+echo "Final state:"
+worker_summary
+
+# Verify system works
+SB_FINAL=$(create_one)
+if [ -n "$SB_FINAL" ]; then
+ sleep 2
+ exec_check "$SB_FINAL" && pass "System healthy after extended chaos" || fail "Post-chaos sandbox broken"
+ destroy_sandbox "$SB_FINAL" >/dev/null 2>&1
+else
+ fail "Cannot create sandbox after chaos"
+fi
+
+echo ""
+echo "=== Final Stats ==="
+echo " Peak sandboxes: ~$TOTAL_CREATED"
+echo " Chaos rounds: $CHAOS_ROUNDS"
+echo " Memory scales: $SCALES_OK ok / $((SCALES_OK + SCALES_FAIL)) total"
+echo " Disk writes: $DISK_WRITES"
+echo " Random destroys: $DESTROYS"
+echo " Random creates: $CREATES"
+echo " Spot checks: $CHECKS_OK ok / $((CHECKS_OK + CHECKS_FAIL)) total"
+
+# Fetch server-side report (includes migration details)
+echo ""
+h "Server Report"
+REPORT=$(api "$API_URL/admin/report" 2>/dev/null)
+if [ -n "$REPORT" ] && echo "$REPORT" | python3 -c "import sys,json; json.load(sys.stdin)" 2>/dev/null; then
+ echo "$REPORT" | python3 -c "
+import sys, json
+r = json.load(sys.stdin)
+print(f' Events tracked: {r[\"total_events\"]}')
+print(f' Creates: {r[\"creates\"]}')
+print(f' Destroys: {r[\"destroys\"]}')
+print(f' Scales: {r[\"scales\"]}')
+print(f' Migrations: {r[\"migrations\"][\"total\"]} (all succeeded)')
+if r['migrations']['details']:
+ print()
+ print(' Migration details:')
+ for m in r['migrations']['details']:
+ print(f' {m[\"time\"]} {m[\"sandbox\"][-8:]} → {m[\"worker\"][-8:]}: {m[\"detail\"]}')
+print()
+print(' Workers:')
+for w in sorted(r.get('workers',[]), key=lambda x: -x['current']):
+ print(f' {w[\"id\"]}: {w[\"current\"]} sandboxes cpu={w[\"cpu_pct\"]:.0f}% mem={w[\"mem_pct\"]:.0f}%')
+print()
+mig = r['migrations']['total']
+if mig > 0:
+ print(f' ✓ All {mig} migrations completed successfully')
+else:
+ print(' No migrations triggered (all scales fit on current worker)')
+" 2>/dev/null
+else
+ echo " (report not available)"
+fi
+
+echo ""
+summary