Skip to content

An open-source, faster Devin alternative

TypeScript

test and demo adjustment

Brian Reardon1dc394dab816
diff --git a/internal/api/admin_demo.go b/internal/api/admin_demo.go
new file mode 100644
index 00000000..5736ec74
--- /dev/null
+++ b/internal/api/admin_demo.go
@@ -0,0 +1,507 @@
+package api
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+)
+
+func (s *Server) demoPingPongPage(c echo.Context) error {
+ return c.HTML(http.StatusOK, demoPingPongHTML)
+}
+
+func (s *Server) demoChaosPage(c echo.Context) error {
+ return c.HTML(http.StatusOK, demoChaosHTML)
+}
+
+const demoPingPongHTML = `<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>Live Migration Demo</title>
+<style>
+ * { margin:0; padding:0; box-sizing:border-box; }
+ body { background:#08080c; color:#e0e0e0; font-family:'JetBrains Mono','SF Mono',monospace; font-size:13px; overflow:hidden; height:100vh; display:flex; flex-direction:column; }
+ .header { padding:20px 30px 10px; }
+ .header h1 { font-size:22px; color:#818cf8; }
+ .header .sub { color:#666; font-size:12px; margin-top:4px; }
+ .main { flex:1; display:flex; padding:0 30px 20px; gap:20px; min-height:0; }
+ .left { flex:2; display:flex; flex-direction:column; gap:12px; }
+ .right { flex:1; display:flex; flex-direction:column; gap:12px; }
+
+ .card { background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); border-radius:10px; padding:16px; }
+ .card h2 { font-size:13px; color:#888; text-transform:uppercase; letter-spacing:1px; margin-bottom:12px; }
+
+ .sandbox-info { display:grid; grid-template-columns:repeat(4,1fr); gap:10px; }
+ .info-item { text-align:center; }
+ .info-item .label { font-size:10px; color:#666; text-transform:uppercase; }
+ .info-item .val { font-size:20px; font-weight:bold; margin-top:2px; }
+ .info-item .val.purple { color:#818cf8; }
+ .info-item .val.green { color:#34d399; }
+ .info-item .val.blue { color:#60a5fa; }
+ .info-item .val.amber { color:#fbbf24; }
+
+ .workers-grid { display:flex; flex-wrap:wrap; gap:8px; }
+ .worker-node { width:110px; height:70px; border-radius:8px; border:1px solid rgba(255,255,255,0.08); background:rgba(255,255,255,0.02); display:flex; flex-direction:column; align-items:center; justify-content:center; transition:all 0.5s; position:relative; }
+ .worker-node .name { font-size:10px; color:#888; }
+ .worker-node .status { font-size:11px; margin-top:4px; color:#555; }
+ .worker-node.active { border-color:#818cf8; background:rgba(129,140,248,0.1); box-shadow:0 0 20px rgba(129,140,248,0.2); }
+ .worker-node.active .name { color:#818cf8; font-weight:bold; }
+ .worker-node.active .status { color:#34d399; }
+ .worker-node.migrating-from { border-color:#f87171; background:rgba(248,113,113,0.1); animation:pulseRed 1s infinite; }
+ .worker-node.migrating-to { border-color:#34d399; background:rgba(52,211,153,0.1); animation:pulseGreen 1s infinite; }
+ @keyframes pulseRed { 0%,100% { box-shadow:0 0 10px rgba(248,113,113,0.2); } 50% { box-shadow:0 0 25px rgba(248,113,113,0.4); } }
+ @keyframes pulseGreen { 0%,100% { box-shadow:0 0 10px rgba(52,211,153,0.2); } 50% { box-shadow:0 0 25px rgba(52,211,153,0.4); } }
+
+ .migration-trail { flex:1; overflow-y:auto; min-height:0; }
+ .trail-entry { display:flex; align-items:center; gap:10px; padding:6px 0; border-bottom:1px solid rgba(255,255,255,0.03); animation:fadeIn 0.3s; }
+ @keyframes fadeIn { from { opacity:0; transform:translateY(-5px); } to { opacity:1; transform:translateY(0); } }
+ .trail-num { color:#555; width:24px; text-align:right; font-size:11px; }
+ .trail-arrow { color:#818cf8; }
+ .trail-time { color:#fbbf24; font-size:11px; }
+ .trail-checks { display:flex; gap:4px; font-size:10px; }
+ .trail-checks .ok { color:#34d399; }
+ .trail-checks .fail { color:#f87171; }
+
+ .verifications { display:flex; flex-wrap:wrap; gap:6px; }
+ .verify-badge { padding:3px 8px; border-radius:4px; font-size:10px; }
+ .verify-badge.pass { background:rgba(52,211,153,0.15); color:#34d399; }
+ .verify-badge.fail { background:rgba(248,113,113,0.15); color:#f87171; }
+ .verify-badge.pending { background:rgba(255,255,255,0.05); color:#555; }
+
+ .counter { text-align:center; padding:20px; }
+ .counter .big { font-size:48px; font-weight:bold; color:#818cf8; }
+ .counter .of { font-size:16px; color:#555; }
+ .counter .label { font-size:11px; color:#666; margin-top:4px; }
+</style>
+</head>
+<body>
+<div class="header">
+ <h1>Live Migration Ping-Pong</h1>
+ <div class="sub">Sandbox migrating across workers with full verification at each hop</div>
+</div>
+
+<div class="main">
+ <div class="left">
+ <div class="card">
+ <h2>Sandbox</h2>
+ <div class="sandbox-info">
+ <div class="info-item"><div class="label">ID</div><div class="val purple" id="sb-id">-</div></div>
+ <div class="info-item"><div class="label">Memory</div><div class="val green" id="sb-mem">-</div></div>
+ <div class="info-item"><div class="label">Processes</div><div class="val blue" id="sb-procs">-</div></div>
+ <div class="info-item"><div class="label">Avg Migration</div><div class="val amber" id="sb-avg">-</div></div>
+ </div>
+ </div>
+
+ <div class="card">
+ <h2>Workers</h2>
+ <div class="workers-grid" id="workers"></div>
+ </div>
+
+ <div class="card" style="flex:1;display:flex;flex-direction:column;min-height:0">
+ <h2>Migration Trail</h2>
+ <div class="migration-trail" id="trail"></div>
+ </div>
+ </div>
+
+ <div class="right">
+ <div class="card counter">
+ <div class="big" id="pass-count">0</div>
+ <div class="of">/ <span id="total-count">0</span></div>
+ <div class="label">Successful Migrations</div>
+ </div>
+
+ <div class="card">
+ <h2>Current Verification</h2>
+ <div class="verifications" id="checks">
+ <span class="verify-badge pending">exec</span>
+ <span class="verify-badge pending">data</span>
+ <span class="verify-badge pending">hash</span>
+ <span class="verify-badge pending">memory</span>
+ <span class="verify-badge pending">processes</span>
+ <span class="verify-badge pending">worker</span>
+ </div>
+ </div>
+
+ <div class="card" style="flex:1;overflow-y:auto">
+ <h2>Event Log</h2>
+ <div id="log" style="font-size:11px;color:#888;"></div>
+ </div>
+ </div>
+</div>
+
+<script>
+const API_KEY = new URLSearchParams(window.location.search).get('key') || '';
+const BASE = window.location.origin;
+let workers = {};
+let currentWorker = '';
+let passCount = 0;
+let totalCount = 0;
+let totalMs = 0;
+
+function addLog(msg, color) {
+ const log = document.getElementById('log');
+ const el = document.createElement('div');
+ el.style.padding = '2px 0';
+ el.style.color = color || '#888';
+ el.innerHTML = new Date().toLocaleTimeString() + ' ' + msg;
+ log.insertBefore(el, log.firstChild);
+}
+
+function addTrail(num, from, to, durationMs, checks) {
+ const trail = document.getElementById('trail');
+ const el = document.createElement('div');
+ el.className = 'trail-entry';
+ const checksHtml = Object.entries(checks).map(([k,v]) =>
+ '<span class="' + (v ? 'ok' : 'fail') + '">' + k + (v ? '✓' : '✗') + '</span>'
+ ).join(' ');
+ el.innerHTML =
+ '<span class="trail-num">' + num + '</span>' +
+ '<span style="color:#888">' + from + '</span>' +
+ '<span class="trail-arrow">→</span>' +
+ '<span style="color:#ccc">' + to + '</span>' +
+ '<span class="trail-time">' + durationMs + 'ms</span>' +
+ '<span class="trail-checks">' + checksHtml + '</span>';
+ trail.insertBefore(el, trail.firstChild);
+}
+
+async function refreshWorkers() {
+ try {
+ const resp = await fetch(BASE + '/api/workers', { headers: { 'X-API-Key': API_KEY } });
+ const data = await resp.json();
+ // Sort workers alphabetically so they stay in a fixed order
+ data.sort((a,b) => a.worker_id.localeCompare(b.worker_id));
+ const grid = document.getElementById('workers');
+ grid.innerHTML = data.map(w => {
+ const id = w.worker_id.slice(-8);
+ const cls = id === currentWorker ? 'active' : '';
+ return '<div class="worker-node ' + cls + '" id="w-' + id + '">' +
+ '<div class="name">' + id + '</div>' +
+ '<div class="status">' + (id === currentWorker ? 'ACTIVE' : w.current + ' sb') + '</div>' +
+ '</div>';
+ }).join('');
+ } catch(e) {}
+}
+
+let sandboxId = '';
+let expectedHash = '';
+
+async function execInSandbox(cmd, args) {
+ try {
+ const resp = await fetch(BASE + '/api/sandboxes/' + sandboxId + '/exec/run', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-API-Key': API_KEY },
+ body: JSON.stringify({ cmd: cmd, args: args || [], timeout: 10 })
+ });
+ const data = await resp.json();
+ return { stdout: (data.stdout || '').trim(), exitCode: data.exitCode };
+ } catch(e) { return { stdout: '', exitCode: -1 }; }
+}
+
+function setCheck(name, pass) {
+ const badges = document.querySelectorAll('#checks .verify-badge');
+ badges.forEach(b => {
+ if (b.textContent.startsWith(name)) {
+ b.className = 'verify-badge ' + (pass ? 'pass' : 'fail');
+ b.textContent = name + (pass ? ' ✓' : ' ✗');
+ }
+ });
+}
+
+function resetChecks() {
+ document.getElementById('checks').innerHTML =
+ ['exec','data','hash','memory','processes','worker'].map(n =>
+ '<span class="verify-badge pending">' + n + ' ⋯</span>'
+ ).join('');
+}
+
+async function runVerification(fullTargetWorker) {
+ resetChecks();
+ const checks = {};
+
+ const echo = await execInSandbox('echo', ['alive']);
+ checks.exec = echo.stdout === 'alive';
+ setCheck('exec', checks.exec);
+
+ const data = await execInSandbox('cat', ['/workspace/data.txt']);
+ checks.data = data.stdout === 'important-data-12345';
+ setCheck('data', checks.data);
+
+ const hash = await execInSandbox('md5sum', ['/workspace/random.bin']);
+ const h = (hash.stdout || '').split(' ')[0];
+ checks.hash = expectedHash ? h === expectedHash : h.length === 32;
+ setCheck('hash', checks.hash);
+
+ const mem = await execInSandbox('free', ['-m']);
+ const memLine = (mem.stdout || '').split('\n').find(l => l.startsWith('Mem:'));
+ const memMB = memLine ? parseInt(memLine.split(/\s+/)[1]) : 0;
+ checks.memory = memMB > 3000;
+ setCheck('memory', checks.memory);
+ document.getElementById('sb-mem').textContent = memMB + 'MB';
+
+ const ps = await execInSandbox('sh', ['-c', 'ps aux | wc -l']);
+ const procs = parseInt(ps.stdout) || 0;
+ checks.processes = procs > 3;
+ setCheck('processes', checks.processes);
+ document.getElementById('sb-procs').textContent = procs;
+
+ try {
+ const sbResp = await fetch(BASE + '/api/sandboxes/' + sandboxId, { headers: { 'X-API-Key': API_KEY } });
+ const sbData = await sbResp.json();
+ checks.worker = sbData.workerID === fullTargetWorker;
+ } catch(e) { checks.worker = false; }
+ setCheck('worker', checks.worker);
+
+ return { checks, allPass: Object.values(checks).every(v => v) };
+}
+
+// Only process events that arrive AFTER page load (ignore history replay)
+const pageLoadTime = Date.now();
+let ready = false;
+setTimeout(() => { ready = true; }, 2000); // ignore events for first 2s (history replay)
+
+const evtSource = new EventSource(BASE + '/admin/events?key=' + API_KEY);
+evtSource.onmessage = async function(e) {
+ if (!ready) return; // skip history replay
+ try {
+ const evt = JSON.parse(e.data);
+ if (evt.type === 'migrate' && evt.sandbox === sandboxId) {
+ const to = evt.worker.slice(-8);
+ const fullTarget = evt.worker;
+ const ms = evt.detail.match(/(\d+)ms/);
+ const duration = ms ? ms[1] : '?';
+ const from = evt.detail.match(/from (\w+)/)?.[1] || '?';
+
+ if (currentWorker) {
+ const old = document.getElementById('w-' + currentWorker);
+ if (old) { old.className = 'worker-node'; old.querySelector('.status').textContent = ''; }
+ }
+ currentWorker = to;
+ const node = document.getElementById('w-' + to);
+ if (node) { node.className = 'worker-node active'; node.querySelector('.status').textContent = 'ACTIVE'; }
+
+ totalCount++;
+ totalMs += parseInt(duration) || 0;
+ document.getElementById('total-count').textContent = totalCount;
+ addLog('Migration #' + totalCount + ' → ' + to + ' (' + duration + 'ms) verifying...', '#818cf8');
+
+ const { checks, allPass } = await runVerification(fullTarget);
+ if (allPass) passCount++;
+ document.getElementById('pass-count').textContent = passCount;
+ document.getElementById('sb-avg').textContent = Math.round(totalMs / totalCount) + 'ms';
+
+ addTrail(totalCount, from, to, duration, checks);
+ addLog('Verified: ' + (allPass ? 'ALL PASS ✓' : 'FAILED ✗'), allPass ? '#34d399' : '#f87171');
+ refreshWorkers();
+
+ } else if (evt.type === 'create') {
+ sandboxId = evt.sandbox;
+ document.getElementById('sb-id').textContent = evt.sandbox.slice(-8);
+ currentWorker = evt.worker.slice(-8);
+ addLog('Created ' + evt.sandbox.slice(-8) + ' on ' + currentWorker, '#34d399');
+ setTimeout(async () => {
+ const hash = await execInSandbox('md5sum', ['/workspace/random.bin']);
+ expectedHash = (hash.stdout || '').split(' ')[0];
+ if (expectedHash) addLog('Hash baseline: ' + expectedHash.slice(0,12) + '...', '#888');
+ }, 5000);
+ refreshWorkers();
+
+ } else if (evt.type === 'scale') {
+ const mem = evt.detail.match(/(\d+)MB/)?.[1];
+ if (mem) document.getElementById('sb-mem').textContent = mem + 'MB';
+ addLog('Scaled: ' + evt.detail, '#fbbf24');
+ }
+ } catch(err) { addLog('Error: ' + err.message, '#f87171'); }
+};
+
+refreshWorkers();
+setInterval(refreshWorkers, 3000);
+</script>
+</body>
+</html>`
+
+const demoChaosHTML = `<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>200-Sandbox Chaos Test</title>
+<style>
+ * { margin:0; padding:0; box-sizing:border-box; }
+ body { background:#08080c; color:#e0e0e0; font-family:'JetBrains Mono','SF Mono',monospace; font-size:13px; overflow:hidden; height:100vh; display:flex; flex-direction:column; }
+ .header { padding:20px 30px 10px; }
+ .header h1 { font-size:22px; color:#34d399; }
+ .header .sub { color:#666; font-size:12px; margin-top:4px; }
+ .main { flex:1; display:flex; padding:0 30px 20px; gap:20px; min-height:0; }
+ .left { flex:2; display:flex; flex-direction:column; gap:12px; }
+ .right { flex:1; display:flex; flex-direction:column; gap:12px; }
+
+ .card { background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06); border-radius:10px; padding:16px; }
+ .card h2 { font-size:13px; color:#888; text-transform:uppercase; letter-spacing:1px; margin-bottom:12px; }
+
+ .stats { display:grid; grid-template-columns:repeat(5,1fr); gap:10px; }
+ .stat { text-align:center; }
+ .stat .val { font-size:28px; font-weight:bold; }
+ .stat .label { font-size:10px; color:#666; text-transform:uppercase; margin-top:2px; }
+ .green { color:#34d399; }
+ .blue { color:#60a5fa; }
+ .amber { color:#fbbf24; }
+ .purple { color:#818cf8; }
+ .red { color:#f87171; }
+
+ .workers-bars { display:flex; flex-direction:column; gap:6px; }
+ .worker-bar { display:flex; align-items:center; gap:8px; }
+ .worker-bar .name { width:70px; font-size:11px; color:#888; text-align:right; }
+ .worker-bar .bar-bg { flex:1; height:20px; background:rgba(255,255,255,0.04); border-radius:4px; overflow:hidden; position:relative; }
+ .worker-bar .bar-fill { height:100%; border-radius:4px; transition:width 0.5s; display:flex; align-items:center; padding-left:6px; font-size:10px; color:rgba(255,255,255,0.8); }
+ .worker-bar .bar-fill.cpu { background:linear-gradient(90deg,#818cf8,#6366f1); }
+ .worker-bar .bar-fill.mem { background:linear-gradient(90deg,#34d399,#059669); }
+ .worker-bar .bar-fill.sandbox { background:linear-gradient(90deg,#60a5fa,#3b82f6); }
+ .worker-bar .count { width:30px; font-size:11px; color:#ccc; text-align:right; }
+
+ .event-feed { flex:1; overflow-y:auto; min-height:0; font-size:11px; }
+ .event { padding:3px 0; animation:fadeIn 0.2s; }
+ @keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
+ .event .time { color:#555; }
+ .event .create { color:#34d399; }
+ .event .destroy { color:#f87171; }
+ .event .scale { color:#fbbf24; }
+ .event .migrate { color:#818cf8; }
+
+ .chaos-indicator { display:flex; align-items:center; gap:8px; padding:8px 12px; border-radius:6px; font-size:12px; }
+ .chaos-indicator.active { background:rgba(248,113,113,0.1); border:1px solid rgba(248,113,113,0.2); color:#f87171; animation:chaosPulse 2s infinite; }
+ .chaos-indicator.idle { background:rgba(52,211,153,0.1); border:1px solid rgba(52,211,153,0.2); color:#34d399; }
+ @keyframes chaosPulse { 0%,100% { opacity:1; } 50% { opacity:0.5; } }
+
+ .chaos-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; }
+ .chaos-stat { text-align:center; padding:8px; background:rgba(255,255,255,0.02); border-radius:6px; }
+ .chaos-stat .val { font-size:18px; font-weight:bold; }
+ .chaos-stat .label { font-size:9px; color:#666; text-transform:uppercase; }
+</style>
+</head>
+<body>
+<div class="header">
+ <h1>200-Sandbox Chaos Test</h1>
+ <div class="sub">Random scaling, disk writes, creates, and destroys across 9 workers</div>
+</div>
+
+<div class="main">
+ <div class="left">
+ <div class="card">
+ <div class="stats">
+ <div class="stat"><div class="val blue" id="workers">0</div><div class="label">Workers</div></div>
+ <div class="stat"><div class="val green" id="sandboxes">0</div><div class="label">Sandboxes</div></div>
+ <div class="stat"><div class="val amber" id="creates">0</div><div class="label">Creates</div></div>
+ <div class="stat"><div class="val red" id="destroys">0</div><div class="label">Destroys</div></div>
+ <div class="stat"><div class="val purple" id="scales">0</div><div class="label">Scales</div></div>
+ </div>
+ </div>
+
+ <div class="card" style="flex:1">
+ <h2>Worker Distribution</h2>
+ <div class="workers-bars" id="worker-bars"></div>
+ </div>
+
+ <div class="card">
+ <h2>Chaos Activity</h2>
+ <div class="chaos-stats">
+ <div class="chaos-stat"><div class="val green" id="c-creates">0</div><div class="label">Creates</div></div>
+ <div class="chaos-stat"><div class="val red" id="c-destroys">0</div><div class="label">Destroys</div></div>
+ <div class="chaos-stat"><div class="val purple" id="c-scales">0</div><div class="label">Mem Scales</div></div>
+ <div class="chaos-stat"><div class="val amber" id="c-migrates">0</div><div class="label">Migrations</div></div>
+ </div>
+ </div>
+ </div>
+
+ <div class="right">
+ <div class="card">
+ <div class="chaos-indicator idle" id="chaos-status">
+ Waiting for test...
+ </div>
+ </div>
+
+ <div class="card" style="flex:1;display:flex;flex-direction:column;min-height:0">
+ <h2>Live Events</h2>
+ <div class="event-feed" id="events"></div>
+ </div>
+ </div>
+</div>
+
+<script>
+const API_KEY = new URLSearchParams(window.location.search).get('key') || '';
+const BASE = window.location.origin;
+let creates = 0, destroys = 0, scales = 0, migrates = 0;
+let prevSandboxes = 0;
+let displayedSandboxes = 0;
+
+function addEvent(msg, type) {
+ const feed = document.getElementById('events');
+ const el = document.createElement('div');
+ el.className = 'event';
+ el.innerHTML = '<span class="time">' + new Date().toLocaleTimeString() + '</span> <span class="' + type + '">' + msg + '</span>';
+ feed.insertBefore(el, feed.firstChild);
+ while (feed.children.length > 200) feed.removeChild(feed.lastChild);
+}
+
+async function refresh() {
+ try {
+ const resp = await fetch(BASE + '/api/workers', { headers: { 'X-API-Key': API_KEY } });
+ const data = await resp.json();
+
+ const totalSb = data.reduce((s,w) => s + w.current, 0);
+ document.getElementById('workers').textContent = data.length;
+
+ document.getElementById('sandboxes').textContent = totalSb;
+
+ if (totalSb > 0) {
+ const indicator = document.getElementById('chaos-status');
+ indicator.className = 'chaos-indicator active';
+ indicator.textContent = 'Chaos active — ' + totalSb + ' sandboxes';
+ }
+ prevSandboxes = totalSb;
+
+ // Worker bars
+ const maxSb = Math.max(1, ...data.map(w => w.current));
+ const bars = document.getElementById('worker-bars');
+ bars.innerHTML = data.sort((a,b) => b.current - a.current).map(w => {
+ const pct = (w.current / Math.max(maxSb, 30)) * 100;
+ const memPct = w.mem_pct;
+ return '<div class="worker-bar">' +
+ '<span class="name">' + w.worker_id.slice(-8) + '</span>' +
+ '<div class="bar-bg"><div class="bar-fill sandbox" style="width:' + pct + '%">' + (w.current > 0 ? w.current : '') + '</div></div>' +
+ '<span class="count" style="color:' + (memPct > 50 ? '#fbbf24' : '#888') + '">' + memPct.toFixed(0) + '%</span>' +
+ '</div>';
+ }).join('');
+
+ } catch(e) {}
+}
+
+// SSE events
+const evtSource = new EventSource(BASE + '/admin/events?key=' + API_KEY);
+evtSource.onmessage = function(e) {
+ try {
+ const evt = JSON.parse(e.data);
+ const sb = evt.sandbox ? evt.sandbox.slice(-8) : '';
+ const wk = evt.worker ? evt.worker.slice(-8) : '';
+
+ if (evt.type === 'create') {
+ document.getElementById('c-creates').textContent = ++creates;
+ addEvent('+' + sb + ' → ' + wk, 'create');
+ } else if (evt.type === 'destroy') {
+ document.getElementById('c-destroys').textContent = ++destroys;
+ addEvent('-' + sb, 'destroy');
+ } else if (evt.type === 'scale') {
+ document.getElementById('c-scales').textContent = ++scales;
+ document.getElementById('scales').textContent = scales;
+ addEvent('~' + sb + ' ' + evt.detail, 'scale');
+ } else if (evt.type === 'migrate') {
+ document.getElementById('c-migrates').textContent = ++migrates;
+ addEvent('→' + sb + ' ' + evt.detail, 'migrate');
+ }
+ } catch(err) {}
+};
+
+refresh();
+setInterval(refresh, 2000);
+</script>
+</body>
+</html>`
diff --git a/internal/api/admin_events.go b/internal/api/admin_events.go
index ce6a6bc2..507dc206 100644
--- a/internal/api/admin_events.go
+++ b/internal/api/admin_events.go
@@ -135,6 +135,16 @@ func (s *Server) adminEventsHistory(c echo.Context) error {
return c.JSON(http.StatusOK, s.adminEvents.History())
}
+// adminClearEvents clears the event history.
+func (s *Server) adminClearEvents(c echo.Context) error {
+ if s.adminEvents != nil {
+ s.adminEvents.mu.Lock()
+ s.adminEvents.history = nil
+ s.adminEvents.mu.Unlock()
+ }
+ return c.JSON(http.StatusOK, map[string]string{"status": "cleared"})
+}
+
// 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 {
diff --git a/internal/api/router.go b/internal/api/router.go
index 6b98cf44..e5688933 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -175,6 +175,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
admin.GET("/events", s.adminEventsSSE)
admin.GET("/events/history", s.adminEventsHistory)
admin.GET("/report", s.adminReport)
+ admin.POST("/events/clear", s.adminClearEvents)
+ admin.GET("/demo/migration", s.demoPingPongPage)
+ admin.GET("/demo/chaos", s.demoChaosPage)
// 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 f29e3561..b99dd5bc 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -764,9 +764,10 @@ func (s *Server) migrateSandbox(c echo.Context) error {
CpuCount int `json:"cpuCount"`
}
_ = json.Unmarshal(session.Config, &sbCfg)
- if sbCfg.MemoryMB <= 0 {
- sbCfg.MemoryMB = 256 // default from golden snapshot
- }
+ // IMPORTANT: Use the QEMU base memory (from golden snapshot), not the API-requested total.
+ // Virtio-mem hotplug state transfers during migration — the target QEMU must start
+ // with the same base memory as the source for the memory layout to match.
+ sbCfg.MemoryMB = 256
if sbCfg.CpuCount <= 0 {
sbCfg.CpuCount = 1
}
@@ -1075,7 +1076,10 @@ 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))
+ // Only emit scale events for non-default sizes (4096MB is the creation default)
+ if requestedMemMB != 4096 || migrated {
+ s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))
+ }
return c.JSON(http.StatusOK, map[string]interface{}{
"sandboxID": sandboxID,
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index 28d3c9b9..c744746b 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -40,12 +40,13 @@ 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
+ rrCounter uint64 // round-robin counter for tie-breaking
+ stop chan struct{}
}
// RedisClient returns the underlying Redis client (for health checks, shared state, etc.).
@@ -313,93 +314,75 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,
r.mu.Lock()
defer r.mu.Unlock()
- var best *WorkerEntry
- bestScore := -1.0
-
- // Bin-pack strategy using committed memory:
- // 1. Active workers with memory headroom → fill the most-loaded first
- // 2. Idle workers → use for burst (scaler replaces idle reserves in background)
- // 3. Workers with no headroom data → fall back to sandbox count
- //
- // Idle reserves are NOT protected from routing — they exist for burst absorption.
- // The scaler will notice the idle count dropped and launch replacements.
- scoreWorker := func(w *WorkerEntry) float64 {
- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
- return -1 // skip — under heavy pressure
- }
-
- // Use committed memory if available (preferred — reflects real capacity)
- if w.TotalMemoryMB > 0 {
- reserveMB := w.TotalMemoryMB / 5 // 20% for OS
- usableMB := w.TotalMemoryMB - reserveMB
- committedPct := float64(w.CommittedMemoryMB) / float64(usableMB) // 0.0 to 1.0+
-
- if committedPct >= 1.0 {
- // No headroom — last resort, spread by how far over
- return 0.01 / (1.0 + committedPct)
- }
- if w.Current == 0 {
- // Idle worker — available for burst. Score below active workers
- // so we fill active ones first, but don't block routing here.
- return 10.0 * (1.0 - committedPct)
- }
- // Active with headroom: higher committed% = higher score (bin-pack).
- // This fills workers proportionally to their memory, not sandbox count.
- return 100.0 + committedPct*50.0
- }
+ // Simple strategy: pick the worker with fewest sandboxes.
+ // Skip workers under heavy resource pressure.
+ // Skip idle reserves unless all active workers are above 60% committed.
+ // Read Redis routing counters to get real-time sandbox counts across both CPs
+ routingCtx, routingCancel := context.WithTimeout(context.Background(), time.Second)
+ defer routingCancel()
- // Fallback: no committed memory data — use sandbox count heuristic
- remaining := w.Capacity - w.Current
- if remaining <= 0 {
- return 0.01 / float64(1+w.Current)
- }
- if w.Current == 0 {
- return 10.0
- }
- return 100.0 + float64(w.Current)*10.0
- }
-
- // First pass: try workers in the requested region
+ var eligible []*WorkerEntry
for _, w := range r.workers {
if region != "" && w.Region != region {
continue
}
- score := scoreWorker(w)
- if score < 0 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
continue
}
- if score > bestScore {
- best = w
- bestScore = score
+ // Use Redis routing counter if higher than heartbeat count
+ rCount, err := r.rdb.Get(routingCtx, "routing:count:"+w.ID).Int()
+ if err == nil && rCount > w.Current {
+ w.Current = rCount
}
+ eligible = append(eligible, w)
}
// Fallback: try any region
- if best == nil && region != "" {
+ if len(eligible) == 0 && region != "" {
for _, w := range r.workers {
- score := scoreWorker(w)
- if score < 0 {
+ if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
continue
}
- if score > bestScore {
- best = w
- bestScore = score
- }
+ eligible = append(eligible, w)
}
}
- if best == nil {
+ if len(eligible) == 0 {
return nil, nil, fmt.Errorf("no workers available")
}
+ // Find workers tied for fewest sandboxes, round-robin among them
+ minCount := eligible[0].Current
+ for _, w := range eligible[1:] {
+ if w.Current < minCount {
+ minCount = w.Current
+ }
+ }
+ var tied []*WorkerEntry
+ for _, w := range eligible {
+ if w.Current <= minCount+1 { // within 1 of the minimum
+ tied = append(tied, w)
+ }
+ }
+
+ // Use Redis-based round-robin counter so both CPs spread evenly
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ rr, _ := r.rdb.Incr(ctx, "routing:rr").Result()
+ cancel()
+ best := tied[rr%int64(len(tied))]
+
client, ok := r.clients[best.ID]
if !ok {
return nil, nil, fmt.Errorf("no gRPC connection to worker %s", best.ID)
}
- // Optimistically increment Current so the next call spreads load.
- // The heartbeat will correct this within 10s if the create fails.
- best.Current++
+ // Atomically increment sandbox count in Redis so BOTH CPs see it instantly.
+ // The heartbeat will correct to the real count within 10s.
+ ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
+ r.rdb.Incr(ctx2, "routing:count:"+best.ID)
+ r.rdb.Expire(ctx2, "routing:count:"+best.ID, 15*time.Second)
+ cancel2()
+ best.Current++ // also update local for this CP
return best, client, nil
}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 95a3c0a8..192794f1 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -1021,15 +1021,17 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
log.Printf("scaler: migrate %s: drives pre-copied to S3 (%dms, mode=%s)", sandboxID, time.Since(t0).Milliseconds(), migrationMode)
// Step 2: Prepare target (downloads from S3, starts QEMU -incoming)
- // Get sandbox config from DB for CPU/memory/port
- cpuCount, memoryMB, guestPort, template := int32(1), int32(1024), int32(80), "base"
+ // IMPORTANT: Use the BASE memory (from creation), not the scaled total.
+ // QEMU migration requires matching memory layout: -m <base> + virtio-mem pool.
+ // The hotplugged virtio-mem state transfers as part of the migration stream.
+ cpuCount, memoryMB, guestPort, template := int32(1), int32(256), int32(80), "default"
if s.store != nil {
session, err := s.store.GetSandboxSession(ctx, sandboxID)
if err == nil && session != nil {
if session.Template != "" {
template = session.Template
}
- // Parse CPU/memory from session config JSON
+ // Parse base CPU/memory from session config JSON
var cfg struct {
CPUCount int32 `json:"cpu_count"`
MemoryMB int32 `json:"memory_mb"`
@@ -1039,6 +1041,8 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
if cfg.CPUCount > 0 {
cpuCount = cfg.CPUCount
}
+ // Use base memory from config — this is the QEMU boot memory,
+ // not the total after virtio-mem scaling.
if cfg.MemoryMB > 0 {
memoryMB = cfg.MemoryMB
}
diff --git a/scripts/qemu-tests/39-extended-chaos.sh b/scripts/qemu-tests/39-extended-chaos.sh
index 01c46ae2..2c04b229 100755
--- a/scripts/qemu-tests/39-extended-chaos.sh
+++ b/scripts/qemu-tests/39-extended-chaos.sh
@@ -11,10 +11,10 @@
source "$(dirname "$0")/common.sh"
-TARGET=${1:-200}
+TARGET=${1:-81}
WAVES=5
PER_WAVE=$((TARGET / WAVES))
-CHAOS_ROUNDS=20
+CHAOS_ROUNDS=5
get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
worker_summary() {
@@ -56,6 +56,9 @@ cleanup() {
}
trap cleanup EXIT INT TERM
+# Clear server event history for a clean dashboard
+api -X POST "$API_URL/admin/events/clear" >/dev/null 2>&1
+
echo "=== Extended Chaos Test ==="
echo "Target: $TARGET sandboxes, $CHAOS_ROUNDS chaos rounds"
echo ""
@@ -95,6 +98,17 @@ echo ""
echo "Post-ramp state:"
worker_summary
+# Start real workloads in 20 random sandboxes (allocate memory, run processes)
+echo ""
+echo " Starting workloads in 20 sandboxes..."
+for sb in $(sort -R < "$SANDBOX_FILE" | head -20); do
+ [ -z "$sb" ] && continue
+ # Write files + start a background counter process
+ exec_run "$sb" "sh" "-c" "dd if=/dev/urandom of=/workspace/data.bin bs=1M count=10 2>/dev/null; python3 -c 'import time; [time.sleep(60)]' &" >/dev/null 2>&1 &
+done
+wait 2>/dev/null || true
+echo " Workloads started"
+
# ============================================================
h "Phase 2: Initial responsiveness (sample 30)"
@@ -106,9 +120,10 @@ echo " $RESPONSIVE/30 responsive"
[ "$RESPONSIVE" -ge 27 ] && pass "≥90% responsive ($RESPONSIVE/30)" || fail "$RESPONSIVE/30"
# ============================================================
-h "Phase 3: Extended chaos ($CHAOS_ROUNDS rounds)"
+h "Phase 3: Extended chaos ($CHAOS_ROUNDS rounds — 5 up + 5 down scales per round)"
-MEM_OPTIONS="4096 8192 16384"
+MEM_UP_OPTIONS="8192 8192 8192 16384 16384"
+MEM_DOWN_OPTIONS="4096"
DISK_SIZES="1024 2048 5120" # MB to write
SCALES_OK=0
@@ -124,11 +139,22 @@ for round in $(seq 1 $CHAOS_ROUNDS); do
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
+ # --- Action 1a: Scale UP 5 random sandboxes to 8GB or 16GB ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -5); 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)
+ MEM=$(echo $MEM_UP_OPTIONS | tr ' ' '\n' | sort -R | head -1)
+ result=$(TIMEOUT=120 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 1b: Scale DOWN 5 random sandboxes back to 4GB ---
+ for sb in $(sort -R < "$SANDBOX_FILE" | head -5); do
+ [ -z "$sb" ] && continue
+ result=$(TIMEOUT=60 api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d "{\"memoryMB\":4096,\"cpuPercent\":100}" 2>/dev/null)
if echo "$result" | grep -q "ok"; then
SCALES_OK=$((SCALES_OK + 1))
else
@@ -144,28 +170,7 @@ for round in $(seq 1 $CHAOS_ROUNDS); do
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"
+ # No create/destroy during chaos — keep count fixed for predictable scaling
# --- Action 5: Spot-check 3 random sandboxes ---
for sb in $(sort -R < "$SANDBOX_FILE" | head -3); do
@@ -181,9 +186,50 @@ for round in $(seq 1 $CHAOS_ROUNDS); do
"$SCALES_OK" "$((SCALES_OK + SCALES_FAIL))" "$DISK_WRITES" "$DESTROYS" "$CREATES" \
"$CHECKS_OK" "$((CHECKS_OK + CHECKS_FAIL))"
- sleep 5
+ sleep 2
done
+# ============================================================
+h "Phase 3b: Migration pressure — scale sandboxes on one worker to 8GB until migration triggers"
+
+# Pick the most-loaded worker
+TARGET_WORKER=$(get_workers | python3 -c "
+import sys,json
+w = sorted(json.load(sys.stdin), key=lambda x: -x['current'])
+print(w[0]['worker_id'] if w else '')
+" 2>/dev/null)
+echo " Target worker: ${TARGET_WORKER##*-}"
+
+# Get sandboxes on that worker and scale them to 8GB one by one
+MIGRATED=0
+for sb in $(sort -R < "$SANDBOX_FILE" | head -20); do
+ [ -z "$sb" ] && continue
+ # Check if this sandbox is on the target worker
+ SB_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)
+ [ "$SB_WORKER" != "$TARGET_WORKER" ] && continue
+
+ result=$(TIMEOUT=180 api -X PUT "$API_URL/api/sandboxes/$sb/limits" -d '{"memoryMB":8192,"cpuPercent":200}' 2>/dev/null)
+ migrated=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('migrated',False))" 2>/dev/null)
+ ok=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('ok',False))" 2>/dev/null)
+ mem=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('memoryMB','?'))" 2>/dev/null)
+
+ if [ "$migrated" = "True" ]; then
+ new_worker=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('workerID','?'))" 2>/dev/null)
+ echo " ${sb##*-}: scaled to ${mem}MB → MIGRATED to ${new_worker##*-}"
+ MIGRATED=$((MIGRATED + 1))
+ SCALES_OK=$((SCALES_OK + 1))
+ elif [ "$ok" = "True" ]; then
+ echo " ${sb##*-}: scaled to ${mem}MB (fit on current worker)"
+ SCALES_OK=$((SCALES_OK + 1))
+ else
+ err=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?')[:60])" 2>/dev/null)
+ echo " ${sb##*-}: FAILED — $err"
+ SCALES_FAIL=$((SCALES_FAIL + 1))
+ fi
+done
+
+[ "$MIGRATED" -gt 0 ] && pass "$MIGRATED migration(s) triggered by memory pressure" || skip "No migrations triggered (workers had room)"
+
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"
diff --git a/scripts/qemu-tests/40-ping-pong-demo.sh b/scripts/qemu-tests/40-ping-pong-demo.sh
new file mode 100755
index 00000000..e6c53cfe
--- /dev/null
+++ b/scripts/qemu-tests/40-ping-pong-demo.sh
@@ -0,0 +1,248 @@
+#!/usr/bin/env bash
+# 40-ping-pong-demo.sh — Live migration demo with a real sandbox
+#
+# Creates a sandbox with running processes, files, and a web server,
+# then migrates it across workers verifying everything survives each hop.
+# Designed for demos — clear output, visual verification at each step.
+#
+# Required env:
+# OPENSANDBOX_API_URL
+# OPENSANDBOX_API_KEY
+
+source "$(dirname "$0")/common.sh"
+
+ROUNDS="${1:-10}"
+SB=""
+cleanup() { [ -n "$SB" ] && destroy_sandbox "$SB"; }
+trap cleanup EXIT INT TERM
+
+get_workers() { api "$API_URL/api/workers" 2>/dev/null || echo "[]"; }
+
+current_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
+}
+
+pick_random_target() {
+ local current="$1"
+ api "$API_URL/api/workers" 2>/dev/null | python3 -c "
+import sys,json
+workers = [w['worker_id'] for w in json.load(sys.stdin) if w['worker_id'] != '$current']
+import random
+print(random.choice(workers) if workers else '')
+" 2>/dev/null
+}
+
+# ============================================================
+echo ""
+printf '\033[1;35m'
+# Clear server event history for a clean dashboard
+api -X POST "$API_URL/admin/events/clear" >/dev/null 2>&1
+
+echo "╔══════════════════════════════════════════════════════╗"
+echo "║ Live Migration Ping-Pong Demo ║"
+echo "║ $ROUNDS migrations with full verification ║"
+echo "╚══════════════════════════════════════════════════════╝"
+printf '\033[0m'
+echo ""
+
+WORKER_COUNT=$(get_workers | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
+echo "Workers available: $WORKER_COUNT"
+get_workers | python3 -c "
+import sys,json
+for w in json.load(sys.stdin):
+ print(f' {w[\"worker_id\"][-12:]} cpu={w[\"cpu_pct\"]:.0f}% mem={w[\"mem_pct\"]:.0f}%')
+" 2>/dev/null
+
+if [ "$WORKER_COUNT" -lt 2 ]; then
+ echo "Need at least 2 workers for ping-pong."
+ exit 1
+fi
+
+# ============================================================
+h "Setup: Creating a realistic sandbox"
+
+SB=$(create_sandbox 0)
+echo " Sandbox: $SB"
+CURRENT=$(current_worker)
+echo " Worker: ${CURRENT##*-}"
+echo ""
+
+# Write persistent files
+echo " Writing files..."
+exec_run "$SB" "sh" "-c" "echo 'important-data-12345' > /workspace/data.txt" >/dev/null 2>&1
+exec_run "$SB" "sh" "-c" "seq 1 10000 > /workspace/numbers.txt" >/dev/null 2>&1
+exec_run "$SB" "sh" "-c" "dd if=/dev/urandom of=/workspace/random.bin bs=1024 count=512 2>/dev/null" >/dev/null 2>&1
+HASH_BEFORE=$(exec_stdout "$SB" "md5sum" "/workspace/random.bin" 2>/dev/null | awk '{print $1}')
+echo " Created: data.txt, numbers.txt, random.bin (512KB, md5=$HASH_BEFORE)"
+
+# Start background processes
+echo " Starting background processes..."
+exec_run "$SB" "sh" "-c" "python3 -c \"
+import time, os
+with open('/workspace/counter.txt', 'w') as f:
+ i = 0
+ while True:
+ i += 1
+ f.seek(0)
+ f.write(str(i))
+ f.flush()
+ time.sleep(0.5)
+\" &" >/dev/null 2>&1 || true
+sleep 2
+
+# Install and start a simple web server
+exec_run "$SB" "sh" "-c" "echo '<html><body><h1>Migration Demo</h1><p>Sandbox: $SB</p></body></html>' > /workspace/index.html" >/dev/null 2>&1
+exec_run "$SB" "sh" "-c" "cd /workspace && python3 -m http.server 8080 &" >/dev/null 2>&1 || true
+sleep 1
+
+# Scale to 4GB to make it a real workload
+api -X PUT "$API_URL/api/sandboxes/$SB/limits" -d '{"memoryMB":4096,"cpuPercent":200}' >/dev/null 2>&1
+echo " Scaled to 4GB / 2 vCPU"
+
+# Verify everything works
+DATA=$(exec_stdout "$SB" "cat" "/workspace/data.txt" 2>/dev/null)
+LINES=$(exec_stdout "$SB" "wc" "-l" "/workspace/numbers.txt" 2>/dev/null | awk '{print $1}')
+MEM=$(exec_stdout "$SB" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+PROCS=$(exec_stdout "$SB" "sh" "-c" "ps aux | wc -l" 2>/dev/null | tr -d ' ')
+echo ""
+echo " Sandbox state:"
+echo " Data file: $DATA"
+echo " Numbers: $LINES lines"
+echo " Random hash: $HASH_BEFORE"
+echo " Memory: ${MEM}MB"
+echo " Processes: $PROCS"
+echo ""
+pass "Sandbox ready with files, processes, and web server"
+
+# ============================================================
+h "Ping-Pong: $ROUNDS migrations"
+echo ""
+
+PASS_COUNT=0
+FAIL_COUNT=0
+TOTAL_MS=0
+
+for i in $(seq 1 "$ROUNDS"); do
+ TARGET=$(pick_random_target "$CURRENT")
+
+ printf ' \033[1m%2d.\033[0m %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))
+ TOTAL_MS=$((TOTAL_MS + DURATION))
+
+ # Check for migration error
+ if echo "$RESULT" | grep -qi "error"; then
+ printf '\033[31mFAIL\033[0m migration error (%dms)\n' "$DURATION"
+ echo " Error: $(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('error','?'))" 2>/dev/null)"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify 1: exec works
+ ECHO_OUT=$(exec_stdout "$SB" "echo" "alive" 2>/dev/null)
+ if [ "$ECHO_OUT" != "alive" ]; then
+ printf '\033[31mFAIL\033[0m exec broken (%dms)\n' "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify 2: data file intact
+ DATA_CHECK=$(exec_stdout "$SB" "cat" "/workspace/data.txt" 2>/dev/null)
+ if [ "$DATA_CHECK" != "important-data-12345" ]; then
+ printf '\033[31mFAIL\033[0m data lost (%dms)\n' "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify 3: random file hash matches
+ HASH_CHECK=$(exec_stdout "$SB" "md5sum" "/workspace/random.bin" 2>/dev/null | awk '{print $1}')
+ if [ "$HASH_CHECK" != "$HASH_BEFORE" ]; then
+ printf '\033[31mFAIL\033[0m hash mismatch (%dms)\n' "$DURATION"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ continue
+ fi
+
+ # Verify 4: memory preserved
+ MEM_CHECK=$(exec_stdout "$SB" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+ MEM_OK="yes"
+ [ -n "$MEM_CHECK" ] && [ "$MEM_CHECK" -gt 3000 ] || MEM_OK="no"
+
+ # Verify 5: worker actually changed
+ NEW_WORKER=$(current_worker)
+ WORKER_OK="yes"
+ [ "$NEW_WORKER" = "$TARGET" ] || WORKER_OK="no"
+
+ # Verify 6: process count (should have processes running)
+ PROC_CHECK=$(exec_stdout "$SB" "sh" "-c" "ps aux | wc -l" 2>/dev/null | tr -d ' ')
+ PROC_OK="yes"
+ [ -n "$PROC_CHECK" ] && [ "$PROC_CHECK" -gt 3 ] || PROC_OK="no"
+
+ if [ "$MEM_OK" = "yes" ] && [ "$WORKER_OK" = "yes" ] && [ "$PROC_OK" = "yes" ]; then
+ printf '\033[32m✓\033[0m %dms (exec ✓ data ✓ hash ✓ %sMB ✓ %s procs ✓)\n' "$DURATION" "$MEM_CHECK" "$PROC_CHECK"
+ PASS_COUNT=$((PASS_COUNT + 1))
+ else
+ printf '\033[33m~\033[0m %dms (mem=%s worker=%s procs=%s)\n' "$DURATION" "$MEM_OK" "$WORKER_OK" "$PROC_OK"
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ fi
+
+ CURRENT="$TARGET"
+done
+
+# ============================================================
+echo ""
+h "Results"
+
+AVG_MS=$((TOTAL_MS / ROUNDS))
+
+echo ""
+printf '\033[1m'
+echo " Migrations: $PASS_COUNT/$ROUNDS passed"
+echo " Average: ${AVG_MS}ms per migration"
+echo " Total: ${TOTAL_MS}ms"
+printf '\033[0m'
+echo ""
+
+# Final state verification
+echo " Final verification:"
+FINAL_DATA=$(exec_stdout "$SB" "cat" "/workspace/data.txt" 2>/dev/null)
+FINAL_HASH=$(exec_stdout "$SB" "md5sum" "/workspace/random.bin" 2>/dev/null | awk '{print $1}')
+FINAL_LINES=$(exec_stdout "$SB" "wc" "-l" "/workspace/numbers.txt" 2>/dev/null | awk '{print $1}')
+FINAL_MEM=$(exec_stdout "$SB" "free" "-m" 2>/dev/null | awk '/Mem:/{print $2}')
+FINAL_WORKER=$(current_worker)
+
+echo " Data: $FINAL_DATA $([ "$FINAL_DATA" = "important-data-12345" ] && echo '✓' || echo '✗')"
+echo " Hash: $FINAL_HASH $([ "$FINAL_HASH" = "$HASH_BEFORE" ] && echo '✓' || echo '✗')"
+echo " Lines: $FINAL_LINES $([ "$FINAL_LINES" = "10000" ] && echo '✓' || echo '✗')"
+echo " Memory: ${FINAL_MEM}MB $([ -n "$FINAL_MEM" ] && [ "$FINAL_MEM" -gt 3000 ] && echo '✓' || echo '✗')"
+echo " Worker: ${FINAL_WORKER##*-}"
+echo ""
+
+# Worker visit distribution
+echo " Worker visit distribution:"
+api "$API_URL/admin/report?key=$API_KEY" 2>/dev/null | python3 -c "
+import sys,json
+try:
+ r = json.load(sys.stdin)
+ migs = r.get('migrations',{}).get('details',[])
+ if migs:
+ workers = {}
+ for m in migs:
+ w = m['worker'][-8:]
+ workers[w] = workers.get(w,0) + 1
+ for w,c in sorted(workers.items(), key=lambda x: -x[1]):
+ bar = '█' * c
+ print(f' {w} {c:2d} {bar}')
+except: pass
+" 2>/dev/null
+
+echo ""
+PASS=0; FAIL=0; SKIP=0
+[ "$PASS_COUNT" -eq "$ROUNDS" ] && pass "All $ROUNDS migrations succeeded with full verification" || fail "$FAIL_COUNT/$ROUNDS migrations failed"
+[ "$FINAL_HASH" = "$HASH_BEFORE" ] && pass "512KB file hash intact after $ROUNDS migrations" || fail "File corruption detected"
+[ "$FINAL_DATA" = "important-data-12345" ] && pass "Data persisted across all migrations" || fail "Data lost"
+
+summary