Skip to content

An open-source, faster Devin alternative

TypeScript

wip lite

Brian Reardonb939ab2db04f
diff --git a/.gitignore b/.gitignore
index 22ecb664..7666e602 100644
--- a/.gitignore
+++ b/.gitignore
@@ -94,3 +94,6 @@ cloudflare-workers/api-edge/wrangler.ci.toml
# stray binaries from `go build ./cmd/...` without -o
/microvm-hooks
/microvm-harness
+
+.dev.vars*
+!.dev.vars.example
diff --git a/benchmarks/tti/_instr.mjs b/benchmarks/tti/_instr.mjs
new file mode 100644
index 00000000..cfc3a9eb
--- /dev/null
+++ b/benchmarks/tti/_instr.mjs
@@ -0,0 +1,175 @@
+// Full instrumentation of the REAL SDK under burst.
+//
+// The TTI bench reports one number per iteration and captures no server-timing,
+// so a slow burst is unattributable: "the platform got slower" and "the client
+// queued" look identical. This wraps globalThis.fetch — which is what every SDK
+// call resolves to — and records EVERY request the SDK makes:
+//
+// start offset when fetch() was CALLED, relative to the burst's t0
+// duration how long it took
+// server-timing the edge's own stage breakdown, inside that same request
+//
+// The start offsets are the discriminator. If 100 creates are all CALLED at
+// t~=0 and return staggered, the queue is server-side. If they are called
+// staggered, the client is the queue and no server fix will help.
+import { Sandbox } from '@opencomputer/sdk';
+import diagnostics from 'node:diagnostics_channel';
+
+const N = parseInt(process.env.N ?? '100', 10);
+const CMD = process.env.CMD ?? 'node -v';
+
+// Connection-level truth. A request that is "slow" because it sat waiting for a
+// socket is a client problem no server change can fix; one that is slow with a
+// socket already in hand is not. undici publishes both, so we count them rather
+// than argue about them.
+const conn = { created: 0, connected: 0, failed: 0, connectMs: [] };
+const connectStart = new Map();
+try {
+ diagnostics.subscribe('undici:client:connectStart', (e) => {
+ connectStart.set(e, performance.now());
+ conn.created++;
+ });
+ diagnostics.subscribe('undici:client:connected', (e) => {
+ conn.connected++;
+ const t = connectStart.get(e);
+ if (t !== undefined) { conn.connectMs.push(performance.now() - t); connectStart.delete(e); }
+ });
+ diagnostics.subscribe('undici:client:connectError', () => { conn.failed++; });
+} catch { /* channels unavailable — the fetch-level numbers still stand */ }
+
+const calls = [];
+let T0 = performance.now();
+
+const realFetch = globalThis.fetch;
+globalThis.fetch = async function (input, init) {
+ const url = typeof input === 'string' ? input : (input?.url ?? String(input));
+ const method = init?.method ?? 'GET';
+ const started = performance.now();
+ const rec = {
+ method,
+ path: url.replace(/^https?:\/\/[^/]+/, '').split('?')[0],
+ start: started - T0,
+ dur: -1,
+ status: 0,
+ timing: {},
+ };
+ calls.push(rec);
+ try {
+ const resp = await realFetch(input, init);
+ rec.dur = performance.now() - started;
+ rec.status = resp.status;
+ const st = resp.headers.get('server-timing') ?? '';
+ for (const part of st.split(',')) {
+ const m = part.trim().match(/^([a-z0-9_]+);dur=([0-9.]+)/i);
+ if (m) rec.timing[m[1]] = Number(m[2]);
+ }
+ return resp;
+ } catch (e) {
+ rec.dur = performance.now() - started;
+ rec.status = -1;
+ throw e;
+ }
+};
+
+// Let the SDK's import-time prewarm settle so it is not racing the burst; those
+// /health calls are recorded too and reported separately.
+await new Promise((r) => setTimeout(r, 2000));
+
+const iters = [];
+async function one(i) {
+ const t = { i, createStart: -1, create: -1, exec: -1, tti: -1, err: null };
+ const s = performance.now();
+ t.createStart = s - T0;
+ let sb;
+ try {
+ sb = await Sandbox.create({});
+ t.create = performance.now() - s;
+ const e = performance.now();
+ await sb.exec.run(CMD);
+ t.exec = performance.now() - e;
+ t.tti = performance.now() - s;
+ } catch (err) {
+ t.err = String(err).slice(0, 90);
+ }
+ iters.push(t);
+ try { if (sb) await sb.destroy(); } catch {}
+}
+
+calls.length = 0; // drop prewarm noise from the window we analyse
+T0 = performance.now();
+const wall0 = performance.now();
+// MODE=seq runs the SAME instrumentation one-at-a-time. That is the control the
+// burst needs: identical client, identical marks, concurrency 1. Comparing the
+// two stage-by-stage is what separates "a stage inflates under load" from "the
+// whole path is uniformly slower".
+if ((process.env.MODE ?? 'burst') === 'seq') {
+ for (let i = 0; i < N; i++) await one(i);
+} else {
+ await Promise.all(Array.from({ length: N }, (_, i) => one(i)));
+}
+const wall = performance.now() - wall0;
+
+// ── report ────────────────────────────────────────────────────────────────
+const f = (n) => (n < 0 ? '-' : n.toFixed(0));
+const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(p * s.length)] ?? -1; };
+const stat = (name, v) => v.length
+ ? `${name.padEnd(16)} n=${String(v.length).padStart(4)} min ${f(Math.min(...v)).padStart(6)} p50 ${f(q(v, .5)).padStart(6)} p95 ${f(q(v, .95)).padStart(6)} max ${f(Math.max(...v)).padStart(6)}`
+ : `${name.padEnd(16)} —`;
+
+const ok = iters.filter((x) => x.err === null);
+console.log(`\n=== SDK burst N=${N} — ${ok.length}/${N} ok, wall ${f(wall)}ms ===\n`);
+console.log('ITERATION (client-observed):');
+console.log(' ' + stat('createStart', ok.map((x) => x.createStart)));
+console.log(' ' + stat('create', ok.map((x) => x.create)));
+console.log(' ' + stat('exec', ok.map((x) => x.exec)));
+console.log(' ' + stat('tti', ok.map((x) => x.tti)));
+
+const byPath = new Map();
+for (const c of calls) {
+ const k = `${c.method} ${c.path.replace(/\/sb-[a-z0-9]+/g, '/:id').replace(/\/[0-9a-f-]{20,}/g, '/:uuid')}`;
+ if (!byPath.has(k)) byPath.set(k, []);
+ byPath.get(k).push(c);
+}
+console.log(`\nREQUESTS the SDK actually made (${calls.length} total for ${N} iterations):`);
+for (const [k, v] of [...byPath.entries()].sort((a, b) => b[1].length - a[1].length)) {
+ console.log(' ' + stat(k.slice(0, 16), v.map((c) => c.dur)) + ` [${k}]`);
+ console.log(' ' + stat(' ↳ startOffset', v.map((c) => c.start)));
+ const marks = new Set(v.flatMap((c) => Object.keys(c.timing)));
+ for (const m of [...marks].sort()) {
+ const vals = v.map((c) => c.timing[m]).filter((x) => x !== undefined);
+ if (vals.length) console.log(' ' + stat(` ↳ ${m}`, vals));
+ }
+}
+console.log(`\nCONNECTIONS opened DURING the burst (client-side queueing):`);
+console.log(` new connections started=${conn.created} connected=${conn.connected} failed=${conn.failed}`);
+if (conn.connectMs.length) console.log(' ' + stat('connect', conn.connectMs));
+console.log(` → ${conn.created} new sockets for ${calls.length} requests` +
+ (conn.created > N * 0.5 ? ' ⚠ most requests paid a fresh connection' : ' (pool was reused)'));
+
+// The ramp, stated directly: bucket every create by when it STARTED and show
+// what it cost. A rising cost with flat start offsets is a server-side queue;
+// rising start offsets are a client-side one.
+const creates = calls.filter((c) => c.method === 'POST' && /\/sandboxes$/.test(c.path));
+if (creates.length) {
+ console.log('\nCREATE RAMP (deciles by start order):');
+ const sorted = [...creates].sort((a, b) => a.start - b.start);
+ const step = Math.max(1, Math.floor(sorted.length / 10));
+ for (let i = 0; i < sorted.length; i += step) {
+ const chunk = sorted.slice(i, i + step);
+ const d = chunk.map((c) => c.dur);
+ const cell = chunk.map((c) => c.timing.cell).filter((x) => x !== undefined);
+ console.log(` #${String(i).padStart(3)}-${String(Math.min(i + step, sorted.length) - 1).padStart(3)}` +
+ ` start ${f(chunk[0].start).padStart(5)}-${f(chunk.at(-1).start).padStart(5)}ms` +
+ ` dur p50 ${f(q(d, .5)).padStart(5)}ms` +
+ (cell.length ? ` edge.cell p50 ${f(q(cell, .5)).padStart(4)}ms` : ''));
+ }
+}
+
+const bad = calls.filter((c) => c.status >= 400 || c.status < 0);
+if (bad.length) {
+ const c2 = new Map();
+ for (const b of bad) c2.set(`${b.status} ${b.path}`, (c2.get(`${b.status} ${b.path}`) ?? 0) + 1);
+ console.log('\nNON-2xx:', [...c2.entries()].map(([k, n]) => `${k} ×${n}`).join(', '));
+}
+const errs = iters.filter((x) => x.err);
+if (errs.length) console.log('\nITER ERRORS:', [...new Set(errs.map((e) => e.err))].slice(0, 5));
diff --git a/benchmarks/tti/_split.mjs b/benchmarks/tti/_split.mjs
new file mode 100644
index 00000000..ab8abea2
--- /dev/null
+++ b/benchmarks/tti/_split.mjs
@@ -0,0 +1,35 @@
+// Burst through the REAL SDK, timing create and exec legs separately.
+// Answers: is SDK burst-100 slow in create, or in exec (inline-hold miss)?
+import { Sandbox } from '@opencomputer/sdk';
+
+const N = parseInt(process.env.N ?? '100', 10);
+const rows = [];
+
+async function one(i) {
+ const t0 = performance.now();
+ let sb, tCreate = -1, tExec = -1, err = null;
+ try {
+ sb = await Sandbox.create({});
+ tCreate = performance.now() - t0;
+ const t1 = performance.now();
+ await sb.exec.run('node -v');
+ tExec = performance.now() - t1;
+ } catch (e) { err = String(e).slice(0, 80); }
+ rows.push({ i, tCreate, tExec, tti: tCreate < 0 ? -1 : tCreate + tExec, err });
+ try { if (sb) await sb.destroy(); } catch {}
+}
+
+const t = performance.now();
+await Promise.all(Array.from({ length: N }, (_, i) => one(i)));
+const wall = performance.now() - t;
+
+const ok = rows.filter(r => r.err === null);
+const q = (arr, p) => { const s = [...arr].sort((a, b) => a - b); return s[Math.floor(p * s.length)] ?? -1; };
+const f = n => n.toFixed(0);
+console.log(`\nwall=${f(wall)}ms ok=${ok.length}/${N}`);
+for (const [k, label] of [['tCreate', 'create'], ['tExec', 'exec'], ['tti', 'TTI']]) {
+ const v = ok.map(r => r[k]);
+ console.log(`${label.padEnd(7)} min=${f(Math.min(...v))} p50=${f(q(v, .5))} p95=${f(q(v, .95))} max=${f(Math.max(...v))}`);
+}
+const errs = rows.filter(r => r.err).map(r => r.err);
+if (errs.length) console.log('errors:', [...new Set(errs)].slice(0, 5));
diff --git a/benchmarks/tti/_transport.mjs b/benchmarks/tti/_transport.mjs
new file mode 100644
index 00000000..3ebf940d
--- /dev/null
+++ b/benchmarks/tti/_transport.mjs
@@ -0,0 +1,53 @@
+// Pure client-transport probe: 100 concurrent POSTs to /health.
+// No sandboxes, no pool. Isolates dispatcher cost (h2 vs h1.1, prewarm vs not).
+const BASE = process.env.BASE ?? 'https://app2.opensandbox.ai';
+const N = parseInt(process.env.N ?? '100', 10);
+const MODE = process.env.TMODE ?? 'raw'; // raw | h2 | h2warm | h1warm
+const PREWARM = parseInt(process.env.PW ?? '48', 10);
+
+async function setup() {
+ if (MODE === 'raw') return 'node-default (h1.1, no prewarm)';
+ const { Agent, setGlobalDispatcher } = await import('undici');
+ const allowH2 = MODE === 'h2' || MODE === 'h2warm' || MODE === 'race';
+ setGlobalDispatcher(new Agent({
+ allowH2,
+ keepAliveTimeout: 600_000,
+ keepAliveMaxTimeout: 600_000,
+ }));
+ if (MODE === 'race') {
+ // Do NOT await: prewarm opens 48 connections WHILE the wave runs — exactly
+ // what Sandbox.create() does with its fire-and-forget prewarmConnections().
+ const ping = () => fetch(`${BASE}/health`, { method: 'POST' })
+ .then(r => r.arrayBuffer()).catch(() => {});
+ void Promise.all(Array.from({ length: PREWARM }, ping));
+ return `undici allowH2=true + prewarm ${PREWARM} RACING the wave`;
+ }
+ if (MODE === 'h2warm' || MODE === 'h1warm') {
+ const ping = () => fetch(`${BASE}/health`, { method: 'POST' })
+ .then(r => r.arrayBuffer()).catch(() => {});
+ await Promise.all(Array.from({ length: PREWARM }, ping));
+ return `undici allowH2=${allowH2} + prewarm ${PREWARM}`;
+ }
+ return `undici allowH2=${allowH2}, no prewarm`;
+}
+
+const desc = await setup();
+
+async function wave(label) {
+ const t0 = performance.now();
+ const lat = await Promise.all(Array.from({ length: N }, async () => {
+ const s = performance.now();
+ try { const r = await fetch(`${BASE}/health`, { method: 'POST' }); await r.arrayBuffer(); }
+ catch { return -1; }
+ return performance.now() - s;
+ }));
+ const wall = performance.now() - t0;
+ const ok = lat.filter(x => x >= 0).sort((a, b) => a - b);
+ const p = q => ok[Math.min(ok.length - 1, Math.floor(q * ok.length))] ?? -1;
+ console.log(`${label.padEnd(8)} wall=${wall.toFixed(0)}ms ok=${ok.length}/${N} ` +
+ `min=${(ok[0] ?? -1).toFixed(0)} p50=${p(0.5).toFixed(0)} p95=${p(0.95).toFixed(0)} max=${(ok.at(-1) ?? -1).toFixed(0)}`);
+}
+
+console.log(`\nmode=${MODE} N=${N} ${desc}`);
+await wave('wave1'); // cold-ish (except when prewarmed)
+await wave('wave2'); // fully warm — connections now exist in every mode
diff --git a/benchmarks/tti/bench.mjs b/benchmarks/tti/bench.mjs
index d33ff499..242eced2 100644
--- a/benchmarks/tti/bench.mjs
+++ b/benchmarks/tti/bench.mjs
@@ -52,6 +52,177 @@ const CONCURRENCY = parseInt(flag('concurrency', 'CONCURRENCY', '100'), 10);
const STAGGER_DELAY_MS = parseInt(flag('stagger-delay-ms', 'STAGGER_DELAY_MS', '200'), 10);
const JSON_OUT = flag('json', 'JSON_OUT', '');
+// ---- server-timing capture ------------------------------------------------
+//
+// The SDK returns parsed results, not Responses, so the only place to read the
+// edge's server-timing header is the fetch layer. Without this the harness can
+// see that a burst is slow but not WHERE, which is how a slow run stays
+// ambiguous between "the tunnel was cold" and "the client was saturated".
+//
+// The marks that matter (see cloudflare-workers/vm-do/src/microvm_session.ts):
+// dlive 1 = the DO already had a live channel; 0 = it had to dial
+// ddial ms spent dialing (0 when no dial happened)
+// dcold 1 = the DO was constructed to serve this request (it had been evicted)
+// dunary the RPC itself — transport PLUS the guest running the command
+// mvmdo the edge's view of the whole DO round trip
+const marks = [];
+// EVERY request the SDK makes, not just the ones that come back with
+// server-timing. A direct-fetch control does 2 requests per TTI iteration; if
+// the SDK does more, the extra ones are invisible in `marks` because a response
+// without a server-timing header is never recorded.
+const httpLog = [];
+const nativeFetch = globalThis.fetch;
+globalThis.fetch = async function instrumentedFetch(input, init) {
+ const u = String(typeof input === 'string' ? input : input?.url ?? '');
+ const t0 = performance.now();
+ const resp = await nativeFetch(input, init);
+ httpLog.push({ method: init?.method ?? 'GET', url: u, ms: performance.now() - t0, status: resp.status });
+ const st = resp.headers?.get?.('server-timing');
+ if (st) {
+ const rec = { url: String(typeof input === 'string' ? input : input?.url ?? '') };
+ for (const part of st.split(',')) {
+ const m = part.trim().match(/^([a-z]+);(?:dur=([-\d.]+)|desc=(.+))$/i);
+ if (m) rec[m[1]] = m[2] !== undefined ? Number(m[2]) : m[3];
+ }
+ marks.push(rec);
+ }
+ return resp;
+};
+
+// markStats reports the distribution of one mark across every exec response.
+function markStats(name) {
+ const vals = marks.map((m) => m[name]).filter((v) => typeof v === 'number' && v >= 0);
+ if (vals.length === 0) return null;
+ vals.sort((a, b) => a - b);
+ const at = (p) => vals[Math.min(vals.length - 1, Math.max(0, Math.ceil((p / 100) * vals.length) - 1))];
+ return { n: vals.length, p50: at(50), p95: at(95), max: vals[vals.length - 1] };
+}
+
+function reportMarks(label) {
+ const live = marks.filter((m) => typeof m.dlive === 'number');
+ if (live.length === 0) {
+ process.stdout.write(` ${label} marks: none captured (no server-timing on any response)\n`);
+ return;
+ }
+ const liveCount = live.filter((m) => m.dlive === 1).length;
+ process.stdout.write(
+ ` ${label} marks: dlive=1 on ${liveCount}/${live.length}` +
+ ` (${((liveCount / live.length) * 100).toFixed(0)}% warm channel)\n`,
+ );
+ // Report EVERY numeric mark seen, not a hardcoded list. The create response
+ // carries its own breakdown (pre/ctx/claim/mintseed/...) and a fixed list of
+ // exec marks silently discarded all of it — which is how a create leg that
+ // turned out to be the dominant cost stayed unattributed while we chased the
+ // exec leg. Exec marks first, then everything else, so the shape stays
+ // familiar.
+ const known = ['ddial', 'dunary', 'mvmdo', 'dcold'];
+ const seenNumeric = new Set();
+ for (const m of marks) {
+ for (const [k, v] of Object.entries(m)) {
+ if (typeof v === 'number' && k !== 'dlive') seenNumeric.add(k);
+ }
+ }
+ const order = [...known.filter((k) => seenNumeric.has(k)), ...[...seenNumeric].filter((k) => !known.includes(k)).sort()];
+ for (const n of order) {
+ const s = markStats(n);
+ if (s) process.stdout.write(` ${n.padEnd(9)} p50=${s.p50} p95=${s.p95} max=${s.max} (n=${s.n})\n`);
+ }
+ // Request census by endpoint shape. A direct-fetch control needs exactly 2
+ // per iteration (create + run-async); anything beyond that is SDK overhead
+ // that no server-side mark can see.
+ if (httpLog.length) {
+ const byShape = {};
+ for (const h of httpLog) {
+ const shape = `${h.method} ${h.url
+ .replace(/^https?:\/\/[^/]+/, '')
+ .replace(/sb-[a-z0-9]+/gi, ':id')
+ .replace(/exec\/[^/]+\/result/, 'exec/:execId/result')}`;
+ (byShape[shape] ??= []).push(h.ms);
+ }
+ process.stdout.write(` http: ${httpLog.length} request(s) total\n`);
+ for (const [shape, v] of Object.entries(byShape).sort((a, b) => b[1].length - a[1].length)) {
+ const s = [...v].sort((a, b) => a - b);
+ process.stdout.write(
+ ` ${String(v.length).padStart(4)}× ${shape} p50=${Math.round(s[Math.ceil(0.5 * s.length) - 1])}ms\n`,
+ );
+ }
+ }
+
+ // Every string-valued mark, not just dcolo. `doclo` (the PoolStock shard's
+ // colo) was being emitted by the edge on every create and dropped here, which
+ // is why the claim cost looked unattributable.
+ // `path` is the edge's own label for which exec route served the request
+ // (stampSub in index.ts): mvm-direct | vmdo | fast | tunnel. This is the
+ // ground truth for "did we take the fast path", and it is stamped on EVERY
+ // exec response — it was being captured all along and simply never printed.
+ // Cross-tabbed with dlive so a live channel can't be confused with a warm one.
+ const byPath = new Map();
+ for (const m of marks) {
+ if (typeof m.path !== 'string') continue;
+ const e = byPath.get(m.path) ?? { n: 0, live: 0, dialed: 0, noMark: 0 };
+ e.n++;
+ if (m.dlive === 1) e.live++;
+ else if (m.dlive === 0) e.dialed++;
+ else e.noMark++;
+ byPath.set(m.path, e);
+ }
+ if (byPath.size) {
+ process.stdout.write(' exec path (edge ground truth):\n');
+ for (const [p, e] of [...byPath.entries()].sort((a, b) => b[1].n - a[1].n)) {
+ process.stdout.write(
+ ` ${p.padEnd(11)} n=${String(e.n).padStart(3)} dlive=1:${e.live} dlive=0(dialed):${e.dialed} no-dlive:${e.noMark}\n`,
+ );
+ }
+ }
+
+ // WHY each tunnel exec gave up on the fast path. `path=tunnel` says a fallback
+ // happened; these say which of the six exits took it, and they are disjoint
+ // fixes: a DO reporting no channel is a pre-warm coverage problem, a DO 409
+ // carrying a dial error is a reachability problem, `reach-null` is a cache
+ // problem. `dialfail` is the second leg — the direct dial's own outcome, which
+ // only runs after the DO declined.
+ for (const name of ['why', 'dialfail']) {
+ const reasons = {};
+ for (const m of marks) if (typeof m[name] === 'string') reasons[m[name]] = (reasons[m[name]] ?? 0) + 1;
+ const seen = Object.entries(reasons).sort((a, b) => b[1] - a[1]);
+ if (!seen.length) continue;
+ process.stdout.write(` ${name === 'why' ? 'fallback reason' : 'direct-dial outcome'}:\n`);
+ for (const [r, n] of seen) process.stdout.write(` ${String(n).padStart(3)}× ${r}\n`);
+ }
+
+ for (const name of ['dcolo', 'doclo']) {
+ const colos = {};
+ for (const m of marks) if (typeof m[name] === 'string') colos[m[name]] = (colos[m[name]] ?? 0) + 1;
+ const seen = Object.entries(colos).sort((a, b) => b[1] - a[1]);
+ if (seen.length) process.stdout.write(` ${name.padEnd(9)} ${seen.map(([c, n]) => `${c}:${n}`).join(' ')}\n`);
+ }
+
+ // The decisive one: claim latency BUCKETED BY the colo that served it. `doin`
+ // is the DO's own half, so `claim - doin` is the hop. If in-metro shards
+ // answer in ~15ms and off-metro shards in ~80ms with doin=0 on both, the cost
+ // is placement, not Durable Objects — and no amount of removing the DO helps,
+ // because whatever replaces it still has to be reached.
+ const byColo = new Map();
+ for (const m of marks) {
+ if (typeof m.doclo !== 'string' || typeof m.claim !== 'number') continue;
+ if (!byColo.has(m.doclo)) byColo.set(m.doclo, []);
+ byColo.get(m.doclo).push({ claim: m.claim, doin: typeof m.doin === 'number' ? m.doin : 0 });
+ }
+ if (byColo.size) {
+ process.stdout.write(' claim by shard colo (hop = claim - doin):\n');
+ const rows = [...byColo.entries()].sort((a, b) => b[1].length - a[1].length);
+ for (const [colo, rs] of rows) {
+ const cs = rs.map((r) => r.claim).sort((a, b) => a - b);
+ const hs = rs.map((r) => r.claim - r.doin).sort((a, b) => a - b);
+ const med = (v) => v[Math.max(0, Math.ceil(0.5 * v.length) - 1)];
+ const p95 = (v) => v[Math.max(0, Math.ceil(0.95 * v.length) - 1)];
+ process.stdout.write(
+ ` ${colo.padEnd(5)} n=${String(rs.length).padStart(3)} claim p50=${med(cs)} p95=${p95(cs)} hop p50=${med(hs)} p95=${p95(hs)}\n`,
+ );
+ }
+ }
+}
+
// Per-op timeouts, matching the leaderboard's tti-task.ts.
const CREATE_TIMEOUT_MS = 120_000;
const COMMAND_TIMEOUT_MS = 30_000;
@@ -142,8 +313,16 @@ async function sweepOutstanding(where) {
}
/** One TTI iteration: create -> node -v (exit 0) -> destroy (untimed). */
+// One provider for the whole run, not one per iteration.
+//
+// This used to be constructed inside ttiTask, so a burst-100 built 100 provider
+// objects plus their wrapper churn on a single event loop — client-side CPU
+// competing with the very latency being measured. Providers are stateless
+// config holders, and the SDK caches its Sandbox class at module scope, so
+// sharing one is both cheaper and closer to how a real caller uses it.
+const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });
+
async function ttiTask() {
- const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });
const start = performance.now();
// Register off the underlying promise so a create that outruns our timeout is
// still swept. Attaching to the raced promise instead would lose exactly the
@@ -173,6 +352,9 @@ async function runMode(label, { iterations, concurrency, staggerDelayMs }) {
`\n== ${label}: iterations=${iterations} concurrency=${concurrency} staggerDelayMs=${staggerDelayMs} ==\n`,
);
const oks = []; // ttiMs of successes
+ // httpLog is global and never reset (a leaked-sandbox sweep between modes
+ // still needs to be visible in it), so remember where this mode started.
+ const httpStart = httpLog.length;
let done = 0;
let fails = 0;
let active = 0;
@@ -203,7 +385,18 @@ async function runMode(label, { iterations, concurrency, staggerDelayMs }) {
// mode a depleted pool and have its result read as a regression.
await sweepOutstanding(label);
- return summarize(label, { iterations, oks, fails });
+ reportMarks(label);
+ // Snapshot before the reset so --json can carry the per-request detail, not
+ // just the percentiles. The printed summary answers "how slow"; only the
+ // per-request sequence answers "which iteration, and which leg of it" — and
+ // in sequential mode the requests arrive in strict order, so position in
+ // these arrays IS iteration order. Without this, attributing one slow run
+ // means re-running and hoping it reproduces.
+ const modeMarks = marks.map((m) => ({ ...m }));
+ const modeHttp = httpLog.slice(httpStart);
+ marks.length = 0; // per-mode, so a burst isn't read through the sequential run's marks
+
+ return { ...summarize(label, { iterations, oks, fails }), marks: modeMarks, http: modeHttp };
}
// ---- stats + scoring (ported verbatim from the leaderboard) ---------------
diff --git a/benchmarks/tti/direct.mjs b/benchmarks/tti/direct.mjs
new file mode 100644
index 00000000..165d62dd
--- /dev/null
+++ b/benchmarks/tti/direct.mjs
@@ -0,0 +1,204 @@
+#!/usr/bin/env node
+/**
+ * DIRECT-API TTI harness — the control for bench.mjs.
+ *
+ * Same TTI definition as bench.mjs (create -> `node -v` exit 0, destroy
+ * untimed), same concurrency model, same endpoints and wire bodies as
+ * @opencomputer/sdk. The ONLY difference is that this speaks raw fetch instead
+ * of going through the SDK object graph.
+ *
+ * It exists because a direct harness reportedly scored ~300ms on a burst where
+ * the SDK scored ~1s against the same backend. If that reproduces here, the
+ * penalty is in the client, not the platform — and every server-side mark we
+ * have would be blind to it, because they all start their clock at handler
+ * entry (see index.ts, the `tPrev` note).
+ *
+ * The instrumentation that matters is per-iteration REQUEST COUNT and
+ * client-side sleep, because that is precisely what the SDK adds:
+ * exec.run() short-circuits only when the response carries no execId
+ * (exec.js:297). Otherwise it polls — an immediate /result, then sleep 50,
+ * 100, 200... on a single Node event loop, which is exactly the thing that
+ * degrades when 100 tasks share that loop.
+ *
+ * OPENCOMPUTER_API_KEY=osb_xxx node direct.mjs --api-url https://app2.opensandbox.ai \
+ * --mode burst --iterations 100 --concurrency 100
+ */
+
+const flag = (n, e, d) => {
+ const i = process.argv.indexOf(`--${n}`);
+ if (i !== -1 && process.argv[i + 1] !== undefined) return process.argv[i + 1];
+ return process.env[e] ?? d;
+};
+const RAW_URL = flag('api-url', 'OPENCOMPUTER_API_URL', 'https://app.opencomputer.dev');
+const BASE = RAW_URL.replace(/\/+$/, '');
+const API = BASE.endsWith('/api') ? BASE : `${BASE}/api`;
+const API_KEY = flag('api-key', 'OPENCOMPUTER_API_KEY', '');
+const MODE = flag('mode', 'MODE', 'sequential');
+const ITER = parseInt(flag('iterations', 'ITERATIONS', '12'), 10);
+if (!API_KEY) {
+ console.error('OPENCOMPUTER_API_KEY is required (env var or --api-key).');
+ process.exit(2);
+}
+
+// Match bench.mjs's mode table exactly so the two are comparable.
+const MODES = {
+ sequential: { concurrency: 1, stagger: 0 },
+ staggered: { concurrency: 100, stagger: 200 },
+ burst: { concurrency: 100, stagger: 0 },
+};
+const modeCfg = MODES[MODE] ?? MODES.sequential;
+const CONC = parseInt(flag('concurrency', 'CONCURRENCY', String(modeCfg.concurrency)), 10);
+const STAGGER = parseInt(flag('stagger', 'STAGGER', String(modeCfg.stagger)), 10);
+
+const KEEP_ALIVE_MS = 600_000;
+const CREATE_TIMEOUT_MS = 120_000;
+const COMMAND_TIMEOUT_MS = 30_000;
+
+const HEADERS = { 'Content-Type': 'application/json', 'X-API-Key': API_KEY };
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const now = () => performance.now();
+
+// Per-iteration counters. `requests` is the headline: the SDK's poll ladder
+// shows up here as >2, and nowhere in any server-timing mark.
+const stats = { requests: [], sleptMs: [], polls: [] };
+
+async function jfetch(url, init) {
+ const resp = await fetch(url, init);
+ if (!resp.ok) {
+ const text = await resp.text().catch(() => '');
+ throw new Error(`${init?.method ?? 'GET'} ${url} -> ${resp.status} ${text.slice(0, 200)}`);
+ }
+ return resp.json();
+}
+
+async function createSandbox() {
+ return jfetch(`${API}/sandboxes`, {
+ method: 'POST',
+ headers: HEADERS,
+ body: JSON.stringify({ templateID: 'base', timeout: KEEP_ALIVE_MS }),
+ });
+}
+
+/**
+ * Byte-for-byte the SDK's run() contract, including the inline short-circuit
+ * and the backoff ladder, so a difference in the numbers cannot be blamed on
+ * this harness taking a cheaper path than the SDK does.
+ */
+async function runCommand(id, command, counters) {
+ const handle = await jfetch(`${API}/sandboxes/${id}/exec/run-async`, {
+ method: 'POST',
+ headers: HEADERS,
+ body: JSON.stringify({ cmd: 'sh', args: ['-c', command], timeout: 60 }),
+ });
+ counters.requests++;
+ // Inline result: the edge's VM-DO fast path answers in the run-async shape
+ // with no execId, and the SDK returns here without ever polling.
+ if (handle.execId == null && handle.exitCode != null) return handle;
+
+ const execId = handle.execId;
+ let delay = 50;
+ for (;;) {
+ const result = await jfetch(`${API}/sandboxes/${id}/exec/${execId}/result`, { headers: HEADERS });
+ counters.requests++;
+ counters.polls++;
+ if (!result.running) return result;
+ await sleep(delay);
+ counters.sleptMs += delay;
+ delay = Math.min(delay * 2, 2000);
+ }
+}
+
+async function destroy(id) {
+ await fetch(`${API}/sandboxes/${id}`, { method: 'DELETE', headers: HEADERS }).catch(() => {});
+}
+
+function withTimeout(p, ms, msg) {
+ let t;
+ return Promise.race([
+ p.finally(() => clearTimeout(t)),
+ new Promise((_, rej) => {
+ t = setTimeout(() => rej(new Error(msg)), ms);
+ }),
+ ]);
+}
+
+async function ttiTask() {
+ const counters = { requests: 0, polls: 0, sleptMs: 0 };
+ const start = now();
+ let box;
+ try {
+ box = await withTimeout(createSandbox(), CREATE_TIMEOUT_MS, 'create timed out');
+ counters.requests++;
+ const id = box.sandboxID ?? box.sandboxId ?? box.id ?? box.sandbox_id;
+ if (!id) throw new Error(`create returned no id: ${JSON.stringify(box).slice(0, 200)}`);
+ const res = await withTimeout(runCommand(id, 'node -v', counters), COMMAND_TIMEOUT_MS, 'command timed out');
+ if (res.exitCode !== 0) throw new Error(`node -v exit ${res.exitCode}: ${res.stderr || 'unknown'}`);
+ const ms = now() - start;
+ stats.requests.push(counters.requests);
+ stats.polls.push(counters.polls);
+ stats.sleptMs.push(counters.sleptMs);
+ return ms;
+ } finally {
+ const id = box?.sandboxID ?? box?.sandboxId ?? box?.id ?? box?.sandbox_id;
+ if (id) await destroy(id);
+ }
+}
+
+async function runMode() {
+ const results = [];
+ let launched = 0;
+ const inFlight = new Set();
+ while (launched < ITER || inFlight.size > 0) {
+ while (launched < ITER && inFlight.size < CONC) {
+ const idx = ++launched;
+ const p = ttiTask()
+ .then((ms) => {
+ results.push(ms);
+ process.stdout.write(` [${idx}/${ITER}] ok ${(ms / 1000).toFixed(2)}s\n`);
+ })
+ .catch((e) => {
+ process.stdout.write(` [${idx}/${ITER}] FAIL ${e.message}\n`);
+ })
+ .finally(() => inFlight.delete(p));
+ inFlight.add(p);
+ if (STAGGER > 0) await sleep(STAGGER);
+ }
+ if (inFlight.size > 0) await Promise.race(inFlight);
+ }
+ return results;
+}
+
+function pct(sorted, p) {
+ if (!sorted.length) return 0;
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
+}
+const fmt = (ms) => (ms >= 1000 ? `${(ms / 1000).toFixed(2)}s` : `${Math.round(ms)}ms`);
+const mean = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0);
+
+(async () => {
+ process.stdout.write(`DIRECT-API TTI → ${API} (key ${API_KEY.slice(0, 6)}…) mode=${MODE} conc=${CONC}\n`);
+ process.stdout.write(`== ${MODE}: iterations=${ITER} concurrency=${CONC} stagger=${STAGGER}ms ==\n`);
+ const t0 = now();
+ const results = await runMode();
+ const wall = now() - t0;
+ const sorted = [...results].sort((a, b) => a - b);
+ process.stdout.write('\n' + '='.repeat(78) + '\n');
+ process.stdout.write(`DIRECT-API TTI — ${API}\n`);
+ process.stdout.write('='.repeat(78) + '\n');
+ process.stdout.write(
+ `mode ok/n succ% min median P95 P99 max mean\n` +
+ `${MODE.padEnd(11)} ${String(results.length).padStart(3)}/${String(ITER).padEnd(4)} ` +
+ `${String(Math.round((results.length / ITER) * 100)).padStart(4)}% ` +
+ `${fmt(sorted[0] ?? 0).padEnd(6)} ${fmt(pct(sorted, 50)).padEnd(7)} ${fmt(pct(sorted, 95)).padEnd(6)} ` +
+ `${fmt(pct(sorted, 99)).padEnd(6)} ${fmt(sorted[sorted.length - 1] ?? 0).padEnd(6)} ${fmt(mean(results))}\n`,
+ );
+ // The client-shape numbers. These are the ones the server cannot see.
+ const reqs = [...stats.requests].sort((a, b) => a - b);
+ const slept = [...stats.sleptMs].sort((a, b) => a - b);
+ process.stdout.write(
+ `\n client shape: requests/iter p50=${pct(reqs, 50)} max=${pct(reqs, 100)}` +
+ ` polls/iter p50=${pct([...stats.polls].sort((a, b) => a - b), 50)}` +
+ ` client sleep p50=${pct(slept, 50)}ms max=${pct(slept, 100)}ms\n`,
+ );
+ process.stdout.write(` wall ${fmt(wall)}\n`);
+})();
diff --git a/cloudflare-workers/api-edge/src/colo_cache.ts b/cloudflare-workers/api-edge/src/colo_cache.ts
index 530e21f1..a7a5f710 100644
--- a/cloudflare-workers/api-edge/src/colo_cache.ts
+++ b/cloudflare-workers/api-edge/src/colo_cache.ts
@@ -54,3 +54,19 @@ export async function coloPut(kind: string, key: string, value: unknown, ttlSec:
/* best-effort */
}
}
+
+// coloDelete drops an entry. Best-effort like the rest of this tier, with one
+// caller that genuinely needs it: a stale-while-revalidate refresh that learns
+// the underlying row is GONE (an API key revoked out of band). Letting that
+// entry age out on its own TTL would keep a revoked credential working for the
+// remainder of the stale window in this colo, which is the exact failure the
+// refresh exists to prevent — so the refresh evicts instead.
+export async function coloDelete(kind: string, key: string): Promise<void> {
+ const cache = cacheOrNull();
+ if (!cache) return;
+ try {
+ await cache.delete(BASE + kind + "/" + encodeURIComponent(key));
+ } catch {
+ /* best-effort */
+ }
+}
diff --git a/cloudflare-workers/api-edge/src/create_context_cache.ts b/cloudflare-workers/api-edge/src/create_context_cache.ts
index 0a6123bf..a5e58544 100644
--- a/cloudflare-workers/api-edge/src/create_context_cache.ts
+++ b/cloudflare-workers/api-edge/src/create_context_cache.ts
@@ -56,16 +56,52 @@ export interface OrgPolicy {
// Freshness windows. The TTL is how long a value is used outright; the STALE
// window is how long it may still gate a create while a refresh runs behind it.
-export const ORG_POLICY_TTL_MS = 5_000; // short: bounds is_halted / cap staleness
-export const ORG_STALE_MAX_MS = 60_000;
-export const CONCURRENCY_COUNT_TTL_MS = 1_500;
-export const CONCURRENCY_STALE_MAX_MS = 30_000;
-export const CELL_TTL_MS = 5_000;
+// 60s, not 5s. These three TTLs expire together, and D1.batch() is ONE round
+// trip — so the moment the shortest of them lapses, the create pays the full
+// read no matter how fresh the other two are. Measured under a burst-100 on
+// dev: ctxd1 245ms for a 3-statement batch against ctxcolo 14ms, i.e. the tier
+// that was supposed to absorb this was fast and EMPTY.
+//
+// Bounding is_halted staleness is still the job, and the stale-while-revalidate
+// window below (60s) has always been the real bound on that — this only changes
+// how long a value is used before a refresh is kicked off behind the response.
+//
+// WHY 60s AND NOT 15s. The three reads are single-flighted per isolate, so when
+// the context has expired ONE request runs the D1 batch and every other request
+// in the burst waits on it. That turns a single slow read into a fixed tax on
+// the whole burst: measured on dev at `ctx` 496ms on 18 of 20 requests with
+// `ctxn` = 3 on exactly one of them. It is what made burst-20 bimodal — 527ms
+// when the context was cached, 1.28s when it had just expired, with a spread of
+// only ~110ms INSIDE each run either way.
+//
+// The stale windows below (5 min) are what actually bound freshness; these
+// values only decide when a background refresh starts.
+export const ORG_POLICY_TTL_MS = 60_000;
+// 5 min, a DELIBERATE trade made 2026-08-26. This window is the bound on halt
+// latency: a stale-but-not-halted policy keeps gating creates while the refresh
+// runs behind it, so an org halted mid-window can keep creating for up to this
+// long. That was raised from 60s knowingly, in exchange for bursts never
+// blocking on the org read. Shorten it if halt enforcement ever needs to be
+// prompt again — it costs latency, not correctness.
+export const ORG_STALE_MAX_MS = 300_000;
+// 1.5s was deliberately shorter than a create→exec→destroy cycle, which meant
+// it expired BETWEEN benchmark-shaped creates by construction — every sequential
+// create dropped to the colo tier (or D1) for a number that had barely moved.
+// 5s matches ORG_POLICY_TTL_MS, is still a small fraction of the 30s stale
+// window the optimistic gate already relies on, and does not change the gate's
+// semantics: this is how long a count is used OUTRIGHT, and the cap has always
+// been approximate to ±CONCURRENCY_STALE_HEADROOM regardless.
+export const CONCURRENCY_COUNT_TTL_MS = 60_000;
+// Also 5 min, same trade. The cap has always been approximate to
+// ±CONCURRENCY_STALE_HEADROOM; this widens the window in which a fast creator
+// can overshoot it before the background refresh catches up.
+export const CONCURRENCY_STALE_MAX_MS = 300_000;
+export const CELL_TTL_MS = 60_000;
// See the isHealthy() interaction noted at the cells stale-serve branch in
// index.ts: reading capacity_updated_at from a ≤30s-stale snapshot stretches
// the effective 120s freshness window to ~150s, still ~5× the CP's ~30s
// capacity cadence.
-export const CELL_STALE_MAX_MS = 30_000;
+export const CELL_STALE_MAX_MS = 300_000;
export const ORG_POLICY_SQL =
"SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1";
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 39ad031b..94716256 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -22,14 +22,14 @@
export { CreditAccount } from "../../shared/credit_account";
// Shared with the vm-do worker's MicrovmSession: the same minimal HTTP/2 client,
// used here only by the dev-only direct-exec probe.
-import { H2Grpc, encodeExecRequest, decodeExecResponse } from "../../shared/h2grpc";
+import { H2Grpc, openTunnel, encodeExecRequest, decodeExecResponse } from "../../shared/h2grpc";
export { PoolStock } from "./pool_stock";
// VmSession (VM-DO exec data plane) lives in its own worker
// (cloudflare-workers/vm-do) and is bound cross-script via VM_SESSIONS —
// deliberately NOT exported here, so the edge's deploy cadence (every merge
// touching web/ or edge code) can't reset the DOs and sever the host-dialed
// VM WebSockets.
-import { coloGet, coloPut } from "./colo_cache";
+import { coloDelete, coloGet, coloPut } from "./colo_cache";
import {
ACTIVE_CELLS_SQL,
CELL_STALE_MAX_MS,
@@ -131,6 +131,25 @@ export interface Env extends DashboardEnv {
// origin round trips. EDGE_CLAIM="0" is the kill switch (default on).
POOL_STOCK: DurableObjectNamespace;
EDGE_CLAIM?: string;
+ // Which shard ids this environment uses, as a comma-separated list — e.g.
+ // "1,4,6,12" for the four-way prod set, or "1" for no sharding at all.
+ //
+ // This has to be per-environment because a shard id is not a number, it is
+ // half of a DO NAME (`${cellID}#${gen}#${id}`). The cell id is the other
+ // half, so the same id names a DIFFERENT object in every cell — and placement
+ // is a property of the object. The measured-into-IAD set below was probed
+ // against PROD's cell and carries no information whatsoever about where dev's
+ // objects of the same id landed. Sharing one hardcoded list across cells was
+ // silently asserting otherwise.
+ POOL_STOCK_SHARD_IDS?: string;
+ // "0" stops the edge answering MicroVM exec itself, handing it to the cell.
+ // Required for a cell whose boxes have no agent tunnel to dial — see the
+ // dispatch in proxyToCellSDK. Unset means the edge path, which is prod.
+ MICROVM_EDGE_EXEC?: string;
+ // "0" stops MicroVM creates attempting edge-claim. Required for a cell that
+ // keeps its warm set in process, where the stock DO can never be filled — see
+ // createSandbox. Unset means edge-claim, which is prod.
+ MICROVM_EDGE_CLAIM?: string;
// VM-DO exec data plane (vm_do_datapane_validation). One DO per sandbox holds a
// persistent host-dialed WebSocket to the QEMU worker; exec routes edge→DO→VM
// instead of tunnel→CP→worker, with automatic tunnel fallback when unconnected.
@@ -383,8 +402,23 @@ function stripApiKeyQueryParam(target: string): string {
// and throttle the last_used bump. Isolates recycle so entries are naturally
// bounded; CACHE_MAX guards pathological key cardinality.
const AUTH_TTL_MS = 60_000;
-// SWR window for org policy in the colo tier: a ≤60s-stale not-halted policy
-// may gate a create while a background refresh runs (see loadCreateContext).
+// SWR window for the auth entry, mirroring the org-policy and active-cells
+// gates in loadCreateContext. Auth was the LAST tier on the create path with no
+// stale-while-revalidate escape: every other cold miss serves a stale value and
+// refreshes behind the response, so a cold-isolate create still paid one
+// blocking D1 read — and it paid it FIRST, before the orgID is even known, so
+// it cannot be batched with the create-context reads. Measured on dev
+// 2026-08-25 (6 sequential creates): `auth` 26-49ms on the four cold isolates
+// while `ctx` was 7-9ms once its colo tier answered — auth was the larger of
+// the two, and for a worse reason.
+//
+// What this widens: revocation lag for a key deleted out of band goes from
+// AUTH_TTL_MS to AUTH_STALE_MAX_MS in the worst case — but only until the
+// background refresh lands (~one D1 read), because that refresh EVICTS both
+// tiers when the row is gone. Ordinary expiry is unaffected: expires_at travels
+// with the cached entry and is still checked inline on every request, stale or
+// not, so an expired key is rejected at the same instant it was before.
+const AUTH_STALE_MAX_MS = 600_000; // 10 min
const LAST_USED_BUMP_MS = 60_000; // at most once/min/key/isolate
const CACHE_MAX = 10_000;
@@ -469,7 +503,65 @@ function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number):
.catch(() => {});
}
-async function authenticate(req: Request, env: Env): Promise<Caller | null> {
+const AUTH_KEY_SQL = "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1";
+
+// In-flight auth refreshes, keyed by hash — same single-flight shape as
+// createContextInflight and for the same reason: a burst that all lands stale
+// would otherwise fire one D1 read per request, which is precisely the
+// stampede the cache tiers exist to prevent.
+const authRefreshInflight = new Map<string, Promise<void>>();
+
+// refreshAuth re-reads the key row and repopulates both cache tiers. It runs
+// BEHIND a response that was already served from a stale entry, so its latency
+// is off the hot path; what matters is that it is authoritative — including
+// when the row is gone, where it evicts rather than leaving a revoked key
+// working until its TTL expires.
+function refreshAuth(env: Env, hash: string): Promise<void> {
+ const inflight = authRefreshInflight.get(hash);
+ if (inflight) return inflight;
+ const p = (async () => {
+ try {
+ const row = await env.OPENCOMPUTER_DB.prepare(AUTH_KEY_SQL)
+ .bind(hash)
+ .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
+ if (!row) {
+ authCache.delete(hash);
+ await coloDelete("auth", hash);
+ return;
+ }
+ const at = Date.now();
+ const caller: Caller = { orgID: row.org_id, userID: row.created_by };
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ authCache.set(hash, {
+ caller,
+ expiresAt: row.expires_at,
+ cachedAtMs: at,
+ lastBumpMs: authCache.get(hash)?.lastBumpMs ?? 0,
+ });
+ await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: at }, AUTH_STALE_MAX_MS / 1000);
+ } catch {
+ // Keep serving the stale entry; the next request retries. Failing closed
+ // here would turn a transient D1 blip into a 401 storm.
+ } finally {
+ authRefreshInflight.delete(hash);
+ }
+ })();
+ authRefreshInflight.set(hash, p);
+ return p;
+}
+
+// Which tier answered auth, and what the slow parts cost. `auth` is one mark
+// over four possible paths (isolate, colo, stale, D1) and a 226ms reading does
+// not say which — the same ambiguity that made `ctx` unfixable until it was
+// split. tier: 0 isolate, 1 colo, 2 stale, 3 D1.
+export interface AuthProbe {
+ tier: number;
+ coloMs: number;
+ d1Ms: number;
+ hashMs: number;
+}
+
+async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {
const apiKey = apiKeyFromRequest(req);
if (!apiKey) return null;
// Act-as-org provisioning token (sessions-api): a signed JWT, not an osb_ key.
@@ -483,13 +575,16 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
) {
return verifyProvisionToken(env.OC_PROVISION_SECRET, apiKey);
}
+ const tHash = Date.now();
const hash = await hashAPIKey(apiKey);
+ if (probe) probe.hashMs = Date.now() - tHash;
const nowMs = Date.now();
const nowSec = Math.floor(nowMs / 1000);
const cached = authCache.get(hash);
if (cached && nowMs - cached.cachedAtMs < AUTH_TTL_MS) {
if (cached.expiresAt && cached.expiresAt < nowSec) return null;
+ if (probe) probe.tier = 0;
bumpLastUsed(env, hash, cached, nowMs);
return cached.caller;
}
@@ -497,8 +592,11 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
// Colo tier: a fresh box's sub-ops usually land on isolates that never saw
// this key. cachedAtMs travels with the entry so the total staleness bound
// (revocation lag) stays AUTH_TTL_MS, not colo-TTL + isolate-TTL stacked.
+ const tColo = Date.now();
const shared = await coloGet<{ caller: Caller; expiresAt: number | null; cachedAtMs: number }>("auth", hash);
+ if (probe) probe.coloMs = Date.now() - tColo;
if (shared && nowMs - shared.cachedAtMs < AUTH_TTL_MS) {
+ if (probe) probe.tier = 1;
if (shared.expiresAt && shared.expiresAt < nowSec) return null;
if (authCache.size >= CACHE_MAX) authCache.clear();
const entry: AuthEntry = { caller: shared.caller, expiresAt: shared.expiresAt, cachedAtMs: shared.cachedAtMs, lastBumpMs: 0 };
@@ -507,11 +605,41 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
return shared.caller;
}
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",
- )
+ // Stale-while-revalidate. Take the FRESHEST stale copy either tier holds —
+ // the isolate entry can outlive the colo entry or vice versa, and using the
+ // older of the two would shorten the window for no benefit. Serving it costs
+ // nothing; the refresh behind it is what keeps the entry honest.
+ const staleShared = shared && nowMs - shared.cachedAtMs < AUTH_STALE_MAX_MS ? shared : null;
+ const staleLocal = cached && nowMs - cached.cachedAtMs < AUTH_STALE_MAX_MS ? cached : null;
+ const stale =
+ staleShared && (!staleLocal || staleShared.cachedAtMs > staleLocal.cachedAtMs) ? staleShared : staleLocal;
+ if (stale) {
+ // Expiry is still enforced inline, exactly as on the fresh paths — the
+ // stale window widens revocation lag, never expiry.
+ if (stale.expiresAt && stale.expiresAt < nowSec) return null;
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ const entry: AuthEntry = {
+ caller: stale.caller,
+ expiresAt: stale.expiresAt,
+ cachedAtMs: stale.cachedAtMs,
+ lastBumpMs: cached?.lastBumpMs ?? 0,
+ };
+ authCache.set(hash, entry);
+ if (probe) probe.tier = 2;
+ const refresh = refreshAuth(env, hash);
+ if (ctx) ctx.waitUntil(refresh);
+ bumpLastUsed(env, hash, entry, nowMs);
+ return stale.caller;
+ }
+
+ const tD1 = Date.now();
+ const row = await env.OPENCOMPUTER_DB.prepare(AUTH_KEY_SQL)
.bind(hash)
.first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
+ if (probe) {
+ probe.tier = 3;
+ probe.d1Ms = Date.now() - tD1;
+ }
if (!row) return null; // never cache negatives — a freshly-created key must work at once
if (row.expires_at && row.expires_at < nowSec) return null;
@@ -519,7 +647,11 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
if (authCache.size >= CACHE_MAX) authCache.clear();
const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };
authCache.set(hash, entry);
- await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_TTL_MS / 1000);
+ // TTL is the STALE bound, not AUTH_TTL_MS: an entry that evaporates at 60s
+ // can never be stale-served, which would leave the SWR branch above reachable
+ // only from the isolate tier — i.e. never on the cross-isolate misses that
+ // are the whole reason the colo tier exists.
+ await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_STALE_MAX_MS / 1000);
bumpLastUsed(env, hash, entry, nowMs);
return caller;
}
@@ -567,12 +699,29 @@ type CreateContext = { org: OrgPolicy | null; activeCount: number; cells: CellRo
// in a finally so a rejection can't wedge every later create for that org.
const createContextInflight = new Map<string, Promise<CreateContext>>();
-function loadCreateContext(env: Env, orgID: string, ctx?: ExecutionContext): Promise<CreateContext> {
+// ctxProbe is filled in by the load below so the create handler can attribute
+// its `ctx` mark. `ctx` conflates three tiers — isolate map, colo cache, D1 —
+// and a 10.6s reading says nothing about WHICH, which is the only thing that
+// decides what to cut. Written, never read, by anything but telemetry.
+export interface CtxProbe {
+ coloMs: number;
+ d1Ms: number;
+ d1Stmts: number;
+ coalesced: boolean;
+}
+
+function loadCreateContext(env: Env, orgID: string, ctx?: ExecutionContext, probe?: CtxProbe): Promise<CreateContext> {
const inflight = createContextInflight.get(orgID);
- if (inflight) return inflight;
+ if (inflight) {
+ // Collapsed onto another request's read IN THIS ISOLATE. Distinguishing
+ // these matters: if a burst shows most requests coalesced and `ctx` is
+ // still large, the isolate fan-out is the problem, not the read.
+ if (probe) probe.coalesced = true;
+ return inflight;
+ }
const p = (async () => {
try {
- return await loadCreateContextUncoalesced(env, orgID, ctx);
+ return await loadCreateContextUncoalesced(env, orgID, ctx, probe);
} finally {
createContextInflight.delete(orgID);
}
@@ -585,6 +734,7 @@ async function loadCreateContextUncoalesced(
env: Env,
orgID: string,
ctx?: ExecutionContext,
+ probe?: CtxProbe,
): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {
const nowMs = Date.now();
const oc = orgPolicyCache.get(orgID);
@@ -608,11 +758,13 @@ async function loadCreateContextUncoalesced(
let staleCount: { count: number; cachedAtMs: number } | null =
cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_STALE_MAX_MS ? cc : null;
{
+ const tColo = Date.now();
const [so, sc, scl] = await Promise.all([
orgHave ? null : coloGet<{ policy: OrgPolicy | null; cachedAtMs: number }>("org", orgID),
cntHave ? null : coloGet<{ count: number; cachedAtMs: number }>("count", orgID),
cellsHave ? null : coloGet<{ cells: CellRow[]; cachedAtMs: number }>("cells", "active"),
]);
+ if (probe) probe.coloMs = Date.now() - tColo;
if (so && nowMs - so.cachedAtMs < ORG_POLICY_TTL_MS) {
org = so.policy;
orgHave = true;
@@ -685,15 +837,20 @@ async function loadCreateContextUncoalesced(
}
// Optimistic concurrency gate: the COUNT read is the last per-create D1
- // dependency once org+cells are cache-served (its 1.5s TTL is shorter than a
- // typical create→exec→destroy cycle, so it expires between benchmark-shaped
- // creates). When the org's policy is already known WITHOUT D1 and a stale
- // (≤30s) count sits comfortably below the limit, use the stale value and
- // refresh it in the background — the cap stays enforced within
- // CONCURRENCY_STALE_HEADROOM of the limit, matching the gate's existing
- // "index trails events, reads low under burst" approximate semantics. Near
- // the limit (or with nothing cached) the blocking read still happens.
- if (!cntHave && orgHave && staleCount) {
+ // dependency once org+cells are cache-served. When the org's policy is
+ // already known WITHOUT D1 and a stale (≤30s) count sits comfortably below
+ // the limit, use the stale value and refresh it in the background — the cap
+ // stays enforced within CONCURRENCY_STALE_HEADROOM of the limit, matching the
+ // gate's existing "index trails events, reads low under burst" approximate
+ // semantics. Near the limit the blocking read still happens.
+ //
+ // `orgHave` is deliberately NOT required any more. It was, and that coupling
+ // is what dragged this back onto D1 in exactly the case that hurts: a burst
+ // arriving on cold isolates has no org either, so the count joined the batch
+ // and every request paid the round trip. The org policy is fetched in that
+ // same batch, so by the time the limit is read below it is present regardless
+ // of which tier supplied it — waiting for it here bought nothing.
+ if (!cntHave && staleCount) {
const limit = org?.max_concurrent_sandboxes ?? DEFAULT_MAX_CONCURRENT_SANDBOXES;
if (staleCount.count + CONCURRENCY_STALE_HEADROOM <= limit) {
activeCount = staleCount.count;
@@ -745,7 +902,12 @@ async function loadCreateContextUncoalesced(
}
if (stmts.length > 0) {
+ const tD1 = Date.now();
const res = await env.OPENCOMPUTER_DB.batch(stmts);
+ if (probe) {
+ probe.d1Ms = Date.now() - tD1;
+ probe.d1Stmts = stmts.length;
+ }
const puts: Promise<void>[] = [];
for (let i = 0; i < kinds.length; i++) {
if (kinds[i] === "org") {
@@ -772,19 +934,75 @@ async function loadCreateContextUncoalesced(
return { org, activeCount, cells };
}
+const CELL_ROW_SQL =
+ `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at
+ FROM cells WHERE cell_id = ?1`;
+
+// In-flight row reads, keyed by cell. Same single-flight shape as
+// createContextInflight and authRefreshInflight, for the same reason.
+const cellRowInflight = new Map<string, Promise<CellRow | null>>();
+
+function readCellRow(env: Env, cellID: string): Promise<CellRow | null> {
+ const inflight = cellRowInflight.get(cellID);
+ if (inflight) return inflight;
+ const p = (async () => {
+ try {
+ const cell = await env.OPENCOMPUTER_DB.prepare(CELL_ROW_SQL).bind(cellID).first<CellRow>();
+ const at = Date.now();
+ if (cellCache.size >= CACHE_MAX) cellCache.clear();
+ cellCache.set(cellID, { cell, cachedAtMs: at });
+ // Only a real row goes to the shared tier. Caching a null would let one
+ // failed read blind every isolate in the colo to a live cell.
+ if (cell) await coloPut("cell", cellID, { cell, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000);
+ return cell;
+ } finally {
+ cellRowInflight.delete(cellID);
+ }
+ })();
+ cellRowInflight.set(cellID, p);
+ return p;
+}
+
+// lookupCell resolves one cell's row, through the same three tiers every other
+// hot read uses: isolate map, colo cache, then D1.
+//
+// It had ONLY the isolate map, and that was the largest remaining blocking read
+// on the exec path. A burst arrives on isolates that have never seen this cell,
+// so each one went straight to D1 for a row that changes almost never —
+// measured at `cell;dur=327` per exec across a burst-100, against `route;dur=9`
+// for the sandbox lookup right beside it that does have the tiers.
+//
+// SERVING STALE IS SAFE HERE, including for placement. The volatile fields are
+// available_workers and capacity_updated_at, and isHealthy() rejects a row whose
+// capacity_updated_at has aged past CAPACITY_FRESH_SEC — so an old row can only
+// ever make a cell look UNhealthy and be skipped. It cannot make a dead cell
+// look alive, which is the direction that would hurt.
async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {
const nowMs = Date.now();
const c = cellCache.get(cellID);
if (c && nowMs - c.cachedAtMs < CELL_TTL_MS) return c.cell;
- const cell = await env.OPENCOMPUTER_DB.prepare(
- `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at
- FROM cells WHERE cell_id = ?1`,
- )
- .bind(cellID)
- .first<CellRow>();
- if (cellCache.size >= CACHE_MAX) cellCache.clear();
- cellCache.set(cellID, { cell, cachedAtMs: nowMs });
- return cell;
+
+ const shared = await coloGet<{ cell: CellRow; cachedAtMs: number }>("cell", cellID);
+ if (shared && nowMs - shared.cachedAtMs < CELL_TTL_MS) {
+ if (cellCache.size >= CACHE_MAX) cellCache.clear();
+ cellCache.set(cellID, { cell: shared.cell, cachedAtMs: shared.cachedAtMs });
+ return shared.cell;
+ }
+
+ // Stale-while-revalidate. Take the fresher of the two stale copies; either
+ // tier can outlive the other.
+ const staleShared = shared && nowMs - shared.cachedAtMs < CELL_STALE_MAX_MS ? shared : null;
+ const staleLocal = c && c.cell && nowMs - c.cachedAtMs < CELL_STALE_MAX_MS ? c : null;
+ const stale =
+ staleShared && (!staleLocal || staleShared.cachedAtMs > staleLocal.cachedAtMs)
+ ? { cell: staleShared.cell, cachedAtMs: staleShared.cachedAtMs }
+ : staleLocal;
+ if (stale && stale.cell) {
+ readCellRow(env, cellID).catch(() => {}); // refresh behind the response
+ return stale.cell;
+ }
+
+ return readCellRow(env, cellID);
}
// Freshness window — the CP emits capacity events every ~30s; 120s is a
@@ -1293,18 +1511,88 @@ function indexSandboxFromSSE(
// special about these indices; they are simply the ones that landed where we
// want, which is the entire idea.
const POOL_STOCK_SHARD_GEN = "g5";
-const POOL_STOCK_SHARD_IDS = [1, 4, 6, 12, 13, 14, 16, 17];
-const POOL_STOCK_SHARDS = POOL_STOCK_SHARD_IDS.length;
+// SHARD COUNT IS A FUNCTION OF POOL SIZE, not a free parameter. The sizing
+// invariant (pool_stock.ts) is SHARDS × TARGET_STOCK ≤ the cell pool, and it
+// binds from BOTH sides: too many shards against a small pool and every shard
+// sits at 0, so claims miss the DO and pay the control-plane fallback instead.
+// Measured on a 10-box dev pool with all eight shards at TARGET_STOCK=1:
+// stock p50=0, 4 of 10 creates took `claimmiss` at 859ms, and the burst median
+// went 886ms → 1.70s versus the same code on a 130-box pool.
+//
+// So take a PREFIX of the measured set rather than inventing indices — these are
+// the ones probed into the right colo, and a prefix keeps that property. Four
+// shards × TARGET_STOCK=2 = 8, inside a 10-box pool with headroom to spare.
+// Restore the full eight when the cell pool goes back above ~128.
+const POOL_STOCK_SHARD_IDS_ALL = [1, 4, 6, 12, 13, 14, 16, 17];
+const POOL_STOCK_SHARD_IDS_DEFAULT = POOL_STOCK_SHARD_IDS_ALL.slice(0, 4);
// How many candidate names the probe route sweeps. Only the ones that report
-// the target colo get promoted into POOL_STOCK_SHARD_IDS above.
+// the target colo get promoted into the shard list.
const POOL_STOCK_CANDIDATES = 64;
+// Resolved once per isolate. The value cannot change under a running isolate —
+// it comes from a binding, and a binding change means a redeploy, which means a
+// new isolate.
+let poolStockShardIdsCache: number[] | null = null;
+
+/**
+ * poolStockShardIds is the ordered list of shard ids this environment uses.
+ *
+ * SHARDING IS A THROUGHPUT TOOL AND IT IS NOT FREE. A shard is a separate
+ * single-threaded Durable Object, so N shards give N concurrent claims — but
+ * they also FRAGMENT the pool N ways, and a claim that lands on an empty shard
+ * pays a full DO round trip to learn nothing. Measured on dev 2026-08-25: a
+ * `claimmiss` cost 300-320ms at 4 shards against 84-98ms at 1, and even a
+ * successful claim cost ~150ms at dotry=2 versus ~88ms at dotry=1.
+ *
+ * The break-even is the sizing invariant (pool_stock.ts): SHARDS × TARGET_STOCK
+ * must be ≤ the cell's real pool. Below that line every extra shard is pure
+ * cost, because there is no concurrency to win — there are not enough boxes to
+ * keep one shard busy, let alone four. A single shard is therefore the correct
+ * configuration for a small pool, not a degraded one, and "1" here is a
+ * first-class setting rather than an emergency fallback.
+ *
+ * Above the line, add shards — but only ids that have been PROBED into the
+ * target colo for THAT CELL (see the gen note above). Never promote an id
+ * nobody has measured: it is a coin flip across five colos.
+ */
+function poolStockShardIds(env: Env): number[] {
+ if (poolStockShardIdsCache) return poolStockShardIdsCache;
+ const raw = (env.POOL_STOCK_SHARD_IDS ?? "").trim();
+ let ids = raw
+ .split(",")
+ .map((s) => Number.parseInt(s.trim(), 10))
+ .filter((n) => Number.isInteger(n) && n >= 0);
+ if (ids.length === 0) {
+ if (raw !== "") {
+ // Loud, because silently serving the prod-measured set to a cell it was
+ // never measured against is precisely the failure this binding exists to
+ // stop.
+ console.error(`pool-stock: POOL_STOCK_SHARD_IDS=${JSON.stringify(raw)} parsed to nothing — falling back to the default set`);
+ }
+ ids = POOL_STOCK_SHARD_IDS_DEFAULT;
+ }
+ poolStockShardIdsCache = ids;
+ return ids;
+}
+
function poolStockShardName(cellID: string, id: number): string {
return `${cellID}#${POOL_STOCK_SHARD_GEN}#${id}`;
}
+/**
+ * poolStockStub resolves a shard INDEX (0..shards-1) to its Durable Object.
+ *
+ * Index, never id. The two were conflated in runPoolKeepWarm, which mapped over
+ * the ID list and passed each id in here as though it were an index: with ids
+ * [1,4,6,12] the keep-warm touched {4,4,6,12}, hitting shard 4 twice and NEVER
+ * touching shard 1. That shard idle-decommissioned its stock after 30 minutes
+ * and its alarm lapsed after 6 hours, so it could not restock proactively and
+ * only ever re-armed on a claim that had already missed. One shard in four was
+ * structurally cold, and 1-in-4 claims paid a miss to discover it.
+ */
function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStub {
- const name = poolStockShardName(cellID, POOL_STOCK_SHARD_IDS[shard] ?? shard);
+ const ids = poolStockShardIds(env);
+ const name = poolStockShardName(cellID, ids[shard] ?? shard);
// Deterministic placement hint: pin the stock DO to eastern North America
// (covers eastus2 / the IAD leaderboard runner) so a claim never eats a
// cross-colo hop even if the first touch comes from an off-metro edge. A
@@ -1354,43 +1642,111 @@ interface PoolBox {
// stocked — the steady state, since each targets POOL_STOCK_TARGET — the first
// call hits and a create costs exactly one DO round trip. The walk below is the
// uneven-drain path, not the common one.
+// Per-shard stock hints, keyed by INDEX into POOL_STOCK_SHARD_IDS.
+//
+// Every claim response already reports how much stock the serving shard had
+// left, and until now the edge stamped it into server-timing and threw it away.
+// That is the exact information needed to stop walking into empty shards, and
+// it arrives for free on a response we are already waiting for — no extra round
+// trip, no extra storage, no extra subrequest.
+//
+// Why it matters: sharding fragments the pool N ways, so under burst some
+// shards are EMPTY BY CONSTRUCTION, and a claim that lands on one pays a full
+// Durable Object round trip to learn nothing. Measured on dev 2026-08-25:
+// `claimmiss` (all shards walked, none stocked) cost 300-320ms at 4 shards and
+// 84-98ms at 1, and even a successful claim cost ~150ms at dotry=2 against
+// ~88ms at dotry=1. The tax is one hop per empty shard, and it is paid on the
+// customer's create.
+//
+// Isolate-local on purpose. A colo-shared copy would help more isolates but
+// costs a Cache API read on the hot path, which is the thing this exists to
+// avoid; a burst lands on many isolates and each learns within its first claim.
+const poolStockHints = new Map<number, { stock: number; atMs: number }>();
+// Hints go stale fast because the control plane is actively restocking. Long
+// enough to steer the shards of one burst, short enough that a shard which has
+// just been refilled is not avoided. Being wrong only costs the walk we would
+// have done anyway — a stale "empty" shard is tried LAST, never skipped.
+const STOCK_HINT_TTL_MS = 1_500;
+
+function noteShardStock(shard: number, stock: number): void {
+ poolStockHints.set(shard, { stock, atMs: Date.now() });
+}
+
+// poolStockWalkOrder returns every shard index, ordered so ones believed to
+// hold stock come first. It never DROPS a shard: full coverage is what fixed
+// the earlier 3-attempt walk, where 56 of 100 concurrent creates fell through
+// to a cold control-plane launch while the shards still held 22-81 boxes.
+// Believed-empty shards are demoted, not excluded.
+//
+// Both groups are shuffled rather than sorted by stock. Sorting would send
+// every isolate in a burst to the same "best" shard and serialize them against
+// one single-threaded object — recreating, at the head of the walk, exactly the
+// contention sharding exists to spread.
+// With a single shard this collapses to [0] and every branch below is dead —
+// no hint bookkeeping, no shuffle, no walk. That is the point: at one shard
+// `dotry` is always 1 and a `claimmiss` means the pool is genuinely empty
+// rather than that we guessed the wrong object.
+function poolStockWalkOrder(shards: number): number[] {
+ if (shards <= 1) return [0];
+ const now = Date.now();
+ const likely: number[] = [];
+ const unlikely: number[] = [];
+ for (let i = 0; i < shards; i++) {
+ const h = poolStockHints.get(i);
+ // Unknown counts as likely: never having asked is not evidence of empty.
+ if (h && now - h.atMs < STOCK_HINT_TTL_MS && h.stock <= 0) unlikely.push(i);
+ else likely.push(i);
+ }
+ for (const g of [likely, unlikely]) {
+ for (let i = g.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [g[i], g[j]] = [g[j], g[i]];
+ }
+ }
+ return likely.concat(unlikely);
+}
+
async function claimPoolBox(
env: Env,
cell: CellRow,
orgID: string,
-): Promise<{ box: PoolBox; stock: number; doMs: number; doColo: string } | null> {
+): Promise<{ box: PoolBox; stock: number; doMs: number; doColo: string; attempts: number } | null> {
const body = JSON.stringify({
cell: { cellID: cell.cell_id, baseURL: cell.base_url },
orgID,
count: 1,
});
- let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);
- // Odd stride only, so the walk is a full cycle of the 8 shards rather than a
- // sub-orbit. An even stride shares a factor with POOL_STOCK_SHARDS and can
- // only ever reach half of them (stride 2 visits 4, stride 4 visits 2), so a
- // create could exhaust its attempts against shards that are empty while the
- // ones holding stock were unreachable by construction.
- const stride = 1 + 2 * Math.floor(Math.random() * (POOL_STOCK_SHARDS / 2));
- // Walk every shard before giving up. Measured on dev: with a 3-attempt walk,
- // 56 of 100 concurrent creates fell through to the control plane while the
- // shards still held 22-81 boxes. Falling back to a cold MicroVM launch while
- // warm stock is sitting one shard away is the expensive mistake here: those
- // creates then serialize behind the RunMicrovm 5/s quota, which is what turns
- // a burst into a 25s tail.
- for (let attempt = 0; attempt < POOL_STOCK_SHARDS; attempt++) {
+ const order = poolStockWalkOrder(poolStockShardIds(env).length);
+ for (let attempt = 0; attempt < order.length; attempt++) {
+ const shard = order[attempt];
try {
const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
method: "POST",
body,
});
- shard = (shard + stride) % POOL_STOCK_SHARDS;
- if (!r.ok) continue;
+ if (!r.ok) {
+ noteShardStock(shard, 0);
+ continue;
+ }
const data = (await r.json()) as { boxes?: PoolBox[]; stock?: number; t?: number; colo?: string };
+ // Record what the shard reported BEFORE deciding, so a shard that handed
+ // out its last box is remembered as empty for the next create.
+ noteShardStock(shard, data.stock ?? 0);
const b = data.boxes?.[0];
if (!b) continue;
- return { box: b, stock: data.stock ?? -1, doMs: data.t ?? -1, doColo: data.colo ?? "?" };
+ // attempts is 1-based: how many shards this claim had to touch to find a
+ // box. Every miss above is a FULL round trip to a DO, so this is the only
+ // way to tell an expensive hop from several cheap ones — `claim` alone
+ // cannot distinguish "one slow shard" from "four empty shards".
+ return {
+ box: b,
+ stock: data.stock ?? -1,
+ doMs: data.t ?? -1,
+ doColo: data.colo ?? "?",
+ attempts: attempt + 1,
+ };
} catch {
- shard = (shard + stride) % POOL_STOCK_SHARDS;
+ noteShardStock(shard, 0);
}
}
return null;
@@ -1427,7 +1783,10 @@ async function runPoolKeepWarm(env: Env): Promise<void> {
let failed = 0;
await Promise.all(
cells.flatMap((cell) =>
- POOL_STOCK_SHARD_IDS.map(async (shard) => {
+ // Map over INDICES, not ids — poolStockStub takes an index. Mapping over
+ // the id list here is the bug described in poolStockStub's docstring: it
+ // left one live shard permanently un-warmed.
+ poolStockShardIds(env).map(async (_id, shard) => {
try {
const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/touch", {
method: "POST",
@@ -1553,14 +1912,36 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
phases.push(`${name};dur=${t - tPrev}`);
tPrev = t;
};
- const caller = await authenticate(req, env);
+ const authProbe: AuthProbe = { tier: 0, coloMs: 0, d1Ms: 0, hashMs: 0 };
+ const caller = await authenticate(req, env, ctx, authProbe);
mark("auth");
+ // `autht` is a TIER, not a duration — 0 isolate, 1 colo, 2 stale, 3 D1.
+ // Which colo served this request. A miss in the colo-shared Cache API tier has
+ // two very different causes — the cache is not holding, or the burst is spread
+ // across colos so each one is legitimately cold — and they need opposite
+ // fixes. `desc` is a colo code, not a duration.
+ phases.push(`colo;desc=${req.headers.get("cf-ray")?.split("-")[1] ?? "?"}`);
+ phases.push(
+ `autht;dur=${authProbe.tier}`,
+ `authcolo;dur=${authProbe.coloMs}`,
+ `authd1;dur=${authProbe.d1Ms}`,
+ `authhash;dur=${authProbe.hashMs}`,
+ );
if (!caller) return json({ error: "missing or invalid API key" }, 401);
// One batched D1 round-trip for org + running-count + active-cells (was three
// serial reads on the create hot path). Cache-aware: warm isolates skip D1.
- const { org, activeCount, cells } = await loadCreateContext(env, caller.orgID, ctx);
+ const ctxProbe: CtxProbe = { coloMs: 0, d1Ms: 0, d1Stmts: 0, coalesced: false };
+ const { org, activeCount, cells } = await loadCreateContext(env, caller.orgID, ctx, ctxProbe);
mark("ctx");
+ // Which tier `ctx` actually spent its time in. `ctxn` is a statement COUNT,
+ // not a duration; Server-Timing has nowhere else to put it.
+ phases.push(
+ `ctxcolo;dur=${ctxProbe.coloMs}`,
+ `ctxd1;dur=${ctxProbe.d1Ms}`,
+ `ctxn;dur=${ctxProbe.d1Stmts}`,
+ `ctxco;dur=${ctxProbe.coalesced ? 1 : 0}`,
+ );
if (!org) return json({ error: "org not found" }, 401);
const plan = org.plan === "pro" ? "pro" : "free";
@@ -1648,7 +2029,23 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// need it (finalizeEdgeClaim mints its own off the response path), and the
// HMAC sign was one of the larger CPU items driving isolate queueing at
// burst-100. The CP-fallback path mints it below, after a miss.
- if (env.EDGE_CLAIM !== "0" && env.POOL_STOCK && edgeClaimEligible(bodyText, parsedBody)) {
+ // MICROVM_EDGE_CLAIM=0 skips edge-claim for MicroVM orgs specifically.
+ //
+ // Edge-claim reserves boxes from the cell's pool through PoolStock. A cell
+ // running the direct-exec backend has no such pool — it keeps its warm set in
+ // process and does not implement EdgeReserve at all — so the DO can never hold
+ // stock for it. Every create then walks the shards, misses, and pays a CP
+ // round trip anyway: measured on dev at 81-87ms of `claimmiss` on EVERY
+ // create, for an outcome that was not merely unlikely but structurally
+ // impossible.
+ //
+ // Scoped to the runtime rather than reusing EDGE_CLAIM=0, which is global. A
+ // cell can serve both runtimes, and switching one cell's MicroVM data plane
+ // must not turn off edge-claim for the QEMU orgs sharing it.
+ const edgeClaimOn =
+ env.EDGE_CLAIM !== "0" &&
+ !(org.runtime === RUNTIME_MICROVM && env.MICROVM_EDGE_CLAIM === "0");
+ if (edgeClaimOn && env.POOL_STOCK && edgeClaimEligible(bodyText, parsedBody)) {
try {
// Sharded stock (see pool_stock.ts): a single DO serializes burst claims
// (~2ms each → ~90ms queue tail at 100-way), so claims spread across
@@ -1671,6 +2068,8 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// so the remainder is the hop — see claimBatch. `doclo` is a colo name,
// not a duration; Server-Timing has nowhere else to put it.
phases.push(`doin;dur=${claimed.doMs}`, `doclo;desc=${claimed.doColo}`);
+ // Shards touched, as a count not a duration. See claimPoolBox.
+ phases.push(`dotry;dur=${claimed.attempts}`);
const token = box.token;
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });
@@ -1975,6 +2374,35 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
return json({ ...sandboxRowToJSON(row), cellEndpoint: cell ? cell.base_url : null });
}
+/**
+ * Why an exec fell back to the tunnel.
+ *
+ * Both fast paths degrade to `return null`, and the dispatcher then labels the
+ * result `path;desc=tunnel` — which says a fallback happened but not which of
+ * the six exits took it. Under burst that share went 30% → 60% and there was no
+ * way to tell a DO that reported no channel from a DO that was never asked, a
+ * reach cache miss from a dial that threw. Each has a different fix.
+ *
+ * The DO already puts its reason on the wire ("channel unavailable: …") and the
+ * edge was discarding the body along with the status. This carries it out.
+ */
+// `why` is the FIRST thing that degraded (the DO, normally). `dial` is the
+// direct-dial leg's own outcome, kept separate because on the MicroVM path the
+// two are sequential: the DO declining is what makes the dial happen at all, so
+// collapsing them would hide whichever one is actually fixable.
+type Fallback = { why?: string; dial?: string };
+
+// Records the reason and returns null, so every degrade site stays a one-liner.
+// First writer wins: the outermost exit is the one that decided.
+function fallback(f: Fallback | undefined, why: string): null {
+ if (f && f.why === undefined) f.why = why;
+ return null;
+}
+
+// server-timing `desc` is a token: commas end the mark and spaces end the value,
+// so an un-sanitized exception message would corrupt every mark after it.
+const descSafe = (s: string): string => s.replace(/[^\w.:/-]+/g, "_").slice(0, 80);
+
// tryVmDoExec routes POST /:id/exec/run-async through the sandbox's VmSession
// Durable Object (the VM-DO exec data plane, vm_do_datapane_validation) instead
// of the tunnel→CP→worker chain. Returns a Response when the DO handled it (a
@@ -1985,8 +2413,8 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
// short-circuits without polling — one edge→DO→host→agent hop. Authz mirrors
// proxyToCellSDK exactly (same route lookup + org-ownership check) so the DO
// path can't be used to exec on another org's sandbox. See vm_session.ts.
-async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0): Promise<Response | null> {
- if (!env.VM_SESSIONS) return null; // binding absent mid-cutover → tunnel
+async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, fall?: Fallback): Promise<Response | null> {
+ if (!env.VM_SESSIONS) return fallback(fall, "no-binding"); // binding absent mid-cutover → tunnel
// MicroVM-backed orgs never have a live VmSession: the host dialer that opens
// the channel is a QEMU-worker component (internal/worker/dodialer.go), and a
// MicroVM box has no worker behind it. So the DO can only ever answer "not
@@ -1998,7 +2426,25 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
const tPol = Date.now();
const orgPolicy = await loadOrgPolicy(env, caller.orgID, ctx);
const polMs = Date.now() - tPol;
- if (orgPolicy?.runtime === RUNTIME_MICROVM) return tryMicrovmDirectExec(req, env, ctx, caller, id, authMs, polMs);
+ if (orgPolicy?.runtime === RUNTIME_MICROVM) {
+ // MICROVM_EDGE_EXEC=0 hands exec to the cell, skipping BOTH Durable
+ // Objects.
+ //
+ // Every edge-side fast path reaches the box by dialing its AGENT TUNNEL,
+ // which is what a session DO holds. A cell running the direct-exec backend
+ // has no tunnel in its story at all: it answers exec with one plain HTTPS
+ // POST, and its boxes are reachable no other way. Serving exec here would
+ // route around the very path such a cell exists to measure — silently,
+ // while still returning correct results, which is exactly how the first dev
+ // run produced a 3s exec with no trace of it in the cell's logs.
+ //
+ // It must return rather than fall through: below this line is the VmSession
+ // DO, whose 400ms entry grace is the cost the MicroVM branch was added to
+ // skip in the first place. Falling through measured 830ms of vmdo to be
+ // told `vm_not_connected` by a DO that could never have been connected.
+ if (env.MICROVM_EDGE_EXEC === "0") return fallback(fall, "cell-owns-exec");
+ return tryMicrovmDirectExec(req, env, ctx, caller, id, authMs, polMs, fall);
+ }
const tRoute = Date.now();
const route = await resolveSandboxRoute(env, id);
const routeMs = Date.now() - tRoute;
@@ -2035,8 +2481,8 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
},
});
}
- console.log(`vmdo-exec ${id}: DO rpc not-connected — tunnel fallback`);
- return null;
+ console.log(`vmdo-exec ${id}: DO rpc not-connected (${res.error}) — tunnel fallback`);
+ return fallback(fall, `vmdo-rpc:${descSafe(res.error)}`);
}
const doResp = await stub.fetch("https://do/exec?sid=" + id, {
method: "POST",
@@ -2058,10 +2504,11 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
});
}
console.log(`vmdo-exec ${id}: DO ${doResp.status} — tunnel fallback`);
- } catch {
+ return fallback(fall, `vmdo-status:${doResp.status}`);
+ } catch (e) {
// DO unreachable — fall through to the tunnel.
+ return fallback(fall, `vmdo-throw:${descSafe(String(e))}`);
}
- return null;
}
/**
@@ -2092,7 +2539,7 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
* SCOPE: one-shot Exec only. Streaming, PTY and file transfer stay on the
* control-plane path via the null return.
*/
-async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, polMs = 0): Promise<Response | null> {
+async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, polMs = 0, fall?: Fallback): Promise<Response | null> {
const tRoute = Date.now();
const route = await resolveSandboxRoute(env, id);
const routeMs = Date.now() - tRoute;
@@ -2111,7 +2558,7 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex
// what the control plane does for this backend rather than word-splitting
// here, where quoting and redirection would be silently mangled.
const cmd = typeof body.cmd === "string" ? body.cmd : typeof body.command === "string" ? body.command : "";
- if (!cmd) return null;
+ if (!cmd) return fallback(fall, "no-cmd");
// Two request shapes reach this endpoint and only one used to be handled.
//
// string form: {cmd: "echo hi"} — cmd IS the shell line
@@ -2158,6 +2605,20 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex
.map((kv) => kv.split("="))
.filter((kv) => kv.length === 2),
) as Record<string, string>;
+ // Split mvmdo three ways using the DO's absolute enter/exit stamps.
+ // mvmdo alone conflates the hop out, time spent QUEUED outside the DO's
+ // handler (a Durable Object runs one invocation at a time, so a keepalive
+ // alarm mid-ping blocks an arriving exec), the handler itself, and the
+ // hop back — and those have entirely different fixes. Measured on dev
+ // 2026-08-25: mvmdo 1098ms against dinside 56ms, with ddial only 42ms,
+ // i.e. a full second was outside everything the DO could see.
+ //
+ // Emitted only when the DO supplied both stamps, so an older vm-do
+ // deployment degrades to the previous header rather than to "0".
+ const dEnter = Number(t.enter);
+ const dExit = Number(t.exit);
+ const haveSpan = Number.isFinite(dEnter) && Number.isFinite(dExit) && dEnter > 0;
+ const span = haveSpan ? `, dto;dur=${dEnter - tDo}, dback;dur=${Date.now() - dExit}` : "";
return new Response(dr.body, {
status: 200,
headers: {
@@ -2165,14 +2626,22 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex
"server-timing":
`auth;dur=${authMs}, pol;dur=${polMs}, mvmdo;dur=${doMs}, ` +
`dlive;dur=${t.live ?? -1}, dcold;dur=${t.cold ?? -1}, ddial;dur=${t.dial ?? -1}, ` +
- `dunary;dur=${t.unary ?? -1}, dinside;dur=${t.inside ?? -1}, ` +
+ `dunary;dur=${t.unary ?? -1}, dinside;dur=${t.inside ?? -1}${span}, ` +
`dcolo;desc=${dr.headers.get("x-mvm-colo") ?? "?"}`,
},
});
}
- } catch {
+ // Not 200. The DO puts the reason in the body ("channel unavailable: …",
+ // "exec failed: …") and this used to discard it along with the status,
+ // which is why a 60%-tunnel burst was unattributable. Reading the body
+ // costs nothing here: we are already on the slow branch.
+ fallback(fall, `do:${dr.status}:${descSafe(((await dr.json().catch(() => ({}))) as { error?: string }).error ?? "")}`);
+ } catch (e) {
/* DO unreachable — the direct dial below is the fallback */
+ fallback(fall, `do-throw:${descSafe(String(e))}`);
}
+ } else {
+ fallback(fall, "no-mvm-binding");
}
const tReach = Date.now();
@@ -2189,7 +2658,10 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex
// westus2) but self-healing, because we cache what it returns.
reach = await fetchMvmReach(env, caller, route.cellID, id);
reachFromCell = true;
- if (!reach) return null; // not a MicroVM box, or the cell won't say — tunnel
+ if (!reach) {
+ if (fall) fall.dial = "reach-null";
+ return fallback(fall, "reach-null"); // not a MicroVM box, or the cell won't say — tunnel
+ }
}
const reachMs = Date.now() - tReach;
@@ -2236,7 +2708,8 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex
// tunnel still works. Logged rather than distinguished, because a path that
// silently degrades is worse than one that is loudly slow.
console.log(`microvm-direct-exec ${id}: ${e} — tunnel fallback`);
- return null;
+ if (fall) fall.dial = descSafe(String(e));
+ return fallback(fall, `dial:${descSafe(String(e))}`);
}
}
@@ -2276,22 +2749,32 @@ let lastReadyMs = 0;
* `ready` is the guest's first SETTINGS frame, which the AWS proxy cannot
* produce until it has connected to the guest port. A slow dial is one or the
* other, never both, and knowing which is the whole diagnosis.
+ *
+ * Both budgets are sized for a box that has SUSPENDED rather than a healthy one.
+ * AWS suspends a MicroVM after its idle window, and with auto-resume on the next
+ * inbound request through the proxy wakes it — Lambda holding the request for the
+ * length of a snapshot restore, which is longer than the 5s/8s this used to
+ * allow. Cutting it short there does not fail fast, it aborts our own resume and
+ * leaves the box suspended for the next caller to fail against as well. A healthy
+ * box finishes both legs in tens of milliseconds and never approaches these.
*/
+const DIAL_HANDSHAKE_MS = 20_000;
+const DIAL_READY_MS = 20_000;
+
async function dialAgent(r: MvmReach): Promise<H2Grpc> {
const host = r.endpoint.replace(/^https?:\/\//, "").split("/")[0];
const tUp = Date.now();
- const up = await fetch(`https://${host}/osb/agent-grpc`, {
- signal: AbortSignal.timeout(5000),
- headers: {
- Upgrade: "websocket",
- "X-aws-proxy-auth": r.token,
- "X-aws-proxy-port": String(r.port),
- },
- });
- const ws = (up as unknown as { webSocket: WebSocket | null }).webSocket;
- if (!ws) throw new Error(`agent tunnel upgrade failed (http ${up.status})`);
+ // openTunnel, not fetch+AbortSignal.timeout — the latter kills the tunnel N ms
+ // after the DIAL, not after the handshake, so warmEdgeTunnel's whole purpose
+ // (hold a live connection from create until the customer's first exec) was
+ // being undone 5s later, every time. See openTunnel's docstring for the
+ // measurement.
+ const { ws } = await openTunnel(
+ `https://${host}/osb/agent-grpc`,
+ { "X-aws-proxy-auth": r.token, "X-aws-proxy-port": String(r.port) },
+ DIAL_HANDSHAKE_MS,
+ );
lastUpgradeMs = Date.now() - tUp;
- ws.accept();
const tReady = Date.now();
const conn = new H2Grpc(ws, host);
// Wait for the GUEST, not just the AWS proxy: the 101 comes from the proxy,
@@ -2299,7 +2782,7 @@ async function dialAgent(r: MvmReach): Promise<H2Grpc> {
// frame is the first proof the agent is actually there.
await Promise.race([
conn.ready,
- new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), 8000)),
+ new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), DIAL_READY_MS)),
]);
lastReadyMs = Date.now() - tReady;
return conn;
@@ -2385,7 +2868,49 @@ async function directExecProbe(req: Request, env: Env, id: string): Promise<Resp
},
});
const ws = (up as unknown as { webSocket: WebSocket | null }).webSocket;
- if (!ws) return json({ error: `tunnel upgrade failed (${up.status})` }, 502);
+ // Report WHICH endpoint+port the upgrade was attempted against. A 502 from
+ // Lambda's proxy means "nothing is listening on the declared port of that
+ // microVM", and the two ways to get there — wrong port, or an endpoint that
+ // no longer belongs to a live box — are indistinguishable from the status
+ // alone. The token is only fingerprinted; it is a bearer credential.
+ if (!ws) {
+ // Same endpoint, same token, same colo — but an ORDINARY GET instead of
+ // an upgrade. /healthz is served by microvm-hooks on the declared port
+ // (cmd/microvm-hooks/main.go), so a 200 here proves the credential, the
+ // endpoint and the network path are all fine and isolates the failure to
+ // the WebSocket upgrade itself. A matching 502 means the box is simply
+ // not reachable and the upgrade is incidental.
+ let plain = "";
+ try {
+ const hz = await fetch(`https://${host}/healthz`, {
+ signal: AbortSignal.timeout(5000),
+ headers: { "X-aws-proxy-auth": info.token, "X-aws-proxy-port": String(info.port) },
+ });
+ plain = `${hz.status}: ${(await hz.text()).slice(0, 200)}`;
+ } catch (e) {
+ plain = `threw: ${e}`;
+ }
+ // Same GET with NO credential at all. AWS answers 403 to an unauthenticated
+ // caller (verified from outside), so a 403 here proves this Worker reaches
+ // AWS and the fault is ours; a 502 proves the subrequest never got there.
+ let noAuth = "";
+ try {
+ const na = await fetch(`https://${host}/healthz`, { signal: AbortSignal.timeout(5000) });
+ noAuth = `${na.status}: ${(await na.text()).slice(0, 120)}`;
+ } catch (e) {
+ noAuth = `threw: ${e}`;
+ }
+ return json({
+ error: `tunnel upgrade failed (${up.status})`,
+ upgradeBody: (await up.text().catch(() => "")).slice(0, 200),
+ healthzSameTokenSameEndpoint: plain,
+ healthzNoCredential: noAuth,
+ endpoint: host,
+ port: info.port,
+ path: info.path ?? "/osb/agent-grpc",
+ tokenLen: info.token?.length ?? 0,
+ }, 502);
+ }
ws.accept();
conn = new H2Grpc(ws, host);
await Promise.race([
@@ -4453,7 +4978,7 @@ export default {
// /api/sandboxes; replaces the legacy CP-side PG routes (deleted in
// the same PR as migration 041).
if (path === "/api/secret-stores") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
if (req.method === "POST") return secretStores.createStore(req, env, caller);
if (req.method === "GET") return secretStores.listStores(req, env, caller);
@@ -4467,7 +4992,7 @@ export default {
const entryName = m[2];
const isEntriesCollection = path.endsWith("/secrets");
const isEntry = !!entryName;
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
if (isEntry) {
if (req.method === "PUT") return secretStores.setEntry(req, env, caller, storeID, entryName);
@@ -4491,7 +5016,7 @@ export default {
// an owning-cell outage). Create routes to the org home_cell with SSE
// build-log streaming. Delete routes to the cell that owns the bytes.
if (path === "/api/snapshots") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
{ const g = provisionScopeGate(caller, path); if (g) return g; }
if (req.method === "GET") return snapshots.listSnapshots(env, caller);
@@ -4507,7 +5032,7 @@ export default {
const sub = m[2] ?? "";
const isPatch = sub.startsWith("/patches");
const isPublishToggle = sub === "/publish" || sub === "/unpublish";
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
{ const g = provisionScopeGate(caller, path); if (g) return g; }
// Patches, publish/unpublish, and delete are cell-work — route to the
@@ -4530,7 +5055,7 @@ export default {
}
}
if (path === "/api/images") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
{ const g = provisionScopeGate(caller, path); if (g) return g; }
if (req.method === "GET") return snapshots.listImages(env, caller);
@@ -4582,7 +5107,7 @@ export default {
path === "/api/managed-agents" ||
path.startsWith("/api/managed-agents/")
) {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) {
return json({ error: "missing or invalid API key" }, 401);
}
@@ -4636,7 +5161,7 @@ export default {
{
const fc = path.match(/^\/api\/sandboxes\/from-checkpoint\/([^/]+)$/);
if (fc && req.method === "POST") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
const cpID = fc[1];
const cpRow = await env.OPENCOMPUTER_DB.prepare(
@@ -4722,7 +5247,7 @@ export default {
{
const cpm = path.match(/^\/api\/sandboxes\/checkpoints\/([^/]+)(\/.*)?$/);
if (cpm) {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
{ const g = provisionScopeGate(caller, path); if (g) return g; }
const cpRow = await env.OPENCOMPUTER_DB.prepare(
@@ -4747,10 +5272,13 @@ export default {
// exactly the blind spot that made create's burst regression unreadable
// until `pre`/`hdl` landed (see createSandbox). `path` names the winner so
// a fallback is counted rather than inferred.
- const stampSub = (resp: Response, servedBy: string): Response => {
+ const stampSub = (resp: Response, servedBy: string, fall?: Fallback): Response => {
// A WebSocket upgrade (pty) can't be reconstructed — pass it through.
if (resp.status === 101 || (resp as unknown as { webSocket?: unknown }).webSocket) return resp;
const extra = [`path;desc=${servedBy}`, `hdl;dur=${Date.now() - tSubEntry}`];
+ // Only meaningful on the tunnel branch, and only there is it set.
+ if (fall?.why) extra.push(`why;desc=${fall.why}`);
+ if (fall?.dial) extra.push(`dialfail;desc=${fall.dial}`);
const clientSentMs = Number(req.headers.get("x-client-sent") ?? "");
if (Number.isFinite(clientSentMs) && clientSentMs > 0) extra.unshift(`pre;dur=${tSubEntry - clientSentMs}`);
const out = new Response(resp.body, resp);
@@ -4761,7 +5289,7 @@ export default {
if (!rest) {
if (req.method === "GET") return getSandbox(req, env, id);
if (req.method === "DELETE") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
return proxyToCellSDK(req, env, ctx, caller, id);
}
@@ -4772,7 +5300,7 @@ export default {
// API-key middleware accepts that JWT shape) so we don't depend on the
// SDK's api-key existing in cell PG.
const tAuth = Date.now();
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
const authMs = Date.now() - tAuth;
if (!caller) return json({ error: "missing or invalid API key" }, 401);
// Exec/delete traffic is what keeps an org's create-context entries warm
@@ -4785,9 +5313,10 @@ export default {
// roll out the host dialer. Gated only on SESSION_JWT_SECRET (present
// wherever the DO auth can be verified at all).
let vmdoMs = 0;
+ const fall: Fallback = {};
if (env.SESSION_JWT_SECRET && req.method === "POST" && rest === "/exec/run-async") {
const tVmdo = Date.now();
- const doResp = await tryVmDoExec(req, env, ctx, caller, id, authMs);
+ const doResp = await tryVmDoExec(req, env, ctx, caller, id, authMs, fall);
vmdoMs = Date.now() - tVmdo;
// Name the winner from the marks it emitted rather than plumbing a label
// back out of two functions that already disagree about their shape.
@@ -4798,7 +5327,7 @@ export default {
}
// vmdo = time spent deciding NOT to use the VM-DO path. For MicroVM orgs
// that decision needs an org-policy lookup, so it is not free.
- return stampSub(await proxyToCellSDK(req, env, ctx, caller, id, authMs, vmdoMs), "tunnel");
+ return stampSub(await proxyToCellSDK(req, env, ctx, caller, id, authMs, vmdoMs), "tunnel", fall);
}
// Generic /api/* fallback for SDK/CLI routes without a dedicated D1-native
@@ -4813,7 +5342,7 @@ export default {
// trusted service resolve an osb_ key to its OC org without custodying it
// (agent-sandbox-ownership Phase 0.5: sessions-api maps osb_ → oc-org:<id>).
if (path === "/api/whoami" && req.method === "GET") {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
if (caller.scope) {
return json({
@@ -4843,13 +5372,13 @@ export default {
// all-at-edge). Same X-API-Key auth as the rest of the public API; must
// precede the proxy catch-all below.
if (path === "/api/webhooks" || path.startsWith("/api/webhooks/")) {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
return webhooks.handleWebhooksAPI(req, env, caller, url);
}
if (path.startsWith("/api/")) {
- const caller = await authenticate(req, env);
+ const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
return proxyToCellAuthed(req, env, caller);
}
diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.toml
index a9e30747..4f4af78a 100644
--- a/cloudflare-workers/api-edge/wrangler.prod.toml
+++ b/cloudflare-workers/api-edge/wrangler.prod.toml
@@ -156,6 +156,17 @@ WORKER_ENV = "prod"
# pool target FIRST, then this. See the SIZING INVARIANT in src/pool_stock.ts.
POOL_STOCK_TARGET = "18"
POOL_STOCK_LOW_WATER = "9"
+# Stated explicitly rather than inherited from the code default, because a shard
+# id is half of a DO NAME (`${cellID}#${gen}#${id}`) and therefore names a
+# different object — with different placement — in every cell. Sharing one
+# implicit list across environments silently asserted that prod's IAD placement
+# measurement also held for dev. It does not; dev now runs a single shard.
+#
+# These four are the prefix of the g5 set probed into IAD against THIS cell on
+# 2026-08-21. Do not extend without re-probing: of 64 candidates, only 27 landed
+# in IAD (EWR 17, ATL 9, MIA 7, ORD 4). No change in behaviour from before —
+# this is what the code default already resolved to.
+POOL_STOCK_SHARD_IDS = "1,4,6,12"
# Cells eligible for new-org home assignment live in the D1 `cells` table
# (`accepts_new_orgs` column), not an env list — toggle a row to onboard a cell,
# no deploy. See pickHomeCell in src/index.ts.
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index ce95764c..3732f669 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -216,8 +216,67 @@ PAUSED_CAP = "10"
# depth prod cannot have). 8 × 3 = 24 against 30, restoring the ratio this file
# used to carry. The tuning above is kept because it is the reasoning that will
# be needed again if dev ever takes the deep pool back.
-POOL_STOCK_TARGET = "3"
+#
+# 2026-08-24: dev takes the depth back — prod's MicroVM pool is at 0, so the
+# shared us-east-1 quota is free. 8 × 16 = 128 staged against a 130 pool.
+#
+# The 44% headroom the sizing above argues for (150 for a burst-100) is stale on
+# two counts, and neither survives in the current code:
+# - The isolate-local "magazine" tier is GONE (index.ts:1319 — "could not be
+# made correct: a magazine lives in isolate-local memory"). The uneven
+# split-across-isolates argument died with it.
+# - claimPoolBox now walks EVERY shard (index.ts:1367 — random start, odd
+# stride so it is a guaranteed full cycle). The measurements that justified
+# the slack ("56 of 100 concurrent creates fell through to the control plane
+# while the shards still held 22-81 boxes") were taken under the old
+# 3-attempt walk, where a create landing on a drained shard gave up.
+# With a full ring walk, TOTAL staged stock is what matters, not per-shard
+# balance: a create landing on a drained shard still reaches stock, costing a
+# round trip rather than a cold launch. What is left to cover is only stock
+# depleted between probe and claim — hence ~2% headroom, not 44%.
+# SIZING INVARIANT: SHARDS x TARGET must stay <= the cell pool. With 8 shards
+# against a 10-box dev pool, the old 16 asked for 128 — every shard permanently
+# below LOW_WATER, restocking on every claim, and the measured latency becomes a
+# function of shard luck rather than of the system under test. 4 shards x 2 = 8 <= 10.
+# Raise both when the cell pool is raised.
+POOL_STOCK_TARGET = "4"
POOL_STOCK_LOW_WATER = "2"
+# NO SHARDING ON DEV. Sharding buys concurrency against a single-threaded DO and
+# pays for it with pool fragmentation — one full DO round trip per empty shard,
+# on the customer's create. Dev's cell pool is 16 boxes and its bursts are a
+# handful of sequential creates, so there is no concurrency here to win and the
+# fragmentation is the only effect that survives. Measured on dev 2026-08-25:
+# claimmiss 300-320ms at 4 shards vs 84-98ms at 1; a dotry=2 claim ~150ms vs
+# ~88ms at dotry=1.
+#
+# The ids are also not portable. A shard id is half of a DO name
+# (`${cellID}#${gen}#${id}`), so the same id is a DIFFERENT object per cell, with
+# its own placement. The [1,4,6,12] default was probed into IAD against PROD's
+# cell and says nothing about dev's objects of the same id — which is why dev
+# creates were answered from ATL, IAD and ORD in a single four-request sample.
+#
+# Raise this only alongside the pool: SHARDS × POOL_STOCK_TARGET ≤ cell pool,
+# and only with ids probed into the target colo FOR THIS CELL.
+POOL_STOCK_SHARD_IDS = "1"
+# Dev's MicroVM cell runs the DIRECT-EXEC backend (OPENSANDBOX_MICROVM_LITE=1),
+# whose boxes are reachable only by a plain HTTPS POST — they hold no agent
+# tunnel for a session DO to dial. Answering exec at the edge would route around
+# the entire path this cell exists to measure while still returning correct
+# results, which is precisely how it went unnoticed for the first dev run: a 3s
+# exec, a correct answer, and not one line about it in the cell's logs.
+#
+# PROD LEAVES THIS UNSET. Its cells run the agent-tunnel backend, where the edge
+# path is both correct and much faster.
+MICROVM_EDGE_EXEC = "0"
+# Same cell, same reason, the create half. That backend keeps its warm set in
+# process and never implements EdgeReserve, so PoolStock cannot hold stock for
+# it — every create walked the shards, missed, and paid the control plane
+# anyway. Measured at 81-87ms of `claimmiss` on every single create, for an
+# outcome that was structurally impossible rather than merely unlikely.
+#
+# PROD LEAVES THIS UNSET: its MicroVM cells do fill the stock DO, and edge-claim
+# is what answers their creates at the edge.
+MICROVM_EDGE_CLAIM = "0"
# Cells eligible for new-org home assignment are NOT configured here anymore —
# it's the `accepts_new_orgs` column on the D1 `cells` table (single source of
# truth, toggled per-row without a deploy). See pickHomeCell in src/index.ts.
diff --git a/cloudflare-workers/shared/h2grpc.ts b/cloudflare-workers/shared/h2grpc.ts
index db41a1f2..19e31bd1 100644
--- a/cloudflare-workers/shared/h2grpc.ts
+++ b/cloudflare-workers/shared/h2grpc.ts
@@ -62,6 +62,51 @@ interface Call {
timer: ReturnType<typeof setTimeout>;
}
+/**
+ * openTunnel performs the WebSocket upgrade and returns an accepted socket,
+ * with a timeout that bounds the HANDSHAKE ONLY.
+ *
+ * `AbortSignal.timeout(n)` cannot be used for this, and using it was a silent
+ * disaster. The signal stays bound to the request for as long as the request
+ * exists, and a WebSocket obtained from a fetch IS that request — so the
+ * timeout does not expire when the handshake completes, it expires `n`
+ * milliseconds later and tears down a perfectly healthy tunnel.
+ *
+ * Measured on dev 2026-08-25, with a 3000ms timeout on the MicroVM agent
+ * tunnel: across 127 observed closures, `dial_duration + tunnel_lifetime` was
+ * 3000ms EXACTLY, every time — a 19ms dial lived 2981ms, a 66ms dial lived
+ * 2934ms, a 2267ms dial lived 733ms. Every socket died at code 1006 with no
+ * Close frame, which reads as "the far end hung up" and is in fact us. The
+ * MicrovmSession keepalive runs on a 5s alarm, so it could never once find a
+ * live channel: the channel was guaranteed dead two seconds before every tick.
+ * 243 dials served 5 execs.
+ *
+ * An AbortController whose timer is CLEARED on completion is the whole fix:
+ * once the handshake resolves nothing can abort the connection any more.
+ */
+export async function openTunnel(
+ url: string,
+ headers: Record<string, string>,
+ handshakeTimeoutMs: number,
+): Promise<{ ws: WebSocket; status: number }> {
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), handshakeTimeoutMs);
+ let resp: Response;
+ try {
+ resp = await fetch(url, {
+ signal: ctrl.signal,
+ headers: { Upgrade: "websocket", ...headers },
+ });
+ } finally {
+ // The entire point. Leaving this timer armed is the bug described above.
+ clearTimeout(timer);
+ }
+ const ws = (resp as unknown as { webSocket: WebSocket | null }).webSocket;
+ if (!ws) throw new Error(`agent tunnel upgrade failed (http ${resp.status})`);
+ ws.accept();
+ return { ws, status: resp.status };
+}
+
/**
* H2Grpc drives one HTTP/2 connection over a WebSocket that carries a raw byte
* stream. One instance per open tunnel; not safe to share across tunnels.
@@ -75,6 +120,10 @@ export class H2Grpc {
private pingSeq = 0;
private nextStream = 1;
private dead: Error | null = null;
+ // When this tunnel was opened, so kill() can report how long it survived.
+ // A channel whose whole purpose is to outlive the gap between requests needs
+ // its lifetime stated, not inferred from how often something re-dials.
+ private readonly openedAt = Date.now();
private readyResolve: (() => void) | null = null;
private readyReject: ((e: Error) => void) | null = null;
/**
@@ -118,7 +167,15 @@ export class H2Grpc {
}
this.onBytes(new Uint8Array(data));
});
- ws.addEventListener("close", () => this.kill(new Error("h2grpc: tunnel closed")));
+ // The close CODE and REASON are the only evidence that distinguishes "the
+ // Durable Object was evicted and took this socket with it" from "the AWS
+ // proxy or the guest hung up on us" — and those two have completely
+ // different fixes. Both were being thrown away here, which is why a fleet
+ // re-dialling every 5s (measured on dev: 243 dials serving 5 execs) looked
+ // like an unexplained latency sawtooth rather than a stated fact.
+ ws.addEventListener("close", (ev: CloseEvent) =>
+ this.kill(new Error(`h2grpc: tunnel closed code=${ev?.code ?? "?"} reason=${ev?.reason || "(none)"} wasClean=${ev?.wasClean ?? "?"}`)),
+ );
ws.addEventListener("error", () => this.kill(new Error("h2grpc: tunnel error")));
// Preface, our SETTINGS, and a connection-level window bump, sent eagerly.
@@ -154,6 +211,13 @@ export class H2Grpc {
private kill(e: Error): void {
if (this.dead) return;
this.dead = e;
+ // The reason a tunnel died was recorded here and never surfaced. That is
+ // how "the keepalive holds one channel open" and "the keepalive rebuilds a
+ // channel every 5s" stayed indistinguishable: both look like a working
+ // alarm loop from the outside. Age is the discriminator — a socket dying at
+ // ~5s is being reclaimed with its object, one dying at its idle timeout is
+ // being hung up on by the far end.
+ console.log(`h2grpc: KILL ${this.authority} after ${Date.now() - this.openedAt}ms — ${e.message}`);
if (this.readyReject) {
this.readyReject(e);
this.readyReject = null;
diff --git a/cloudflare-workers/vm-do/src/microvm_session.ts b/cloudflare-workers/vm-do/src/microvm_session.ts
index 05a2fb15..3b0e4087 100644
--- a/cloudflare-workers/vm-do/src/microvm_session.ts
+++ b/cloudflare-workers/vm-do/src/microvm_session.ts
@@ -21,7 +21,7 @@
// control-plane path — they are not implemented here and calls for them should
// never be routed to this DO.
-import { H2Grpc, encodeExecRequest, decodeExecResponse, type ExecReq } from "../../shared/h2grpc";
+import { H2Grpc, openTunnel, encodeExecRequest, decodeExecResponse, type ExecReq } from "../../shared/h2grpc";
const EXEC_PATH = "/agent.SandboxAgent/Exec";
const AGENT_TUNNEL_PATH = "/osb/agent-grpc"; // must match internal/awsvm.AgentTunnelPath
@@ -74,6 +74,45 @@ const MAX_KEEPALIVE_FAILURES = 5;
// box which comes good is back on the fast cadence within a minute.
const KEEPALIVE_BACKOFF_MS = 60_000;
const PING_TIMEOUT_MS = 3_000;
+// Minimum gap between PINGs, which is NOT the same thing as the alarm cadence
+// and must not be conflated with it again.
+//
+// The alarm has two jobs with opposite constraints. Residency needs a tick
+// comfortably inside Cloudflare's ~10s idle eviction. But the agent's gRPC
+// server sets KeepaliveEnforcementPolicy{MinTime: 10s} (internal/agent/
+// server.go) — ping faster than that and Go's gRPC counts strikes, and at two
+// strikes it sends GOAWAY and drops the connection. Pinging on every 5s alarm
+// meant strikes at 5s and 10s and a GOAWAY at ~15s, forever: measured on dev
+// 2026-08-25, twelve consecutive tunnels died at 15039-15092ms to
+// "server sent GOAWAY". The keepalive was causing the disconnection it exists
+// to prevent.
+//
+// So: wake every KEEPALIVE_MS to stay resident, ping only every
+// PING_MIN_INTERVAL_MS to stay inside the agent's floor. 12s rather than 10s
+// because alarm delivery jitters and being 200ms early costs the whole channel.
+// Raising it further trades against whatever idle timeout the AWS proxy applies
+// to the guest attachment — which the h2grpc KILL log will name if we cross it.
+const PING_MIN_INTERVAL_MS = 12_000;
+// How stale the PERSISTED warmUntil may get before exec bothers to rewrite it.
+// Five minutes against a one-hour TTL: a re-created instance reading a value
+// this stale reaches the same decision, and in exchange the common exec does
+// zero storage writes. See the write site in exec().
+const WARM_PERSIST_SLACK_MS = 5 * 60 * 1000;
+// How long the WebSocket handshake and the guest's first SETTINGS frame may
+// take. Sized for a box that has SUSPENDED, not for a healthy one.
+//
+// AWS suspends a MicroVM after its configured idle window and, with auto-resume
+// on, the next inbound request through the proxy wakes it — Lambda holds that
+// request for the length of a snapshot restore. That is far longer than the
+// 3000ms this used to allow, so the old budget guaranteed the one outcome we
+// least wanted: we aborted our own resume, reported a dial failure, and left the
+// box suspended for the next caller to fail against too.
+//
+// The cost of the larger budget is bounded and lands in the right place. A dial
+// only happens when the channel is cold; a healthy box completes both legs in
+// tens of milliseconds and never approaches this.
+const DIAL_HANDSHAKE_MS = 20_000;
+const DIAL_READY_MS = 20_000;
interface Creds {
endpoint: string;
@@ -100,6 +139,14 @@ export class MicrovmSession {
// Last dial cost, so the exec that triggered a dial can attribute it. Set by
// dial(), consumed and cleared by exec().
private lastDialMs = 0;
+ // When this instance last sent a PING, to hold the alarm to the agent's
+ // MinTime floor — see PING_MIN_INTERVAL_MS. In memory only: a fresh instance
+ // has a fresh channel too, so it owes no ping debt.
+ private lastPingAt = 0;
+ // What this instance last armed the alarm for, and what it last persisted as
+ // warmUntil. Both exist to keep storage OFF the exec path — see armKeepalive.
+ private alarmDueAt = 0;
+ private warmUntilPersisted = 0;
constructor(state: DurableObjectState) {
this.state = state;
@@ -211,10 +258,29 @@ export class MicrovmSession {
// setAlarm overwrites, so this is also the re-arm. Only skip when one is
// already due sooner than we would set it — a burst of attaches must not
// push the next tick further out.
- const due = await this.state.storage.getAlarm();
+ //
+ // The due time is read from MEMORY first, and that is a latency fix, not a
+ // micro-optimisation. Durable Object output gates hold a response until
+ // every pending storage write is confirmed durable, so a storage op on the
+ // exec path is paid by the CALLER, after the handler has already finished.
+ // It is invisible in `inside` and lands squarely in the edge's `dback`.
+ // Measured on dev 2026-08-25 with getAlarm+put on every exec: `dinside`
+ // never left 11-29ms while `mvmdo` swung 101->535ms, with the excursions in
+ // `dto`/`dback` (~200ms and ~300ms) and not in the handler.
+ //
+ // alarmDueAt is a cache of what this instance last armed. A fresh instance
+ // starts at 0 and falls through to the real read once, which is correct:
+ // it genuinely does not know. Being wrong in the stale direction only costs
+ // a redundant setAlarm, never a missed tick.
const next = Date.now() + KEEPALIVE_MS;
- if (due !== null && due <= next) return;
+ if (this.alarmDueAt > Date.now() && this.alarmDueAt <= next) return;
+ const due = this.alarmDueAt > 0 ? this.alarmDueAt : await this.state.storage.getAlarm();
+ if (due !== null && due > Date.now() && due <= next) {
+ this.alarmDueAt = due;
+ return;
+ }
await this.state.storage.setAlarm(next);
+ this.alarmDueAt = next;
}
/**
@@ -232,6 +298,12 @@ export class MicrovmSession {
* platform's schedule, not ours, and we would rather re-arm deliberately.
*/
async alarm(): Promise<void> {
+ // Absolute stamps, to be read against exec's enter/exit. A Durable Object
+ // serializes its invocations, so an alarm that spends up to PING_TIMEOUT_MS
+ // failing a ping is a window in which an arriving exec cannot start. That is
+ // the leading explanation for the ~1s gap between the edge's mvmdo and this
+ // object's own `inside`, and it is only checkable if both are timestamped.
+ const tAlarm = Date.now();
const creds = await this.loadCreds();
if (!creds) return; // detached — let the loop end
if (!this.warmUntil) this.warmUntil = (await this.state.storage.get<number>("warmUntil")) ?? 0;
@@ -243,8 +315,16 @@ export class MicrovmSession {
}
let next = KEEPALIVE_MS;
try {
+ // Waking is unconditional — that is what keeps the object resident and so
+ // keeps the channel alive at all. PINGING is rate-limited to the agent's
+ // enforcement floor. A tick that only wakes is not a wasted tick; it is
+ // the majority of them, and it is doing the more important of the two jobs.
const conn = await this.channel();
- await conn.ping(PING_TIMEOUT_MS);
+ const sincePing = Date.now() - this.lastPingAt;
+ if (this.lastPingAt === 0 || sincePing >= PING_MIN_INTERVAL_MS) {
+ this.lastPingAt = Date.now();
+ await conn.ping(PING_TIMEOUT_MS);
+ }
if (this.failures > 0) console.log(`mvm-do: keepalive recovered after ${this.failures}`);
this.failures = 0;
} catch (e) {
@@ -256,6 +336,7 @@ export class MicrovmSession {
// the thing that ends this loop.
if (this.failures >= MAX_KEEPALIVE_FAILURES) next = KEEPALIVE_BACKOFF_MS;
}
+ console.log(`mvm-do: alarm span ${tAlarm}..${Date.now()} (${Date.now() - tAlarm}ms), next in ${next}ms`);
await this.state.storage.setAlarm(Date.now() + next);
}
@@ -277,24 +358,22 @@ export class MicrovmSession {
const p = (async (): Promise<H2Grpc> => {
const tDial = Date.now();
const host = creds.endpoint.replace(/^https?:\/\//, "").split("/")[0];
- const resp = await fetch(`https://${host}${AGENT_TUNNEL_PATH}`, {
- signal: AbortSignal.timeout(3000),
- headers: {
- Upgrade: "websocket",
- "X-aws-proxy-auth": creds.token,
- "X-aws-proxy-port": String(creds.port),
- },
- });
- const ws = (resp as unknown as { webSocket: WebSocket | null }).webSocket;
- if (!ws) throw new Error(`agent tunnel upgrade failed (http ${resp.status})`);
- ws.accept();
+ // openTunnel, NOT fetch with AbortSignal.timeout — see its docstring. The
+ // timeout here must bound the handshake; bound to the connection it kills
+ // the tunnel 3s after every dial, which is exactly what this keepalive
+ // exists to prevent and exactly what it was doing.
+ const { ws } = await openTunnel(
+ `https://${host}${AGENT_TUNNEL_PATH}`,
+ { "X-aws-proxy-auth": creds.token, "X-aws-proxy-port": String(creds.port) },
+ DIAL_HANDSHAKE_MS,
+ );
this.ws = ws;
const conn = new H2Grpc(ws, host);
this.conn = conn;
// Wait for the guest, not just the proxy — see H2Grpc.ready.
await Promise.race([
conn.ready,
- new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), 8000)),
+ new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), DIAL_READY_MS)),
]);
// Logged rather than dropped: a dial here is the ~1.1s guest-attach the
// keepalive exists to keep off the customer's path, so a run of them is
@@ -394,12 +473,33 @@ export class MicrovmSession {
// lapsed (TTL expiry, or a run of failures while the box was resuming).
this.warmUntil = Date.now() + KEEPALIVE_TTL_MS;
this.failures = 0;
- await this.state.storage.put("warmUntil", this.warmUntil);
+ // Persist only when the durable copy has drifted far enough to matter.
+ // The in-memory value is what this instance actually uses; the stored one
+ // exists solely so a RE-CREATED instance knows whether to keep warming,
+ // and for that a value up to WARM_PERSIST_SLACK_MS stale is identical in
+ // effect. Writing on every exec put a storage op inside the output gate,
+ // which delays the RESPONSE — the caller pays it, and it shows up in the
+ // edge's `dback` rather than anywhere this object can see.
+ if (this.warmUntil - this.warmUntilPersisted >= WARM_PERSIST_SLACK_MS) {
+ this.warmUntilPersisted = this.warmUntil;
+ await this.state.storage.put("warmUntil", this.warmUntil);
+ }
await this.armKeepalive();
return json(decodeExecResponse(res), 200, {
// live=1 means the channel survived from the last request or the
// keepalive — the state this whole design is trying to be in.
- "x-mvm-timing": `live=${wasLive ? 1 : 0},cold=${coldStart ? 1 : 0},dial=${this.lastDialMs},unary=${unaryMs},inside=${Date.now() - tEnter}`,
+ // enter/exit are ABSOLUTE epoch ms, not durations. The edge measures the
+ // whole round trip as one number (mvmdo) and this object measures its
+ // own work (inside); the difference has been over a SECOND on some
+ // execs while inside was 41-56ms, and a single opaque gap cannot say
+ // whether that second was spent getting here, queued outside this
+ // handler, or going back. Pairing these with the edge's own send/receive
+ // stamps splits it three ways.
+ //
+ // Both ends are Workers, so the clocks are the same source; Date.now()
+ // in a Worker only advances on I/O, which makes these unusable for
+ // anything small — and completely adequate against a 1000ms question.
+ "x-mvm-timing": `live=${wasLive ? 1 : 0},cold=${coldStart ? 1 : 0},dial=${this.lastDialMs},unary=${unaryMs},inside=${Date.now() - tEnter},enter=${tEnter},exit=${Date.now()}`,
"x-mvm-colo": this.colo,
});
} catch (e) {
diff --git a/cmd/microvm-hooks/main.go b/cmd/microvm-hooks/main.go
index f561463d..a4f9998c 100644
--- a/cmd/microvm-hooks/main.go
+++ b/cmd/microvm-hooks/main.go
@@ -72,6 +72,66 @@ const (
// agentTunnelPath is the WebSocket endpoint carrying gRPC to the agent.
// Must match internal/awsvm's dialer.
agentTunnelPath = "/osb/agent-grpc"
+
+ // runCmdPath executes one command and returns its result as ordinary JSON.
+ // Must match internal/awsvmlite.
+ runCmdPath = "/osb/run"
+)
+
+// runCmdRequest / runCmdResponse are the whole protocol of the direct exec path.
+//
+// PLAIN HTTP ON PURPOSE. Everything else in this file exists to carry gRPC into
+// the guest: the agent bridge, the WebSocket tunnel, the h2c handler. All of it
+// is there because gRPC reports its status in HTTP/2 trailers and Lambda's proxy
+// strips them, so a gRPC reply arrives with the command already executed and the
+// result missing.
+//
+// A JSON request/response has no trailers to lose. That single difference
+// removes the entire tunnel tier — no WebSocket, no persistent channel, no
+// keepalive, no re-dial, no Durable Object holding a socket open — and with it
+// every failure mode that tier has: measured on dev the same day this was
+// written, a box answering /healthz in 90ms with agentUp=true was simultaneously
+// logged by the control plane as tunnel-less with re-dial timing out at 30s.
+//
+// The cost is deliberate and total: no streaming, no PTY, no sessions, no file
+// transfer. One command, buffered output, one reply. Anything richer belongs on
+// the agent path.
+// The field names mirror types.ProcessConfig so the control plane forwards a
+// customer's exec request without reshaping it.
+type runCmdRequest struct {
+ Cmd string `json:"cmd"`
+ // Args, when present, makes Cmd an executable rather than a shell string —
+ // the same rule the agent's exec follows.
+ //
+ // Carried as real fields rather than folded into one shell string on the
+ // host, because building `cd %s && export %s=%s; %s` puts three separate
+ // quoting problems on the exec hot path: a path with a space, a value with a
+ // quote, and a command the customer wrote for a shell that isn't this one.
+ // exec.Cmd already has Dir and Env, and they cannot be escaped wrong.
+ Args []string `json:"args,omitempty"`
+ Env map[string]string `json:"envs,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ // TimeoutSec bounds the command. Zero means runCmdDefaultTimeout.
+ TimeoutSec int `json:"timeoutSec,omitempty"`
+}
+
+type runCmdResponse struct {
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ ExitCode int `json:"exitCode"`
+ DurationMs int64 `json:"durationMs"`
+ // TimedOut distinguishes "the command was killed at the deadline" from "the
+ // command exited non-zero", which are the same exit status otherwise.
+ TimedOut bool `json:"timedOut,omitempty"`
+}
+
+const (
+ runCmdDefaultTimeout = 30 * time.Second
+ runCmdMaxTimeout = 10 * time.Minute
+ // runCmdMaxOutput caps each stream. Buffered in memory and returned in a
+ // JSON body, so an unbounded `cat /dev/urandom` would otherwise take the
+ // guest's memory and the reply with it.
+ runCmdMaxOutput = 1 << 20 // 1 MiB per stream
)
// runPayload is the body Lambda POSTs to /run. runHookPayload is per-MicroVM
@@ -187,6 +247,12 @@ func main() {
// proxy could not — and why osb-agent needs no change at all.
mux.HandleFunc(agentTunnelPath, s.handleAgentTunnel)
+ // Direct exec. Registered before the catch-all below because ServeMux picks
+ // the longest matching pattern — without an explicit entry this path would
+ // be forwarded to osb-agent's gRPC listener, which answers a JSON POST with
+ // 415 and no explanation.
+ mux.HandleFunc(runCmdPath, s.handleRunCmd)
+
// Everything that is not a hook is forwarded to osb-agent.
//
// This exists because Lambda's proxy forwards guest traffic ONLY to the port
@@ -313,6 +379,116 @@ func agentUp() bool {
// tells Lambda to snapshot; 503 means retry. Return 503 immediately rather than
// holding the request open — a held request that outlives the timeout kills the
// whole build.
+// handleRunCmd runs one command and returns its result as JSON.
+//
+// See runCmdRequest for why this exists alongside the agent bridge rather than
+// through it.
+//
+// A command that fails is NOT an HTTP error: a non-zero exit is a perfectly
+// ordinary result and the caller needs the output either way. Only a malformed
+// request or a failure to start the process gets a 4xx/5xx, so the caller can
+// tell "your command exited 1" from "the sandbox could not run it".
+func (s *server) handleRunCmd(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ var req runCmdRequest
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil {
+ http.Error(w, "bad request body", http.StatusBadRequest)
+ return
+ }
+ if strings.TrimSpace(req.Cmd) == "" {
+ http.Error(w, "cmd is required", http.StatusBadRequest)
+ return
+ }
+
+ timeout := runCmdDefaultTimeout
+ if req.TimeoutSec > 0 {
+ timeout = time.Duration(req.TimeoutSec) * time.Second
+ if timeout > runCmdMaxTimeout {
+ timeout = runCmdMaxTimeout
+ }
+ }
+ // Bound by the request's context too, so a caller that gives up does not
+ // leave the command running in the guest.
+ ctx, cancel := context.WithTimeout(r.Context(), timeout)
+ defer cancel()
+
+ // `sh -lc` matches what the agent's exec does, so a command behaves the same
+ // on both paths — the login shell sources the same profile chain and finds
+ // the same PATH. With explicit args the command is an executable instead,
+ // which is also what the agent does.
+ started := time.Now()
+ name, args := "/bin/sh", []string{"-lc", req.Cmd}
+ if len(req.Args) > 0 {
+ name, args = req.Cmd, req.Args
+ }
+ cmd := exec.CommandContext(ctx, name, args...)
+ cmd.Dir = req.Cwd
+ if len(req.Env) > 0 {
+ // Appended to the guest's environment, not substituted for it: replacing
+ // it would drop PATH and HOME, so every command that named a binary
+ // rather than a path would stop resolving.
+ env := os.Environ()
+ for k, v := range req.Env {
+ env = append(env, k+"="+v)
+ }
+ cmd.Env = env
+ }
+ var stdout, stderr cappedBuffer
+ stdout.limit, stderr.limit = runCmdMaxOutput, runCmdMaxOutput
+ cmd.Stdout, cmd.Stderr = &stdout, &stderr
+
+ runErr := cmd.Run()
+ resp := runCmdResponse{
+ Stdout: stdout.String(),
+ Stderr: stderr.String(),
+ DurationMs: time.Since(started).Milliseconds(),
+ TimedOut: ctx.Err() != nil,
+ }
+ switch {
+ case runErr == nil:
+ resp.ExitCode = 0
+ case cmd.ProcessState != nil:
+ // Ran and exited non-zero — a result, not an error.
+ resp.ExitCode = cmd.ProcessState.ExitCode()
+ default:
+ // Never started: no binary, no fork, nothing to report an exit code for.
+ http.Error(w, "could not start command: "+runErr.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(resp)
+}
+
+// cappedBuffer accumulates up to limit bytes and silently discards the rest.
+//
+// Discarding rather than erroring is deliberate: a command that prints more than
+// the cap has still done its work, and failing the whole call over trailing
+// output would turn a successful build into an error. The caller sees a
+// truncated stream, which is the same contract every log tail has.
+type cappedBuffer struct {
+ buf []byte
+ limit int
+}
+
+func (b *cappedBuffer) Write(p []byte) (int, error) {
+ if room := b.limit - len(b.buf); room > 0 {
+ if len(p) < room {
+ room = len(p)
+ }
+ b.buf = append(b.buf, p[:room]...)
+ }
+ // Always report the full length: an io.Writer that under-reports makes
+ // os/exec treat a capped stream as a short write and fail the command.
+ return len(p), nil
+}
+
+func (b *cappedBuffer) String() string { return string(b.buf) }
+
func (s *server) handleReady(w http.ResponseWriter, _ *http.Request) {
if !agentUp() {
http.Error(w, "agent not listening yet", http.StatusServiceUnavailable)
diff --git a/cmd/microvm-hooks/run_test.go b/cmd/microvm-hooks/run_test.go
new file mode 100644
index 00000000..c7495038
--- /dev/null
+++ b/cmd/microvm-hooks/run_test.go
@@ -0,0 +1,148 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// These cover the contract the direct exec path depends on. The whole point of
+// runCmdPath is that a caller gets a RESULT rather than a transport error, so
+// the cases that matter are the ones where something went wrong in the guest and
+// the reply still has to be well-formed JSON with the right exit code.
+
+func postRunCmd(t *testing.T, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ s := &server{}
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, runCmdPath, strings.NewReader(body))
+ s.handleRunCmd(rec, req)
+ return rec
+}
+
+func decodeRunCmd(t *testing.T, rec *httptest.ResponseRecorder) runCmdResponse {
+ t.Helper()
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body %q", rec.Code, rec.Body.String())
+ }
+ var out runCmdResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+ t.Fatalf("decode: %v (body %q)", err, rec.Body.String())
+ }
+ return out
+}
+
+func TestRunCmdReturnsStdoutAndZeroExit(t *testing.T) {
+ out := decodeRunCmd(t, postRunCmd(t, `{"cmd":"echo hello"}`))
+ if strings.TrimSpace(out.Stdout) != "hello" {
+ t.Fatalf("stdout = %q, want %q", out.Stdout, "hello")
+ }
+ if out.ExitCode != 0 {
+ t.Fatalf("exitCode = %d, want 0", out.ExitCode)
+ }
+}
+
+// A non-zero exit is a RESULT, not an HTTP error. Returning 500 here would make
+// every failing customer command indistinguishable from a broken sandbox, and
+// would throw away the output that explains the failure.
+func TestNonZeroExitIsStillA200WithOutput(t *testing.T) {
+ out := decodeRunCmd(t, postRunCmd(t, `{"cmd":"echo oops >&2; exit 3"}`))
+ if out.ExitCode != 3 {
+ t.Fatalf("exitCode = %d, want 3", out.ExitCode)
+ }
+ if strings.TrimSpace(out.Stderr) != "oops" {
+ t.Fatalf("stderr = %q, want %q", out.Stderr, "oops")
+ }
+}
+
+// The deadline has to be reported, because a killed command and a command that
+// chose to exit non-zero otherwise look identical to the caller.
+func TestTimeoutIsReportedRatherThanHidden(t *testing.T) {
+ out := decodeRunCmd(t, postRunCmd(t, `{"cmd":"sleep 5","timeoutSec":1}`))
+ if !out.TimedOut {
+ t.Fatalf("timedOut = false for a command killed at its deadline (exit %d)", out.ExitCode)
+ }
+}
+
+// cwd and envs are part of the exec contract the control plane forwards. They
+// are carried as real fields precisely so no host-side quoting can mangle them,
+// and these two pin that end of it — a path with a space and a value with a
+// quote are exactly what a hand-built `cd %s && export %s=%s` gets wrong.
+func TestCwdAndEnvAreAppliedWithoutQuoting(t *testing.T) {
+ dir := t.TempDir() + "/a dir"
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ body, _ := json.Marshal(runCmdRequest{
+ Cmd: `printf '%s|%s' "$PWD" "$OSB_T"`,
+ Cwd: dir,
+ Env: map[string]string{"OSB_T": `it's "quoted"`},
+ })
+ out := decodeRunCmd(t, postRunCmd(t, string(body)))
+ // Resolved because the host may hand back a symlinked temp dir (macOS
+ // /var → /private/var); the guest never does, and the point here is the
+ // space and the quote, not the prefix.
+ resolved, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := resolved + `|it's "quoted"`; out.Stdout != want {
+ t.Fatalf("stdout = %q, want %q", out.Stdout, want)
+ }
+}
+
+// An explicit env must not replace the guest's own: dropping PATH would break
+// every command that names a binary instead of a path.
+func TestExplicitEnvKeepsTheInheritedEnvironment(t *testing.T) {
+ body, _ := json.Marshal(runCmdRequest{Cmd: `command -v sh >/dev/null && echo found`, Env: map[string]string{"OSB_T": "1"}})
+ out := decodeRunCmd(t, postRunCmd(t, string(body)))
+ if strings.TrimSpace(out.Stdout) != "found" {
+ t.Fatalf("stdout = %q — PATH did not survive an explicit env", out.Stdout)
+ }
+}
+
+// With args present, cmd is an executable and NOT a shell string — the agent's
+// rule. Without this the two paths would disagree on what `echo` even means.
+func TestArgsMakeCmdAnExecutable(t *testing.T) {
+ body, _ := json.Marshal(runCmdRequest{Cmd: "/bin/echo", Args: []string{"a b", "c"}})
+ out := decodeRunCmd(t, postRunCmd(t, string(body)))
+ if strings.TrimSpace(out.Stdout) != "a b c" {
+ t.Fatalf("stdout = %q, want %q", out.Stdout, "a b c")
+ }
+}
+
+func TestEmptyCommandIsRejected(t *testing.T) {
+ if rec := postRunCmd(t, `{"cmd":" "}`); rec.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d for an empty command, want 400", rec.Code)
+ }
+}
+
+// cappedBuffer must report the FULL write length even when it discards. An
+// io.Writer that under-reports makes os/exec treat the capped stream as a short
+// write and fail the command — turning "your command printed a lot" into "your
+// command did not run".
+func TestCappedBufferTruncatesWithoutFailingTheCommand(t *testing.T) {
+ b := &cappedBuffer{limit: 4}
+ n, err := b.Write([]byte("abcdefgh"))
+ if err != nil {
+ t.Fatalf("Write returned %v; os/exec aborts the command on a writer error", err)
+ }
+ if n != 8 {
+ t.Fatalf("Write reported %d of 8 bytes — a short write fails the command", n)
+ }
+ if b.String() != "abcd" {
+ t.Fatalf("buffered %q, want %q", b.String(), "abcd")
+ }
+
+ out := decodeRunCmd(t, postRunCmd(t, `{"cmd":"head -c 3000000 /dev/zero | tr '\\0' 'x'"}`))
+ if out.ExitCode != 0 {
+ t.Fatalf("exitCode = %d for an over-cap command, want 0 (stderr %q)", out.ExitCode, out.Stderr)
+ }
+ if len(out.Stdout) != runCmdMaxOutput {
+ t.Fatalf("stdout = %d bytes, want the cap %d", len(out.Stdout), runCmdMaxOutput)
+ }
+}
diff --git a/deploy/microvm/publish.sh b/deploy/microvm/publish.sh
index 3ff4d7d7..949fe0e9 100755
--- a/deploy/microvm/publish.sh
+++ b/deploy/microvm/publish.sh
@@ -9,6 +9,17 @@
# script rather than in copy-paste instructions is what stops that recurring.
#
# ./deploy/microvm/publish.sh s3://bucket/agent-image.zip
+#
+# Size tiers: memory is a property of the IMAGE, so each tier is its own image
+# published from the SAME artifact with a different name and memory. Only the
+# default tier is pooled; the rest cold-launch.
+#
+# MICROVM_IMAGE_NAME=opensandbox-agent-dev-8192 \
+# MICROVM_IMAGE_MEMORY_MB=8192 \
+# ./deploy/microvm/publish.sh s3://bucket/agent-image.zip
+#
+# Then point the cell at them:
+# OPENSANDBOX_MICROVM_SIZE_IMAGES="8192=arn:...:microvm-image:opensandbox-agent-dev-8192"
set -euo pipefail
DEST="${1:-}"
@@ -60,9 +71,22 @@ JSON
# to match; stating it explicitly here keeps the two from drifting apart silently.
CPU='[{"architecture":"ARM_64"}]'
+# Memory is the ONLY sizing knob this platform has, and it lives here rather
+# than at launch: RunMicrovmInput carries no memory or vCPU field, so a size
+# tier IS an image. Offering N sizes means publishing N images and selecting one
+# per create (see awsvm.Config.SizeImages).
+#
# 2048 MiB is the smallest baseline that still gets a full vCPU under Lambda's
-# baseline-peak model, and peak scales to 4x it.
-RESOURCES='[{"minimumMemoryInMiB":2048}]'
+# baseline-peak model, and peak scales to 4x it. Keep that as the floor: below
+# it a box may not get a full vCPU, and there is no way to ask for one.
+#
+# There is deliberately no vCPU setting to mirror. cpu-configurations carries an
+# architecture and nothing else; CPU is allocated as a function of memory.
+MEMORY_MB="${MICROVM_IMAGE_MEMORY_MB:-2048}"
+if (( MEMORY_MB < 2048 )); then
+ echo "warning: ${MEMORY_MB}MiB is below the 2048 baseline — this tier may not get a full vCPU" >&2
+fi
+RESOURCES="[{\"minimumMemoryInMiB\":${MEMORY_MB}}]"
# Name the log group explicitly so build failures are greppable at a known path
# instead of wherever the service would otherwise default.
diff --git a/docs/api-reference/checkpoints/fork.mdx b/docs/api-reference/checkpoints/fork.mdx
index 69ffab92..bf35baed 100644
--- a/docs/api-reference/checkpoints/fork.mdx
+++ b/docs/api-reference/checkpoints/fork.mdx
@@ -22,7 +22,7 @@ Create a new sandbox from a checkpoint.
</ParamField>
<ParamField body="memoryMB" type="integer">
- Memory for the forked sandbox, in MB. Clamped to a valid range: the floor is the checkpoint's own memory (a fork can't start smaller than the snapshot it restores, so a smaller value is ignored) and the ceiling is 16384 (16 GB; larger values are capped). The `memoryMB` field in the response reports the effective value after clamping.
+ Memory for the forked sandbox, in MB. Clamped to a valid range: the floor is the checkpoint's own memory (a fork can't start smaller than the snapshot it restores, so a smaller value is ignored) and the ceiling is 8192 (8 GB; larger values are capped). The `memoryMB` field in the response reports the effective value after clamping.
</ParamField>
<ResponseExample>
diff --git a/docs/api-reference/sandboxes/create.mdx b/docs/api-reference/sandboxes/create.mdx
index 42d32dd7..e027f702 100644
--- a/docs/api-reference/sandboxes/create.mdx
+++ b/docs/api-reference/sandboxes/create.mdx
@@ -29,6 +29,13 @@ The 1 GB tier provides 1 vCPU on a best-effort basis. For guaranteed CPU allocat
If both `cpuCount` and `memoryMB` are provided, they must match a platform tier.
+<Note>
+ `memoryMB` is the only opportunity to size a sandbox: the size is fixed for the
+ sandbox's lifetime and cannot be changed afterwards. A size outside the
+ supported tiers is rejected rather than rounded down, so you are never quietly
+ given less than you asked for. See [Sizing](/sandboxes/sizing).
+</Note>
+
<ParamField body="envs" type="object">
Environment variables as key-value pairs
</ParamField>
diff --git a/docs/docs.json b/docs/docs.json
index cf2e4ace..514bcc02 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -98,7 +98,7 @@
"sandboxes/patches",
"sandboxes/preview-urls",
"sandboxes/webhooks",
- "sandboxes/elasticity",
+ "sandboxes/sizing",
"sandboxes/burst-sandboxes",
{
"group": "Usage",
@@ -150,7 +150,6 @@
"pages": [
"reference/typescript-sdk/overview",
"reference/typescript-sdk/sandbox",
- "reference/typescript-sdk/scaling",
{
"group": "Usage & Tags",
"tag": "Preview",
@@ -170,7 +169,6 @@
"pages": [
"reference/python-sdk/overview",
"reference/python-sdk/sandbox",
- "reference/python-sdk/scaling",
"reference/python-sdk/exec",
"reference/python-sdk/filesystem",
"reference/python-sdk/pty",
@@ -184,7 +182,6 @@
"pages": [
"reference/cli/overview",
"reference/cli/sandbox",
- "reference/cli/scaling",
"reference/cli/exec",
"reference/cli/shell",
"reference/cli/checkpoint",
diff --git a/docs/guides/browser-automation.mdx b/docs/guides/browser-automation.mdx
index f82524d8..5c3a0ce6 100644
--- a/docs/guides/browser-automation.mdx
+++ b/docs/guides/browser-automation.mdx
@@ -233,7 +233,7 @@ The profile lives on the data disk, which survives sandbox hibernation. For cros
## Resource and concurrency limits
-- **Memory per VM** — default is ~1GB. Each headless Chromium uses ~300-500MB; headed full Chromium uses ~500-800MB. Pass `memoryMB: 16384` to `Sandbox.create` for browser-heavy work.
+- **Memory per VM** — default is ~1GB. Each headless Chromium uses ~300-500MB; headed full Chromium uses ~500-800MB. Pass `memoryMB: 8192` to `Sandbox.create` for browser-heavy work.
- **File descriptors** — the default `nofile` limit of 1024 is too low for Chromium (which opens hundreds of FDs). Launch the server process under `sudo bash -c "ulimit -n 65535 && exec ..."` to raise it.
- **Concurrency** — with default memory, run 2-3 browsers concurrently per sandbox. With 16GB and proper limits, 5+ works cleanly.
diff --git a/docs/how-it-works.mdx b/docs/how-it-works.mdx
index c229f8d5..255e68bd 100644
--- a/docs/how-it-works.mdx
+++ b/docs/how-it-works.mdx
@@ -65,7 +65,7 @@ See [Templates](/sandboxes/templates) for the full guide.
## Elasticity
-Sandboxes can scale memory at runtime via an internal metadata endpoint (`http://169.254.169.254/v1/scale`) accessible from inside the VM. CPU scales proportionally. This lets workloads request more resources before heavy tasks and release them after. See [Elasticity](/sandboxes/elasticity) for details.
+A sandbox's memory is chosen when it is created and stays fixed for its lifetime, with CPU allocated proportionally. See [Sizing](/sandboxes/sizing) for the available tiers.
## Networking
diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx
index d08f2bed..2acf9a03 100644
--- a/docs/quickstart.mdx
+++ b/docs/quickstart.mdx
@@ -60,8 +60,8 @@ Your sandboxes stay alive as long as you need them. They don't shut down after a
## Next Steps
<CardGroup cols={2}>
- <Card title="Elastic Compute" icon="gauge-high" href="/sandboxes/elasticity">
- Scale memory and CPU at runtime based on workload
+ <Card title="Sizing" icon="gauge-high" href="/sandboxes/sizing">
+ Pick the memory and CPU your workload needs at create time
</Card>
<Card title="Upload & Download Files" icon="file-arrow-up" href="/sandboxes/working-with-files">
Read, write, and transfer files to and from sandboxes
diff --git a/docs/reference/cli/sandbox.mdx b/docs/reference/cli/sandbox.mdx
index 6f675a9a..845a3bfc 100644
--- a/docs/reference/cli/sandbox.mdx
+++ b/docs/reference/cli/sandbox.mdx
@@ -100,7 +100,7 @@ oc sandbox set-timeout sb-abc123 600
---
-For commands that resize a sandbox or freeze its size — `scale`, `autoscale`, `lock`, `unlock`, `lock-status` — see [Scaling](/reference/cli/scaling).
+A sandbox's size is chosen at create with `--memory`; see [Sizing](/sandboxes/sizing).
---
diff --git a/docs/reference/cli/scaling.mdx b/docs/reference/cli/scaling.mdx
deleted file mode 100644
index 62f42815..00000000
--- a/docs/reference/cli/scaling.mdx
+++ /dev/null
@@ -1,121 +0,0 @@
----
-title: "oc sandbox scaling"
-description: "Resize sandboxes, configure autoscale, and manage scaling locks from the CLI"
----
-
-The CLI groups three related actions for sizing a sandbox:
-
-| Command | What it does |
-| --- | --- |
-| [`oc sandbox autoscale`](#oc-sandbox-autoscale-id) | Turn the platform autoscaler on/off and inspect its config |
-| [`oc sandbox scale`](#oc-sandbox-scale-id-memory-mb) | Manually resize once |
-| [`oc sandbox lock`](#oc-sandbox-lock-id) / [`unlock`](#oc-sandbox-unlock-id) / [`lock-status`](#oc-sandbox-lock-status-id) | Freeze or unfreeze the current size |
-
-CPU follows memory per the platform's tier table; you don't pick CPU separately.
-
-For the underlying concepts and how these three modes interact, see the [Elasticity](/sandboxes/elasticity) guide.
-
----
-
-## `oc sandbox autoscale <id>`
-
-Configure or inspect per-sandbox autoscale. [HTTP API →](/api-reference/sandboxes/autoscale)
-
-Run with no flags to print the current configuration:
-
-```bash
-oc sandbox autoscale sb-abc123
-# Autoscale enabled for sb-abc123 (1024–16384 MB)
-```
-
-Enable with bounds:
-
-```bash
-oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384
-```
-
-Disable:
-
-```bash
-oc sandbox autoscale sb-abc123 --off
-```
-
-When enabled, the platform watches memory pressure and resizes the sandbox between `--min` and `--max`:
-
-- **Scale up** on a single 1-min sample above 75 % memory utilization. Cooldown 60 s between up-scales.
-- **Scale down** only when the 1-min, 5-min, AND 15-min averages all sit below 25 %. Cooldown 5 min between down-scales.
-
-The asymmetry is deliberate: rapid response when the user notices lag, conservative shrink after sustained idle.
-
-**Flags**
-
-| Flag | Description |
-| --- | --- |
-| `--on` | Enable autoscale (requires `--min` and `--max`). |
-| `--off` | Disable autoscale. Mutually exclusive with `--on`. |
-| `--min N` | Minimum memory in MB. |
-| `--max N` | Maximum memory in MB. Must be ≥ `--min`. |
-
-**Errors**
-
-- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.
-- `402 Payment Required` — `--max` exceeds your plan cap.
-
----
-
-## `oc sandbox scale <id> <memory-mb>`
-
-Manually resize a sandbox to a specific memory tier. [HTTP API →](/api-reference/sandboxes/scale)
-
-```bash
-oc sandbox scale sb-abc123 8192
-# Scaled sb-abc123 to 8192MB / 400% CPU
-```
-
-A manual scale **disables autoscale** on this sandbox as a side effect — explicit intent overrides the loop. Re-enable with `oc sandbox autoscale --on` if you want size to track load again.
-
-**Errors**
-
-- `scaling_locked` — the sandbox has a scaling lock active. Run `oc sandbox unlock <id>` first.
-- `402 Payment Required` — requested size exceeds your plan cap.
-
----
-
-## `oc sandbox lock <id>`
-
-Pin a sandbox at its current size. [HTTP API →](/api-reference/sandboxes/scaling-lock)
-
-```bash
-oc sandbox lock sb-abc123
-# Sandbox sb-abc123 locked (scaling disabled)
-```
-
-While locked:
-
-- `oc sandbox scale` is rejected with `scaling_locked`.
-- `oc sandbox autoscale --on` is rejected with `scaling_locked`.
-- The platform autoscaler skips the sandbox entirely.
-
-Locking **also** disables autoscale (single knob — "I don't want this scaling, period"). Unlocking does NOT re-enable autoscale; run `oc sandbox autoscale --on` explicitly if you want it back.
-
----
-
-## `oc sandbox unlock <id>`
-
-Clear the scaling lock.
-
-```bash
-oc sandbox unlock sb-abc123
-# Sandbox sb-abc123 unlocked
-```
-
----
-
-## `oc sandbox lock-status <id>`
-
-Print the current scaling-lock state.
-
-```bash
-oc sandbox lock-status sb-abc123
-# Sandbox sb-abc123 is unlocked
-```
diff --git a/docs/reference/python-sdk/scaling.mdx b/docs/reference/python-sdk/scaling.mdx
deleted file mode 100644
index b8138a6f..00000000
--- a/docs/reference/python-sdk/scaling.mdx
+++ /dev/null
@@ -1,171 +0,0 @@
----
-title: "Scaling"
-description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."
----
-
-OpenComputer sandboxes can change size at runtime. There are three knobs:
-
-| What you want | Use |
-| --- | --- |
-| Resize once, predictably | [`scale()`](#sandbox-scale-memory-mb) |
-| Track memory pressure automatically | [`set_autoscale()`](#sandbox-set-autoscale) |
-| Freeze the current size | [`set_scaling_lock()`](#sandbox-set-scaling-lock-locked) |
-
-CPU follows memory per the platform's tier table. You don't pick CPU separately.
-
-## How the three interact
-
-- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable with `set_autoscale(enabled=True, ...)` after if you want.
-- **Setting a scaling lock** disables autoscale at the same time (single knob: "I don't want this scaling, period"). While locked, both `scale()` and `set_autoscale(enabled=True)` raise `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.
-- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap raise `PlanLimitError`.
-
----
-
-## `sandbox.scale(memory_mb)`
-
-Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)
-
-<ParamField body="memory_mb" type="int" required>
- Target memory in MB.
-</ParamField>
-
-**Returns:** `dict` with `sandboxID`, `memoryMB`, `cpuPercent`.
-
-**Raises:**
-
-- `ScalingLockedError` — sandbox has a scaling lock active.
-- `PlanLimitError` — `memory_mb` exceeds the org's plan cap.
-
-```python
-from opencomputer import Sandbox, ScalingLockedError, PlanLimitError
-
-sandbox = await Sandbox.connect("sb-abc123")
-
-try:
- result = await sandbox.scale(memory_mb=8192)
- print(f"scaled to {result['memoryMB']}MB / {result['cpuPercent']}% CPU")
-except ScalingLockedError:
- print("sandbox is locked — unlock to scale")
-except PlanLimitError:
- print("upgrade required for larger instances")
-```
-
----
-
-## `sandbox.set_autoscale(enabled, *, min_memory_mb=None, max_memory_mb=None)`
-
-Enable or disable per-sandbox autoscale.
-
-<ParamField body="enabled" type="bool" required>
- Whether autoscale should be active.
-</ParamField>
-
-<ParamField body="min_memory_mb" type="int">
- Lower bound when `enabled=True`.
-</ParamField>
-
-<ParamField body="max_memory_mb" type="int">
- Upper bound when `enabled=True`. Must be ≥ `min_memory_mb`.
-</ParamField>
-
-**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.
-
-**Raises:**
-
-- `ScalingLockedError` — sandbox has a scaling lock active.
-- `PlanLimitError` — `max_memory_mb` exceeds the org's plan cap.
-
-When `enabled=True`, the platform watches the sandbox's memory pressure and resizes it within the bounds:
-
-- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.
-- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.
-
-The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.
-
-```python
-await sandbox.set_autoscale(
- enabled=True,
- min_memory_mb=1024,
- max_memory_mb=16384,
-)
-```
-
-To turn off:
-
-```python
-await sandbox.set_autoscale(enabled=False)
-```
-
----
-
-## `sandbox.get_autoscale()`
-
-Get the current autoscale configuration.
-
-**Returns:** `dict` with `sandboxID`, `enabled`, `minMemoryMB`, `maxMemoryMB`.
-
-```python
-cfg = await sandbox.get_autoscale()
-if cfg["enabled"]:
- print(f"autoscale {cfg['minMemoryMB']}–{cfg['maxMemoryMB']} MB")
-```
-
----
-
-## `sandbox.set_scaling_lock(locked)`
-
-Lock or unlock the sandbox's resources against any size change.
-
-<ParamField body="locked" type="bool" required>
- `True` to freeze, `False` to allow scaling again.
-</ParamField>
-
-**Returns:** `dict` with `sandboxID`, `locked`.
-
-While locked:
-
-- `scale()` raises `ScalingLockedError`.
-- `set_autoscale(enabled=True)` raises `ScalingLockedError`.
-- The platform autoscaler skips this sandbox entirely.
-
-Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `set_autoscale(enabled=True, ...)` explicitly if you want it back.
-
-```python
-# Pin a sandbox at its current size during a critical workload
-await sandbox.set_scaling_lock(True)
-
-# ...
-
-# Allow scaling again after
-await sandbox.set_scaling_lock(False)
-```
-
----
-
-## `sandbox.get_scaling_lock()`
-
-Get the current scaling-lock state.
-
-**Returns:** `dict` with `sandboxID`, `locked`.
-
----
-
-## Errors
-
-### `ScalingLockedError`
-
-Raised when the sandbox has a scaling lock active. Has a class attribute `code = "scaling_locked"` for parity with the HTTP API's error code.
-
-```python
-from opencomputer import ScalingLockedError
-
-try:
- await sandbox.scale(memory_mb=8192)
-except ScalingLockedError:
- # unlock first, or surface to user
- ...
-```
-
-### `PlanLimitError`
-
-Raised when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.
diff --git a/docs/reference/typescript-sdk/scaling.mdx b/docs/reference/typescript-sdk/scaling.mdx
deleted file mode 100644
index 0b01de58..00000000
--- a/docs/reference/typescript-sdk/scaling.mdx
+++ /dev/null
@@ -1,179 +0,0 @@
----
-title: "Scaling"
-description: "Resize a sandbox manually, autoscale on memory pressure, or freeze its resources."
----
-
-OpenComputer sandboxes can change size at runtime. There are three knobs:
-
-| What you want | Use |
-| --- | --- |
-| Resize once, predictably | [`scale()`](#sandbox-scale-opts) |
-| Track memory pressure automatically | [`setAutoscale()`](#sandbox-setautoscale-opts) |
-| Freeze the current size | [`setScalingLock()`](#sandbox-setscalinglock-locked) |
-
-CPU follows memory per the platform's tier table. You don't pick CPU separately.
-
-## How the three interact
-
-- **Manual `scale()`** disables autoscale on the sandbox as a side effect — explicit user intent overrides the loop. Re-enable autoscale with `setAutoscale({ enabled: true, ... })` after if you want.
-- **Setting a scaling lock** disables autoscale at the same time (single-knob: "I don't want this scaling, period"). While locked, both `scale()` and `setAutoscale({ enabled: true })` reject with `ScalingLockedError`. Unlocking does NOT auto-re-enable autoscale.
-- **Plan caps** apply everywhere. Free-tier orgs are capped at 4 GB. Calls above the cap throw `PlanLimitError`.
-
----
-
-## `sandbox.scale(opts)`
-
-Manually resize the sandbox. [HTTP API →](/api-reference/sandboxes/scale)
-
-<ParamField body="memoryMB" type="number" required>
- Target memory in MB.
-</ParamField>
-
-**Returns:** `Promise<{ sandboxID: string; memoryMB: number; cpuPercent: number }>`
-
-**Throws:**
-
-- `ScalingLockedError` — sandbox has a scaling lock active.
-- `PlanLimitError` — `memoryMB` exceeds the org's plan cap.
-
-```typescript
-import { Sandbox, ScalingLockedError, PlanLimitError } from "@opencomputer/sdk";
-
-const sandbox = await Sandbox.connect("sb-abc123");
-
-try {
- const result = await sandbox.scale({ memoryMB: 8192 });
- console.log(`scaled to ${result.memoryMB}MB / ${result.cpuPercent}% CPU`);
-} catch (err) {
- if (err instanceof ScalingLockedError) {
- console.warn("sandbox is locked — unlock to scale");
- } else if (err instanceof PlanLimitError) {
- console.warn("upgrade required for larger instances");
- } else {
- throw err;
- }
-}
-```
-
----
-
-## `sandbox.setAutoscale(opts)`
-
-Enable or disable per-sandbox autoscale.
-
-<ParamField body="enabled" type="boolean" required>
- Whether autoscale should be active.
-</ParamField>
-
-<ParamField body="minMemoryMB" type="number">
- Lower bound when `enabled=true`.
-</ParamField>
-
-<ParamField body="maxMemoryMB" type="number">
- Upper bound when `enabled=true`. Must be ≥ `minMemoryMB`.
-</ParamField>
-
-**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`
-
-**Throws:**
-
-- `ScalingLockedError` — sandbox has a scaling lock active.
-- `PlanLimitError` — `maxMemoryMB` exceeds the org's plan cap.
-
-When `enabled=true`, the platform watches the sandbox's memory pressure and resizes it within the bounds:
-
-- **Scale up** on a single 1-min sample above 75% memory utilization. Cooldown 60s between up-scales.
-- **Scale down** only when 1-min, 5-min, AND 15-min averages all sit below 25%. Cooldown 5 min between down-scales.
-
-The asymmetry matches user perception: rapid response when the user notices lag, conservative shrink after sustained idle. The 15-min window is the dominant constraint on shrink, so a sandbox that briefly idles and resumes won't sawtooth.
-
-```typescript
-await sandbox.setAutoscale({
- enabled: true,
- minMemoryMB: 1024,
- maxMemoryMB: 16384,
-});
-```
-
-To turn off:
-
-```typescript
-await sandbox.setAutoscale({ enabled: false });
-```
-
----
-
-## `sandbox.getAutoscale()`
-
-Get the current autoscale configuration.
-
-**Returns:** `Promise<{ sandboxID: string; enabled: boolean; minMemoryMB: number; maxMemoryMB: number }>`
-
-```typescript
-const cfg = await sandbox.getAutoscale();
-if (cfg.enabled) {
- console.log(`autoscale ${cfg.minMemoryMB}–${cfg.maxMemoryMB} MB`);
-}
-```
-
----
-
-## `sandbox.setScalingLock(locked)`
-
-Lock or unlock the sandbox's resources against any size change.
-
-<ParamField body="locked" type="boolean" required>
- `true` to freeze, `false` to allow scaling again.
-</ParamField>
-
-**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`
-
-While locked:
-
-- `scale()` rejects with `ScalingLockedError`.
-- `setAutoscale({ enabled: true })` rejects with `ScalingLockedError`.
-- The platform autoscaler skips this sandbox entirely.
-
-Locking ALSO disables autoscale (single knob — "I don't want this scaling"). Unlocking does **not** re-enable autoscale; call `setAutoscale({ enabled: true, ... })` explicitly if you want it back.
-
-```typescript
-// Pin a sandbox at its current size during a critical workload
-await sandbox.setScalingLock(true);
-
-// ...
-
-// Allow scaling again after
-await sandbox.setScalingLock(false);
-```
-
----
-
-## `sandbox.getScalingLock()`
-
-Get the current scaling-lock state.
-
-**Returns:** `Promise<{ sandboxID: string; locked: boolean }>`
-
----
-
-## Errors
-
-### `ScalingLockedError`
-
-Thrown when the sandbox has a scaling lock active. Has a `code` property of `"scaling_locked"` for parity with the HTTP API's error code.
-
-```typescript
-import { ScalingLockedError } from "@opencomputer/sdk";
-
-try {
- await sandbox.scale({ memoryMB: 8192 });
-} catch (err) {
- if (err instanceof ScalingLockedError) {
- // unlock first, or surface to user
- }
-}
-```
-
-### `PlanLimitError`
-
-Thrown when the requested size exceeds the org's plan cap. The HTTP API returns 402 Payment Required for this case.
diff --git a/docs/sandboxes/burst-sandboxes.mdx b/docs/sandboxes/burst-sandboxes.mdx
index bf673033..2ddd8fa3 100644
--- a/docs/sandboxes/burst-sandboxes.mdx
+++ b/docs/sandboxes/burst-sandboxes.mdx
@@ -225,8 +225,8 @@ When OpenComputer receives notice, it runs the hook with the notice window in se
## Related
<CardGroup cols={2}>
- <Card title="Elasticity" href="/sandboxes/elasticity">
- Resource tiers and autoscaling
+ <Card title="Sizing" href="/sandboxes/sizing">
+ Resource tiers and how to choose one
</Card>
<Card title="Checkpoints" href="/sandboxes/checkpoints">
Save and resume sandbox state
diff --git a/docs/sandboxes/elasticity.mdx b/docs/sandboxes/elasticity.mdx
deleted file mode 100644
index 5a1333c5..00000000
--- a/docs/sandboxes/elasticity.mdx
+++ /dev/null
@@ -1,307 +0,0 @@
----
-title: "Elasticity"
-description: "Dynamically scale sandbox memory and CPU — automatically, manually, or via the in-VM API"
----
-
-A sandbox's memory and CPU can be resized at runtime. The platform's recommended path is **Autoscaling** — opt the sandbox in once and we resize it for you based on observed memory pressure. Lower-level controls are also available if you want to drive sizing yourself or freeze it.
-
-CPU scales proportionally to memory in all modes (1 vCPU per ~4 GB up to 16 GB / 4 vCPU). The permissible memory tiers are:
-
-| Memory | vCPU |
-| --- | --- |
-| 1 GB | 1 (best-effort) |
-| 4 GB | 1 |
-| 8 GB | 2 |
-| 16 GB | 4 |
-
-If you want a sandbox to **stay at a fixed size**, see [Locking Resources](#locking-resources).
-
-## Autoscaling
-
-Opt a sandbox into the per-sandbox autoscaler and the platform resizes it for you based on observed memory pressure. Autoscale is **opt-in per sandbox** and **disabled by default**.
-
-This is the recommended way to size a sandbox: turn it on once with bounds you're comfortable with, then leave it. Manual `scale` and the in-VM API are escape hatches for cases where the autoscaler isn't a good fit (e.g. you want a hard guarantee for a benchmark, or you're scripting your own logic).
-
-### Enable
-
-<CodeGroup>
-```typescript TypeScript
-await sandbox.setAutoscale({
- enabled: true,
- minMemoryMB: 1024,
- maxMemoryMB: 16384,
-});
-```
-
-```python Python
-await sandbox.set_autoscale(
- enabled=True,
- min_memory_mb=1024,
- max_memory_mb=16384,
-)
-```
-
-```bash CLI
-oc sandbox autoscale sb-abc123 --on --min 1024 --max 16384
-```
-
-```bash HTTP
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
- -H "X-API-Key: $API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"enabled": true, "minMemoryMB": 1024, "maxMemoryMB": 16384}'
-```
-</CodeGroup>
-
-`minMemoryMB` and `maxMemoryMB` must be values from the tier table above. The autoscaler keeps the sandbox between these bounds, in tier steps.
-
-### Behavior
-
-- **Scale up**: when the sandbox's 1-minute average memory utilization exceeds 75 %, jump to the next tier. 60-second cooldown between up-events.
-- **Scale down**: when **all** of the 1-min, 5-min, and 15-min utilization averages stay below 25 %, drop one tier. 5-minute cooldown between down-events. Down requires at least 15 minutes of low-utilization data, so a brief idle pause won't shrink you.
-- **Manual override**: any explicit `scale` call disables autoscale on that sandbox. Re-enable explicitly via `setAutoscale({ enabled: true, ... })` (or the equivalent in any SDK) if you want it back.
-
-### Disable
-
-<CodeGroup>
-```typescript TypeScript
-await sandbox.setAutoscale({ enabled: false });
-```
-
-```python Python
-await sandbox.set_autoscale(enabled=False)
-```
-
-```bash CLI
-oc sandbox autoscale sb-abc123 --off
-```
-
-```bash HTTP
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/autoscale" \
- -H "X-API-Key: $API_KEY" \
- -d '{"enabled": false}'
-```
-</CodeGroup>
-
-### Inspect
-
-<CodeGroup>
-```typescript TypeScript
-const cfg = await sandbox.getAutoscale();
-// { sandboxID: "sb-...", enabled: true, minMemoryMB: 1024, maxMemoryMB: 16384 }
-```
-
-```python Python
-cfg = await sandbox.get_autoscale()
-# {"sandboxID": "sb-...", "enabled": True, "minMemoryMB": 1024, "maxMemoryMB": 16384}
-```
-
-```bash CLI
-oc sandbox autoscale sb-abc123
-# Autoscale enabled for sb-abc123 (1024–16384 MB)
-```
-
-```bash HTTP
-curl -sf "$API/api/sandboxes/$SANDBOX_ID/autoscale" -H "X-API-Key: $API_KEY"
-# {"sandboxID":"sb-...","enabled":true,"minMemoryMB":1024,"maxMemoryMB":16384}
-```
-</CodeGroup>
-
-## Manual Scaling (Control Plane)
-
-When you want to resize once — predictable size for a benchmark, a one-off scale-up before a known-heavy task, an operator response to an alert — call `scale` from your application or operator tooling:
-
-<CodeGroup>
-```typescript TypeScript
-await sandbox.scale({ memoryMB: 4096 });
-```
-
-```python Python
-await sandbox.scale(memory_mb=4096)
-```
-
-```bash CLI
-oc sandbox scale sb-abc123 4096
-```
-
-```bash HTTP
-curl -sf -X POST "$API/api/sandboxes/$SANDBOX_ID/scale" \
- -H "X-API-Key: $API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"memoryMB": 4096}'
-```
-</CodeGroup>
-
-A manual scale **disables autoscale** on the sandbox — explicit user intent overrides the loop. Re-enable it later if you want size to track load again.
-
-The endpoint can return:
-
-- **403 `scaling_locked`** — the sandbox is locked. See [Locking Resources](#locking-resources).
-- **409 `oom_floor`** — the requested size would force a guest OOM-kill because the current working set exceeds it. Free memory inside the guest, then retry.
-- **402 Payment Required** — the requested size exceeds your plan cap.
-
-## In-VM Scaling
-
-Sandboxes expose an internal metadata API at `http://169.254.169.254` that lets code **inside** the VM scale itself. Useful for workload-aware scripts where the workload knows its own demand better than the platform autoscaler can infer (e.g. "scale up before this build, back down after").
-
-<Note>
- This endpoint is only reachable from inside the sandbox. It is not exposed through the control plane API or SDKs.
-</Note>
-
-### Scale Memory
-
-Send a `POST` to `/v1/scale` with the desired memory in MB. CPU is adjusted proportionally.
-
-```bash
-curl -s -X POST http://169.254.169.254/v1/scale \
- -H "Content-Type: application/json" \
- -d '{"memoryMB": 4096}'
-```
-
-### Check Current Limits
-
-```bash
-curl -s http://169.254.169.254/v1/limits
-```
-
-### Example: Rust Compilation
-
-Rust builds are memory-hungry. You can alias `cargo` to scale up before compilation and scale back down after:
-
-```bash
-alias cargo='_cargo_scaled'
-_cargo_scaled() {
- # Scale up to 16GB / 4 vCPU before build
- curl -sf -X POST http://169.254.169.254/v1/scale \
- -H "Content-Type: application/json" -d '{"memoryMB": 16384}'
-
- # Run the actual cargo command
- command cargo "$@"
- local exit_code=$?
-
- # Scale back down to 4GB / 1 vCPU
- curl -sf -X POST http://169.254.169.254/v1/scale \
- -H "Content-Type: application/json" -d '{"memoryMB": 4096}'
-
- return $exit_code
-}
-```
-
-Add this to your sandbox's `~/.bashrc` or inject it via `sandbox.exec.run` so every `cargo build`, `cargo test`, etc. automatically gets the extra resources.
-
-### Example: Custom Scaling Loop
-
-A simple shell script that monitors memory pressure and scales automatically. Useful when you want fine-grained control inside the sandbox itself; for the platform-managed equivalent see [Autoscaling](#autoscaling) above.
-
-```bash
-#!/bin/sh
-SCALE_API="http://169.254.169.254/v1/scale"
-MIN_MB=1024
-MAX_MB=8192
-SCALE_UP_THRESHOLD=80
-SCALE_DOWN_THRESHOLD=30
-COOLDOWN=30
-last_scale=0
-
-while true; do
- mem_total=$(awk '/MemTotal/{print $2}' /proc/meminfo)
- mem_avail=$(awk '/MemAvailable/{print $2}' /proc/meminfo)
- usage_pct=$(( (mem_total - mem_avail) * 100 / mem_total ))
- total_mb=$((mem_total / 1024))
- now=$(date +%s)
- elapsed=$((now - last_scale))
-
- if [ $usage_pct -gt $SCALE_UP_THRESHOLD ] && [ $elapsed -gt $COOLDOWN ]; then
- new_mb=$((total_mb * 2))
- [ $new_mb -gt $MAX_MB ] && new_mb=$MAX_MB
- if [ $new_mb -gt $total_mb ]; then
- echo "usage=$usage_pct% -> scaling UP to ${new_mb}MB"
- curl -sf -X POST "$SCALE_API" \
- -H "Content-Type: application/json" \
- -d "{\"memoryMB\":$new_mb}"
- last_scale=$now
- fi
- elif [ $usage_pct -lt $SCALE_DOWN_THRESHOLD ] && [ $total_mb -gt $MIN_MB ] && [ $elapsed -gt $COOLDOWN ]; then
- new_mb=$((total_mb / 2))
- [ $new_mb -lt $MIN_MB ] && new_mb=$MIN_MB
- if [ $new_mb -lt $total_mb ]; then
- echo "usage=$usage_pct% -> scaling DOWN to ${new_mb}MB"
- curl -sf -X POST "$SCALE_API" \
- -H "Content-Type: application/json" \
- -d "{\"memoryMB\":$new_mb}"
- last_scale=$now
- fi
- fi
-
- sleep 5
-done
-```
-
-## Locking Resources
-
-If you want a sandbox to **stay at a fixed size** — predictable billing, a benchmark, a long-running pinned workload — lock it. Locking blocks both manual scaling and autoscaling on the sandbox.
-
-<CodeGroup>
-```typescript TypeScript
-await sandbox.setScalingLock(true);
-```
-
-```python Python
-await sandbox.set_scaling_lock(True)
-```
-
-```bash CLI
-oc sandbox lock sb-abc123
-```
-
-```bash HTTP
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
- -H "X-API-Key: $API_KEY" \
- -H "Content-Type: application/json" \
- -d '{"locked": true}'
-```
-</CodeGroup>
-
-While locked:
-
-- `scale` returns **403** `scaling_locked`
-- `setAutoscale({ enabled: true })` returns **403** `scaling_locked`
-- The autoscaler skips the sandbox
-
-Locking automatically disables autoscale on the sandbox, so you have a single user-facing toggle. Unlocking does **not** auto-re-enable autoscale; turn it back on explicitly if you want it.
-
-<CodeGroup>
-```typescript TypeScript
-// Unlock
-await sandbox.setScalingLock(false);
-
-// Inspect
-const lock = await sandbox.getScalingLock();
-// { sandboxID: "sb-...", locked: false }
-```
-
-```python Python
-# Unlock
-await sandbox.set_scaling_lock(False)
-
-# Inspect
-lock = await sandbox.get_scaling_lock()
-# {"sandboxID": "sb-...", "locked": False}
-```
-
-```bash CLI
-oc sandbox unlock sb-abc123
-oc sandbox lock-status sb-abc123
-```
-
-```bash HTTP
-# Unlock
-curl -sf -X PUT "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" \
- -H "X-API-Key: $API_KEY" \
- -d '{"locked": false}'
-
-# Inspect
-curl -sf "$API/api/sandboxes/$SANDBOX_ID/scaling-lock" -H "X-API-Key: $API_KEY"
-# {"sandboxID":"sb-...","locked":false}
-```
-</CodeGroup>
diff --git a/docs/sandboxes/sizing.mdx b/docs/sandboxes/sizing.mdx
new file mode 100644
index 00000000..25bee7f5
--- /dev/null
+++ b/docs/sandboxes/sizing.mdx
@@ -0,0 +1,66 @@
+---
+title: "Sizing"
+description: "Choose a sandbox's memory and CPU at create time"
+---
+
+A sandbox's memory is chosen when you create it and stays fixed for the
+sandbox's lifetime. CPU is allocated proportionally to memory.
+
+| Memory | vCPU |
+| --- | --- |
+| 1 GB | best-effort |
+| 4 GB (default) | 1 |
+| 8 GB | 2 |
+
+Omitting `memoryMB` gives you the 4 GB default.
+
+## Choosing a size
+
+Pass `memoryMB` at create:
+
+<CodeGroup>
+```typescript TypeScript
+const sandbox = await Sandbox.create({ memoryMB: 8192 });
+```
+
+```bash CLI
+oc sandbox create --memory 8192
+```
+
+```bash HTTP
+curl -sf -X POST "$API/api/sandboxes" \
+ -H "X-API-Key: $API_KEY" \
+ -H "Content-Type: application/json" \
+ -d '{"memoryMB": 8192}'
+```
+</CodeGroup>
+
+`cpuCount` may be given instead and the matching memory tier is inferred. If both
+are supplied they must describe the same tier.
+
+<Note>
+ The 1 GB tier provides CPU on a best-effort basis. For CPU-sensitive work, use
+ 4 GB or above.
+</Note>
+
+## Sizes outside the table
+
+A request for a size that is not offered is **rejected**, not rounded down. You
+will never be quietly given a smaller sandbox than you asked for, and never
+billed for a size you did not receive.
+
+Sizes above 8 GB are not available self-serve. If you need more, contact us —
+larger configurations are handled out of band.
+
+## Size is fixed for the sandbox's lifetime
+
+Memory cannot be changed after a sandbox starts. Size is a property of the
+machine the sandbox runs on, decided when that machine boots, so there is no
+resize operation to call.
+
+If a workload needs more memory than it was created with, create a new sandbox
+at the larger tier. Where you need to carry work across, write what matters to
+the workspace and read it back on the new sandbox.
+
+Plan for the peak rather than the average: a sandbox that occasionally needs
+8 GB should be created at 8 GB.
diff --git a/internal/api/backend.go b/internal/api/backend.go
index 494bf83f..1ca7fcf4 100644
--- a/internal/api/backend.go
+++ b/internal/api/backend.go
@@ -198,6 +198,31 @@ type Placer interface {
Release(ctx context.Context, sandboxID, workerID string)
}
+// SelfStocking is a Backend that keeps its own warm stock.
+//
+// The cell's Postgres pool belongs to the QEMU fleet: rows claimed by
+// resume+rebind on a worker. A backend that manufactures and holds its own boxes
+// has a different supply, and consulting that pool for one of its creates is not
+// a miss that costs nothing — the claim takes row locks, so under a burst it
+// serializes creates behind a query that could never have succeeded.
+//
+// Optional, and absent means "draws from the cell pool", so the QEMU fleet and
+// anything predating this interface behave exactly as before.
+type SelfStocking interface {
+ Backend
+
+ // ServesOwnStock reports that this backend supplies warm hosts from inside
+ // Claim, so the cell pool must not be consulted on its behalf.
+ ServesOwnStock() bool
+}
+
+// servesOwnStock reports whether a backend supplies its own warm hosts. False
+// for nil and for anything not implementing SelfStocking.
+func servesOwnStock(b Backend) bool {
+ ss, ok := b.(SelfStocking)
+ return ok && ss.ServesOwnStock()
+}
+
// Hibernator is a Backend that parks and revives a sandbox in process.
//
// Optional in the same way Placer is, and for the same reason: the capability
diff --git a/internal/api/backend_conformance_test.go b/internal/api/backend_conformance_test.go
index efe51f5e..6161a4a6 100644
--- a/internal/api/backend_conformance_test.go
+++ b/internal/api/backend_conformance_test.go
@@ -58,6 +58,54 @@ var conformanceBackends = []conformanceBackend{
hostIDPrefix + "abc123",
},
},
+ {
+ // The direct-exec data plane over the SAME hosts. Its identity answers
+ // are deliberately identical to vmhost's — the worker_id names the box,
+ // and switching data planes must not orphan the other one's rows — so
+ // running the whole contract against it is what proves that stayed true.
+ name: "vmhost-lite",
+ buildDisabled: func() Backend { return (*liteBackend)(nil) },
+ ownedWorkerID: microvmWorkerID("abc123"),
+ foreignWorkerIDs: []string{
+ "w-azure-osb-worker-2512f614",
+ "worker-eastus2-7",
+ "",
+ "vmhost:",
+ "vmhost",
+ "microvm:",
+ hostIDPrefix + "abc123",
+ },
+ },
+}
+
+// The two managed backends must never both be registered on a cell: they
+// manufacture from one image against one regional quota, and two fillers each
+// believing they own the fleet overrun it and starve each other. The exclusion
+// lives in newMicrovmBackend, which stands down when the lite flag is set.
+func TestManagedBackendsAreMutuallyExclusive(t *testing.T) {
+ t.Setenv("OPENSANDBOX_MICROVM_ENABLED", "1")
+ t.Setenv("OPENSANDBOX_MICROVM_IMAGE_ARN", "arn:aws:test:::image/x")
+ t.Setenv("OPENSANDBOX_MICROVM_LITE", "1")
+
+ // No AWS call is reached: the stand-down is checked before the client is
+ // built, which is also what makes this test runnable without credentials.
+ b, err := newMicrovmBackend(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("newMicrovmBackend: %v", err)
+ }
+ if b != nil {
+ t.Fatal("the agent-tunnel backend built itself while the direct-exec one is enabled — both would fill from the same quota")
+ }
+}
+
+// ...and with the flag off, nothing changes for the path production runs. A
+// regression here would silently take prod's MicroVM cells off their backend.
+func TestAgentBackendStillBuildsWithoutTheLiteFlag(t *testing.T) {
+ t.Setenv("OPENSANDBOX_MICROVM_ENABLED", "1")
+ t.Setenv("OPENSANDBOX_MICROVM_LITE", "")
+ if liteEnabled() {
+ t.Fatal("liteEnabled() is true with the flag unset")
+ }
}
// A backend must recognize what it owns. This is the durable identity question
diff --git a/internal/api/create_flow.go b/internal/api/create_flow.go
index 8c432388..b1fc42d3 100644
--- a/internal/api/create_flow.go
+++ b/internal/api/create_flow.go
@@ -100,9 +100,11 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
}
}()
+ tr := traceFrom(ctx)
t := time.Now()
workerID, err = steps.claim(ctx)
claimMs = time.Since(t).Milliseconds()
+ tr.mark("claim")
if err != nil {
return "", err
}
@@ -115,6 +117,7 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
t = time.Now()
aerr := steps.activate(ctx, workerID)
activateMs = time.Since(t).Milliseconds()
+ tr.mark("activate")
if aerr != nil {
if steps.cleanup != nil {
steps.cleanup(ctx, workerID, aerr)
diff --git a/internal/api/create_trace.go b/internal/api/create_trace.go
new file mode 100644
index 00000000..e31cc7cf
--- /dev/null
+++ b/internal/api/create_trace.go
@@ -0,0 +1,138 @@
+package api
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "strings"
+ "sync"
+ "time"
+)
+
+// create_trace.go — per-create step timing, for finding serialization.
+//
+// The existing create timing log fires only past a threshold and only covers
+// runCreate's four steps, which is the wrong shape for this question. A burst of
+// twenty creates that each take 3ms of work but come back at 1, 6, 24, 38, 53ms
+// has no slow step at all — it has a queue — and averaging or thresholding hides
+// exactly that.
+//
+// So this records two things a duration alone cannot express:
+//
+// enter when the handler was entered, as an offset from process start
+// each step's own elapsed time
+//
+// Comparing `enter` across a burst is what separates the two explanations. If
+// all twenty enter together and exit staggered, something inside serializes
+// them. If they enter staggered, the queue is upstream of this handler and no
+// amount of work removed from it will help.
+//
+// Off by default. One line per create is far too much for a cell serving real
+// traffic; set OPENSANDBOX_CREATE_TRACE=1 on the cell being measured.
+
+// createTraceEnabled is read once. A per-create getenv on the hot path would be
+// its own small tax on the thing being measured.
+var createTraceEnabled = os.Getenv("OPENSANDBOX_CREATE_TRACE") == "1"
+
+// traceEpoch anchors `enter` offsets. Absolute wall-clock would work too, but a
+// process-relative millisecond count is far easier to compare by eye across
+// twenty log lines.
+var traceEpoch = time.Now()
+
+type createTraceCtxKey struct{}
+
+type createTrace struct {
+ // kind names the line ("createtrace", "exectrace", …) so more than one hot
+ // path can use this machinery and still be greppable apart.
+ kind string
+ sandboxID string
+ start time.Time
+
+ mu sync.Mutex
+ last time.Time
+ marks []traceMark
+}
+
+type traceMark struct {
+ label string
+ dur time.Duration
+}
+
+// newCreateTrace returns a trace, or nil when tracing is off. Every method is
+// nil-safe, so call sites stay unconditional.
+func newCreateTrace() *createTrace {
+ return newTrace("createtrace")
+}
+
+// newExecTrace traces the exec hot path. Exec is half of TTI and had no
+// per-step timing at all, which meant a burst whose exec leg degraded was
+// indistinguishable from one whose create leg did.
+func newExecTrace() *createTrace {
+ return newTrace("exectrace")
+}
+
+func newTrace(kind string) *createTrace {
+ if !createTraceEnabled {
+ return nil
+ }
+ now := time.Now()
+ return &createTrace{kind: kind, start: now, last: now}
+}
+
+// mark records the time since the previous mark.
+func (t *createTrace) mark(label string) {
+ if t == nil {
+ return
+ }
+ now := time.Now()
+ t.mu.Lock()
+ t.marks = append(t.marks, traceMark{label: label, dur: now.Sub(t.last)})
+ t.last = now
+ t.mu.Unlock()
+}
+
+func (t *createTrace) setSandboxID(id string) {
+ if t == nil {
+ return
+ }
+ t.mu.Lock()
+ t.sandboxID = id
+ t.mu.Unlock()
+}
+
+// emit writes the line. Sub-millisecond steps are reported in microseconds
+// rather than rounded to 0 — a step that is genuinely free and a step that is
+// 900µs look identical at millisecond resolution, and twenty of the latter is
+// the whole effect being chased.
+func (t *createTrace) emit() {
+ if t == nil {
+ return
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ var b strings.Builder
+ fmt.Fprintf(&b, "%s %s enter=%dms total=%dus",
+ t.kind,
+ t.sandboxID,
+ t.start.Sub(traceEpoch).Milliseconds(),
+ time.Since(t.start).Microseconds())
+ for _, m := range t.marks {
+ fmt.Fprintf(&b, " %s=%dus", m.label, m.dur.Microseconds())
+ }
+ log.Print(b.String())
+}
+
+func withCreateTrace(ctx context.Context, t *createTrace) context.Context {
+ if t == nil {
+ return ctx
+ }
+ return context.WithValue(ctx, createTraceCtxKey{}, t)
+}
+
+// traceFrom recovers the trace a caller started, so the steps that live in
+// another function can add to the same line instead of a second one.
+func traceFrom(ctx context.Context) *createTrace {
+ t, _ := ctx.Value(createTraceCtxKey{}).(*createTrace)
+ return t
+}
diff --git a/internal/api/edge_claim_microvm.go b/internal/api/edge_claim_microvm.go
index 0b417b95..bfdd67c6 100644
--- a/internal/api/edge_claim_microvm.go
+++ b/internal/api/edge_claim_microvm.go
@@ -337,7 +337,18 @@ func (b *microvmBackend) warmReservedTunnels() {
// first exec. See the keepalive block in internal/awsvm/agent.go.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
- if ok, failed := b.manager.PingAgents(ctx, reserved); ok+failed > 0 {
- log.Printf("microvm: keepalive pinged %d reserved box(es) (%d failed)", ok, failed)
+ if ok, failed, retired, sample := b.manager.PingAgents(ctx, reserved); ok+failed > 0 {
+ // The sampled cause is the point of the line. A bare failure count is what
+ // let the stock pool decay from 130 live tunnels to 5 without anything in
+ // the log naming a reason.
+ msg := fmt.Sprintf("microvm: keepalive pinged %d reserved box(es) (%d failed", ok, failed)
+ if retired > 0 {
+ msg += fmt.Sprintf(", %d channel(s) retired for re-dial", retired)
+ }
+ msg += ")"
+ if sample != nil {
+ msg += fmt.Sprintf("; first failure: %v", sample)
+ }
+ log.Print(msg)
}
}
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 012835e5..69dd507b 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -446,6 +446,13 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
Timeout: req.Timeout,
}
+ // Exec is half of TTI and was the only leg with no per-step timing, so a
+ // burst that degraded here looked the same as one that degraded in create.
+ // `enter` separates "this handler is slow" from "the queue is upstream".
+ tr := newExecTrace()
+ tr.setSandboxID(id)
+ defer tr.emit()
+
var session *sandbox.ExecSessionHandle
routeOp := func(_ context.Context) error {
@@ -463,6 +470,8 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
}
+ // Everything up to here is route + CreateSession — the dial/bind to the box.
+ tr.mark("session")
// Fast-exec fold: hold the response briefly and, if the command exits inside
// the window, return the legacy inline result shape (no execId). The SDK's
@@ -472,13 +481,20 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
// so the GetResult read below is final. Truncated output falls through to
// the handle shape — ProcessResult can't carry the truncated flag.
if hold := execHoldMs("OPENSANDBOX_EXEC_INLINE_HOLD_MS", 400*time.Millisecond); hold > 0 {
- if res, ok := s.awaitExecDone(c.Request().Context(), id, session.ID, hold); ok && res.ExitCode != nil && !res.Truncated {
+ res, ok := s.awaitExecDone(c.Request().Context(), id, session.ID, hold)
+ // `hold` is the command actually running when it lands well under the
+ // budget, and the full hold budget when it does not — so a value pinned
+ // at the budget means the fold MISSED and the client fell onto its poll.
+ tr.mark("hold")
+ if ok && res.ExitCode != nil && !res.Truncated {
+ tr.mark("inline")
return c.JSON(http.StatusOK, types.ProcessResult{
ExitCode: *res.ExitCode,
Stdout: string(res.Stdout),
Stderr: string(res.Stderr),
})
}
+ tr.mark("holdmiss")
}
return c.JSON(http.StatusAccepted, types.ExecRunResponse{
@@ -502,6 +518,13 @@ func (s *Server) execResult(c echo.Context) error {
id := c.Param("id")
sessionID := c.Param("sessionID")
+ // A poll only happens when the inline fold missed, so these lines appearing
+ // at all is itself the signal — and their count says how deep the SDK's
+ // retry ladder went.
+ tr := newTrace("resulttrace")
+ tr.setSandboxID(id)
+ defer tr.emit()
+
var res *types.ExecSessionResult
routeOp := func(_ context.Context) error {
@@ -526,11 +549,13 @@ func (s *Server) execResult(c echo.Context) error {
// retry ladder. Done closes only after ExitCode is captured, so the re-read
// is final. Route already ensured the sandbox is running; the re-read is a
// local scrollback+exit-code snapshot, no re-route needed.
+ tr.mark("read")
if res.Running {
if hold := execHoldMs("OPENSANDBOX_EXEC_RESULT_HOLD_MS", 500*time.Millisecond); hold > 0 {
if res2, ok := s.awaitExecDone(c.Request().Context(), id, sessionID, hold); ok {
res = res2
}
+ tr.mark("longpoll")
if s.router != nil {
s.router.Touch(id) // the hold was interaction; keep the idle timer honest
}
diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.go
index 8bd7b591..63515e5a 100644
--- a/internal/api/internal_sandbox.go
+++ b/internal/api/internal_sandbox.go
@@ -1,6 +1,7 @@
package api
import (
+ "context"
"net/http"
"strings"
@@ -65,6 +66,13 @@ func (s *Server) capTokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
// return the same body as POST /api/sandboxes. The edge records the resulting
// sandbox in D1's sandboxes_index — we don't touch any global tables.
func (s *Server) internalCreateSandbox(c echo.Context) error {
+ // Started at the very top so `enter` reflects when this handler actually got
+ // the request — the gap between entries across a burst is what says whether
+ // the queue is in here or in front of us.
+ tr := newCreateTrace()
+ defer tr.emit()
+ c.SetRequest(c.Request().WithContext(withCreateTrace(c.Request().Context(), tr)))
+
claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)
if claims == nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": "missing capability claims"})
@@ -85,7 +93,18 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
// and lazily materialize the row here. Plan comes from the cap-token so
// the worker's event resolver can tag usage_tick events correctly.
if s.store != nil {
- if upErr := s.store.UpsertOrgFromCapToken(c.Request().Context(), orgID, claims.Plan, claims.BillingProvider); upErr != nil {
+ // Memoized per org — see internal/api/materialize.go. Both statements
+ // below are an upsert against ONE row, so running them on every create
+ // made concurrent creates for an org queue on a Postgres row lock rather
+ // than run in parallel.
+ //
+ // The key carries the plan and provider, so a change to either misses the
+ // memo and writes through immediately instead of waiting out the TTL.
+ tr.mark("pre")
+ orgKey := "org:" + orgID.String() + ":" + claims.Plan + ":" + claims.BillingProvider
+ if upErr := s.materialize.ensure(c.Request().Context(), orgKey, func(ctx context.Context) error {
+ return s.store.UpsertOrgFromCapToken(ctx, orgID, claims.Plan, claims.BillingProvider)
+ }); upErr != nil {
// Non-fatal — the create may still succeed; downstream gates fall through
// when the row is missing. Logged so ops can investigate persistent failures.
c.Logger().Errorf("upsert org from cap-token: %v", upErr)
@@ -97,13 +116,21 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
// exec/wake/etc requests return "sandbox not found".
if claims.UserID != nil {
if uid, err := uuid.Parse(*claims.UserID); err == nil {
- if upErr := s.store.UpsertUserFromCapToken(c.Request().Context(), uid, orgID); upErr != nil {
+ // Memoized too, and for a stronger reason: this one is
+ // ON CONFLICT DO NOTHING, so after the first create it is pure
+ // contention — every subsequent statement takes the lock, finds
+ // the row, and writes nothing.
+ if upErr := s.materialize.ensure(c.Request().Context(), "user:"+uid.String(), func(ctx context.Context) error {
+ return s.store.UpsertUserFromCapToken(ctx, uid, orgID)
+ }); upErr != nil {
c.Logger().Errorf("upsert user from cap-token: %v", upErr)
}
}
}
}
+ tr.mark("upsert")
+
var cfg types.SandboxConfig
if err := c.Bind(&cfg); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
@@ -130,6 +157,7 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
if cfg.DiskMB == 0 {
cfg.DiskMB = 20480
}
+ tr.mark("bind")
if err := types.ValidateResourceTier(&cfg); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
diff --git a/internal/api/lite_backend.go b/internal/api/lite_backend.go
new file mode 100644
index 00000000..ad1aff83
--- /dev/null
+++ b/internal/api/lite_backend.go
@@ -0,0 +1,480 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log"
+ "os"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/internal/awsvmlite"
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/worker"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/redis/go-redis/v9"
+)
+
+// lite_backend.go — the same MicroVM fleet, reached without a tunnel.
+//
+// This is a SECOND way of talking to the boxes microvm_backend.go already
+// launches, not a second fleet: same image, same region, same idle policy, same
+// regional quota, built from the same newMicrovmClient. What differs is the data
+// plane. Where that backend carries gRPC to osb-agent inside a WebSocket — the
+// only way to reach it, because Lambda's proxy strips the HTTP/2 trailers gRPC
+// reports status in — this one issues a plain HTTPS POST to a hook endpoint in
+// the guest. See internal/awsvmlite for the measurement that motivated it.
+//
+// The two are mutually exclusive on a cell, because they would otherwise
+// compete for the same regional quota while each believed it owned the fleet.
+// OPENSANDBOX_MICROVM_LITE=1 selects this one; anything else keeps the agent
+// path, which is what production runs.
+//
+// Deliberately absent, relative to the agent path: hibernate/wake, file
+// transfer, streaming, PTY, checkpoints, edge-claim, and the warm-tunnel tier.
+// Their absence is the experiment. What remains is create, exec, destroy.
+
+// liteEnabled reports whether this cell serves MicroVMs over the direct exec
+// path instead of the agent tunnel. Requires the MicroVM backend to be enabled
+// at all — this is a choice of data plane, not an independent runtime.
+func liteEnabled() bool {
+ return microvmEnabled() && os.Getenv("OPENSANDBOX_MICROVM_LITE") == "1"
+}
+
+type liteBackend struct {
+ client *awsvm.Client
+ mgr *awsvmlite.Manager
+ // sm is the sandbox.Manager face the control plane's data-plane routes
+ // dispatch through. One instance, shared: it holds no state of its own.
+ sm *awsvmlite.SandboxManager
+
+ stopRun context.CancelFunc
+ usageTicker *worker.UsageTicker
+ eventPub *worker.RedisEventPublisher
+ capacity *controlplane.CapacityReporter
+}
+
+// newLiteBackend builds the direct-exec MicroVM backend, or returns nil if this
+// cell is not configured for it.
+func newLiteBackend(ctx context.Context) (*liteBackend, error) {
+ if !liteEnabled() {
+ return nil, nil
+ }
+ client, err := newMicrovmClient(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ // Warm target falls back to the agent path's pool target so a cell that is
+ // switched over keeps the depth it was sized for, rather than silently
+ // dropping to a default and cold-launching every create.
+ warm := envInt("OPENSANDBOX_MICROVM_LITE_WARM", envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
+
+ mgr := awsvmlite.New(client, awsvmlite.Config{
+ WarmTarget: warm,
+ TouchInterval: time.Duration(
+ envInt("OPENSANDBOX_MICROVM_LITE_TOUCH_SECONDS", 300)) * time.Second,
+ })
+ runCtx, stop := context.WithCancel(context.Background())
+ b := &liteBackend{client: client, mgr: mgr, sm: awsvmlite.NewSandboxManager(mgr), stopRun: stop}
+ go mgr.Run(runCtx)
+
+ log.Printf("vmhost-lite: backend enabled (region=%s warm=%d) — direct exec, no agent tunnel",
+ client.Config().Region, warm)
+ return b, nil
+}
+
+// ── Backend ─────────────────────────────────────────────────────────────────
+
+// Compile-time proof this satisfies the dispatch seam, for the same reason the
+// agent-path backend asserts it: a signature drift here surfaces as a silent
+// fall-through to the worker path rather than a build failure.
+var _ Placer = (*liteBackend)(nil)
+
+func (b *liteBackend) Name() string { return "vmhost-lite" }
+
+// WorkerIDPrefixes and OwnsWorkerID are deliberately IDENTICAL to the agent
+// path's. A worker_id names which box holds a sandbox, and the box is the same
+// box — switching data planes must not orphan the rows written by the other one,
+// because a row nothing claims is a box nothing terminates.
+func (b *liteBackend) WorkerIDPrefixes() []string {
+ return []string{microvmWorkerPrefix, legacyWorkerPrefix}
+}
+
+func (b *liteBackend) OwnsWorkerID(workerID string) bool {
+ _, ok := parseMicrovmWorkerID(workerID)
+ return ok
+}
+
+// Route reports whether this backend holds the sandbox, from its in-memory
+// binding only — never an availability check. False sends the caller to another
+// backend, so "mine but sick" must not look like "not mine".
+func (b *liteBackend) Route(_ context.Context, sandboxID string) (sandbox.Manager, bool) {
+ if b == nil {
+ return nil, false
+ }
+ if _, ok := b.mgr.BoxFor(sandboxID); !ok {
+ return nil, false
+ }
+ return b.sm, true
+}
+
+// Capacity reports a constant 1 available, as the agent path does and for the
+// same reason: the real ceiling is an AWS regional quota far above current use,
+// and advertising warm depth would 503 creates this backend can serve. The
+// freshness of the report is the load-bearing half — the edge drops a cell whose
+// capacity_updated_at is older than 120s, so this doubles as a heartbeat.
+func (b *liteBackend) Capacity() (healthy, available, running int) {
+ if b == nil {
+ return 0, 0, 0
+ }
+ return 1, 1, len(b.mgr.Bound())
+}
+
+// Close stops the warm-set loop and gives the stock back.
+//
+// Not optional: a redeploy that abandons warm boxes leaks a full set on every
+// rollout, and each one bills compute and holds regional memory quota until the
+// 8h service cap. Bound sandboxes are left alone — they belong to customers, and
+// the reconciler re-adopts them on the way back up.
+func (b *liteBackend) Close() {
+ if b == nil {
+ return
+ }
+ if b.usageTicker != nil {
+ stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _ = b.usageTicker.Stop(stopCtx)
+ cancel()
+ }
+ // After the ticker, so its final slices are in SQLite before the publisher
+ // drains them.
+ if b.eventPub != nil {
+ stopCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ _ = b.eventPub.Stop(stopCtx)
+ cancel()
+ }
+ if b.capacity != nil {
+ b.capacity.Stop()
+ }
+ b.stopRun()
+ drainCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if n := b.mgr.DrainWarm(drainCtx); n > 0 {
+ log.Printf("vmhost-lite: released %d warm box(es) on shutdown", n)
+ }
+}
+
+// ── Placer ──────────────────────────────────────────────────────────────────
+
+// Accepts mirrors the agent path exactly — same runtime assignment, same
+// template rule. It has to: an org pinned to the MicroVM runtime reaches
+// whichever of the two backends this cell registered, and a cell that accepted
+// a different set of creates depending on its data plane would make the choice
+// visible to customers.
+func (b *liteBackend) Accepts(p placement) bool {
+ if b == nil {
+ return false
+ }
+ if p.runtime != runtimeMicrovm {
+ return false
+ }
+ if p.cfg.Template != "" && p.cfg.Template != "default" && p.cfg.Template != poolTemplateName() {
+ return false
+ }
+ return true
+}
+
+// Claim pops a warm box, or launches one when the set is empty.
+//
+// A miss is slow (a cold launch, ~3s) but not an error — the warm set is a
+// latency optimization, not the capacity limit.
+func (b *liteBackend) Claim(ctx context.Context, p placement) (string, error) {
+ if b == nil {
+ return "", errors.New("vmhost-lite: backend disabled")
+ }
+ start := time.Now()
+ box, warm, err := b.mgr.Claim(ctx, p.sandboxID, awsvmlite.Meta{
+ Template: p.cfg.Template,
+ MemoryMB: p.cfg.MemoryMB,
+ CPUCount: p.cfg.CpuCount,
+ })
+ if err != nil {
+ return "", err
+ }
+ if !warm {
+ log.Printf("vmhost-lite: COLD CREATE %s -> %s in %s (warm set was empty)",
+ p.sandboxID, box.MicrovmID, time.Since(start).Round(time.Millisecond))
+ }
+ return microvmWorkerID(box.MicrovmID), nil
+}
+
+// Activate has nothing to do: Claim returns a box that is already RUNNING.
+func (b *liteBackend) Activate(_ context.Context, a activation) (activated, error) {
+ return activated{sandboxID: a.sandboxID, status: "running"}, nil
+}
+
+// RequiresPersistedRow is true: this backend rebuilds its bindings FROM these
+// rows after a restart (see Restore), so a box with no row is one nothing will
+// ever terminate.
+func (b *liteBackend) RequiresPersistedRow() bool { return true }
+
+// DefersPersist is true: Claim binds sandbox→box in memory before it returns,
+// so exec, destroy and routing all resolve without reading the row.
+func (b *liteBackend) DefersPersist() bool { return true }
+
+// Release terminates a box whose create failed after Claim. Merely forgetting it
+// would leave one billing with nothing tracking it.
+func (b *liteBackend) Release(ctx context.Context, sandboxID, _ string) {
+ if b == nil {
+ return
+ }
+ if err := b.mgr.Destroy(ctx, sandboxID); err != nil {
+ log.Printf("vmhost-lite: release %s: %v", sandboxID, err)
+ }
+}
+
+// ── Reconciliation ──────────────────────────────────────────────────────────
+
+// Restore rebuilds the sandbox→box map from the database after a restart.
+//
+// Nothing here survives the process, but the boxes do. Skipping this leaves
+// live sandboxes simultaneously unroutable and unreapable — billing until the
+// 8h cap with nothing able to find them.
+func (b *liteBackend) Restore(ctx context.Context, store *db.Store) {
+ b.Reconcile(ctx, store)
+}
+
+func (b *liteBackend) Reconcile(ctx context.Context, store *db.Store) {
+ if b == nil || store == nil {
+ return
+ }
+ rows, err := store.ListMicrovmSessions(ctx, b.WorkerIDPrefixes())
+ if err != nil {
+ log.Printf("vmhost-lite: reconcile query failed: %v", err)
+ return
+ }
+ bound := b.mgr.Bindings()
+
+ var adopted, closed int
+ seen := make(map[string]struct{}, len(rows))
+ for _, r := range rows {
+ seen[r.SandboxID] = struct{}{}
+ microvmID, ok := parseMicrovmWorkerID(r.WorkerID)
+ if !ok {
+ continue
+ }
+ if _, held := bound[r.SandboxID]; held {
+ continue
+ }
+ // Sizing is re-derived from the row rather than defaulted, so a restart
+ // does not silently re-meter every sandbox at the default tier for the
+ // rest of its life.
+ var meta awsvmlite.Meta
+ if len(r.Config) > 0 {
+ var cfg types.SandboxConfig
+ if err := json.Unmarshal(r.Config, &cfg); err != nil {
+ log.Printf("vmhost-lite: reconcile %s: config unmarshal failed (%v) — adopting with defaults", r.SandboxID, err)
+ } else {
+ meta = awsvmlite.Meta{Template: cfg.Template, MemoryMB: cfg.MemoryMB, CPUCount: cfg.CpuCount}
+ }
+ }
+ alive, err := b.mgr.Adopt(ctx, r.SandboxID, microvmID, meta)
+ if err != nil {
+ // Could not prove anything. Leaving the row alone is the safe
+ // direction: a transient describe failure must never close out a
+ // live sandbox.
+ continue
+ }
+ if !alive {
+ msg := "microvm no longer exists"
+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)
+ closed++
+ continue
+ }
+ adopted++
+ }
+
+ // The mirror image: a binding whose row has reached a terminal state by some
+ // path that never called Kill. Nothing else would ever drop it, and it would
+ // keep being metered.
+ var forgotten int
+ for sandboxID := range bound {
+ if _, ok := seen[sandboxID]; ok {
+ continue
+ }
+ alive, err := b.mgr.Alive(ctx, sandboxID)
+ if err != nil || alive {
+ continue
+ }
+ b.mgr.Forget(sandboxID)
+ forgotten++
+ }
+
+ if adopted > 0 || closed > 0 || forgotten > 0 {
+ log.Printf("vmhost-lite: reconciled — adopted %d, closed %d dead row(s), forgot %d dead binding(s)",
+ adopted, closed, forgotten)
+ }
+}
+
+// StartReconciler sweeps on a ticker for the life of the process. Nothing
+// reports in for these boxes — no worker exists — so this is the only thing that
+// ever notices one dying.
+func (b *liteBackend) StartReconciler(ctx context.Context, store *db.Store) {
+ if b == nil || store == nil {
+ return
+ }
+ go func() {
+ t := time.NewTicker(microvmReconcileInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ b.Reconcile(ctx, store)
+ }
+ }
+ }()
+}
+
+// ── Billing ─────────────────────────────────────────────────────────────────
+
+// StartUsageTicker meters these sandboxes. There is no worker to emit ticks for
+// them, so the control plane does it over the same sandbox.Manager interface.
+func (b *liteBackend) StartUsageTicker(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager) {
+ if b == nil {
+ return
+ }
+ t := worker.NewUsageTicker(b.sm, sandboxDBs, 20*time.Second, 10)
+ if t == nil {
+ // Said loudly: silent non-billing is the failure mode nobody notices.
+ log.Printf("vmhost-lite: WARNING usage ticker disabled — sandboxes will not be metered")
+ return
+ }
+ b.usageTicker = t
+ t.Start(ctx)
+ log.Printf("vmhost-lite: usage ticker started")
+}
+
+// StartEventPublisher drains those ticks to the cell's Redis stream. Without
+// this half the ticks sit on local disk and are never billed — and every log
+// line still says metering is working.
+func (b *liteBackend) StartEventPublisher(ctx context.Context, sandboxDBs *sandbox.SandboxDBManager, rdb *redis.Client, cellID string, store *db.Store) {
+ if b == nil {
+ return
+ }
+ if sandboxDBs == nil || rdb == nil || cellID == "" {
+ log.Printf("vmhost-lite: WARNING event publisher disabled (sandboxDBs=%v redis=%v cellID=%q) — usage ticks stay on local disk",
+ sandboxDBs != nil, rdb != nil, cellID)
+ return
+ }
+
+ // events-ingest drops a tick whose worker_id disagrees with
+ // sandboxes_index.worker_id, and each of these sandboxes has its own, so the
+ // id has to be resolved per sandbox rather than stamped fleet-wide.
+ workerIDs := func(sandboxID string) (string, bool) {
+ box, ok := b.mgr.BoxFor(sandboxID)
+ if !ok {
+ return "", false
+ }
+ return microvmWorkerID(box.MicrovmID), true
+ }
+
+ var meta worker.MetadataResolver
+ if store != nil {
+ meta = func(sandboxID string) (string, string, bool) {
+ lookupCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ orgIDStr, err := store.GetSandboxOrgID(lookupCtx, sandboxID)
+ if err != nil || orgIDStr == "" {
+ return "", "", false
+ }
+ orgID, err := uuid.Parse(orgIDStr)
+ if err != nil {
+ return "", "", false
+ }
+ org, err := store.GetOrg(lookupCtx, orgID)
+ if err != nil {
+ return orgIDStr, "", true
+ }
+ return orgIDStr, org.Plan, true
+ }
+ }
+
+ pub, err := worker.NewRedisEventPublisher(worker.RedisEventPublisherConfig{
+ Client: rdb,
+ SandboxDBs: sandboxDBs,
+ CellID: cellID,
+ WorkerID: microvmPublisherWorkerID,
+ Resolver: meta,
+ WorkerIDResolver: workerIDs,
+ })
+ if err != nil {
+ log.Printf("vmhost-lite: WARNING event publisher init failed: %v — usage ticks will not be billed", err)
+ return
+ }
+ // Flush before the SQLite file is deleted, or a destroyed sandbox's final
+ // usage slice races the 2s poll and is lost.
+ sandboxDBs.SetOnRemove(func(sandboxID string) {
+ pub.FlushSandbox(context.Background(), sandboxID)
+ })
+ pub.Start(ctx)
+ b.eventPub = pub
+ log.Printf("vmhost-lite: event publisher started (stream=events:%s)", cellID)
+}
+
+// StartCapacityReporter publishes this cell's capacity, without which the edge
+// does not route creates to it at all — its health gate reads the worker
+// registry, and a cell with no workers never writes one.
+func (b *liteBackend) StartCapacityReporter(ctx context.Context, rdb *redis.Client, cellID string) {
+ if b == nil {
+ return
+ }
+ if rdb == nil || cellID == "" {
+ log.Printf("vmhost-lite: WARNING capacity reporter disabled (redis=%v cellID=%q) — the edge will not route creates here",
+ rdb != nil, cellID)
+ return
+ }
+ cr, err := controlplane.NewCapacityReporter(controlplane.CapacityReporterConfig{
+ Redis: rdb,
+ Source: b,
+ CellID: cellID,
+ })
+ if err != nil {
+ log.Printf("vmhost-lite: WARNING capacity reporter init failed: %v", err)
+ return
+ }
+ cr.Start(ctx)
+ b.capacity = cr
+ log.Printf("vmhost-lite: capacity reporter started (cell=%s)", cellID)
+}
+
+// Depth reports warm stock, for telemetry.
+func (b *liteBackend) Depth() int {
+ if b == nil {
+ return 0
+ }
+ return b.mgr.Depth()
+}
+
+// Status is the operator's view of the warm set, for the admin endpoint.
+func (b *liteBackend) Status() map[string]any {
+ if b == nil {
+ return map[string]any{"enabled": false}
+ }
+ return map[string]any{
+ "enabled": true,
+ "warm": b.mgr.Depth(),
+ "bound": len(b.mgr.Bound()),
+ "region": b.client.Config().Region,
+ }
+}
+
+// ServesOwnStock: this backend manufactures and holds its own warm boxes, so the
+// cell's Postgres pool is not its supply. See SelfStocking — consulting that
+// pool for these creates measured 49-78ms of guaranteed miss per create.
+func (b *liteBackend) ServesOwnStock() bool { return true }
diff --git a/internal/api/materialize.go b/internal/api/materialize.go
new file mode 100644
index 00000000..fefaf08f
--- /dev/null
+++ b/internal/api/materialize.go
@@ -0,0 +1,103 @@
+package api
+
+import (
+ "context"
+ "sync"
+ "time"
+)
+
+// materialize.go — keep "make sure this row exists" off the create hot path.
+//
+// The edge is authoritative on org and user identity, so a cell has to lazily
+// create its local rows the first time it serves an org. That was done inline on
+// every create, and both statements are an INSERT ... ON CONFLICT against a
+// SINGLE row — the same org id and the same user id for every create an org
+// makes.
+//
+// Postgres takes a row-level lock to resolve the conflict, so concurrent creates
+// for one org do not merely repeat the work, they QUEUE for it. Measured on dev
+// with a 20-way burst, control-plane create handlers came back 8, 11, 19, 34,
+// 42, 53, 58, 66, 72, 79, 86ms — a flat ramp at roughly one statement's latency
+// per request, which is a serialization signature rather than a slow query. The
+// rows in question already existed for all twenty.
+//
+// So the work is memoized. The first create for an org still does it inline,
+// because the session insert has foreign keys to both rows and must not race
+// them. Everything after that inside the TTL skips it entirely.
+//
+// WHAT THE TTL COSTS: the cell's copy of `plan` and `billing_provider` is a
+// mirror of D1, refreshed by this upsert. Memoizing it means a plan change takes
+// up to the TTL to reach the cell. That is acceptable because the edge — not the
+// cell — enforces every billing gate; the cell's copy only tags usage events. A
+// TTL of zero would restore the old behaviour exactly.
+
+// materializeTTL is how long a successful materialization is trusted. Short
+// enough that a plan change reaches the cell's event tagging promptly, long
+// enough that no realistic burst pays for it twice.
+const materializeTTL = 5 * time.Minute
+
+// materializer memoizes idempotent "ensure this row exists" work per key.
+//
+// Per-key locking, not one global lock: two different orgs creating at once must
+// not block each other, and holding a single mutex across database I/O would
+// make one slow upsert stall every create on the cell.
+type materializer struct {
+ ttl time.Duration
+
+ mu sync.Mutex
+ seen map[string]*materializeEntry
+}
+
+type materializeEntry struct {
+ mu sync.Mutex
+ at time.Time // zero until the first success
+}
+
+func newMaterializer(ttl time.Duration) *materializer {
+ return &materializer{ttl: ttl, seen: map[string]*materializeEntry{}}
+}
+
+// ensure runs fn unless it has already succeeded for this key inside the TTL.
+//
+// Concurrent callers for the same key collapse onto one run: the rest block on
+// the entry's mutex and then observe the fresh timestamp. That is the property
+// that matters for a burst — twenty simultaneous creates for one org do the work
+// once, rather than twenty times through a row lock.
+//
+// A failure is not cached, so the next create retries. The error is returned for
+// the caller to decide about; both current callers treat it as non-fatal,
+// because a create can still succeed when the mirror is stale.
+func (m *materializer) ensure(ctx context.Context, key string, fn func(context.Context) error) error {
+ if m == nil {
+ return nil
+ }
+ m.mu.Lock()
+ e, ok := m.seen[key]
+ if !ok {
+ e = &materializeEntry{}
+ m.seen[key] = e
+ }
+ m.mu.Unlock()
+
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if !e.at.IsZero() && time.Since(e.at) < m.ttl {
+ return nil
+ }
+ if err := fn(ctx); err != nil {
+ return err
+ }
+ e.at = time.Now()
+ return nil
+}
+
+// forget drops a key's memo, so the next caller re-runs the work. For a caller
+// that learns the row is gone.
+func (m *materializer) forget(key string) {
+ if m == nil {
+ return
+ }
+ m.mu.Lock()
+ delete(m.seen, key)
+ m.mu.Unlock()
+}
diff --git a/internal/api/materialize_test.go b/internal/api/materialize_test.go
new file mode 100644
index 00000000..c9287af1
--- /dev/null
+++ b/internal/api/materialize_test.go
@@ -0,0 +1,141 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// The whole point is that a burst of creates for one org does this work ONCE.
+// Doing it per create is what made concurrent creates queue on a Postgres row
+// lock, because both callers upsert a single row.
+func TestConcurrentEnsuresForOneKeyCollapseToASingleRun(t *testing.T) {
+ m := newMaterializer(time.Minute)
+ var runs atomic.Int64
+
+ var wg sync.WaitGroup
+ for i := 0; i < 20; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _ = m.ensure(context.Background(), "org:a", func(context.Context) error {
+ runs.Add(1)
+ // Long enough that every other goroutine is definitely inside
+ // ensure while this one holds the entry.
+ time.Sleep(20 * time.Millisecond)
+ return nil
+ })
+ }()
+ }
+ wg.Wait()
+
+ if n := runs.Load(); n != 1 {
+ t.Fatalf("ran %d times for 20 concurrent callers, want 1 — the rest still contend", n)
+ }
+}
+
+// Different keys must not block each other, or one org's slow upsert stalls
+// every other org's creates on the cell.
+func TestDifferentKeysDoNotSerialize(t *testing.T) {
+ m := newMaterializer(time.Minute)
+ release := make(chan struct{})
+ started := make(chan struct{})
+
+ go func() {
+ _ = m.ensure(context.Background(), "org:slow", func(context.Context) error {
+ close(started)
+ <-release
+ return nil
+ })
+ }()
+ <-started
+
+ done := make(chan struct{})
+ go func() {
+ _ = m.ensure(context.Background(), "org:fast", func(context.Context) error { return nil })
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ close(release)
+ t.Fatal("a second key blocked behind the first — per-key locking is not working")
+ }
+ close(release)
+}
+
+// A failure must NOT be memoized: the row still does not exist, and the session
+// insert that follows has foreign keys to it.
+func TestFailureIsNotCached(t *testing.T) {
+ m := newMaterializer(time.Minute)
+ var runs atomic.Int64
+ boom := errors.New("boom")
+
+ if err := m.ensure(context.Background(), "k", func(context.Context) error {
+ runs.Add(1)
+ return boom
+ }); !errors.Is(err, boom) {
+ t.Fatalf("ensure returned %v, want the underlying error", err)
+ }
+ _ = m.ensure(context.Background(), "k", func(context.Context) error {
+ runs.Add(1)
+ return nil
+ })
+ if n := runs.Load(); n != 2 {
+ t.Fatalf("ran %d times, want 2 — a failed materialization was cached", n)
+ }
+}
+
+// Past the TTL the work runs again, so the cell's mirrored plan does not go
+// stale forever.
+func TestWorkRerunsAfterTheTTL(t *testing.T) {
+ m := newMaterializer(20 * time.Millisecond)
+ var runs atomic.Int64
+ run := func() {
+ _ = m.ensure(context.Background(), "k", func(context.Context) error { runs.Add(1); return nil })
+ }
+
+ run()
+ run()
+ if n := runs.Load(); n != 1 {
+ t.Fatalf("ran %d times inside the TTL, want 1", n)
+ }
+ time.Sleep(30 * time.Millisecond)
+ run()
+ if n := runs.Load(); n != 2 {
+ t.Fatalf("ran %d times after the TTL expired, want 2", n)
+ }
+}
+
+// forget drops the memo, for a caller that learns the row is gone.
+func TestForgetForcesARerun(t *testing.T) {
+ m := newMaterializer(time.Hour)
+ var runs atomic.Int64
+ run := func() {
+ _ = m.ensure(context.Background(), "k", func(context.Context) error { runs.Add(1); return nil })
+ }
+
+ run()
+ m.forget("k")
+ run()
+ if n := runs.Load(); n != 2 {
+ t.Fatalf("ran %d times, want 2 — forget did not drop the memo", n)
+ }
+}
+
+// A nil materializer must be inert rather than panic: it is a field on Server,
+// and tests construct Servers directly.
+func TestNilMaterializerIsInert(t *testing.T) {
+ var m *materializer
+ if err := m.ensure(context.Background(), "k", func(context.Context) error {
+ t.Fatal("fn ran on a nil materializer")
+ return nil
+ }); err != nil {
+ t.Fatalf("nil ensure returned %v", err)
+ }
+ m.forget("k")
+}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
index 9e4b94bc..3f6cbdd8 100644
--- a/internal/api/microvm_backend.go
+++ b/internal/api/microvm_backend.go
@@ -8,6 +8,7 @@ import (
"log"
"net/http"
"os"
+ "sort"
"strconv"
"strings"
"sync/atomic"
@@ -115,60 +116,19 @@ func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointS
if !microvmEnabled() {
return nil, nil
}
-
- image := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_ARN")
- if image == "" {
- return nil, fmt.Errorf("OPENSANDBOX_MICROVM_ENABLED=1 but OPENSANDBOX_MICROVM_IMAGE_ARN is unset")
- }
- region := os.Getenv("OPENSANDBOX_MICROVM_REGION")
- if region == "" {
- region = "us-east-1"
+ // The direct-exec backend replaces this one rather than joining it — see the
+ // registration order in router.go. Returning nil here is what makes that
+ // exclusive: otherwise both pools would fill from the same regional quota.
+ if liteEnabled() {
+ log.Printf("microvm: agent-tunnel backend stood down — OPENSANDBOX_MICROVM_LITE=1 is serving this cell")
+ return nil, nil
}
- awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))
+ client, err := newMicrovmClient(ctx)
if err != nil {
- return nil, fmt.Errorf("microvm: load AWS config: %w", err)
+ return nil, err
}
-
- // Idle policy. Measured on dev: with idle=60s and suspended=300s, a sandbox
- // was TERMINATED — disk and all — roughly six minutes after its last
- // request. The old defaults (900/1800) put that at 45 minutes of inactivity,
- // which silently destroys any sandbox a customer steps away from.
- //
- // idle seconds without inbound proxy traffic before AWS suspends.
- // A persistent agent tunnel does NOT count as traffic — only
- // requests through the proxy do, which is why an open connection
- // does not keep a box alive.
- // suspended seconds a box may stay suspended before AWS TERMINATES it.
- // This, not the 8h ceiling, is what actually bounds a parked
- // sandbox, and when it fires the disk goes with it.
- // resume whether an inbound request wakes a suspended box. With this
- // off, nothing can reach a box during its suspended window, so
- // the window always runs out and the sandbox is destroyed.
- //
- // Default idle deliberately exceeds the pool's MaxBoxAge (7h) so stock never
- // drifts into SUSPENDED while waiting — the pool's docstring requires that,
- // and the previous 900s default did not deliver it. Auto-resume defaults ON
- // so that anything which does suspend is recoverable rather than doomed.
- idleSec := envInt("OPENSANDBOX_MICROVM_IDLE_SECONDS", 28_800)
- // Default to the hard ceiling rather than 1800: AWS terminates a suspended
- // box when this fires, taking its disk with it, so a 30-minute default made
- // "hibernate" mean "deleted in half an hour". At the ceiling this timer
- // never fires before the 8h total cap does, which leaves the cap as the
- // single deadline to reason about — and the one the blob promotion works
- // against.
- suspendedSec := envInt("OPENSANDBOX_MICROVM_SUSPENDED_SECONDS", 28_800)
- autoResume := os.Getenv("OPENSANDBOX_MICROVM_AUTO_RESUME") != "0"
- client := awsvm.NewClient(awsCfg, awsvm.Config{
- Region: region,
- ImageIdentifier: image,
- ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),
- MaxIdleDurationSeconds: int32(idleSec),
- SuspendedDurationSeconds: int32(suspendedSec),
- AutoResume: autoResume,
- })
- log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",
- idleSec, suspendedSec, autoResume)
+ region := client.Config().Region
poolCtx, stop := context.WithCancel(context.Background())
@@ -224,11 +184,84 @@ func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointS
go b.pool.Run(poolCtx)
log.Printf("microvm: backend enabled (region=%s image=%s poolTarget=%d)",
- region, image, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
+ region, client.Config().ImageIdentifier, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
return b, nil
}
+// newMicrovmClient builds the AWS client from environment config.
+//
+// Shared by both MicroVM backends — the agent-tunnel one above and the direct
+// exec one in lite_backend.go — because they are two ways of TALKING to a box,
+// not two fleets. They launch from the same image, in the same region, under the
+// same idle policy and the same regional quota, and letting those drift apart
+// would make a measurement taken on one say nothing about the other.
+func newMicrovmClient(ctx context.Context) (*awsvm.Client, error) {
+ image := os.Getenv("OPENSANDBOX_MICROVM_IMAGE_ARN")
+ if image == "" {
+ return nil, fmt.Errorf("OPENSANDBOX_MICROVM_ENABLED=1 but OPENSANDBOX_MICROVM_IMAGE_ARN is unset")
+ }
+ region := os.Getenv("OPENSANDBOX_MICROVM_REGION")
+ if region == "" {
+ region = "us-east-1"
+ }
+
+ awsCfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region))
+ if err != nil {
+ return nil, fmt.Errorf("microvm: load AWS config: %w", err)
+ }
+
+ // Idle policy. Measured on dev: with idle=60s and suspended=300s, a sandbox
+ // was TERMINATED — disk and all — roughly six minutes after its last
+ // request. The old defaults (900/1800) put that at 45 minutes of inactivity,
+ // which silently destroys any sandbox a customer steps away from.
+ //
+ // idle seconds without inbound proxy traffic before AWS suspends.
+ // A persistent agent tunnel does NOT count as traffic — only
+ // requests through the proxy do, which is why an open connection
+ // does not keep a box alive.
+ // suspended seconds a box may stay suspended before AWS TERMINATES it.
+ // This, not the 8h ceiling, is what actually bounds a parked
+ // sandbox, and when it fires the disk goes with it.
+ // resume whether an inbound request wakes a suspended box. With this
+ // off, nothing can reach a box during its suspended window, so
+ // the window always runs out and the sandbox is destroyed.
+ //
+ // Default idle deliberately exceeds the pool's MaxBoxAge (7h) so stock never
+ // drifts into SUSPENDED while waiting — the pool's docstring requires that,
+ // and the previous 900s default did not deliver it. Auto-resume defaults ON
+ // so that anything which does suspend is recoverable rather than doomed.
+ idleSec := envInt("OPENSANDBOX_MICROVM_IDLE_SECONDS", 28_800)
+ // Default to the hard ceiling rather than 1800: AWS terminates a suspended
+ // box when this fires, taking its disk with it, so a 30-minute default made
+ // "hibernate" mean "deleted in half an hour". At the ceiling this timer
+ // never fires before the 8h total cap does, which leaves the cap as the
+ // single deadline to reason about — and the one the blob promotion works
+ // against.
+ suspendedSec := envInt("OPENSANDBOX_MICROVM_SUSPENDED_SECONDS", 28_800)
+ autoResume := os.Getenv("OPENSANDBOX_MICROVM_AUTO_RESUME") != "0"
+ sizeImages := parseSizeImages(os.Getenv("OPENSANDBOX_MICROVM_SIZE_IMAGES"))
+ defaultMemoryMB := envInt("OPENSANDBOX_MICROVM_DEFAULT_MEMORY_MB", 0)
+ client := awsvm.NewClient(awsCfg, awsvm.Config{
+ Region: region,
+ ImageIdentifier: image,
+ DefaultMemoryMB: defaultMemoryMB,
+ SizeImages: sizeImages,
+ ExecutionRoleArn: os.Getenv("OPENSANDBOX_MICROVM_EXECUTION_ROLE_ARN"),
+ MaxIdleDurationSeconds: int32(idleSec),
+ SuspendedDurationSeconds: int32(suspendedSec),
+ AutoResume: autoResume,
+ })
+ if len(sizeImages) > 0 {
+ log.Printf("microvm: size tiers — default %dMB pooled, cold-only: %v",
+ client.Config().DefaultMemoryMB, sortedTiers(sizeImages))
+ }
+ log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",
+ idleSec, suspendedSec, autoResume)
+
+ return client, nil
+}
+
// claimPooled binds a warm host to a sandbox id and returns whether one was
// available. It makes NO provider calls — that is the property the whole pool
// design exists to preserve, because launch and resume are both rate-limited
@@ -239,6 +272,18 @@ func (b *microvmBackend) claimPooled(sandboxID string, cfg types.SandboxConfig)
if b == nil {
return "", false
}
+ // Only the default tier is pooled, so a request for any other size must miss
+ // the pool on purpose and cold-launch its own image.
+ //
+ // Without this the pool would happily hand a 16 GB request a default-size
+ // box: warm stock is manufactured from one image and carries no record of
+ // what it was asked for, so nothing downstream can tell the difference. The
+ // customer gets a box a quarter the size they asked for, metered at what
+ // they actually got, with no error anywhere.
+ if !b.client.Config().IsDefaultTier(cfg.MemoryMB) {
+ log.Printf("microvm: %s asked for %dMB — not the pooled tier, cold create", sandboxID, cfg.MemoryMB)
+ return "", false
+ }
entry, ok := b.pool.Claim()
if !ok {
log.Printf("microvm: pool empty on claim for %s — cold create", sandboxID)
@@ -295,8 +340,16 @@ func (b *microvmBackend) Claim(ctx context.Context, p placement) (string, error)
launchCtx, cancel := context.WithTimeout(ctx, coldCreateTimeout)
defer cancel()
+ // Resolve the tier's image. Refused rather than downgraded — see
+ // awsvm.Config.ImageForMemory.
+ image, _, ok := b.client.Config().ImageForMemory(cfg.MemoryMB)
+ if !ok {
+ return "", fmt.Errorf("microvm: %s: no image configured for %dMB: %w",
+ sandboxID, cfg.MemoryMB, awsvm.ErrUnsupported)
+ }
+
start := time.Now()
- box, err := b.client.Run(launchCtx, "")
+ box, err := b.client.RunImage(launchCtx, "", image)
if err != nil {
return "", err // already classified (quota vs throttle) by awsvm
}
@@ -580,7 +633,13 @@ func (b *microvmBackend) sweepOrphans(ctx context.Context) {
known[id] = struct{}{}
}
- ourImage := b.client.Config().ImageIdentifier
+ // Every image this cell launches from, not just the default: a box on a size
+ // tier is equally ours, and testing only the default image would leave every
+ // tier orphan uncollectable (it reads as another product's host).
+ ourImages := make(map[string]struct{}, 4)
+ for _, arn := range b.client.Config().OwnedImages() {
+ ourImages[arn] = struct{}{}
+ }
armed := envInt("OPENSANDBOX_MICROVM_ORPHAN_REAP", 0) == 1
var orphans []string
@@ -622,7 +681,7 @@ func (b *microvmBackend) sweepOrphans(ctx context.Context) {
arn = full.ImageArn
}
}
- if ourImage == "" || arn != ourImage {
+ if _, ours := ourImages[arn]; len(ourImages) == 0 || !ours {
if arn == "" {
skippedUnprovable++
} else {
@@ -1121,9 +1180,10 @@ func (b *microvmBackend) Reconcile(ctx context.Context, store *db.Store) {
//
// The distinction matters to callers: a 500 invites a retry and reads as our
// bug, while 501 says the operation will never succeed on this runtime. The
-// MicroVM backend returns ErrUnsupported for checkpoint/fork/reboot/power-cycle
-// — operations with no counterpart in a service where images are built through
-// an API rather than captured from a running VM.
+// MicroVM backend returns ErrUnsupported for checkpoint/fork (no counterpart in
+// a service where images are built through an API rather than captured from a
+// running VM) and for SetResourceLimits (sizing belongs to the image, so there
+// is no per-sandbox knob to turn).
func respondManagerErr(c echo.Context, err error) error {
if errors.Is(err, awsvm.ErrUnsupported) {
return c.JSON(http.StatusNotImplemented, map[string]string{
@@ -1138,6 +1198,48 @@ func respondManagerErr(c echo.Context, err error) error {
})
}
+// parseSizeImages reads the tier→image map from
+// OPENSANDBOX_MICROVM_SIZE_IMAGES, formatted "1024=arn:...,8192=arn:...".
+//
+// Only tiers listed here are offered beyond the default; an unlisted size is
+// refused at create rather than served from the default image. Malformed
+// entries are dropped with a log rather than failing startup — a typo in one
+// tier must not take the whole cell down, but it must not silently become a
+// wrong-size sandbox either, and dropping it makes that tier 501 instead.
+func parseSizeImages(raw string) map[int]string {
+ if strings.TrimSpace(raw) == "" {
+ return nil
+ }
+ out := map[int]string{}
+ for _, pair := range strings.Split(raw, ",") {
+ pair = strings.TrimSpace(pair)
+ if pair == "" {
+ continue
+ }
+ k, v, found := strings.Cut(pair, "=")
+ mb, err := strconv.Atoi(strings.TrimSpace(k))
+ if !found || err != nil || mb <= 0 || strings.TrimSpace(v) == "" {
+ log.Printf("microvm: ignoring malformed SIZE_IMAGES entry %q — that tier will be refused, not downsized", pair)
+ continue
+ }
+ out[mb] = strings.TrimSpace(v)
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
+// sortedTiers lists configured tier sizes in ascending order, for logging.
+func sortedTiers(m map[int]string) []int {
+ out := make([]int, 0, len(m))
+ for mb := range m {
+ out = append(out, mb)
+ }
+ sort.Ints(out)
+ return out
+}
+
func envInt(key string, def int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
@@ -1147,3 +1249,7 @@ func envInt(key string, def int) int {
}
return def
}
+
+// ServesOwnStock: warm hosts come from this backend's own pool (awsvm.Pool),
+// claimed inside Claim, not from the cell's Postgres pool. See SelfStocking.
+func (b *microvmBackend) ServesOwnStock() bool { return true }
diff --git a/internal/api/router.go b/internal/api/router.go
index 4ebdee7e..fb38badc 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -75,6 +75,9 @@ type Server struct {
redisClient *redis.Client // nil if Redis not configured (for health checks)
adminEvents *AdminEventBus // real-time event bus for admin dashboard
microvm *microvmBackend // managed-host backend; nil unless enabled (see microvm_backend.go)
+ lite *liteBackend // direct-exec managed-host backend; mutually exclusive with microvm (see lite_backend.go)
+ materialize *materializer // memoizes per-org/user row creation off the create hot path (materialize.go)
+ templateCache *templateCache // caches name→template so create doesn't call the edge every time (template_cache.go)
// backends is the dispatch set for placement and routing (see backend.go).
// The worker path is deliberately absent — it is reached by falling through.
backends []Backend
@@ -116,6 +119,35 @@ func (s *Server) SetMigrator(m MigrationOrchestrator) {
// constructing it with the right base URL + HMAC secret (CFEventSecret).
func (s *Server) SetEdgeClient(c *edgeclient.Client) {
s.edge = c
+ s.prewarmPoolTemplate()
+}
+
+// prewarmPoolTemplate resolves the default template once at startup so no
+// customer create is ever the one that pays for it.
+//
+// Every SDK create carries a template name ("base" unless overridden), and the
+// first one to arrive after a restart would otherwise block on the edge round
+// trip — which, if that first create arrives as part of a burst, is the 580ms
+// case the template cache exists to prevent. Doing it here costs one request at
+// boot, off any hot path.
+//
+// Best effort by design: a failure just leaves the cache empty, which is
+// exactly the state this would have been in anyway. The public-template
+// fallback means the pool template resolves without an org.
+func (s *Server) prewarmPoolTemplate() {
+ if s.edge == nil || s.templateCache == nil {
+ return
+ }
+ name := poolTemplateName()
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), templateRefreshTimeout)
+ defer cancel()
+ if _, err := s.templateCache.lookup(ctx, uuid.Nil, name, func(fctx context.Context) (*db.DBTemplate, error) {
+ return s.edge.LookupTemplate(fctx, uuid.Nil, name)
+ }); err != nil {
+ log.Printf("template cache: prewarm of %q failed: %v — first create will resolve it", name, err)
+ }
+ }()
}
// SetWSGateway wires the in-process WebSocket broker. When non-nil,
@@ -185,9 +217,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
e.HidePort = true
s := &Server{
- echo: e,
- manager: mgr,
- ptyManager: ptyMgr,
+ echo: e,
+ manager: mgr,
+ ptyManager: ptyMgr,
+ materialize: newMaterializer(materializeTTL),
+ templateCache: newTemplateCache(),
}
// Mount service is only useful in combined mode (this process owns the
// sandbox manager). In server mode the CP proxies to a worker, which
@@ -807,6 +841,29 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Serve web dashboard SPA at root (catch-all after API/auth routes)
s.serveDashboardUI(e, frontendURL)
+ // The direct-exec MicroVM backend (OPENSANDBOX_MICROVM_LITE=1). Selected
+ // INSTEAD of the agent-tunnel one below, never alongside it: both manufacture
+ // boxes from the same image against the same regional quota, and two fillers
+ // each believing they own the fleet would overrun it and starve each other.
+ //
+ // See lite_backend.go. The trade is total — no files, no hibernate, no
+ // streaming — so this is a measurement configuration, not a default.
+ if lite, err := newLiteBackend(context.Background()); err != nil {
+ log.Fatalf("opensandbox: vmhost-lite backend: %v", err)
+ } else if lite != nil {
+ s.lite = lite
+ s.registerBackend(lite)
+ // Rebuild sandbox→box bindings before serving. A restart otherwise
+ // leaves live sandboxes unroutable AND unreapable.
+ lite.Restore(context.Background(), s.store)
+ lite.StartReconciler(context.Background(), s.store)
+ lite.StartUsageTicker(context.Background(), s.sandboxDBs)
+ lite.StartEventPublisher(context.Background(), s.sandboxDBs, s.redisClient, s.cellID, s.store)
+ if s.workerRegistry == nil || s.workersDisabled {
+ lite.StartCapacityReporter(context.Background(), s.redisClient, s.cellID)
+ }
+ }
+
// AWS Lambda MicroVM backend. Disabled by default: this returns nil and no
// AWS call is ever made, so the QEMU fleet is unaffected. When it IS enabled
// but misconfigured, fail loudly rather than silently serving QEMU from a
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 201a6b47..cebe34b2 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -545,6 +545,15 @@ func layerSecretStores(cfg *types.SandboxConfig, inheritedBase, inheritedChild,
// shape (the existing db.DBTemplate); same semantics (org-scoped first,
// public fallback). Returns (nil, nil) when no template name was supplied
// or no source is configured — caller should treat that as "no template".
+// isDefaultTemplate reports whether name is the platform's default template —
+// the one the pool manufactures and the SDK sends when the caller did not ask
+// for anything. Creates naming it are treated exactly like creates naming
+// nothing: they resolve off the hot path, and failing to resolve is not a 404
+// (404-ing the default would fail every create on the cell).
+func isDefaultTemplate(name string) bool {
+ return name == poolTemplateName()
+}
+
func (s *Server) resolveTemplate(ctx context.Context, orgID [16]byte, hasOrg bool, name string) (*db.DBTemplate, error) {
if name == "" {
return nil, nil
@@ -554,7 +563,35 @@ func (s *Server) resolveTemplate(ctx context.Context, orgID [16]byte, hasOrg boo
if hasOrg {
oid = uuid.UUID(orgID)
}
- t, err := s.edge.LookupTemplate(ctx, oid, name)
+ fetch := func(fctx context.Context) (*db.DBTemplate, error) {
+ return s.edge.LookupTemplate(fctx, oid, name)
+ }
+
+ // The default template never blocks a create. It is the name virtually
+ // every create carries (the SDK sends "base" unless told otherwise), it
+ // is the shape the pool already manufactures, and nothing the create
+ // path does with the hot response depends on resolving it — which is
+ // precisely why a create that omits the name entirely was ~64us while
+ // one that named "base" was 580ms.
+ //
+ // Answer from cache, fill in the background, and treat "not resolved
+ // yet" the same as "no name given". isDefaultTemplate keeps the caller's
+ // not-found branch from turning that into a 404.
+ if isDefaultTemplate(name) {
+ return s.templateCache.lookupNonBlocking(oid, name, fetch), nil
+ }
+
+ // A named custom template DOES have to resolve before the create can
+ // proceed — its drive keys decide what the sandbox boots from, and a
+ // name that does not exist must 404 rather than silently boot a base
+ // box. Single-flighted and stale-while-revalidate, so only a name never
+ // seen before pays a round trip.
+ //
+ // Only positive results are cached. A miss means "no such template", and
+ // caching that would break the create-a-template-then-use-it sequence for
+ // the length of the TTL — a correctness bug traded for latency we can get
+ // another way.
+ t, err := s.templateCache.lookup(ctx, oid, name, fetch)
if err != nil {
if errors.Is(err, edgeclient.ErrNotFound) {
return nil, nil
@@ -803,6 +840,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// Edge-first when s.edge is configured (post-migration 041), local PG
// otherwise. Same return shape so the rest of the create flow doesn't
// care which path produced it.
+ tr := traceFrom(ctx)
+ tr.mark("region")
+
var templateRootfsKey, templateWorkspaceKey string
var templateID *uuid.UUID
tmpl, err := s.resolveTemplate(ctx, orgID, hasOrg, cfg.Template)
@@ -821,8 +861,14 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
templateWorkspaceKey = *tmpl.WorkspaceS3Key
log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)
}
- } else if cfg.Template != "" {
+ } else if cfg.Template != "" && !isDefaultTemplate(cfg.Template) {
// Requested a template by name but it didn't resolve (not found).
+ //
+ // The default template is exempt: it resolves off the hot path and may
+ // legitimately read as nil before its first background fill lands. That
+ // is the same state as a create that named no template at all, which
+ // boots a base box — so 404-ing here would fail ordinary creates for a
+ // value the create does not use.
return c.JSON(http.StatusNotFound, map[string]string{"error": "template not found: " + cfg.Template})
}
@@ -831,35 +877,55 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// try to claim a pre-warmed pooled box — resume + rebind, skipping the ~260ms
// cold restore. A miss or any ineligibility falls through to the cold create
// below, so it's never worse than the status quo.
- if s.store != nil && hasOrg && s.poolEnabled() && s.poolTarget() > 0 &&
- templateRootfsKey == "" && cfg.ImageRef == "" && cfg.CheckpointID == "" &&
- len(cfg.EgressAllowlist) == 0 && len(cfg.SecretAllowedHosts) == 0 {
- // A no-template create wants a base-golden box, which is exactly what the
- // pool manufactures. Default to poolTemplateName() (the same value the
- // manufacture + reconciler use — "base" unless overridden) so the claim
- // query matches the pooled rows; the prior hardcoded "default" never
- // matched, sending every default-shape origin create to the cold path.
- poolTemplate := cfg.Template
- if poolTemplate == "" {
- poolTemplate = poolTemplateName()
- }
- // This is the fleet's own warm pool, which lives in PG and is claimed by
- // resume+rebind on a worker. A backend that keeps its own warm stock
- // serves it from inside Claim instead, so there is nothing to branch on
- // here — the create below is the same call either way.
- if done, resp := s.tryClaimPooled(c, ctx, cfg, uuid.UUID(orgID), secretStoreID, region, poolTemplate); done {
- return resp
+ // Resolved BEFORE the pool fast-path below, because which backend serves this
+ // create decides whether that pool is even its supply. Safe to move earlier:
+ // Accepts is documented as a pure function of the request, so asking it here
+ // yields the same answer it would further down.
+ tr.mark("tmpl")
+ orgRuntime := runtimeFor(c)
+ backend, ok := s.claimBackend(placement{
+ region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,
+ })
+
+ // This is the FLEET's warm pool: rows in this cell's Postgres, claimed by
+ // resume+rebind on a QEMU worker. A backend that keeps its own warm stock
+ // draws from somewhere else entirely, so for those creates this query is not
+ // a fast path — it is a guaranteed miss with a row-locking claim inside it.
+ //
+ // An earlier version of this comment said there was nothing to branch on
+ // here. That was wrong, and the cost was the largest single item on the
+ // create path: per-step tracing of a 20-way burst on a MicroVM cell put
+ // 49-78ms in this block while every other step in the handler — bind,
+ // backend selection, claim, activate, token — measured 1-35 MICROseconds.
+ // It ramped across the burst, which is the row lock, and it could never once
+ // have succeeded, because that cell has no QEMU pool to claim from.
+ //
+ // The guard is a property of the backend rather than a runtime name, so a
+ // future self-stocking backend gets it without touching this file.
+ if !ok || !servesOwnStock(backend) {
+ if s.store != nil && hasOrg && s.poolEnabled() && s.poolTarget() > 0 &&
+ templateRootfsKey == "" && cfg.ImageRef == "" && cfg.CheckpointID == "" &&
+ len(cfg.EgressAllowlist) == 0 && len(cfg.SecretAllowedHosts) == 0 {
+ // A no-template create wants a base-golden box, which is exactly what the
+ // pool manufactures. Default to poolTemplateName() (the same value the
+ // manufacture + reconciler use — "base" unless overridden) so the claim
+ // query matches the pooled rows; the prior hardcoded "default" never
+ // matched, sending every default-shape origin create to the cold path.
+ poolTemplate := cfg.Template
+ if poolTemplate == "" {
+ poolTemplate = poolTemplateName()
+ }
+ if done, resp := s.tryClaimPooled(c, ctx, cfg, uuid.UUID(orgID), secretStoreID, region, poolTemplate); done {
+ return resp
+ }
}
}
+ tr.mark("pgpool")
// Everything below is runtime-independent: choose a host, write the row,
// start the host, promote. runCreate owns that order; the closures below own
// what each step means here. Before this the sequence was inline and the
// persist-before-activate constraint was a comment.
- orgRuntime := runtimeFor(c)
- backend, ok := s.claimBackend(placement{
- region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,
- })
if !ok {
// No registered backend can accept a sandbox. A cell in this state can
// still serve the ones it already has, so this is a capacity answer.
@@ -871,6 +937,8 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// Pre-generate the sandbox id: the row must carry it before the host boots,
// because the host looks its org up by this id while starting.
sandboxID := "sb-" + uuid.New().String()[:8]
+ tr.setSandboxID(sandboxID)
+ tr.mark("backend")
// Register inline webhooks at the edge (Svix) BEFORE the row and the boot, so
// the endpoint exists well before `created` is relayed. On this path `created`
@@ -881,6 +949,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
inlineWebhooks = s.registerInlineWebhooksEdge(ctx, orgID, sandboxID, cfg.Webhooks)
}
+ tr.mark("webhooks")
var host activated
workerID, err := runCreate(ctx, sandboxID, createSteps{
claim: func(ctx context.Context) (string, error) {
@@ -959,6 +1028,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// started emits no events, so those endpoints simply sit idle.
},
})
+ tr.mark("runcreate")
if err != nil {
return respondCreateErr(c, err)
}
@@ -996,6 +1066,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// Reason text reaches customers through webhooks, so it says what happened
// rather than what ran it.
+ tr.mark("token")
s.emitEvent("create", sandboxID, workerID, "sandbox started")
resp := map[string]interface{}{
@@ -1615,10 +1686,11 @@ func (s *Server) setLimits(c echo.Context) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ // respondManagerErr, not a bare 500: a runtime that has no sizing knob at all
+ // (MicroVM) must answer 501 so the caller stops retrying a resize that can
+ // never apply, rather than reading it as a transient server fault.
if err := s.manager.SetResourceLimits(ctx, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
+ return respondManagerErr(c, err)
}
return c.JSON(http.StatusOK, map[string]interface{}{
@@ -1697,8 +1769,9 @@ func (s *Server) scaleSandbox(c echo.Context) error {
if s.manager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ // See the sibling handler: 501 for a runtime with no sizing knob.
if err := s.manager.SetResourceLimits(c.Request().Context(), id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec); err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ return respondManagerErr(c, err)
}
return c.JSON(http.StatusOK, map[string]interface{}{
"sandboxID": id,
diff --git a/internal/api/template_cache.go b/internal/api/template_cache.go
new file mode 100644
index 00000000..2604d486
--- /dev/null
+++ b/internal/api/template_cache.go
@@ -0,0 +1,281 @@
+package api
+
+import (
+ "context"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// template_cache.go — keep the template lookup off the create hot path.
+//
+// resolveTemplate asks the edge to turn a template NAME into a row, and it does
+// that inside every create, synchronously. Found by tailing the edge rather than
+// the control plane: `GET /internal/templates/by-name?name=base` at 66-69ms on
+// every single create, for a row that changes about never.
+//
+// It was invisible from both sides on its own. The control plane's create trace
+// stops at the process boundary, so the call showed up only inside the `tmpl`
+// span; the edge saw it as an ordinary internal request with nothing to compare
+// it against. It took counting requests at the edge during an SDK run to see
+// that a "3 request" TTI was actually making five.
+//
+// POSITIVE RESULTS ONLY. A miss means the template does not exist, and caching
+// that would make "create a template, then create a sandbox from it" fail for
+// the length of the TTL. That is a correctness bug bought with latency, and the
+// latency is available without it — a miss is exactly the case where the extra
+// round trip is doing real work.
+
+// templateCacheTTL bounds how stale a resolved template may be. Templates are
+// immutable in the way that matters here — the drive keys a name resolves to —
+// and a rebuild publishes a new row, so a minute of staleness costs at most one
+// create landing on the previous revision.
+const templateCacheTTL = 60 * time.Second
+
+// templateStaleMax bounds how old an entry may be and still be served without
+// waiting. Past it a create blocks on a fresh read rather than acting on a value
+// nothing has been able to confirm for this long — a background refresh that
+// keeps failing must eventually surface, not persist silently forever.
+//
+// Generous on purpose: the cost of being wrong is one create landing on the
+// previous revision of a template, while the cost of blocking is the 580ms
+// above. A rebuild publishes a new row, and the refresh below picks it up
+// within a TTL of the next create.
+const templateStaleMax = 30 * time.Minute
+
+// templateRefreshTimeout bounds a background refresh. It is deliberately not
+// the request's context: the request returns immediately (that is the point),
+// so a refresh tied to it would be cancelled the moment the response is sent.
+const templateRefreshTimeout = 15 * time.Second
+
+// A CACHE WITHOUT SINGLE-FLIGHT IS NOT A CACHE UNDER BURST.
+//
+// The TTL above made this cheap for sequential traffic and did nothing at all
+// for a burst: 100 concurrent creates all read the same empty entry in the same
+// instant, all miss, and all issue their own control-plane→edge lookup for the
+// same name. Measured on dev with a burst of 100, the only difference being
+// whether the create body carried a template name:
+//
+// body {} create.cell (the CP's own answer) 138ms
+// body {"templateID":"base"} create.cell 932ms
+//
+// ~794ms, entirely inside the control plane, for a value that is identical in
+// all 100 requests. It hides from sequential benchmarks by construction — the
+// first create fills the entry and the rest hit it — so it only exists at
+// exactly the concurrency that matters. It reaches every real SDK user, because
+// the SDK always sends templateID ("base" by default); a raw client that omits
+// the field skips resolveTemplate entirely and never sees it.
+//
+// The fix is the same one lookupCell needed at the edge: collapse concurrent
+// misses for one key into ONE flight and let the rest wait on its result.
+//
+// SINGLE-FLIGHT ALONE IS NOT ENOUGH, and the trace says why. With 90 concurrent
+// creates carrying a template name, on the control plane's own per-create trace:
+//
+// ENTER offsets spread=56ms (all 90 reach the handler together)
+// handler total med=580,065us
+// tmpl med=579,862us ← 99.97% of the handler
+// token=12us bind=8us activate=3us claim=2us
+//
+// versus a handler median of 64us for a create with no template name. The
+// single flight had already collapsed 90 lookups into one; every caller then
+// waited on that one lookup, and the lookup itself took 580ms.
+//
+// It takes 580ms because of the topology, not the work: a create arrives at the
+// edge, the edge calls this control plane, and this control plane calls BACK
+// INTO THE SAME EDGE for the template. During a burst the edge is already
+// saturated holding those creates open, so the lookup queues behind the very
+// requests that are blocked waiting for it. Idle, the same call is ~60ms.
+//
+// So the hot path must never wait on it. An entry that exists is served
+// IMMEDIATELY, however old, and refreshed in the background; only a name never
+// resolved before can block, which is the one case where the round trip is
+// doing real work (it decides between a real template and a 404).
+type templateCache struct {
+ mu sync.Mutex
+ m map[string]templateCacheEntry
+ flight map[string]*templateFlight
+}
+
+type templateCacheEntry struct {
+ tmpl *db.DBTemplate
+ at time.Time
+}
+
+// templateFlight is one in-progress lookup that later arrivals join instead of
+// duplicating. done is closed exactly once, by the goroutine that started it.
+type templateFlight struct {
+ done chan struct{}
+ tmpl *db.DBTemplate
+ err error
+}
+
+func newTemplateCache() *templateCache {
+ return &templateCache{
+ m: map[string]templateCacheEntry{},
+ flight: map[string]*templateFlight{},
+ }
+}
+
+func templateCacheKey(orgID uuid.UUID, name string) string {
+ // Org-scoped: resolution falls back to public templates, so the same name can
+ // legitimately mean different rows for different orgs. A global key would
+ // serve one org's template to another.
+ return orgID.String() + "\x00" + name
+}
+
+// get returns a cached template. The bool reports whether the cache answered at
+// all — distinct from a cached nil, which this deliberately never stores.
+func (c *templateCache) get(orgID uuid.UUID, name string) (*db.DBTemplate, bool) {
+ if c == nil {
+ return nil, false
+ }
+ c.mu.Lock()
+ e, ok := c.m[templateCacheKey(orgID, name)]
+ c.mu.Unlock()
+ if !ok || time.Since(e.at) >= templateCacheTTL {
+ return nil, false
+ }
+ return e.tmpl, true
+}
+
+// lookup returns the template for name without blocking the caller whenever it
+// can avoid it:
+//
+// fresh entry (< TTL) → returned as-is
+// stale entry (< staleMax) → returned IMMEDIATELY, refreshed in background
+// no entry (or past staleMax) → blocks, single-flighted across all callers
+//
+// fetch receives a context because the two paths need different ones: a
+// blocking lookup belongs to the request, while a background refresh must
+// outlive it (the request returns first, by design).
+//
+// The result of a joined flight is shared, including its error: a failing
+// lookup fails all of its waiters identically, which is what they would each
+// have gotten anyway. Only positive results are cached (see put).
+func (c *templateCache) lookup(ctx context.Context, orgID uuid.UUID, name string, fetch func(context.Context) (*db.DBTemplate, error)) (*db.DBTemplate, error) {
+ if c == nil {
+ return fetch(ctx)
+ }
+
+ key := templateCacheKey(orgID, name)
+ c.mu.Lock()
+ if e, ok := c.m[key]; ok {
+ age := time.Since(e.at)
+ if age < templateCacheTTL {
+ c.mu.Unlock()
+ return e.tmpl, nil
+ }
+ if age < templateStaleMax {
+ // Serve stale, refresh behind the response. startFlightLocked is a
+ // no-op when a refresh for this key is already running, so a burst
+ // kicks exactly one.
+ c.startRefreshLocked(key, orgID, name, fetch)
+ c.mu.Unlock()
+ return e.tmpl, nil
+ }
+ }
+ if f, ok := c.flight[key]; ok {
+ c.mu.Unlock()
+ <-f.done
+ return f.tmpl, f.err
+ }
+ f := &templateFlight{done: make(chan struct{})}
+ c.flight[key] = f
+ c.mu.Unlock()
+
+ tmpl, err := fetch(ctx)
+ c.finishFlight(key, orgID, name, f, tmpl, err)
+ return f.tmpl, f.err
+}
+
+// lookupNonBlocking returns whatever is cached for name — fresh or stale — and
+// NEVER waits on the edge. A key with nothing cached yet returns nil and fills
+// in the background.
+//
+// This is the default-template path. The blocking lookup above still costs one
+// cold round trip per key, and a burst that arrives cold is exactly the case
+// that cannot afford it: measured after single-flight + stale-while-revalidate,
+// a burst of 70 still spent tmpl=156,838us of a 156,943us handler, because
+// every caller piled onto the one cold flight.
+//
+// It is sound only because the create path does not use the result for the
+// default template: drive keys are read solely for TemplateType=="sandbox"
+// (custom snapshot templates), and the resolved ID feeds a bookkeeping UPDATE
+// that already runs after the response. A name that resolves to nothing here
+// must therefore NOT 404 — see the caller.
+func (c *templateCache) lookupNonBlocking(orgID uuid.UUID, name string, fetch func(context.Context) (*db.DBTemplate, error)) *db.DBTemplate {
+ if c == nil {
+ return nil
+ }
+ key := templateCacheKey(orgID, name)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ e, ok := c.m[key]
+ if ok && time.Since(e.at) < templateCacheTTL {
+ return e.tmpl
+ }
+ // Absent or stale: fill behind the response and answer with what we have
+ // (nil on the very first call for this key).
+ c.startRefreshLocked(key, orgID, name, fetch)
+ if ok {
+ return e.tmpl
+ }
+ return nil
+}
+
+// startRefreshLocked kicks a background refresh for key unless one is already in
+// flight. Caller must hold c.mu.
+func (c *templateCache) startRefreshLocked(key string, orgID uuid.UUID, name string, fetch func(context.Context) (*db.DBTemplate, error)) {
+ if _, ok := c.flight[key]; ok {
+ return
+ }
+ f := &templateFlight{done: make(chan struct{})}
+ c.flight[key] = f
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), templateRefreshTimeout)
+ defer cancel()
+ tmpl, err := fetch(ctx)
+ if err != nil {
+ // Keep serving the existing entry; the next create past the TTL
+ // tries again. Logged because a refresh that never succeeds is how
+ // a stale template would eventually start blocking creates.
+ log.Printf("template cache: background refresh of %q failed: %v", name, err)
+ }
+ c.finishFlight(key, orgID, name, f, tmpl, err)
+ }()
+}
+
+// finishFlight publishes a flight's result: cache it (positive only), drop the
+// flight, then wake the waiters — in that order, so nobody wakes up and
+// re-misses on the entry this flight just produced.
+func (c *templateCache) finishFlight(key string, orgID uuid.UUID, name string, f *templateFlight, tmpl *db.DBTemplate, err error) {
+ f.tmpl, f.err = tmpl, err
+ if err == nil {
+ c.put(orgID, name, tmpl)
+ }
+ c.mu.Lock()
+ delete(c.flight, key)
+ c.mu.Unlock()
+ close(f.done)
+}
+
+// put stores a resolved template. A nil template is dropped rather than stored —
+// see the package note on negative caching.
+func (c *templateCache) put(orgID uuid.UUID, name string, tmpl *db.DBTemplate) {
+ if c == nil || tmpl == nil {
+ return
+ }
+ c.mu.Lock()
+ if len(c.m) >= 4096 {
+ // Unbounded growth would be a slow leak on a cell serving many orgs, and
+ // this is a latency cache — dropping it whole is cheaper than tracking
+ // eviction order for something that refills in one request.
+ c.m = map[string]templateCacheEntry{}
+ }
+ c.m[templateCacheKey(orgID, name)] = templateCacheEntry{tmpl: tmpl, at: time.Now()}
+ c.mu.Unlock()
+}
diff --git a/internal/api/template_cache_test.go b/internal/api/template_cache_test.go
new file mode 100644
index 00000000..99e87a3c
--- /dev/null
+++ b/internal/api/template_cache_test.go
@@ -0,0 +1,339 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// The whole point of the single flight is what happens when N callers miss at
+// the same instant, so the fetch blocks until every caller has arrived.
+func TestTemplateCacheLookupSingleFlights(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ want := &db.DBTemplate{ID: uuid.New()}
+
+ const n = 100
+ var calls atomic.Int32
+ release := make(chan struct{})
+ var arrived sync.WaitGroup
+ arrived.Add(n)
+
+ var wg sync.WaitGroup
+ got := make([]*db.DBTemplate, n)
+ errs := make([]error, n)
+ for i := range n {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ arrived.Done()
+ got[i], errs[i] = c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) {
+ calls.Add(1)
+ <-release // hold the flight open so all n callers pile onto it
+ return want, nil
+ })
+ }()
+ }
+
+ arrived.Wait()
+ // Give the goroutines a moment to actually reach lookup and join the flight.
+ time.Sleep(50 * time.Millisecond)
+ close(release)
+ wg.Wait()
+
+ if c := calls.Load(); c != 1 {
+ t.Fatalf("fetch ran %d times, want exactly 1 (the herd is the bug)", c)
+ }
+ for i := range n {
+ if errs[i] != nil {
+ t.Fatalf("caller %d: unexpected error %v", i, errs[i])
+ }
+ if got[i] != want {
+ t.Fatalf("caller %d: got %v, want the single flight's result %v", i, got[i], want)
+ }
+ }
+}
+
+// A hit must not start a flight at all.
+func TestTemplateCacheLookupServesCached(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ want := &db.DBTemplate{ID: uuid.New()}
+
+ if _, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) { return want, nil }); err != nil {
+ t.Fatalf("seed lookup: %v", err)
+ }
+ got, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) {
+ t.Fatal("fetch ran on a cached entry")
+ return nil, nil
+ })
+ if err != nil || got != want {
+ t.Fatalf("got (%v, %v), want (%v, nil)", got, err, want)
+ }
+}
+
+// Errors are shared by the flight rather than silently cached: every waiter
+// sees the failure, and the NEXT caller retries instead of inheriting it.
+func TestTemplateCacheLookupSharesErrorAndDoesNotCacheIt(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ boom := errors.New("edge unreachable")
+
+ var calls atomic.Int32
+ release := make(chan struct{})
+ var wg sync.WaitGroup
+ errsOut := make([]error, 8)
+ for i := range 8 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, errsOut[i] = c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) {
+ calls.Add(1)
+ <-release
+ return nil, boom
+ })
+ }()
+ }
+ time.Sleep(50 * time.Millisecond)
+ close(release)
+ wg.Wait()
+
+ if c := calls.Load(); c != 1 {
+ t.Fatalf("fetch ran %d times, want 1", c)
+ }
+ for i, err := range errsOut {
+ if !errors.Is(err, boom) {
+ t.Fatalf("waiter %d got %v, want the flight's error", i, err)
+ }
+ }
+
+ // A failure must leave nothing behind — the retry has to reach the edge.
+ want := &db.DBTemplate{ID: uuid.New()}
+ got, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) { return want, nil })
+ if err != nil || got != want {
+ t.Fatalf("after a failed flight got (%v, %v), want a fresh fetch", got, err)
+ }
+}
+
+// A nil template (name resolves to nothing) must not be cached as a positive,
+// or create-template-then-use-it breaks for the length of the TTL.
+func TestTemplateCacheLookupDoesNotCacheNil(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+
+ var calls atomic.Int32
+ fetch := func(context.Context) (*db.DBTemplate, error) { calls.Add(1); return nil, nil }
+ for range 3 {
+ if got, err := c.lookup(t.Context(), org, "ghost", fetch); got != nil || err != nil {
+ t.Fatalf("got (%v, %v), want (nil, nil)", got, err)
+ }
+ }
+ if c := calls.Load(); c != 3 {
+ t.Fatalf("fetch ran %d times, want 3 — a nil result must stay uncached", c)
+ }
+}
+
+// Distinct keys must not share a flight.
+func TestTemplateCacheLookupKeysAreIndependent(t *testing.T) {
+ c := newTemplateCache()
+ orgA, orgB := uuid.New(), uuid.New()
+ a := &db.DBTemplate{ID: uuid.New()}
+ b := &db.DBTemplate{ID: uuid.New()}
+
+ gotA, _ := c.lookup(t.Context(), orgA, "base", func(context.Context) (*db.DBTemplate, error) { return a, nil })
+ gotB, _ := c.lookup(t.Context(), orgB, "base", func(context.Context) (*db.DBTemplate, error) { return b, nil })
+ gotName, _ := c.lookup(t.Context(), orgA, "other", func(context.Context) (*db.DBTemplate, error) { return b, nil })
+
+ if gotA != a || gotB != b || gotName != b {
+ t.Fatalf("keys bled together: orgA=%v orgB=%v otherName=%v", gotA, gotB, gotName)
+ }
+}
+
+// The load-bearing one: a STALE entry must be served immediately and refreshed
+// behind the response. If this regresses, a burst blocks on the edge round trip
+// again — the 580ms handler.
+func TestTemplateCacheLookupServesStaleWithoutBlocking(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ old := &db.DBTemplate{ID: uuid.New()}
+ fresh := &db.DBTemplate{ID: uuid.New()}
+
+ if _, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) { return old, nil }); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ // Age the entry past the TTL but well inside the stale ceiling.
+ key := templateCacheKey(org, "base")
+ c.mu.Lock()
+ e := c.m[key]
+ e.at = time.Now().Add(-(templateCacheTTL + time.Second))
+ c.m[key] = e
+ c.mu.Unlock()
+
+ refreshed := make(chan struct{})
+ start := time.Now()
+ got, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) {
+ time.Sleep(300 * time.Millisecond) // a slow edge, the whole point
+ close(refreshed)
+ return fresh, nil
+ })
+ elapsed := time.Since(start)
+
+ if err != nil {
+ t.Fatalf("stale lookup errored: %v", err)
+ }
+ if got != old {
+ t.Fatalf("got %v, want the STALE value %v served immediately", got, old)
+ }
+ if elapsed > 100*time.Millisecond {
+ t.Fatalf("stale lookup blocked for %v — it must not wait on the refresh", elapsed)
+ }
+
+ select {
+ case <-refreshed:
+ case <-time.After(3 * time.Second):
+ t.Fatal("background refresh never ran")
+ }
+ // And the refreshed value replaces it.
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if got, _ := c.get(org, "base"); got == fresh {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("refresh completed but the cache still holds the stale value")
+}
+
+// Concurrent stale reads must kick exactly ONE background refresh, not one each.
+func TestTemplateCacheStaleRefreshIsSingleFlighted(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ old := &db.DBTemplate{ID: uuid.New()}
+
+ if _, err := c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) { return old, nil }); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ key := templateCacheKey(org, "base")
+ c.mu.Lock()
+ e := c.m[key]
+ e.at = time.Now().Add(-(templateCacheTTL + time.Second))
+ c.m[key] = e
+ c.mu.Unlock()
+
+ var calls atomic.Int32
+ var wg sync.WaitGroup
+ for range 50 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, _ = c.lookup(t.Context(), org, "base", func(context.Context) (*db.DBTemplate, error) {
+ calls.Add(1)
+ time.Sleep(100 * time.Millisecond)
+ return old, nil
+ })
+ }()
+ }
+ wg.Wait()
+ time.Sleep(300 * time.Millisecond) // let the refresh finish
+
+ if n := calls.Load(); n != 1 {
+ t.Fatalf("%d background refreshes ran, want 1", n)
+ }
+}
+
+// The default-template path: a cold key must return nil IMMEDIATELY rather than
+// wait, and fill behind the caller.
+func TestTemplateCacheLookupNonBlockingNeverWaits(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ want := &db.DBTemplate{ID: uuid.New()}
+ filled := make(chan struct{})
+
+ start := time.Now()
+ got := c.lookupNonBlocking(org, "base", func(context.Context) (*db.DBTemplate, error) {
+ time.Sleep(300 * time.Millisecond) // a saturated edge
+ close(filled)
+ return want, nil
+ })
+ elapsed := time.Since(start)
+
+ if got != nil {
+ t.Fatalf("cold key returned %v, want nil (it must not wait to find out)", got)
+ }
+ if elapsed > 100*time.Millisecond {
+ t.Fatalf("blocked for %v — the default template must never block a create", elapsed)
+ }
+
+ select {
+ case <-filled:
+ case <-time.After(3 * time.Second):
+ t.Fatal("background fill never ran")
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if c.lookupNonBlocking(org, "base", func(context.Context) (*db.DBTemplate, error) {
+ return nil, errors.New("should not refetch a fresh entry")
+ }) == want {
+ return
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ t.Fatal("fill completed but the cache never served it")
+}
+
+// A burst on a cold default key must kick ONE fill, not one per caller.
+func TestTemplateCacheNonBlockingBurstFillsOnce(t *testing.T) {
+ c := newTemplateCache()
+ org := uuid.New()
+ var calls atomic.Int32
+
+ var wg sync.WaitGroup
+ for range 70 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ c.lookupNonBlocking(org, "base", func(context.Context) (*db.DBTemplate, error) {
+ calls.Add(1)
+ time.Sleep(150 * time.Millisecond)
+ return &db.DBTemplate{ID: uuid.New()}, nil
+ })
+ }()
+ }
+ wg.Wait()
+ time.Sleep(400 * time.Millisecond)
+
+ if n := calls.Load(); n != 1 {
+ t.Fatalf("%d fills ran for one cold key, want 1", n)
+ }
+}
+
+// isDefaultTemplate decides whether an unresolved name 404s. If it stopped
+// matching the pool's template name, every ordinary create would 404 on a cold
+// cache — so pin the two together.
+func TestIsDefaultTemplateTracksPoolTemplateName(t *testing.T) {
+ if !isDefaultTemplate(poolTemplateName()) {
+ t.Fatalf("isDefaultTemplate(%q) is false — an unresolved default would 404 every create", poolTemplateName())
+ }
+ if isDefaultTemplate("some-custom-template") {
+ t.Fatal("a custom template must NOT be exempt from the not-found 404")
+ }
+ if isDefaultTemplate("") {
+ t.Fatal("the empty name has its own earlier short-circuit; it must not match here")
+ }
+}
+
+// A nil cache still resolves (the edge-less / test path).
+func TestTemplateCacheLookupNilReceiver(t *testing.T) {
+ var c *templateCache
+ want := &db.DBTemplate{ID: uuid.New()}
+ got, err := c.lookup(t.Context(), uuid.New(), "base", func(context.Context) (*db.DBTemplate, error) { return want, nil })
+ if err != nil || got != want {
+ t.Fatalf("got (%v, %v), want (%v, nil)", got, err, want)
+ }
+}
diff --git a/internal/awsvm/agent.go b/internal/awsvm/agent.go
index 15553814..baac1dc2 100644
--- a/internal/awsvm/agent.go
+++ b/internal/awsvm/agent.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"fmt"
+ "io"
"log"
"net"
"net/http"
@@ -80,7 +81,31 @@ const AgentTunnelPath = agentTunnelPath
// may be mid-resume, and blocking here would put connection setup on the
// caller's critical path. gRPC connects lazily on the first RPC, and if the box
// is suspended, Lambda holds that request while it auto-resumes.
-func dialAgent(endpoint string, port int32, token tokenProvider) (*agentConn, error) {
+// holdIdle selects the keepalive contract for a channel, and the two callers
+// want opposite things from it.
+//
+// A CUSTOMER sandbox should be allowed to fall idle and suspend — that is how
+// this backend stops billing compute for a box nobody is using — so its channel
+// must not ping when there are no active RPCs.
+//
+// POOL STOCK is the exact inverse: the pool's whole job is to keep a box warm
+// and reachable so the first exec doesn't pay a handshake, and it pays for that
+// on purpose. With PermitWithoutStream false, a stocked channel emits nothing
+// between the pool's 30s application pings, so a transport that dies in between
+// is discovered only by a ping that then has to rebuild it inside pingTimeout
+// (3s) — which is far less than a WebSocket upgrade plus guest attach. Two of
+// those in a row retire the channel, and gRPC's reconnect backoff climbs toward
+// ~2 minutes, so the box stays cold. Measured consequence: 96% of edge reserves
+// found warm_tunnel=false despite every box having been dialled successfully at
+// manufacture (7456 launches, zero pre-dial failures).
+type holdIdle bool
+
+const (
+ idleMaySuspend holdIdle = false // customer sandboxes
+ idleKeepWarm holdIdle = true // pool stock
+)
+
+func dialAgent(endpoint string, port int32, token tokenProvider, hold holdIdle) (*agentConn, error) {
if endpoint == "" {
return nil, fmt.Errorf("awsvm: empty MicroVM endpoint")
}
@@ -125,14 +150,12 @@ func dialAgent(endpoint string, port int32, token tokenProvider) (*agentConn, er
grpc.MaxCallRecvMsgSize(256*1024*1024),
grpc.MaxCallSendMsgSize(256*1024*1024),
),
- // Keepalive without permit-without-stream: an idle sandbox should be
- // allowed to go idle and suspend, which is exactly how this backend
- // stops billing compute for it. Pinging a suspended box would defeat
- // the idle policy and keep it needlessly RUNNING.
+ // See holdIdle: pool stock keeps its transport alive between pings,
+ // customer sandboxes are allowed to fall idle and suspend.
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: 60 * time.Second,
Timeout: 20 * time.Second,
- PermitWithoutStream: false,
+ PermitWithoutStream: bool(hold),
}),
)
if err != nil {
@@ -147,9 +170,10 @@ func dialAgent(endpoint string, port int32, token tokenProvider) (*agentConn, er
// demand by default, so a "pre-dialled" channel that was never forced open
// would still hand the full handshake cost to the first exec.
func (c *Client) DialAgentConnected(ctx context.Context, microvmID, endpoint string) (*agentConn, error) {
+ // Pool stock: hold the transport open between the pool's 30s pings.
a, err := dialAgent(endpoint, c.cfg.AgentPort, func(ctx context.Context) (string, error) {
return c.AuthToken(ctx, microvmID)
- })
+ }, idleKeepWarm)
if err != nil {
return nil, err
}
@@ -199,10 +223,13 @@ func hostOnly(endpoint string) string {
type agentPool struct {
mu sync.Mutex
conns map[string]*agentConn
+ // failures counts CONSECUTIVE failed keepalive pings per sandbox. Reset by
+ // any success, and by dropping the channel. See pingTracked.
+ failures map[string]int
}
func newAgentPool() *agentPool {
- return &agentPool{conns: make(map[string]*agentConn)}
+ return &agentPool{conns: make(map[string]*agentConn), failures: make(map[string]int)}
}
// get returns the cached channel for a sandbox, dialing if needed.
@@ -233,7 +260,8 @@ func (p *agentPool) get(sandboxID, endpoint string, port int32, token tokenProvi
// survive to the first exec, which is exactly the ~330ms TTI penalty we are
// hunting. Logged so the cold path is visible instead of merely slow.
log.Printf("awsvm: agent COLD DIAL for %s (%s) — no warm tunnel in pool", sandboxID, endpoint)
- c, err := dialAgent(endpoint, port, token)
+ // Customer sandbox: let it fall idle and suspend.
+ c, err := dialAgent(endpoint, port, token, idleMaySuspend)
if err != nil {
return nil, err
}
@@ -296,11 +324,16 @@ func (p *agentPool) warm(sandboxIDs map[string]struct{}) int {
}
p.mu.Unlock()
+ // Only Idle is re-warmable here. Connect() is a no-op on a conn already in
+ // TransientFailure — it is retrying on gRPC's own backoff, which grows toward
+ // ~2 minutes — so counting those as "re-warmed" reports work that did not
+ // happen. Healing them is pingTracked's job: it retires the channel so the
+ // next get() re-dials.
n := 0
for _, c := range conns {
switch c.conn.GetState() {
- case connectivity.Ready, connectivity.Connecting, connectivity.Shutdown:
- default: // Idle, TransientFailure
+ case connectivity.Ready, connectivity.Connecting, connectivity.Shutdown, connectivity.TransientFailure:
+ default: // Idle
c.conn.Connect()
n++
}
@@ -344,9 +377,24 @@ func (p *agentPool) closeAll() {
// (the WebSocket 101 comes from the proxy; the proxy only dials the guest when
// payload first arrives).
+// A dead box must not be allowed to starve a live one of its keepalive.
+//
+// These two numbers together bound how long a maintenance tick can take, and
+// the worst case is every box failing: len(stock)/pingConcurrency * pingTimeout.
+// At 16/5s that is 130/16*5 = ~41s for a 130-box pool — longer than the 30s
+// tick period, so the tick overruns, the NEXT tick starts late, and the boxes
+// that were still healthy miss their keepalive and go idle too. That is not a
+// hypothetical: dev decayed 130 → 75 → 55 → 30 live tunnels over ten minutes
+// while the tick timestamps drifted off their 30s cadence, each dead box paying
+// a full 5s timeout and dragging the healthy ones down with it.
+//
+// At 64/3s the same all-dead pool costs 130/64*3 = ~6s, comfortably inside the
+// period. The timeout is still many times a healthy ping (single-digit ms
+// through an established tunnel), so it only bites on boxes that are already
+// gone.
const (
- pingConcurrency = 16
- pingTimeout = 5 * time.Second
+ pingConcurrency = 64
+ pingTimeout = 3 * time.Second
)
func (a *agentConn) ping(ctx context.Context) error {
@@ -357,6 +405,80 @@ func (a *agentConn) ping(ctx context.Context) error {
return err
}
+// proxyTouchPath is the guest endpoint the idle-timer touch requests. Served by
+// cmd/microvm-hooks on the declared hook port; cheap, side-effect free, and it
+// answers from the guest rather than the proxy, so a 200 also proves the whole
+// path is intact.
+const proxyTouchPath = "/healthz"
+
+// proxyTouchTimeout bounds one touch. Deliberately generous relative to how long
+// /healthz takes (single-digit ms): if the box has ALREADY suspended, this
+// request is what wakes it, and Lambda holds it for the length of a snapshot
+// restore. Timing out at a "reasonable" few seconds would abort our own resume
+// and leave the box suspended, which is the failure this exists to prevent.
+const proxyTouchTimeout = 30 * time.Second
+
+// proxyTouchClient is shared so touches reuse TCP/TLS connections instead of
+// paying a fresh handshake per box per tick.
+var proxyTouchClient = &http.Client{
+ Timeout: proxyTouchTimeout,
+ Transport: &http.Transport{
+ MaxIdleConns: 256,
+ MaxIdleConnsPerHost: 2,
+ IdleConnTimeout: 90 * time.Second,
+ ForceAttemptHTTP2: true,
+ TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
+ },
+}
+
+// proxyTouch sends one real HTTP request through a MicroVM's proxy endpoint, to
+// reset AWS's idle timer.
+//
+// This exists because our agent keepalive CANNOT do it, by construction. AWS
+// defines idleness as "no inbound traffic through the MicroVM proxy endpoint"
+// for maxIdleDurationSeconds — and the keepalive sends HTTP/2 PINGs INSIDE an
+// already-established WebSocket. Those are bytes on a connection the proxy
+// forwards opaquely; they are not new inbound requests, and they do not count.
+// The evidence is unambiguous: stocked boxes with a keepalive pinging them every
+// 30s still suspended at exactly the 15-minute idle window, then answered every
+// subsequent exec with 502, then were terminated 30 minutes later.
+//
+// So the touch has to be a fresh request at the proxy's own layer. It is the
+// only thing in this package that AWS's idle accounting can actually see.
+//
+// A non-2xx is returned as an error but is NOT proof the box is bad: a 502 here
+// means the proxy could not reach the guest AT THIS MOMENT, which includes a box
+// mid-resume. Callers log it; nothing evicts on it.
+func proxyTouch(ctx context.Context, endpoint string, port int32, token tokenProvider) error {
+ if endpoint == "" {
+ return fmt.Errorf("awsvm: empty MicroVM endpoint")
+ }
+ v, err := token(ctx)
+ if err != nil {
+ return fmt.Errorf("awsvm: auth token: %w", err)
+ }
+ host := hostOnly(endpoint)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+proxyTouchPath, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("X-aws-proxy-auth", v)
+ req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", port))
+
+ resp, err := proxyTouchClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("awsvm: idle touch %s: %w", host, err)
+ }
+ // Drain before closing or the connection cannot be reused, which would turn
+ // every touch into a fresh TLS handshake.
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
+ _ = resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return fmt.Errorf("awsvm: idle touch %s: http %d", host, resp.StatusCode)
+ }
+ return nil
+}
+
// warmShellTimeout bounds the manufacture-time warm-up. Generous, because it
// runs on a box nobody is waiting for and the whole point is to absorb a slow
// first shell rather than skip it.
@@ -389,48 +511,136 @@ func (a *agentConn) warmShell(ctx context.Context) error {
return err
}
-// pingAll pings every channel, bounded so a large pool cannot open hundreds of
-// concurrent RPCs on a maintenance tick. Failures are counted, not returned: a
-// box that does not answer is the tick's problem to report, not to fix.
-func pingAll(ctx context.Context, conns []*agentConn) (ok, failed int) {
+// pingEach pings every channel and returns the outcome per index (nil = ok),
+// bounded so a large pool cannot open hundreds of concurrent RPCs on a
+// maintenance tick.
+//
+// Per-index rather than a bare tally because the caller has to be able to act on
+// a specific box: a channel that keeps failing has to be retired and re-dialled,
+// and that is impossible if all the tick knows is how many failed. Returning the
+// error rather than a bool matters for the same reason — "75 failed" with the
+// cause discarded is a number nobody can act on, which is exactly how a pool
+// decaying to a third of its tunnels stayed invisible in the log.
+func pingEach(ctx context.Context, conns []*agentConn) []error {
+ errs := make([]error, len(conns))
if len(conns) == 0 {
- return 0, 0
+ return errs
}
sem := make(chan struct{}, pingConcurrency)
- var mu sync.Mutex
var wg sync.WaitGroup
- for _, c := range conns {
+ for i, c := range conns {
wg.Add(1)
- go func(c *agentConn) {
+ // Each goroutine owns its own slot, so no lock is needed.
+ go func(i int, c *agentConn) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
pctx, cancel := context.WithTimeout(ctx, pingTimeout)
defer cancel()
- err := c.ping(pctx)
- mu.Lock()
- if err != nil {
- failed++
- } else {
- ok++
- }
- mu.Unlock()
- }(c)
+ errs[i] = c.ping(pctx)
+ }(i, c)
}
wg.Wait()
+ return errs
+}
+
+// pingAll is the tally-only form, for callers with nothing to heal.
+func pingAll(ctx context.Context, conns []*agentConn) (ok, failed int) {
+ for _, err := range pingEach(ctx, conns) {
+ if err != nil {
+ failed++
+ } else {
+ ok++
+ }
+ }
return ok, failed
}
// pingTracked pings the channels held for the given sandbox ids (edge
-// reservations, which are the boxes customers actually claim).
-func (p *agentPool) pingTracked(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed int) {
+// reservations, which are the boxes customers actually claim) and RETIRES any
+// that keep failing.
+//
+// Same defect, same fix, as Pool.warmTunnels — see maxAgentPingFailures. A
+// channel that has gone bad was never replaced here either: warm() could only
+// call Connect(), which does nothing to a conn already in TransientFailure, and
+// get() explicitly leaves every non-Shutdown state alone on the theory that it
+// "does recover on its own". Measured on dev, it does not: a 130-box pool decayed
+// to 5 live tunnels and stayed there.
+//
+// This path matters more than stock's, not less. These boxes are one claim away
+// from a customer, so a dead channel here IS the cold dial on someone's first
+// exec. Dropping the entry closes the channel and forgets it, which is exactly
+// what get() needs to re-dial with a freshly minted token.
+func (p *agentPool) pingTracked(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed, retired int, sample error) {
p.mu.Lock()
+ ids := make([]string, 0, len(sandboxIDs))
conns := make([]*agentConn, 0, len(sandboxIDs))
for id := range sandboxIDs {
if c, found := p.conns[id]; found && c.conn != nil {
+ ids = append(ids, id)
conns = append(conns, c)
}
}
p.mu.Unlock()
- return pingAll(ctx, conns)
+
+ errs := pingEach(ctx, conns)
+
+ type doomedConn struct {
+ id string
+ conn *agentConn
+ }
+ var doomed []doomedConn
+ p.mu.Lock()
+ for i, err := range errs {
+ id := ids[i]
+ if err == nil {
+ delete(p.failures, id)
+ ok++
+ continue
+ }
+ failed++
+ if sample == nil {
+ sample = err
+ }
+ p.failures[id]++
+ if p.failures[id] >= maxAgentPingFailures {
+ doomed = append(doomed, doomedConn{id: id, conn: conns[i]})
+ delete(p.failures, id)
+ }
+ }
+ // A sandbox that stops being reserved while mid-failure would otherwise leave
+ // its count behind forever. Bounded cleanup, since the caller passes the full
+ // current set every tick.
+ for id := range p.failures {
+ if _, still := sandboxIDs[id]; !still {
+ delete(p.failures, id)
+ }
+ }
+ p.mu.Unlock()
+
+ // Retire only the exact channel that failed. A plain drop() would close
+ // whatever the map holds NOW, and if the box was claimed between the ping and
+ // here, put() has already installed a fresh channel for its new owner —
+ // closing that would hand the customer a broken tunnel instead of healing one.
+ for _, d := range doomed {
+ if p.dropIf(d.id, d.conn) {
+ retired++
+ }
+ }
+ return ok, failed, retired, sample
+}
+
+// dropIf closes and forgets a sandbox's channel only if it is still the one the
+// caller expects. Reports whether it did.
+func (p *agentPool) dropIf(sandboxID string, want *agentConn) bool {
+ p.mu.Lock()
+ c, found := p.conns[sandboxID]
+ if !found || c != want {
+ p.mu.Unlock()
+ return false
+ }
+ delete(p.conns, sandboxID)
+ p.mu.Unlock()
+ _ = c.Close()
+ return true
}
diff --git a/internal/awsvm/client.go b/internal/awsvm/client.go
index 07de8c97..63cd5073 100644
--- a/internal/awsvm/client.go
+++ b/internal/awsvm/client.go
@@ -59,9 +59,40 @@ type Config struct {
// ImageIdentifier is the MicroVM image ARN holding osb-agent plus the
// lifecycle hook server. ImageVersion empty means "latest active".
+ //
+ // This is also the DEFAULT SIZE TIER, and the only one the warm pool stocks.
+ // See SizeImages.
ImageIdentifier string
ImageVersion string
+ // DefaultMemoryMB is how much memory ImageIdentifier actually delivers —
+ // its minimumMemoryInMiB. 0 means the built-in baseline.
+ //
+ // Configurable rather than constant because it is a property of an image we
+ // own and can raise with UpdateMicrovmImage (no rebuild), and because
+ // metering reads it: if it drifts from the image, every sandbox on that
+ // image is billed for the wrong size.
+ DefaultMemoryMB int
+
+ // SizeImages maps a requested memory tier (MB) to the image ARN that
+ // delivers it, for tiers OTHER than the default.
+ //
+ // Sizing is a property of the image on this platform — RunMicrovmInput has
+ // no memory or vCPU field, and the only knob anywhere is
+ // Resources.MinimumMemoryInMiB at image build/update time. So "offer more
+ // sizes" means "run more images", one per tier, selected at launch.
+ //
+ // Only the default tier is pooled. Every other tier cold-launches, which is
+ // the deliberate trade: warm stock is per-image, so N pooled tiers would
+ // either multiply idle spend by N or split one pool N ways and destroy the
+ // latency the pool exists for.
+ //
+ // A tier absent from this map is NOT silently served from the default
+ // image. It is rejected — see Manager.Create. Handing a 16 GB request a
+ // 4 GB box is the silent-wrong-size failure this whole path is built to
+ // avoid.
+ SizeImages map[int]string
+
// ExecutionRoleArn is assumed by the MicroVM itself, for the guest's own AWS
// access. It is NOT the role this worker uses to call the API.
ExecutionRoleArn string
@@ -102,14 +133,79 @@ func (c *Config) applyDefaults() {
c.MaxDurationSeconds = maxDurationCeilingSeconds
}
if c.MaxIdleDurationSeconds <= 0 {
- c.MaxIdleDurationSeconds = 900
+ // Both idle timers default to the total-lifetime ceiling, which means
+ // neither can fire before the 8h cap does. That leaves ONE deadline to
+ // reason about instead of three interacting ones.
+ //
+ // The previous defaults (900 idle / 1800 suspended) were measured doing
+ // real damage. AWS counts a box idle when no request arrives through its
+ // PROXY ENDPOINT — an established agent tunnel carrying h2 PINGs is not
+ // proxy traffic and does not count — so pool stock suspended after 15
+ // minutes of waiting despite a keepalive that was pinging it every 30s.
+ // A suspended box answers the proxy with 502, which is exactly the 502
+ // that was failing customer execs, and 30 minutes later AWS terminated
+ // it outright. See Pool.touchIdleTimers for the other half of the fix.
+ c.MaxIdleDurationSeconds = maxDurationCeilingSeconds
}
if c.SuspendedDurationSeconds <= 0 {
// Suspended boxes bill snapshot storage rather than compute, so holding
// them is cheap — but they still count against the region's memory
// quota, which is what actually caps warm-pool depth.
- c.SuspendedDurationSeconds = 1800
+ //
+ // Cheap is not the reason for the ceiling, though. When this timer fires
+ // AWS TERMINATES the box and takes its disk with it, so any value short
+ // of the cap silently converts "parked sandbox" into "deleted sandbox".
+ c.SuspendedDurationSeconds = maxDurationCeilingSeconds
+ }
+ if c.DefaultMemoryMB <= 0 {
+ c.DefaultMemoryMB = deliveredMicrovmMemoryMB
+ }
+}
+
+// ImageForMemory resolves which image delivers a requested memory tier, and how
+// much memory that image actually provides.
+//
+// memoryMB 0 means "unspecified" — the caller gets the default tier, which is
+// the pooled one. Anything matching the default's delivered size is also the
+// default tier, so a request that names the size it would get anyway still
+// takes the fast path rather than being pushed to a cold launch.
+//
+// ok=false means the tier is not offered here. Callers MUST surface that as an
+// error rather than falling back to the default image: the whole reason this
+// returns a bool instead of just defaulting is that a silent downgrade bills a
+// customer for one size and hands them another.
+func (c Config) ImageForMemory(memoryMB int) (image string, deliveredMB int, ok bool) {
+ if memoryMB == 0 || memoryMB == c.DefaultMemoryMB {
+ return c.ImageIdentifier, c.DefaultMemoryMB, true
+ }
+ if arn, found := c.SizeImages[memoryMB]; found && arn != "" {
+ return arn, memoryMB, true
}
+ return "", 0, false
+}
+
+// IsDefaultTier reports whether a request can be served from warm stock. Only
+// the default tier is pooled, so this is what gates a pool claim.
+func (c Config) IsDefaultTier(memoryMB int) bool {
+ return memoryMB == 0 || memoryMB == c.DefaultMemoryMB
+}
+
+// OwnedImages lists every image ARN this cell launches boxes from.
+//
+// The orphan sweep uses the image ARN as its ownership test, so it has to know
+// about every tier — a box launched from a tier image would otherwise look like
+// it belongs to nobody and be terminated underneath a live customer.
+func (c Config) OwnedImages() []string {
+ out := make([]string, 0, 1+len(c.SizeImages))
+ if c.ImageIdentifier != "" {
+ out = append(out, c.ImageIdentifier)
+ }
+ for _, arn := range c.SizeImages {
+ if arn != "" && arn != c.ImageIdentifier {
+ out = append(out, arn)
+ }
+ }
+ return out
}
// Box is one MicroVM as this package sees it.
@@ -186,8 +282,21 @@ func (c *Client) Config() Config { return c.cfg }
// because a leaked VM burns regional memory quota until it ages out — and quota
// is what caps warm-pool depth.
func (c *Client) Run(ctx context.Context, clientToken string) (*Box, error) {
+ return c.RunImage(ctx, clientToken, c.cfg.ImageIdentifier)
+}
+
+// RunImage is Run against a specific image, for size tiers other than the
+// default (see Config.SizeImages). An empty image means the default.
+//
+// Separate entry point rather than a Config field so the warm pool keeps
+// launching the default image with no change: the pool is deliberately
+// single-tier, and a tier selected per-call must not be able to leak into it.
+func (c *Client) RunImage(ctx context.Context, clientToken, image string) (*Box, error) {
+ if image == "" {
+ image = c.cfg.ImageIdentifier
+ }
in := &lambdamicrovms.RunMicrovmInput{
- ImageIdentifier: aws.String(c.cfg.ImageIdentifier),
+ ImageIdentifier: aws.String(image),
MaximumDurationInSeconds: aws.Int32(c.cfg.MaxDurationSeconds),
IdlePolicy: &types.IdlePolicy{
AutoResumeEnabled: aws.Bool(c.cfg.AutoResume),
@@ -195,7 +304,10 @@ func (c *Client) Run(ctx context.Context, clientToken string) (*Box, error) {
SuspendedDurationSeconds: aws.Int32(c.cfg.SuspendedDurationSeconds),
},
}
- if c.cfg.ImageVersion != "" {
+ // ImageVersion pins a version of the DEFAULT image. Version numbers are
+ // per-image, so carrying it onto a tier image would either pin an unrelated
+ // build or fail outright — a tier image takes its own latest active.
+ if c.cfg.ImageVersion != "" && image == c.cfg.ImageIdentifier {
in.ImageVersion = aws.String(c.cfg.ImageVersion)
}
if c.cfg.ExecutionRoleArn != "" {
diff --git a/internal/awsvm/keepalive_test.go b/internal/awsvm/keepalive_test.go
new file mode 100644
index 00000000..792ed937
--- /dev/null
+++ b/internal/awsvm/keepalive_test.go
@@ -0,0 +1,206 @@
+package awsvm
+
+import (
+ "errors"
+ "testing"
+ "time"
+)
+
+// The bug these cover: a stocked box's agent channel that went bad was never
+// replaced. warmTunnels healed a MISSING channel by re-dialling, but a channel
+// that was present-and-dead only ever got ClientConn.Connect() — a no-op on a
+// conn already in TransientFailure — so the pool decayed monotonically and every
+// exec that landed on one of those boxes paid a full cold dial. Measured on dev
+// at a 130-box pool: 75 live tunnels, then 55, then 30.
+
+func TestFailedPingRetiresChannelForRedial(t *testing.T) {
+ p, _ := testPool(t, PoolConfig{TargetStock: 2})
+
+ entry := &StockEntry{MicrovmID: "mvm-dead"}
+ entry.agent = &agentConn{}
+ live := []*StockEntry{entry}
+ boom := errors.New("agent tunnel handshake: 401")
+
+ // One failure is forgiven: a box that is merely mid-resume must not have a
+ // working tunnel churned out from under it.
+ ok, failed, retired, dead, sample := p.applyPingResults(live, []error{boom})
+ if ok != 0 || failed != 1 || retired != 0 {
+ t.Fatalf("first failure: ok=%d failed=%d retired=%d, want 0/1/0", ok, failed, retired)
+ }
+ if len(dead) != 0 {
+ t.Fatalf("first failure closed %d channel(s), want 0", len(dead))
+ }
+ if entry.agent == nil {
+ t.Fatal("first failure cleared the channel; one blip must be tolerated")
+ }
+ if sample == nil {
+ t.Fatal("sampled error not returned — an unexplained failure count is what hid this bug")
+ }
+
+ // The second consecutive failure retires it, so the bounded re-dial path
+ // rebuilds it next tick with a freshly minted token.
+ _, _, retired, dead, _ = p.applyPingResults(live, []error{boom})
+ if retired != 1 {
+ t.Fatalf("retired = %d after %d consecutive failures, want 1", retired, maxAgentPingFailures)
+ }
+ if len(dead) != 1 {
+ t.Fatalf("returned %d channel(s) to close, want 1 — not closing it leaks the socket", len(dead))
+ }
+ if entry.agent != nil {
+ t.Fatal("agent still set after retirement; warmTunnels only re-dials entries with agent == nil")
+ }
+}
+
+func TestSuccessfulPingResetsTheFailureRun(t *testing.T) {
+ p, _ := testPool(t, PoolConfig{TargetStock: 2})
+
+ entry := &StockEntry{MicrovmID: "mvm-flaky"}
+ entry.agent = &agentConn{}
+ live := []*StockEntry{entry}
+
+ // Fail, recover, fail: the run is broken by the success, so this must not
+ // count as two consecutive failures and retire a working channel.
+ p.applyPingResults(live, []error{errors.New("timeout")})
+ p.applyPingResults(live, []error{nil})
+ if entry.agentFailures != 0 {
+ t.Fatalf("agentFailures = %d after a success, want 0", entry.agentFailures)
+ }
+ _, _, retired, _, _ := p.applyPingResults(live, []error{errors.New("timeout")})
+ if retired != 0 {
+ t.Fatalf("retired a channel whose failures were not consecutive")
+ }
+ if entry.agent == nil {
+ t.Fatal("cleared the channel of a box that answered in between")
+ }
+}
+
+// A box claimed between the ping and the fold-back has had its channel handed to
+// the manager, which clears this field. Closing the conn we pinged would tear
+// down a live customer's tunnel.
+func TestRetirementNeverClosesAChannelTheEntryNoLongerHolds(t *testing.T) {
+ p, _ := testPool(t, PoolConfig{TargetStock: 2})
+
+ entry := &StockEntry{MicrovmID: "mvm-claimed"}
+ entry.agent = &agentConn{}
+ live := []*StockEntry{entry}
+ boom := errors.New("unavailable")
+
+ p.applyPingResults(live, []error{boom})
+ // TrackClaimed transfers ownership and clears the field.
+ entry.agent = nil
+
+ _, _, retired, dead, _ := p.applyPingResults(live, []error{boom})
+ if retired != 0 || len(dead) != 0 {
+ t.Fatalf("retired=%d closed=%d for an entry that no longer owns its channel, want 0/0", retired, len(dead))
+ }
+}
+
+// The same defect lived on the edge-reservation path, where it matters more:
+// these boxes are one claim away from a customer, so a dead channel here IS the
+// cold dial on someone's first exec. warm() could only call Connect() (a no-op
+// in TransientFailure) and get() deliberately left every non-Shutdown state
+// alone, so nothing ever replaced a channel that had gone bad.
+func TestDropIfOnlyRetiresTheChannelThatFailed(t *testing.T) {
+ p := newAgentPool()
+ failed := &agentConn{}
+ p.conns["sb-1"] = failed
+
+ if !p.dropIf("sb-1", failed) {
+ t.Fatal("dropIf refused to retire the channel it was given")
+ }
+ if _, still := p.conns["sb-1"]; still {
+ t.Fatal("channel still cached after retirement; get() re-dials only on a miss")
+ }
+
+ // The hazard: the box is claimed between the ping and the retirement, and
+ // put() installs a fresh channel for its new owner. Retiring by id alone
+ // would close that one and hand the customer a broken tunnel.
+ fresh := &agentConn{}
+ p.conns["sb-2"] = fresh
+ stale := &agentConn{}
+ if p.dropIf("sb-2", stale) {
+ t.Fatal("dropIf closed a channel that had already been replaced")
+ }
+ if p.conns["sb-2"] != fresh {
+ t.Fatal("the new owner's channel was evicted")
+ }
+}
+
+func TestPingTrackedForgetsFailureCountsForUnreservedBoxes(t *testing.T) {
+ p := newAgentPool()
+ // Left over from a box that stopped being reserved while mid-failure. Without
+ // pruning, this map grows for the process's lifetime.
+ p.failures["sb-gone"] = 1
+
+ p.pingTracked(t.Context(), map[string]struct{}{"sb-here": {}})
+ if _, leaked := p.failures["sb-gone"]; leaked {
+ t.Fatal("failure count retained for a box that is no longer reserved")
+ }
+}
+
+// The idle-timer touch is the ONLY thing in this package AWS's idle accounting
+// can see — an h2 PING inside an established tunnel is not inbound proxy
+// traffic. So the one property that matters is that the touch cadence stays
+// comfortably inside whatever idle window the box was launched with, for every
+// window someone might configure. Getting this wrong does not fail loudly: the
+// box is suspended, answers 502, and is terminated half an hour later.
+func TestIdleTouchIntervalStaysInsideTheIdleWindow(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ windowSec int32
+ want time.Duration
+ mustCover bool // the interval must leave room for two missed touches
+ }{
+ // The 8h ceiling, which is the default. A literal third would be 2h40m —
+ // long enough that a window lowered elsewhere would go unnoticed for
+ // hours, so the ceiling clamp holds it at 15 minutes.
+ {name: "8h ceiling", windowSec: 28_800, want: 15 * time.Minute, mustCover: true},
+ // The old default, and the one that was actually suspending stock.
+ {name: "old 15m default", windowSec: 900, want: 5 * time.Minute, mustCover: true},
+ // The service minimum. A third is 20s, floored to a minute — which no
+ // longer covers two missed touches, and cannot: we refuse to send a
+ // network request per box more often than that.
+ {name: "service minimum", windowSec: 60, want: time.Minute, mustCover: false},
+ // Unset — the pool must still touch on some sane cadence rather than
+ // treating "no window" as "never suspends".
+ {name: "unconfigured", windowSec: 0, want: 5 * time.Minute, mustCover: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := NewClientWithAPI(&poolAPI{}, Config{
+ ImageIdentifier: "arn:image",
+ MaxIdleDurationSeconds: tc.windowSec,
+ })
+ // Config.applyDefaults raises a zero window to the ceiling, so drive
+ // the unconfigured case through the field the method actually reads.
+ if tc.windowSec == 0 {
+ c.cfg.MaxIdleDurationSeconds = 0
+ }
+ got := NewPool(c, PoolConfig{TargetStock: 1}).idleTouchInterval()
+ if got != tc.want {
+ t.Fatalf("idleTouchInterval() = %s, want %s", got, tc.want)
+ }
+ if got < time.Minute {
+ t.Fatalf("interval %s would touch every box more than once a minute", got)
+ }
+ window := time.Duration(tc.windowSec) * time.Second
+ if tc.mustCover && tc.windowSec > 0 && got*3 > window {
+ t.Fatalf("interval %s leaves no room for two missed touches inside a %s window", got, window)
+ }
+ })
+ }
+}
+
+func TestPingEachReportsPerIndexSoFailuresCanBeAttributed(t *testing.T) {
+ // A nil client pings OK (see agentConn.ping), which is enough to prove the
+ // result slice stays aligned with the input — the property retirement relies
+ // on to map a failure back to the entry that owns the channel.
+ conns := []*agentConn{{}, {}, {}}
+ errs := pingEach(t.Context(), conns)
+ if len(errs) != len(conns) {
+ t.Fatalf("pingEach returned %d results for %d conns", len(errs), len(conns))
+ }
+ ok, failed := pingAll(t.Context(), conns)
+ if ok != 3 || failed != 0 {
+ t.Fatalf("pingAll = %d ok / %d failed, want 3/0", ok, failed)
+ }
+}
diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.go
index d28eef0f..938379a7 100644
--- a/internal/awsvm/manager.go
+++ b/internal/awsvm/manager.go
@@ -26,11 +26,16 @@ import (
// tens of thousands internal/qemu needs.
//
// Deliberately unsupported here (see ErrUnsupported): checkpoints, fork-from-
-// checkpoint, template/checkpoint caches, reboot and power-cycle. Those are
-// snapshot-and-disk operations with no counterpart in this service; a MicroVM
-// image is built through an API, not captured from a running box. They return a
-// typed error the control plane can turn into a clean 4xx rather than a panic
-// or, worse, a silent success.
+// checkpoint, and resource limits. The first two are snapshot-and-disk
+// operations with no counterpart in this service — a MicroVM image is built
+// through an API, not captured from a running box. The third has no knob to
+// turn: sizing belongs to the image, not the sandbox (see deliveredSize). They
+// return a typed error the control plane can turn into a clean 501 rather than
+// a panic or, worse, a silent success.
+//
+// Reboot and power-cycle ARE supported (PowerCycleSandbox delegates to
+// RebootSandbox); template/checkpoint caches are inert rather than erroring,
+// since "" is a truthful answer to "is it cached locally".
// ErrUnsupported marks a Manager capability this backend does not implement.
// Callers should surface it as "not available on this runtime", never retry it.
@@ -121,37 +126,87 @@ func (m *Manager) TrackClaimed(sandboxID string, e *StockEntry, cfg types.Sandbo
// pro-tier metering prices on. Whatever is recorded here is what the customer
// is billed for.
//
-// 2048 MiB matches the image's minimumMemoryInMiB, and Lambda gives a full vCPU
-// at that baseline (peak scales to 4x).
+// The default image's minimumMemoryInMiB, used when Config.DefaultMemoryMB is
+// unset. MUST track the image or every box is metered at the wrong size.
+//
+// Raised 2048 → 4096 on 2026-08-24 (image version 12.0) so the backend actually
+// delivers the platform default: the API defaults a create to 4096 and QEMU
+// gives 4096, while this image gave 2048 — so every default create was silently
+// served half what it asked for, and metered at the half.
+//
+// Lambda gives a full vCPU from 2048 up (peak scales to 4x), so 4096 keeps the
+// 1-vCPU tier promise. Supported sizes are an ENUM, not a free integer:
+// [512, 1024, 2048, 4096, 8192] on base image al2023-1.
const (
- deliveredMicrovmMemoryMB = 2048
+ deliveredMicrovmMemoryMB = 4096
deliveredMicrovmCPUCount = 1
)
-// deliveredSize reports what the platform actually provides, which on this
-// backend has nothing to do with what was requested.
+// vcpusForMemory reports the vCPU count that goes with a memory tier.
+//
+// We do NOT control this. There is no vCPU field anywhere in the API —
+// CpuConfiguration carries an Architecture (x86_64/arm64) and nothing else — so
+// the platform allocates CPU as a function of memory. The tier table is
+// therefore the honest reading of what a customer on that tier is buying, and
+// the same number QEMU delivers for it, which is what parity means here.
+//
+// Unknown tiers fall back to the baseline rather than guessing upward: over-
+// reporting cpuCount is an overcharge, and the meter reads this.
+//
+// NOT VALIDATED per tier. The proportional allocation is documented for the
+// default only; the 1024 tier is the one to check first, because it is the only
+// tier whose memory sits BELOW the baseline where a full vCPU is known good.
+func vcpusForMemory(memoryMB int) int {
+ for _, t := range types.AllowedResourceTiers {
+ if t.MemoryMB == memoryMB {
+ return t.VCPUs
+ }
+ }
+ return deliveredMicrovmCPUCount
+}
+
+// deliveredSize reports what the platform actually provides for a request,
+// given the memory the resolved image delivers.
//
// RunMicrovmInput has no memory or vCPU field — sizing is a property of the
-// IMAGE, and the seven-operation API has no way to change it before or after
-// launch. So a create asking for 8 GB gets the image baseline either way.
+// IMAGE. Offering more than one size means running more than one image and
+// picking at launch (Config.SizeImages); within a single image there is no knob
+// to turn at all.
//
// This used to record the REQUESTED size, which was never sent to AWS but was
// still what the meter charged for: ask for 8 GB, receive the baseline, pay for
// 8 GB. A silent overcharge that scaled with the size of the ask. Metering the
// delivered size is the only honest reading, and the mismatch is logged rather
-// than swallowed so an operator can see demand the image cannot satisfy.
-func deliveredSize(sandboxID string, requestedMemoryMB, requestedCPUCount int) (memoryMB, cpuCount int) {
- if requestedMemoryMB > deliveredMicrovmMemoryMB || requestedCPUCount > deliveredMicrovmCPUCount {
+// than swallowed so an operator can see demand the images cannot satisfy.
+func deliveredSize(sandboxID string, requestedMemoryMB, requestedCPUCount, deliveredMemoryMB int) (memoryMB, cpuCount int) {
+ if deliveredMemoryMB <= 0 {
+ deliveredMemoryMB = deliveredMicrovmMemoryMB
+ }
+ cpuCount = vcpusForMemory(deliveredMemoryMB)
+ if requestedMemoryMB > deliveredMemoryMB || requestedCPUCount > cpuCount {
log.Printf("awsvm: %s requested %dMB/%dcpu but this backend delivers %dMB/%dcpu — "+
- "metering the delivered size (the platform has no sizing knob)",
+ "metering the delivered size (sizing is a property of the image)",
sandboxID, requestedMemoryMB, requestedCPUCount,
- deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount)
+ deliveredMemoryMB, cpuCount)
}
- return deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount
+ return deliveredMemoryMB, cpuCount
}
-func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) {
- memoryMB, cpuCount := deliveredSize(sandboxID, cfg.MemoryMB, cfg.CpuCount)
+// Track records a sandbox→MicroVM binding and returns the size it recorded.
+//
+// The return values exist so callers can report the DELIVERED size rather than
+// the requested one. Get reads them back off the entry; Create used to echo
+// cfg.MemoryMB/cfg.CpuCount straight back instead, so a create asking for 8 GB
+// answered "8192" and the very next Get on the same sandbox answered "2048".
+// Same reasoning as deliveredSize itself: the requested number is not a fact
+// about this sandbox, and repeating it anywhere is how it ends up believed.
+func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) (memoryMB, cpuCount int) {
+ // Which tier this box actually is. A request for a tier we do not offer is
+ // rejected in Create long before here; if one somehow reaches this point,
+ // resolving to the default is the safe direction (it is what the box
+ // physically is) and deliveredSize logs the mismatch.
+ _, deliveredMB, _ := m.config().ImageForMemory(cfg.MemoryMB)
+ memoryMB, cpuCount = deliveredSize(sandboxID, cfg.MemoryMB, cfg.CpuCount, deliveredMB)
m.mu.Lock()
m.byID[sandboxID] = &entry{
sandboxID: sandboxID,
@@ -163,6 +218,21 @@ func (m *Manager) Track(sandboxID string, box *Box, cfg types.SandboxConfig) {
startedAt: time.Now(),
}
m.mu.Unlock()
+ return memoryMB, cpuCount
+}
+
+// config returns the client's resolved config, tolerating a nil client.
+//
+// Track runs on paths that construct a Manager without one (tests, and the
+// bookkeeping-only callers that never talk to AWS), so reaching through
+// m.client unguarded turns a pure in-memory bind into a panic. Defaults applied
+// here match applyDefaults so an unconfigured Manager still resolves the
+// default tier rather than reporting 0 MB.
+func (m *Manager) config() Config {
+ if m == nil || m.client == nil {
+ return Config{DefaultMemoryMB: deliveredMicrovmMemoryMB}
+ }
+ return m.client.Config()
}
// MicrovmIDFor returns the AWS MicroVM id bound to a sandbox, from memory only.
@@ -207,20 +277,30 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.S
if sandboxID == "" {
return nil, fmt.Errorf("awsvm: create requires a pre-assigned sandbox id")
}
- box, err := m.client.Run(ctx, sandboxID)
+ // Pick the image that delivers the requested size. A tier with no image
+ // configured is refused rather than served from the default: handing a 16 GB
+ // request a 4 GB box, and billing it as 4 GB, is a silent wrong-size
+ // delivery — the failure mode ErrUnsupported exists to make impossible.
+ image, _, ok := m.config().ImageForMemory(cfg.MemoryMB)
+ if !ok {
+ return nil, fmt.Errorf("awsvm: %s: no image configured for %dMB: %w",
+ sandboxID, cfg.MemoryMB, ErrUnsupported)
+ }
+ box, err := m.client.RunImage(ctx, sandboxID, image)
if err != nil {
return nil, err
}
- m.Track(sandboxID, box, cfg)
+ memoryMB, cpuCount := m.Track(sandboxID, box, cfg)
log.Printf("awsvm: created %s (microvm=%s endpoint=%s)", sandboxID, box.ID, box.Endpoint)
+ // Delivered, not requested — see Track. Get answers from the same numbers.
return &types.Sandbox{
ID: sandboxID,
Template: cfg.Template,
Status: types.SandboxStatusRunning,
StartedAt: time.Now(),
- CpuCount: cfg.CpuCount,
- MemoryMB: cfg.MemoryMB,
+ CpuCount: cpuCount,
+ MemoryMB: memoryMB,
}, nil
}
@@ -693,8 +773,20 @@ func (m *Manager) restoreFromArchive(ctx context.Context, sandboxID, key string,
// configuration, and cannot be resized in place the way virtio-mem allows.
// Returning nil rather than an error keeps the control plane's post-claim grow
// step harmless instead of failing every create.
+// SetResourceLimits cannot be honoured on this backend.
+//
+// Sizing is a property of the IMAGE (see deliveredSize): RunMicrovmInput has no
+// memory or vCPU field, and the only knob in the whole API is
+// Resources.MinimumMemoryInMiB at image build/update time — which is
+// account-wide for every box on that image, not per sandbox.
+//
+// This used to `return nil`, which made a resize request answer 200 OK and
+// change nothing. That is the failure mode ErrUnsupported exists to prevent: a
+// caller cannot tell a silent success apart from a real one, so it believes a
+// limit is in force that was never applied. 501 tells the truth — the operation
+// will never succeed on this runtime, so do not retry it.
func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPids int32, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec int64) error {
- return nil
+ return unsupported("SetResourceLimits")
}
// UpdateSandboxSecret injects or replaces a secret in a running sandbox.
@@ -963,6 +1055,10 @@ func (m *Manager) DirectInfo(ctx context.Context, sandboxID string) (endpoint, t
// PingAgents keeps the given sandboxes' boxes out of AWS's idle policy. See the
// keepalive block in agent.go for why an open connection is not enough.
-func (m *Manager) PingAgents(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed int) {
+//
+// Also retires channels that keep failing, so a reservation whose tunnel died
+// does not hand its eventual customer a cold dial. retired counts those; sample
+// is one representative failure, for the caller to log.
+func (m *Manager) PingAgents(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed, retired int, sample error) {
return m.agents.pingTracked(ctx, sandboxIDs)
}
diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.go
index cc3cd365..a5c967a7 100644
--- a/internal/awsvm/pool.go
+++ b/internal/awsvm/pool.go
@@ -3,6 +3,7 @@ package awsvm
import (
"context"
"errors"
+ "fmt"
"log"
"sync"
"time"
@@ -189,6 +190,29 @@ type StockEntry struct {
// box is idle in stock, for the same reason tokens are pre-minted.
agent *agentConn
+ // agentFailures counts CONSECUTIVE failed keepalive pings on the channel
+ // above. Reset by any success. Once it reaches maxAgentPingFailures the
+ // channel is retired and re-dialled — see warmTunnels.
+ agentFailures int
+
+ // redialFailures counts CONSECUTIVE failed attempts to give this box a
+ // tunnel back. Reset by any success.
+ //
+ // Retiring a channel used to be the end of the line: the box went
+ // tunnel-less, the re-dial failed silently, and it sat in stock — countable
+ // by Depth(), claimable by the edge, dead to every customer that got it —
+ // until MaxBoxAge (7h) evicted it on age alone. Measured on dev: 34 in stock
+ // against ONE live microVM in the whole account, and creates kept succeeding
+ // onto the corpses. A box whose tunnel cannot be rebuilt with a freshly
+ // minted token is not cold, it is gone, and stock must say so.
+ redialFailures int
+
+ // lastProxyTouch is when this box last received a real inbound request
+ // through its AWS proxy endpoint — the only kind of traffic AWS's idle
+ // accounting can see. Zero means "never since we started tracking", which
+ // makes the box due immediately. See Pool.touchIdleTimers.
+ lastProxyTouch time.Time
+
tokenMintedAt time.Time
launchedAt time.Time
}
@@ -498,6 +522,11 @@ func (p *Pool) Run(ctx context.Context) {
p.refreshTokens(ctx)
p.retireAged(ctx)
p.warmTunnels(ctx)
+ // Runs in its own goroutine: a touch against a box that has already
+ // suspended is held by Lambda for the length of a snapshot restore,
+ // and blocking the maintenance tick on that would stall token
+ // refresh, retirement and reservation expiry behind it.
+ go p.touchIdleTimers(ctx)
if p.cfg.OnMaintain != nil {
p.cfg.OnMaintain()
}
@@ -776,10 +805,14 @@ func (p *Pool) retireAged(ctx context.Context) {
func (p *Pool) warmTunnels(ctx context.Context) {
p.mu.Lock()
conns := make([]*agentConn, 0, len(p.stock))
+ // Kept aligned with conns so a ping failure can be attributed back to the
+ // entry that owns the channel, which is what makes retiring one possible.
+ live := make([]*StockEntry, 0, len(p.stock))
var missing []*StockEntry
for _, e := range p.stock {
if e.agent != nil {
conns = append(conns, e.agent)
+ live = append(live, e)
continue
}
// No tunnel at all. The common cause is a round trip through the edge:
@@ -804,18 +837,89 @@ func (p *Pool) warmTunnels(ctx context.Context) {
// AWS to suspend it. This is the expensive-on-purpose half of the trade —
// an unsuspended box bills compute while it waits — and it is what keeps a
// claim's first exec off the ~1s resume path.
- if ok, failed := pingAll(ctx, conns); ok+failed > 0 {
- log.Printf("awsvm: pool keepalive pinged %d stocked box(es) (%d failed)", ok, failed)
+ //
+ // A channel that keeps failing is RETIRED here rather than nudged. The
+ // re-warm loop below can only call ClientConn.Connect(), which moves an Idle
+ // conn to Connecting and does nothing at all to one already in
+ // TransientFailure — and gRPC's own reconnect backoff climbs toward ~2
+ // minutes, so a channel that went bad stays bad. Nothing else ever replaced
+ // it either: the re-dial path below heals a MISSING tunnel (e.agent == nil)
+ // and a dead-but-present one is not missing, so it was never a candidate.
+ //
+ // The result was a pool that decayed monotonically and never recovered —
+ // measured on dev at a 130-box pool: 75 live tunnels, then 55, then 30, with
+ // the tick reporting "re-warmed 75" every 30s while re-warming nothing. Every
+ // exec against one of those boxes pays a full cold dial (~1.1s guest attach),
+ // which is precisely the cost this pre-dial exists to avoid.
+ //
+ // Retiring means: close the channel, clear the field, and let the bounded
+ // re-dial above rebuild it on the next tick with a freshly minted token. That
+ // also covers the case Connect() could never have fixed — the token expired,
+ // so the WebSocket upgrade itself is being refused and only a new dial with a
+ // new credential can succeed.
+ ok, failed, retired, dead, sample := p.applyPingResults(live, pingEach(ctx, conns))
+ for _, a := range dead {
+ _ = a.Close()
+ }
+ if ok+failed > 0 {
+ // The sampled error is the point of the line. "75 failed" on its own is
+ // unactionable, and was: it took watching the count decay across ten
+ // minutes to work out that anything was wrong at all.
+ msg := fmt.Sprintf("awsvm: pool keepalive pinged %d stocked box(es) (%d failed", ok, failed)
+ if retired > 0 {
+ msg += fmt.Sprintf(", %d channel(s) retired for re-dial", retired)
+ }
+ msg += ")"
+ if sample != nil {
+ msg += fmt.Sprintf("; first failure: %v", sample)
+ }
+ log.Print(msg)
}
if p.preDial != nil {
+ redialed, redialFailed := 0, 0
+ var firstErr error
+ var firstErrBox string
+ var evicted []*StockEntry
for _, e := range missing {
dialCtx, cancel := context.WithTimeout(ctx, p.cfg.PreDialTimeout)
a, err := p.preDial(dialCtx, e.MicrovmID, e.Endpoint)
cancel()
if err != nil {
+ // The error was previously discarded here, and the line below
+ // reported len(missing) — boxes ATTEMPTED — so a tick that healed
+ // nothing logged identically to one that healed everything. That
+ // is why a pool sitting at 1 live box out of 34 in stock looked
+ // healthy: this is the only place that knows why a stocked box
+ // cannot get a tunnel, and it threw the reason away.
+ redialFailed++
+ if firstErr == nil {
+ firstErr, firstErrBox = err, e.MicrovmID
+ }
+ // Count it against the box, and evict once it is out of chances.
+ // The dial mints a fresh token first, so an expired credential
+ // cannot cause this; what remains is a box that is gone.
+ p.mu.Lock()
+ e.redialFailures++
+ doomed := e.redialFailures >= maxRedialFailures
+ if doomed {
+ for i, s := range p.stock {
+ if s == e {
+ p.stock = append(p.stock[:i], p.stock[i+1:]...)
+ break
+ }
+ }
+ }
+ p.mu.Unlock()
+ if doomed {
+ evicted = append(evicted, e)
+ }
continue // still usable cold; try again next tick
}
+ redialed++
+ p.mu.Lock()
+ e.redialFailures = 0
+ p.mu.Unlock()
// Re-check under the lock: the entry may have been reserved or
// terminated while we dialled, and installing a tunnel on an entry
// that has left stock would leak the channel.
@@ -834,11 +938,44 @@ func (p *Pool) warmTunnels(ctx context.Context) {
}
}
if len(missing) > 0 {
- log.Printf("awsvm: pool re-dialled tunnels for %d tunnel-less stocked box(es)", len(missing))
+ // Successes and failures separately, plus a sampled error. A count of
+ // attempts cannot distinguish "stock is healing" from "stock is dead
+ // and every dial is refused", and those have completely different
+ // fixes. `capped` marks the ticks where warmDialPerTick truncated the
+ // work, so a backlog is visible rather than looking like a steady
+ // trickle of the same 32 boxes.
+ msg := fmt.Sprintf("awsvm: pool re-dial: %d healed, %d failed, of %d tunnel-less stocked box(es)",
+ redialed, redialFailed, len(missing))
+ if len(missing) >= warmDialPerTick {
+ msg += " (capped this tick — more are waiting)"
+ }
+ if len(evicted) > 0 {
+ msg += fmt.Sprintf("; EVICTED %d unreachable box(es) after %d consecutive failures", len(evicted), maxRedialFailures)
+ }
+ if firstErr != nil {
+ msg += fmt.Sprintf("; first failure %s: %v", firstErrBox, firstErr)
+ }
+ log.Print(msg)
+ }
+ // Outside the lock: terminate reaches AWS. These boxes are already out
+ // of stock, so nothing can claim them while this runs.
+ for _, e := range evicted {
+ go p.terminate(e)
}
}
- rewarmed := 0
+ // Nudge Idle channels back to Connecting. This is a genuine, cheap win — an
+ // Idle conn has no transport but no problem either, and Connect() rebuilds it
+ // before a customer needs it.
+ //
+ // TransientFailure is counted SEPARATELY and deliberately not nudged.
+ // Connect() is documented as a no-op on a conn that is already trying, and
+ // these are already trying — on gRPC's own backoff, which grows toward ~2
+ // minutes. Lumping the two together is what produced "re-warmed 75 idle agent
+ // tunnel(s)" every 30s on a pool where nothing was being re-warmed and the
+ // live count was falling: the number described an intention, not an effect.
+ // Failing channels are healed by the retirement above, not here.
+ idle, failing := 0, 0
for _, a := range conns {
if a.conn == nil {
continue
@@ -848,14 +985,184 @@ func (p *Pool) warmTunnels(ctx context.Context) {
// Already warm, or already on its way.
case connectivity.Shutdown:
// Terminal — the entry is dead stock; retireAged/terminate owns it.
- default: // Idle, TransientFailure
+ case connectivity.TransientFailure:
+ failing++
+ default: // Idle
a.conn.Connect()
- rewarmed++
+ idle++
}
}
- if rewarmed > 0 {
- log.Printf("awsvm: pool re-warmed %d idle agent tunnel(s) of %d stocked", rewarmed, len(conns))
+ if idle > 0 || failing > 0 {
+ log.Printf("awsvm: pool tunnels of %d stocked: %d idle re-connected, %d in transient failure (awaiting retirement)",
+ len(conns), idle, failing)
+ }
+}
+
+// idleTouchConcurrency bounds how many idle-timer touches run at once. Lower
+// than pingConcurrency because these are full HTTPS requests to distinct hosts
+// rather than RPCs on channels we already hold, and because they are never
+// urgent: the pacing below gives every box a wide window to be served in.
+const idleTouchConcurrency = 16
+
+// idleTouchInterval is how often each stocked box must receive a real proxy
+// request, derived from the idle window AWS was actually configured with.
+//
+// A third of the window, so a box survives two consecutive missed touches — a
+// maintenance tick that is late, or a touch that fails — before AWS can suspend
+// it. Clamped at both ends: never more often than once a minute (this is a
+// network request per box and the pool can be large), and never less often than
+// every 15 minutes (at the 8h ceiling a third would be 2h40m, which is long
+// enough that a lowered idle window elsewhere would go unnoticed for hours).
+func (p *Pool) idleTouchInterval() time.Duration {
+ window := time.Duration(p.client.Config().MaxIdleDurationSeconds) * time.Second
+ if window <= 0 {
+ window = 15 * time.Minute
+ }
+ iv := window / 3
+ if iv < time.Minute {
+ iv = time.Minute
+ }
+ if iv > 15*time.Minute {
+ iv = 15 * time.Minute
}
+ return iv
+}
+
+// touchIdleTimers sends one real inbound request through the proxy endpoint of
+// every stocked box that is due for one, so AWS never counts it idle.
+//
+// This is the half of the keepalive that AWS can see. warmTunnels keeps our own
+// agent channel healthy — which is what makes a claim's first exec fast — but it
+// does all of that INSIDE an established WebSocket, and AWS measures idleness by
+// inbound requests through the proxy endpoint. So the pool could hold a box
+// perfectly warm by every measure we had, while AWS independently decided nobody
+// had touched it in 15 minutes and suspended it. That is what produced stock
+// answering 502, and then stock being terminated outright 30 minutes later.
+//
+// Belt to the ceiling's braces: with maxIdleDurationSeconds now defaulted to the
+// 8h total-lifetime cap, no box should ever reach its idle window before
+// MaxBoxAge retires it anyway. This runs regardless, cheaply, because that
+// ceiling is a default someone can lower with an env var and the failure mode
+// when they do is silent, delayed, and destroys sandboxes.
+//
+// Failures are logged and nothing more. A failed touch is not evidence the box
+// is bad — a 502 here includes a box mid-resume — and warmTunnels already owns
+// the decision to retire or evict on evidence it can actually trust.
+func (p *Pool) touchIdleTimers(ctx context.Context) {
+ interval := p.idleTouchInterval()
+ now := time.Now()
+
+ p.mu.Lock()
+ due := make([]*StockEntry, 0, len(p.stock))
+ for _, e := range p.stock {
+ if e.lastProxyTouch.IsZero() || now.Sub(e.lastProxyTouch) >= interval {
+ due = append(due, e)
+ }
+ }
+ p.mu.Unlock()
+ if len(due) == 0 {
+ return
+ }
+
+ var (
+ mu sync.Mutex
+ ok int
+ failed int
+ sample error
+ sampleBox string
+ touched []*StockEntry
+ wg sync.WaitGroup
+ )
+ sem := make(chan struct{}, idleTouchConcurrency)
+ for _, e := range due {
+ wg.Add(1)
+ go func(e *StockEntry) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+
+ err := proxyTouch(ctx, e.Endpoint, p.client.Config().AgentPort,
+ func(ctx context.Context) (string, error) {
+ return p.client.AuthToken(ctx, e.MicrovmID)
+ })
+
+ mu.Lock()
+ defer mu.Unlock()
+ if err != nil {
+ failed++
+ if sample == nil {
+ sample, sampleBox = err, e.MicrovmID
+ }
+ return
+ }
+ ok++
+ touched = append(touched, e)
+ }(e)
+ }
+ wg.Wait()
+
+ // Stamped under the pool lock, and only on success: every other reader of
+ // lastProxyTouch holds p.mu, and a box whose touches keep failing must stay
+ // due on every tick rather than drift quietly toward suspension.
+ if len(touched) > 0 {
+ stamp := time.Now()
+ p.mu.Lock()
+ for _, e := range touched {
+ e.lastProxyTouch = stamp
+ }
+ p.mu.Unlock()
+ }
+
+ msg := fmt.Sprintf("awsvm: pool idle-timer touch: %d ok, %d failed, of %d due (every %s)",
+ ok, failed, len(due), interval)
+ if sample != nil {
+ msg += fmt.Sprintf("; first failure %s: %v", sampleBox, sample)
+ }
+ log.Print(msg)
+}
+
+// applyPingResults folds one tick's keepalive outcome back into the stock,
+// returning the channels the caller must close.
+//
+// Split out from warmTunnels so the retirement rule is testable without a live
+// gRPC channel: agentConn.ping talks to a real client, so the only way to
+// exercise "two consecutive failures retire the tunnel" in a unit test is to
+// drive the decision directly.
+//
+// errs is aligned with live by index — see pingEach.
+func (p *Pool) applyPingResults(live []*StockEntry, errs []error) (ok, failed, retired int, dead []*agentConn, sample error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ for i, err := range errs {
+ if i >= len(live) {
+ break
+ }
+ e := live[i]
+ if err == nil {
+ e.agentFailures = 0
+ ok++
+ continue
+ }
+ failed++
+ if sample == nil {
+ sample = err
+ }
+ e.agentFailures++
+ if e.agentFailures < maxAgentPingFailures {
+ continue
+ }
+ // Only ever close what the entry STILL holds. Between the ping and here
+ // the box may have been claimed, and TrackClaimed transfers the channel
+ // to the manager and clears this field — closing the pinged conn blindly
+ // would tear down a live customer's tunnel.
+ if e.agent != nil {
+ dead = append(dead, e.agent)
+ e.agent = nil
+ e.agentFailures = 0
+ retired++
+ }
+ }
+ return ok, failed, retired, dead, sample
}
func (p *Pool) terminate(e *StockEntry) {
@@ -877,6 +1184,23 @@ func (p *Pool) terminate(e *StockEntry) {
// the work costs a few ticks and keeps the pool's own traffic predictable.
const warmDialPerTick = 32
+// maxAgentPingFailures is how many CONSECUTIVE failed keepalive pings retire a
+// stocked box's channel for re-dial. Two, at a 30s tick, means one blip is
+// forgiven and a genuinely dead channel is replaced within ~a minute.
+//
+// Not one: a single ping can lose to a box that is mid-resume, and churning a
+// working tunnel costs a full re-dial for nothing. Not five: every tick spent
+// waiting is a tick where any create landing on that box hands its customer a
+// cold dial.
+const maxAgentPingFailures = 2
+
+// maxRedialFailures is how many CONSECUTIVE failed re-dials evict a stocked box
+// entirely. Three, at a 30s tick, means ~90s of a box being unreachable with a
+// freshly minted token before the pool stops counting it as stock. Deliberately
+// larger than maxAgentPingFailures: retiring a channel is cheap and reversible,
+// while eviction terminates the box, so it should need more evidence.
+const maxRedialFailures = 3
+
const terminateInterval = 125 * time.Millisecond
// terminateAttempts bounds retries of a throttled terminate. Giving up leaks
diff --git a/internal/awsvm/sizing_test.go b/internal/awsvm/sizing_test.go
new file mode 100644
index 00000000..0773b757
--- /dev/null
+++ b/internal/awsvm/sizing_test.go
@@ -0,0 +1,188 @@
+package awsvm
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// imageSpyAPI records which image each RunMicrovm asked for. Sizing is a
+// property of the image here, so "did we launch the right image" IS "did the
+// customer get the size they paid for" — there is nothing else to assert on.
+type imageSpyAPI struct {
+ API
+ mu sync.Mutex
+ images []string
+ n int
+}
+
+func (f *imageSpyAPI) RunMicrovm(_ context.Context, in *lambdamicrovms.RunMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {
+ f.mu.Lock()
+ f.n++
+ id := "mvm-" + string(rune('a'+f.n-1))
+ f.images = append(f.images, aws.ToString(in.ImageIdentifier))
+ f.mu.Unlock()
+ return &lambdamicrovms.RunMicrovmOutput{
+ MicrovmId: aws.String(id),
+ Endpoint: aws.String(id + ".microvm.aws.dev"),
+ }, nil
+}
+
+func (f *imageSpyAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ id := aws.ToString(in.MicrovmIdentifier)
+ return &lambdamicrovms.GetMicrovmOutput{
+ MicrovmId: aws.String(id),
+ Endpoint: aws.String(id + ".microvm.aws.dev"),
+ State: mvtypes.MicrovmStateRunning,
+ }, nil
+}
+
+func (f *imageSpyAPI) launched() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.images...)
+}
+
+func tieredManager(t *testing.T) (*Manager, *imageSpyAPI) {
+ t.Helper()
+ spy := &imageSpyAPI{}
+ c := NewClientWithAPI(spy, Config{
+ ImageIdentifier: "arn:default",
+ DefaultMemoryMB: 4096,
+ SizeImages: map[int]string{8192: "arn:8gb"},
+ })
+ return NewManager(c, t.TempDir()), spy
+}
+
+// Create and Get must report the SAME size, and it must be the delivered one.
+//
+// Create used to echo cfg.MemoryMB/cfg.CpuCount straight back while Track
+// recorded deliveredSize, so a create asking for 8 GB answered "8192" and an
+// immediate Get on the same sandbox answered "2048". Whichever number a caller
+// happened to read became what it believed.
+func TestCreateReportsDeliveredSizeAndAgreesWithGet(t *testing.T) {
+ m, _ := tieredManager(t)
+
+ sb, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-def"})
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ if sb.MemoryMB != 4096 {
+ t.Errorf("Create reported %dMB, want the delivered 4096", sb.MemoryMB)
+ }
+ got, err := m.Get(context.Background(), "sb-def")
+ if err != nil {
+ t.Fatalf("Get: %v", err)
+ }
+ if got.MemoryMB != sb.MemoryMB || got.CpuCount != sb.CpuCount {
+ t.Errorf("Get says %dMB/%dcpu but Create said %dMB/%dcpu — the two must never disagree",
+ got.MemoryMB, got.CpuCount, sb.MemoryMB, sb.CpuCount)
+ }
+}
+
+// A configured tier must launch ITS image, not the default one.
+func TestCreateLaunchesTheTierImage(t *testing.T) {
+ m, spy := tieredManager(t)
+
+ sb, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-8g", MemoryMB: 8192})
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ if launched := spy.launched(); len(launched) != 1 || launched[0] != "arn:8gb" {
+ t.Fatalf("launched %v, want [arn:8gb] — a tier served from the default image is a silent downsize", launched)
+ }
+ if sb.MemoryMB != 8192 {
+ t.Errorf("Create reported %dMB for the 8 GB tier, want 8192", sb.MemoryMB)
+ }
+ if sb.CpuCount != 2 {
+ t.Errorf("CpuCount=%d for the 8 GB tier, want 2 to match the published tier table", sb.CpuCount)
+ }
+}
+
+// A tier with no image must be REFUSED, never quietly served from the default.
+//
+// This is the whole reason ImageForMemory returns a bool instead of defaulting:
+// handing a 16 GB request a 4 GB box, and metering it at 4 GB, is a wrong-size
+// delivery the customer has no way to detect.
+func TestUnconfiguredTierIsRefusedNotDownsized(t *testing.T) {
+ m, spy := tieredManager(t)
+
+ _, err := m.Create(context.Background(), types.SandboxConfig{SandboxID: "sb-16g", MemoryMB: 16384})
+ if err == nil {
+ t.Fatal("Create succeeded for an unconfigured tier — that means a downsized box was handed out")
+ }
+ if !errors.Is(err, ErrUnsupported) {
+ t.Errorf("Create returned %v, want ErrUnsupported so the API answers 501", err)
+ }
+ if launched := spy.launched(); len(launched) != 0 {
+ t.Errorf("launched %v for a refused tier — nothing should have been started", launched)
+ }
+}
+
+// Only the default tier may be served from warm stock. This is what stops the
+// pool handing a big request a default-size box.
+func TestOnlyTheDefaultTierIsPoolable(t *testing.T) {
+ cfg := Config{ImageIdentifier: "arn:default", DefaultMemoryMB: 4096, SizeImages: map[int]string{8192: "arn:8gb"}}
+ cfg.applyDefaults()
+
+ if !cfg.IsDefaultTier(0) {
+ t.Error("unspecified size must be poolable — it is what the default create asks for")
+ }
+ if !cfg.IsDefaultTier(4096) {
+ t.Error("naming the default size explicitly must still be poolable")
+ }
+ if cfg.IsDefaultTier(8192) || cfg.IsDefaultTier(16384) {
+ t.Error("a non-default tier must miss the pool — warm stock is all one image")
+ }
+}
+
+// OwnedImages must cover every tier, or the orphan sweep treats tier boxes as
+// another product's and never reclaims them.
+func TestOwnedImagesCoversEveryTier(t *testing.T) {
+ cfg := Config{ImageIdentifier: "arn:default", SizeImages: map[int]string{8192: "arn:8gb", 1024: "arn:1gb"}}
+ owned := map[string]bool{}
+ for _, arn := range cfg.OwnedImages() {
+ owned[arn] = true
+ }
+ for _, want := range []string{"arn:default", "arn:8gb", "arn:1gb"} {
+ if !owned[want] {
+ t.Errorf("OwnedImages missing %s — orphans on that image would never be reclaimed", want)
+ }
+ }
+}
+
+// deliveredSize ignores the ask and reports what the resolved image provides.
+func TestDeliveredSizeIgnoresTheRequest(t *testing.T) {
+ for _, tc := range []struct {
+ requestedMB, requestedCPU, deliveredMB, wantMB, wantCPU int
+ }{
+ {8192, 4, 4096, 4096, 1}, // asked above the tier it resolved to
+ {512, 1, 4096, 4096, 1}, // asked below
+ {0, 0, 4096, 4096, 1}, // unspecified
+ {8192, 2, 8192, 8192, 2}, // the 8 GB tier, honoured
+ {16384, 4, 16384, 16384, 4}, // the 16 GB tier, honoured
+ } {
+ mem, cpu := deliveredSize("sb-x", tc.requestedMB, tc.requestedCPU, tc.deliveredMB)
+ if mem != tc.wantMB || cpu != tc.wantCPU {
+ t.Errorf("deliveredSize(req %d/%d, delivered %d) = %d/%d; want %d/%d",
+ tc.requestedMB, tc.requestedCPU, tc.deliveredMB, mem, cpu, tc.wantMB, tc.wantCPU)
+ }
+ }
+}
+
+// A Manager with no client must still bind, not panic: several callers build
+// one for bookkeeping only and never talk to AWS.
+func TestTrackToleratesAClientlessManager(t *testing.T) {
+ m := NewManager(nil, t.TempDir())
+ mem, cpu := m.Track("sb-nil", &Box{ID: "mvm-nil"}, types.SandboxConfig{})
+ if mem != deliveredMicrovmMemoryMB || cpu != deliveredMicrovmCPUCount {
+ t.Errorf("Track on a clientless Manager gave %d/%d, want the baseline %d/%d",
+ mem, cpu, deliveredMicrovmMemoryMB, deliveredMicrovmCPUCount)
+ }
+}
diff --git a/internal/awsvmlite/lite.go b/internal/awsvmlite/lite.go
new file mode 100644
index 00000000..e750c808
--- /dev/null
+++ b/internal/awsvmlite/lite.go
@@ -0,0 +1,770 @@
+// Package awsvmlite is a second, deliberately minimal MicroVM backend.
+//
+// It exists because of one measurement. Lambda's proxy strips HTTP/2 trailers,
+// and gRPC reports its status in trailers, so reaching osb-agent requires
+// tunnelling gRPC inside a WebSocket. That tunnel is the source of an entire
+// tier of machinery — a persistent channel per box, application-level
+// keepalives, a re-dial ladder, eviction on repeated failure, and a Durable
+// Object at the edge whose only job is to hold the socket open — and of the
+// failure mode that tier produces: measured on dev, a box answering /healthz in
+// 90ms with agentUp=true was simultaneously logged by the control plane as
+// tunnel-less, with re-dial timing out at its full 30s budget.
+//
+// A plain HTTP request has no trailers to lose. Verified directly against a live
+// box before this package was written: GET /healthz returned 200 five times out
+// of five through the proxy, and a POST with a JSON body reached osb-agent
+// intact (it answered 415, from inside the guest). So the tunnel is not required
+// to talk to a MicroVM; it is required only to speak gRPC to one.
+//
+// This backend therefore does the smallest possible thing:
+//
+// create pop a pre-launched box off a warm set, or launch one
+// exec one HTTPS POST to /osb/run on the hook port, connection reused
+// destroy TerminateMicrovm
+// warm a real GET /healthz on an interval, which is the only kind of
+// traffic AWS's idle accounting can see
+//
+// No WebSocket. No persistent channel. No keepalive ping. No re-dial. No
+// Durable Object. No pool sharding. Nothing to decay.
+//
+// WHAT IS GIVEN UP, deliberately and completely: streaming output, PTY
+// sessions, file transfer, and everything else osb-agent's API offers. One
+// command, buffered output, one reply. This is not a replacement for the agent
+// path — it is the floor that path should be measured against.
+package awsvmlite
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+const (
+ // runCmdPath must match cmd/microvm-hooks.
+ runCmdPath = "/osb/run"
+ // healthPath is the keep-warm probe. Cheap, side-effect free, and served by
+ // the guest rather than the proxy, so a 200 proves the whole path.
+ healthPath = "/healthz"
+
+ // idleConnTimeout is how long an unused connection to a box is kept. It is a
+ // constant rather than an inline field because Config.applyDefaults has to
+ // keep the touch interval underneath it — see the reasoning there.
+ idleConnTimeout = 90 * time.Second
+
+ // defaultTouchInterval is comfortably under idleConnTimeout, and far under
+ // the 8h AWS idle window the touch also serves. The binding constraint is
+ // the connection, not the suspension.
+ defaultTouchInterval = 60 * time.Second
+)
+
+// Config is everything this backend can be told. Short on purpose: a knob here
+// is a thing that can be set wrong, and the point of this package is that there
+// is almost nothing to get wrong.
+type Config struct {
+ // WarmTarget is how many pre-launched boxes to hold. 0 disables the warm
+ // set, and every create cold-launches (~3s, per AWS's own published
+ // benchmark) instead of ~0.
+ WarmTarget int
+
+ // LaunchInterval paces RunMicrovm against the account's rate quota.
+ LaunchInterval time.Duration
+
+ // ReadyTimeout bounds how long a launching box may stay PENDING.
+ ReadyTimeout time.Duration
+
+ // TouchInterval is how often each warm box receives a real proxy request.
+ //
+ // This is the entire keep-warm mechanism. AWS suspends a MicroVM after
+ // maxIdleDurationSeconds with no INBOUND REQUESTS THROUGH THE PROXY
+ // ENDPOINT — traffic inside an already-established connection does not
+ // count, which is why the agent path's in-tunnel pings never deferred a
+ // suspension. A GET here does, by definition.
+ TouchInterval time.Duration
+
+ // ExecTimeout bounds one exec at the HTTP layer, independent of the
+ // command's own timeout. Generous: if the box has already suspended, this
+ // request is what resumes it, and Lambda holds it for a snapshot restore.
+ ExecTimeout time.Duration
+}
+
+func (c *Config) applyDefaults() {
+ if c.LaunchInterval <= 0 {
+ c.LaunchInterval = 250 * time.Millisecond
+ }
+ if c.ReadyTimeout <= 0 {
+ c.ReadyTimeout = 90 * time.Second
+ }
+ if c.TouchInterval <= 0 {
+ c.TouchInterval = defaultTouchInterval
+ }
+ // The touch keeps TWO things alive, and only one of them is obvious.
+ //
+ // AWS's idle accounting is the stated purpose. But the touch is also a real
+ // HTTPS request, so it is what holds this box's keep-alive connection open —
+ // and a connection that lapses costs ~180ms of TCP+TLS on whichever exec
+ // happens to be first through it.
+ //
+ // Touching less often than idleConnTimeout therefore guarantees the lapse:
+ // the connection dies partway through every gap and the next exec pays for
+ // it. Measured on dev with touch=300s against idleConnTimeout=90s — the
+ // connection was dead for 210s of every 300s cycle, and CP-side exec
+ // round-trips came back bimodal at ~83ms or ~260ms with the guest reporting
+ // 11-13ms in both cases.
+ if c.TouchInterval >= idleConnTimeout {
+ c.TouchInterval = idleConnTimeout - 30*time.Second
+ }
+ if c.ExecTimeout <= 0 {
+ c.ExecTimeout = 60 * time.Second
+ }
+}
+
+// Box is a MicroVM this backend can reach. Everything needed to talk to it is
+// here, which is the whole point: an exec touches no AWS API and no other
+// process.
+type Box struct {
+ MicrovmID string
+ Endpoint string
+ Token string
+ Port int32
+
+ // Meta is set when the box is bound to a sandbox, and is empty for one
+ // still sitting in the warm set.
+ Meta Meta
+
+ launchedAt time.Time
+ boundAt time.Time
+ lastTouch time.Time
+}
+
+// Meta is the part of a sandbox's config this backend still has to remember
+// after the box is handed over: what to call the sandbox and what to bill it at.
+//
+// Nothing else from SandboxConfig survives the claim, and that is the honest
+// position — warm stock is manufactured from one image before anyone asks for
+// it, so a box cannot carry per-request sizing. Recording what was DELIVERED
+// (see Manager.Claim) rather than what was requested is what keeps metering
+// truthful about that.
+type Meta struct {
+ Template string
+ MemoryMB int
+ CPUCount int
+}
+
+// RunRequest mirrors cmd/microvm-hooks' runCmdRequest. Field-for-field with
+// types.ProcessConfig so a customer's exec is forwarded, not translated.
+type RunRequest struct {
+ Cmd string `json:"cmd"`
+ Args []string `json:"args,omitempty"`
+ Env map[string]string `json:"envs,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ TimeoutSec int `json:"timeoutSec,omitempty"`
+}
+
+// RunResult mirrors cmd/microvm-hooks' runCmdResponse.
+type RunResult struct {
+ Stdout string `json:"stdout"`
+ Stderr string `json:"stderr"`
+ ExitCode int `json:"exitCode"`
+ DurationMs int64 `json:"durationMs"`
+ TimedOut bool `json:"timedOut,omitempty"`
+}
+
+// Manager holds the warm set and the sandbox→box bindings.
+type Manager struct {
+ client *awsvm.Client
+ cfg Config
+ http *http.Client
+
+ mu sync.Mutex
+ warm []*Box
+ bound map[string]*Box // sandboxID → box
+ // inflight counts launches in progress, so the filler targets committed
+ // boxes rather than landed ones and does not overshoot WarmTarget by
+ // however many are mid-launch.
+ inflight int
+}
+
+func New(client *awsvm.Client, cfg Config) *Manager {
+ cfg.applyDefaults()
+ return &Manager{
+ client: client,
+ cfg: cfg,
+ bound: map[string]*Box{},
+ http: &http.Client{
+ Timeout: cfg.ExecTimeout,
+ // Connection reuse is the single most important line in this file.
+ // Measured from off-region, a cold GET through the proxy cost 270ms
+ // of which ~180ms was TCP connect + TLS. Amortising that handshake
+ // across a keep-alive pool is what turns an exec into a request
+ // rather than a connection.
+ Transport: &http.Transport{
+ MaxIdleConns: 512,
+ MaxIdleConnsPerHost: 4,
+ IdleConnTimeout: idleConnTimeout,
+ ForceAttemptHTTP2: true,
+ TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
+ },
+ },
+ }
+}
+
+// Depth reports how many boxes are ready to hand out.
+func (m *Manager) Depth() int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return len(m.warm)
+}
+
+// Run drives the warm set: top it up, and keep every box in it non-idle.
+func (m *Manager) Run(ctx context.Context) {
+ log.Printf("awsvmlite: starting (warm target=%d touch=%s)", m.cfg.WarmTarget, m.cfg.TouchInterval)
+ launch := time.NewTicker(m.cfg.LaunchInterval)
+ defer launch.Stop()
+ // Derived from the interval, not fixed. A box becomes due at TouchInterval
+ // and is only touched on the next tick, so a coarse tick adds its whole
+ // period to the real gap — with a 30s tick against a 60s interval that is up
+ // to 90s, which is exactly idleConnTimeout, putting the thing back inside the
+ // window applyDefaults just moved it out of.
+ touchTick := m.cfg.TouchInterval / 4
+ if touchTick < 5*time.Second {
+ touchTick = 5 * time.Second
+ }
+ touch := time.NewTicker(touchTick)
+ defer touch.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-launch.C:
+ m.mu.Lock()
+ committed := len(m.warm) + m.inflight
+ m.mu.Unlock()
+ if committed >= m.cfg.WarmTarget {
+ continue
+ }
+ go func() {
+ if err := m.launchOne(ctx); err != nil {
+ log.Printf("awsvmlite: launch failed: %v", err)
+ }
+ }()
+ case <-touch.C:
+ // In its own goroutine: a touch against an already-suspended box is
+ // held by Lambda for the length of a restore, and blocking the tick
+ // on that would stall the filler behind it.
+ go m.touchIdle(ctx)
+ }
+ }
+}
+
+// launchOne manufactures one warm box.
+//
+// Compare internal/awsvm's equivalent, which additionally pre-dials a gRPC
+// channel and forces it to READY. That part is absent here — there is no channel
+// to pre-dial.
+//
+// The warm shell it also runs IS kept, because dropping it was measured and it
+// was expensive: see the call below. An earlier version of this comment claimed
+// the agent path made the first exec pay for the login shell too. It does not —
+// it pre-pays it at manufacture, exactly as this now does.
+func (m *Manager) launchOne(ctx context.Context) error {
+ m.mu.Lock()
+ m.inflight++
+ m.mu.Unlock()
+ defer func() {
+ m.mu.Lock()
+ m.inflight--
+ m.mu.Unlock()
+ }()
+
+ runCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
+ defer cancel()
+
+ box, err := m.client.Run(runCtx, "")
+ if err != nil {
+ return err
+ }
+ // Do not hand out a box before Lambda says RUNNING: the proxy answers 502
+ // for a VM that is still restoring, and absorbing that wait is the whole
+ // reason a warm set exists.
+ ready, err := m.client.WaitRunning(runCtx, box.ID, m.cfg.ReadyTimeout)
+ if err != nil {
+ go m.terminate(box.ID)
+ return err
+ }
+ token, err := m.client.AuthToken(runCtx, ready.ID)
+ if err != nil {
+ go m.terminate(ready.ID)
+ return err
+ }
+
+ b := &Box{
+ MicrovmID: ready.ID,
+ Endpoint: ready.Endpoint,
+ Token: token,
+ Port: m.client.Config().AgentPort,
+ launchedAt: time.Now(),
+ }
+ // Pay the login shell here, once, instead of on the customer's first
+ // command. Measured on dev before this existed: first exec rt=2218ms of
+ // which cmd=2147ms was spent INSIDE the guest, against 81ms/13ms for every
+ // exec after it on the same box. That is `sh -lc` faulting in the shell and
+ // sourcing the whole profile chain on a box that has never run one — not
+ // network, and not something a faster data plane can fix.
+ //
+ // Best effort: a box that cannot run this is probably broken, but the claim
+ // path will find that out for itself, and refusing to stock it here would
+ // turn a slow first command into no box at all.
+ if err := m.warmShell(runCtx, b); err != nil {
+ log.Printf("awsvmlite: warm shell on %s failed (%v) — stocking anyway; its first exec will be slow", b.MicrovmID, err)
+ } else {
+ // It opened the connection and it was inbound proxy traffic, so the box
+ // starts its life already touched rather than immediately due.
+ b.lastTouch = time.Now()
+ }
+ m.mu.Lock()
+ m.warm = append(m.warm, b)
+ depth := len(m.warm)
+ m.mu.Unlock()
+ log.Printf("awsvmlite: warm +1 %s (depth=%d/%d)", b.MicrovmID, depth, m.cfg.WarmTarget)
+ return nil
+}
+
+// Claim binds a warm box to a sandbox id, or launches one if the set is empty.
+//
+// Returns the box and whether it came from the warm set — the caller wants that
+// in its timing, because the two differ by the entire cold-launch cost.
+func (m *Manager) Claim(ctx context.Context, sandboxID string, meta Meta) (*Box, bool, error) {
+ meta = m.delivered(meta)
+ m.mu.Lock()
+ if b := m.popLocked(sandboxID, meta); b != nil {
+ m.mu.Unlock()
+ return b, true, nil
+ }
+ m.mu.Unlock()
+
+ if err := m.launchOne(ctx); err != nil {
+ return nil, false, fmt.Errorf("awsvmlite: cold launch for %s: %w", sandboxID, err)
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if b := m.popLocked(sandboxID, meta); b != nil {
+ return b, false, nil
+ }
+ // The box we just launched was taken by a concurrent claim. Rare, and the
+ // caller retrying is better than launching again inside a lock.
+ return nil, false, fmt.Errorf("awsvmlite: no box available for %s", sandboxID)
+}
+
+// popLocked moves one box from the warm set to a sandbox. Caller holds m.mu.
+func (m *Manager) popLocked(sandboxID string, meta Meta) *Box {
+ n := len(m.warm)
+ if n == 0 {
+ return nil
+ }
+ b := m.warm[n-1]
+ m.warm = m.warm[:n-1]
+ b.Meta = meta
+ b.boundAt = time.Now()
+ m.bound[sandboxID] = b
+ return b
+}
+
+// delivered resolves what the customer will actually get, which is not always
+// what they asked for: every box in the warm set is built from one image, so a
+// request for another tier is served at the image's size or not at all.
+//
+// Recorded as delivered rather than requested because this is what metering
+// reads. Billing a 4 GB box as the 16 GB that was asked for is a silent
+// overcharge, and billing it as 0 is a silent free ride.
+func (m *Manager) delivered(meta Meta) Meta {
+ // Nil-safe on the client, matching awsvm.Manager.config(): this is pure
+ // bookkeeping and is reached from tests that never talk to AWS, so a missing
+ // client should degrade to defaults rather than panic on the claim path.
+ if m != nil && m.client != nil {
+ cfg := m.client.Config()
+ if _, mb, ok := cfg.ImageForMemory(meta.MemoryMB); ok && mb > 0 {
+ meta.MemoryMB = mb
+ } else if meta.MemoryMB <= 0 {
+ meta.MemoryMB = cfg.DefaultMemoryMB
+ }
+ }
+ if meta.CPUCount <= 0 {
+ meta.CPUCount = 1
+ }
+ return meta
+}
+
+// Adopt rebinds a sandbox to a box that already exists, rebuilding a binding
+// this process lost.
+//
+// A control plane restart drops the whole map while the boxes keep running, and
+// the persisted worker_id is the only surviving link between the two. Without
+// this the sandboxes are simultaneously unreachable (nothing routes to them) and
+// unreapable (nothing knows to terminate them), so they bill and hold regional
+// quota until the 8h cap.
+//
+// Reports false when AWS says the box is gone, which is the caller's cue to
+// close the row rather than keep a sandbox nobody can serve.
+func (m *Manager) Adopt(ctx context.Context, sandboxID, microvmID string, meta Meta) (bool, error) {
+ box, err := m.client.Get(ctx, microvmID)
+ if err != nil {
+ return false, err
+ }
+ if !box.Alive() {
+ return false, nil
+ }
+ token, err := m.client.AuthToken(ctx, box.ID)
+ if err != nil {
+ return false, err
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.bound[sandboxID] = &Box{
+ MicrovmID: box.ID,
+ Endpoint: box.Endpoint,
+ Token: token,
+ Port: m.client.Config().AgentPort,
+ Meta: m.delivered(meta),
+ launchedAt: box.StartedAt,
+ // The row's own start time is not carried here: this is a re-bind, and
+ // what callers ask boundAt is "since when could this process serve it".
+ boundAt: time.Now(),
+ }
+ return true, nil
+}
+
+// Bound snapshots every sandbox this process is serving, for callers that walk
+// the population — metering, and the reconciler.
+func (m *Manager) Bound() map[string]Box {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make(map[string]Box, len(m.bound))
+ for id, b := range m.bound {
+ out[id] = *b
+ }
+ return out
+}
+
+// BoundAt reports when a sandbox was bound, for status reporting.
+func (b Box) BoundAt() time.Time { return b.boundAt }
+
+// Bindings snapshots sandboxID → MicrovmID for callers that reconcile against
+// persisted rows.
+func (m *Manager) Bindings() map[string]string {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ out := make(map[string]string, len(m.bound))
+ for id, b := range m.bound {
+ out[id] = b.MicrovmID
+ }
+ return out
+}
+
+// Forget drops a binding without terminating anything. For a sandbox whose box
+// AWS has already taken.
+func (m *Manager) Forget(sandboxID string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.bound, sandboxID)
+}
+
+// Alive asks AWS whether a sandbox's box still exists.
+//
+// Deliberately not a read of the local map: this is what gates billing, and the
+// local map is exactly the thing that goes stale when a box dies underneath us.
+// A sandbox we cannot prove is alive must not be metered.
+func (m *Manager) Alive(ctx context.Context, sandboxID string) (bool, error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return false, nil
+ }
+ box, err := m.client.Get(ctx, b.MicrovmID)
+ if err != nil {
+ return false, err
+ }
+ return box.Alive(), nil
+}
+
+// BoxFor returns the box bound to a sandbox.
+func (m *Manager) BoxFor(sandboxID string) (*Box, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ b, ok := m.bound[sandboxID]
+ return b, ok
+}
+
+// Exec runs one command in a sandbox and returns its result.
+//
+// This is the whole data plane. One request, one response, over a connection the
+// transport above almost always already holds.
+func (m *Manager) Exec(ctx context.Context, sandboxID string, req RunRequest) (*RunResult, error) {
+ b, ok := m.BoxFor(sandboxID)
+ if !ok {
+ return nil, fmt.Errorf("awsvmlite: no box bound to %s", sandboxID)
+ }
+ body, err := json.Marshal(req)
+ if err != nil {
+ return nil, err
+ }
+ started := time.Now()
+ resp, err := m.do(ctx, b, http.MethodPost, runCmdPath, body)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ // The host-side round trip, logged per exec because it is the ONLY leg this
+ // backend controls. Everything else in a customer's measurement is geography
+ // — client to edge, edge to control plane, control plane to region — and
+ // without this number a slow exec cannot be told apart from a cell sitting on
+ // the wrong side of the country from its boxes.
+ roundTrip := time.Since(started)
+ if resp.StatusCode != http.StatusOK {
+ msg, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ return nil, fmt.Errorf("awsvmlite: exec on %s: http %d: %s",
+ sandboxID, resp.StatusCode, strings.TrimSpace(string(msg)))
+ }
+ var out RunResult
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&out); err != nil {
+ return nil, fmt.Errorf("awsvmlite: exec on %s: decode: %w", sandboxID, err)
+ }
+ // An exec IS inbound proxy traffic and it IS a use of the connection, so it
+ // satisfies everything the touch exists to satisfy. Without this, a busy
+ // sandbox would still be probed on schedule — pointless load against the box
+ // its customer is actively using.
+ m.stampTouch(b)
+ // rt is the whole request; cmd is what the guest spent running it. The
+ // difference is network plus proxy, and it is the number this backend exists
+ // to make small.
+ log.Printf("awsvmlite: exec %s rt=%dms cmd=%dms exit=%d",
+ sandboxID, roundTrip.Milliseconds(), out.DurationMs, out.ExitCode)
+ return &out, nil
+}
+
+// stampTouch records that a box just served real traffic.
+func (m *Manager) stampTouch(b *Box) {
+ m.mu.Lock()
+ b.lastTouch = time.Now()
+ m.mu.Unlock()
+}
+
+// warmShellTimeout bounds the manufacture-time warm-up. Generous, because on a
+// cold box this is the slowest thing that will ever run on it.
+const warmShellTimeout = 30 * time.Second
+
+// warmShell runs one throwaway command so the customer's first exec doesn't pay
+// for the login shell. See the call site in launchOne for the measurement.
+//
+// `|| true` so a box without node still gets its profile sourced and still
+// reports success — the point is the shell, not the binary.
+func (m *Manager) warmShell(ctx context.Context, b *Box) error {
+ ctx, cancel := context.WithTimeout(ctx, warmShellTimeout)
+ defer cancel()
+ body, err := json.Marshal(RunRequest{
+ Cmd: "node --version >/dev/null 2>&1 || true",
+ TimeoutSec: int(warmShellTimeout / time.Second),
+ })
+ if err != nil {
+ return err
+ }
+ resp, err := m.do(ctx, b, http.MethodPost, runCmdPath, body)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("http %d", resp.StatusCode)
+ }
+ return nil
+}
+
+// DrainWarm terminates every box in the warm set and returns how many it
+// released. Bound sandboxes are untouched — they belong to customers.
+//
+// Called on shutdown. Without it a redeploy abandons the whole warm set, and
+// every abandoned box bills compute and holds regional memory quota — the real
+// ceiling on how deep the set can be — until the 8h service cap. That is a leak
+// per rollout, not per incident.
+func (m *Manager) DrainWarm(ctx context.Context) int {
+ m.mu.Lock()
+ warm := m.warm
+ m.warm = nil
+ m.mu.Unlock()
+
+ var wg sync.WaitGroup
+ sem := make(chan struct{}, 16)
+ for _, b := range warm {
+ wg.Add(1)
+ go func(b *Box) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ if err := m.client.Terminate(ctx, b.MicrovmID); err != nil {
+ log.Printf("awsvmlite: drain terminate %s: %v", b.MicrovmID, err)
+ }
+ }(b)
+ }
+ wg.Wait()
+ return len(warm)
+}
+
+// Destroy terminates a sandbox's box and forgets the binding.
+func (m *Manager) Destroy(ctx context.Context, sandboxID string) error {
+ m.mu.Lock()
+ b, ok := m.bound[sandboxID]
+ delete(m.bound, sandboxID)
+ m.mu.Unlock()
+ if !ok {
+ return nil
+ }
+ return m.client.Terminate(ctx, b.MicrovmID)
+}
+
+// do issues one authenticated request through a box's proxy endpoint.
+//
+// The token is read from the box rather than minted per call: tokens last up to
+// an hour and Client.AuthToken caches and refreshes them, so an exec never waits
+// on the AWS control plane.
+func (m *Manager) do(ctx context.Context, b *Box, method, path string, body []byte) (*http.Response, error) {
+ host := hostOnly(b.Endpoint)
+ var rdr io.Reader
+ if body != nil {
+ rdr = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, "https://"+host+path, rdr)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("X-aws-proxy-auth", b.Token)
+ req.Header.Set("X-aws-proxy-port", fmt.Sprintf("%d", b.Port))
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ return m.http.Do(req)
+}
+
+// touchIdle sends a real inbound request through the proxy of every box due
+// for one — warm stock and bound sandboxes alike — so neither AWS's idle timer
+// nor our keep-alive connection lapses. See Config.TouchInterval.
+//
+// Failures are logged and nothing more. A non-200 here is not proof the box is
+// bad — a 502 includes a box mid-resume — and this backend deliberately has no
+// eviction ladder to feed. A box that is genuinely gone fails its next claim,
+// which is the only place the distinction matters.
+func (m *Manager) touchIdle(ctx context.Context) {
+ now := time.Now()
+ m.mu.Lock()
+ due := make([]*Box, 0, len(m.warm)+len(m.bound))
+ // Warm stock AND bound sandboxes. Covering only the warm set was wrong in
+ // both directions this touch matters: a customer's sandbox that sits idle
+ // loses its keep-alive connection like any other box, so their next command
+ // pays the handshake — and nothing was refreshing AWS's idle timer for it
+ // either, which is the failure that ends in a suspended box and a full
+ // snapshot restore rather than a slow request.
+ for _, b := range m.warm {
+ if b.lastTouch.IsZero() || now.Sub(b.lastTouch) >= m.cfg.TouchInterval {
+ due = append(due, b)
+ }
+ }
+ for _, b := range m.bound {
+ if b.lastTouch.IsZero() || now.Sub(b.lastTouch) >= m.cfg.TouchInterval {
+ due = append(due, b)
+ }
+ }
+ m.mu.Unlock()
+ if len(due) == 0 {
+ return
+ }
+
+ var (
+ wg sync.WaitGroup
+ mu sync.Mutex
+ ok int
+ failed int
+ sample error
+ touched []*Box
+ )
+ sem := make(chan struct{}, 16)
+ for _, b := range due {
+ wg.Add(1)
+ go func(b *Box) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+
+ err := func() error {
+ resp, err := m.do(ctx, b, http.MethodGet, healthPath, nil)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ // Drain before closing or the connection cannot be reused,
+ // which would defeat the point of the shared transport.
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("http %d", resp.StatusCode)
+ }
+ return nil
+ }()
+
+ mu.Lock()
+ defer mu.Unlock()
+ if err != nil {
+ failed++
+ if sample == nil {
+ sample = fmt.Errorf("%s: %w", b.MicrovmID, err)
+ }
+ return
+ }
+ ok++
+ touched = append(touched, b)
+ }(b)
+ }
+ wg.Wait()
+
+ // Stamped under the manager lock, and only on success: every other reader of
+ // lastTouch holds m.mu, and a box whose touches keep failing must stay due
+ // on every tick rather than drift quietly toward suspension.
+ if len(touched) > 0 {
+ stamp := time.Now()
+ m.mu.Lock()
+ for _, b := range touched {
+ b.lastTouch = stamp
+ }
+ m.mu.Unlock()
+ }
+
+ msg := fmt.Sprintf("awsvmlite: touched %d/%d box(es), %d failed", ok, len(due), failed)
+ if sample != nil {
+ msg += fmt.Sprintf("; first failure %v", sample)
+ }
+ log.Print(msg)
+}
+
+func (m *Manager) terminate(id string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := m.client.Terminate(ctx, id); err != nil {
+ log.Printf("awsvmlite: terminate %s: %v", id, err)
+ }
+}
+
+// hostOnly strips scheme and any trailing path from an endpoint.
+func hostOnly(endpoint string) string {
+ h := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")
+ if i := strings.IndexByte(h, '/'); i >= 0 {
+ return h[:i]
+ }
+ return h
+}
diff --git a/internal/awsvmlite/lite_test.go b/internal/awsvmlite/lite_test.go
new file mode 100644
index 00000000..9179665a
--- /dev/null
+++ b/internal/awsvmlite/lite_test.go
@@ -0,0 +1,90 @@
+package awsvmlite
+
+import (
+ "testing"
+ "time"
+)
+
+// The touch interval and the connection idle timeout are one mechanism, not two
+// settings. The touch is a real HTTPS request, so it is what keeps the box's
+// keep-alive connection open; if boxes are touched LESS often than connections
+// are reaped, every connection lapses partway through every gap and some exec
+// pays ~180ms of TCP+TLS to reopen it.
+//
+// That is not hypothetical. Dev ran touch=300s against idleConnTimeout=90s, and
+// control-plane exec round-trips came back bimodal at ~83ms or ~260ms with the
+// guest reporting 11-13ms of actual command in both cases.
+func TestTouchIntervalStaysUnderTheConnectionIdleTimeout(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ in time.Duration
+ }{
+ {"unset", 0},
+ {"the old default that caused the lapse", 5 * time.Minute},
+ {"exactly the idle timeout", idleConnTimeout},
+ {"absurdly long", time.Hour},
+ {"already short enough", 30 * time.Second},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c := Config{TouchInterval: tc.in}
+ c.applyDefaults()
+ if c.TouchInterval >= idleConnTimeout {
+ t.Fatalf("TouchInterval %s >= idleConnTimeout %s — connections will lapse between touches",
+ c.TouchInterval, idleConnTimeout)
+ }
+ if c.TouchInterval <= 0 {
+ t.Fatalf("TouchInterval %s — nothing would ever be touched", c.TouchInterval)
+ }
+ })
+ }
+}
+
+// A short interval must be honoured rather than overwritten, or the clamp above
+// would quietly become "always 60s" and no caller could tighten it.
+func TestAShortTouchIntervalIsLeftAlone(t *testing.T) {
+ c := Config{TouchInterval: 20 * time.Second}
+ c.applyDefaults()
+ if c.TouchInterval != 20*time.Second {
+ t.Fatalf("TouchInterval = %s, want the configured 20s", c.TouchInterval)
+ }
+}
+
+// The tick that scans for due boxes has to be finer than the interval itself.
+// A box becomes due at TouchInterval and is only touched on the following tick,
+// so the real worst-case gap is interval + tick — and if that reaches
+// idleConnTimeout the clamp above has bought nothing. This pins the arithmetic
+// the Run loop does.
+func TestTouchTickKeepsTheWorstCaseGapUnderTheIdleTimeout(t *testing.T) {
+ for _, in := range []time.Duration{0, 5 * time.Minute, 30 * time.Second, time.Hour} {
+ c := Config{TouchInterval: in}
+ c.applyDefaults()
+
+ tick := c.TouchInterval / 4
+ if tick < 5*time.Second {
+ tick = 5 * time.Second
+ }
+ if worst := c.TouchInterval + tick; worst >= idleConnTimeout {
+ t.Fatalf("in=%s: worst-case gap %s (interval %s + tick %s) >= idleConnTimeout %s",
+ in, worst, c.TouchInterval, tick, idleConnTimeout)
+ }
+ }
+}
+
+// Delivered sizing, not requested. Warm stock is built from one image before
+// anyone asks for it, so a claim cannot change what the customer physically
+// gets — and recording the request instead of the delivery is what turns a
+// wrong-size box into a wrong bill.
+func TestDeliveredSizeFallsBackToTheImageRatherThanZero(t *testing.T) {
+ m := &Manager{} // no client — must degrade to defaults, not panic on a claim
+ got := m.delivered(Meta{})
+ if got.CPUCount <= 0 {
+ t.Fatalf("CPUCount = %d, want a positive default — a sandbox metered at 0 CPUs is billed as free",
+ got.CPUCount)
+ }
+
+ // An explicitly requested size must survive when there is nothing to resolve
+ // it against, rather than being zeroed.
+ if got := m.delivered(Meta{MemoryMB: 8192, CPUCount: 4}); got.MemoryMB != 8192 || got.CPUCount != 4 {
+ t.Fatalf("delivered = %dMB/%dcpu, want the requested 8192MB/4cpu", got.MemoryMB, got.CPUCount)
+ }
+}
diff --git a/internal/awsvmlite/sandbox_manager.go b/internal/awsvmlite/sandbox_manager.go
new file mode 100644
index 00000000..614426ab
--- /dev/null
+++ b/internal/awsvmlite/sandbox_manager.go
@@ -0,0 +1,255 @@
+package awsvmlite
+
+import (
+ "context"
+ "fmt"
+ "io"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// SandboxManager presents this backend through sandbox.Manager, the interface
+// the control plane's data-plane routes already dispatch on.
+//
+// Written as an adapter rather than a set of special cases in the API layer for
+// one reason: every route that touches a sandbox — exec, files, stats, kill,
+// hibernate — resolves its manager through the backend registry, and a backend
+// that answered only some of them would have to be checked for by hand at each
+// site. That is precisely the shape internal/api/backend.go was introduced to
+// remove, and every one of the bugs it removed failed silently.
+//
+// So this type implements ALL of it, and says no to most of it. The
+// unimplemented half returns awsvm.ErrUnsupported, which the API layer already
+// maps to 501 Not Implemented — "this runtime will never do that", as distinct
+// from a 500 that invites a retry. That is the truthful answer here: without a
+// gRPC tunnel there is no file transfer, no PTY, no streaming, and no
+// checkpoint. See the package doc for why that trade was made deliberately.
+type SandboxManager struct {
+ m *Manager
+}
+
+// NewSandboxManager wraps a Manager for the control plane's dispatch seam.
+func NewSandboxManager(m *Manager) *SandboxManager { return &SandboxManager{m: m} }
+
+// Compile-time proof the adapter is complete. Without it a change to
+// sandbox.Manager would surface as a registration failure at startup rather
+// than here.
+var _ sandbox.Manager = (*SandboxManager)(nil)
+
+// unsupported is the answer for everything the direct exec path cannot carry.
+// Wrapping ErrUnsupported is what turns it into a 501 upstream.
+func unsupported(op string) error {
+ return fmt.Errorf("awsvmlite: %s: %w", op, awsvm.ErrUnsupported)
+}
+
+// ── Lifecycle ───────────────────────────────────────────────────────────────
+
+// Create is not reachable: placement goes through the backend's Claim, which
+// pops a warm box. A create arriving here would launch a SECOND box for a
+// sandbox that already has one, so it refuses rather than leaking.
+func (s *SandboxManager) Create(context.Context, types.SandboxConfig) (*types.Sandbox, error) {
+ return nil, unsupported("create (placement is the backend's Claim)")
+}
+
+func (s *SandboxManager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
+ b, ok := s.m.BoxFor(id)
+ if !ok {
+ return nil, fmt.Errorf("awsvmlite: sandbox %s not found", id)
+ }
+ // Status comes from AWS, not the local binding: the binding is exactly what
+ // goes stale when a box dies underneath us, and Get is where a caller asks
+ // whether the sandbox is really there.
+ box, err := s.m.client.Get(ctx, b.MicrovmID)
+ if err != nil {
+ return nil, err
+ }
+ status := types.SandboxStatusRunning
+ if !box.Alive() {
+ status = types.SandboxStatusStopped
+ }
+ return &types.Sandbox{
+ ID: id,
+ Template: b.Meta.Template,
+ Status: status,
+ StartedAt: b.boundAt,
+ CpuCount: b.Meta.CPUCount,
+ MemoryMB: b.Meta.MemoryMB,
+ }, nil
+}
+
+func (s *SandboxManager) Kill(ctx context.Context, id string) error {
+ return s.m.Destroy(ctx, id)
+}
+
+func (s *SandboxManager) List(context.Context) ([]types.Sandbox, error) {
+ bound := s.m.Bound()
+ out := make([]types.Sandbox, 0, len(bound))
+ for id, b := range bound {
+ out = append(out, types.Sandbox{
+ ID: id,
+ Template: b.Meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: b.boundAt,
+ CpuCount: b.Meta.CPUCount,
+ MemoryMB: b.Meta.MemoryMB,
+ })
+ }
+ return out, nil
+}
+
+func (s *SandboxManager) Count(context.Context) (int, error) {
+ return len(s.m.Bound()), nil
+}
+
+// IsSandboxAlive gates billing, so it asks AWS rather than trusting the local
+// map — a stale binding metering a terminated box is the failure this exists to
+// prevent. An error is reported as not-alive: skipping a tick costs a fraction
+// of a cent, and billing a sandbox that does not exist costs trust.
+func (s *SandboxManager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
+ alive, err := s.m.Alive(ctx, id)
+ if err != nil {
+ return false, nil
+ }
+ return alive, nil
+}
+
+func (s *SandboxManager) Close() {}
+
+// ── Execution ───────────────────────────────────────────────────────────────
+
+// Exec is the whole point of this backend: one HTTPS POST, no tunnel.
+func (s *SandboxManager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
+ timeout := cfg.Timeout
+ if timeout <= 0 {
+ timeout = 60
+ }
+ res, err := s.m.Exec(ctx, sandboxID, RunRequest{
+ Cmd: cfg.Command,
+ Args: cfg.Args,
+ Env: cfg.Env,
+ Cwd: cfg.Cwd,
+ TimeoutSec: timeout,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &types.ProcessResult{
+ ExitCode: res.ExitCode,
+ Stdout: res.Stdout,
+ Stderr: res.Stderr,
+ }, nil
+}
+
+// ── Filesystem ──────────────────────────────────────────────────────────────
+//
+// All refused. The agent's file RPCs are gRPC, and gRPC is the one thing this
+// path deliberately cannot speak. A customer gets 501 rather than a hang or a
+// half-written file.
+
+func (s *SandboxManager) ReadFile(context.Context, string, string) (string, error) {
+ return "", unsupported("read file")
+}
+
+func (s *SandboxManager) WriteFile(context.Context, string, string, string) error {
+ return unsupported("write file")
+}
+
+func (s *SandboxManager) ReadFileStream(context.Context, string, string) (io.ReadCloser, int64, error) {
+ return nil, 0, unsupported("read file stream")
+}
+
+func (s *SandboxManager) WriteFileStream(context.Context, string, string, uint32, io.Reader) (int64, error) {
+ return 0, unsupported("write file stream")
+}
+
+func (s *SandboxManager) ListDir(context.Context, string, string) ([]types.EntryInfo, error) {
+ return nil, unsupported("list dir")
+}
+
+func (s *SandboxManager) MakeDir(context.Context, string, string) error {
+ return unsupported("make dir")
+}
+
+func (s *SandboxManager) Remove(context.Context, string, string) error {
+ return unsupported("remove")
+}
+
+func (s *SandboxManager) Exists(context.Context, string, string) (bool, error) {
+ return false, unsupported("exists")
+}
+
+func (s *SandboxManager) Stat(context.Context, string, string) (*types.FileInfo, error) {
+ return nil, unsupported("stat")
+}
+
+// ── Everything else ─────────────────────────────────────────────────────────
+
+// SetResourceLimits: sizing belongs to the image, so there is no per-sandbox
+// knob to turn. Same answer the agent-path backend gives.
+func (s *SandboxManager) SetResourceLimits(context.Context, string, int32, int64, int64, int64) error {
+ return unsupported("set resource limits")
+}
+
+// UpdateSandboxSecret reports (false, nil) — "no session matched" — rather than
+// an error, which is the contract the secret-store update flow expects for a
+// transient miss. There is no secrets proxy on this path to update.
+func (s *SandboxManager) UpdateSandboxSecret(context.Context, string, string, string) (bool, error) {
+ return false, nil
+}
+
+func (s *SandboxManager) Stats(context.Context, string) (*sandbox.SandboxStats, error) {
+ return nil, unsupported("stats")
+}
+
+func (s *SandboxManager) HostPort(context.Context, string) (int, error) {
+ return 0, unsupported("host port")
+}
+
+func (s *SandboxManager) ContainerAddr(context.Context, string, int) (string, error) {
+ return "", unsupported("container addr")
+}
+
+// DataDir has no meaning here — the host is managed and its disk is not ours to
+// name — but it must not panic, because callers log it.
+func (s *SandboxManager) DataDir() string { return "" }
+
+func (s *SandboxManager) ContainerName(id string) string { return id }
+
+// Hibernate/Wake: parking needs the workspace archived out of the guest, and
+// that is a file transfer over the agent. Refused rather than half-done — a
+// hibernate that reported success without an archive would destroy the box and
+// the customer's data with it.
+func (s *SandboxManager) Hibernate(context.Context, string, *storage.CheckpointStore) (*sandbox.HibernateResult, error) {
+ return nil, unsupported("hibernate")
+}
+
+func (s *SandboxManager) Wake(context.Context, string, string, *storage.CheckpointStore, int) (*types.Sandbox, error) {
+ return nil, unsupported("wake")
+}
+
+func (s *SandboxManager) RebootSandbox(context.Context, string) error {
+ return unsupported("reboot")
+}
+
+func (s *SandboxManager) PowerCycleSandbox(context.Context, string) (int, error) {
+ return 0, unsupported("power cycle")
+}
+
+func (s *SandboxManager) TemplateCachePath(string, string) string { return "" }
+
+func (s *SandboxManager) CreateCheckpoint(context.Context, string, string, *storage.CheckpointStore, func()) (string, string, int64, error) {
+ return "", "", 0, unsupported("create checkpoint")
+}
+
+func (s *SandboxManager) RestoreFromCheckpoint(context.Context, string, string) error {
+ return unsupported("restore from checkpoint")
+}
+
+func (s *SandboxManager) ForkFromCheckpoint(context.Context, string, types.SandboxConfig) (*types.Sandbox, error) {
+ return nil, unsupported("fork from checkpoint")
+}
+
+func (s *SandboxManager) CheckpointCachePath(string, string) string { return "" }
diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.go
index f513c263..5fdd9faf 100644
--- a/internal/edgeclient/client.go
+++ b/internal/edgeclient/client.go
@@ -46,13 +46,27 @@ type Client struct {
HTTP *http.Client
}
+// edgeIdleConns is the per-host idle-connection pool for control-plane→edge
+// calls.
+//
+// http.DefaultTransport keeps MaxIdleConnsPerHost=2. Every one of these calls
+// goes to a single host, so under any concurrency above two the surplus
+// connections are closed the moment they go idle and the next burst pays a
+// fresh TLS handshake for each — on a 2-vCPU control plane, against a TLS
+// endpoint, inside a create. Sized to cover a burst of concurrent creates with
+// headroom; idle sockets to one host are cheap, re-handshaking them is not.
+const edgeIdleConns = 128
+
// New returns a Client with a sane default http.Client. Pass an explicit
// http.Client (with a transport / timeout) for production use.
func New(baseURL, secret string) *Client {
+ tr := http.DefaultTransport.(*http.Transport).Clone()
+ tr.MaxIdleConns = edgeIdleConns
+ tr.MaxIdleConnsPerHost = edgeIdleConns
return &Client{
BaseURL: strings.TrimRight(baseURL, "/"),
Secret: secret,
- HTTP: &http.Client{Timeout: 10 * time.Second},
+ HTTP: &http.Client{Timeout: 10 * time.Second, Transport: tr},
}
}
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 036743b3..19276e40 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.6",
+ "version": "0.15.7",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/sandbox.test.ts b/sdks/typescript/src/sandbox.test.ts
index 09672f9e..5a604c43 100644
--- a/sdks/typescript/src/sandbox.test.ts
+++ b/sdks/typescript/src/sandbox.test.ts
@@ -71,3 +71,59 @@ describe("Sandbox checkpoint requests", () => {
});
});
});
+
+describe("Sandbox.destroy", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ // The bug this exists to prevent: connect()+kill() reads a 404 from the GET
+ // as "already gone" and never issues the DELETE, leaking a live sandbox while
+ // reporting success. destroy() must go straight to the DELETE.
+ it("issues DELETE without a preceding GET", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(null, { status: 204 }),
+ );
+
+ await Sandbox.destroy("sb_1", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(String(url)).toBe("https://api.example.test/api/sandboxes/sb_1");
+ expect(init?.method).toBe("DELETE");
+ });
+
+ // A 404 from the DELETE means the sandbox really is gone, which is the
+ // caller's desired end state.
+ it("treats a 404 from the DELETE as success", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 404 }));
+
+ await expect(
+ Sandbox.destroy("sb_missing", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" }),
+ ).resolves.toBeUndefined();
+ });
+
+ // Anything else must throw: a delete that did not happen must never look
+ // like one that did.
+ it("throws when the delete genuinely failed", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 500 }));
+
+ await expect(
+ Sandbox.destroy("sb_1", { apiUrl: "https://api.example.test/api", apiKey: "osb_test" }),
+ ).rejects.toThrow(/Failed to destroy sandbox sb_1: 500/);
+ });
+
+ it("forwards deleteSecretStore", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null, { status: 204 }));
+
+ await Sandbox.destroy("sb_1", {
+ apiUrl: "https://api.example.test/api",
+ apiKey: "osb_test",
+ deleteSecretStore: true,
+ });
+
+ expect(String(fetchMock.mock.calls[0][0])).toBe(
+ "https://api.example.test/api/sandboxes/sb_1?deleteSecretStore=true",
+ );
+ });
+});
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 03e88008..78f08c60 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -416,6 +416,43 @@ export class Sandbox {
return new Sandbox(data, apiUrl, apiKey);
}
+ /**
+ * Delete a sandbox by id, without connecting to it first.
+ *
+ * `connect()` + `kill()` is the obvious way to do this and it is subtly
+ * wrong, because `connect()` is a GET whose result `kill()` never uses —
+ * killing needs only the id, the URL and the key. So the GET is a
+ * precondition that can fail on its own: during the create→finalize window,
+ * against a stale route cache, or on any transient miss it answers 404, and
+ * a caller that reads "404" as "already gone" skips the DELETE entirely and
+ * leaks a running sandbox that nothing will ever collect. That failure is
+ * silent by construction — the caller sees success.
+ *
+ * This issues the DELETE directly, so there is no GET to misread.
+ *
+ * Idempotent: a 404 from the DELETE itself means the sandbox is genuinely
+ * gone, which is the caller's desired end state, so it resolves rather than
+ * throwing. Every other non-2xx throws — a delete that did not happen must
+ * never look like one that did.
+ */
+ static async destroy(
+ sandboxId: string,
+ opts: Pick<SandboxOpts, "apiKey" | "apiUrl"> & SandboxKillOptions = {},
+ ): Promise<void> {
+ const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
+ const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
+ const query = opts.deleteSecretStore ? "?deleteSecretStore=true" : "";
+
+ const resp = await fetch(`${apiUrl}/sandboxes/${sandboxId}${query}`, {
+ method: "DELETE",
+ headers: apiKey ? { "X-API-Key": apiKey } : {},
+ });
+
+ if (!resp.ok && resp.status !== 404) {
+ throw new Error(`Failed to destroy sandbox ${sandboxId}: ${resp.status}`);
+ }
+ }
+
/**
* Issue a new preview-URL bearer token and invalidate the previous one.
*
diff --git a/wrangler.jsonc b/wrangler.jsonc
new file mode 100644
index 00000000..4d7aa82d
--- /dev/null
+++ b/wrangler.jsonc
@@ -0,0 +1,14 @@
+{
+ "$schema": "node_modules/wrangler/config-schema.json",
+ "name": "opencomputer3",
+ "compatibility_date": "2026-08-25",
+ "observability": {
+ "enabled": true
+ },
+ "assets": {
+ "directory": "."
+ },
+ "compatibility_flags": [
+ "nodejs_compat"
+ ]
+}