Skip to content

An open-source, faster Devin alternative

TypeScript

wip

Brian Reardon5d3ed71a4f89
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index d1a4eeaf..7590dcc3 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1197,144 +1197,63 @@ function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectSt
}
// ---------------------------------------------------------------------------
-// Magazine: isolate-local inventory of pre-claimed, pre-tokened pool boxes.
+// Pool claim: one DO pop per create.
//
-// Every create used to cost one PoolStock DO subrequest + one HMAC on the create
-// isolate. Prod attribution showed the burst-100 gate is isolate admission/CPU
-// (create wall ~420ms against ~10ms of server-side claim), so the win is to stop
-// doing per-create work at all: one /claim-batch call fetches N boxes WITH their
-// tokens already minted in the DO, and the next N-1 creates are pure memory —
-// zero subrequests, zero crypto. Classic magazine/thread-local free-list.
+// There used to be a third tier here — an isolate-local "magazine" that batched
+// a refill across shards and served subsequent creates from memory. It is gone.
+// The idea was sound (amortize the DO subrequest + HMAC over a burst) but it
+// could not be made correct: a magazine lives in isolate-local memory, so a
+// burst that fragments across isolates leaves each one holding stock no other
+// create can reach, and Cloudflare may evict the isolate at any time. Sizing it
+// was a forced choice between over-fetching (boxes strand until the cell's
+// 15-min reaper) and under-fetching (misses fall through to a 9-17s cold
+// launch). Measured on dev at 100-way: of 104 boxes staged in the shards, 48
+// served creates, 24 were still in the shards, and ~32 were simply gone.
//
-// Sizing is ADAPTIVE so this never wastes boxes on low traffic: the refill asks
-// for exactly as many creates as are currently waiting (clamped to
-// MAGAZINE_MAX). A lone create asks for 1 — byte-identical to the old behaviour.
-// A 100-way burst asks for MAGAZINE_MAX and serves the rest from memory.
-//
-// Safety: a magazine is keyed by cell AND org, and its boxes are already tokened
-// for that org, so a box can only ever be handed to the org it was minted for —
-// no cross-tenant exposure. pop() is atomic w.r.t. other tasks (single-threaded
-// JS), so two concurrent creates can never take the same box. The residual cost
-// is waste: boxes held by an isolate that gets evicted are stranded until the
-// cell's reaper reclaims them, which is why the TTL is short and the batch is
-// sized to demand rather than a fixed constant.
-interface MagazineBox {
+// It was also solving the wrong problem. The magazine bought back a ~10ms
+// server-side claim while every create and exec was paying ~165ms to cross the
+// continent to a control plane in westus2 for boxes in us-east-1. Removing a
+// tier of cache is worth more than tuning one: what remains has a single owner
+// (the DO) and one expiry (ENTRY_TTL), so a box cannot be in two places.
+interface PoolBox {
id: string;
workerID: string;
region: string;
sandboxDomain: string;
token: string;
- atMs: number;
}
-// Must cover a full burst in ONE refill. The refill is single-flighted per
-// (cell,org), so a cap below the burst width serializes: with MAX=24 and 100
-// concurrent creates, waiters go through ~5 sequential refill rounds and the
-// ones that exhaust their 3 attempts fall through to the CP create — the slow
-// path (measured ~1.6s at 100-way). Sized to the leaderboard burst width; the
-// batch is still demand-sized (`want = waiters`), so a lone create asks for 1.
-const MAGAZINE_MAX = 100;
-const MAGAZINE_TTL_MS = 60_000;
-const magazines = new Map<string, MagazineBox[]>();
-const magazineInflight = new Map<string, Promise<void>>();
-const magazineWaiters = new Map<string, number>();
-// Stock depth reported by the most recent refill (telemetry only).
-const magazineLastStock = new Map<string, number>();
-
-// refillMagazine pulls one batch into this isolate's magazine, walking shards the
-// same way a single claim does (random start + stride, 3 tries) so a drained or
-// unlucky shard falls through instead of failing the create.
-async function refillMagazine(
- env: Env,
- cell: CellRow,
- orgID: string,
- key: string,
- want: number,
-): Promise<void> {
- // Fan out to every shard in parallel, but RESOLVE ON THE FIRST one that
- // returns stock — do not await the slowest of eight.
- //
- // Measured on dev (N=20, 30-box pool), the two earlier shapes each got half
- // of this right. A single-shard claim (`?nomag=1`) is fast per call (min
- // 139-197ms) but misses often when that shard is empty (9-14 of 20 served).
- // Awaiting all eight shards covered the pool (17 of 20 served) but made the
- // FASTEST possible create 258-410ms, because every claim paid for the slowest
- // shard. First-responder gives the single-shard latency and the all-shard
- // coverage: the caller unblocks on whichever shard answers first, and the
- // stragglers still land — they top the magazine up in the background, so
- // their boxes serve the next create instead of being wasted.
- const per = Math.max(1, Math.ceil(want / POOL_STOCK_SHARDS));
- const start = Math.floor(Math.random() * POOL_STOCK_SHARDS);
-
- // Deposit boxes into the magazine as each shard answers, whenever it answers.
- const deposit = (data: { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number } | null): number => {
- if (!data) return 0;
- if (data.stock !== undefined) magazineLastStock.set(key, data.stock);
- const boxes = data.boxes ?? [];
- if (boxes.length === 0) return 0;
- const arr = magazines.get(key) ?? [];
- const at = Date.now();
- for (const b of boxes) arr.push({ ...b, atMs: at });
- magazines.set(key, arr);
- return boxes.length;
- };
- const shardCall = async (i: number): Promise<number> => {
- const shard = (start + i) % POOL_STOCK_SHARDS;
- try {
- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
- method: "POST",
- body: JSON.stringify({
- cell: { cellID: cell.cell_id, baseURL: cell.base_url },
- orgID,
- count: per,
- }),
- });
- if (!r.ok) return 0;
- return deposit((await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number });
- } catch {
- return 0;
- }
- };
-
- // Settle as soon as one shard has produced stock. The losers keep running and
- // deposit on their own — they are never awaited by this caller, so a slow or
- // empty shard can't hold up the create. shardCall never rejects, so no
- // unhandled rejection can escape the un-awaited tail.
- const calls = Array.from({ length: POOL_STOCK_SHARDS }, (_, i) => shardCall(i));
- await new Promise<void>((resolve) => {
- let pending = calls.length;
- let settled = false;
- const finish = (): void => {
- if (settled) return;
- settled = true;
- resolve();
- };
- for (const c of calls) {
- void c.then((n) => {
- if (n > 0) finish(); // first shard with boxes unblocks the caller
- if (--pending === 0) finish(); // all shards empty — fall through to CP
- });
- }
- });
-}
-
-// claimDirectBox is the CONTROL arm for the magazine A/B (`?nomag=1`): exactly
-// one claim-batch(count:1) per request, no isolate-local inventory, no
-// single-flight. This is the pre-magazine shape — 100 concurrent creates issue
-// 100 parallel DO claims — so the two arms differ only in the batching strategy.
-async function claimDirectBox(
+// claimPoolBox pops one ready-to-serve box (token already minted in the DO).
+// Returns null to fall through to the CP create.
+//
+// One /claim-batch(count:1) against a random shard. When the shards are evenly
+// 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.
+async function claimPoolBox(
env: Env,
cell: CellRow,
orgID: string,
-): Promise<{ box: MagazineBox; amortized: boolean; stock: number } | null> {
+): Promise<{ box: PoolBox; stock: 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);
- const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));
- for (let attempt = 0; attempt < 3; attempt++) {
+ // 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++) {
try {
const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
method: "POST",
@@ -1342,10 +1261,10 @@ async function claimDirectBox(
});
shard = (shard + stride) % POOL_STOCK_SHARDS;
if (!r.ok) continue;
- const data = (await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number };
+ const data = (await r.json()) as { boxes?: PoolBox[]; stock?: number };
const b = data.boxes?.[0];
if (!b) continue;
- return { box: { ...b, atMs: Date.now() }, amortized: false, stock: data.stock ?? -1 };
+ return { box: b, stock: data.stock ?? -1 };
} catch {
shard = (shard + stride) % POOL_STOCK_SHARDS;
}
@@ -1353,54 +1272,6 @@ async function claimDirectBox(
return null;
}
-// claimMagazineBox returns a ready-to-serve box (token already minted) or null to
-// fall through to the CP create. `amortized` reports that this create did NOT
-// perform a DO call of its own — it either popped a box already in memory or
-// rode someone else's in-flight batch. That ratio IS the fan-out reduction: in a
-// burst of N served by one batch, one create pays and N-1 are amortized.
-async function claimMagazineBox(
- env: Env,
- cell: CellRow,
- orgID: string,
-): Promise<{ box: MagazineBox; amortized: boolean; stock: number } | null> {
- const key = `${cell.cell_id}|${orgID}`;
- magazineWaiters.set(key, (magazineWaiters.get(key) ?? 0) + 1);
- let didRefill = false;
- try {
- for (let attempt = 0; attempt < 3; attempt++) {
- const mag = magazines.get(key);
- if (mag && mag.length > 0) {
- const box = mag.pop()!;
- // Held too long (idle isolate): drop the whole batch rather than serve a
- // box the cell may be about to reap. Rare — TTL is far under the DO's
- // 10-min entry TTL and the cell's 15-min destroy backstop.
- if (Date.now() - box.atMs < MAGAZINE_TTL_MS) {
- return { box, amortized: !didRefill, stock: magazineLastStock.get(key) ?? -1 };
- }
- magazines.set(key, []);
- }
- let inflight = magazineInflight.get(key);
- if (!inflight) {
- didRefill = true;
- // Size the batch to demand: how many creates are waiting on this org's
- // magazine right now (1 for a lone create → no over-fetch, no waste).
- const want = Math.min(MAGAZINE_MAX, Math.max(1, magazineWaiters.get(key) ?? 1));
- inflight = refillMagazine(env, cell, orgID, key, want);
- magazineInflight.set(key, inflight);
- void inflight.finally(() => {
- if (magazineInflight.get(key) === inflight) magazineInflight.delete(key);
- });
- }
- await inflight;
- }
- return null;
- } finally {
- const n = (magazineWaiters.get(key) ?? 1) - 1;
- if (n <= 0) magazineWaiters.delete(key);
- else magazineWaiters.set(key, n);
- }
-}
-
// edgeClaimEligible: a create qualifies for the edge fast path only when it
// asks for exactly what pool boxes are manufactured as — base template at the
// default shape (4GB/1cpu/default disk), no guest-side customization (envs,
@@ -1597,24 +1468,15 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// first-class shard instead of hoarding reservations until TTL. One empty
// shard (404) gets one retry on a different shard before the CP fallback.
mark("cap");
- // Magazine claim: a hit is pure isolate memory (no subrequest, no HMAC —
- // the DO minted the token when it filled the batch). A miss single-flights
- // one /claim-batch sized to the number of creates currently waiting, so a
- // burst pays ~N/MAGAZINE_MAX DO calls instead of N.
- // `?nomag=1` bypasses the isolate magazine and does the pre-magazine
- // thing: one direct DO claim for this request. Kept so magazine-vs-direct
- // can be A/B'd against a SINGLE deploy — otherwise the two arms differ by
- // a deploy as well as by the variable, which is not a controlled test.
- const claimed = req.url.includes("nomag=1")
- ? await claimDirectBox(env, cell, caller.orgID)
- : await claimMagazineBox(env, cell, caller.orgID);
+ // One DO pop. The token was minted in the DO when it filled its stock, so
+ // a hit costs one subrequest and no crypto on this isolate.
+ const claimed = await claimPoolBox(env, cell, caller.orgID);
const box = claimed?.box ?? null;
if (box && claimed) {
mark("claim");
- // Telemetry (#7): whether this create was served from the magazine (no
- // origin work at all) and the stock left in the shard at last refill.
- // `dur` is a value here, not a duration.
- phases.push(`mag;dur=${claimed.amortized ? 1 : 0}`, `stock;dur=${claimed.stock}`);
+ // Telemetry: stock left in the shard that served this claim. `dur` is a
+ // value here, not a duration.
+ phases.push(`stock;dur=${claimed.stock}`);
const token = box.token;
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });
@@ -1623,6 +1485,18 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// race-safe here: the client can't send that exec until the 201 crosses
// the network (≥ one RTT), and the put lands in ~5ms.
ctx.waitUntil(coloPut("route", box.id, { cellID: cell.cell_id, orgID: caller.orgID }, ROUTE_COLO_TTL_SEC));
+ // Warm the edge→cell connection for the exec that is about to follow.
+ //
+ // Measured on dev: a create's first exec spends 200ms in `origin` against
+ // 102ms steady — TLS + CF Tunnel setup on the first outbound request,
+ // paid once and then free. TTI measures exactly that first exec.
+ //
+ // EXPERIMENT, and its result is not obvious: the exec usually lands on a
+ // DIFFERENT isolate than the create, so this only helps if Workers pool
+ // outbound connections more broadly than per-isolate. If the first-exec
+ // `origin` does not fall toward 102ms after this ships, that hypothesis
+ // is dead and the warming has to live somewhere shared instead.
+ ctx.waitUntil(warmCellConnection(cell));
mark("mintseed");
const resp: Record<string, unknown> = {
sandboxID: box.id,
@@ -1678,9 +1552,15 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
}
}
+ // Reaching here means edge-claim was skipped or missed. Marked separately so a
+ // fallback create's header shows whether it paid for a failed claim attempt
+ // (DO round-trip + retry) before falling through, or never tried at all.
+ mark("claimmiss");
+
// CP fallback from here on — mint the cap-token the cell requires (the
// edge-claim path above returns without ever needing it).
const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);
+ mark("capmint");
// SSE build streaming: image/snapshot creates can take minutes (apt installs,
// etc.). Preserve live streaming, but index the final `result` event inline
@@ -1710,8 +1590,14 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
} catch (e) {
return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);
}
+ // The edge→cell leg, isolated. This is the fork in the road for the fallback
+ // create: `cell` covers network RTT to the cell plus everything the CP does,
+ // and the CP logs its own handler time, so `cell` minus that is the tunnel.
+ // Everything before it is edge compute + D1.
+ mark("cell");
const cpText = await cpResp.text();
+ mark("cellbody");
if (cpResp.status >= 200 && cpResp.status < 300) {
let parsed: SandboxCreateResult = {};
try {
@@ -1734,10 +1620,13 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
),
);
}
- // Pass the CP's response through verbatim (status + body).
+ if (env.DIAG === "1") console.log(`create-timing fallback ${cell.cell_id} ${phases.join(" ")}`);
+ // Pass the CP's response through verbatim (status + body), plus the phase
+ // breakdown — the edge-claim path above already returns one, and a fallback
+ // create with no header is exactly the case that needed attributing.
return new Response(cpText, {
status: cpResp.status,
- headers: { "content-type": "application/json" },
+ headers: { "content-type": "application/json", "server-timing": phases.join(", ") },
});
}
@@ -1908,10 +1797,40 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
// and stream the response back. Pre-fix this was a 307 redirect, which broke
// when the SDK's API key didn't exist in cell PG (api_keys are global in D1
// now, not mirrored per-cell).
-async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string): Promise<Response> {
+// warmCellConnection opens (and discards) a cheap request to a cell so the
+// TLS + tunnel handshake is already paid when the real one arrives. Best-effort
+// by construction: it runs in waitUntil, and a failure just means the next
+// request pays what it would have paid anyway.
+async function warmCellConnection(cell: CellRow): Promise<void> {
+ try {
+ await fetch(cell.base_url.replace(/\/$/, "") + "/health", {
+ method: "GET",
+ signal: AbortSignal.timeout(2000),
+ });
+ } catch {
+ /* best-effort */
+ }
+}
+
+async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, vmdoMs = 0): Promise<Response> {
+ // Step timing for the data-plane path. Measured on dev, an exec through here
+ // cost ~718-851ms end to end while the network legs account for only ~200ms
+ // (client↔CP 118ms + CP↔box 81ms), so ~500ms was unattributed. Nothing on
+ // this path emitted server-timing, which is why it stayed invisible.
+ const t0 = Date.now();
+ let tPrev = t0;
+ const phases: string[] = [];
+ if (authMs > 0) phases.push(`auth;dur=${authMs}`);
+ if (vmdoMs > 0) phases.push(`vmdo;dur=${vmdoMs}`);
+ const mark = (name: string): void => {
+ const now = Date.now();
+ phases.push(`${name};dur=${now - tPrev}`);
+ tPrev = now;
+ };
// Route cache first — the sandbox→cell mapping is immutable, and the D1 read
// it replaces is a blocking per-sub-op cost (2-3× per SDK runCommand).
const route = await resolveSandboxRoute(env, id);
+ mark("route");
if (!route) return json({ error: "sandbox not found" }, 404);
// Authorization: the sandbox must belong to the caller's org. Without this,
// any authenticated org could exec/files/pty/delete/hibernate/wake another
@@ -1919,6 +1838,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// we don't leak which sandbox ids exist.
if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
const cell = await lookupCell(env, route.cellID);
+ mark("cell");
if (!cell) return json({ error: `cell ${route.cellID} not registered` }, 503);
const url = new URL(req.url);
@@ -1929,6 +1849,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// Reuse the per-isolate org-policy cache instead of a separate per-request
// SELECT plan — under a burst these are all the same org.
const orgPol = await loadOrgPolicy(env, caller.orgID);
+ mark("pol");
// Mint a cap-token (iss=opensandbox-edge, signed with SESSION_JWT_SECRET).
// The cell's PGAPIKeyMiddleware accepts cap-tokens too (alongside identity
// tokens and API keys), so the same handler chain that runs for SDK
@@ -1938,6 +1859,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// whose backend is already fixed by its persisted worker_id. Runtime only
// decides placement, and placement has already happened.
const token = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, route.cellID, orgPol?.plan ?? "free", "", "", caller.userID);
+ mark("tok");
const headers = new Headers();
for (const [k, v] of req.headers.entries()) {
@@ -2012,6 +1934,11 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// Otherwise the dashboard accumulates phantoms — D1 rows stuck at
// "running" after the actual sandbox stopped.
const resp = await fetch(target, init);
+ mark("origin");
+ // Copy through so the step breakdown rides along with the cell's own answer.
+ // Response headers are immutable, hence the rewrap.
+ const timed = new Response(resp.body, resp);
+ timed.headers.set("server-timing", phases.join(", "));
if (postUpdate && resp.status >= 200 && resp.status < 300) {
const nowSec = Math.floor(Date.now() / 1000);
let stmt: D1PreparedStatement;
@@ -2042,7 +1969,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
}),
);
}
- return resp;
+ return timed;
}
// proxyToCellAuthed forwards an authenticated SDK/CLI request to a cell with an
@@ -4040,11 +3967,16 @@ export default {
// channel isn't live (DO 409) — so this is safe even before/while workers
// roll out the host dialer. Gated only on SESSION_JWT_SECRET (present
// wherever the DO auth can be verified at all).
+ let vmdoMs = 0;
if (env.SESSION_JWT_SECRET && req.method === "POST" && rest === "/exec/run-async") {
+ const tVmdo = Date.now();
const doResp = await tryVmDoExec(req, env, caller, id, authMs);
+ vmdoMs = Date.now() - tVmdo;
if (doResp) return doResp;
}
- return proxyToCellSDK(req, env, ctx, caller, id);
+ // 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 proxyToCellSDK(req, env, ctx, caller, id, authMs, vmdoMs);
}
// Generic /api/* fallback for SDK/CLI routes without a dedicated D1-native
diff --git a/cloudflare-workers/api-edge/src/pool_stock.test.ts b/cloudflare-workers/api-edge/src/pool_stock.test.ts
new file mode 100644
index 00000000..5619a382
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/pool_stock.test.ts
@@ -0,0 +1,224 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { PoolStock } from "./pool_stock";
+
+// ── fakes ───────────────────────────────────────────────────────────────────
+class FakeStorage {
+ map = new Map<string, unknown>();
+ alarm: number | null = null;
+ async get<T>(k: string): Promise<T | undefined> {
+ return this.map.get(k) as T | undefined;
+ }
+ async put(k: string, v: unknown): Promise<void> {
+ this.map.set(k, v);
+ }
+ async getAlarm(): Promise<number | null> {
+ return this.alarm;
+ }
+ async setAlarm(t: number): Promise<void> {
+ this.alarm = t;
+ }
+}
+
+class FakeState {
+ storage = new FakeStorage();
+ pending: Promise<unknown>[] = [];
+ async blockConcurrencyWhile<T>(cb: () => Promise<T>): Promise<T> {
+ return cb();
+ }
+ waitUntil(p: Promise<unknown>): void {
+ this.pending.push(p.catch(() => {}));
+ }
+ async settle(): Promise<void> {
+ // Drain repeatedly: waitUntil work can itself schedule more waitUntil work.
+ for (let i = 0; i < 5 && this.pending.length > 0; i++) {
+ const batch = this.pending;
+ this.pending = [];
+ await Promise.all(batch);
+ }
+ }
+}
+
+const CELL = { cellID: "cell-a", baseURL: "https://cell-a.example" };
+const ORG_A = "11111111-1111-4111-8111-111111111111";
+
+interface ReserveBox {
+ sandboxID: string;
+ workerID: string;
+}
+
+/** Records every origin call the DO makes, and controls what edge-reserve returns. */
+class FakeOrigin {
+ reserved: ReserveBox[][] = [];
+ releasedIDs: string[] = [];
+ supply: ReserveBox[] = [];
+ /** Control-plane process identity; changing it simulates a CP restart. */
+ epoch = "epoch-1";
+ handler = async (url: string, init?: RequestInit): Promise<Response> => {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ if (url.includes("/internal/pool/edge-reserve")) {
+ const give = this.supply.splice(0, Number(body.count) || 0);
+ this.reserved.push(give);
+ return Response.json({
+ region: "westus2",
+ sandboxDomain: "sb.example",
+ epoch: this.epoch,
+ boxes: give,
+ });
+ }
+ if (url.includes("/internal/pool/edge-release")) {
+ this.releasedIDs.push(...(body.sandboxIDs as string[]));
+ return Response.json({ ok: true });
+ }
+ throw new Error(`unexpected origin call: ${url}`);
+ };
+}
+
+function makeDO(origin: FakeOrigin, target = "4", lowWater = "1") {
+ const state = new FakeState();
+ const env = {
+ SESSION_JWT_SECRET: "test-secret",
+ POOL_STOCK_TARGET: target,
+ POOL_STOCK_LOW_WATER: lowWater,
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const doInstance = new PoolStock(state as any, env as any);
+ vi.stubGlobal("fetch", ((input: RequestInfo | URL, init?: RequestInit) =>
+ origin.handler(String(input), init)) as typeof fetch);
+ return { doInstance, state };
+}
+
+const post = (doInstance: PoolStock, path: string, body: unknown): Promise<Response> =>
+ doInstance.fetch(new Request(`https://pool-stock${path}`, { method: "POST", body: JSON.stringify(body) }));
+
+interface ClaimedBox {
+ id: string;
+ workerID: string;
+ region: string;
+ sandboxDomain: string;
+ token: string;
+}
+
+async function claimBatch(
+ doInstance: PoolStock,
+ state: FakeState,
+ orgID: string,
+ count: number,
+): Promise<{ boxes: ClaimedBox[]; stock: number }> {
+ const r = await post(doInstance, "/claim-batch", { cell: CELL, orgID, count });
+ const data = (await r.json()) as { boxes?: ClaimedBox[]; stock: number };
+ await state.settle();
+ return { boxes: data.boxes ?? [], stock: data.stock };
+}
+
+// ── tests ───────────────────────────────────────────────────────────────────
+describe("PoolStock", () => {
+ let origin: FakeOrigin;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-19T00:00:00Z"));
+ origin = new FakeOrigin();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("hands a box out exactly once", async () => {
+ origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
+ const { doInstance, state } = makeDO(origin);
+
+ await claimBatch(doInstance, state, ORG_A, 1); // primes the stock
+ const first = await claimBatch(doInstance, state, ORG_A, 1);
+ expect(first.boxes.map((b) => b.id)).toEqual(["sb-1"]);
+
+ // A popped box is TOKENED. It must never reappear in stock — the header's
+ // lifecycle invariant, and the reason the magazine's /return route is gone.
+ const again = await claimBatch(doInstance, state, ORG_A, 1);
+ expect(again.boxes).toEqual([]);
+ });
+
+ it("serves FIFO so the stock stays young", async () => {
+ origin.supply = [
+ { sandboxID: "sb-1", workerID: "w-1" },
+ { sandboxID: "sb-2", workerID: "w-2" },
+ ];
+ const { doInstance, state } = makeDO(origin);
+ await claimBatch(doInstance, state, ORG_A, 0); // prime
+
+ // Oldest first: sb-1 was reserved before sb-2, so it is closer to the
+ // cell's 15-min destroy backstop and has to go out first.
+ expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-1"]);
+ expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-2"]);
+ });
+
+ it("releases an unclaimed (never-tokened) box back to the pool", async () => {
+ // Stock that expires without ever being popped was never tokened, so it is
+ // cheap and safe to re-pool rather than leave to the cell's reaper.
+ origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
+ const { doInstance, state } = makeDO(origin);
+ await claimBatch(doInstance, state, ORG_A, 0);
+
+ vi.setSystemTime(Date.now() + 11 * 60_000);
+ await doInstance.alarm();
+ await state.settle();
+
+ expect(origin.releasedIDs).toEqual(["sb-1"]);
+ });
+
+ it("drops stock minted by a control plane that has since restarted", async () => {
+ // The MicroVM backend binds a sandbox id to a box IN MEMORY at reserve, so a
+ // CP restart invalidates every id this DO is holding. Without the fence the
+ // shard keeps serving them for the full ENTRY_TTL: each one 201s a create
+ // for a box with no manager binding, and the customer's first exec 500s.
+ origin.supply = [{ sandboxID: "sb-old", workerID: "w-1" }];
+ const { doInstance, state } = makeDO(origin);
+ await claimBatch(doInstance, state, ORG_A, 0); // stock sb-old under epoch-1
+
+ origin.epoch = "epoch-2"; // control plane restarted
+ origin.supply = [{ sandboxID: "sb-new", workerID: "w-2" }];
+ await doInstance.alarm(); // proactive top-up notices the new epoch
+ await state.settle();
+
+ const served = await claimBatch(doInstance, state, ORG_A, 5);
+ expect(served.boxes.map((b) => b.id)).toEqual(["sb-new"]);
+ });
+
+ it("keeps stock when the cell sends no epoch at all", async () => {
+ // A Postgres-backed cell reserves by flipping a row, so its reservations
+ // survive a restart and it sends no epoch. The fence must not fire there.
+ origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
+ const { doInstance, state } = makeDO(origin);
+ origin.handler = async (url: string, init?: RequestInit): Promise<Response> => {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ if (url.includes("/internal/pool/edge-reserve")) {
+ const give = origin.supply.splice(0, Number(body.count) || 0);
+ return Response.json({ region: "westus2", sandboxDomain: "sb.example", boxes: give });
+ }
+ origin.releasedIDs.push(...(body.sandboxIDs as string[]));
+ return Response.json({ ok: true });
+ };
+ await claimBatch(doInstance, state, ORG_A, 0);
+ await doInstance.alarm();
+ await state.settle();
+
+ expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-1"]);
+ });
+
+ it("exposes no route that can re-stock an already-tokened box", async () => {
+ // Regression guard. /return existed to un-strand the isolate-local
+ // magazine's surplus; with the magazine deleted there is no surplus, and a
+ // route that puts a tokened box back in stock is a cross-tenant hazard with
+ // no remaining caller. Deleting the magazine is what retires the hazard.
+ const { doInstance, state } = makeDO(origin);
+ await claimBatch(doInstance, state, ORG_A, 0);
+
+ const r = await post(doInstance, "/return", {
+ orgID: ORG_A,
+ boxes: [{ id: "sb-1", workerID: "w-1", region: "westus2", sandboxDomain: "sb.example" }],
+ });
+ expect(r.status).not.toBe(200);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 2e9cf5ca..afbbfb14 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -180,6 +180,10 @@ export class PoolStock {
// without waiting for the next claim (a fresh DO after eviction still knows
// which cell to reserve from).
private cell: { cellID: string; baseURL: string } | null = null;
+ // The control-plane process that issued the stock we are holding, when that
+ // cell's reservations are process-local (see edge_claim.go processEpoch).
+ // Persisted alongside the stock because it is only meaningful paired with it.
+ private epoch: string | null = null;
// Resolved once per isolate from env (see the sizing invariant above).
private readonly targetStock: number;
private readonly lowWater: number;
@@ -201,6 +205,7 @@ export class PoolStock {
this.state.blockConcurrencyWhile(async () => {
this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];
this.cell = (await this.state.storage.get<{ cellID: string; baseURL: string }>("cell")) ?? null;
+ this.epoch = (await this.state.storage.get<string>("epoch")) ?? null;
});
}
@@ -249,7 +254,8 @@ export class PoolStock {
this.state.waitUntil(this.release(stale));
}
- const entry = this.stock.shift(); // FIFO — oldest first keeps the stock young
+ // FIFO — oldest first keeps the stock young.
+ const entry = this.stock.shift();
this.lastClaimMs = Date.now();
void this.state.storage.put("lastClaim", this.lastClaimMs, { allowUnconfirmed: true });
this.persist();
@@ -304,7 +310,8 @@ export class PoolStock {
this.stock = fresh;
if (stale.length > 0) this.state.waitUntil(this.release(stale));
- const entries = this.stock.splice(0, Math.min(count, this.stock.length));
+ // FIFO — oldest first keeps the stock young.
+ const entries = this.stock.splice(0, count);
this.lastClaimMs = Date.now();
void this.state.storage.put("lastClaim", this.lastClaimMs, { allowUnconfirmed: true });
this.persist();
@@ -407,6 +414,7 @@ export class PoolStock {
// the `edge_reserved` CAS and fails cleanly. Rare + already-handled, and
// the claim hop is the entire cost of an edge create, so the ~10ms wins.
void this.state.storage.put("stock", this.stock, { allowUnconfirmed: true });
+ void this.state.storage.put("epoch", this.epoch, { allowUnconfirmed: true });
}
// restockToTarget fills the stock up to TARGET_STOCK by issuing up to
@@ -445,8 +453,30 @@ export class PoolStock {
const data = (await r.json()) as {
region: string;
sandboxDomain: string;
+ epoch?: string;
boxes: Array<{ sandboxID: string; workerID: string }>;
};
+ // Epoch fence. A cell that stamps an epoch is telling us its edge
+ // reservations live in that process's memory, not in Postgres — so when
+ // the value changes, every id we are holding was minted by a control
+ // plane that no longer exists. Those boxes have no manager binding: a
+ // create served from them 201s and the customer's first exec 500s,
+ // because routing goes through a sandbox→box map that died with the
+ // process. Drop the lot rather than serve one.
+ //
+ // Not released back to the pool — the new process has no record of these
+ // ids, so an edge-release would be a no-op round trip. The cell's own
+ // reaper owns the boxes now.
+ //
+ // Absent epoch = a Postgres-backed cell, whose reservations are rows and
+ // survive a restart. No fence, and no behaviour change for those cells.
+ if (data.epoch && this.epoch && data.epoch !== this.epoch && this.stock.length > 0) {
+ console.log(
+ `pool-stock ${cell.cellID}: control-plane epoch changed (${this.epoch} → ${data.epoch}) — dropping ${this.stock.length} stale entr(ies)`,
+ );
+ this.stock = [];
+ }
+ if (data.epoch) this.epoch = data.epoch;
const now = Date.now();
const have = new Set(this.stock.map((e) => e.id));
let added = 0;
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 64834fb4..5326e2c2 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -161,14 +161,50 @@ WORKER_ENV = "dev"
# promotion path can be exercised without pausing hundreds of boxes.
PAUSED_CAP = "10"
# PoolStock sizing, scaled to THIS cell's pool. The DO defaults (38 per shard ×
-# 8 shards = 304) are sized for prod's 320-box pool; dev's cell holds ~30, so the
-# defaults put every shard permanently below low-water, restocking on every claim
-# and competing for a supply that can never satisfy them — creates that hash to a
-# starved shard fall through to the ~10× slower CP path and dev burst numbers
-# stop measuring anything real. 8 × 3 = 24 keeps the fleet target under the 30
-# available with headroom. See the SIZING INVARIANT in src/pool_stock.ts.
-POOL_STOCK_TARGET = "3"
-POOL_STOCK_LOW_WATER = "2"
+# 8 shards = 304) are sized for prod's 320-box pool. Oversizing starves every
+# shard below low-water, restocking on every claim and competing for a supply
+# that can never satisfy them; undersizing caps how much of a burst the edge can
+# absorb, because anything past SHARDS × TARGET falls through to the ~10× slower
+# CP path. See the SIZING INVARIANT in src/pool_stock.ts.
+#
+# 8 × 18 = 144 against dev's 150-box MicroVM pool. Sized for the burst-100
+# benchmark with ~44 boxes of headroom, and that headroom is the whole point:
+# 8 × 14 = 112 against a 130-box pool looked like it covered a burst-100 and did
+# not. Measured, twice: shards probed SEQUENTIALLY reported 12-13 of 14 each
+# (~104 staged, apparently enough), yet 51 then 65 of 100 concurrent creates
+# missed the magazine and fell through to a cold MicroVM launch — which then
+# serialized behind the RunMicrovm 5/s quota into a 25s tail.
+#
+# The reason a 4-box margin is not a margin: `magazines` in index.ts is an
+# ISOLATE-LOCAL map. A 100-wide burst lands across several isolates, each with
+# its own magazine, its own waiter count, and its own refill fan-out, all
+# drawing on the same staged stock without coordinating. Whichever isolate
+# refills last finds the shards drained, and behind them the pool has almost no
+# free stock to backfill because the rest is already held as reservations. So
+# the stock has to cover the burst with enough slack to survive an uneven split
+# across SHARDS × isolates, not merely equal it.
+#
+# Why the pool can afford 150: a claimed box comes OUT of staged stock rather
+# than being added alongside it, so peak footprint during the burst is the pool
+# itself (~150), not pool + 100. Refill afterwards is what pushes toward
+# pool + burst, and OPENSANDBOX_MICROVM_MAX_TOTAL_BOXES caps that at 230 —
+# under the ~256-box ceiling the 1024GB regional quota actually allows (charged
+# at roughly 4GB per box, not the image's 2048MiB minimum; measured by stalling
+# the fleet at 262).
+#
+# Was 8 × 3 = 24, and the old value's reasoning does NOT carry over. On QEMU the
+# ~30 was a fleet property: boxes live on provisioned workers, so growing the
+# pool means growing the fleet. A MicroVM pool is just a dial — boxes launch in
+# ~1.5s and depth is OPENSANDBOX_MICROVM_POOL_TARGET — so what actually bounds
+# it is the AWS regional memory quota (~500 boxes at the 2048MB delivered size,
+# shared with everything else in the account), not any fleet.
+#
+# What survives is only this: the edge reserves OUT of pool stock, so targeting
+# more than the pool maintains starves every shard. Raise the pool first, then
+# this. Measured before the change: burst-30 returned exactly 24 fast (90ms
+# median) and dropped the remaining 6 to the CP.
+POOL_STOCK_TARGET = "18"
+POOL_STOCK_LOW_WATER = "9"
# 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/internal/api/backend.go b/internal/api/backend.go
index a1a5a30d..494bf83f 100644
--- a/internal/api/backend.go
+++ b/internal/api/backend.go
@@ -177,6 +177,16 @@ type Placer interface {
// rows, where an unwritten row is a host nothing will ever reclaim.
RequiresPersistedRow() bool
+ // DefersPersist reports whether the session row may be written after the
+ // create has already been answered.
+ //
+ // True only when Claim itself leaves the sandbox fully serviceable in this
+ // process — bound, routable, and warm — so nothing in the request path
+ // reads the row it is skipping. A backend that resolves a sandbox by
+ // querying the database must answer false, or its own next request races
+ // a write that has not landed.
+ DefersPersist() bool
+
// Release gives back a claim that will not be activated, after a create
// fails between the two calls.
//
diff --git a/internal/api/backend_conformance_test.go b/internal/api/backend_conformance_test.go
index dd2ca562..efe51f5e 100644
--- a/internal/api/backend_conformance_test.go
+++ b/internal/api/backend_conformance_test.go
@@ -234,6 +234,11 @@ func (f *fakePlacer) Accepts(placement) bool { return true }
func (f *fakePlacer) RequiresPersistedRow() bool { return false }
+// DefersPersist false: these fakes assert on registration and routing order,
+// and deferring the write would move a step out of the sequence the ordering
+// tests exist to pin.
+func (f *fakePlacer) DefersPersist() bool { return false }
+
func (f *fakePlacer) Release(context.Context, string, string) {}
func (f *fakePlacer) Claim(context.Context, placement) (string, error) {
diff --git a/internal/api/create_flow.go b/internal/api/create_flow.go
index 4e267d0f..8c432388 100644
--- a/internal/api/create_flow.go
+++ b/internal/api/create_flow.go
@@ -60,6 +60,23 @@ type createSteps struct {
promote func(ctx context.Context, workerID string) error
// cleanup runs when activate fails, with the cause. Nil skips it.
cleanup func(ctx context.Context, workerID string, cause error)
+ // deferPersist moves persist+promote off the request, running them after
+ // the caller already has its answer.
+ //
+ // Only safe for a backend whose claim has ALREADY made the sandbox usable
+ // in-process — the MicroVM backend binds sandbox→box and adopts the warm
+ // tunnel inside Claim, so exec, destroy and routing all work the instant
+ // Claim returns. The row is bookkeeping consumed by restart recovery and
+ // billing, neither of which cares about a few hundred milliseconds.
+ //
+ // Measured: those two writes were 230ms of a 450ms create — over half the
+ // customer-visible latency spent on a row nobody reads during the request.
+ //
+ // The safety net is what makes this defensible rather than reckless: a
+ // write that fails leaves a box the runtime still knows about, which the
+ // reconciler adopts from AWS and the orphan sweep reclaims if it does not.
+ // Without both of those this would be a quota leak generator.
+ deferPersist bool
}
// runCreate executes the steps in the one order that is correct.
@@ -90,6 +107,25 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
return "", err
}
+ // Deferred-persist backends run activate on the request and everything
+ // durable behind it. Activate stays inline because it is the step that can
+ // still fail the create; the writes cannot, by construction.
+ if steps.deferPersist {
+ if steps.activate != nil {
+ t = time.Now()
+ aerr := steps.activate(ctx, workerID)
+ activateMs = time.Since(t).Milliseconds()
+ if aerr != nil {
+ if steps.cleanup != nil {
+ steps.cleanup(ctx, workerID, aerr)
+ }
+ return "", fmt.Errorf("create: activate %s on %s: %w", sandboxID, workerID, aerr)
+ }
+ }
+ go persistAfterResponse(sandboxID, workerID, steps)
+ return workerID, nil
+ }
+
if steps.persist != nil {
t = time.Now()
err := steps.persist(ctx, workerID)
@@ -136,6 +172,44 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
return workerID, nil
}
+// persistDeferTimeout bounds the background write. Generous — the customer is
+// not waiting — but finite, so a wedged database cannot accumulate goroutines
+// for every create the cell serves.
+const persistDeferTimeout = 30 * time.Second
+
+// persistAfterResponse writes the session row once the customer already has
+// their sandbox. Runs on its own context: the request's is cancelled the moment
+// the response is flushed, which would abort every one of these writes.
+//
+// Failures are logged, not retried here. The reconciler adopts a live box whose
+// row is missing, and the orphan sweep reclaims one nothing adopts — retrying
+// against a database that just failed is less reliable than the sweep that
+// exists for precisely this case.
+func persistAfterResponse(sandboxID, workerID string, steps createSteps) {
+ ctx, cancel := context.WithTimeout(context.Background(), persistDeferTimeout)
+ defer cancel()
+
+ start := time.Now()
+ if steps.persist != nil {
+ if err := steps.persist(ctx, workerID); err != nil {
+ log.Printf("create: deferred persist failed for %s on %s: %v — reconciler will settle it",
+ sandboxID, workerID, err)
+ // Skip promote: flipping a row to running that was never inserted
+ // is a no-op at best and a confusing partial write at worst.
+ return
+ }
+ }
+ if steps.promote != nil {
+ if err := steps.promote(ctx, workerID); err != nil {
+ log.Printf("create: deferred promote failed for %s on %s: %v", sandboxID, workerID, err)
+ return
+ }
+ }
+ if d := time.Since(start); d >= createTimingLogThreshold {
+ log.Printf("create: %s deferred writes took %dms (off the request path)", sandboxID, d.Milliseconds())
+ }
+}
+
// respondCreateErr answers a failed create, separating "we are full" from "we
// are being asked too fast" from "that host is restarting" from everything else.
//
diff --git a/internal/api/create_flow_test.go b/internal/api/create_flow_test.go
index a0e02a9a..800d9e7f 100644
--- a/internal/api/create_flow_test.go
+++ b/internal/api/create_flow_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"strings"
"testing"
+ "time"
)
// create_flow_test.go — the create sequence, which until now was a comment.
@@ -151,3 +152,76 @@ func TestRunCreateSkipsNilActivate(t *testing.T) {
t.Fatalf("sequence was %q, want the activate step skipped", got)
}
}
+
+// The whole point of deferPersist is that the customer is not waiting on the
+// database. Blocking the write and asserting the create still returns proves
+// that directly — if persist were inline this test would deadlock until the
+// timeout, which is exactly the 230ms we are removing from every create.
+func TestDeferPersistAnswersBeforeTheWriteCompletes(t *testing.T) {
+ release := make(chan struct{})
+ persistStarted := make(chan struct{})
+ promoted := make(chan struct{})
+
+ steps := createSteps{
+ claim: func(context.Context) (string, error) { return "vmhost:mvm-1", nil },
+ deferPersist: true,
+ persist: func(context.Context, string) error {
+ close(persistStarted)
+ <-release
+ return nil
+ },
+ promote: func(context.Context, string) error { close(promoted); return nil },
+ }
+
+ done := make(chan string, 1)
+ go func() {
+ id, err := runCreate(context.Background(), "sb-1", steps)
+ if err != nil {
+ t.Errorf("runCreate: %v", err)
+ }
+ done <- id
+ }()
+
+ select {
+ case id := <-done:
+ if id != "vmhost:mvm-1" {
+ t.Fatalf("workerID = %q", id)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("create blocked on the deferred write — it is still on the request path")
+ }
+
+ // And the write really does happen, rather than being dropped.
+ select {
+ case <-persistStarted:
+ case <-time.After(3 * time.Second):
+ t.Fatal("deferred persist never started")
+ }
+ close(release)
+ select {
+ case <-promoted:
+ case <-time.After(3 * time.Second):
+ t.Fatal("deferred promote never ran after persist succeeded")
+ }
+}
+
+// A failed deferred persist must not promote: flipping a row to running that
+// was never inserted is a partial write nothing else expects. The box is still
+// recoverable — the reconciler adopts it from AWS — but the row must not lie.
+func TestDeferPersistSkipsPromoteWhenPersistFails(t *testing.T) {
+ promoteCalled := make(chan struct{}, 1)
+ steps := createSteps{
+ claim: func(context.Context) (string, error) { return "vmhost:mvm-2", nil },
+ deferPersist: true,
+ persist: func(context.Context, string) error { return errors.New("db down") },
+ promote: func(context.Context, string) error { promoteCalled <- struct{}{}; return nil },
+ }
+ if _, err := runCreate(context.Background(), "sb-2", steps); err != nil {
+ t.Fatalf("create must succeed even when the deferred write will fail: %v", err)
+ }
+ select {
+ case <-promoteCalled:
+ t.Fatal("promoted a row that was never inserted")
+ case <-time.After(300 * time.Millisecond):
+ }
+}
diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.go
index d60faabf..e9d09abc 100644
--- a/internal/api/edge_claim.go
+++ b/internal/api/edge_claim.go
@@ -7,6 +7,7 @@ import (
"net/http"
"time"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
@@ -14,6 +15,16 @@ import (
pb "github.com/opensandbox/opensandbox/proto/worker"
)
+// processEpoch identifies THIS control-plane process to the edge's PoolStock
+// DOs. Any backend whose edge reservations live in memory rather than in
+// Postgres stamps its reserve responses with it, so a DO holding stock from a
+// previous process can tell that every id it has is dead and drop them (see
+// edgeReservePool for the failure this prevents).
+//
+// Generated per process, deliberately: a value derived from anything stable —
+// hostname, cell id, config — would survive the restart it exists to detect.
+var processEpoch = uuid.New().String()
+
// Edge claim: the api-edge Worker's PoolStock Durable Object reserves parked
// pool boxes ahead of time (edge-reserve), answers default-shape creates
// entirely at the edge (pop + mint token + 201), then finalizes the claim
@@ -52,6 +63,37 @@ func (s *Server) edgeReservePool(c echo.Context) error {
if region == "" {
region = "local"
}
+
+ // A cell whose backend keeps its own stock answers from that instead of the
+ // Postgres pool — its boxes have no rows to flip.
+ //
+ // That difference is why this branch carries an epoch and the Postgres one
+ // below does not. A PG reservation is a row: it survives a restart, so stock
+ // the DO is holding stays valid across one. An in-memory reservation does
+ // not. The sandbox id, the manager binding behind it, and the pool entry
+ // itself all live in this process, so a restart silently invalidates every
+ // id the DO is holding — and with no epoch the DO would keep serving up to
+ // SHARDS × TARGET_STOCK of them for the full ENTRY_TTL. Each one 201s a
+ // create for a box that no longer routes, so the customer's first exec finds
+ // no binding and 500s. Measured on dev after a restart: 46 and 47 lost
+ // finalizes in consecutive 10-minute buckets.
+ //
+ // The DO drops its whole stock when this value changes (see pool_stock.ts),
+ // which bounds the exposure to one restock cycle.
+ if ec, ok := s.edgeClaimBackend(); ok {
+ boxes := ec.EdgeReserve(req.Count)
+ out := make([]map[string]string, 0, len(boxes))
+ for _, b := range boxes {
+ out = append(out, map[string]string{"sandboxID": b.SandboxID, "workerID": b.WorkerID})
+ }
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "region": region,
+ "sandboxDomain": s.sandboxDomain,
+ "epoch": processEpoch,
+ "boxes": out,
+ })
+ }
+
boxes, err := s.store.ReservePooledForEdge(c.Request().Context(), region, poolTemplateName(), req.Count)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
@@ -77,6 +119,9 @@ func (s *Server) edgeReleasePool(c echo.Context) error {
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})
}
+ if ec, ok := s.edgeClaimBackend(); ok {
+ return c.JSON(http.StatusOK, map[string]int{"released": ec.EdgeRelease(req.SandboxIDs)})
+ }
n, err := s.store.ReleaseEdgeReservations(c.Request().Context(), req.SandboxIDs)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
@@ -127,6 +172,43 @@ func (s *Server) claimFinalize(c echo.Context) error {
cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
metadataJSON, _ := json.Marshal(cfg.Metadata)
+
+ // Backend-owned stock: redeem the reservation in memory, then write the row
+ // the QEMU path flips instead of inserts. There is no ClaimSandbox call and
+ // no worker to reach — the box was bound and its tunnel adopted back at
+ // reserve, which is the whole reason this finalize can run after the
+ // customer already holds their 201.
+ if ec, ok := s.edgeClaimBackend(); ok {
+ workerID, err := ec.EdgeFinalize(cfg.SandboxID, cfg)
+ if err != nil {
+ // The reservation is gone (reaped, or a duplicate delivery of a
+ // finalize that already ran). Nothing to bind and nothing to undo.
+ log.Printf("sandbox: EDGE CLAIM FINALIZE LOST %s (%v)", cfg.SandboxID, err)
+ return c.JSON(http.StatusConflict, map[string]string{"error": "reservation lost"})
+ }
+ template := cfg.Template
+ if template == "" {
+ template = "default"
+ }
+ if s.store != nil {
+ if _, err := s.store.CreateSandboxSessionWithStatus(ctx, cfg.SandboxID, orgID, auth.GetUserID(c),
+ template, s.poolStockRegion(), workerID, cfgJSON, metadataJSON, "running", nil); err != nil {
+ // The host is live and the customer holds a token for it, so
+ // failing here does not take it back. Report it and let the
+ // orphan sweep reclaim a box with no row — the mechanism that
+ // exists for exactly this hole.
+ log.Printf("sandbox: edge claim-finalize row insert %s failed: %v", cfg.SandboxID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ }
+ s.emitEvent("create", cfg.SandboxID, workerID, "claimed from warm pool (edge)")
+ log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", cfg.SandboxID, workerID)
+ return c.JSON(http.StatusOK, map[string]string{
+ "sandboxID": cfg.SandboxID,
+ "workerID": workerID,
+ "status": "running",
+ })
+ }
box, err := s.store.ClaimReservedSession(ctx, cfg.SandboxID, orgID, auth.GetUserID(c), cfgJSON, metadataJSON, nil)
if err != nil {
// Reservation lost (reaped/drained). Nothing is bound; make sure the
diff --git a/internal/api/edge_claim_microvm.go b/internal/api/edge_claim_microvm.go
new file mode 100644
index 00000000..88f2cf0f
--- /dev/null
+++ b/internal/api/edge_claim_microvm.go
@@ -0,0 +1,304 @@
+package api
+
+import (
+ "fmt"
+ "log"
+ "sync"
+
+ "github.com/google/uuid"
+
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// edge_claim_microvm.go — the MicroVM half of the edge-claim protocol.
+//
+// The QEMU implementation next door runs the whole reservation state machine in
+// Postgres, because there a pool box is already a row: it was created by a
+// worker, it has a sandbox id, and the CP's only job is to flip its status. None
+// of that is true here. A MicroVM pool box is an in-memory *awsvm.StockEntry
+// holding a live gRPC channel; it has no row, no sandbox id, and it cannot be
+// serialized anywhere. So this path implements the same transitions against the
+// pool's own reservation map:
+//
+// pooled → reserved EdgeReserve (pool.Reserve)
+// reserved → bound EdgeFinalize (pool.ClaimReserved; the caller writes the row)
+// reserved → pooled EdgeRelease (pool.ReleaseReserved — never tokened)
+// reserved → gone pool.expireReservations, which TERMINATES (see its
+// docstring: a stale reservation may already be in a
+// customer's hands, so re-pooling it is cross-tenant access)
+//
+// The one real design difference from QEMU: the sandbox id is assigned at
+// RESERVE, not at finalize, and the box is bound to it immediately. That is what
+// makes the edge answer safe. The edge returns a 201 the moment it pops a box
+// from DO stock, and the customer's first exec can arrive before finalize has
+// run — on the QEMU path that resolves anyway because the cell proxies by
+// worker_id, but here routing goes through the manager's sandbox→box map. If
+// that map were only written at finalize, every create would have a window where
+// its own sandbox id 404s. Binding at reserve closes it: by the time the id
+// exists anywhere outside this process, it already routes.
+//
+// The cost of binding early is that a reservation which dies unclaimed leaves a
+// binding behind, which is what PoolConfig.OnExpire is for.
+
+// edgeBox is one reserved box as the PoolStock DO sees it: an identity, nothing
+// more. The tunnel and the entry stay in this process.
+type edgeBox struct {
+ SandboxID string
+ WorkerID string
+}
+
+// edgeClaimer is a backend that serves edge-claim from its own stock instead of
+// the shared Postgres pool. A backend that does not implement it falls through
+// to the PG path, which is what every QEMU cell does.
+//
+// Deliberately store-free: the row write is identical for every backend and the
+// handler already owns every other store call on this path, so keeping it there
+// leaves this interface about stock and bindings only.
+type edgeClaimer interface {
+ EdgeReserve(n int) []edgeBox
+ EdgeRelease(sandboxIDs []string) int
+ EdgeFinalize(sandboxID string, cfg types.SandboxConfig) (workerID string, err error)
+}
+
+var _ edgeClaimer = (*microvmBackend)(nil)
+
+// edgeReservedMap tracks reservations this backend made for the edge, keyed by
+// the AWS host id so an expiry callback — which only knows the host — can find
+// the sandbox id it has to forget.
+type edgeReservedMap struct {
+ mu sync.Mutex
+ m map[string]string // microvmID → sandboxID
+}
+
+func (r *edgeReservedMap) put(microvmID, sandboxID string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.m == nil {
+ r.m = make(map[string]string)
+ }
+ r.m[microvmID] = sandboxID
+}
+
+func (r *edgeReservedMap) take(microvmID string) (string, bool) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ id, ok := r.m[microvmID]
+ if ok {
+ delete(r.m, microvmID)
+ }
+ return id, ok
+}
+
+func (r *edgeReservedMap) depth() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return len(r.m)
+}
+
+// sandboxIDs returns the sandbox ids currently held as edge reservations.
+//
+// A reservation has a binding in the manager but no running row — it is
+// deliberately parked between the two. Anything reconciling bindings against
+// rows has to subtract these first, or every reservation reads as a binding
+// whose sandbox has vanished.
+func (r *edgeReservedMap) sandboxIDs() map[string]struct{} {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ out := make(map[string]struct{}, len(r.m))
+ for _, id := range r.m {
+ out[id] = struct{}{}
+ }
+ return out
+}
+
+// EdgeReserve promises up to n warm boxes to the edge's PoolStock DO, assigning
+// each a sandbox id and binding it now — see the file docstring for why the
+// binding cannot wait for finalize.
+//
+// Returns fewer than n, or none, when stock is short. Not an error: the DO tops
+// up again on its next alarm, and a create that finds empty stock falls back to
+// the control plane, which is exactly the path this optimization skips.
+func (b *microvmBackend) EdgeReserve(n int) []edgeBox {
+ if b == nil || b.pool == nil {
+ return nil
+ }
+ entries := b.pool.Reserve(n)
+ if len(entries) == 0 {
+ return nil
+ }
+ out := make([]edgeBox, 0, len(entries))
+ for _, e := range entries {
+ sandboxID := "sb-" + uuid.New().String()[:8]
+ // Empty cfg deliberately: nobody has asked for anything yet. It resolves
+ // to the delivered size, which is what this runtime hands out regardless
+ // of the request (see deliveredSize), so the billing shape is already
+ // correct before the customer arrives. EdgeFinalize re-tracks with the
+ // real config once there is one.
+ b.manager.TrackClaimed(sandboxID, e, types.SandboxConfig{})
+ b.edgeReserved.put(e.MicrovmID, sandboxID)
+ out = append(out, edgeBox{SandboxID: sandboxID, WorkerID: microvmWorkerID(e.MicrovmID)})
+ }
+ log.Printf("microvm: edge-reserved %d box(es) (asked %d, %d left in stock)", len(out), n, b.pool.Depth())
+ return out
+}
+
+// EdgeRelease takes back stock the DO discarded without ever handing it to a
+// customer. Safe to re-pool precisely because of that assertion — which is the
+// DO's to make, not ours; see expireReservations for the case where we cannot
+// make it and must terminate instead.
+func (b *microvmBackend) EdgeRelease(sandboxIDs []string) int {
+ if b == nil || b.pool == nil {
+ return 0
+ }
+ released := 0
+ for _, sandboxID := range sandboxIDs {
+ microvmID, ok := b.manager.MicrovmIDFor(sandboxID)
+ if !ok {
+ continue
+ }
+ if !b.pool.ReleaseReserved(microvmID) {
+ // Already claimed, or already expired. Leave the binding alone: if it
+ // was claimed it belongs to a customer now, and forgetting it here
+ // would strand a live sandbox.
+ continue
+ }
+ // Hand the tunnel back to the pool before dropping the binding. Forget
+ // would CLOSE it, and the box then re-enters stock with no tunnel — so
+ // the next customer to claim it pays a full cold dial on their first
+ // exec (measured 549ms vs 76ms warm). Safe here and nowhere else: the DO
+ // is asserting it never handed this box to a customer, which is the same
+ // assertion that makes re-pooling the box itself legal.
+ //
+ // Ordered after ReleaseReserved deliberately — if that failed the box is
+ // claimed, the customer owns the channel, and we must not take it.
+ if a := b.manager.DetachAgent(sandboxID); a != nil {
+ b.pool.AttachAgent(microvmID, a)
+ }
+ b.edgeReserved.take(microvmID)
+ // Back to anonymous stock, so this id must stop resolving — the box will
+ // be reissued under a different one at the next reserve.
+ b.manager.Forget(sandboxID)
+ released++
+ }
+ if released > 0 {
+ log.Printf("microvm: edge released %d reservation(s) back to stock", released)
+ }
+ return released
+}
+
+// EdgeFinalize redeems the reservation and rebinds the box to the config the
+// customer actually sent. The caller writes the durable row; this is the part
+// only the backend can do.
+//
+// Redeeming is what makes finalizing late safe: ClaimReserved fails if the
+// reaper got there first, so a finalize racing expiry reports the loss instead
+// of confirming a box that no longer exists.
+func (b *microvmBackend) EdgeFinalize(sandboxID string, cfg types.SandboxConfig) (string, error) {
+ if b == nil || b.pool == nil {
+ return "", fmt.Errorf("microvm: backend disabled")
+ }
+ microvmID, ok := b.manager.MicrovmIDFor(sandboxID)
+ if !ok {
+ return "", fmt.Errorf("microvm: finalize %s: no box bound to that sandbox", sandboxID)
+ }
+ entry, ok := b.pool.ClaimReserved(microvmID)
+ if !ok {
+ return "", fmt.Errorf("microvm: finalize %s: reservation lost (box %s)", sandboxID, microvmID)
+ }
+ b.edgeReserved.take(microvmID)
+
+ // Re-track with the real config. Track overwrites the byID entry only — the
+ // agent channel lives in a separate map keyed by sandbox id — so the
+ // pre-dialled tunnel adopted at reserve survives this.
+ b.manager.TrackClaimed(sandboxID, entry, cfg)
+ return microvmWorkerID(microvmID), nil
+}
+
+// forgetExpiredReservation is the PoolConfig.OnExpire callback: a reservation
+// died unredeemed and its box has been terminated, so the sandbox id bound at
+// reserve must stop resolving.
+func (b *microvmBackend) forgetExpiredReservation(microvmID string) {
+ sandboxID, ok := b.edgeReserved.take(microvmID)
+ if !ok {
+ return
+ }
+ b.manager.Forget(sandboxID)
+ log.Printf("microvm: edge reservation %s (box %s) expired unclaimed — binding dropped", sandboxID, microvmID)
+}
+
+// edgeClaimBackend returns this cell's backend if it serves edge-claim from its
+// own stock. Dispatching on the placing backend rather than on the caller's org
+// is deliberate: a reserve request arrives from a Durable Object holding stock
+// for THIS cell, so the question is what this cell runs — a fact the cell knows
+// without consulting anyone.
+func (s *Server) edgeClaimBackend() (edgeClaimer, bool) {
+ b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})
+ if !ok {
+ return nil, false
+ }
+ ec, ok := b.(edgeClaimer)
+ return ec, ok
+}
+
+// poolStockRegion is the region stamped on rows and on the reserve response.
+// "local" stands in for an unset region so a dev cell still writes a row that
+// the reconciler's region-scoped queries can find.
+func (s *Server) poolStockRegion() string {
+ if s.region == "" {
+ return "local"
+ }
+ return s.region
+}
+
+// boxesInUse reports the boxes the pool cannot see: ones bound to a live
+// sandbox. It is what PoolConfig.InUse asks, and the budget adds it to the
+// pool's own committed count to decide whether there is room to refill.
+//
+// The subtraction is the whole point. EdgeReserve binds a box to its sandbox id
+// at RESERVE rather than at finalize (see the file header for why that window
+// has to be closed), so a box waiting in a PoolStock shard is tracked by the
+// manager AND counted by committed()'s len(p.reserved). Left uncorrected the
+// budget sees roughly SHARDS × POOL_STOCK_TARGET boxes that do not exist —
+// measured on dev as "130 in use + 124 committed" against a fleet of 130 —
+// which holds the pool at a permanent refill freeze.
+func (b *microvmBackend) boxesInUse() int {
+ if b == nil || b.manager == nil {
+ return 0
+ }
+ n := len(b.manager.TrackedMicrovmIDs()) - b.edgeReserved.depth()
+ if n < 0 {
+ // The two counts are taken without a shared lock, so a reserve landing
+ // between them can transiently invert the difference. Reporting a
+ // negative would credit the budget with headroom it does not have.
+ return 0
+ }
+ return n
+}
+
+// warmReservedTunnels keeps the agent channel alive on every box reserved to the
+// edge but not yet claimed by a customer. Wired to PoolConfig.OnMaintain.
+//
+// These boxes are the pool's whole reason for existing and they are the ones
+// nothing else warms. EdgeReserve moves the channel to the manager and takes the
+// entry out of p.stock, so the pool's own warmTunnels cannot see it — measured
+// on dev, that left ~126 of 150 boxes unwarmed while only the 24 free ones were
+// being maintained. A reservation then sits in a PoolStock shard for minutes
+// with no traffic, its tunnel lapses, and the customer who claims it pays the
+// re-handshake on their FIRST exec, which is exactly what TTI measures
+// (383ms cold vs 75ms warm).
+//
+// Safe to ping precisely because no customer owns these yet: the idle-suspend
+// policy that forbids keepalive on a live sandbox has nothing to say about warm
+// stock, which is supposed to be running and ready.
+func (b *microvmBackend) warmReservedTunnels() {
+ if b == nil || b.manager == nil {
+ return
+ }
+ reserved := b.edgeReserved.sandboxIDs()
+ if len(reserved) == 0 {
+ return
+ }
+ if n := b.manager.WarmAgents(reserved); n > 0 {
+ log.Printf("microvm: re-warmed %d idle tunnel(s) across %d edge reservation(s)", n, len(reserved))
+ }
+}
diff --git a/internal/api/edge_claim_microvm_test.go b/internal/api/edge_claim_microvm_test.go
new file mode 100644
index 00000000..1267c610
--- /dev/null
+++ b/internal/api/edge_claim_microvm_test.go
@@ -0,0 +1,184 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+
+ lambdamicrovms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// failingGetAPI answers every describe with an error, standing in for the
+// transient API failures that must never be mistaken for a terminated box.
+type failingGetAPI struct{ sweepAPI }
+
+func (f *failingGetAPI) GetMicrovm(context.Context, *lambdamicrovms.GetMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ return nil, errors.New("describe unavailable")
+}
+
+// A disabled backend is what every QEMU cell has. The edge-claim endpoints are
+// reachable on all of them, so each entry point must be inert rather than
+// dereferencing a nil pool — the same class of bug the conformance suite exists
+// to catch, now on three new methods.
+func TestEdgeClaimIsInertWhenDisabled(t *testing.T) {
+ var b *microvmBackend
+ if got := b.EdgeReserve(5); got != nil {
+ t.Errorf("disabled backend reserved %d box(es)", len(got))
+ }
+ if n := b.EdgeRelease([]string{"sb-anything"}); n != 0 {
+ t.Errorf("disabled backend released %d", n)
+ }
+ if _, err := b.EdgeFinalize("sb-anything", types.SandboxConfig{}); err == nil {
+ t.Error("disabled backend finalized a claim without error")
+ }
+}
+
+// The expiry callback is the counterpart to binding a sandbox id at reserve
+// time. Its whole job is to make that id stop resolving once the box behind it
+// has been terminated; a binding that outlives its box turns a clean 404 into a
+// timeout somewhere in the agent tunnel.
+func TestForgetExpiredReservationDropsTheBinding(t *testing.T) {
+ b := &microvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}
+ const microvmID = "microvm-abc123"
+ const sandboxID = "sb-deadbeef"
+
+ b.manager.TrackClaimed(sandboxID, &awsvm.StockEntry{MicrovmID: microvmID}, types.SandboxConfig{})
+ b.edgeReserved.put(microvmID, sandboxID)
+ if _, ok := b.manager.MicrovmIDFor(sandboxID); !ok {
+ t.Fatal("reserve did not bind the sandbox id — routing would 404 before finalize")
+ }
+
+ b.forgetExpiredReservation(microvmID)
+
+ if _, ok := b.manager.MicrovmIDFor(sandboxID); ok {
+ t.Error("sandbox id still resolves after its reservation expired and its box was terminated")
+ }
+ if b.edgeReserved.depth() != 0 {
+ t.Errorf("reservation map still holds %d entry(s)", b.edgeReserved.depth())
+ }
+ // Idempotent: the pool fires this from a goroutine per stale entry, and a
+ // duplicate must not unbind something a later reserve rebound.
+ b.forgetExpiredReservation(microvmID)
+}
+
+// Finalize must refuse a sandbox id it never handed out. Accepting one would
+// write a durable row for a box this cell does not hold.
+func TestEdgeFinalizeRejectsAnUnboundSandbox(t *testing.T) {
+ b := &microvmBackend{
+ manager: awsvm.NewManager(nil, os.TempDir()),
+ pool: awsvm.NewPool(nil, awsvm.PoolConfig{}),
+ }
+ if _, err := b.EdgeFinalize("sb-neverseen", types.SandboxConfig{}); err == nil {
+ t.Fatal("finalized a sandbox that was never reserved")
+ }
+}
+
+// The pool's box budget is only as good as the inventory it is fed. Reserving
+// for the edge binds a box in the manager while it is still counted as pool
+// stock, so a naive "in use = everything tracked" double-counts the entire
+// magazine — on dev that read 130 in use against a fleet of exactly 130 boxes,
+// freezing refill for good.
+func TestEdgeReservationsAreNotCountedAsBoxesInUse(t *testing.T) {
+ b := &microvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}
+
+ // Two boxes sitting in edge stock, one genuinely claimed by a customer.
+ for _, id := range []string{"mvm-stock-1", "mvm-stock-2"} {
+ sb := "sb-" + id
+ b.manager.TrackClaimed(sb, &awsvm.StockEntry{MicrovmID: id}, types.SandboxConfig{})
+ b.edgeReserved.put(id, sb)
+ }
+ b.manager.TrackClaimed("sb-live", &awsvm.StockEntry{MicrovmID: "mvm-live"}, types.SandboxConfig{})
+
+ if got := b.boxesInUse(); got != 1 {
+ t.Fatalf("boxesInUse = %d, want 1 — edge stock is already counted by the pool's committed(), so counting it here inflates the budget by the whole magazine", got)
+ }
+
+ // Finalizing a reservation hands the box to a customer: it leaves the
+ // reservation map and must start counting.
+ b.edgeReserved.take("mvm-stock-1")
+ if got := b.boxesInUse(); got != 2 {
+ t.Fatalf("boxesInUse = %d after a reservation was claimed, want 2", got)
+ }
+}
+
+// A reserve landing between the two unsynchronized reads must never produce a
+// negative, which would hand the budget headroom that does not exist.
+func TestBoxesInUseNeverGoesNegative(t *testing.T) {
+ b := &microvmBackend{manager: awsvm.NewManager(nil, os.TempDir())}
+ b.edgeReserved.put("mvm-racing", "sb-racing") // reserved, not yet tracked
+ if got := b.boxesInUse(); got != 0 {
+ t.Fatalf("boxesInUse = %d, want 0", got)
+ }
+}
+
+// The reconciler is driven by the sessions table, so it can only ever repair a
+// binding whose sandbox still has a running row. Bindings whose row reached a
+// terminal state by some other path are unreachable by it — and because
+// TrackedMicrovmIDs feeds boxesInUse, which is the pool budget's "in use" term,
+// each one permanently convinces the pool that a box is busy. The pool then
+// refuses to manufacture a replacement for a box that no longer exists, so a
+// cell's usable depth decays over its uptime and only a restart clears it.
+//
+// Measured on dev: 80 "in use" against a 230-box budget, with the pool pinned at
+// depth 1-3 out of a target of 150 while the edge served creates cold.
+func TestDeadBindingsStopHoldingPoolBudget(t *testing.T) {
+ f := &sweepAPI{
+ getImage: map[string]string{},
+ getState: map[string]mvtypes.MicrovmState{
+ "mvm-dead": mvtypes.MicrovmStateTerminated,
+ },
+ }
+ b := sweepBackend(t, f)
+
+ // Four bindings, one of each shape the sweep has to tell apart.
+ b.manager.TrackClaimed("sb-live", &awsvm.StockEntry{MicrovmID: "mvm-live"}, types.SandboxConfig{})
+ b.manager.TrackClaimed("sb-dead", &awsvm.StockEntry{MicrovmID: "mvm-dead"}, types.SandboxConfig{})
+ b.manager.TrackClaimed("sb-rowless", &awsvm.StockEntry{MicrovmID: "mvm-rowless"}, types.SandboxConfig{})
+ b.manager.TrackClaimed("sb-reserved", &awsvm.StockEntry{MicrovmID: "mvm-reserved"}, types.SandboxConfig{})
+ b.edgeReserved.put("mvm-reserved", "sb-reserved")
+
+ // Only sb-live still has a row; everything else is invisible to reconcileOnce.
+ b.forgetDeadBindings(context.Background(), map[string]struct{}{"sb-live": {}})
+
+ if _, ok := b.manager.MicrovmIDFor("sb-dead"); ok {
+ t.Error("kept a binding whose box AWS reports terminated — this is the entry that holds budget forever")
+ }
+ if _, ok := b.manager.MicrovmIDFor("sb-live"); !ok {
+ t.Error("dropped a binding that still has a running row")
+ }
+ // Rowless but alive is ambiguous — a create mid-flight looks exactly like a
+ // leak. On an account shared with other products the sweep reports it and
+ // leaves it to sweepOrphans, which has the age and image guards.
+ if _, ok := b.manager.MicrovmIDFor("sb-rowless"); !ok {
+ t.Error("unbound a live box on the strength of a missing row alone")
+ }
+ // Reservations are rowless by construction: binding before the row exists is
+ // the entire point of reserving. Reaping them would break every create the
+ // edge has in flight.
+ if _, ok := b.manager.MicrovmIDFor("sb-reserved"); !ok {
+ t.Error("unbound an in-flight edge reservation")
+ }
+ if len(f.terminated) != 0 {
+ t.Errorf("binding sweep terminated %v — it must only ever drop local state; this AWS account is shared", f.terminated)
+ }
+}
+
+// A describe that fails must not be read as "the box is gone". Unbinding a live
+// sandbox on a transient API error would 404 a customer's running box.
+func TestBindingSweepKeepsBindingsItCannotProveDead(t *testing.T) {
+ f := &failingGetAPI{}
+ b := sweepBackend(t, &sweepAPI{getImage: map[string]string{}})
+ b.client = awsvm.NewClientWithAPI(f, awsvm.Config{ImageIdentifier: "arn:ours"})
+ b.manager.TrackClaimed("sb-unprovable", &awsvm.StockEntry{MicrovmID: "mvm-unprovable"}, types.SandboxConfig{})
+
+ b.forgetDeadBindings(context.Background(), nil)
+
+ if _, ok := b.manager.MicrovmIDFor("sb-unprovable"); !ok {
+ t.Fatal("dropped a binding because the describe failed — an API blip must not unbind a running sandbox")
+ }
+}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
index e002bf25..25bb70ad 100644
--- a/internal/api/microvm_backend.go
+++ b/internal/api/microvm_backend.go
@@ -80,6 +80,11 @@ type microvmBackend struct {
// not leave stock running: abandoned boxes bill compute and hold regional
// memory quota until the 8h service cap.
stopPool context.CancelFunc
+
+ // edgeReserved maps a reserved box back to the sandbox id bound to it at
+ // reserve time, so an expiring reservation can drop that binding. See
+ // edge_claim_microvm.go for why the binding happens that early.
+ edgeReserved edgeReservedMap
}
// microvmEnabled reports whether this cell serves MicroVM-backed sandboxes.
@@ -153,24 +158,62 @@ func newMicrovmBackend(ctx context.Context, checkpointStore *storage.CheckpointS
log.Printf("microvm: idle policy — suspend after %ds idle, terminate after %ds suspended, auto-resume=%v",
idleSec, suspendedSec, autoResume)
- pool := awsvm.NewPool(client, awsvm.PoolConfig{
- TargetStock: envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20),
- })
-
poolCtx, stop := context.WithCancel(context.Background())
- go pool.Run(poolCtx)
- log.Printf("microvm: backend enabled (region=%s image=%s poolTarget=%d)",
- region, image, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
-
- return &microvmBackend{
+ // Built before the pool because the pool's expiry callback reaches back into
+ // it: an edge reservation that dies unclaimed has to drop the sandbox
+ // binding this backend made when it handed the box to the edge.
+ b := &microvmBackend{
client: client,
- pool: pool,
manager: awsvm.NewManager(client, os.TempDir()),
checkpointStore: checkpointStore,
coldSlots: make(chan struct{}, maxColdCreates),
stopPool: stop,
- }, nil
+ }
+ // The account-wide ceiling, in boxes. The regional quota is expressed in
+ // gigabytes (1024 by default, adjustable), and every box costs the image's
+ // delivered size regardless of what the create asked for — so the box count
+ // is what actually has to be capped. Default 0 (off) so a cell nobody has
+ // sized keeps its previous behaviour rather than silently refusing to fill.
+ maxTotal := envInt("OPENSANDBOX_MICROVM_MAX_TOTAL_BOXES", 0)
+ b.pool = awsvm.NewPool(client, awsvm.PoolConfig{
+ TargetStock: envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20),
+ MaxTotalBoxes: maxTotal,
+ // Claimed boxes are exactly the ones the manager tracks: a box enters on
+ // Claim and leaves on Release, which is the population the pool is blind
+ // to and the reason a target-only filler can overrun the quota.
+ //
+ // Minus the edge's reservations, which the pool already counts itself.
+ // EdgeReserve binds a box to its sandbox id at RESERVE (see
+ // edge_claim_microvm.go for why that window has to be closed), so every
+ // box sitting in a PoolStock shard is simultaneously tracked here and
+ // inside committed()'s len(p.reserved). Double-counting them makes the
+ // budget hallucinate a fleet roughly SHARDS × POOL_STOCK_TARGET larger
+ // than the one AWS is actually running — measured on dev at 130 "in
+ // use" against 130 boxes alive in total, which pinned the pool at a
+ // permanent budget hold and would have starved refill through exactly
+ // the burst the budget exists to survive.
+ InUse: b.boxesInUse,
+ OnExpire: b.forgetExpiredReservation,
+ OnMaintain: b.warmReservedTunnels,
+ // How long refill stands down once the budget is reached. Tunable
+ // because the right value is a property of the workload, not the code:
+ // it wants to outlast the burst that drained the pool, so that the
+ // releases behind it accumulate into headroom instead of being spent
+ // one at a time against the regional quota the burst still needs.
+ RefillDelay: time.Duration(envInt("OPENSANDBOX_MICROVM_POOL_REFILL_DELAY_SECONDS", 60)) * time.Second,
+ })
+ if maxTotal > 0 {
+ log.Printf("microvm: box budget %d (pool target %d) — refill pauses while claimed boxes fill the rest",
+ maxTotal, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
+ }
+
+ go b.pool.Run(poolCtx)
+
+ log.Printf("microvm: backend enabled (region=%s image=%s poolTarget=%d)",
+ region, image, envInt("OPENSANDBOX_MICROVM_POOL_TARGET", 20))
+
+ return b, nil
}
// claimPooled binds a warm host to a sandbox id and returns whether one was
@@ -326,7 +369,11 @@ func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {
}
var restored, closed int
+ hasRow := make(map[string]struct{}, len(rows))
for _, r := range rows {
+ // Recorded before the parse check: a row we cannot parse is still a row,
+ // and the binding sweep below must not treat its sandbox as vanished.
+ hasRow[r.SandboxID] = struct{}{}
microvmID, ok := parseMicrovmWorkerID(r.WorkerID)
if !ok {
continue
@@ -351,6 +398,15 @@ func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {
// against a sandbox that cannot exist.
msg := "microvm no longer exists"
_ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "stopped", &msg)
+ // Drop the in-memory binding too. Closing only the row leaves a
+ // phantom entry in the manager's map that nothing can ever remove:
+ // ListMicrovmSessions returns running rows, so the next pass does not
+ // even see this sandbox again. Those phantoms are counted by
+ // TrackedMicrovmIDs, which is what the pool's box budget treats as
+ // "in use" — measured on dev at 112 phantoms against 130 boxes
+ // actually alive, i.e. a budget that would refuse to refill the pool
+ // during exactly the burst it was sized for.
+ b.manager.Forget(r.SandboxID)
closed++
continue
}
@@ -372,6 +428,77 @@ func (b *microvmBackend) reconcileOnce(ctx context.Context, store *db.Store) {
if restored > 0 || closed > 0 {
log.Printf("microvm: reconciled — adopted %d sandbox(es), closed %d dead row(s)", restored, closed)
}
+ b.forgetDeadBindings(ctx, hasRow)
+}
+
+// bindingSweepCap bounds how many rowless bindings one pass probes against AWS.
+// Each probe is a GetMicrovm, and a cell that has accumulated a large backlog
+// should drain it over successive passes rather than spend its API budget in one
+// burst — the same reasoning as orphanReapCap, minus the blast radius, since
+// this sweep only ever forgets local state.
+const bindingSweepCap = 50
+
+// forgetDeadBindings drops in-memory bindings whose sandbox no longer has a row.
+//
+// reconcileOnce walks the sessions table and can therefore only ever fix a
+// binding whose sandbox still has a running row. That leaves the opposite leak
+// structurally invisible: when a row reaches a terminal state by any path that
+// does not also call Kill or Forget, its binding stays in the manager's map with
+// nothing left that can reach it. Nothing reaps it, and it is counted forever by
+// TrackedMicrovmIDs — which is precisely what boxesInUse reports to the pool as
+// the budget's "in use" term. Every stranded binding is a box the pool believes
+// is working and permanently refuses to replace, so the pool's usable depth
+// decays toward zero over a cell's uptime and never recovers without a restart.
+//
+// Two cases, treated differently on purpose:
+//
+// - Box dead in AWS. Unambiguous, and forgetting is purely local — no API call,
+// nothing destroyed. Dropped.
+// - Box alive but rowless. Only reported. It may be a genuine leak, but it may
+// equally be a create mid-flight whose row has not landed yet, and this
+// account is shared with other products, so acting on "I cannot find the
+// paperwork" is exactly the reasoning that must never terminate anything.
+// sweepOrphans owns that decision, behind its age and attribution guards.
+func (b *microvmBackend) forgetDeadBindings(ctx context.Context, hasRow map[string]struct{}) {
+ if b == nil || b.manager == nil {
+ return
+ }
+ // Edge reservations are bound before any row exists — that window is the
+ // whole point of reserving — so they are rowless by design, not by leak.
+ reserved := b.edgeReserved.sandboxIDs()
+
+ var forgotten, aliveRowless, probed int
+ for sandboxID, microvmID := range b.manager.TrackedBindings() {
+ if _, ok := hasRow[sandboxID]; ok {
+ continue
+ }
+ if _, ok := reserved[sandboxID]; ok {
+ continue
+ }
+ if probed >= bindingSweepCap {
+ break
+ }
+ probed++
+ box, err := b.client.Get(ctx, microvmID)
+ if err != nil {
+ // Could not prove it is dead, so leave it. A transient describe
+ // failure must not be able to unbind a live sandbox.
+ continue
+ }
+ if box.Alive() {
+ aliveRowless++
+ continue
+ }
+ b.manager.Forget(sandboxID)
+ forgotten++
+ }
+ if forgotten > 0 {
+ log.Printf("microvm: binding sweep forgot %d dead binding(s) holding pool budget", forgotten)
+ }
+ if aliveRowless > 0 {
+ log.Printf("microvm: binding sweep — %d live box(es) bound to a sandbox with no row; left alone for the orphan sweep to age out",
+ aliveRowless)
+ }
}
// orphanMinAge is how old a MicroVM must be before the sweep will consider it
@@ -425,7 +552,7 @@ func (b *microvmBackend) sweepOrphans(ctx context.Context) {
armed := envInt("OPENSANDBOX_MICROVM_ORPHAN_REAP", 0) == 1
var orphans []string
- var skippedYoung, skippedForeign int
+ var skippedYoung, skippedForeign, skippedUnprovable int
for _, box := range boxes {
if !box.Alive() {
continue // already terminating; nothing to reclaim
@@ -433,27 +560,55 @@ func (b *microvmBackend) sweepOrphans(ctx context.Context) {
if _, ok := known[box.ID]; ok {
continue
}
- // Never reap a box we did not build. Without this the sweep would
- // happily terminate another environment's pool out from under it.
- if ourImage != "" && box.ImageArn != "" && box.ImageArn != ourImage {
- skippedForeign++
- continue
- }
// An unset StartedAt must protect the box, not expose it. The API does
// not always populate it (observed empty on real Get responses), and
// time.Since(zero) is enormous — so a naive age comparison reads
// "ancient" for exactly the boxes whose age we failed to learn, turning
// the guard inside out and making unknown boxes the most eligible.
+ //
+ // Checked before the image lookup below so a fleet of young boxes cannot
+ // cost us a GetMicrovm each — ListMicrovms already throttles on this
+ // account.
if box.StartedAt.IsZero() || time.Since(box.StartedAt) < orphanMinAge {
skippedYoung++
continue
}
+ // Never reap a box we did not build: this AWS account is shared with
+ // other products, and terminating their hosts would be far worse than
+ // leaking one of ours.
+ //
+ // The match must be POSITIVE. An earlier version skipped the comparison
+ // whenever ImageArn was empty, which inverted the guard exactly like the
+ // StartedAt bug above: a box whose image we failed to learn became
+ // eligible instead of protected. ListMicrovms returns a reduced
+ // projection (it carries no endpoint either), so an empty ImageArn here
+ // says nothing about ownership — resolve it with a Get, and if it still
+ // cannot be established, leave the box alone.
+ arn := box.ImageArn
+ if arn == "" {
+ if full, gerr := b.client.Get(ctx, box.ID); gerr == nil {
+ arn = full.ImageArn
+ }
+ }
+ if ourImage == "" || arn != ourImage {
+ if arn == "" {
+ skippedUnprovable++
+ } else {
+ skippedForeign++
+ }
+ continue
+ }
orphans = append(orphans, box.ID)
}
+ if skippedForeign > 0 || skippedUnprovable > 0 {
+ log.Printf("microvm: orphan sweep left %d foreign-image and %d unprovable box(es) alone",
+ skippedForeign, skippedUnprovable)
+ }
if len(orphans) == 0 {
- if skippedYoung > 0 || skippedForeign > 0 {
- log.Printf("microvm: orphan sweep clean (skipped %d too-young, %d foreign-image)", skippedYoung, skippedForeign)
+ if skippedYoung > 0 || skippedForeign > 0 || skippedUnprovable > 0 {
+ log.Printf("microvm: orphan sweep clean (skipped %d too-young, %d foreign-image, %d unprovable)",
+ skippedYoung, skippedForeign, skippedUnprovable)
}
return
}
@@ -818,6 +973,13 @@ func (b *microvmBackend) Activate(_ context.Context, a activation) (activated, e
// hard lifetime cap.
func (b *microvmBackend) RequiresPersistedRow() bool { return true }
+// DefersPersist is true: Claim binds sandbox→MicroVM in the manager and adopts
+// the pool's warm tunnel before it returns, so exec, destroy and routing all
+// resolve from memory the moment the create is answered. Nothing on the request
+// path reads the row, and the two writes it contains measured 230ms of a 450ms
+// create. Restart recovery reads it, and tolerates arriving late.
+func (b *microvmBackend) DefersPersist() bool { return true }
+
// Release terminates the host, because here Claim already produced a running
// one — from warm stock or a cold launch. Merely forgetting it would leave a
// box that bills compute and holds regional capacity with nothing tracking it,
diff --git a/internal/api/microvm_orphan_test.go b/internal/api/microvm_orphan_test.go
new file mode 100644
index 00000000..7273e99f
--- /dev/null
+++ b/internal/api/microvm_orphan_test.go
@@ -0,0 +1,159 @@
+package api
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ lambdamicrovms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms"
+ mvtypes "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+// sweepAPI serves a fixed inventory to the orphan sweep and records every
+// termination it attempts. Only the calls the sweep makes are implemented.
+type sweepAPI struct {
+ items []mvtypes.MicrovmItem
+ getImage map[string]string // id → ImageArn returned by GetMicrovm
+ getState map[string]mvtypes.MicrovmState
+ terminated []string
+ gets int
+}
+
+func (f *sweepAPI) ListMicrovms(context.Context, *lambdamicrovms.ListMicrovmsInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error) {
+ return &lambdamicrovms.ListMicrovmsOutput{Items: f.items}, nil
+}
+func (f *sweepAPI) GetMicrovm(_ context.Context, in *lambdamicrovms.GetMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.GetMicrovmOutput, error) {
+ f.gets++
+ id := aws.ToString(in.MicrovmIdentifier)
+ state := mvtypes.MicrovmStateRunning
+ if s, ok := f.getState[id]; ok {
+ state = s
+ }
+ return &lambdamicrovms.GetMicrovmOutput{
+ MicrovmId: aws.String(id),
+ ImageArn: aws.String(f.getImage[id]),
+ State: state,
+ }, nil
+}
+func (f *sweepAPI) TerminateMicrovm(_ context.Context, in *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {
+ f.terminated = append(f.terminated, aws.ToString(in.MicrovmIdentifier))
+ return &lambdamicrovms.TerminateMicrovmOutput{}, nil
+}
+func (f *sweepAPI) RunMicrovm(context.Context, *lambdamicrovms.RunMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.RunMicrovmOutput, error) {
+ panic("sweep must not launch")
+}
+func (f *sweepAPI) SuspendMicrovm(context.Context, *lambdamicrovms.SuspendMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.SuspendMicrovmOutput, error) {
+ panic("sweep must not suspend")
+}
+func (f *sweepAPI) ResumeMicrovm(context.Context, *lambdamicrovms.ResumeMicrovmInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ResumeMicrovmOutput, error) {
+ panic("sweep must not resume")
+}
+func (f *sweepAPI) CreateMicrovmAuthToken(context.Context, *lambdamicrovms.CreateMicrovmAuthTokenInput, ...func(*lambdamicrovms.Options)) (*lambdamicrovms.CreateMicrovmAuthTokenOutput, error) {
+ panic("sweep must not mint tokens")
+}
+
+func summary(id, image string, age time.Duration) mvtypes.MicrovmItem {
+ return mvtypes.MicrovmItem{
+ MicrovmId: aws.String(id),
+ ImageArn: aws.String(image),
+ State: mvtypes.MicrovmStateRunning,
+ StartedAt: aws.Time(time.Now().Add(-age)),
+ }
+}
+
+func sweepBackend(t *testing.T, f *sweepAPI) *microvmBackend {
+ t.Helper()
+ const ourImage = "arn:ours"
+ c := awsvm.NewClientWithAPI(f, awsvm.Config{ImageIdentifier: ourImage})
+ return &microvmBackend{
+ client: c,
+ pool: awsvm.NewPool(c, awsvm.PoolConfig{}),
+ manager: awsvm.NewManager(c, os.TempDir()),
+ }
+}
+
+// This AWS account is shared with other products. The image check is the only
+// thing standing between the sweep and someone else's fleet, so it must require
+// a POSITIVE match — an unknown image has to protect a box, not expose it.
+//
+// The original guard read `ImageArn != "" && ImageArn != ourImage`, which skipped
+// the comparison entirely when the field was empty. ListMicrovms returns a
+// reduced projection, so "empty" is a routine answer, not a rare one — that
+// version would have terminated every foreign box whose image it failed to read.
+func TestOrphanSweepNeverReapsWhatItCannotProveIsOurs(t *testing.T) {
+ t.Setenv("OPENSANDBOX_MICROVM_ORPHAN_REAP", "1")
+ old := 2 * orphanMinAge
+
+ f := &sweepAPI{
+ items: []mvtypes.MicrovmItem{
+ summary("microvm-ours", "arn:ours", old),
+ summary("microvm-theirs", "arn:someone-else", old),
+ summary("microvm-blank", "", old), // list omitted it; Get says foreign
+ summary("microvm-hidden", "", old), // list omitted it; Get says ours
+ },
+ getImage: map[string]string{
+ "microvm-blank": "arn:someone-else",
+ "microvm-hidden": "arn:ours",
+ },
+ }
+ b := sweepBackend(t, f)
+ b.sweepOrphans(context.Background())
+
+ got := map[string]bool{}
+ for _, id := range f.terminated {
+ got[id] = true
+ }
+ if !got["microvm-ours"] {
+ t.Error("did not reap microvm-ours — an abandoned box of ours keeps holding quota")
+ }
+ if !got["microvm-hidden"] {
+ t.Error("did not reap microvm-hidden — a Get proved it ours, so the list projection gap should not shield it")
+ }
+ if got["microvm-theirs"] {
+ t.Fatal("TERMINATED ANOTHER PRODUCT'S BOX (microvm-theirs) — foreign image was reaped")
+ }
+ if got["microvm-blank"] {
+ t.Fatal("TERMINATED ANOTHER PRODUCT'S BOX (microvm-blank) — empty list image fell through the guard")
+ }
+}
+
+// If the image cannot be established at all, nothing is eligible. A sweep that
+// reaps on ignorance is worse than one that reaps nothing.
+func TestOrphanSweepReapsNothingWhenOwnershipIsUnknowable(t *testing.T) {
+ t.Setenv("OPENSANDBOX_MICROVM_ORPHAN_REAP", "1")
+ old := 2 * orphanMinAge
+
+ f := &sweepAPI{
+ items: []mvtypes.MicrovmItem{
+ summary("microvm-a", "", old),
+ summary("microvm-b", "", old),
+ },
+ getImage: map[string]string{}, // Get returns "" too
+ }
+ b := sweepBackend(t, f)
+ b.sweepOrphans(context.Background())
+
+ if len(f.terminated) != 0 {
+ t.Fatalf("terminated %v with no provable ownership", f.terminated)
+ }
+}
+
+// Young boxes must be skipped before the image lookup, or a large foreign fleet
+// costs a GetMicrovm each on an account that already throttles ListMicrovms.
+func TestOrphanSweepDoesNotProbeYoungBoxes(t *testing.T) {
+ f := &sweepAPI{
+ items: []mvtypes.MicrovmItem{
+ summary("microvm-young", "", time.Minute),
+ },
+ }
+ b := sweepBackend(t, f)
+ b.sweepOrphans(context.Background())
+
+ if f.gets != 0 {
+ t.Fatalf("issued %d GetMicrovm call(s) for a box too young to reap", f.gets)
+ }
+}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 1eb03207..201a6b47 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -891,6 +891,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
},
persistRequired: backend.RequiresPersistedRow(),
+ deferPersist: backend.DefersPersist(),
persist: func(ctx context.Context, workerID string) error {
if s.store == nil || !hasOrg {
diff --git a/internal/api/worker_backend.go b/internal/api/worker_backend.go
index e1ed77d3..a7d3e448 100644
--- a/internal/api/worker_backend.go
+++ b/internal/api/worker_backend.go
@@ -223,6 +223,12 @@ func (w *workerBackend) dropPending(sandboxID string) {
// blip.
func (w *workerBackend) RequiresPersistedRow() bool { return false }
+// DefersPersist is false. The worker path resolves a sandbox by reading its
+// session row (worker_id, org, status) on the very next request, so answering
+// a create before that row exists would make the SDK's own follow-up call race
+// a write in flight.
+func (w *workerBackend) DefersPersist() bool { return false }
+
// Release forgets the selection. Nothing was started — Claim only picked a
// worker — so there is no host to reclaim, and the worker's own capacity
// accounting needs no correction.
diff --git a/internal/awsvm/agent.go b/internal/awsvm/agent.go
index 4996cad6..0ec00ff6 100644
--- a/internal/awsvm/agent.go
+++ b/internal/awsvm/agent.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"fmt"
+ "log"
"net"
"net/http"
"sync"
@@ -204,11 +205,30 @@ func newAgentPool() *agentPool {
func (p *agentPool) get(sandboxID, endpoint string, port int32, token tokenProvider) (*agentConn, error) {
p.mu.Lock()
if c, ok := p.conns[sandboxID]; ok {
+ // A cached channel is only useful if it is still usable. Serving one
+ // that has been shut down is a permanent, silent break: every exec on
+ // that sandbox returns "grpc: the client connection is closing" in
+ // milliseconds and nothing ever re-dials, because this map hit is what
+ // suppresses the dial. Shutdown is terminal in gRPC — it never
+ // reconnects — so drop it and fall through to a fresh dial. Any other
+ // state (Idle, Connecting, TransientFailure) does recover on its own
+ // and must be left alone, or a blip would churn channels under load.
+ if c.conn == nil || c.conn.GetState() == connectivity.Shutdown {
+ delete(p.conns, sandboxID)
+ p.mu.Unlock()
+ _ = c.Close()
+ } else {
+ p.mu.Unlock()
+ return c, nil
+ }
+ } else {
p.mu.Unlock()
- return c, nil
}
- p.mu.Unlock()
+ // Reaching here on a claimed box means the pre-dialled tunnel did not
+ // 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)
if err != nil {
return nil, err
@@ -251,6 +271,50 @@ func (p *agentPool) drop(sandboxID string) {
}
}
+// warm reconnects the channels of the given sandboxes if they have gone idle.
+// Returns how many needed it.
+//
+// Used for boxes reserved to the edge but not yet claimed by a customer: they
+// are warm stock, so keeping their tunnel established is the whole point, and
+// none of the idle-suspend reasoning that justifies PermitWithoutStream:false
+// applies to a box with no customer on it yet.
+//
+// Connect() rather than a probe RPC: it restores the transport without touching
+// the guest, so nothing that watches for sandbox activity can mistake it for
+// any.
+func (p *agentPool) warm(sandboxIDs map[string]struct{}) int {
+ p.mu.Lock()
+ conns := make([]*agentConn, 0, len(sandboxIDs))
+ for id := range sandboxIDs {
+ if c, ok := p.conns[id]; ok && c.conn != nil {
+ conns = append(conns, c)
+ }
+ }
+ p.mu.Unlock()
+
+ n := 0
+ for _, c := range conns {
+ switch c.conn.GetState() {
+ case connectivity.Ready, connectivity.Connecting, connectivity.Shutdown:
+ default: // Idle, TransientFailure
+ c.conn.Connect()
+ n++
+ }
+ }
+ return n
+}
+
+// detach removes a sandbox's channel WITHOUT closing it, handing ownership to
+// the caller. drop() is the closing variant; this exists for the one case where
+// the channel outlives the binding — an edge reservation returning to stock.
+func (p *agentPool) detach(sandboxID string) *agentConn {
+ p.mu.Lock()
+ c := p.conns[sandboxID]
+ delete(p.conns, sandboxID)
+ p.mu.Unlock()
+ return c
+}
+
func (p *agentPool) closeAll() {
p.mu.Lock()
conns := p.conns
diff --git a/internal/awsvm/client.go b/internal/awsvm/client.go
index e3608c59..07de8c97 100644
--- a/internal/awsvm/client.go
+++ b/internal/awsvm/client.go
@@ -22,6 +22,7 @@ package awsvm
import (
"context"
+ "errors"
"fmt"
"strings"
"sync"
@@ -320,11 +321,52 @@ func (c *Client) Terminate(ctx context.Context, id string) error {
// List enumerates this account's MicroVMs in the region. Used for reconciling
// our view against reality — the analogue of the QEMU orphan reaper, since a VM
// we lose track of keeps consuming quota.
+// listAttempts bounds retries on a single page of ListMicrovms.
+//
+// This call is throttled harder than the rest of the API on a busy account —
+// observed failing on most passes with "exceeded maximum number of attempts, 3",
+// the SDK's own default. The SDK gives up quickly and List is only ever called
+// by background reconciliation, where nobody is waiting, so it is worth being
+// considerably more patient than the default.
+//
+// It matters because List is the ONLY way the control plane sees a box that has
+// no database row. A List that gives up does not degrade gracefully — it makes
+// the orphan sweep a no-op, so leaked hosts bill and hold regional quota
+// indefinitely while the sweep logs a failure nobody reads.
+const listAttempts = 6
+
+// listBackoff is the first delay between page retries, doubling thereafter. A
+// var rather than a const so tests can exercise the full ladder without paying
+// for it in wall-clock.
+var listBackoff = 500 * time.Millisecond
+
+// listPage fetches one page, retrying throttles with exponential backoff.
+func (c *Client) listPage(ctx context.Context, next *string) (*lambdamicrovms.ListMicrovmsOutput, error) {
+ backoff := listBackoff
+ for attempt := 1; ; attempt++ {
+ out, err := c.api.ListMicrovms(ctx, &lambdamicrovms.ListMicrovmsInput{NextToken: next})
+ if err == nil {
+ return out, nil
+ }
+ // Only throttling is worth retrying: a permissions or validation failure
+ // answers the same way however long we wait.
+ if !errors.Is(classifyLaunchError(err), ErrThrottled) || attempt >= listAttempts {
+ return nil, err
+ }
+ select {
+ case <-time.After(backoff):
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ backoff *= 2
+ }
+}
+
func (c *Client) List(ctx context.Context) ([]Box, error) {
var boxes []Box
var next *string
for {
- out, err := c.api.ListMicrovms(ctx, &lambdamicrovms.ListMicrovmsInput{NextToken: next})
+ out, err := c.listPage(ctx, next)
if err != nil {
return nil, fmt.Errorf("awsvm: list microvms: %w", err)
}
diff --git a/internal/awsvm/client_test.go b/internal/awsvm/client_test.go
index 8b0721aa..d0ddd7d5 100644
--- a/internal/awsvm/client_test.go
+++ b/internal/awsvm/client_test.go
@@ -2,6 +2,7 @@ package awsvm
import (
"context"
+ "errors"
"testing"
"time"
@@ -187,3 +188,98 @@ func TestAgentURLNormalisesScheme(t *testing.T) {
}
}
}
+
+// shortenListBackoff collapses the retry ladder so a test can assert on attempt
+// counts without waiting out the production delays.
+func shortenListBackoff(t *testing.T) {
+ t.Helper()
+ prev := listBackoff
+ listBackoff = time.Millisecond
+ t.Cleanup(func() { listBackoff = prev })
+}
+
+// throttleAPI fails the first `failures` ListMicrovms calls with the error the
+// account actually returns under load, then succeeds.
+type throttleAPI struct {
+ fakeAPI
+ failures int
+ calls int
+ err error
+}
+
+func (f *throttleAPI) ListMicrovms(ctx context.Context, in *lambdamicrovms.ListMicrovmsInput, opts ...func(*lambdamicrovms.Options)) (*lambdamicrovms.ListMicrovmsOutput, error) {
+ f.calls++
+ if f.calls <= f.failures {
+ return nil, f.err
+ }
+ return f.fakeAPI.ListMicrovms(ctx, in, opts...)
+}
+
+// List is the only way the control plane sees a box with no database row, so a
+// List that gives up silently turns the orphan sweep into a no-op and leaked
+// hosts bill and hold regional quota forever. On a busy account this call is
+// throttled harder than the rest of the API — observed failing on most passes
+// with the SDK's own "exceeded maximum number of attempts, 3" — so it has to be
+// more patient than the SDK default.
+func TestListRetriesThrottledPages(t *testing.T) {
+ shortenListBackoff(t)
+ f := &throttleAPI{
+ failures: 3,
+ err: &types.ThrottlingException{},
+ }
+ f.listPages = [][]types.MicrovmItem{{{MicrovmId: aws.String("mvm-1")}}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+
+ boxes, err := c.List(context.Background())
+ if err != nil {
+ t.Fatalf("List gave up on a throttle the sweep depends on: %v", err)
+ }
+ if len(boxes) != 1 {
+ t.Fatalf("List returned %d boxes, want 1", len(boxes))
+ }
+ if f.calls != 4 {
+ t.Fatalf("made %d calls, want 4 (3 throttled + 1 success)", f.calls)
+ }
+}
+
+// Retrying a permissions or validation failure just delays the same answer.
+// Worse, it would hold the reconcile tick for the full backoff ladder every
+// pass, so the sweep runs less often precisely when it is already broken.
+func TestListDoesNotRetryNonThrottleErrors(t *testing.T) {
+ f := &throttleAPI{
+ failures: 99,
+ err: errors.New("AccessDeniedException: not authorized"),
+ }
+ f.listPages = [][]types.MicrovmItem{{}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+
+ if _, err := c.List(context.Background()); err == nil {
+ t.Fatal("List hid a non-throttle failure")
+ }
+ if f.calls != 1 {
+ t.Fatalf("made %d calls for a permanent error, want 1", f.calls)
+ }
+}
+
+// A throttle that never clears must still terminate, and must report the cause
+// rather than an empty inventory — an empty list would read as "no orphans".
+func TestListGivesUpAfterListAttempts(t *testing.T) {
+ shortenListBackoff(t)
+ f := &throttleAPI{
+ failures: 99,
+ err: &types.ThrottlingException{},
+ }
+ f.listPages = [][]types.MicrovmItem{{}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+
+ boxes, err := c.List(context.Background())
+ if err == nil {
+ t.Fatal("List reported success while permanently throttled — the sweep would read an empty inventory as 'no orphans'")
+ }
+ if boxes != nil {
+ t.Fatalf("List returned %d boxes alongside an error", len(boxes))
+ }
+ if f.calls != listAttempts {
+ t.Fatalf("made %d attempts, want listAttempts=%d", f.calls, listAttempts)
+ }
+}
diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.go
index 07475b97..6dd1780c 100644
--- a/internal/awsvm/manager.go
+++ b/internal/awsvm/manager.go
@@ -59,6 +59,10 @@ type Manager struct {
agents *agentPool
dataDir string
+ // term paces destroys against the TerminateMicrovm quota. See terminator.go
+ // for why a direct call on this path leaked a box on every throttle.
+ term *terminator
+
mu sync.RWMutex
byID map[string]*entry
}
@@ -75,6 +79,7 @@ func NewManager(client *Client, dataDir string) *Manager {
client: client,
agents: newAgentPool(),
dataDir: dataDir,
+ term: newTerminator(client),
byID: make(map[string]*entry),
}
}
@@ -87,8 +92,25 @@ func NewManager(client *Client, dataDir string) *Manager {
// than paying the ~1.4s dial. This is the claim path: still zero AWS calls.
func (m *Manager) TrackClaimed(sandboxID string, e *StockEntry, cfg types.SandboxConfig) {
m.Track(sandboxID, &Box{ID: e.MicrovmID, Endpoint: e.Endpoint}, cfg)
+ // Whether the warm tunnel actually reached the customer. This is the single
+ // biggest term in benchmark TTI — TTI measures the FIRST exec, and a cold
+ // dial costs ~330ms against an 82ms warm call — so it is worth one line.
+ log.Printf("awsvm: TrackClaimed %s (box %s) warm_tunnel=%v", sandboxID, e.MicrovmID, e.agent != nil)
if e.agent != nil {
m.agents.put(sandboxID, e.agent)
+ // TRANSFER OWNERSHIP. The pool and the manager would otherwise hold the
+ // same *agentConn, and Pool.terminate closes e.agent — so any pool-side
+ // path that retires this entry (expireReservations, aged-stock retire,
+ // overshoot shed) would close the tunnel of a box a customer is already
+ // using. The binding survives that, so the sandbox keeps routing and
+ // every exec fails instantly with "grpc: the client connection is
+ // closing" until the box is destroyed. Observed on dev: exec dead in
+ // ~5ms from localhost, no network involved.
+ //
+ // Clearing the pool's reference is the whole fix: the manager now owns
+ // the channel and closes it in agents.drop (destroy/Forget), and
+ // terminate's nil check makes the pool a no-op on an adopted entry.
+ e.agent = nil
}
}
@@ -215,6 +237,27 @@ func (m *Manager) TrackedMicrovmIDs() map[string]struct{} {
return ids
}
+// TrackedBindings returns every sandbox id this manager is routing, mapped to
+// the MicroVM behind it.
+//
+// TrackedMicrovmIDs answers "which boxes are spoken for", which is what the
+// orphan sweep needs. This answers the other direction — "which bindings do we
+// hold" — which is what a reconciler needs to find bindings whose sandbox no
+// longer exists. Those are invisible to any pass driven by the sessions table,
+// because such a pass can only visit sandboxes that still have a row.
+func (m *Manager) TrackedBindings() map[string]string {
+ if m == nil {
+ return nil
+ }
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ out := make(map[string]string, len(m.byID))
+ for id, e := range m.byID {
+ out[id] = e.microvmID
+ }
+ return out
+}
+
func (m *Manager) Get(ctx context.Context, id string) (*types.Sandbox, error) {
e, err := m.lookup(id)
if err != nil {
@@ -260,13 +303,22 @@ func (m *Manager) Kill(ctx context.Context, id string) error {
return nil // already gone; destroy is idempotent
}
m.agents.drop(id)
- if err := m.client.Terminate(ctx, e.microvmID); err != nil {
- return err
- }
+ // Forget the binding first, then hand the box to the paced queue. Order
+ // matters: the sandbox is gone from the caller's perspective the moment this
+ // returns, and leaving it routable while the terminate drains would let an
+ // exec land on a box already condemned.
m.mu.Lock()
delete(m.byID, id)
m.mu.Unlock()
- return nil
+
+ // A throttled terminate used to surface as a 500 AND leave the box running —
+ // a leak on the customer-facing delete path, which is where a share of the
+ // orphan population came from. Queued, it retries at the quota instead.
+ if m.term.enqueue(e.microvmID) {
+ return nil
+ }
+ // Queue full: better to pay the call inline than lose the box.
+ return m.client.Terminate(ctx, e.microvmID)
}
func (m *Manager) List(ctx context.Context) ([]types.Sandbox, error) {
@@ -314,6 +366,25 @@ func (m *Manager) IsSandboxAlive(ctx context.Context, id string) (bool, error) {
func (m *Manager) Close() { m.agents.closeAll() }
+// DetachAgent surrenders a sandbox's agent channel without closing it. Only the
+// edge-release path should use this: it is handing a still-good tunnel back to
+// the pool rather than throwing it away. Every other unbind wants Forget.
+func (m *Manager) DetachAgent(sandboxID string) *agentConn {
+ if m == nil {
+ return nil
+ }
+ return m.agents.detach(sandboxID)
+}
+
+// WarmAgents re-establishes idle agent channels for the given sandboxes. See
+// agentPool.warm — intended for edge reservations awaiting a customer.
+func (m *Manager) WarmAgents(sandboxIDs map[string]struct{}) int {
+ if m == nil || len(sandboxIDs) == 0 {
+ return 0
+ }
+ return m.agents.warm(sandboxIDs)
+}
+
// ── Execution ───────────────────────────────────────────────────────────────
func (m *Manager) Exec(ctx context.Context, sandboxID string, cfg types.ProcessConfig) (*types.ProcessResult, error) {
diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.go
index 87ae884d..00835433 100644
--- a/internal/awsvm/pool.go
+++ b/internal/awsvm/pool.go
@@ -6,6 +6,8 @@ import (
"log"
"sync"
"time"
+
+ "google.golang.org/grpc/connectivity"
)
// pool.go — a warm pool of RUNNING MicroVMs.
@@ -62,6 +64,75 @@ type PoolConfig struct {
// PreDialTimeout bounds establishing a stocked box's agent tunnel. Exceeding
// it costs only a cold first exec on that box, never the box itself.
PreDialTimeout time.Duration
+
+ // MaxTotalBoxes caps pool stock PLUS everything claimed out of it, against
+ // the regional memory quota. 0 disables the cap.
+ //
+ // TargetStock alone is not a safety property. It bounds what the pool holds,
+ // not what exists: a claimed box leaves the stock, the filler sees a hole and
+ // launches a replacement, so pool + live sandboxes grows without limit as
+ // load rises. That is exactly how a 200-box pool alongside 300 live sandboxes
+ // put this account over its 1024GB ceiling and turned every create into
+ // ServiceQuotaExceeded — the filler was chasing its target while blind to the
+ // boxes doing the actual work.
+ //
+ // With a budget set, the pool becomes something a burst can DRAIN rather than
+ // a floor it fights: claims consume stock, refill waits until those boxes are
+ // released, and the total never exceeds what the region will allow.
+ MaxTotalBoxes int
+
+ // InUse reports boxes alive outside the pool — claimed sandboxes still doing
+ // work. Supplied by the owner because the pool deliberately forgets a box the
+ // moment it is claimed; the manager is what tracks it afterwards.
+ //
+ // Nil means "nothing else exists", which is only true in tests.
+ InUse func() int
+
+ // RefillDelay is how long the filler stands down after finding itself at
+ // MaxTotalBoxes.
+ //
+ // Standing down matters because the budget check alone only skips a tick.
+ // At the ceiling that re-probes every LaunchInterval, so the instant any box
+ // is released the pool launches a replacement and is immediately at the
+ // ceiling again — it tracks the budget exactly, and every one of those
+ // launches is a RunMicrovm call competing with the customer creates that are
+ // cold precisely because the pool is empty. Measured on dev: 366 boxes
+ // manufactured in 30 minutes against 28 "regional MicroVM quota exhausted"
+ // creates, the pool and its own customers bidding for the same quota.
+ //
+ // A cooldown makes the pool yield instead. It re-probes once per delay, so
+ // releases accumulate into real headroom before the filler spends quota on
+ // them, and a burst's cold creates get the regional quota to themselves.
+ // Time-bounded rather than event-driven on purpose: a delay armed by every
+ // claim would be pushed forward indefinitely by sustained traffic and the
+ // pool would never refill at all.
+ RefillDelay time.Duration
+
+ // OnExpire is called after a stale edge reservation has been terminated.
+ //
+ // Reserving for the edge binds a sandbox id to the box BEFORE any customer
+ // claims it, so that routing and the warm tunnel resolve the instant the
+ // edge answers a create. When the reservation dies instead of being claimed,
+ // that binding has to die with it — otherwise the control plane keeps
+ // routing a live sandbox id to a terminated box, and every operation on it
+ // fails somewhere deep in the agent tunnel rather than with "not found".
+ //
+ // Called without the pool lock held, so implementations may take their own.
+ OnExpire func(microvmID string)
+
+ // OnMaintain runs on each maintenance tick, after the pool has warmed its
+ // own stock.
+ //
+ // It exists because the pool cannot warm the boxes that matter most. An
+ // edge reservation moves its agent channel to the manager (TrackClaimed) and
+ // leaves p.stock, so a box staged in a PoolStock shard — the exact box the
+ // next create will be handed — is invisible to warmTunnels. Those sit for
+ // minutes with no traffic, their tunnels lapse, and the cost lands on the
+ // customer's first exec, which is what TTI measures. Only the owner knows
+ // which sandbox ids are reserved-but-unclaimed, so it does that warming.
+ //
+ // Called without the pool lock held.
+ OnMaintain func()
}
func (c *PoolConfig) applyDefaults() {
@@ -92,6 +163,9 @@ func (c *PoolConfig) applyDefaults() {
if c.PreDialTimeout <= 0 {
c.PreDialTimeout = 30 * time.Second
}
+ if c.RefillDelay <= 0 {
+ c.RefillDelay = time.Minute
+ }
}
// StockEntry is one ready-to-claim box. Everything a caller needs to talk to it
@@ -113,6 +187,23 @@ type StockEntry struct {
launchedAt time.Time
}
+// reservation is a stocked box promised to the edge, with the moment it was
+// promised so the reaper can tell a claim that is in flight from one that is
+// never coming.
+type reservation struct {
+ entry *StockEntry
+ at time.Time
+}
+
+// reservationTTL bounds how long the edge may hold a box without binding it.
+// Short enough that a dead DO does not quietly shrink the pool, but it MUST
+// comfortably exceed the PoolStock DO's own ENTRY_TTL_MS (10 minutes), because
+// a reservation the DO still counts as stock is one it will happily hand to a
+// customer. Expiring first would mean the edge answering a create with a box
+// this pool had already terminated — a 201 for a sandbox that does not exist.
+// 15 minutes matches the QEMU edge_reserved reaper for the same reason.
+const reservationTTL = 15 * time.Minute
+
// Pool keeps TargetStock boxes launched, tokened and fresh.
type Pool struct {
client *Client
@@ -126,6 +217,19 @@ type Pool struct {
mu sync.Mutex
stock []*StockEntry
+ // budgetLoggedAt rate-limits the at-budget notice; see overBudget.
+ budgetLoggedAt time.Time
+ // reserved holds boxes promised to the edge's PoolStock DO but not yet
+ // bound to a sandbox. They stay HERE rather than moving to the DO because
+ // the pre-dialled tunnel is a live gRPC channel in this process — it cannot
+ // be serialized to a Durable Object. The DO holds only the identity; the
+ // control plane keeps the thing that makes a claim fast.
+ //
+ // A reservation is deliberately not a claim: nothing is bound, no sandbox
+ // id exists yet, and an unclaimed one returns to stock. That is what makes
+ // an edge that dies mid-create cost a box for one reaper interval instead
+ // of until the 8h cap.
+ reserved map[string]*reservation
// backoffUntil suppresses launches after the account hits its regional
// memory quota. Without it the ticker keeps firing doomed RunMicrovm calls
// — a 402 fails instantly, so inflight drops straight back and the next
@@ -166,6 +270,150 @@ func (p *Pool) Claim() (*StockEntry, bool) {
return nil, false
}
+// Reserve promises up to n boxes to the edge and returns them. The caller gets
+// identity only — MicrovmID, Endpoint, Token — which is all the DO needs to
+// hand a box to a customer; the tunnel stays here.
+//
+// Returns fewer than n (possibly none) when stock is short. That is not an
+// error: the edge falls back to asking the control plane, which is the same
+// path it uses when the DO is cold.
+func (p *Pool) Reserve(n int) []*StockEntry {
+ if n <= 0 {
+ return nil
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.reserved == nil {
+ p.reserved = make(map[string]*reservation)
+ }
+ now := time.Now()
+ out := make([]*StockEntry, 0, n)
+ for len(out) < n {
+ if len(p.stock) == 0 {
+ break
+ }
+ e := p.stock[len(p.stock)-1]
+ p.stock = p.stock[:len(p.stock)-1]
+ // Same age rule as Claim: never promise a box Lambda is about to
+ // terminate underneath the customer.
+ if time.Since(e.launchedAt) >= p.cfg.MaxBoxAge {
+ go p.terminate(e)
+ continue
+ }
+ p.reserved[e.MicrovmID] = &reservation{entry: e, at: now}
+ out = append(out, e)
+ }
+ return out
+}
+
+// ClaimReserved binds a previously reserved box, returning the full entry so the
+// caller can adopt its tunnel. Reports false if the reservation is unknown —
+// already claimed, expired back to stock, or never made — which the caller must
+// treat as a miss rather than a failure, because the edge can legitimately race
+// the reaper.
+func (p *Pool) ClaimReserved(microvmID string) (*StockEntry, bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ r, ok := p.reserved[microvmID]
+ if !ok {
+ return nil, false
+ }
+ delete(p.reserved, microvmID)
+ return r.entry, true
+}
+
+// ReleaseReserved returns an unclaimed reservation to stock — the edge deciding
+// it does not need the box after all. Cheaper than letting it expire, and the
+// box keeps its warm tunnel.
+func (p *Pool) ReleaseReserved(microvmID string) bool {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ r, ok := p.reserved[microvmID]
+ if !ok {
+ return false
+ }
+ delete(p.reserved, microvmID)
+ p.stock = append(p.stock, r.entry)
+ return true
+}
+
+// AttachAgent gives a stocked box back its agent channel.
+//
+// Pairs with Manager.DetachAgent on the release path. TrackClaimed transfers a
+// reservation's tunnel to the manager, so a reservation the edge hands back has
+// none — and re-dialling it costs the next customer ~470ms on their first exec
+// (measured: 549ms cold vs 76ms warm). Since the release path knows the channel
+// is still good and that no customer ever held it, moving it back is strictly
+// better than closing it and dialling again.
+//
+// warmTunnels re-dials anything that still ends up tunnel-less; this just keeps
+// the common case from needing it, because the 30s maintenance tick loses the
+// race when the DO releases a batch and immediately re-reserves it.
+func (p *Pool) AttachAgent(microvmID string, a *agentConn) {
+ if a == nil {
+ return
+ }
+ p.mu.Lock()
+ for _, e := range p.stock {
+ if e.MicrovmID == microvmID && e.agent == nil {
+ e.agent = a
+ p.mu.Unlock()
+ return
+ }
+ }
+ p.mu.Unlock()
+ // Left stock between the release and here — don't leak the channel.
+ _ = a.Close()
+}
+
+// expireReservations TERMINATES promises the edge never redeemed. It does not
+// return them to stock, and that distinction is a security boundary rather than
+// a cleanup preference.
+//
+// A reservation carries a pre-minted auth token, handed to the DO. When a
+// reservation goes stale we cannot tell "the DO died before handing this out"
+// from "the DO gave it to a customer and the finalize was lost" — and in the
+// second case the customer holds a live token for that box. Re-pooling it would
+// hand a second customer a box the first can still reach: cross-tenant access.
+// Burning a warm box is the cheap outcome; the other one is a breach.
+//
+// This mirrors the QEMU edge-claim reaper, which destroys stale edge_reserved
+// rows for exactly this reason (see edge_claim.go). ReleaseReserved is the safe
+// counterpart: there the edge is positively asserting it never handed the box
+// out, which is knowledge this path does not have.
+func (p *Pool) expireReservations() int {
+ p.mu.Lock()
+ stale := make([]*StockEntry, 0)
+ for id, r := range p.reserved {
+ if time.Since(r.at) < reservationTTL {
+ continue
+ }
+ delete(p.reserved, id)
+ stale = append(stale, r.entry)
+ }
+ p.mu.Unlock()
+
+ for _, e := range stale {
+ go p.terminate(e)
+ // Drop the sandbox binding the reserve made, so nothing keeps routing a
+ // live id to a box that no longer exists. Ordering does not matter — the
+ // box is doomed either way — but this must not run under p.mu, because
+ // the callback reaches back into the backend.
+ if p.cfg.OnExpire != nil {
+ p.cfg.OnExpire(e.MicrovmID)
+ }
+ }
+ return len(stale)
+}
+
+// ReservedDepth reports outstanding reservations, for telemetry and for the
+// sizing invariant.
+func (p *Pool) ReservedDepth() int {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return len(p.reserved)
+}
+
// Depth reports current stock, for telemetry and for the sizing invariant: the
// edge's shards must not target more stock in aggregate than the pool can hold,
// or shards starve while hoarding — the same failure that cost us 1045ms vs
@@ -203,6 +451,22 @@ func (p *Pool) Run(ctx context.Context) {
if p.launchSuppressed() {
continue
}
+ // Budget before target: when a burst has drained the pool into live
+ // sandboxes, the right move is to WAIT for them rather than launch
+ // replacements alongside them. Refilling here is what doubles the
+ // footprint and trips the regional quota.
+ if p.overBudget() {
+ // Stand down rather than re-probe at tick rate. Skipping the tick
+ // alone leaves the filler glued to the ceiling: it wakes every
+ // LaunchInterval, and the moment a single box is released it spends
+ // a RunMicrovm on a replacement and is at the ceiling again. Those
+ // launches contend for the same regional quota as the customer
+ // creates that went cold because the pool was drained, so the pool
+ // competes with the burst it exists to absorb. Backing off lets
+ // releases pool up into real headroom first.
+ p.standDown(p.cfg.RefillDelay)
+ continue
+ }
if p.committed() < p.cfg.TargetStock {
go func() {
if err := p.launchOne(ctx); err != nil {
@@ -222,6 +486,13 @@ func (p *Pool) Run(ctx context.Context) {
case <-maintain.C:
p.refreshTokens(ctx)
p.retireAged(ctx)
+ p.warmTunnels(ctx)
+ if p.cfg.OnMaintain != nil {
+ p.cfg.OnMaintain()
+ }
+ if n := p.expireReservations(); n > 0 {
+ log.Printf("awsvm: pool re-pooled %d unclaimed edge reservation(s)", n)
+ }
}
}
}
@@ -241,6 +512,22 @@ func (p *Pool) launchSuppressed() bool {
return time.Now().Before(p.backoffUntil)
}
+// standDown pauses launches for d without logging, for callers that have
+// already said why. Never shortens an existing pause: a quota backoff and a
+// budget backoff can be armed in the same window, and the longer one is the one
+// that reflects a condition we know has not cleared.
+func (p *Pool) standDown(d time.Duration) {
+ if d <= 0 {
+ return
+ }
+ until := time.Now().Add(d)
+ p.mu.Lock()
+ if until.After(p.backoffUntil) {
+ p.backoffUntil = until
+ }
+ p.mu.Unlock()
+}
+
// suppressLaunches stands the launch loop down for d. Logged once per cooldown
// rather than once per attempt: the old behaviour buried every other log line
// on the cell under identical quota errors.
@@ -259,10 +546,48 @@ func (p *Pool) suppressLaunches(d time.Duration, cause error) {
// committed is stock plus launches still in flight — what the pool will have
// once everything settles, and therefore the right number to compare against
// the target when deciding whether to launch more.
+// overBudget reports whether pool stock plus everything claimed out of it has
+// reached MaxTotalBoxes, in which case the filler must stand down.
+//
+// Logged at most once per cooldown rather than per tick: hitting the budget is a
+// normal steady state during a burst, not an incident, and a line every
+// LaunchInterval would bury the log in it.
+func (p *Pool) overBudget() bool {
+ if p.cfg.MaxTotalBoxes <= 0 {
+ return false
+ }
+ inUse := 0
+ if p.cfg.InUse != nil {
+ inUse = p.cfg.InUse()
+ }
+ total := p.committed() + inUse
+ if total < p.cfg.MaxTotalBoxes {
+ return false
+ }
+ // Gate on the refill delay rather than a fixed minute so the notice tracks
+ // however long the filler is actually standing down, and at 9/10 of it so a
+ // once-per-delay caller cannot alias against the window and go silent.
+ p.mu.Lock()
+ quiet := time.Since(p.budgetLoggedAt) < p.cfg.RefillDelay*9/10
+ if !quiet {
+ p.budgetLoggedAt = time.Now()
+ }
+ p.mu.Unlock()
+ if !quiet {
+ log.Printf("awsvm: pool at box budget (%d in use + %d committed >= %d) — refill paused %s to leave regional quota for creates",
+ inUse, p.committed(), p.cfg.MaxTotalBoxes, p.cfg.RefillDelay)
+ }
+ return true
+}
+
func (p *Pool) committed() int {
p.mu.Lock()
defer p.mu.Unlock()
- return len(p.stock) + p.inflight
+ // Reservations count: they are boxes we own and will hand out. Omitting
+ // them would make the filler see a hole that isn't there and launch
+ // replacements for boxes already promised, overshooting the target by
+ // however many creates the edge has in flight.
+ return len(p.stock) + p.inflight + len(p.reserved)
}
func (p *Pool) launchOne(ctx context.Context) error {
@@ -397,6 +722,99 @@ func (p *Pool) retireAged(ctx context.Context) {
}
}
+// warmTunnels keeps every stocked box's agent channel in READY, so the first
+// exec after a claim does not pay to re-establish it.
+//
+// Pre-dialling at manufacture is not enough on its own. dialAgent sets
+// PermitWithoutStream:false — deliberately, so an idle CUSTOMER sandbox is
+// allowed to suspend instead of being held RUNNING by keepalive pings — which
+// means a box waiting in stock sends no traffic at all and the proxy drops its
+// WebSocket tunnel. gRPC keeps the ClientConn, so nothing looks broken and no
+// re-dial is logged; the cost simply lands on the customer's first RPC as a
+// silent tunnel re-handshake. Measured on dev: first exec 383ms vs 75ms warm,
+// and TTI is defined by exactly that first call.
+//
+// Reconnecting is done with conn.Connect() rather than a probe RPC: it restores
+// the transport without touching the guest, so this cannot be mistaken for
+// sandbox activity by anything that watches for it. Only stock is warmed —
+// claimed boxes keep the existing idle-and-suspend behaviour untouched.
+func (p *Pool) warmTunnels(ctx context.Context) {
+ p.mu.Lock()
+ conns := make([]*agentConn, 0, len(p.stock))
+ var missing []*StockEntry
+ for _, e := range p.stock {
+ if e.agent != nil {
+ conns = append(conns, e.agent)
+ continue
+ }
+ // No tunnel at all. The common cause is a round trip through the edge:
+ // TrackClaimed transfers ownership of the channel to the manager (and
+ // clears this field, so the pool can never close a live customer's
+ // tunnel), then EdgeRelease hands the unused reservation back to stock —
+ // and what returns has no tunnel and no way to get one. Measured on dev:
+ // ~130 boxes released across 8 batches produced 134 reserves with
+ // warm_tunnel=false against 136 with it, i.e. half of all creates were
+ // paying a cold dial on their first exec.
+ //
+ // Re-dialling here rather than in ReleaseReserved is deliberate: stock
+ // with no tunnel is wrong however it got that way, so healing it in the
+ // maintenance tick covers every cause, including ones we have not found.
+ if len(missing) < warmDialPerTick {
+ missing = append(missing, e)
+ }
+ }
+ p.mu.Unlock()
+
+ if p.preDial != nil {
+ 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 {
+ continue // still usable cold; try again next tick
+ }
+ // 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.
+ p.mu.Lock()
+ stillStocked := false
+ for _, s := range p.stock {
+ if s == e && s.agent == nil {
+ s.agent = a
+ stillStocked = true
+ break
+ }
+ }
+ p.mu.Unlock()
+ if !stillStocked {
+ _ = a.Close()
+ }
+ }
+ if len(missing) > 0 {
+ log.Printf("awsvm: pool re-dialled tunnels for %d tunnel-less stocked box(es)", len(missing))
+ }
+ }
+
+ rewarmed := 0
+ for _, a := range conns {
+ if a.conn == nil {
+ continue
+ }
+ switch a.conn.GetState() {
+ case connectivity.Ready, connectivity.Connecting:
+ // Already warm, or already on its way.
+ case connectivity.Shutdown:
+ // Terminal — the entry is dead stock; retireAged/terminate owns it.
+ default: // Idle, TransientFailure
+ a.conn.Connect()
+ rewarmed++
+ }
+ }
+ if rewarmed > 0 {
+ log.Printf("awsvm: pool re-warmed %d idle agent tunnel(s) of %d stocked", rewarmed, len(conns))
+ }
+}
+
func (p *Pool) terminate(e *StockEntry) {
// Close the pre-dialled tunnel too, or retiring stock leaks a goroutine and
// a socket per box.
@@ -410,6 +828,12 @@ func (p *Pool) terminate(e *StockEntry) {
// leaves room for the reconciler and customer destroys, which draw on the same
// bucket. Without pacing, draining a full pool fires every terminate at once
// and most of them come back throttled.
+// warmDialPerTick bounds how many tunnel-less stock boxes are re-dialled per
+// maintenance tick. Each dial is a real WebSocket+TLS handshake to the proxy, so
+// healing a fully cold pool all at once would burst hundreds of them; spreading
+// the work costs a few ticks and keeps the pool's own traffic predictable.
+const warmDialPerTick = 32
+
const terminateInterval = 125 * time.Millisecond
// terminateAttempts bounds retries of a throttled terminate. Giving up leaks
@@ -448,10 +872,17 @@ func (p *Pool) terminateID(id string) {
func (p *Pool) StockIDs() map[string]struct{} {
p.mu.Lock()
defer p.mu.Unlock()
- ids := make(map[string]struct{}, len(p.stock))
+ ids := make(map[string]struct{}, len(p.stock)+len(p.reserved))
for _, e := range p.stock {
ids[e.MicrovmID] = struct{}{}
}
+ // Reserved boxes are owned, just spoken for. Leaving them out would make
+ // the orphan sweep classify every in-flight edge claim as abandoned and
+ // terminate boxes out from under customers mid-create — the worst possible
+ // bug in this file.
+ for id := range p.reserved {
+ ids[id] = struct{}{}
+ }
return ids
}
@@ -462,6 +893,13 @@ func (p *Pool) Drain() {
p.mu.Lock()
stock := p.stock
p.stock = nil
+ // Reserved boxes are ours too. A shutdown that drained only stock would
+ // abandon every outstanding reservation to the 8h cap — the same leak this
+ // function exists to prevent, just through a different door.
+ for id, r := range p.reserved {
+ stock = append(stock, r.entry)
+ delete(p.reserved, id)
+ }
p.mu.Unlock()
// Paced, not a fan-out. Firing every terminate at once against a 10/s quota
diff --git a/internal/awsvm/pool_test.go b/internal/awsvm/pool_test.go
index 732e90da..59b812b7 100644
--- a/internal/awsvm/pool_test.go
+++ b/internal/awsvm/pool_test.go
@@ -2,8 +2,10 @@ package awsvm
import (
"context"
+ "errors"
"fmt"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -339,3 +341,300 @@ func TestStockIDsReportsEveryParkedBox(t *testing.T) {
}
}
}
+
+// A reservation is owned stock, not free stock. Every accounting path has to
+// agree on that, and each of these assertions corresponds to a distinct way the
+// pool could quietly destroy itself.
+func TestReservationsHoldTheirInvariants(t *testing.T) {
+ p, f := testPool(t, PoolConfig{TargetStock: 4})
+ for i := 0; i < 4; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+
+ got := p.Reserve(3)
+ if len(got) != 3 {
+ t.Fatalf("Reserve(3) returned %d", len(got))
+ }
+ if p.Depth() != 1 {
+ t.Fatalf("stock after reserving 3 of 4 = %d, want 1", p.Depth())
+ }
+ // committed must still see all four, or the filler launches replacements
+ // for boxes that were merely promised.
+ if c := p.committed(); c != 4 {
+ t.Fatalf("committed = %d, want 4 (reservations are owned)", c)
+ }
+ // The orphan sweep keys off StockIDs. A reserved box missing here would be
+ // terminated mid-create.
+ ids := p.StockIDs()
+ if len(ids) != 4 {
+ t.Fatalf("StockIDs = %d, want 4 (stock + reserved)", len(ids))
+ }
+ for _, e := range got {
+ if _, ok := ids[e.MicrovmID]; !ok {
+ t.Fatalf("reserved box %s absent from StockIDs — the sweep would reap it", e.MicrovmID)
+ }
+ }
+
+ // Claim binds exactly one, and only once.
+ e0 := got[0]
+ if _, ok := p.ClaimReserved(e0.MicrovmID); !ok {
+ t.Fatal("ClaimReserved missed a live reservation")
+ }
+ if _, ok := p.ClaimReserved(e0.MicrovmID); ok {
+ t.Fatal("ClaimReserved returned the same reservation twice")
+ }
+
+ // Release puts one back as usable stock.
+ if !p.ReleaseReserved(got[1].MicrovmID) {
+ t.Fatal("ReleaseReserved missed a live reservation")
+ }
+ if p.Depth() != 2 {
+ t.Fatalf("stock after release = %d, want 2", p.Depth())
+ }
+
+ // A stale reservation is DESTROYED, never returned to stock: its token may
+ // already be in a customer's hands, and re-issuing the box would be
+ // cross-tenant access. Burning a warm box is the cheap failure.
+ stockBefore := p.Depth()
+ p.mu.Lock()
+ for _, r := range p.reserved {
+ r.at = time.Now().Add(-2 * reservationTTL)
+ }
+ p.mu.Unlock()
+ if n := p.expireReservations(); n != 1 {
+ t.Fatalf("expireReservations retired %d, want 1", n)
+ }
+ if p.ReservedDepth() != 0 {
+ t.Fatalf("reservations outstanding after expiry: %d", p.ReservedDepth())
+ }
+ if p.Depth() != stockBefore {
+ t.Fatalf("stock grew from %d to %d — an expired reservation was re-pooled, which can hand a live token to a second tenant",
+ stockBefore, p.Depth())
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if _, _, terms := f.counts(); terms >= 1 {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if _, _, terms := f.counts(); terms < 1 {
+ t.Fatal("expired reservation was neither re-pooled nor terminated — it leaks quota")
+ }
+}
+
+// A reservation binds a sandbox id to a box before any customer claims it, so
+// the control plane can route that id the instant the edge answers a create.
+// When the reservation dies instead, the binding has to die with it — otherwise
+// a live sandbox id keeps resolving to a terminated box and every operation on
+// it fails deep in the agent tunnel instead of cleanly.
+func TestExpiringReservationNotifiesTheOwner(t *testing.T) {
+ var mu sync.Mutex
+ var forgot []string
+ p, _ := testPool(t, PoolConfig{
+ TargetStock: 2,
+ OnExpire: func(microvmID string) {
+ mu.Lock()
+ defer mu.Unlock()
+ forgot = append(forgot, microvmID)
+ },
+ })
+ for i := 0; i < 2; i++ {
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ got := p.Reserve(2)
+ if len(got) != 2 {
+ t.Fatalf("Reserve(2) returned %d", len(got))
+ }
+
+ p.mu.Lock()
+ for _, r := range p.reserved {
+ r.at = time.Now().Add(-2 * reservationTTL)
+ }
+ p.mu.Unlock()
+ if n := p.expireReservations(); n != 2 {
+ t.Fatalf("expireReservations retired %d, want 2", n)
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(forgot) != 2 {
+ t.Fatalf("OnExpire fired %d time(s), want 2 — a binding survived its box", len(forgot))
+ }
+ for _, e := range got {
+ found := false
+ for _, id := range forgot {
+ if id == e.MicrovmID {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("OnExpire never reported %s — its sandbox id still routes to a dead box", e.MicrovmID)
+ }
+ }
+}
+
+// The edge's PoolStock DO holds reserved boxes in its own stock for up to
+// ENTRY_TTL_MS (10 minutes, cloudflare-workers/api-edge/src/pool_stock.ts)
+// before releasing them. If this pool expired a reservation first it would
+// terminate a box the DO still believes it owns, and the next create to pop that
+// entry would get a 201 for a sandbox that does not exist.
+//
+// This is a real bug that shipped in the first cut of the reservation layer,
+// where the TTL was 2 minutes. The margin belongs to us, so pin it.
+func TestReservationTTLOutlivesTheEdgeStockTTL(t *testing.T) {
+ const doEntryTTL = 10 * time.Minute
+ if reservationTTL <= doEntryTTL {
+ t.Fatalf("reservationTTL=%s does not exceed the DO's stock TTL (%s) — the edge would hand out terminated boxes",
+ reservationTTL, doEntryTTL)
+ }
+}
+
+// TargetStock bounds what the pool HOLDS, not what exists. A claimed box leaves
+// the stock, so a target-only filler launches a replacement alongside every box
+// doing real work — pool + live sandboxes grows without limit as load rises.
+// That is how a 200-box pool alongside 300 live sandboxes put this account past
+// its 1024GB regional ceiling and turned every create into ServiceQuotaExceeded.
+//
+// With a budget the pool becomes drainable: claims consume stock and refill
+// waits for those boxes to be released.
+func TestPoolStopsRefillingAtTheBoxBudget(t *testing.T) {
+ inUse := 0
+ p, f := testPool(t, PoolConfig{
+ TargetStock: 10,
+ MaxTotalBoxes: 12,
+ InUse: func() int { return inUse },
+ })
+
+ // Nothing claimed: the pool fills to its target as usual.
+ for i := 0; i < 10; i++ {
+ if p.overBudget() {
+ t.Fatalf("refused to fill at stock=%d with nothing claimed", p.Depth())
+ }
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ if p.Depth() != 10 {
+ t.Fatalf("stock = %d, want 10", p.Depth())
+ }
+
+ // A burst claims eight. Stock drops to 2, and a target-only filler would
+ // launch eight replacements — 10 stock + 8 claimed = 18 boxes, half again
+ // over the budget of 12.
+ for i := 0; i < 8; i++ {
+ if _, ok := p.Claim(); !ok {
+ t.Fatalf("claim %d missed", i)
+ }
+ inUse++
+ }
+ if p.Depth() != 2 {
+ t.Fatalf("stock after 8 claims = %d, want 2", p.Depth())
+ }
+
+ // Refill is allowed up to the budget, not up to the target: 8 claimed + 2
+ // stock = 10, so exactly 2 more boxes may be launched.
+ for i := 0; i < 2; i++ {
+ if p.overBudget() {
+ t.Fatalf("stopped refilling at %d claimed + %d committed, under the budget of 12", inUse, p.committed())
+ }
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne: %v", err)
+ }
+ }
+ // Now at the ceiling. This is the assertion that matters: the pool is 6 short
+ // of its target and must still refuse, because the missing boxes are alive as
+ // customer sandboxes rather than gone.
+ if total := p.committed() + inUse; total != 12 {
+ t.Fatalf("total = %d, want 12", total)
+ }
+ if !p.overBudget() {
+ t.Fatalf("pool kept refilling at the budget: %d claimed + %d committed, target %d — this is the overrun that exhausted the region",
+ inUse, p.committed(), 10)
+ }
+
+ // As the burst drains, refill resumes.
+ inUse = 5
+ if p.overBudget() {
+ t.Fatalf("still refusing to refill at %d claimed + %d committed, under the budget of 12", inUse, p.committed())
+ }
+ if err := p.launchOne(context.Background()); err != nil {
+ t.Fatalf("launchOne after release: %v", err)
+ }
+ if f.runs == 0 {
+ t.Fatal("no launches recorded")
+ }
+}
+
+// A pool with no budget configured must behave exactly as before — cells that
+// nobody has sized should not silently stop filling.
+func TestPoolWithoutBudgetAlwaysRefills(t *testing.T) {
+ p, _ := testPool(t, PoolConfig{TargetStock: 3})
+ if p.overBudget() {
+ t.Fatal("unbudgeted pool refused to refill")
+ }
+}
+
+// Refusing to launch at the budget is not the same as standing down. Before the
+// backoff, the filler re-evaluated the budget every LaunchInterval, so the
+// instant any box was released it spent a RunMicrovm on a replacement and was at
+// the ceiling again — tracking the budget exactly, and bidding for the same
+// regional quota as the customer creates that had gone cold because the pool was
+// drained. Measured on dev: 366 boxes manufactured in 30 minutes alongside 28
+// creates rejected with "regional MicroVM quota exhausted".
+//
+// The observable difference is how often the loop asks. This counts that.
+func TestAtBudgetTheFillerStandsDownInsteadOfProbingEveryTick(t *testing.T) {
+ var probes int64
+ const (
+ interval = time.Millisecond
+ delay = 150 * time.Millisecond
+ window = 750 * time.Millisecond
+ )
+ p, f := testPool(t, PoolConfig{
+ TargetStock: 50,
+ MaxTotalBoxes: 10,
+ LaunchInterval: interval,
+ RefillDelay: delay,
+ // Pinned at the ceiling for the whole window: the burst has not drained.
+ InUse: func() int { atomic.AddInt64(&probes, 1); return 10 },
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ go p.Run(ctx)
+ time.Sleep(window)
+ cancel()
+
+ got := atomic.LoadInt64(&probes)
+ // One probe per delay, so ~5 across the window. Without the backoff the loop
+ // evaluates the budget once per LaunchInterval — ~750, two orders of
+ // magnitude more, every one of them a candidate launch.
+ if max := int64(window/delay) + 3; got > max {
+ t.Fatalf("budget evaluated %d times in %s, want at most %d — the filler is still spinning at tick rate, which is what makes it race customer creates for the regional quota",
+ got, window, max)
+ }
+ if got == 0 {
+ t.Fatal("budget never evaluated — the filler stood down permanently and would not refill when the burst drains")
+ }
+ if runs, _, _ := f.counts(); runs != 0 {
+ t.Fatalf("launched %d box(es) while at the budget", runs)
+ }
+}
+
+// The stand-down must never shorten an existing pause. A budget backoff landing
+// during a quota backoff would otherwise let the pool resume launching straight
+// into a quota that has not recovered.
+func TestStandDownNeverShortensAnExistingPause(t *testing.T) {
+ p, _ := testPool(t, PoolConfig{TargetStock: 1})
+
+ p.suppressLaunches(time.Hour, errors.New("regional quota exhausted"))
+ p.standDown(time.Millisecond)
+
+ if !p.launchSuppressed() {
+ t.Fatal("a short budget backoff cancelled a long quota backoff — the pool would relaunch into an exhausted quota")
+ }
+}
diff --git a/internal/awsvm/terminator.go b/internal/awsvm/terminator.go
new file mode 100644
index 00000000..36c339dd
--- /dev/null
+++ b/internal/awsvm/terminator.go
@@ -0,0 +1,172 @@
+package awsvm
+
+import (
+ "context"
+ "errors"
+ "log"
+ "sync"
+ "time"
+)
+
+// terminator.go — a paced, retrying queue for TerminateMicrovm.
+//
+// TerminateMicrovm is quota'd at 10/s. Every caller that destroyed a box by
+// calling the API directly was therefore one burst away from failure, and the
+// failure mode is the worst one available: a throttled terminate returns an
+// error to the customer AND leaves the box running, so it bills and holds
+// regional memory quota until the 8h service cap. Measured on dev — a delete of
+// 112 sandboxes returned 11 × HTTP 500, each one a leaked box.
+//
+// That is also where a share of the "orphans" came from. The orphan sweep exists
+// to catch boxes nothing owns, but it is a backstop with a 20-minute floor and a
+// 25-per-pass cap; manufacturing orphans on every bulk delete and relying on the
+// sweep to mop up is not a design, it is a leak with a janitor.
+//
+// So destroys are enqueued rather than called. The queue drains at the quota,
+// retries throttles with backoff, and the caller returns as soon as the intent
+// is recorded — which is honest, because AWS terminate is asynchronous anyway:
+// the API acknowledges long before the box is actually gone.
+//
+// What this deliberately does NOT do is guarantee delivery across a process
+// restart. A queued terminate lost to a crash becomes an orphan, and the sweep
+// reclaims it — that is the layering: the queue makes leaks rare, the sweep makes
+// them recoverable.
+
+// terminateQueueDepth bounds the backlog. Sized well above any plausible burst
+// (a benchmark destroying 100 sandboxes at once is 100 entries) so enqueue never
+// blocks the caller in practice; if it ever fills, falling back to a synchronous
+// terminate is better than dropping the box on the floor.
+const terminateQueueDepth = 4096
+
+// terminatePace is the interval between terminate calls. The quota is 10/s;
+// 120ms leaves headroom for the pool's own retirement traffic, which shares it.
+const terminatePace = 120 * time.Millisecond
+
+// terminateRetries bounds attempts per box. Combined with the doubling backoff
+// this spans well over a minute, which is far longer than any throttle episode
+// observed on this account.
+const terminateRetries = 6
+
+// terminator serializes destroys onto one paced worker.
+type terminator struct {
+ client *Client
+ queue chan string
+
+ start sync.Once
+ stop chan struct{}
+
+ mu sync.Mutex
+ inflight map[string]struct{} // dedupes repeat destroys of the same box
+}
+
+func newTerminator(client *Client) *terminator {
+ return &terminator{
+ client: client,
+ queue: make(chan string, terminateQueueDepth),
+ stop: make(chan struct{}),
+ inflight: make(map[string]struct{}),
+ }
+}
+
+// enqueue schedules a box for termination. Returns false if the queue is full,
+// which tells the caller to terminate synchronously rather than lose the box.
+//
+// Duplicate ids are dropped: destroy is idempotent, and a customer double-click
+// should not consume two slots of a rate-limited quota.
+func (t *terminator) enqueue(microvmID string) bool {
+ if t == nil || microvmID == "" {
+ return false
+ }
+ t.start.Do(func() { go t.run() })
+
+ t.mu.Lock()
+ if _, dup := t.inflight[microvmID]; dup {
+ t.mu.Unlock()
+ return true
+ }
+ t.inflight[microvmID] = struct{}{}
+ t.mu.Unlock()
+
+ select {
+ case t.queue <- microvmID:
+ return true
+ default:
+ t.mu.Lock()
+ delete(t.inflight, microvmID)
+ t.mu.Unlock()
+ log.Printf("awsvm: terminate queue full (%d) — falling back to a direct call for %s", terminateQueueDepth, microvmID)
+ return false
+ }
+}
+
+// depth reports the current backlog, for telemetry and tests.
+func (t *terminator) depth() int {
+ if t == nil {
+ return 0
+ }
+ return len(t.queue)
+}
+
+func (t *terminator) run() {
+ tick := time.NewTicker(terminatePace)
+ defer tick.Stop()
+ for {
+ select {
+ case <-t.stop:
+ return
+ case id := <-t.queue:
+ t.terminateWithRetry(id)
+ // Pace AFTER the call, so a burst cannot arrive faster than the
+ // quota even when every terminate succeeds immediately.
+ select {
+ case <-tick.C:
+ case <-t.stop:
+ return
+ }
+ }
+ }
+}
+
+func (t *terminator) terminateWithRetry(microvmID string) {
+ defer func() {
+ t.mu.Lock()
+ delete(t.inflight, microvmID)
+ t.mu.Unlock()
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+
+ backoff := 250 * time.Millisecond
+ for attempt := 1; ; attempt++ {
+ err := t.client.Terminate(ctx, microvmID)
+ if err == nil {
+ return
+ }
+ // Only throttling is worth retrying: a box already gone, or one we are
+ // not allowed to touch, answers identically however long we wait.
+ if !errors.Is(err, ErrThrottled) || attempt >= terminateRetries {
+ log.Printf("awsvm: terminate %s failed after %d attempt(s): %v — the orphan sweep is the backstop",
+ microvmID, attempt, err)
+ return
+ }
+ select {
+ case <-time.After(backoff):
+ case <-ctx.Done():
+ log.Printf("awsvm: terminate %s abandoned after %d attempt(s) — box holds quota until the age cap", microvmID, attempt)
+ return
+ }
+ backoff *= 2
+ }
+}
+
+func (t *terminator) close() {
+ if t == nil {
+ return
+ }
+ select {
+ case <-t.stop:
+ default:
+ close(t.stop)
+ }
+}
diff --git a/internal/awsvm/terminator_test.go b/internal/awsvm/terminator_test.go
new file mode 100644
index 00000000..5fb210ad
--- /dev/null
+++ b/internal/awsvm/terminator_test.go
@@ -0,0 +1,173 @@
+package awsvm
+
+import (
+ "context"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ lambdamicrovms "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"
+)
+
+// termAPI records terminate calls and can fail the first N of them the way a
+// throttled account does.
+type termAPI struct {
+ fakeAPI
+ mu sync.Mutex
+ calls []string
+ failFor map[string]int // id → remaining throttles to serve
+ seenOnce map[string]int // id → total attempts
+}
+
+func (f *termAPI) TerminateMicrovm(_ context.Context, in *lambdamicrovms.TerminateMicrovmInput, _ ...func(*lambdamicrovms.Options)) (*lambdamicrovms.TerminateMicrovmOutput, error) {
+ id := aws.ToString(in.MicrovmIdentifier)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.seenOnce == nil {
+ f.seenOnce = map[string]int{}
+ }
+ f.seenOnce[id]++
+ if n := f.failFor[id]; n > 0 {
+ f.failFor[id] = n - 1
+ return nil, &mvtypes.ThrottlingException{}
+ }
+ f.calls = append(f.calls, id)
+ return &lambdamicrovms.TerminateMicrovmOutput{}, nil
+}
+
+func (f *termAPI) done() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.calls...)
+}
+
+func waitFor(t *testing.T, d time.Duration, cond func() bool) bool {
+ t.Helper()
+ deadline := time.Now().Add(d)
+ for time.Now().Before(deadline) {
+ if cond() {
+ return true
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ return cond()
+}
+
+// A throttled terminate used to return an error to the customer AND leave the
+// box running — it bills and holds regional quota until the 8h cap. Deleting 112
+// sandboxes on dev produced 11 such leaks. The queue must retry until the box is
+// actually gone.
+func TestTerminateQueueRetriesThrottledDestroys(t *testing.T) {
+ f := &termAPI{failFor: map[string]int{"mvm-1": 3}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ term := newTerminator(c)
+ defer term.close()
+
+ if !term.enqueue("mvm-1") {
+ t.Fatal("enqueue refused")
+ }
+ if !waitFor(t, 10*time.Second, func() bool { return len(f.done()) == 1 }) {
+ t.Fatalf("box never terminated through %d throttles — this is the leak", 3)
+ }
+ if got := f.seenOnce["mvm-1"]; got != 4 {
+ t.Fatalf("attempts = %d, want 4 (3 throttled + 1 success)", got)
+ }
+}
+
+// Destroy is idempotent, and a rate-limited quota must not be spent twice on the
+// same box because a client retried or double-clicked.
+func TestTerminateQueueDedupesInFlight(t *testing.T) {
+ f := &termAPI{failFor: map[string]int{}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ term := newTerminator(c)
+ defer term.close()
+
+ for i := 0; i < 5; i++ {
+ term.enqueue("mvm-dup")
+ }
+ if !waitFor(t, 5*time.Second, func() bool { return len(f.done()) >= 1 }) {
+ t.Fatal("never terminated")
+ }
+ time.Sleep(300 * time.Millisecond)
+ if n := len(f.done()); n != 1 {
+ t.Fatalf("terminated the same box %d times — duplicate destroys burn a 10/s quota", n)
+ }
+}
+
+// The whole point is pacing: a bulk delete must not fire every terminate at once
+// against a 10/s quota, which is what produced the throttles in the first place.
+func TestTerminateQueuePacesBulkDestroys(t *testing.T) {
+ f := &termAPI{failFor: map[string]int{}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ term := newTerminator(c)
+ defer term.close()
+
+ const n = 8
+ start := time.Now()
+ for i := 0; i < n; i++ {
+ term.enqueue(string(rune('a'+i)) + "-box")
+ }
+ if !waitFor(t, 15*time.Second, func() bool { return len(f.done()) == n }) {
+ t.Fatalf("only %d of %d terminated", len(f.done()), n)
+ }
+ // n calls at terminatePace apart take at least (n-1) intervals.
+ min := time.Duration(n-1) * terminatePace
+ if elapsed := time.Since(start); elapsed < min {
+ t.Fatalf("drained %d terminates in %s, faster than the %s the quota allows — pacing is not applied",
+ n, elapsed, min)
+ }
+}
+
+// Kill must stop routing the sandbox immediately, even though the terminate
+// itself drains asynchronously — an exec landing on a condemned box is worse
+// than a slightly stale inventory.
+func TestKillUnbindsBeforeTheTerminateDrains(t *testing.T) {
+ f := &termAPI{failFor: map[string]int{"mvm-9": 2}}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ m := NewManager(c, t.TempDir())
+ m.Track("sb-9", &Box{ID: "mvm-9"}, types.SandboxConfig{})
+
+ if err := m.Kill(context.Background(), "sb-9"); err != nil {
+ t.Fatalf("Kill returned %v — a queued destroy must not fail the caller", err)
+ }
+ if _, ok := m.MicrovmIDFor("sb-9"); ok {
+ t.Fatal("sandbox still routes after Kill — an exec could reach a condemned box")
+ }
+ if !waitFor(t, 10*time.Second, func() bool { return len(f.done()) == 1 }) {
+ t.Fatal("box was never actually terminated")
+ }
+}
+
+// The pool's box budget treats TrackedMicrovmIDs as "in use", so a binding that
+// outlives its box silently shrinks the headroom the pool is allowed to refill
+// into. Measured on dev: 112 phantom bindings against 130 boxes actually alive,
+// which would have made the pool refuse to restock during exactly the burst it
+// was sized for. Forget is what the reconciler calls when it finds a dead box;
+// this pins the invariant that doing so actually returns the budget.
+func TestForgottenSandboxesStopCountingAgainstTheBudget(t *testing.T) {
+ f := &termAPI{}
+ c := NewClientWithAPI(f, Config{ImageIdentifier: "arn:image"})
+ m := NewManager(c, t.TempDir())
+
+ m.Track("sb-live", &Box{ID: "mvm-live"}, types.SandboxConfig{})
+ m.Track("sb-dead", &Box{ID: "mvm-dead"}, types.SandboxConfig{})
+ if got := len(m.TrackedMicrovmIDs()); got != 2 {
+ t.Fatalf("tracked %d boxes, want 2", got)
+ }
+
+ m.Forget("sb-dead")
+
+ tracked := m.TrackedMicrovmIDs()
+ if _, phantom := tracked["mvm-dead"]; phantom {
+ t.Fatal("a forgotten sandbox still counts as in use — the pool budget would refuse to refill against a box that no longer exists")
+ }
+ if _, ok := tracked["mvm-live"]; !ok || len(tracked) != 1 {
+ t.Fatalf("Forget disturbed the live binding: %v", tracked)
+ }
+ if len(f.done()) != 0 {
+ t.Fatalf("Forget terminated %v — the box is already gone, and on a shared account we must never issue a destroy we did not decide on", f.done())
+ }
+}