Skip to content

An open-source, faster Devin alternative

TypeScript

option c path

Brian Reardonbb2c3363feee
diff --git a/cloudflare-workers/api-edge/src/colo_cache.ts b/cloudflare-workers/api-edge/src/colo_cache.ts
index a7a5f710..9d3631de 100644
--- a/cloudflare-workers/api-edge/src/colo_cache.ts
+++ b/cloudflare-workers/api-edge/src/colo_cache.ts
@@ -23,6 +23,15 @@ function cacheOrNull(): Cache | null {
}
}
+// coloAvailable reports whether this runtime actually has a colo cache. Plain
+// node (vitest, local tooling) does not, and callers that treat a cache miss as
+// a decision — the voucher free-list claim, which reads "delete lost" as "some
+// other isolate took this box" — need to tell "nobody won" apart from "there is
+// no cache here at all".
+export function coloAvailable(): boolean {
+ return cacheOrNull() !== null;
+}
+
export async function coloGet<T>(kind: string, key: string): Promise<T | null> {
const cache = cacheOrNull();
if (!cache) return null;
@@ -61,12 +70,19 @@ export async function coloPut(kind: string, key: string, value: unknown, ttlSec:
// entry age out on its own TTL would keep a revoked credential working for the
// remainder of the stale window in this colo, which is the exact failure the
// refresh exists to prevent — so the refresh evicts instead.
-export async function coloDelete(kind: string, key: string): Promise<void> {
+// Returns whether THIS caller was the one that removed the entry. That boolean
+// is the only single-winner primitive available to a Worker that costs no
+// subrequest, and the voucher book draws on it: a voucher is claimed by deleting
+// its free-list entry, so at most one isolate should observe `true`. Cloudflare
+// does not document delete() as atomic under concurrency, so the book treats a
+// win as a strong hint and lets the guest CAS arbitrate for real — see
+// voucher_book.ts claimFree.
+export async function coloDelete(kind: string, key: string): Promise<boolean> {
const cache = cacheOrNull();
- if (!cache) return;
+ if (!cache) return false;
try {
- await cache.delete(BASE + kind + "/" + encodeURIComponent(key));
+ return await cache.delete(BASE + kind + "/" + encodeURIComponent(key));
} catch {
- /* best-effort */
+ return false;
}
}
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index def8b1dc..e84a1eac 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -24,6 +24,19 @@ export { CreditAccount } from "../../shared/credit_account";
// used here only by the dev-only direct-exec probe.
import { H2Grpc, openTunnel, encodeExecRequest, decodeExecResponse } from "../../shared/h2grpc";
export { PoolStock } from "./pool_stock";
+import { mintPoolCapToken } from "./pool_stock";
+import {
+ takeVoucher,
+ resolveBinding,
+ drawReplacement,
+ evictVoucher,
+ bindVoucher,
+ purgeBooks,
+ peekVoucher,
+ lastResolveTier,
+} from "./voucher_book";
+import type { Draw } from "./voucher_book";
+import { popVoucher } from "./voucher_cache";
// VmSession (VM-DO exec data plane) lives in its own worker
// (cloudflare-workers/vm-do) and is bound cross-script via VM_SESSIONS —
// deliberately NOT exported here, so the edge's deploy cadence (every merge
@@ -152,11 +165,25 @@ export interface Env extends DashboardEnv {
// keeps its warm set in process, where the stock DO can never be filled — see
// createSandbox. Unset means edge-claim, which is prod.
MICROVM_EDGE_CLAIM?: string;
+ // Zero-subrequest edge claim (voucher_book.ts). Default OFF; PoolStock stays
+ // the path for everything else until this is proven under burst.
+ LITE_VOUCHER_CLAIM?: string;
// CREATE_BATCH=1 coalesces concurrent creates on the CP-fallback path into one
// request per isolate. Off by default: measured on dev with a settled pool it
// batched 26-at-a-time and saved nothing, because the edge->cell hop is round
// trip, not connection setup (CP handler is ~40us for a 132ms hop).
CREATE_BATCH?: string;
+ // "0" makes a voucher create hold ZERO connections: no binding write, no
+ // finalize send. Diagnostic only — it leaves the sandbox with no row and no
+ // resolvable box, so exec 404s and the box leaks. It exists to test whether
+ // the unexplained ~150ms of burst create latency is our own waitUntil
+ // connection use. A Worker invocation may hold six connections and each
+ // waitUntil takes one, so the cost of holding them lands on the NEXT request
+ // to that isolate — i.e. inside the residual, invisible to `hdl`.
+ CREATE_WAITUNTIL?: string;
+ // Shared token for the in-region voucher cache. Absent = tier 0 disabled and
+ // creates draw from the colo book exactly as before.
+ VOUCHER_CACHE_SECRET?: string;
// VM-DO exec data plane (vm_do_datapane_validation). One DO per sandbox holds a
// persistent host-dialed WebSocket to the QEMU worker; exec routes edge→DO→VM
// instead of tunnel→CP→worker, with automatic tunnel fallback when unconnected.
@@ -188,6 +215,8 @@ export interface FinalizeMsg {
runtime: string;
sandboxID: string;
workerID: string;
+ /** Voucher creates only: the box to redeem against. Absent on every other path. */
+ microvmID?: string;
bodyText: string;
}
@@ -691,7 +720,7 @@ async function listActiveCells(env: Env): Promise<CellRow[]> {
// (fresh isolates, caches empty) that collapses ~3×D1-latency into one. Each
// piece still honours + populates its existing per-isolate cache, so warm/
// sustained traffic skips D1 entirely and only the cold misses are batched.
-type CreateContext = { org: OrgPolicy | null; activeCount: number; cells: CellRow[] };
+type CreateContext = { org: OrgPolicy | null; activeCount: number; cells: CellRow[]; cellsAtMs: number };
// In-flight loads, keyed by org. The three cache tiers below only help a request
// that arrives after some earlier request has already finished populating them —
@@ -742,7 +771,7 @@ async function loadCreateContextUncoalesced(
orgID: string,
ctx?: ExecutionContext,
probe?: CtxProbe,
-): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {
+): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[]; cellsAtMs: number }> {
const nowMs = Date.now();
const oc = orgPolicyCache.get(orgID);
const cc = concurrencyCountCache.get(orgID);
@@ -938,7 +967,16 @@ async function loadCreateContextUncoalesced(
}
await Promise.all(puts);
}
- return { org, activeCount, cells };
+ // cellsAtMs is WHEN these rows were read, and callers must judge cell
+ // heartbeat freshness against it rather than against wall-clock now.
+ //
+ // Without it the stale tier defeats itself: it is allowed to serve a snapshot
+ // for CELL_STALE_MAX_MS (5 min) while isHealthy rejects any capacity_updated_at
+ // older than CAPACITY_FRESH_SEC (2 min) — so every create served a snapshot
+ // between those two ages got "no cells available with capacity" while the cell
+ // was perfectly healthy in D1. Reproduced at burst-100 as 100/100 creates
+ // failing instantly (hdl=0) seconds after a sequential run passed 5/5.
+ return { org, activeCount, cells, cellsAtMs: activeCellsCache?.cachedAtMs ?? nowMs };
}
const CELL_ROW_SQL =
@@ -1016,10 +1054,14 @@ async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {
// generous 4× margin that covers a missed sample without flapping.
const CAPACITY_FRESH_SEC = 120;
-function isHealthy(cell: CellRow, nowSec: number): boolean {
+// observedAtSec is when the row was READ. Heartbeat freshness is a property of
+// the reading, not of this moment — re-judging a cached snapshot against a later
+// clock makes every cache tier expire its own contents early. Defaults to
+// nowSec, so an uncached read behaves exactly as before.
+function isHealthy(cell: CellRow, nowSec: number, observedAtSec: number = nowSec): boolean {
if (cell.status !== "active") return false;
if (cell.capacity_updated_at == null) return false;
- if (nowSec - cell.capacity_updated_at > CAPACITY_FRESH_SEC) return false;
+ if (observedAtSec - cell.capacity_updated_at > CAPACITY_FRESH_SEC) return false;
if (cell.available_workers <= 0) return false;
return true;
}
@@ -1074,8 +1116,10 @@ async function pickCell(
homeCell: string,
requestedCellID: string | null,
prefetchedCells?: CellRow[],
+ cellsObservedAtMs?: number,
): Promise<CellRow | null> {
const nowSec = Math.floor(Date.now() / 1000);
+ const observedSec = cellsObservedAtMs ? Math.floor(cellsObservedAtMs / 1000) : nowSec;
// 0. Hard pin
if (requestedCellID) {
@@ -1093,7 +1137,7 @@ async function pickCell(
let home = results.find((c) => c.cell_id === homeCell) ?? null;
if (!home) home = await lookupCell(env, homeCell);
- const healthy = results.filter((c) => isHealthy(c, nowSec));
+ const healthy = results.filter((c) => isHealthy(c, nowSec, prefetchedCells ? observedSec : nowSec));
if (healthy.length === 0) return null;
if (home) {
@@ -1850,6 +1894,7 @@ async function finalizeEdgeClaim(
sandboxID: string,
workerID: string,
bodyText: string,
+ microvmID?: string,
): Promise<void> {
// Index insert is DEFERRED below the finalize call + a short delay: D1 has a
// single writer, and a create burst otherwise queues ~100 inserts exactly
@@ -1868,6 +1913,11 @@ async function finalizeEdgeClaim(
/* eligibility already vetted the body; belt-and-braces */
}
body.sandboxID = sandboxID;
+ // Voucher creates carry the box, because the cell has nothing else to
+ // redeem against: the sandbox id was minted at the edge and the cell has
+ // never seen it. Omitted on every other path, where the cell finds its own
+ // reservation by sandbox id.
+ if (microvmID) body.microvmID = microvmID;
// Bill/grow at the default create shape the box was manufactured as.
if (!body.memoryMB) body.memoryMB = 4096;
if (!body.cpuCount) body.cpuCount = 1;
@@ -1876,7 +1926,18 @@ async function finalizeEdgeClaim(
headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },
body: JSON.stringify(body),
});
- if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
+ if (!r.ok) {
+ const detail = await r.text();
+ // The cell disowned the box this create drew, which for a voucher means
+ // the book it came from belongs to a cell generation that no longer
+ // exists. Abandon it so the next create refills instead of drawing more
+ // vouchers for dead boxes.
+ if (r.status === 409 && detail.includes("voucher lost")) {
+ console.error(`voucher: cell disowned ${sandboxID} (box ${microvmID}) — purging the book`);
+ await purgeBooks();
+ }
+ throw new Error(`${r.status} ${detail}`);
+ }
await new Promise((resolve) => setTimeout(resolve, 1500));
await insertSandboxIndex(env, caller, cell.cell_id, { sandboxID, workerID, status: "running", memoryMB: 4096 }, 1, 4096).catch((e) =>
console.error(`edge-claim: index insert failed for ${sandboxID}:`, e),
@@ -1894,7 +1955,7 @@ async function finalizeEdgeClaim(
}
}
-async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop?: number): Promise<Response> {
// Per-phase timing → Server-Timing response header (Date.now advances on I/O
// in Workers, so deltas attribute I/O waits; pure CPU shows ~0).
const phases: string[] = [];
@@ -1910,6 +1971,11 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
//
// Client-supplied clock, so it carries the client's skew — fine against a
// ~700ms signal, useless for anything small. Absent header => no mark.
+ // `top` is OUR routing cost: Worker invocation -> this handler. Skew-free,
+ // unlike `pre` below, which needs a client clock. It splits the residual in
+ // two: anything before tTop happened before the isolate ran (admission,
+ // transport), anything between tTop and here is ours to cut.
+ if (typeof tTop === "number") phases.push(`top;dur=${tEntry - tTop}`);
const clientSentMs = Number(req.headers.get("x-client-sent") ?? "");
if (Number.isFinite(clientSentMs) && clientSentMs > 0) {
phases.push(`pre;dur=${tEntry - clientSentMs}`);
@@ -1939,7 +2005,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// One batched D1 round-trip for org + running-count + active-cells (was three
// serial reads on the create hot path). Cache-aware: warm isolates skip D1.
const ctxProbe: CtxProbe = { coloMs: 0, d1Ms: 0, d1Stmts: 0, coalesced: false };
- const { org, activeCount, cells } = await loadCreateContext(env, caller.orgID, ctx, ctxProbe);
+ const { org, activeCount, cells, cellsAtMs } = await loadCreateContext(env, caller.orgID, ctx, ctxProbe);
mark("ctx");
// Which tier `ctx` actually spent its time in. `ctxn` is a statement COUNT,
// not a duration; Server-Timing has nowhere else to put it.
@@ -2013,7 +2079,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
memoryMB: bodyMemoryMB,
diskMB: bodyDiskMB,
}, activeCount),
- pickCell(env, org.home_cell, requestedCellID, cells),
+ pickCell(env, org.home_cell, requestedCellID, cells, cellsAtMs),
]);
mark("gatecell");
if (gate) return gate;
@@ -2049,6 +2115,154 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// Scoped to the runtime rather than reusing EDGE_CLAIM=0, which is global. A
// cell can serve both runtimes, and switching one cell's MicroVM data plane
// must not turn off edge-claim for the QEMU orgs sharing it.
+ // ZERO-SUBREQUEST CLAIM. Answer out of the colo's voucher book — no Durable
+ // Object, no origin call, no route write. See voucher_book.ts for why that is
+ // the whole game: at burst-100 the edge→CP call cost 310ms while the CP's own
+ // handler took 75us, so the time was scheduling, not work, and the only way to
+ // stop paying it is to not make the call.
+ //
+ // Ownership is NOT established here. The voucher is a hint; the box settles it
+ // with a compare-and-swap fused onto the first exec. A miss falls through to
+ // everything below, which is exactly what runs today.
+ if (
+ env.LITE_VOUCHER_CLAIM === "1" &&
+ org.runtime === RUNTIME_MICROVM &&
+ edgeClaimEligible(bodyText, parsedBody)
+ ) {
+ try {
+ const colo = req.headers.get("cf-ray")?.split("-")[1] ?? "unknown";
+ const mintCap = () => mintPoolCapToken(env.SESSION_JWT_SECRET, cell.cell_id);
+
+ // Tier 0: the in-region voucher cache (voucher_cache.ts). A pop is
+ // atomic by construction — one process, one mutex — so unlike the colo
+ // book it cannot hand the same box to two concurrent creates, and it has
+ // no cold state to rebuild. Null here is ordinary and falls through to
+ // the book below, which still works exactly as it did.
+ let draw: Draw | null = null;
+ if (env.VOUCHER_CACHE_SECRET) {
+ const pop = await popVoucher(cell.base_url, env.VOUCHER_CACHE_SECRET, mintCap, (p) =>
+ ctx.waitUntil(p),
+ );
+ if (pop) {
+ phases.push(`vpop;dur=${pop.ms}`, `vptry;dur=${pop.tries}`, `vdisc;dur=${pop.discMs}`);
+ draw = {
+ voucher: pop.voucher,
+ readMs: pop.ms,
+ casMs: 0,
+ // Not a book draw: there is no memo, no free-list probe, and the
+ // instance's remaining depth is its business, not ours.
+ memoHit: 0,
+ remaining: -1,
+ probes: 0,
+ };
+ }
+ }
+ if (!draw) {
+ draw = await takeVoucher(
+ cell.base_url,
+ colo,
+ mintCap,
+ (p) => ctx.waitUntil(p),
+ );
+ }
+ mark("vdraw");
+ if (draw) {
+ phases.push(
+ `vstock;dur=${draw.remaining}`,
+ `vclaim;dur=${draw.probes}`,
+ `vread;dur=${draw.readMs}`,
+ `vcas;dur=${draw.casMs}`,
+ `vmemo;dur=${draw.memoHit}`,
+ );
+ // The sandbox ID is minted HERE, per create, and never read out of the
+ // voucher.
+ //
+ // That is what makes a duplicate draw survivable. The book is finite and
+ // a burst can exceed it, so by pigeonhole two creates WILL sometimes
+ // draw the same box; with the ID minted here they arrive at that box as
+ // two different sandboxes, the guest CAS picks one, and the loser
+ // retries against the next voucher. When the ID came from the voucher
+ // instead, the CAS saw one sandbox claiming its box twice, reported an
+ // idempotent replay, and both customers walked away holding the same
+ // sandbox.
+ const sandboxID = "sb-" + crypto.randomUUID().replace(/-/g, "").slice(0, 8);
+ // The box's proxy token is deliberately NOT returned. It is a secret
+ // that reaches the AWS proxy directly, and the customer never needs it:
+ // the SDK falls back to X-API-Key when the sandbox token is empty
+ // (sdks/typescript/src/exec.ts), which the edge already authenticates.
+ const resp: Record<string, unknown> = {
+ sandboxID,
+ token: "",
+ status: "running",
+ region: cell.region ?? "",
+ workerID: "vmhost-lite:" + draw.voucher.microvmID,
+ };
+ // Seed the route. This is NOT optional bookkeeping — it is what makes
+ // the sandbox reachable at all.
+ //
+ // Dropping it was a real mistake, and an expensive one: a voucher create
+ // writes no D1 row (finalize rides a queue), so with no route entry the
+ // edge cannot resolve the sandbox to a cell and answers the customer's
+ // first exec with 404 "sandbox not found" — before the request ever
+ // reaches the control plane that could have fixed it. Measured at
+ // burst-100 as 98/100 execs failing while every create succeeded.
+ //
+ // Worth its connection: create is ~215ms with two waitUntils against a
+ // six-connection budget, and the alternative is a create that returns a
+ // sandbox nobody can use.
+ if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
+ sandboxRouteCache.set(sandboxID, { cellID: cell.cell_id, orgID: caller.orgID });
+ ctx.waitUntil(
+ coloPut("route", sandboxID, { cellID: cell.cell_id, orgID: caller.orgID }, MVM_REACH_TTL_SEC),
+ );
+ // Record which box this sandbox got. Only this invocation knows the
+ // pairing now that the id is minted here, so nothing else can write it.
+ // Bound below, once the finalize it may later need to correct exists.
+ // The finalize send. Each waitUntil holds an open connection and an
+ // invocation may hold six; this path spends two so a burst of creates
+ // does not queue behind its own bookkeeping.
+ const holdConnections = env.CREATE_WAITUNTIL !== "0";
+ phases.push(`wu;dur=${holdConnections ? 2 : 0}`);
+ if (env.FINALIZE_QUEUE && holdConnections) {
+ const msg: FinalizeMsg = {
+ orgID: caller.orgID,
+ userID: caller.userID ?? null,
+ cellID: cell.cell_id,
+ baseURL: cell.base_url,
+ plan,
+ billingProvider: org.billing_provider,
+ runtime: org.runtime ?? "",
+ sandboxID,
+ workerID: "vmhost-lite:" + draw.voucher.microvmID,
+ // The cell redeems the voucher BY BOX, because the box is the only
+ // identity a voucher has. Without this the finalize has nothing to
+ // redeem: measured as 473 consecutive "EDGE CLAIM FINALIZE LOST"
+ // and zero successes, i.e. every voucher create returned a sandbox
+ // that was never written to the database and could never be exec'd.
+ microvmID: draw.voucher.microvmID,
+ bodyText,
+ };
+ bindVoucher(sandboxID, draw.voucher, (p) => ctx.waitUntil(p), msg);
+ ctx.waitUntil(env.FINALIZE_QUEUE.send(msg).catch(() => {}));
+ } else {
+ bindVoucher(sandboxID, draw.voucher, (p) => ctx.waitUntil(p));
+ }
+ phases.push(
+ `hdl;dur=${Date.now() - tEntry}`,
+ `iso;dur=${tEntry - ISO_BORN}`,
+ `isn;dur=${ISO_SEQ}`,
+ `isot;dur=${tEntry % 10_000_000}`,
+ );
+ return new Response(JSON.stringify(resp), {
+ status: 201,
+ headers: { "content-type": "application/json", "server-timing": phases.join(", ") },
+ });
+ }
+ } catch (e) {
+ console.error("voucher-claim: falling through to the existing path:", e);
+ }
+ }
+
const edgeClaimOn =
env.EDGE_CLAIM !== "0" &&
!(org.runtime === RUNTIME_MICROVM && env.MICROVM_EDGE_CLAIM === "0");
@@ -2427,6 +2641,168 @@ function fallback(f: Fallback | undefined, why: string): null {
// so an un-sanitized exception message would corrupt every mark after it.
const descSafe = (s: string): string => s.replace(/[^\w.:/-]+/g, "_").slice(0, 80);
+// tryVoucherExec settles ownership and runs the command in ONE round trip.
+//
+// Returns null whenever this is not a voucher sandbox, or the ladder ran out —
+// both mean "use the normal path", and neither is an error.
+//
+// The retry ladder is bounded and every attempt is independent. Nothing here
+// waits on another request's I/O: an earlier experiment that coalesced creates
+// bought 0ms and cost 18% of a burst to Cloudflare error 1101 when one
+// invocation's work was made to depend on another's.
+// Attempts against DIFFERENT boxes, each one claimed from the free list before
+// it is tried. Deep enough to ride out a handful of dead boxes without letting a
+// wedged colo walk the whole book on a customer's request.
+const VOUCHER_EXEC_ATTEMPTS = 6;
+
+async function tryVoucherExec(
+ req: Request,
+ env: Env,
+ ctx: ExecutionContext,
+ sandboxID: string,
+ authMs: number,
+): Promise<Response | null> {
+ // Outer guard: returning null must ALWAYS be available as an answer.
+ //
+ // This path's whole safety argument is "a miss is never worse than today" —
+ // it falls through to the control-plane exec that has always worked. An
+ // exception escaping this function breaks that promise in the worst way: the
+ // customer gets a Cloudflare 1101 error page instead of their command output.
+ // Measured at burst-100 as 37/100 execs returning `500 <!DOCTYPE html>` while
+ // 100/100 creates succeeded.
+ try {
+ return await voucherExec(req, env, ctx, sandboxID, authMs);
+ } catch (e) {
+ console.log(`voucher-exec FELL THROUGH ${sandboxID} err=${String(e).slice(0, 200)}`);
+ return null;
+ }
+}
+
+async function voucherExec(
+ req: Request,
+ env: Env,
+ ctx: ExecutionContext,
+ sandboxID: string,
+ authMs: number,
+): Promise<Response | null> {
+ const t0 = Date.now();
+ const bound = await resolveBinding(sandboxID);
+ let v = bound?.voucher ?? null;
+ if (!v) {
+ // Loud on purpose: a miss here sends the request to the tunnel, which for a
+ // voucher-created sandbox 404s (its D1 row rides the finalize queue). So a
+ // miss is not a graceful degradation, it is a failure, and it must be
+ // diagnosable without guessing from latency.
+ console.log(`voucher-resolve MISS ${sandboxID} tier=${lastResolveTier}`);
+ return null;
+ }
+ console.log(`voucher-resolve HIT ${sandboxID} tier=${lastResolveTier}`);
+
+ // Read from a CLONE. A Request body can be consumed exactly once, and every
+ // branch below can still decide to return null — at which point the caller
+ // hands this same Request to the normal exec path, which reads the body
+ // again. Consuming the original made that second read throw, and the throw
+ // surfaced to the customer as a Cloudflare 500 page.
+ //
+ // That is why the failure tracked the FALLBACK rate rather than the voucher
+ // logic: sequentially the ladder always won on its first try and nothing fell
+ // through (10/10), while at burst-100 the 409/502 branches fired and every
+ // request that took them died — 37/100, all with the identical error.
+ let body: Record<string, unknown>;
+ try {
+ body = (await req.clone().json()) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+
+ const marks: string[] = [`auth;dur=${authMs}`];
+ // Set once the ladder moves off the box the create handed out. A rebind is not
+ // just a retry: the control plane still has the FIRST box recorded against
+ // this sandbox, so it has to be corrected before anything acts on it.
+ let rebound = false;
+ for (let attempt = 0; attempt < VOUCHER_EXEC_ATTEMPTS && v; attempt++) {
+ try {
+ const r = await fetch(`https://${v.endpoint}/osb/claim-and-run`, {
+ method: "POST",
+ headers: {
+ "X-aws-proxy-auth": v.token,
+ "X-aws-proxy-port": String(v.port),
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ sandboxID, ...body }),
+ });
+ if (r.status !== 200) {
+ console.log(`voucher-exec BOXFAIL ${sandboxID} box=${v.microvmID} status=${r.status} body=${(await r.text()).slice(0, 160)}`);
+ }
+ if (r.status !== 200) {
+ // Two different failures, one response: someone else owns that box
+ // (409), or the box is gone — a 502 from the AWS proxy means terminated
+ // or unreachable. Neither is retryable against the SAME box, since a
+ // voucher names exactly one, so the ladder moves to another.
+ //
+ // A 409 is also a correctness signal and gets said out loud. Once the
+ // free list arbitrates draws it should be near-impossible: the create
+ // took this box by deleting its free-list entry, and Cache API delete
+ // has exactly one winner per colo.
+ if (r.status === 409) {
+ console.log(`voucher-exec CONFLICT ${sandboxID} box=${v.microvmID} — box owned by another sandbox`);
+ }
+ // A replacement is CLAIMED from the free list, so it is ours alone and
+ // will not lose the same race twice. Null means the colo's book is dry;
+ // fall back to the control plane rather than acquiring a cell handle
+ // here, which would cost the subrequest this path exists to avoid.
+ const next = await drawReplacement();
+ if (!next) {
+ // Nothing to move to. Drop the binding so no later exec retries this
+ // box; the cell settles who actually owns it (ReconcileVouchers).
+ ctx.waitUntil(evictVoucher(sandboxID));
+ break;
+ }
+ console.log(`voucher-exec REBIND ${sandboxID} ${v.microvmID} → ${next.microvmID} (${r.status})`);
+ v = next;
+ rebound = true;
+ continue;
+ }
+ const out = (await r.json()) as { run?: { stdout?: string; stderr?: string; exitCode?: number } };
+ const run = out.run ?? { stdout: "", stderr: "", exitCode: 0 };
+ if (rebound) {
+ // The sandbox lives on a different box than the create announced. Move
+ // the binding, and re-send the create's own finalize with the box that
+ // actually won — otherwise the control plane keeps pointing at the first
+ // box, and destroying this sandbox would terminate another customer's.
+ bindVoucher(sandboxID, v, (p) => ctx.waitUntil(p), bound?.fin);
+ const fin = bound?.fin as FinalizeMsg | undefined;
+ if (fin && env.FINALIZE_QUEUE) {
+ const corrected: FinalizeMsg = {
+ ...fin,
+ workerID: "vmhost-lite:" + v.microvmID,
+ microvmID: v.microvmID,
+ };
+ ctx.waitUntil(env.FINALIZE_QUEUE.send(corrected).catch(() => {}));
+ } else {
+ console.error(`voucher-exec REBIND ${sandboxID} has no finalize context — cell still names the old box`);
+ }
+ }
+ marks.push(`vexec;dur=${Date.now() - t0}`, `vtry;dur=${attempt + 1}`);
+ // The inline run-async shape the SDK short-circuits on, so exec.run()
+ // never enters its poll ladder.
+ return new Response(
+ JSON.stringify({ exitCode: run.exitCode ?? 0, stdout: run.stdout ?? "", stderr: run.stderr ?? "" }),
+ { status: 200, headers: { "content-type": "application/json", "server-timing": marks.join(", ") } },
+ );
+ } catch (e) {
+ console.log(`voucher-exec THROW ${sandboxID} box=${v.microvmID} err=${String(e).slice(0, 200)}`);
+ break;
+ }
+ }
+ // NOTE: nothing is handed back here, deliberately. A 409 means the BOX is
+ // owned by a different sandbox, so our voucher's box is live — returning it
+ // would re-pool a box a customer is using. The cell settles expired vouchers
+ // by asking each box who owns it (ReconcileVouchers); the edge is not in a
+ // position to assert anything about ownership, and must not pretend to be.
+ return null;
+}
+
// tryVmDoExec routes POST /:id/exec/run-async through the sandbox's VmSession
// Durable Object (the VM-DO exec data plane, vm_do_datapane_validation) instead
// of the tunnel→CP→worker chain. Returns a Response when the DO handled it (a
@@ -4726,8 +5102,29 @@ async function runPausedCapEnforcer(env: Env): Promise<void> {
}
}
+// Isolate identity, for telling COLD START apart from admission queueing.
+//
+// A burst's "colo_admit" (the benchmark's total minus our handler) is a residual,
+// not a measurement: it holds the wire leg, client-side H2 stream scheduling, CF
+// admission, isolate scheduling and the response path all at once. Within one
+// run it decayed 189ms → 86ms → 11ms across create/exec/delete at identical
+// concurrency, which is the shape of a warm-up curve rather than a load curve —
+// and every burst so far has been the first traffic after a deploy, so every
+// isolate serving it was born cold.
+//
+// These three marks settle it. ISO_AGE says how old the isolate was when the
+// request landed; ISO_SEQ says how many requests it had already served; ISO_T
+// stamps handler entry so the SPREAD of entry times across a burst can be
+// compared against what the client observed. If 100 handler entries span 180ms,
+// admission really is serializing. If they span 10ms, the time is somewhere the
+// edge cannot see.
+const ISO_BORN = Date.now();
+let ISO_SEQ = 0;
+
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
+ const tTop = Date.now();
+ ISO_SEQ++;
const url = new URL(req.url);
const path = url.pathname;
@@ -4743,6 +5140,81 @@ export default {
return json({ ok: true, env: env.WORKER_ENV });
}
+ // Dev-only: drop this colo's voucher book so the next create refills from
+ // the cell.
+ //
+ // Exists for measurement hygiene. A pool reset terminates every box the
+ // current book names, and nothing in the book records liveness — `usable`
+ // only checks expiry — so the next burst would claim corpses and spend its
+ // whole ladder discovering that. Until now the only way to force a fresh
+ // book was to bump BOOK_GEN and redeploy, which also discards every warm
+ // isolate, making "fresh book" and "warm isolates" mutually exclusive and
+ // quietly turning every measured burst into a first-traffic-after-deploy
+ // run. That is the confound this route removes.
+ if (path === "/internal/_purgebook") {
+ if (env.WORKER_ENV === "production") return json({ error: "not found" }, 404);
+ await purgeBooks();
+ return json({ purged: true, colo: (req as { cf?: { colo?: string } }).cf?.colo ?? "unknown" });
+ }
+
+ // Dev-only: time this colo's round trip to an arbitrary origin.
+ //
+ // Exists to size the in-region voucher cache. Every latency number we have
+ // for the edge→AWS path (vexec = 78ms p50) is contaminated by guest work and
+ // the claim CAS, so it cannot answer the only question the cache design
+ // turns on: what does a bare request from this colo to a box in us-east-1
+ // cost? A pop-per-create is only viable if that is single-digit ms;
+ // otherwise the edge has to pop batches and hand them out locally.
+ //
+ // Reports EVERY iteration, not an average, because the first one pays TLS
+ // and the rest reuse the pooled connection — and it is the warm number the
+ // design depends on.
+ if (path === "/internal/_rtt") {
+ if (env.WORKER_ENV === "production") return json({ error: "not found" }, 404);
+ const u = new URL(req.url);
+ let target = u.searchParams.get("target");
+ let auto: Record<string, string> = {};
+ if (!target) {
+ // No explicit target: address a real pool box through the AWS proxy.
+ // /healthz is the cheapest thing behind that proxy, so what is left is
+ // network + proxy — the leg the cache would pay on every pop.
+ const v = await peekVoucher();
+ if (!v) return json({ error: "no voucher in book; pass ?target=" }, 503);
+ target = `https://${v.endpoint}/healthz`;
+ auto = { "X-aws-proxy-auth": v.token, "X-aws-proxy-port": String(v.port) };
+ }
+ const n = Math.min(20, Math.max(1, Number(u.searchParams.get("n") ?? 6)));
+ const headers: Record<string, string> = { ...auto };
+ const tok = u.searchParams.get("auth");
+ const port = u.searchParams.get("port");
+ if (tok) headers["X-aws-proxy-auth"] = tok;
+ if (port) headers["X-aws-proxy-port"] = port;
+ const ms: number[] = [];
+ const codes: number[] = [];
+ for (let i = 0; i < n; i++) {
+ const t = Date.now();
+ try {
+ const r = await fetch(target, { headers });
+ await r.arrayBuffer();
+ codes.push(r.status);
+ } catch (e) {
+ codes.push(-1);
+ console.log(`_rtt THROW ${String(e).slice(0, 120)}`);
+ }
+ ms.push(Date.now() - t);
+ }
+ const warm = ms.slice(1).sort((a, b) => a - b);
+ return json({
+ colo: (req as { cf?: { colo?: string } }).cf?.colo ?? "unknown",
+ target,
+ ms,
+ codes,
+ cold: ms[0],
+ warmMedian: warm.length ? warm[Math.floor(warm.length / 2)] : null,
+ warmMin: warm.length ? warm[0] : null,
+ });
+ }
+
// VM-DO host dial: the QEMU worker host opens a persistent WebSocket to the
// per-sandbox VmSession DO here (vm_session.ts). Auth is a per-sandbox connect
// token = HMAC(SESSION_JWT_SECRET, "vmdo:"+id), minted by the CP and delivered
@@ -5171,7 +5643,7 @@ export default {
// /api/sandboxes and /api/sandboxes/:id[/...]
if (path === "/api/sandboxes") {
- if (req.method === "POST") return createSandbox(req, env, ctx);
+ if (req.method === "POST") return createSandbox(req, env, ctx, tTop);
if (req.method === "GET") return listSandboxes(req, env);
return json({ error: "method not allowed" }, 405);
}
@@ -5331,6 +5803,18 @@ export default {
// in THIS colo between its bursts. Off the hot path (waitUntil) and a
// no-op unless an entry is actually aging.
keepCreateContextWarm(env.OPENCOMPUTER_DB, ctx, caller.orgID);
+ // FUSED CLAIM+EXEC. If this sandbox came from a voucher, its box has not
+ // been bound to anyone yet — ownership is settled right here, on the exec
+ // that had to reach the box regardless. That is what lets create cost zero
+ // round trips: the claim rides along instead of buying its own transit.
+ //
+ // A 409 means another isolate drew the same voucher first. Expected, not
+ // exceptional: draw the next one and retry. Exhausting the ladder falls
+ // through to everything below, which is the path that runs today.
+ if (env.LITE_VOUCHER_CLAIM === "1" && req.method === "POST" && rest === "/exec/run-async") {
+ const fusedResp = await tryVoucherExec(req, env, ctx, id, authMs);
+ if (fusedResp) return stampSub(fusedResp, "voucher");
+ }
// VM-DO exec fast path: route POST /:id/exec/run-async through the
// sandbox's VmSession DO. Automatic tunnel fallback (no flag) whenever the
// channel isn't live (DO 409) — so this is safe even before/while workers
@@ -5474,6 +5958,7 @@ export default {
b.sandboxID,
b.workerID,
b.bodyText,
+ b.microvmID,
);
} catch (e) {
console.error(`finalize-queue: ${b.sandboxID} failed:`, e);
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index e5d13642..58ef9492 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -191,7 +191,12 @@ async function mintSandboxTokenDO(
return signingInput + "." + b64url(sig);
}
-async function mintPoolCapToken(secret: string, cellID: string): Promise<string> {
+// Exported so the voucher path (voucher_book.ts, via index.ts) can authenticate
+// its off-hot-path refill with the same synthetic pool identity PoolStock uses.
+// The refill hits /internal/pool/vouchers on the same cell and the CP applies
+// the same internal check, so a second token shape would be a second thing to
+// keep correct for no gain.
+export async function mintPoolCapToken(secret: string, cellID: string): Promise<string> {
const now = Math.floor(Date.now() / 1000);
const enc = new TextEncoder();
const header = { alg: "HS256", typ: "JWT" };
diff --git a/cloudflare-workers/api-edge/src/voucher_book.test.ts b/cloudflare-workers/api-edge/src/voucher_book.test.ts
new file mode 100644
index 00000000..e4f7ea04
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/voucher_book.test.ts
@@ -0,0 +1,408 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { _resetVoucherIsolateState, _rewindCursorForTest, bindVoucher, resolveVoucher, takeVoucher, type Voucher } from "./voucher_book";
+
+// A minimal stand-in for caches.default. The real one is colo-shared and
+// best-effort; what matters for these cases is that it is SHARED, because that
+// is the property the per-isolate hint map lacked.
+function installFakeColoCache() {
+ // Honours max-age, because that is the ONLY thing enforcing BOOK_TTL_SEC — the
+ // module never checks book age on read, it relies on the entry evicting. A
+ // fake that stores forever would make the idle-gap test pass at any TTL and
+ // pin nothing.
+ const store = new Map<string, { body: string; expiresAtMs: number }>();
+ (globalThis as unknown as { caches: unknown }).caches = {
+ default: {
+ async match(url: string) {
+ const v = store.get(url);
+ if (v === undefined) return undefined;
+ if (Date.now() >= v.expiresAtMs) {
+ store.delete(url);
+ return undefined;
+ }
+ return new Response(v.body);
+ },
+ async put(url: string, resp: Response) {
+ const cc = resp.headers.get("cache-control") ?? "";
+ const m = cc.match(/max-age=(\d+)/);
+ const ttlMs = (m ? Number(m[1]) : 0) * 1000;
+ store.set(url, { body: await resp.text(), expiresAtMs: Date.now() + ttlMs });
+ },
+ async delete(url: string) {
+ return store.delete(url);
+ },
+ },
+ };
+ return store;
+}
+
+function mkVouchers(n: number, ttlSec = 3600): Voucher[] {
+ const exp = Math.floor(Date.now() / 1000) + ttlSec;
+ return Array.from({ length: n }, (_, i) => ({
+ microvmID: `mvm-${i}`,
+ endpoint: `ep-${i}`,
+ token: "t",
+ port: 8080,
+ expiresAtUnix: exp,
+ }));
+}
+
+const noWait = (p: Promise<unknown>) => void p.catch(() => {});
+
+// Rewind this isolate's cursor while KEEPING what it has learned. _reset clears
+// the taken-set too, which would stand in for a different isolate entirely.
+const cursorBackToStart = () => _rewindCursorForTest();
+
+describe("voucher book", () => {
+ // Every test leaves refills in flight — a draw schedules one through waitUntil
+ // and the helpers hand it a swallowing stub. Let those settle BEFORE resetting,
+ // or a stale single-flight promise is what the next test's cold path awaits,
+ // and it resolves against the previous test's cache.
+ beforeEach(async () => {
+ await new Promise((r) => setTimeout(r, 0));
+ installFakeColoCache();
+ _resetVoucherIsolateState(0);
+ vi.restoreAllMocks();
+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ["Date"] });
+ });
+
+ async function seed(vouchers: Voucher[]) {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ vouchers })));
+ vi.stubGlobal("fetch", fetchMock);
+ // First draw finds a cold book, waits for the refill it triggered, and is
+ // served from it — the whole point of the cold path.
+ const first = await takeVoucher("https://cell", "IAD", async () => "k", (p) => void p);
+ expect(first).not.toBeNull();
+ await new Promise((r) => setTimeout(r, 0));
+ return fetchMock;
+ }
+
+ it("fills a cold book on demand and serves the create that found it cold", async () => {
+ const fetchMock = await seed(mkVouchers(64));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ _resetVoucherIsolateState(0);
+ const got = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(got?.voucher.microvmID).toBeTruthy();
+ });
+
+ // The core burst property: one isolate must never hand the same box to two
+ // creates. Cross-isolate collisions are tolerable (the box CAS settles them);
+ // self-collisions would be gratuitous.
+ it("never draws the same voucher twice within an isolate", async () => {
+ await seed(mkVouchers(256));
+ _resetVoucherIsolateState(0);
+ const seen = new Set<string>();
+ for (let i = 0; i < 100; i++) {
+ const d = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(d).not.toBeNull();
+ expect(seen.has(d!.voucher.microvmID)).toBe(false);
+ seen.add(d!.voucher.microvmID);
+ }
+ expect(seen.size).toBe(100);
+ });
+
+ // Different isolates start at different offsets, so a burst spread across
+ // isolates does not have every one of them draw index 0.
+ it("spreads draws across isolates via the random base", async () => {
+ await seed(mkVouchers(256));
+ const firstOf = (b: number) => {
+ _resetVoucherIsolateState(b);
+ return takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ };
+ const a = await firstOf(0);
+ const b = await firstOf(97);
+ expect(a!.voucher.microvmID).not.toBe(b!.voucher.microvmID);
+ });
+
+ // THE burst property, and the reason the free list exists. Two isolates
+ // reading one shared book pick independently, so at a load factor near 1 the
+ // pigeonhole guarantees overlap — 37 of 100 measured. The claim is what makes
+ // the draw disjoint: a box is taken by DELETING its free-list entry, and
+ // Cache API delete reports a single winner.
+ it("never hands the same box to two isolates drawing the same book", async () => {
+ await seed(mkVouchers(64));
+ const drawnBy = async (b: number) => {
+ _resetVoucherIsolateState(b);
+ return takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ };
+ const seen = new Set<string>();
+ // Every isolate starts at index 0 — the worst case the old code had no
+ // answer for, since base is what used to spread them. Each one therefore
+ // walks past everything already taken, so 20 draws is also the deepest walk
+ // PROBE_BUDGET has to absorb here.
+ for (let i = 0; i < 20; i++) {
+ const d = await drawnBy(0);
+ expect(d).not.toBeNull();
+ expect(seen.has(d!.voucher.microvmID)).toBe(false);
+ seen.add(d!.voucher.microvmID);
+ }
+ expect(seen.size).toBe(20);
+ });
+
+ // A lost claim costs a ~1ms colo op, not an ~80ms round trip to a box, so the
+ // draw walks past taken boxes rather than handing one out and losing at the CAS.
+ it("walks past boxes another isolate already claimed", async () => {
+ await seed(mkVouchers(8));
+ // Isolate A takes the first three from index 0.
+ _resetVoucherIsolateState(0);
+ const taken = new Set<string>();
+ for (let i = 0; i < 3; i++) {
+ taken.add((await takeVoucher("https://cell", "IAD", async () => "k", noWait))!.voucher.microvmID);
+ }
+ // Isolate B starts at the same base and must skip all three.
+ _resetVoucherIsolateState(0);
+ const d = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(d).not.toBeNull();
+ expect(taken.has(d!.voucher.microvmID)).toBe(false);
+ // seed() itself drew one, so four boxes are gone: four losses, then the win.
+ expect(d!.probes).toBe(5);
+ });
+
+ // A lost claim is permanent, so an isolate must never pay for the same loss
+ // twice. Before the local set existed, `vclaim` p95 was 11 probes and `vcas`
+ // p95 144ms at burst-100 — the tail of a draw was re-discovering losses it had
+ // already discovered, at ~13ms of colo round trip each.
+ it("never re-probes a box it has already lost", async () => {
+ await seed(mkVouchers(16));
+ // Another isolate takes the first four.
+ _resetVoucherIsolateState(0);
+ for (let i = 0; i < 4; i++) await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+
+ _resetVoucherIsolateState(0);
+ const first = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ // seed() took one and the loop took four, so five losses precede the win.
+ expect(first!.probes).toBe(6);
+
+ // The next draw starts at the same base and must walk the same dead entries
+ // WITHOUT paying for them again.
+ cursorBackToStart();
+ const second = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(second).not.toBeNull();
+ expect(second!.probes).toBe(1);
+ });
+
+ // Refills used to REPLACE the book, stranding every box the previous one had
+ // not handed out — and since the cell vouchers out of `warm` and never takes a
+ // promise back, the next refill then returns almost nothing at a 150-box pool.
+ it("carries undrawn stock forward across a refill", async () => {
+ await seed(mkVouchers(8));
+ _resetVoucherIsolateState(0);
+ const first = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+
+ const fresh = mkVouchers(4).map((v) => ({ ...v, microvmID: "new-" + v.microvmID }));
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ vouchers: fresh }))));
+ const { refillBook } = await import("./voucher_book");
+ // Past the colo's refill window, so this counts as a NEW pull rather than
+ // one racing the pull that just happened.
+ vi.setSystemTime(Date.now() + 6_000);
+ await refillBook("https://cell", "IAD", async () => "k");
+
+ // 4 new + 6 still-unclaimed carried = 10 drawable (seed() took one too), and
+ // neither box already handed out is among them.
+ _resetVoucherIsolateState(0);
+ const seen = new Set<string>();
+ for (let i = 0; i < 10; i++) {
+ const d = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(d).not.toBeNull();
+ seen.add(d!.voucher.microvmID);
+ }
+ expect(seen.size).toBe(10);
+ expect(seen.has(first!.voucher.microvmID)).toBe(false);
+ });
+
+ // The cold-book stampede. A burst arriving on many cold isolates must produce
+ // ONE pull for the colo, not one per isolate: the cell serves them in order, so
+ // the first takes almost the whole pool and the rest get zero vouchers back.
+ // Measured against a purged book before the lease existed: create p50 2874.9ms,
+ // 75/100, vstock=0 on every create.
+ it("pulls once per colo when many cold isolates race for a missing book", async () => {
+ let pulls = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ pulls++;
+ // The cell only has stock for the FIRST puller, exactly as it behaves
+ // when a colo drains it: everyone after gets an empty answer.
+ return new Response(JSON.stringify({ vouchers: pulls === 1 ? mkVouchers(64) : [] }));
+ }),
+ );
+ const { refillBook } = await import("./voucher_book");
+ // Each cold isolate is its own module state, so reset between them — that is
+ // precisely why per-isolate single-flight was no protection.
+ for (let i = 0; i < 10; i++) {
+ _resetVoucherIsolateState(i);
+ await refillBook("https://cell", "IAD", async () => "k");
+ }
+ expect(pulls).toBe(1);
+
+ // ...and the losers can still draw, from the winner's book.
+ _resetVoucherIsolateState(3);
+ const d = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(d).not.toBeNull();
+ });
+
+ // A loser must not serve out its full wait when the pull it is waiting on has
+ // already died — the winner deletes the lease on failure, so "no lease and no
+ // book" means nobody is coming.
+ it("stops waiting as soon as the winning pull fails", async () => {
+ let pulls = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ pulls++;
+ return new Response("nope", { status: 500 });
+ }),
+ );
+ const { refillBook } = await import("./voucher_book");
+ _resetVoucherIsolateState(0);
+ await refillBook("https://cell", "IAD", async () => "k"); // winner: fails, releases
+
+ // A second isolate must return promptly rather than burning LEASE_WAIT_MS,
+ // and because the lease was released it is free to pull again itself.
+ _resetVoucherIsolateState(1);
+ const t0 = Date.now();
+ await refillBook("https://cell", "IAD", async () => "k");
+ expect(Date.now() - t0).toBeLessThan(500);
+ expect(pulls).toBe(2);
+ });
+
+ // A voucher about to be reclaimed by the CP's reaper must not be handed out —
+ // the claim would race it and lose.
+ it("skips vouchers close to expiry rather than losing a race with the reaper", async () => {
+ // Not via seed(): a book of nothing BUT near-expiry vouchers can never
+ // serve, which is precisely what this asserts.
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ vouchers: mkVouchers(32, 5) }))));
+ _resetVoucherIsolateState(0);
+ const got = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(got).toBeNull();
+ });
+
+ // A binding is written by the create that minted the id, and must survive any
+ // number of book rotations — it has nothing to do with book retention.
+ it("resolves a sandbox back to its box, and across a book rotation", async () => {
+ await seed(mkVouchers(16));
+ _resetVoucherIsolateState(0);
+ const drawn = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ bindVoucher("sb-mine", drawn!.voucher, noWait);
+ expect((await resolveVoucher("sb-mine"))?.microvmID).toBe(drawn!.voucher.microvmID);
+
+ // Rotate: a brand-new, disjoint book replaces the current one.
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ vouchers: mkVouchers(16) }))));
+ const { refillBook } = await import("./voucher_book");
+ // Past the colo's refill window, so this counts as a NEW pull rather than
+ // one racing the pull that just happened.
+ vi.setSystemTime(Date.now() + 6_000);
+ await refillBook("https://cell", "IAD", async () => "k");
+
+ expect((await resolveVoucher("sb-mine"))?.microvmID).toBe(drawn!.voucher.microvmID);
+ expect(await resolveVoucher("sb-never-issued")).toBeNull();
+ });
+
+ // The burst-100 regression, pinned: a book must still serve after an idle gap
+ // far longer than the old 45s TTL. When it did not, 100 creates missed at once
+ // and stampeded the control plane (TTI p50 8.7s, 35 rate-limit 503s).
+ it("still serves after a long idle gap", async () => {
+ await seed(mkVouchers(256, 3600));
+ _resetVoucherIsolateState(0);
+ // Ten minutes of nothing — the gap that produced the 8.7s burst.
+ vi.setSystemTime(Date.now() + 10 * 60_000);
+ const got = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(got).not.toBeNull();
+ vi.useRealTimers();
+ });
+
+ // Freshness must not depend on a miss noticing the book is cold — by then a
+ // burst has already fallen through.
+ it("refreshes proactively at half life, while still serving", async () => {
+ const fetchMock = await seed(mkVouchers(256, 3600));
+ _resetVoucherIsolateState(0);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ vi.setSystemTime(Date.now() + 20 * 60_000); // past half of the 30-min TTL
+ const got = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(got).not.toBeNull(); // served from the current book...
+ await new Promise((r) => setTimeout(r, 0));
+ expect(fetchMock.mock.calls.length).toBeGreaterThan(1); // ...and refreshed behind it
+ vi.useRealTimers();
+ });
+
+ // The burst-100 stampede, pinned: when the book is cold, concurrent creates
+ // must issue ONE refill and then all draw from it — not all fall through to
+ // the control plane together.
+ it("a cold book coalesces concurrent creates onto one refill", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ vouchers: mkVouchers(256) })));
+ vi.stubGlobal("fetch", fetchMock);
+ _resetVoucherIsolateState(0);
+
+ const draws = await Promise.all(
+ Array.from({ length: 20 }, () => takeVoucher("https://cell", "IAD", async () => "k", noWait)),
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(1); // one refill, not twenty
+ const served = draws.filter((d) => d !== null);
+ expect(served.length).toBeGreaterThan(0); // and they got served, not dropped
+ const ids = new Set(served.map((d) => d!.voucher.microvmID));
+ expect(ids.size).toBe(served.length); // still no self-collision
+ });
+
+ // THE burst-100 exec failure, pinned. Every create succeeded and every exec
+ // 404'd because the book rotated out from under its own in-flight requests.
+ // Resolution must survive any number of rotations.
+ it("resolves a sandbox after many book rotations", async () => {
+ await seed(mkVouchers(50));
+ _resetVoucherIsolateState(0);
+ const drawn = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ const box = drawn!.voucher.microvmID;
+ bindVoucher("sb-mine", drawn!.voucher, noWait);
+
+ // Five disjoint refills — far past the two-deep book rotation that dropped it.
+ const { refillBook } = await import("./voucher_book");
+ for (let r = 0; r < 5; r++) {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ vouchers: mkVouchers(50) }))));
+ await refillBook("https://cell", "IAD", async () => "k");
+ }
+
+ const got = await resolveVoucher("sb-mine");
+ expect(got).not.toBeNull();
+ expect(got!.microvmID).toBe(box);
+ });
+
+ // The defect that made burst unusable, pinned from the edge side: a book
+ // smaller than the burst must REFUSE rather than wrap. Wrapping re-issued a
+ // voucher this isolate had already handed out, and when the sandbox id lived
+ // inside the voucher that meant two customers holding the same sandbox.
+ it("refuses to draw past the end of the book instead of wrapping", async () => {
+ await seed(mkVouchers(8));
+ _resetVoucherIsolateState(0);
+ // Refills return nothing, so the book cannot grow under the test and the
+ // only thing being measured is what ONE book will serve.
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ vouchers: [] }))));
+ const seen = new Set<string>();
+ let nulls = 0;
+ for (let i = 0; i < 20; i++) {
+ const d = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ if (!d) {
+ nulls++;
+ continue;
+ }
+ expect(seen.has(d.voucher.microvmID)).toBe(false);
+ seen.add(d.voucher.microvmID);
+ }
+ expect(seen.size).toBeLessThanOrEqual(8);
+ expect(nulls).toBeGreaterThan(0); // the excess fell through to the CP path
+
+ // Restock is NOT asserted here. It needs a refill to land mid-test, and the
+ // loop above leaves refills in flight that this one would race — see
+ // "carries undrawn stock forward across a refill", which pins it cleanly.
+ });
+
+ // The index must not answer for a sandbox nobody issued.
+ it("does not resolve an unknown sandbox", async () => {
+ await seed(mkVouchers(50));
+ expect(await resolveVoucher("sb-never-issued")).toBeNull();
+ });
+
+ it("a failed refill degrades to the fallback rather than throwing", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("nope", { status: 500 })));
+ const got = await takeVoucher("https://cell", "IAD", async () => "k", noWait);
+ expect(got).toBeNull();
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/voucher_book.ts b/cloudflare-workers/api-edge/src/voucher_book.ts
new file mode 100644
index 00000000..b108c2b3
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/voucher_book.ts
@@ -0,0 +1,744 @@
+// The voucher book: how a create answers without calling anyone.
+//
+// MEASURED PROBLEM. At burst-100 a create spent 310ms in the edge→control-plane
+// call while the CP's own handler took 75 MICROSECONDS and swallowed the whole
+// burst inside 30ms. The time is not work — it is this isolate waiting to be
+// scheduled. A Worker invocation may hold only six open connections, and every
+// subrequest and every waitUntil consumes one. Sequentially the same call is
+// 67ms; the extra ~243ms is a uniform toll paid per request under concurrency
+// (flat across arrival deciles, so contention, not a queue draining).
+//
+// So the goal is not a faster call. It is ZERO calls. A create reads this book
+// out of the colo-shared Cache API — which is not a subrequest — picks a
+// voucher, and returns.
+//
+// WHY THIS SUCCEEDS WHERE TWO PREDECESSORS FAILED.
+//
+// PoolStock (Durable Object). The pop was a subrequest on the hot path — the
+// exact 310ms term. Everything else about it (sticky placement, now on shard
+// generation g5; the SHARDS x TARGET_STOCK sizing invariant; epoch fencing)
+// was work spent making a coordination point behave, when the coordination
+// point was itself the cost.
+//
+// Per-isolate hint maps. Module state is per-ISOLATE, and a burst fragments
+// across isolates that cannot see each other, so hints missed almost always.
+// This book lives in caches.default, shared by every isolate in the colo.
+//
+// THE INVARIANT THAT MAKES IT SAFE: the edge holds hints, never ownership. A
+// voucher confers nothing. Two isolates may draw the same one; the box settles
+// it with an idempotent compare-and-swap (cmd/microvm-hooks/claim.go) and the
+// loser retries against the next voucher. Staleness, eviction and duplication
+// all degrade to a retry — never to a double-owned box.
+
+import { coloAvailable, coloDelete, coloGet, coloPut } from "./colo_cache";
+
+export interface Voucher {
+ // A voucher names a BOX. It deliberately does not carry a sandbox ID.
+ //
+ // It used to, and that was the defect that made burst unusable. A book of N
+ // served a burst of B>N, so by pigeonhole several creates drew the SAME
+ // voucher — and with the sandbox ID inside it, that meant handing the same
+ // sandbox ID to different customers. Nothing downstream could catch it: the
+ // guest CAS saw one ID claiming its box twice and correctly reported an
+ // idempotent replay.
+ //
+ // With the ID minted per create at the edge, a duplicate draw becomes two
+ // DIFFERENT sandboxes racing for one box, which is exactly the case the CAS
+ // exists to settle: one wins, the loser gets 409 and takes the next voucher.
+ // That is the difference between a hint and a promise.
+ microvmID: string;
+ endpoint: string;
+ token: string;
+ port: number;
+ expiresAtUnix: number;
+}
+
+interface Book {
+ vouchers: Voucher[];
+ // Stamped by us on write, so an isolate can tell one book from the next
+ // without comparing contents.
+ fetchedAtMs: number;
+}
+
+// How long a book may serve.
+//
+// Sized so the book SURVIVES IDLE. At 45s it did not: a burst arriving ten
+// minutes after the last create found nothing, so all 100 creates missed at
+// once, fell through to the control plane together, and produced 5.1s of D1
+// contention and 35 rate-limit 503s — TTI p50 8.7s, worse than not having this
+// path at all (measured 2026-08-26). The failure mode of an empty book is not
+// "slightly slower", it is a stampede, so the book must effectively always be
+// warm.
+//
+// Stays well under the CP's voucherTTL (60 min) so a voucher cannot be handed
+// out after it has been reclaimed.
+const BOOK_TTL_SEC = 1800;
+
+// Books are kept in a two-deep rotation, current and previous.
+//
+// Not for redundancy — for RESOLUTION. A create draws from `cur`, but the first
+// exec usually lands on a different isolate and possibly after a refill, and it
+// must still be able to turn its sandbox ID back into a box. Keeping the
+// outgoing book resolvable is what lets create write no route entry at all,
+// which is one fewer waitUntil connection on the hot path.
+// Bumped to abandon every book in every colo at once.
+//
+// Needed because a book OUTLIVES THE CELL THAT WROTE IT. A control-plane restart
+// terminates its warm set and comes back with entirely new boxes, but the edge's
+// book is a 30-minute colo-cache entry that knows nothing about that — so every
+// create for the next half hour draws a voucher naming a box that no longer
+// exists. Measured: 100/100 creates answered from a pre-restart book, 100
+// finalizes lost, 11/100 execs. purgeBooks below makes this self-heal; this
+// constant is the manual escape hatch when it has not yet.
+const BOOK_GEN = "g4";
+const CUR = "vbookcur" + BOOK_GEN;
+const PREV = "vbookprev" + BOOK_GEN;
+
+// THE BINDING — sandbox id -> box, written by the create that minted the id.
+//
+// This cannot be built at refill time any more: the sandbox ID does not exist
+// until a create invents it, so only the create knows the pairing. That costs
+// one colo-cache write on the create path — not a subrequest, and it rides the
+// waitUntil budget the route seed already spends.
+//
+// It replaces a sharded index keyed by a control-plane-minted sandbox ID. That
+// index worked, but only because the ID was pre-paired — the same pre-pairing
+// that made duplicate draws unsafe. Writing the binding here is what lets the
+// voucher be a hint rather than a promise.
+//
+// Lives as long as a voucher can (~ the cell's voucherTTL): a sandbox must stay
+// resolvable for as long as it can plausibly run a command, which has nothing to
+// do with how fast the book turns over.
+// ── free list ────────────────────────────────────────────────────────────────
+//
+// The book says which boxes exist. The FREE LIST says which are still unclaimed,
+// and it is what actually makes a draw safe.
+//
+// One entry per voucher, keyed by box. Drawing a box means DELETING its entry,
+// and Cache API delete reports whether this caller was the one that removed it.
+// That boolean is a single-winner primitive across every isolate in the colo:
+// measured 2026-08-26 at 100 concurrent deletes per armed key, 30 rounds, 1640
+// requests — exactly one `true` every time, with a 20ms settle after the put.
+//
+// This is the piece the design was missing. Without it, ~50 isolates read one
+// shared book and pick independently, so a burst of B into a book of n collides
+// at about B^2/2n — 42 expected at B=100, n=120, and 37 observed. No hashing or
+// cursor discipline can fix that: it is the pigeonhole principle, and the only
+// escapes are partitioning supply (which STARVES at a 150-box pool, since total
+// outstanding vouchers can never exceed the pool — the same invariant that broke
+// PoolStock) or coordinating. The free list coordinates, and costs no subrequest.
+//
+// A lost claim is now discovered in ~1ms here instead of by an ~80ms round trip
+// to the box, which is what makes contention affordable at a load factor of 0.8.
+// The guest CAS remains the authority; this only stops us racing toward it.
+// ── refill lease ─────────────────────────────────────────────────────────────
+//
+// Exactly one isolate in a colo may pull a book per window.
+//
+// `refilling` below is single-flight PER ISOLATE, which is no protection at all
+// when the book is missing: a burst arrives on ~100 cold isolates, each finds no
+// book, and each issues its own pull. The cell serves them in order, so the first
+// takes ~95% of the pool and every other pull returns ZERO — leaving 99 creates
+// with no book to draw from, all falling through to the control plane at once.
+// Measured 2026-08-27 against a purged book: create p50 2874.9ms, 75/100,
+// `vstock=0` on every create and `cell=2437ms`. The bounded cold-wait cannot
+// help, because the supply is already gone by the time the waiters look.
+//
+// So the pull is gated on winning a lease, using the same delete-wins primitive
+// the free list uses (see FREE). The winner pulls and re-arms; the losers wait
+// for the book it writes, which is what they wanted anyway.
+const LEASE = "vlease";
+
+// One pull per colo per window. Short enough that a genuinely needed refresh is
+// not held off for long, long enough to cover a slow pull.
+const REFILL_WINDOW_SEC = 5;
+
+// How long a loser waits for the winner's book.
+//
+// Sized against what giving up COSTS, which is the thing the first version got
+// wrong. A loser that falls through takes the control-plane path, and under a
+// cold-book burst that path measured ~2600ms — so quitting after 400ms to go do
+// something six times slower is never right. Worse, the quitters are what makes
+// the control plane slow, which delays the very pull they were waiting on.
+//
+// The flat timeout is only the ceiling. The loop below also watches for the pull
+// DYING: `releaseLease` deletes the lease on a failed pull, so no lease and no
+// book means nobody is coming and the loser should leave immediately rather than
+// serve out its budget.
+const LEASE_WAIT_MS = 1800;
+const LEASE_POLL_MS = 25;
+
+// claimLease returns true for an isolate that may pull.
+//
+// A cooldown entry, not a token handed back and forth: the entry's PRESENCE
+// means "someone pulled recently, don't". Handing a token back after each pull
+// does not work — the next isolate takes it immediately and the stampede is
+// unchanged, which is what the first version of this did.
+//
+// The check and the write are not atomic, so a few isolates arriving inside the
+// write's own latency can both win. That is a bounded race — a handful rather
+// than the hundred this exists to prevent — and the cost of losing it is one
+// extra pull, not a broken book.
+async function claimLease(): Promise<boolean> {
+ if (!coloAvailable()) return true;
+ if (await coloGet<unknown>(LEASE, BOOK_GEN)) return false;
+ await coloPut(LEASE, BOOK_GEN, { at: Date.now() }, REFILL_WINDOW_SEC);
+ return true;
+}
+
+// releaseLease reopens the window immediately, for a pull that produced nothing.
+// Holding the colo off for the full window after a dud would leave every create
+// on the control-plane path for no reason.
+async function releaseLease(): Promise<void> {
+ // DELETE, not a short-TTL write. The check is `coloGet(...)` truthy, and any
+ // object written here — even {at:0} — reads as "held", so re-putting would
+ // keep the colo blocked rather than reopening it.
+ await coloDelete(LEASE, BOOK_GEN).catch(() => {});
+}
+
+const FREE = "vfree";
+
+// Entries live as long as the promise behind them, so a box is drawable for its
+// whole voucher TTL. An entry that evicts early only makes its box undrawable —
+// the cell re-pools it via ReconcileVouchers. Safe direction.
+const FREE_TTL_MIN_SEC = 60;
+const FREE_TTL_MAX_SEC = 3600;
+
+function freeTTL(v: Voucher, nowSec: number): number {
+ const left = v.expiresAtUnix - nowSec;
+ return Math.max(FREE_TTL_MIN_SEC, Math.min(FREE_TTL_MAX_SEC, left));
+}
+
+// publishFree lists boxes as claimable. Only ever called for vouchers the cell
+// just handed us: re-publishing one that was already drawn would resurrect a box
+// a customer is using.
+async function publishFree(vouchers: Voucher[]): Promise<void> {
+ const nowSec = Math.floor(Date.now() / 1000);
+ const CHUNK = 32;
+ for (let i = 0; i < vouchers.length; i += CHUNK) {
+ await Promise.all(
+ vouchers.slice(i, i + CHUNK).map((v) => coloPut(FREE, v.microvmID, { m: v.microvmID }, freeTTL(v, nowSec))),
+ );
+ }
+}
+
+// claimFree returns true when THIS caller took the box.
+//
+// With no colo cache (vitest, local tooling) there is no free list to arbitrate,
+// so claiming always succeeds and the cursor discipline below is what bounds a
+// draw — exactly the behaviour these tests were written against.
+// Boxes this isolate has already seen taken. A lost claim is PERMANENT — the
+// box now belongs to whoever won it — so re-probing one is a ~13ms colo round
+// trip that can only fail again.
+//
+// Without this an isolate walks the same claimed entries on every subsequent
+// draw: measured at burst-100, `vclaim` p95 was 11 probes and `vcas` p95 144ms,
+// i.e. the tail of a draw was almost entirely re-discovering losses it had
+// already discovered.
+const takenLocal = new Set<string>();
+const TAKEN_MAX_LOCAL = 20_000;
+
+async function claimFree(microvmID: string): Promise<boolean> {
+ if (!coloAvailable()) return true;
+ if (takenLocal.has(microvmID)) return false;
+ const won = await coloDelete(FREE, microvmID);
+ // Either way this box is spent: lost to another isolate, or claimed by us.
+ // Both make it unclaimable, so both are worth remembering — a box we won
+ // ourselves would otherwise cost a wasted probe on our very next draw.
+ if (takenLocal.size >= TAKEN_MAX_LOCAL) takenLocal.clear();
+ takenLocal.add(microvmID);
+ return won;
+}
+
+const BIND = "vbind";
+const BIND_TTL_SEC = 3600;
+
+// Refill when this fraction of a book has been drawn by THIS isolate.
+//
+// Raised from 0.25: at a quarter, a 50-voucher book refilled every ~12 draws, so
+// a burst-100 rotated it several times mid-flight. Rotation is no longer fatal
+// (the index survives it) but it is still churn, and each rotation costs a pull
+// against the cell.
+const REFILL_AT_FRACTION = 0.5;
+
+// How many vouchers to ask for. Sized against the burst, not the pool: at N>=4x
+// the concurrent draw count, same-colo collisions stay to a few percent. The CP
+// clamps this to available stock minus the reserve it holds back for its own
+// create path.
+const BOOK_SIZE = 512;
+
+// A voucher this close to expiry is skipped rather than handed out — it would
+// likely lose its race with the CP's reconciler. Scaled with the TTLs above.
+const EXPIRY_GUARD_SEC = 300;
+
+// How many free-list claims one draw may attempt before giving up on the book.
+// Sized against the load factor a 150-box pool produces: a burst of 100 into a
+// book of ~120-142 needs about 2 probes on average and ~6 for the last arrival,
+// so this leaves headroom without letting a draw walk the whole book.
+const PROBE_BUDGET = 24;
+
+// How long an isolate may serve the book out of local memory.
+//
+// Was 5s, which produced a 32% memo hit rate at burst-100 — two draws in three
+// re-read and re-parsed a ~30KB book that had not changed. The book carries its
+// own 30-minute TTL and every refill overwrites this, so a short window here
+// bought no freshness; it only bought work. A stale entry is also harmless: the
+// free-list claim, not the book, decides whether a box is actually available.
+const MEMO_TTL_MS = 60_000;
+
+// Refresh once a book is older than this, on ANY request, in waitUntil.
+//
+// This is what keeps the book warm without depending on a miss to notice it is
+// cold. A miss is far too late: under burst, a hundred of them arrive together
+// and every one falls through. Refreshing at half life means steady traffic
+// keeps the book permanently fresh, and the miss path becomes the rare case it
+// was designed to be.
+const REFRESH_AGE_MS = (BOOK_TTL_SEC * 1000) / 2;
+
+// How long a create will wait for a cold book to fill before giving up and
+// taking the control-plane path.
+//
+// Generous relative to the refill (one origin GET, ~70ms in-region) because the
+// alternative is not "wait less", it is a hundred simultaneous control-plane
+// creates. Bounded so a sick cell cannot hold creates hostage.
+const COLD_REFILL_WAIT_MS = 2000;
+
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+// Per-isolate draw state.
+//
+// `base` is randomised ONCE per isolate. Two isolates in a colo therefore start
+// at different offsets into the same book, and `cursor` guarantees an isolate
+// never draws the same index twice. That is the whole collision-avoidance
+// scheme, and it is deliberately local — any shared counter would be a
+// coordination point, which is the thing this design exists to remove.
+let base = Math.floor(Math.random() * 1_000_003);
+let cursor = 0;
+let drawnFromBookAt = 0;
+let drawnCount = 0;
+
+// Parsed-book memo, so repeated draws in one isolate do not re-parse JSON.
+let memo: { book: Book; at: number } | null = null;
+
+// Bindings this isolate made or has already looked up. Not a cache tier that
+// can be wrong: a binding is immutable once written, so a local hit is exactly
+// what the colo cache holds.
+/**
+ * What a create recorded about the sandbox it just answered: the box it claimed,
+ * plus the finalize it sent for that box.
+ *
+ * The finalize rides along because a rebind has to CORRECT it. Finalize is
+ * enqueued at create naming the box the create drew, so if the exec ladder ends
+ * up on a different box — the first one is dead, or was claimed out from under
+ * us — the control plane is left pointing at a box this sandbox does not own,
+ * and a later destroy would terminate someone else's. The exec has no cell
+ * handle to rebuild that message from, so the create leaves it here.
+ */
+export interface Binding {
+ voucher: Voucher;
+ /** The FinalizeMsg the create enqueued, opaque to this module. */
+ fin?: unknown;
+}
+
+const bindings = new Map<string, Binding>();
+const BIND_MAX_LOCAL = 5000;
+
+// One refill in flight per isolate. Not a correctness device — a duplicate
+// refill is harmless because the CP hands out disjoint sets — purely to avoid
+// spending several connections on the same work.
+let refilling: Promise<void> | null = null;
+
+function usable(v: Voucher, nowSec: number): boolean {
+ return !!v && !!v.endpoint && !!v.microvmID && v.expiresAtUnix - nowSec > EXPIRY_GUARD_SEC;
+}
+
+async function readBook(key: string): Promise<Book | null> {
+ const b = await coloGet<Book>(key, "book");
+ if (!b || !Array.isArray(b.vouchers) || b.vouchers.length === 0) return null;
+ return b;
+}
+
+/**
+ * refillBook pulls a fresh book from the cell and rotates the current one into
+ * the previous slot.
+ *
+ * ALWAYS called from waitUntil, never awaited on a create. This is the only
+ * place the voucher path talks to the control plane, and it happens once per
+ * colo per refill window rather than once per create — which is the entire
+ * point.
+ */
+export async function refillBook(
+ cellBaseURL: string,
+ colo: string,
+ mintToken: () => Promise<string>,
+): Promise<void> {
+ if (refilling) return refilling;
+ refilling = (async () => {
+ try {
+ if (!(await claimLease())) {
+ // Another isolate is pulling for this colo. Wait for its book rather
+ // than issuing a competing pull that would return zero vouchers.
+ for (let waited = 0; waited < LEASE_WAIT_MS; waited += LEASE_POLL_MS) {
+ await sleep(LEASE_POLL_MS);
+ const b = await readBook(CUR);
+ if (!b && !(await coloGet<unknown>(LEASE, BOOK_GEN))) {
+ // The pull failed and released the lease. Waiting longer cannot
+ // help, and the next create through here will start a new one.
+ return;
+ }
+ if (b && b.vouchers.length > 0) {
+ memo = { book: b, at: Date.now() };
+ if (b.fetchedAtMs !== drawnFromBookAt) {
+ drawnFromBookAt = b.fetchedAtMs;
+ drawnCount = 0;
+ cursor = 0;
+ }
+ return;
+ }
+ }
+ return;
+ }
+ const url = `${cellBaseURL.replace(/\/$/, "")}/internal/pool/vouchers?colo=${encodeURIComponent(colo)}&n=${BOOK_SIZE}`;
+ // The HMAC mint lives HERE, inside the refill, and never on a create.
+ // Signing was measured as one of the larger CPU items driving isolate
+ // queueing at burst-100, and a create must not pay it.
+ const resp = await fetch(url, { headers: { authorization: "Bearer " + (await mintToken()) } });
+ if (!resp.ok) { await releaseLease(); return; }
+ const body = (await resp.json()) as { vouchers?: Voucher[] };
+ const vouchers = body?.vouchers ?? [];
+ if (vouchers.length === 0) { await releaseLease(); return; }
+
+ // Rotate before overwriting: vouchers already handed out of the outgoing
+ // book must stay resolvable for the execs that will arrive against them.
+ const outgoing = await readBook(CUR);
+ if (outgoing) await coloPut(PREV, "book", outgoing, BOOK_TTL_SEC * 2);
+
+ // List the NEW boxes as claimable. Never the carried-forward ones: they
+ // already have entries, and the drawn ones among them have had those
+ // entries deleted on purpose.
+ await publishFree(vouchers);
+
+ // Carry undrawn stock forward instead of dropping it.
+ //
+ // The cell vouchers out of `warm` and a promised box does not go back, so
+ // each refill returns a DIFFERENT set — replacing the book outright
+ // stranded everything the previous one had not handed out, and at a
+ // 150-box pool the second refill then returns almost nothing. Merging is
+ // safe now that the free list exists: a carried-forward box that was
+ // already drawn simply loses its claim.
+ const nowSec2 = Math.floor(Date.now() / 1000);
+ const seen = new Set(vouchers.map((v) => v.microvmID));
+ const carried = (outgoing?.vouchers ?? []).filter((v) => usable(v, nowSec2) && !seen.has(v.microvmID));
+ const merged = [...vouchers, ...carried].slice(0, BOOK_SIZE);
+
+ const next: Book = { vouchers: merged, fetchedAtMs: Date.now() };
+ await coloPut(CUR, "book", next, BOOK_TTL_SEC);
+ memo = { book: next, at: Date.now() };
+ // New book, new draw window. `cursor` resets WITH it — a fresh book is a
+ // disjoint set of boxes from the cell, so starting over at the base is
+ // drawing new stock, not re-drawing spent stock. Without this reset an
+ // isolate that once hit the end of a book could never draw again, since
+ // the hard stop below compares cursor against the new book's length.
+ drawnFromBookAt = next.fetchedAtMs;
+ drawnCount = 0;
+ cursor = 0;
+ takenLocal.clear();
+ } catch {
+ await releaseLease();
+ // Best-effort by construction: a failed refill just means the next create
+ // misses the book and takes the control-plane path, which is correct and
+ // is what every create did before this existed.
+ } finally {
+ refilling = null;
+ }
+ })();
+ return refilling;
+}
+
+export interface Draw {
+ voucher: Voucher;
+ /** Colo-cache read + parse of the book, ms. 0 when the isolate memo served it. */
+ readMs: number;
+ /** Free-list claim deletes, ms. */
+ casMs: number;
+ /** 1 when this isolate's memo served the book, 0 when it had to read. */
+ memoHit: number;
+ /** Vouchers left in the book after this draw, for telemetry only. */
+ remaining: number;
+ /** Free-list claims attempted for this draw. 1 means uncontended. */
+ probes: number;
+}
+
+/**
+ * takeVoucher draws one voucher for a create. Returns null when the book cannot
+ * serve, and the caller must fall through to the control-plane create path.
+ *
+ * Never throws and never blocks on I/O beyond a single colo cache read.
+ */
+export async function takeVoucher(
+ cellBaseURL: string,
+ colo: string,
+ mintToken: () => Promise<string>,
+ waitUntil: (p: Promise<unknown>) => void,
+): Promise<Draw | null> {
+ const nowMs = Date.now();
+ const nowSec = Math.floor(nowMs / 1000);
+
+ let book = memo && nowMs - memo.at < MEMO_TTL_MS ? memo.book : null;
+ const memoHit = book ? 1 : 0;
+ let readMs = 0;
+ let casMs = 0;
+ const tRead = Date.now();
+ if (!book) {
+ book = await readBook(CUR);
+ if (book) memo = { book, at: nowMs };
+ }
+ readMs = Date.now() - tRead;
+ if (!book) {
+ // COLD BOOK. Do not simply fall through — under burst that is the stampede:
+ // 100 creates miss together, all fall through to the control plane at once,
+ // and drive it to 5.1s of D1 and 34 rate-limit 503s (measured 2026-08-26,
+ // TTI p50 8.7s, worse than having no voucher path at all). Raising TTLs does
+ // not help here, because the very first traffic after a deploy IS the burst.
+ //
+ // So wait for the refill instead, bounded. refillBook is single-flight per
+ // isolate, so the hundred creates sharing this isolate issue ONE fetch and
+ // then all draw from the result. That is intra-isolate coalescing — the same
+ // shape loadCreateContext already uses — and is NOT the cross-request
+ // dependency that cost 18% of a burst to error 1101: every request still
+ // owns its own response, and a slow refill degrades to the old path rather
+ // than hanging.
+ const refill = refillBook(cellBaseURL, colo, mintToken);
+ waitUntil(refill);
+ await Promise.race([refill, sleep(COLD_REFILL_WAIT_MS)]);
+ book = await readBook(CUR);
+ if (!book) return null;
+ memo = { book, at: Date.now() };
+ // Deliberately does NOT reset `cursor`: refillBook already did, once, and
+ // the concurrent creates that shared this cold path all arrive here after
+ // it. Resetting per request would hand every one of them the same index.
+ drawnFromBookAt = book.fetchedAtMs;
+ drawnCount = 0;
+ }
+
+ // A new book resets this isolate's draw window.
+ if (book.fetchedAtMs !== drawnFromBookAt) {
+ drawnFromBookAt = book.fetchedAtMs;
+ drawnCount = 0;
+ cursor = 0;
+ }
+
+ const n = book.vouchers.length;
+ // HARD STOP AT THE END OF THE BOOK — the modulo must never wrap.
+ //
+ // `cursor` is monotonic within a book window, so this isolate's draw sequence
+ // is base, base+1, ... base+n-1: exactly n DISTINCT indices. Wrapping past
+ // that re-issues a voucher this isolate has already handed out, and a voucher
+ // carries its sandbox ID — so two customers receive the SAME sandbox. Nothing
+ // downstream can catch it: the guest CAS sees the same sandbox ID and reports
+ // idempotent success, which is indistinguishable from a legitimate replay.
+ //
+ // This is not the tolerable duplicate the header describes. That argument
+ // holds only for two isolates drawing DIFFERENT sandbox IDs for one box,
+ // where the CAS picks a winner. A wrap produces a duplicate the CAS is blind
+ // to, and it is guaranteed rather than unlikely the moment the burst exceeds
+ // the book (measured: a 100-burst against an 80-voucher book).
+ //
+ // Past the end we return null and the caller takes the control-plane path,
+ // which is slower and correct.
+ //
+ // Each candidate must be CLAIMED, not just picked — see the free-list note
+ // above. A lost claim means another isolate already took that box, so we
+ // advance. The budget is generous because a probe is a ~1ms colo op, not the
+ // ~80ms box round trip a lost race used to cost: even a worst-case walk here
+ // is cheaper than one wasted CAS against a box.
+ let picked: Voucher | null = null;
+ let probes = 0;
+ for (let i = 0; i < PROBE_BUDGET && !picked && cursor < n; i++) {
+ const v = book.vouchers[(base + cursor++) % n];
+ if (!usable(v, nowSec)) continue;
+ // Skipping a known-taken box is free and is NOT a probe. Deciding that by
+ // elapsed time would be wrong — a fast colo delete also takes ~0ms — so ask
+ // the set directly.
+ if (takenLocal.has(v.microvmID)) continue;
+ probes++;
+ const tCas = Date.now();
+ const won = await claimFree(v.microvmID);
+ casMs += Date.now() - tCas;
+ if (won) picked = v;
+ }
+ const exhausted = cursor >= n;
+ drawnCount++;
+
+ // Refill on ANY of: this isolate has drawn its share, the book is past half
+ // its life, or we could not find a usable voucher. The age trigger is the one
+ // that prevents the stampede — it refreshes while the book is still serving,
+ // rather than waiting for it to be empty.
+ if (
+ drawnCount >= n * REFILL_AT_FRACTION ||
+ nowMs - book.fetchedAtMs > REFRESH_AGE_MS ||
+ !picked ||
+ exhausted
+ ) {
+ waitUntil(refillBook(cellBaseURL, colo, mintToken));
+ }
+ if (!picked) return null;
+ return { voucher: picked, remaining: Math.max(0, n - drawnCount), probes, readMs, casMs, memoHit };
+}
+
+/**
+ * drawReplacement claims another box for a sandbox whose first one did not work
+ * out — the box CAS said someone else owns it, or the proxy says it is gone.
+ *
+ * Deliberately cannot refill: an exec has no cell handle and must not acquire
+ * one, since a subrequest here is the very cost this whole path exists to avoid.
+ * If the colo's book is dry it returns null and the caller falls back to the
+ * control plane, which is slower and correct.
+ */
+export async function drawReplacement(): Promise<Voucher | null> {
+ const nowMs = Date.now();
+ const nowSec = Math.floor(nowMs / 1000);
+ const book = memo && nowMs - memo.at < MEMO_TTL_MS ? memo.book : await readBook(CUR);
+ if (!book) return null;
+ const n = book.vouchers.length;
+ if (n === 0) return null;
+ if (book.fetchedAtMs !== drawnFromBookAt) {
+ drawnFromBookAt = book.fetchedAtMs;
+ drawnCount = 0;
+ cursor = 0;
+ }
+ for (let i = 0; i < PROBE_BUDGET && cursor < n; i++) {
+ const v = book.vouchers[(base + cursor++) % n];
+ if (!usable(v, nowSec)) continue;
+ if (await claimFree(v.microvmID)) {
+ drawnCount++;
+ return v;
+ }
+ }
+ return null;
+}
+
+/**
+ * bindVoucher records which box a create handed to which sandbox.
+ *
+ * The create path calls this; nothing else establishes the pairing, because
+ * nothing else knows it. Cheap on purpose: one colo-cache write, no subrequest,
+ * and the in-isolate map means the common case (create and exec landing on the
+ * same isolate) resolves without touching the cache at all.
+ */
+export function bindVoucher(
+ sandboxID: string,
+ v: Voucher,
+ waitUntil: (p: Promise<unknown>) => void,
+ fin?: unknown,
+): void {
+ if (bindings.size >= BIND_MAX_LOCAL) bindings.clear();
+ const b: Binding = { voucher: v, fin };
+ bindings.set(sandboxID, b);
+ waitUntil(coloPut(BIND, sandboxID, b, BIND_TTL_SEC).catch(() => {}));
+}
+
+// Why a resolution went the way it did. Emitted on the exec path so a miss is
+// diagnosable from the outside — inferring it from latency alone is how two
+// separate wrong theories survived a full day.
+export type ResolveTier = "local" | "bind" | "miss";
+export let lastResolveTier: ResolveTier = "miss";
+
+/**
+ * resolveVoucher turns a sandbox ID back into the box its create drew.
+ *
+ * Null means "not ours", and the caller falls back to normal routing — which is
+ * the control-plane path that has always worked.
+ */
+export async function resolveBinding(sandboxID: string): Promise<Binding | null> {
+ const local = bindings.get(sandboxID);
+ if (local) {
+ lastResolveTier = "local";
+ return local;
+ }
+ const hit = await coloGet<Binding>(BIND, sandboxID);
+ if (hit && hit.voucher?.endpoint) {
+ bindings.set(sandboxID, hit);
+ lastResolveTier = "bind";
+ return hit;
+ }
+ lastResolveTier = "miss";
+ return null;
+}
+
+export async function resolveVoucher(sandboxID: string): Promise<Voucher | null> {
+ return (await resolveBinding(sandboxID))?.voucher ?? null;
+}
+
+/**
+ * evictVoucher drops a binding whose box is gone (AWS 502).
+ *
+ * A binding outlives the sandbox it names: the customer destroys the sandbox,
+ * the cell terminates the box, and this entry still points at it for the rest of
+ * its TTL. Dialling it then yields a 502, so the exec ladder evicts and retries
+ * rather than reporting a dead box as the customer's answer.
+ */
+export async function evictVoucher(sandboxID: string): Promise<void> {
+ bindings.delete(sandboxID);
+ await coloPut(BIND, sandboxID, { voucher: { microvmID: "", endpoint: "", token: "", port: 0, expiresAtUnix: 0 } }, 1).catch(
+ () => {},
+ );
+}
+
+/**
+ * purgeBooks abandons this colo's book after the cell disowned a voucher from it.
+ *
+ * A lost finalize is the cell saying "that box was never mine to give" — which,
+ * for a whole book at once, means the cell restarted underneath it. Nothing else
+ * detects that: the book is a cache entry with its own TTL and no knowledge of
+ * the process that filled it, so without this a single restart poisons every
+ * create in the colo until the entry ages out.
+ *
+ * Runs off the response path (the finalize is already async), and the next
+ * create takes the cold path, refills, and is served correctly.
+ */
+export async function purgeBooks(): Promise<void> {
+ memo = null;
+ bindings.clear();
+ cursor = 0;
+ drawnFromBookAt = 0;
+ drawnCount = 0;
+ const dead = { vouchers: [] as Voucher[], fetchedAtMs: 0 };
+ await Promise.all([
+ coloPut(CUR, "book", dead, 1).catch(() => {}),
+ coloPut(PREV, "book", dead, 1).catch(() => {}),
+ ]);
+}
+
+// peekVoucher returns a live voucher WITHOUT claiming it. Measurement only —
+// the RTT probe needs a real box it can address through the AWS proxy, and
+// drawing one properly would consume stock and skew the very pool the probe is
+// run against. Never call this on a create path: two callers get the same box.
+export async function peekVoucher(): Promise<Voucher | null> {
+ const book = memo?.book ?? (await readBook(CUR));
+ if (!book) return null;
+ const nowSec = Math.floor(Date.now() / 1000);
+ return book.vouchers.find((v) => usable(v, nowSec)) ?? null;
+}
+
+/** Test seam: drop per-isolate state so cases do not bleed into each other. */
+// Test seam: rewind the draw cursor without forgetting which boxes this isolate
+// has already lost. Distinguishes "same isolate draws again" from "a different
+// isolate draws", which _resetVoucherIsolateState models.
+export function _rewindCursorForTest(): void {
+ cursor = 0;
+}
+
+export function _resetVoucherIsolateState(newBase = 0): void {
+ base = newBase;
+ cursor = 0;
+ drawnFromBookAt = 0;
+ drawnCount = 0;
+ memo = null;
+ refilling = null;
+ bindings.clear();
+ // Part of this isolate's identity: a different isolate has not seen these
+ // losses, and tests rely on that to stand in for separate isolates.
+ takenLocal.clear();
+ lastResolveTier = "miss";
+}
diff --git a/cloudflare-workers/api-edge/src/voucher_cache.test.ts b/cloudflare-workers/api-edge/src/voucher_cache.test.ts
new file mode 100644
index 00000000..dfc7d3b1
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/voucher_cache.test.ts
@@ -0,0 +1,208 @@
+import { describe, it, expect, beforeEach, vi, afterEach } from "vitest";
+import {
+ popVoucher,
+ _resetCacheClientState,
+ _setPeersForTest,
+ type CachePeer,
+} from "./voucher_cache";
+
+const SECRET = "shh";
+const mintToken = async () => "cap-token";
+const waitUntil = (p: Promise<unknown>) => { void p.catch(() => {}); };
+
+function voucher(id: string) {
+ return {
+ microvmID: id,
+ endpoint: "box.example",
+ token: "t",
+ port: 8080,
+ expiresAtUnix: Math.floor(Date.now() / 1000) + 3600,
+ };
+}
+
+function peer(endpoint: string, retireAtUnix?: number): CachePeer {
+ return { endpoint, token: "pt", port: 8079, retireAtUnix };
+}
+
+let fetchMock: ReturnType<typeof vi.fn>;
+
+beforeEach(() => {
+ _resetCacheClientState();
+ fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function popOK(v: unknown, peers?: CachePeer[]) {
+ return new Response(JSON.stringify({ voucher: v, peers }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+describe("in-region voucher cache client", () => {
+ it("pops a voucher and reports how many instances it had to try", async () => {
+ _setPeersForTest([peer("a.example")]);
+ fetchMock.mockResolvedValue(popOK(voucher("mvm-1")));
+
+ const got = await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(got?.voucher.microvmID).toBe("mvm-1");
+ expect(got?.tries).toBe(1);
+ });
+
+ // A cold isolate must ask the control plane ONCE. This is the same stampede
+ // that made a cold colo book cost 1498ms: 100 concurrent creates each
+ // discovering independently is 100 calls into the thing we are avoiding.
+ // A cold isolate must not block on discovery — awaiting it cost 336ms p50 at
+ // burst-100 because every cold isolate called the control plane at once. It
+ // returns null (caller falls back to the book) and discovers in background.
+ it("does not block a create on discovery", async () => {
+ fetchMock.mockImplementation(async (url: string) => {
+ if (String(url).includes("/internal/pool/cache-peers")) {
+ return new Response(JSON.stringify({ peers: [peer("a.example")] }), { status: 200 });
+ }
+ return popOK(voucher("mvm-x"));
+ });
+ expect(await popVoucher("https://cell", SECRET, mintToken, waitUntil)).toBeNull();
+ await new Promise((r) => setTimeout(r, 5));
+ // Now warm: the next create pops without touching the control plane.
+ const got = await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(got?.voucher.microvmID).toBe("mvm-x");
+ });
+
+ it("pops on a cold isolate when the colo already knows the peers", async () => {
+ // The regression that made this tier dead under burst: a burst is almost
+ // entirely COLD isolates, so folding the colo read into the background
+ // discovery path meant every create returned null and fell through to the
+ // book. Measured burst-100: vpop=0 on all 100. The colo read is same-colo
+ // and cheap, so a cold isolate must await it; only the control-plane fetch
+ // stays in the background.
+ vi.stubGlobal("caches", {
+ default: {
+ match: async () =>
+ new Response(JSON.stringify([peer("a.example")]), {
+ headers: { "content-type": "application/json" },
+ }),
+ put: async () => {},
+ delete: async () => true,
+ },
+ });
+ fetchMock.mockImplementation(async (url: string) => {
+ if (String(url).includes("/internal/pool/cache-peers")) {
+ throw new Error("cold isolate must not wait on the control plane");
+ }
+ return popOK(voucher("mvm-colo"));
+ });
+
+ // First call on a brand-new isolate: no module state, straight to a pop.
+ const got = await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(got?.voucher.microvmID).toBe("mvm-colo");
+ expect(
+ fetchMock.mock.calls.filter((c) => String(c[0]).includes("/internal/pool/cache-peers")).length,
+ ).toBe(0);
+ });
+
+ it("discovers peers once no matter how many creates race", async () => {
+ fetchMock.mockImplementation(async (url: string) => {
+ if (String(url).includes("/internal/pool/cache-peers")) {
+ return new Response(JSON.stringify({ peers: [peer("a.example")] }), { status: 200 });
+ }
+ return popOK(voucher("mvm-x"));
+ });
+
+ await Promise.all(Array.from({ length: 100 }, () => popVoucher("https://cell", SECRET, mintToken, waitUntil)));
+ await new Promise((r) => setTimeout(r, 5));
+
+ const discoveries = fetchMock.mock.calls.filter((c) =>
+ String(c[0]).includes("/internal/pool/cache-peers"),
+ );
+ expect(discoveries.length).toBe(1);
+ });
+
+ // Rotation. The control plane publishes the replacement before retiring the
+ // incumbent, and the edge must pick it up from ordinary traffic — never by
+ // asking, which would put discovery back on a create.
+ it("learns the new instance set from the pop response", async () => {
+ _setPeersForTest([peer("old.example", 100)]);
+ fetchMock.mockResolvedValueOnce(
+ popOK(voucher("mvm-1"), [peer("old.example", 100), peer("new.example", 999)]),
+ );
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+
+ fetchMock.mockResolvedValueOnce(popOK(voucher("mvm-2")));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(String(fetchMock.mock.calls[1][0])).toContain("new.example");
+ });
+
+ it("prefers the instance furthest from retirement", async () => {
+ _setPeersForTest([peer("soon.example", 10), peer("later.example", 10_000)]);
+ fetchMock.mockResolvedValue(popOK(voucher("mvm-1")));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(String(fetchMock.mock.calls[0][0])).toContain("later.example");
+ });
+
+ // An empty instance is not a broken one — it stays in the list, because the
+ // control plane is about to refill it.
+ it("falls through to the next instance when one is stocked out", async () => {
+ _setPeersForTest([peer("a.example", 999), peer("b.example", 998)]);
+ fetchMock
+ .mockResolvedValueOnce(new Response(null, { status: 204 }))
+ .mockResolvedValueOnce(popOK(voucher("mvm-2")));
+
+ const got = await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(got?.voucher.microvmID).toBe("mvm-2");
+ expect(got?.tries).toBe(2);
+ });
+
+ it("returns null when every instance is empty, so the caller falls back", async () => {
+ _setPeersForTest([peer("a.example", 999), peer("b.example", 998)]);
+ fetchMock.mockResolvedValue(new Response(null, { status: 204 }));
+ expect(await popVoucher("https://cell", SECRET, mintToken, waitUntil)).toBeNull();
+ });
+
+ // A 502 means the box is gone (rotation raced us). Leaving it at the head of
+ // the list would make every subsequent create pay a timeout to rediscover it.
+ it("drops an instance that is gone instead of retrying it forever", async () => {
+ _setPeersForTest([peer("dead.example", 999), peer("live.example", 998)]);
+ fetchMock
+ .mockResolvedValueOnce(new Response("gone", { status: 502 }))
+ .mockResolvedValueOnce(popOK(voucher("mvm-2")));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+
+ fetchMock.mockResolvedValue(popOK(voucher("mvm-3")));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ const targets = fetchMock.mock.calls.map((c) => String(c[0]));
+ expect(targets.filter((t) => t.includes("dead.example")).length).toBe(1);
+ });
+
+ // Every failure here has to become a fall-through. A throw would take down a
+ // create that the colo book or the control plane could still have served.
+ it("never throws when the transport fails", async () => {
+ _setPeersForTest([peer("a.example")]);
+ fetchMock.mockRejectedValue(new Error("connection reset"));
+ await expect(popVoucher("https://cell", SECRET, mintToken, waitUntil)).resolves.toBeNull();
+ });
+
+ it("does not re-ask the control plane on every create when no cache exists", async () => {
+ fetchMock.mockResolvedValue(new Response(JSON.stringify({ peers: [] }), { status: 200 }));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ await new Promise((r) => setTimeout(r, 5));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ expect(fetchMock.mock.calls.length).toBe(1);
+ });
+
+ it("sends the shared secret and the proxy headers", async () => {
+ _setPeersForTest([peer("a.example")]);
+ fetchMock.mockResolvedValue(popOK(voucher("mvm-1")));
+ await popVoucher("https://cell", SECRET, mintToken, waitUntil);
+ const init = fetchMock.mock.calls[0][1] as RequestInit;
+ const h = init.headers as Record<string, string>;
+ expect(h["X-osb-cache-auth"]).toBe(SECRET);
+ expect(h["X-aws-proxy-auth"]).toBe("pt");
+ expect(h["X-aws-proxy-port"]).toBe("8079");
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/voucher_cache.ts b/cloudflare-workers/api-edge/src/voucher_cache.ts
new file mode 100644
index 00000000..b6cd0ef2
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/voucher_cache.ts
@@ -0,0 +1,318 @@
+// Client for the in-region voucher cache (cmd/voucher-cache).
+//
+// This is tier 0 of the create fast path. It replaces the colo voucher book for
+// the case the book was worst at: a cold or evicted book cost 1498ms at
+// burst-100, because the create that discovered the loss had to rebuild it from
+// the control plane in westus2. The cache cannot go cold in that sense — it is a
+// process in us-east-1 holding stock in RAM, refilled on a timer by the control
+// plane, and it answers a pop in ~13ms p50 measured from the IAD colo.
+//
+// Three things this module must never do, each learned the expensive way:
+//
+// NEVER BLOCK A CREATE ON DISCOVERY. Peer discovery rides on pop responses,
+// so the steady state costs zero extra requests. Only an isolate that has
+// never popped asks the control plane, and it asks once.
+//
+// NEVER TREAT A POP AS OWNERSHIP. A voucher is a hint that a box is probably
+// free; the guest CAS decides. That is what lets a pop be a single
+// unreplicated in-memory operation.
+//
+// NEVER THROW. Every failure here is a fall-through to the colo book and then
+// to the control-plane create, both of which are slower and correct.
+
+import { coloGet, coloPut } from "./colo_cache";
+
+export interface CachePeer {
+ endpoint: string;
+ token: string;
+ // The guest AGENT port. The AWS proxy forwards only to the port declared in
+ // the image hook config, so the cache shares the agent's listener rather than
+ // opening its own — a second port answers "403 Access to port denied".
+ port: number;
+ retireAtUnix?: number;
+}
+
+export interface CachedVoucher {
+ microvmID: string;
+ endpoint: string;
+ token: string;
+ port: number;
+ expiresAtUnix: number;
+}
+
+// Isolate-local view of the instance set. Survives as long as the isolate does,
+// which under load is many creates.
+let peers: CachePeer[] = [];
+// Single-flight for the cold discovery fetch, so 100 concurrent creates on a
+// fresh isolate make one control-plane call rather than 100 — the same stampede
+// that made a cold colo book cost 1498ms.
+let discovering: Promise<void> | null = null;
+let discoveredAt = 0;
+
+// How long a failed discovery is remembered, so a cell with no cache configured
+// does not pay a control-plane round trip on every create.
+const DISCOVERY_BACKOFF_MS = 30_000;
+
+// Colo-cache key for the peer list, and how long it lives there.
+//
+// Isolate memory alone is not enough. Measured on dev: a create landing on a
+// cold isolate spent ~400ms in popVoucher, essentially all of it asking the
+// control plane in westus2 where the cache instances are. With ~15-21 isolates
+// serving a burst of 100, that is the cold-start cost the whole design exists
+// to remove, reintroduced one layer up.
+//
+// The peer list is the RIGHT shape for the colo cache, unlike the voucher book
+// that used to live there: it is a handful of bytes, it is read-only, it is
+// identical for every isolate, and it changes once per rotation rather than
+// once per create. Eviction costs one control-plane call, not a book rebuild.
+// TTL is short relative to MaxLifetime so a retired instance ages out well
+// before it is terminated.
+const PEERS_KEY = "vcpeers";
+// Peers change only when the fleet rotates (~8h), so a short TTL buys nothing
+// and costs a lot: when this entry expires, EVERY isolate in the colo goes cold
+// at once, and a burst arriving in that window misses the cache entirely —
+// measured vpop=0 across all 100 creates of a burst that ran 7 minutes after
+// the entry was written. Stale peers are cheap (a dead one is dropped on its
+// first bad pop); an expired entry is not.
+const PEERS_TTL_SEC = 3600;
+// A same-colo read; if it is slower than this something is wrong and the book
+// is the better answer.
+const COLO_PEERS_TIMEOUT_MS = 50;
+
+// How many instances one create may try. Two: enough to ride out a single
+// instance that is retiring or momentarily empty, without turning a miss into a
+// long serial walk on a customer's create.
+const MAX_TRIES = 2;
+
+// A pop is a local operation on a warm in-region process. If it has not
+// answered in this long, something is wrong with the box, not the request, and
+// waiting longer only makes the create worse than the fallback it could have
+// taken.
+const POP_TIMEOUT_MS = 400;
+
+/** Test seam: forget the isolate's view of the fleet. */
+export function _resetCacheClientState(): void {
+ peers = [];
+ discovering = null;
+ discoveredAt = 0;
+}
+
+/** Test seam: seed the peer list without a discovery round trip. */
+export function _setPeersForTest(p: CachePeer[]): void {
+ peers = p;
+}
+
+function orderPeers(list: CachePeer[]): CachePeer[] {
+ // Prefer the instance that lives longest. During a rotation both are healthy
+ // but one is minutes from termination, and sending creates to it means a
+ // steady trickle of pops that fail exactly when it goes away.
+ return [...list].sort((a, b) => (b.retireAtUnix ?? 0) - (a.retireAtUnix ?? 0));
+}
+
+// The cheap half of discovery: what this colo already knows. Bounded so a slow
+// cache read can never become the thing that delays a create.
+async function peersFromColo(): Promise<boolean> {
+ try {
+ const cached = await withTimeout(
+ coloGet<CachePeer[]>(PEERS_KEY, "list"),
+ COLO_PEERS_TIMEOUT_MS,
+ );
+ if (Array.isArray(cached) && cached.length > 0) {
+ peers = orderPeers(cached);
+ return true;
+ }
+ } catch {
+ /* fall through to the colo book */
+ }
+ return false;
+}
+
+function withTimeout<T>(p: Promise<T>, ms: number): Promise<T | null> {
+ return Promise.race([
+ p,
+ new Promise<null>((res) => setTimeout(() => res(null), ms)),
+ ]);
+}
+
+// The expensive half: ask the control plane. Never awaited on a create — this
+// runs in waitUntil so exactly one cold isolate pays for it and every isolate
+// after it reads the colo entry instead.
+async function discoverFromCell(cellBaseURL: string, mintToken: () => Promise<string>): Promise<void> {
+ if (discovering) return discovering;
+ if (peers.length === 0 && Date.now() - discoveredAt < DISCOVERY_BACKOFF_MS) return;
+ discovering = (async () => {
+ try {
+ // Re-check the colo: another isolate may have landed it while we queued.
+ if (await peersFromColo()) return;
+ const token = await mintToken();
+ const r = await fetch(`${cellBaseURL}/internal/pool/cache-peers`, {
+ headers: { authorization: "Bearer " + token },
+ });
+ if (r.ok) {
+ const body = (await r.json()) as { peers?: CachePeer[] };
+ if (Array.isArray(body.peers) && body.peers.length > 0) {
+ peers = orderPeers(body.peers);
+ // Pay this once per colo, not once per cold isolate.
+ await coloPut(PEERS_KEY, "list", peers, PEERS_TTL_SEC);
+ }
+ }
+ } catch {
+ /* fall through to the colo book */
+ } finally {
+ discoveredAt = Date.now();
+ discovering = null;
+ }
+ })();
+ return discovering;
+}
+
+export interface Pop {
+ voucher: CachedVoucher;
+ /** Wall time of the pop that won, ms. */
+ ms: number;
+ /** How many instances were tried. 1 means uncontended. */
+ tries: number;
+ /** Peer discovery, ms. 0 once this isolate knows the fleet. */
+ discMs: number;
+}
+
+/**
+ * popVoucher takes one voucher from the in-region cache, or returns null so the
+ * caller falls through to the colo book.
+ *
+ * Null is a completely ordinary answer: no cache configured, every instance
+ * empty, or a rotation in progress.
+ */
+export async function popVoucher(
+ cellBaseURL: string,
+ secret: string,
+ mintToken: () => Promise<string>,
+ waitUntil: (p: Promise<unknown>) => void,
+): Promise<Pop | null> {
+ const t0 = Date.now();
+ // An isolate that does not yet know the fleet does NOT wait to find out.
+ //
+ // Measured on dev at burst-100: awaiting discovery here cost 336ms at p50 and
+ // pushed TTI to 1091ms. Single-flight does not help, because the flight is
+ // per-isolate: ~15-21 isolates cold-start together, all miss the colo entry
+ // before any of them has written it, and all call the control plane in
+ // westus2 at once. That is the same stampede shape the colo book needed a
+ // refill lease for.
+ //
+ // So discovery is kicked off in the background and this create falls through
+ // to the book, which is exactly what it is for. The cost is bounded and
+ // self-correcting: the first creates in a cold colo take the old path, the
+ // discovery lands in the colo cache, and every isolate after that pops.
+ let discMs = 0;
+ if (peers.length === 0) {
+ // Two sources, two very different costs, and conflating them is what made
+ // this tier dead under burst.
+ //
+ // The colo entry is a same-colo read (single-digit ms) that some earlier
+ // isolate already paid for, so it is worth awaiting. The control plane is a
+ // cross-cloud subrequest, and awaiting THAT is what cost 336ms p50 and
+ // 1091ms TTI: single-flight is per-isolate, so ~15-21 isolates cold-start
+ // together and all call the control plane at once.
+ //
+ // Measured burst-100 with both folded into the background path: vpop=0 on
+ // every create. A burst is almost entirely cold isolates, so "the first few
+ // creates take the old path" silently became "every create takes the old
+ // path" — the cache never engaged in the one case it exists for.
+ const d0 = Date.now();
+ const warmed = await peersFromColo();
+ discMs = Date.now() - d0;
+ if (!warmed) {
+ waitUntil(discoverFromCell(cellBaseURL, mintToken));
+ return null;
+ }
+ }
+
+ const candidates = orderPeers(peers).slice(0, MAX_TRIES);
+ let tries = 0;
+ for (const p of candidates) {
+ tries++;
+ try {
+ const ctl = new AbortController();
+ const timer = setTimeout(() => ctl.abort(), POP_TIMEOUT_MS);
+ let r: Response;
+ try {
+ r = await fetch(`https://${p.endpoint}/osb/cache/pop`, {
+ method: "POST",
+ headers: {
+ "X-aws-proxy-auth": p.token,
+ "X-aws-proxy-port": String(p.port),
+ "X-osb-cache-auth": secret,
+ },
+ signal: ctl.signal,
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (r.status === 204) {
+ // Stocked out. Said out loud because it is otherwise invisible: the
+ // create still succeeds on the fallback, so the only symptom is a
+ // latency regression with no error attached to it.
+ console.log(`voucher-cache EMPTY ${p.endpoint} — falling through`);
+ continue;
+ }
+ if (!r.ok) {
+ // A 502 from the AWS proxy means the box is gone; a 503 means the
+ // instance is filling. Either way this peer is not usable right now,
+ // and leaving it at the head of the list would make every create pay
+ // to rediscover that.
+ console.log(`voucher-cache BAD ${p.endpoint} status=${r.status}`);
+ peers = peers.filter((x) => x.endpoint !== p.endpoint);
+ continue;
+ }
+
+ const body = (await r.json()) as { voucher?: CachedVoucher; peers?: CachePeer[] };
+ // Rotation rides here. The control plane adds the replacement to the peer
+ // list before retiring the incumbent, so ordinary create traffic moves the
+ // edge across without anyone asking where to go.
+ if (Array.isArray(body.peers) && body.peers.length > 0) {
+ const next = orderPeers(body.peers);
+ // Only write when the set actually changed. A put per create would be
+ // pure overhead on the hot path; a put per rotation is what we want.
+ if (JSON.stringify(next) !== JSON.stringify(peers)) {
+ peers = next;
+ void coloPut(PEERS_KEY, "list", next, PEERS_TTL_SEC).catch(() => {});
+ }
+ }
+ if (!body.voucher || !body.voucher.microvmID || !body.voucher.endpoint) continue;
+ return { voucher: body.voucher, ms: Date.now() - t0, tries, discMs };
+ } catch {
+ // Timeout or transport failure. Drop it and try the next.
+ peers = peers.filter((x) => x.endpoint !== p.endpoint);
+ }
+ }
+ return null;
+}
+
+/**
+ * releaseVoucher hands a voucher back, for the narrow case where the edge drew
+ * one and then failed BEFORE any claim was attempted.
+ *
+ * Deliberately not called when a claim loses its CAS: that box is live under
+ * another sandbox, and returning it would hand a running box to a second
+ * customer. Only the box knows which case it is, so the edge releases only on
+ * its own local failures.
+ */
+export async function releaseVoucher(v: CachedVoucher, secret: string): Promise<void> {
+ const p = orderPeers(peers)[0];
+ if (!p) return;
+ try {
+ await fetch(`https://${p.endpoint}/osb/cache/release`, {
+ method: "POST",
+ headers: {
+ "X-aws-proxy-auth": p.token,
+ "X-aws-proxy-port": String(p.port),
+ "X-osb-cache-auth": secret,
+ "content-type": "application/json",
+ },
+ body: JSON.stringify(v),
+ });
+ } catch {
+ /* the cell's reconciler settles anything we fail to return */
+ }
+}
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 3732f669..5299b591 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -164,6 +164,14 @@ crons = ["*/5 * * * *"]
[vars]
WORKER_ENV = "dev"
+# Zero-subrequest edge claim for the direct-exec (lite) lane — see
+# src/voucher_book.ts. Creates are answered out of a colo-shared voucher book
+# with NO subrequest and one waitUntil; ownership is settled by a
+# compare-and-swap at the box, fused onto the first exec.
+#
+# Dev-only while it is proven under burst. PoolStock stays the path for every
+# other org, untouched.
+LITE_VOUCHER_CLAIM = "1"
# Dev override of the per-org paused-sandbox cap (prod defaults to 100) so the
# promotion path can be exercised without pausing hundreds of boxes.
PAUSED_CAP = "10"
diff --git a/cmd/microvm-hooks/claim.go b/cmd/microvm-hooks/claim.go
new file mode 100644
index 00000000..db37d3e6
--- /dev/null
+++ b/cmd/microvm-hooks/claim.go
@@ -0,0 +1,203 @@
+package main
+
+// Ownership of a box is decided HERE, in the guest, and nowhere else.
+//
+// This is the load-bearing idea behind edge claim. The edge hands out
+// "vouchers" — hints that a box is probably free — from a cache it shares with
+// every other isolate in its colo. Caches go stale, get evicted, and are read
+// concurrently by isolates that cannot see each other, so two creates CAN and
+// WILL name the same box. That is not a bug to be engineered away with
+// cross-request coordination; the two previous edge-claim attempts both died
+// trying (a Durable Object pop put a subrequest on the hot path, which is the
+// single largest term in a burst create; a per-isolate hint map fragmented
+// across cold isolates and fell back 64 times in 100).
+//
+// Instead the invariant is: a voucher confers NOTHING. It is a guess. The box
+// itself is the only authority, it answers exactly one question — "am I yours?"
+// — and it answers it under a mutex. A duplicate costs the loser one retry
+// against the next voucher. Staleness, eviction, and duplication all degrade to
+// a retry rather than to a double-owned box.
+//
+// Two properties this must have, both exercised by the tests:
+//
+// - IDEMPOTENT by sandbox ID. The edge retries; a retry that reaches a box
+// already bound to the SAME sandbox must succeed, not 409. Otherwise a
+// dropped response turns a healthy claim into a permanent failure.
+// - ATOMIC. The compare and the set happen under one lock, so two concurrent
+// claims for different sandboxes cannot both observe "free".
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ // claimPath binds this box to a sandbox ID. Must match internal/awsvmlite.
+ claimPath = "/osb/claim"
+
+ // claimAndRunPath binds and then executes in ONE round trip.
+ //
+ // Fusing them is the whole point of doing the claim on the exec leg: the
+ // first exec has to reach the box anyway, so the claim rides along for free
+ // instead of costing a second transit. A create then owes the network
+ // nothing at all.
+ claimAndRunPath = "/osb/claim-and-run"
+)
+
+// boxClaim is process-global because the claim is a property of the BOX, not of
+// any one request or connection. It lives and dies with the MicroVM.
+var boxClaim = &claimState{}
+
+type claimState struct {
+ mu sync.Mutex
+ sandboxID string
+ at time.Time
+}
+
+// claim binds this box to sandboxID.
+//
+// owned reports whether the caller may use the box. fresh distinguishes the
+// call that did the binding from an idempotent replay — the host uses it to
+// count real claims without double-counting retries.
+func (c *claimState) claim(sandboxID string) (owned, fresh bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch {
+ case c.sandboxID == "":
+ c.sandboxID, c.at = sandboxID, time.Now()
+ return true, true
+ case c.sandboxID == sandboxID:
+ // Replay. The first claim already succeeded and its response was lost,
+ // or the edge fused a claim onto a second exec. Either way the answer
+ // is the same one we gave before.
+ return true, false
+ default:
+ return false, false
+ }
+}
+
+// current reports the binding, for /healthz and host-side reconciliation.
+func (c *claimState) current() (string, time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.sandboxID, c.at
+}
+
+type claimRequest struct {
+ SandboxID string `json:"sandboxID"`
+}
+
+type claimResult struct {
+ SandboxID string `json:"sandboxID"`
+ Fresh bool `json:"fresh"`
+ // OwnedBy is set only on a 409, so the caller can tell "someone else took
+ // it" from "the box is sick" without a second request. Only our own edge
+ // can reach this port (Lambda's proxy requires the box auth token), so this
+ // is not customer-visible.
+ OwnedBy string `json:"ownedBy,omitempty"`
+}
+
+// claimAndRunRequest is a claim plus the run it is fused to. runCmdRequest is
+// embedded so the wire shape of the run half stays byte-identical to /osb/run —
+// one command shape, not two that can drift.
+type claimAndRunRequest struct {
+ SandboxID string `json:"sandboxID"`
+ runCmdRequest
+}
+
+type claimAndRunResponse struct {
+ Claim claimResult `json:"claim"`
+ Run *runCmdResponse `json:"run,omitempty"`
+}
+
+func decodeClaimBody(w http.ResponseWriter, r *http.Request, dst any) bool {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return false
+ }
+ if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(dst); err != nil {
+ http.Error(w, "bad request body", http.StatusBadRequest)
+ return false
+ }
+ return true
+}
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func (s *server) handleClaim(w http.ResponseWriter, r *http.Request) {
+ var req claimRequest
+ if !decodeClaimBody(w, r, &req) {
+ return
+ }
+ id := strings.TrimSpace(req.SandboxID)
+ if id == "" {
+ http.Error(w, "sandboxID is required", http.StatusBadRequest)
+ return
+ }
+ owned, fresh := boxClaim.claim(id)
+ if !owned {
+ owner, _ := boxClaim.current()
+ // 409 is the signal the edge retries on. It is an ordinary, expected
+ // outcome of an optimistic claim — not an error worth logging loudly.
+ writeJSON(w, http.StatusConflict, claimResult{SandboxID: id, OwnedBy: owner})
+ return
+ }
+ writeJSON(w, http.StatusOK, claimResult{SandboxID: id, Fresh: fresh})
+}
+
+func (s *server) handleClaimAndRun(w http.ResponseWriter, r *http.Request) {
+ var req claimAndRunRequest
+ if !decodeClaimBody(w, r, &req) {
+ return
+ }
+ id := strings.TrimSpace(req.SandboxID)
+ if id == "" {
+ http.Error(w, "sandboxID is required", http.StatusBadRequest)
+ return
+ }
+ owned, fresh := boxClaim.claim(id)
+ if !owned {
+ owner, _ := boxClaim.current()
+ // Claim lost: do NOT run. Running would execute a customer's command on
+ // a box owned by someone else, which is the one failure this whole
+ // design exists to make impossible.
+ writeJSON(w, http.StatusConflict, claimAndRunResponse{
+ Claim: claimResult{SandboxID: id, OwnedBy: owner},
+ })
+ return
+ }
+ // An empty cmd is a claim-only call that took this path — legal, and cheaper
+ // for the caller than a second endpoint.
+ if strings.TrimSpace(req.Cmd) == "" {
+ writeJSON(w, http.StatusOK, claimAndRunResponse{
+ Claim: claimResult{SandboxID: id, Fresh: fresh},
+ })
+ return
+ }
+ out, err := runCmd(r.Context(), req.runCmdRequest)
+ if err != nil {
+ // The claim SUCCEEDED even though the command never started, and the
+ // box is now bound. Reporting a bare 500 would tell the edge to retry
+ // elsewhere and strand this box, so the claim result goes back with it.
+ writeJSON(w, http.StatusOK, claimAndRunResponse{
+ Claim: claimResult{SandboxID: id, Fresh: fresh},
+ Run: &runCmdResponse{
+ Stderr: "could not start command: " + err.Error(),
+ ExitCode: -1,
+ },
+ })
+ return
+ }
+ writeJSON(w, http.StatusOK, claimAndRunResponse{
+ Claim: claimResult{SandboxID: id, Fresh: fresh},
+ Run: &out,
+ })
+}
diff --git a/cmd/microvm-hooks/claim_test.go b/cmd/microvm-hooks/claim_test.go
new file mode 100644
index 00000000..af0b5290
--- /dev/null
+++ b/cmd/microvm-hooks/claim_test.go
@@ -0,0 +1,152 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+)
+
+// The whole optimistic-claim design rests on this: a replay must succeed and a
+// different sandbox must not. If either flips, the edge either strands boxes on
+// dropped responses or hands one box to two customers.
+func TestClaimIsIdempotentBySandboxAndExclusiveOtherwise(t *testing.T) {
+ c := &claimState{}
+
+ owned, fresh := c.claim("sb-a")
+ if !owned || !fresh {
+ t.Fatalf("first claim: owned=%v fresh=%v, want true/true", owned, fresh)
+ }
+ // Replay of the SAME sandbox — the edge retried, or fused a claim onto a
+ // second exec. Must succeed, and must not be reported as a new binding.
+ owned, fresh = c.claim("sb-a")
+ if !owned || fresh {
+ t.Fatalf("replay: owned=%v fresh=%v, want true/false", owned, fresh)
+ }
+ // A DIFFERENT sandbox must lose, forever.
+ if owned, _ := c.claim("sb-b"); owned {
+ t.Fatal("second sandbox won a claim on an already-bound box")
+ }
+ if got, _ := c.current(); got != "sb-a" {
+ t.Fatalf("binding drifted to %q", got)
+ }
+}
+
+// Concurrency is the case the mutex exists for: N racing claims for N distinct
+// sandboxes must produce exactly one winner.
+func TestClaimRaceHasExactlyOneWinner(t *testing.T) {
+ c := &claimState{}
+ const n = 64
+ var wg sync.WaitGroup
+ wins := make([]bool, n)
+ start := make(chan struct{})
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ <-start
+ owned, fresh := c.claim(string(rune('a'+i%26)) + "-" + itoa(i))
+ wins[i] = owned && fresh
+ }(i)
+ }
+ close(start)
+ wg.Wait()
+ got := 0
+ for _, w := range wins {
+ if w {
+ got++
+ }
+ }
+ if got != 1 {
+ t.Fatalf("fresh winners = %d, want exactly 1", got)
+ }
+}
+
+func itoa(i int) string {
+ if i == 0 {
+ return "0"
+ }
+ var b []byte
+ for i > 0 {
+ b = append([]byte{byte('0' + i%10)}, b...)
+ i /= 10
+ }
+ return string(b)
+}
+
+func postJSON(t *testing.T, h http.HandlerFunc, body any) *httptest.ResponseRecorder {
+ t.Helper()
+ buf, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := httptest.NewRecorder()
+ h(rec, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(buf)))
+ return rec
+}
+
+// A lost claim must NOT run the command. Running it would execute a customer's
+// command on someone else's box.
+func TestClaimAndRunDoesNotExecuteWhenClaimIsLost(t *testing.T) {
+ prev := boxClaim
+ boxClaim = &claimState{}
+ defer func() { boxClaim = prev }()
+
+ s := &server{}
+ if rec := postJSON(t, s.handleClaim, claimRequest{SandboxID: "sb-owner"}); rec.Code != http.StatusOK {
+ t.Fatalf("seed claim: status %d", rec.Code)
+ }
+
+ rec := postJSON(t, s.handleClaimAndRun, map[string]any{
+ "sandboxID": "sb-intruder",
+ "cmd": "echo SHOULD_NOT_RUN",
+ })
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("status = %d, want 409", rec.Code)
+ }
+ var out claimAndRunResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ if out.Run != nil {
+ t.Fatalf("command ran despite a lost claim: %+v", out.Run)
+ }
+ if out.Claim.OwnedBy != "sb-owner" {
+ t.Fatalf("ownedBy = %q, want sb-owner", out.Claim.OwnedBy)
+ }
+}
+
+// The happy path: one round trip both binds the box and returns the output.
+func TestClaimAndRunFusesBindAndExec(t *testing.T) {
+ prev := boxClaim
+ boxClaim = &claimState{}
+ defer func() { boxClaim = prev }()
+
+ s := &server{}
+ rec := postJSON(t, s.handleClaimAndRun, map[string]any{
+ "sandboxID": "sb-fused",
+ "cmd": "echo hello-fused",
+ })
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body %s)", rec.Code, rec.Body.String())
+ }
+ var out claimAndRunResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+ t.Fatal(err)
+ }
+ if !out.Claim.Fresh {
+ t.Fatal("first fused claim was not reported as fresh")
+ }
+ if out.Run == nil || out.Run.ExitCode != 0 {
+ t.Fatalf("run result = %+v, want exit 0", out.Run)
+ }
+ if got := out.Run.Stdout; got != "hello-fused\n" {
+ t.Fatalf("stdout = %q", got)
+ }
+ // And the fused claim is visible to the host's reconciliation read.
+ if got, _ := boxClaim.current(); got != "sb-fused" {
+ t.Fatalf("binding = %q", got)
+ }
+}
diff --git a/cmd/microvm-hooks/main.go b/cmd/microvm-hooks/main.go
index a4f9998c..324dda94 100644
--- a/cmd/microvm-hooks/main.go
+++ b/cmd/microvm-hooks/main.go
@@ -41,6 +41,8 @@ import (
"google.golang.org/grpc/credentials/insecure"
pb "github.com/opensandbox/opensandbox/proto/agent"
+
+ "github.com/opensandbox/opensandbox/internal/vouchercache"
)
const (
@@ -76,6 +78,9 @@ const (
// runCmdPath executes one command and returns its result as ordinary JSON.
// Must match internal/awsvmlite.
runCmdPath = "/osb/run"
+ // cachePath is the prefix the voucher cache mounts under. Trailing slash:
+ // its routes are cachePath+"pop", +"fill", +"release", +"stats".
+ cachePath = "/osb/cache/"
)
// runCmdRequest / runCmdResponse are the whole protocol of the direct exec path.
@@ -156,6 +161,11 @@ type server struct {
// a restored snapshot rather than a fresh boot.
var startedAt = time.Now()
+// vcache is the in-region voucher cache this box serves, when it is being used
+// as a cache instance. Every box carries the code; only the ones the control
+// plane fills ever hold stock.
+var vcache *vouchercache.Server
+
func main() {
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
log.Printf("microvm-hooks: starting (pid=%d)", os.Getpid())
@@ -189,14 +199,25 @@ func main() {
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
- _ = json.NewEncoder(w).Encode(map[string]any{
+ // The binding, reported so the CP's existing keepalive sweep can learn
+ // who owns each box WITHOUT the edge telling it. That makes host-side
+ // bookkeeping self-healing: a finalize message that never arrives is
+ // reconciled on the next touch instead of stranding the box.
+ claimedBy, claimedAt := boxClaim.current()
+ h := map[string]any{
"agentUp": agentUp(),
"agentPid": pid,
"agentAddr": agentAddr,
"microvmId": id,
"ranRunHook": id != "",
"uptimeSec": int(time.Since(startedAt).Seconds()),
- })
+ "claimed": claimedBy != "",
+ }
+ if claimedBy != "" {
+ h["claimedBy"] = claimedBy
+ h["claimedAtUnix"] = claimedAt.Unix()
+ }
+ _ = json.NewEncoder(w).Encode(h)
})
// Diagnostic: emit an UNANNOUNCED HTTP/2 trailer, the way gRPC sends
@@ -252,6 +273,20 @@ func main() {
// be forwarded to osb-agent's gRPC listener, which answers a JSON POST with
// 415 and no explanation.
mux.HandleFunc(runCmdPath, s.handleRunCmd)
+ // Edge claim. See claim.go: the box is the only authority on who owns it,
+ // so these are the endpoints that actually decide it.
+ // In-region voucher cache (internal/vouchercache). Mounted on the agent's
+ // own listener because the AWS proxy forwards only to the port declared in
+ // the image hook config — a standalone service on a second port answers
+ // "403 Access to port denied", which is how this ended up here.
+ //
+ // Unauthenticated for the same reason /osb/run and /osb/claim are: reaching
+ // this box at all requires the per-box proxy JWE, which only the control
+ // plane and the edge hold. OSB_CACHE_SECRET adds a second factor when set.
+ vcache = vouchercache.New(os.Getenv("OSB_CACHE_SECRET"))
+ vcache.Mount(mux, cachePath)
+ mux.HandleFunc(claimPath, s.handleClaim)
+ mux.HandleFunc(claimAndRunPath, s.handleClaimAndRun)
// Everything that is not a hook is forwarded to osb-agent.
//
@@ -403,6 +438,28 @@ func (s *server) handleRunCmd(w http.ResponseWriter, r *http.Request) {
return
}
+ out, err := runCmd(r.Context(), req)
+ if err != nil {
+ // Never started: no binary, no fork, nothing to report an exit code for.
+ http.Error(w, "could not start command: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(out)
+}
+
+// runCmd executes one command and reports the result.
+//
+// Split out of handleRunCmd so /osb/claim-and-run runs commands through the
+// EXACT same path rather than a second copy that can drift — the fused endpoint
+// differs from the plain one only in what it does before the command, never in
+// how the command runs.
+//
+// A non-nil error means the command never started (no binary, fork failure).
+// That is the only case a caller has to decide about; a command that ran and
+// exited non-zero is a result, and comes back in the response with its code.
+func runCmd(reqCtx context.Context, req runCmdRequest) (runCmdResponse, error) {
timeout := runCmdDefaultTimeout
if req.TimeoutSec > 0 {
timeout = time.Duration(req.TimeoutSec) * time.Second
@@ -412,7 +469,7 @@ func (s *server) handleRunCmd(w http.ResponseWriter, r *http.Request) {
}
// Bound by the request's context too, so a caller that gives up does not
// leave the command running in the guest.
- ctx, cancel := context.WithTimeout(r.Context(), timeout)
+ ctx, cancel := context.WithTimeout(reqCtx, timeout)
defer cancel()
// `sh -lc` matches what the agent's exec does, so a command behaves the same
@@ -454,14 +511,9 @@ func (s *server) handleRunCmd(w http.ResponseWriter, r *http.Request) {
// Ran and exited non-zero — a result, not an error.
resp.ExitCode = cmd.ProcessState.ExitCode()
default:
- // Never started: no binary, no fork, nothing to report an exit code for.
- http.Error(w, "could not start command: "+runErr.Error(), http.StatusInternalServerError)
- return
+ return runCmdResponse{}, runErr
}
-
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusOK)
- _ = json.NewEncoder(w).Encode(resp)
+ return resp, nil
}
// cappedBuffer accumulates up to limit bytes and silently discards the rest.
diff --git a/internal/api/backend.go b/internal/api/backend.go
index 1ca7fcf4..5308f9fe 100644
--- a/internal/api/backend.go
+++ b/internal/api/backend.go
@@ -2,6 +2,8 @@ package api
import (
"context"
+ "sync"
+ "time"
"github.com/google/uuid"
@@ -420,12 +422,82 @@ func (s *Server) claimBackend(p placement) (Placer, bool) {
// come through the edge. That resolves to the QEMU fleet, which is the only
// safe default: a create whose runtime we cannot establish must land on the
// backend that can serve anything, never on a specialised one.
-func runtimeFor(c echo.Context) string {
+func (s *Server) runtimeFor(c echo.Context) string {
claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)
- if claims == nil {
+ if claims != nil && claims.Runtime != "" {
+ return claims.Runtime
+ }
+ // No cap-token: this is the direct-to-cell create, authenticated with an
+ // API key against this cell rather than through the edge. D1 is still
+ // authoritative on org runtime, but there is no token here carrying it, so
+ // read the copy synced from the last cap-token create.
+ //
+ // Deliberately per-ORG, not per-cell. A cell-wide default would divert
+ // every unlabeled create — including QEMU orgs that simply have no runtime
+ // set — onto whichever backend the cell happened to prefer. Keying on the
+ // org means QEMU stays the default for everyone and orgs move over one at
+ // a time by setting this column.
+ orgID, ok := auth.GetOrgID(c)
+ if !ok || orgID == uuid.Nil || s.store == nil {
+ return ""
+ }
+ if rt, ok := s.orgRuntime.get(orgID); ok {
+ return rt
+ }
+ rt, err := s.store.GetOrgRuntime(c.Request().Context(), orgID)
+ if err != nil {
+ // Unknown runtime resolves to QEMU, the backend that serves anything.
return ""
}
- return claims.Runtime
+ s.orgRuntime.put(orgID, rt)
+ return rt
+}
+
+// orgRuntimeTTL bounds how long a runtime flip in Postgres takes to reach this
+// cell's create path. Short enough to move an org over without a restart, long
+// enough that a burst does not re-read the same row 100 times.
+const orgRuntimeTTL = 30 * time.Second
+
+// orgRuntimeCache is a small TTL memo in front of the orgs.runtime read.
+//
+// The read is local Postgres and cheap, but it sits on the create path and a
+// burst asks the same question for the same org every time. The TTL is what
+// bounds how long a runtime flip takes to take effect on this cell.
+type orgRuntimeCache struct {
+ mu sync.Mutex
+ ttl time.Duration
+ m map[uuid.UUID]orgRuntimeEntry
+}
+
+type orgRuntimeEntry struct {
+ runtime string
+ expires time.Time
+}
+
+func newOrgRuntimeCache(ttl time.Duration) *orgRuntimeCache {
+ return &orgRuntimeCache{ttl: ttl, m: map[uuid.UUID]orgRuntimeEntry{}}
+}
+
+func (c *orgRuntimeCache) get(orgID uuid.UUID) (string, bool) {
+ if c == nil {
+ return "", false
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ e, ok := c.m[orgID]
+ if !ok || time.Now().After(e.expires) {
+ return "", false
+ }
+ return e.runtime, true
+}
+
+func (c *orgRuntimeCache) put(orgID uuid.UUID, runtime string) {
+ if c == nil {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.m[orgID] = orgRuntimeEntry{runtime: runtime, expires: time.Now().Add(c.ttl)}
}
// canPlace reports whether any registered backend would take a create for this
diff --git a/internal/api/backend_gating_test.go b/internal/api/backend_gating_test.go
index 54b7f00e..328360e8 100644
--- a/internal/api/backend_gating_test.go
+++ b/internal/api/backend_gating_test.go
@@ -1,13 +1,24 @@
package api
import (
+ "net/http"
+ "net/http/httptest"
"testing"
+ "time"
"github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/pkg/types"
)
+// newTestEchoContext builds a bare echo context for handler-free unit tests.
+func newTestEchoContext() echo.Context {
+ req := httptest.NewRequest(http.MethodPost, "/api/sandboxes", nil)
+ return echo.New().NewContext(req, httptest.NewRecorder())
+}
+
// backend_gating_test.go — which runtime serves a create, and the one-way street.
//
// Assignment lives in D1 orgs.runtime and reaches the cell on the capability
@@ -145,3 +156,48 @@ func TestOrgIDAloneDoesNotDecidePlacement(t *testing.T) {
t.Error("an assigned org was declined")
}
}
+
+// runtimeFor resolves the runtime for a create. The cap-token path is the
+// normal one; the direct-to-cell path (API key straight at this CP, no edge)
+// has no token and must fall back to the per-org column without ever turning
+// into a cell-wide default — that would divert unassigned QEMU orgs onto a
+// specialised backend, which is exactly what the gating above forbids.
+func TestRuntimeForPrefersTheCapToken(t *testing.T) {
+ s := &Server{orgRuntime: newOrgRuntimeCache(orgRuntimeTTL)}
+ c := newTestEchoContext()
+ c.Set(capClaimsKey, &auth.CapabilityClaims{Runtime: runtimeMicrovm})
+
+ if got := s.runtimeFor(c); got != runtimeMicrovm {
+ t.Fatalf("cap-token runtime ignored: got %q, want %q", got, runtimeMicrovm)
+ }
+}
+
+// The safety property: no token and no store to consult resolves to the fleet,
+// never to a specialised backend. A regression here sends every unlabeled
+// create — including ordinary QEMU orgs — onto the MicroVM lane.
+func TestRuntimeForWithoutTokenOrStoreIsTheFleet(t *testing.T) {
+ s := &Server{orgRuntime: newOrgRuntimeCache(orgRuntimeTTL)}
+ c := newTestEchoContext()
+ auth.SetOrgID(c, uuid.New())
+
+ if got := s.runtimeFor(c); got != "" {
+ t.Fatalf("unlabeled create did not resolve to the fleet: got %q", got)
+ }
+}
+
+func TestOrgRuntimeCacheExpires(t *testing.T) {
+ cache := newOrgRuntimeCache(-1 * time.Second) // already expired on write
+ org := uuid.New()
+ cache.put(org, runtimeMicrovm)
+
+ if _, ok := cache.get(org); ok {
+ t.Error("expired entry served — a runtime flip would never take effect")
+ }
+
+ fresh := newOrgRuntimeCache(time.Minute)
+ fresh.put(org, runtimeMicrovm)
+ got, ok := fresh.get(org)
+ if !ok || got != runtimeMicrovm {
+ t.Errorf("live entry not served: got %q ok=%v", got, ok)
+ }
+}
diff --git a/internal/api/create_flow.go b/internal/api/create_flow.go
index b1fc42d3..ac8e5eaa 100644
--- a/internal/api/create_flow.go
+++ b/internal/api/create_flow.go
@@ -125,6 +125,9 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
return "", fmt.Errorf("create: activate %s on %s: %w", sandboxID, workerID, aerr)
}
}
+ // Deferred: the durable writes are off the response, so what this mark
+ // measures is the handoff, not the database.
+ tr.mark("deferpersist")
go persistAfterResponse(sandboxID, workerID, steps)
return workerID, nil
}
@@ -133,6 +136,7 @@ func runCreate(ctx context.Context, sandboxID string, steps createSteps) (worker
t = time.Now()
err := steps.persist(ctx, workerID)
persistMs = time.Since(t).Milliseconds()
+ tr.mark("persist")
if err != nil {
if steps.persistRequired {
// Nothing else knows this host exists, so continuing would hand
diff --git a/internal/api/create_trace.go b/internal/api/create_trace.go
index e31cc7cf..b3527895 100644
--- a/internal/api/create_trace.go
+++ b/internal/api/create_trace.go
@@ -8,6 +8,10 @@ import (
"strings"
"sync"
"time"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/reqtime"
)
// create_trace.go — per-create step timing, for finding serialization.
@@ -123,6 +127,59 @@ func (t *createTrace) emit() {
log.Print(b.String())
}
+// serverTiming renders the marks as a Server-Timing header value.
+//
+// The log line is the right shape for reading one request; it is the wrong
+// shape for a benchmark, which has to attribute a p50 across a hundred of
+// them. The direct-to-cell path made that gap obvious: with no edge Worker in
+// front, every harness column that came from Server-Timing read 0, so a 483ms
+// exec was a single opaque number with no way to tell a slow dial from a
+// burned inline hold.
+//
+// Durations are milliseconds because that is what Server-Timing specifies and
+// what the harness parses; the log line keeps microsecond resolution.
+func (t *createTrace) serverTiming() string {
+ if t == nil {
+ return ""
+ }
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ var b strings.Builder
+ fmt.Fprintf(&b, "tot;dur=%d", time.Since(t.start).Milliseconds())
+ for _, m := range t.marks {
+ fmt.Fprintf(&b, ", %s;dur=%d", m.label, m.dur.Milliseconds())
+ }
+ return b.String()
+}
+
+// emitServerTiming arranges for this trace to ride out on the response.
+//
+// Registered as a Before hook rather than written at each return: these
+// handlers have several exits (inline fold, handle shape, and every error
+// path), and a header set at only some of them is worse than none — the
+// missing ones read as zero rather than as absent.
+func (t *createTrace) emitServerTiming(c echo.Context) {
+ if t == nil {
+ return
+ }
+ c.Response().Before(func() {
+ v := t.serverTiming()
+ if v == "" {
+ return
+ }
+ // gotot brackets the entire middleware chain, so gotot minus tot is
+ // everything Go did before the handler was entered — auth above all.
+ // Without it a handler that reports tot=0 while the client measures
+ // 200ms is unattributable: the time is either upstream of the handler
+ // or upstream of Go itself, and those need opposite fixes.
+ if rt := reqtime.From(c); rt != nil {
+ v = fmt.Sprintf("gotot;dur=%d, auth;dur=%d, ",
+ rt.Since().Milliseconds(), rt.Auth().Milliseconds()) + v
+ }
+ c.Response().Header().Set("Server-Timing", v)
+ })
+}
+
func withCreateTrace(ctx context.Context, t *createTrace) context.Context {
if t == nil {
return ctx
diff --git a/internal/api/create_trace_timing_test.go b/internal/api/create_trace_timing_test.go
new file mode 100644
index 00000000..5393f3f1
--- /dev/null
+++ b/internal/api/create_trace_timing_test.go
@@ -0,0 +1,65 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/labstack/echo/v4"
+)
+
+// The direct-to-cell path has no edge Worker in front of it, so Server-Timing
+// from the CP is the only per-step attribution a benchmark can see. A burst
+// there reported exec p50 483ms as one opaque number.
+func TestServerTimingCarriesEveryMark(t *testing.T) {
+ if !createTraceEnabled {
+ t.Skip("tracing compiled off; serverTiming is nil-safe and returns empty")
+ }
+ tr := newTrace("exectrace")
+ tr.mark("session")
+ tr.mark("hold")
+
+ got := tr.serverTiming()
+ for _, want := range []string{"tot;dur=", "session;dur=", "hold;dur="} {
+ if !strings.Contains(got, want) {
+ t.Errorf("Server-Timing missing %q: %s", want, got)
+ }
+ }
+}
+
+// A nil trace is the tracing-disabled case and must stay safe at every call
+// site, since the emitters are called unconditionally.
+func TestNilTraceEmitsNothing(t *testing.T) {
+ var tr *createTrace
+ if got := tr.serverTiming(); got != "" {
+ t.Errorf("nil trace produced a header: %q", got)
+ }
+
+ rec := httptest.NewRecorder()
+ c := echo.New().NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
+ tr.emitServerTiming(c) // must not panic
+ c.NoContent(http.StatusOK)
+ if v := rec.Header().Get("Server-Timing"); v != "" {
+ t.Errorf("nil trace set a header: %q", v)
+ }
+}
+
+// The header has to be set on EVERY exit, which is why it is a Before hook
+// rather than a write at each return.
+func TestServerTimingSetOnResponse(t *testing.T) {
+ if !createTraceEnabled {
+ t.Skip("tracing compiled off")
+ }
+ rec := httptest.NewRecorder()
+ c := echo.New().NewContext(httptest.NewRequest(http.MethodPost, "/", nil), rec)
+
+ tr := newTrace("exectrace")
+ tr.emitServerTiming(c)
+ tr.mark("session")
+ c.NoContent(http.StatusAccepted)
+
+ if v := rec.Header().Get("Server-Timing"); !strings.Contains(v, "session;dur=") {
+ t.Errorf("marks recorded after the hook was registered were lost: %q", v)
+ }
+}
diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.go
index 40d34b09..4bc6822f 100644
--- a/internal/api/edge_claim.go
+++ b/internal/api/edge_claim.go
@@ -250,6 +250,9 @@ func (s *Server) claimFinalize(c echo.Context) error {
var req struct {
types.SandboxConfig
SandboxID string `json:"sandboxID"`
+ // Voucher creates only. The edge minted the sandbox id, so it has to say
+ // which box that sandbox drew — nothing here can look it up.
+ MicrovmID string `json:"microvmID"`
}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
@@ -279,6 +282,67 @@ func (s *Server) claimFinalize(c echo.Context) error {
cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
metadataJSON, _ := json.Marshal(cfg.Metadata)
+ // Voucher stock: the edge answered this create out of a local book without
+ // calling us at all, so there is no reservation to find — the binding
+ // arrives here, in this request, or it never happens.
+ //
+ // Without this branch the request fell through to ClaimReservedSession,
+ // which looks for a reserved ROW a voucher create never writes. On dev that
+ // was 473 consecutive "FINALIZE LOST" and zero successes: every create
+ // returned a sandbox id with no row behind it, so every exec 404'd while the
+ // cell sat at bound=0. Create looked perfect and nothing worked.
+ if req.MicrovmID != "" {
+ if vb, ok := s.voucherRedeemer(); ok {
+ workerID, rebound, err := vb.RedeemVoucher(req.MicrovmID, cfg.SandboxID, cfg)
+ if err != nil {
+ log.Printf("sandbox: VOUCHER FINALIZE LOST %s box=%s (%v)", cfg.SandboxID, req.MicrovmID, err)
+ finalizeErr = err
+ return c.JSON(http.StatusConflict, map[string]string{"error": "voucher lost"})
+ }
+ template := cfg.Template
+ if template == "" {
+ template = "default"
+ }
+ if s.store != nil && rebound {
+ // The row already exists and names the box the CREATE drew. The
+ // exec ladder moved this sandbox elsewhere, so correct the row
+ // instead of inserting a second one — leaving it would point a
+ // destroy at a box belonging to someone else.
+ if err := s.store.UpdateSandboxSessionWorker(ctx, cfg.SandboxID, workerID); err != nil {
+ log.Printf("sandbox: voucher rebind %s → %s failed: %v", cfg.SandboxID, workerID, err)
+ finalizeErr = err
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ s.emitEvent("create", cfg.SandboxID, workerID, "rebound to another box (edge)")
+ finalizeErr = nil
+ return c.JSON(http.StatusOK, map[string]string{
+ "sandboxID": cfg.SandboxID,
+ "workerID": workerID,
+ "status": "running",
+ })
+ }
+ 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 box is live and the customer already holds its id, so
+ // failing here does not take it back. Report it and let the
+ // orphan sweep reclaim a box with no row.
+ log.Printf("sandbox: voucher finalize row insert %s failed: %v", cfg.SandboxID, err)
+ finalizeErr = err
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ }
+ s.emitEvent("create", cfg.SandboxID, workerID, "claimed from voucher (edge)")
+ finalizeErr = nil
+ return c.JSON(http.StatusOK, map[string]string{
+ "sandboxID": cfg.SandboxID,
+ "workerID": workerID,
+ "status": "running",
+ })
+ }
+ log.Printf("sandbox: VOUCHER FINALIZE LOST %s box=%s (this cell does not serve vouchers)", cfg.SandboxID, req.MicrovmID)
+ }
+
// 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
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 69dd507b..e15890f3 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -363,7 +363,17 @@ func (s *Server) execRunAsyncRoute(c echo.Context) error {
// the SDK short-circuit its poll loop — the same contract as the worker path's
// inline-hold fast path, reached without the hold.
func (s *Server) execRunMicrovm(c echo.Context, mgr sandbox.Manager, sandboxID string, req types.ProcessConfig) error {
+ // This path, not execRunAsync, is what a MicroVM exec actually runs — which
+ // is why the exec leg produced no Server-Timing at all while it was the
+ // larger half of TTI, and why the inline hold could not have been costing
+ // anything here: there is no hold on this path to burn.
+ tr := newExecTrace()
+ tr.setSandboxID(sandboxID)
+ tr.emitServerTiming(c)
+ defer tr.emit()
+
res, err := mgr.Exec(c.Request().Context(), sandboxID, req)
+ tr.mark("mgrexec")
if err != nil {
log.Printf("microvm: exec %s failed: %v", sandboxID, err)
return respondManagerErr(c, err)
@@ -371,6 +381,7 @@ func (s *Server) execRunMicrovm(c echo.Context, mgr sandbox.Manager, sandboxID s
if s.router != nil {
s.router.Touch(sandboxID) // keep the idle timer honest, as the worker path does
}
+ tr.mark("touch")
return c.JSON(http.StatusOK, types.ExecRunResult{
Running: false,
ExitCode: &res.ExitCode,
@@ -451,6 +462,7 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
// `enter` separates "this handler is slow" from "the queue is upstream".
tr := newExecTrace()
tr.setSandboxID(id)
+ tr.emitServerTiming(c)
defer tr.emit()
var session *sandbox.ExecSessionHandle
@@ -523,6 +535,7 @@ func (s *Server) execResult(c echo.Context) error {
// retry ladder went.
tr := newTrace("resulttrace")
tr.setSandboxID(id)
+ tr.emitServerTiming(c)
defer tr.emit()
var res *types.ExecSessionResult
diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.go
index 63515e5a..f77a322f 100644
--- a/internal/api/internal_sandbox.go
+++ b/internal/api/internal_sandbox.go
@@ -101,9 +101,9 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
// The key carries the plan and provider, so a change to either misses the
// memo and writes through immediately instead of waiting out the TTL.
tr.mark("pre")
- orgKey := "org:" + orgID.String() + ":" + claims.Plan + ":" + claims.BillingProvider
+ orgKey := "org:" + orgID.String() + ":" + claims.Plan + ":" + claims.BillingProvider + ":" + claims.Runtime
if upErr := s.materialize.ensure(c.Request().Context(), orgKey, func(ctx context.Context) error {
- return s.store.UpsertOrgFromCapToken(ctx, orgID, claims.Plan, claims.BillingProvider)
+ return s.store.UpsertOrgFromCapToken(ctx, orgID, claims.Plan, claims.BillingProvider, claims.Runtime)
}); upErr != nil {
// Non-fatal — the create may still succeed; downstream gates fall through
// when the row is missing. Logged so ops can investigate persistent failures.
diff --git a/internal/api/lite_backend.go b/internal/api/lite_backend.go
index ad1aff83..70563e20 100644
--- a/internal/api/lite_backend.go
+++ b/internal/api/lite_backend.go
@@ -52,6 +52,9 @@ type liteBackend struct {
// dispatch through. One instance, shared: it holds no state of its own.
sm *awsvmlite.SandboxManager
+ // cache is the in-region voucher cache fleet, nil when not configured.
+ cache *awsvmlite.CacheFleet
+
stopRun context.CancelFunc
usageTicker *worker.UsageTicker
eventPub *worker.RedisEventPublisher
@@ -83,6 +86,20 @@ func newLiteBackend(ctx context.Context) (*liteBackend, error) {
b := &liteBackend{client: client, mgr: mgr, sm: awsvmlite.NewSandboxManager(mgr), stopRun: stop}
go mgr.Run(runCtx)
+ // In-region voucher cache (see awsvmlite/cache_fleet.go). Opt-in: without a
+ // binary URL there is nothing to install, and the edge falls back to the
+ // colo book exactly as before.
+ if os.Getenv("OPENSANDBOX_VOUCHER_CACHE") == "1" {
+ b.cache = awsvmlite.NewCacheFleet(mgr, awsvmlite.CacheConfig{
+ Enabled: true,
+ Replicas: envInt("OPENSANDBOX_VOUCHER_CACHE_REPLICAS", 2),
+ Target: envInt("OPENSANDBOX_VOUCHER_CACHE_TARGET", warm),
+ FillInterval: time.Duration(
+ envInt("OPENSANDBOX_VOUCHER_CACHE_FILL_SECONDS", 10)) * time.Second,
+ })
+ go b.cache.Run(runCtx)
+ }
+
log.Printf("vmhost-lite: backend enabled (region=%s warm=%d) — direct exec, no agent tunnel",
client.Config().Region, warm)
return b, nil
@@ -478,3 +495,50 @@ func (b *liteBackend) Status() map[string]any {
// cell's Postgres pool is not its supply. See SelfStocking — consulting that
// pool for these creates measured 49-78ms of guaranteed miss per create.
func (b *liteBackend) ServesOwnStock() bool { return true }
+
+// Vouchers promises warm boxes to one colo so the edge can answer creates out of
+// a local cache instead of calling this process. See voucher_claim.go.
+func (b *liteBackend) Vouchers(colo string, n int) []awsvmlite.Voucher {
+ if b == nil || b.mgr == nil {
+ return nil
+ }
+ return b.mgr.Vouchers(colo, n)
+}
+
+// RedeemVoucher binds a voucher-created sandbox to the box it drew.
+//
+// This is the bookkeeping half of a zero-subrequest create, and until it existed
+// the voucher path had no bookkeeping at all: finalize fell through to
+// ClaimReservedSession, which looks for a reserved ROW that a voucher create
+// never writes. Measured on dev as 473 consecutive "EDGE CLAIM FINALIZE LOST"
+// against zero successes, with the cell reporting bound=0 while a hundred
+// customers held sandbox ids — every one of them unusable, because the row that
+// makes a sandbox exist was never written.
+//
+// Keyed by box, because the box is the only identity a voucher has: the sandbox
+// id was minted at the edge and this process is seeing it for the first time.
+// The `rebound` return says this sandbox was already bound to a DIFFERENT box
+// and has just been moved — the caller has a row to correct, not one to insert.
+func (b *liteBackend) RedeemVoucher(microvmID, sandboxID string, cfg types.SandboxConfig) (string, bool, error) {
+ if b == nil || b.mgr == nil {
+ return "", false, errors.New("vmhost-lite: backend disabled")
+ }
+ box, ok, rebound := b.mgr.RedeemVoucher(microvmID, sandboxID, awsvmlite.Meta{
+ Template: cfg.Template,
+ MemoryMB: cfg.MemoryMB,
+ CPUCount: cfg.CpuCount,
+ })
+ if !ok {
+ return "", false, errors.New("vmhost-lite: no voucher outstanding for box " + microvmID)
+ }
+ return microvmWorkerID(box.MicrovmID), rebound, nil
+}
+
+// CachePeers reports the in-region voucher cache instances the edge may pop
+// from. Empty when no cache is configured or none has finished filling.
+func (b *liteBackend) CachePeers() []awsvmlite.CachePeer {
+ if b == nil || b.cache == nil {
+ return nil
+ }
+ return b.cache.Peers()
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index e757f882..48c4addf 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -29,6 +29,7 @@ import (
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
+ "github.com/opensandbox/opensandbox/internal/reqtime"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
"github.com/opensandbox/opensandbox/internal/wsgateway"
@@ -84,6 +85,7 @@ type Server struct {
microvm *microvmBackend // managed-host backend; nil unless enabled (see microvm_backend.go)
lite *liteBackend // direct-exec managed-host backend; mutually exclusive with microvm (see lite_backend.go)
materialize *materializer // memoizes per-org/user row creation off the create hot path (materialize.go)
+ orgRuntime *orgRuntimeCache // memoizes orgs.runtime for the direct-to-cell create path (backend.go)
templateCache *templateCache // caches name→template so create doesn't call the edge every time (template_cache.go)
// backends is the dispatch set for placement and routing (see backend.go).
// The worker path is deliberately absent — it is reached by falling through.
@@ -228,6 +230,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
manager: mgr,
ptyManager: ptyMgr,
materialize: newMaterializer(materializeTTL),
+ orgRuntime: newOrgRuntimeCache(orgRuntimeTTL),
templateCache: newTemplateCache(),
}
// Mount service is only useful in combined mode (this process owns the
@@ -301,6 +304,8 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// is on the response by the time obslog reads it. obslog replaces Echo's
// built-in Logger() — same access log line, but JSON with the host
// envelope and request_id/sandbox_id pulled from context.
+ // Outermost, so it brackets the whole chain including auth.
+ e.Use(reqtime.Middleware())
e.Use(observability.EchoMiddleware())
e.Use(middleware.Recover())
e.Use(middleware.RequestID())
@@ -410,6 +415,14 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
internal.POST("/pool/edge-reserve", s.edgeReservePool)
internal.POST("/pool/edge-release", s.edgeReleasePool)
internal.POST("/sandboxes/claim-finalize", s.claimFinalize)
+ // Zero-subrequest edge claim (see voucher_claim.go): the edge pulls a
+ // book of pre-paired boxes per colo OFF the hot path, then answers
+ // creates locally. Never on a customer's critical path.
+ internal.GET("/pool/vouchers", s.publishVouchers)
+ // Cold-start discovery for the in-region voucher cache. Steady-state
+ // discovery rides on pop responses, so this is hit once per cold
+ // isolate rather than once per create.
+ internal.GET("/pool/cache-peers", s.publishCachePeers)
// Direct-path seam (see microvm_direct.go): lets the edge dial a
// MicroVM's agent itself instead of relaying exec through this process.
internal.GET("/microvm/direct/:id", s.microvmDirectInfo)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index cebe34b2..1b2f8e23 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -56,6 +56,17 @@ func shouldPromoteCheckpoint(kind string, promoteToFull *bool) bool {
}
func (s *Server) createSandbox(c echo.Context) error {
+ // The direct-to-cell create had no trace at all: it was built as the
+ // legacy/combined-mode entrypoint, and every measured create came through
+ // internalCreateSandbox instead. Now that the SDK can talk straight to a
+ // cell, this is the hot path and needs the same per-step attribution —
+ // createSandboxRemote's marks already exist and only need a trace in the
+ // context to land on.
+ tr := newCreateTrace()
+ tr.emitServerTiming(c)
+ defer tr.emit()
+ c.SetRequest(c.Request().WithContext(withCreateTrace(c.Request().Context(), tr)))
+
var cfg types.SandboxConfig
if err := c.Bind(&cfg); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{
@@ -189,7 +200,7 @@ func (s *Server) createSandbox(c echo.Context) error {
// condition is backend registration, not the worker registry: a cell served
// by a backend has no registry and no local manager, so gating on the
// registry made every create there fail with "server-only mode".
- if s.canPlace(uuid.UUID(orgID), runtimeFor(c), cfg) {
+ if s.canPlace(uuid.UUID(orgID), s.runtimeFor(c), cfg) {
return s.createSandboxRemote(c, ctx, cfg, orgID, hasOrg, secretStoreID)
}
@@ -882,7 +893,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
// Accepts is documented as a pure function of the request, so asking it here
// yields the same answer it would further down.
tr.mark("tmpl")
- orgRuntime := runtimeFor(c)
+ orgRuntime := s.runtimeFor(c)
backend, ok := s.claimBackend(placement{
region: region, orgID: uuid.UUID(orgID), runtime: orgRuntime, cfg: cfg,
})
diff --git a/internal/api/voucher_claim.go b/internal/api/voucher_claim.go
new file mode 100644
index 00000000..d67196bf
--- /dev/null
+++ b/internal/api/voucher_claim.go
@@ -0,0 +1,154 @@
+package api
+
+// The control-plane half of zero-subrequest edge claim.
+//
+// The edge pulls a book of vouchers per colo, OFF the create hot path, and then
+// answers creates out of that book without calling anyone. This endpoint is what
+// it pulls from. Everything about it is shaped by the fact that it is never on a
+// customer's critical path: it can be slow, it can return fewer than asked, and
+// it can be called by only one request in a colo per refresh window.
+//
+// See internal/awsvmlite/voucher.go for the warm/vouchered/bound state machine
+// and cmd/microvm-hooks/claim.go for where ownership is actually decided.
+
+import (
+ "net/http"
+ "strconv"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/awsvmlite"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// maxVoucherBatch caps one pull.
+//
+// Sized against the burst it has to absorb, not against the pool: the edge wants
+// enough vouchers that concurrent draws from one colo's book rarely collide
+// (N >= 4x burst keeps collisions to a few percent), and a collision only costs
+// a retry. The manager clamps this again to what stock actually allows, minus
+// the reserve it keeps for the control-plane path.
+const maxVoucherBatch = 512
+
+// voucherPublisher is a backend that can promise boxes to a colo ahead of any
+// customer asking. Only the direct-exec (lite) backend implements it today —
+// the pool-backed MicroVM backend serves the older PoolStock path instead.
+type voucherPublisher interface {
+ Vouchers(colo string, n int) []awsvmlite.Voucher
+}
+
+var _ voucherPublisher = (*liteBackend)(nil)
+
+func (s *Server) voucherBackend() (voucherPublisher, bool) {
+ b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})
+ if !ok {
+ return nil, false
+ }
+ vp, ok := b.(voucherPublisher)
+ return vp, ok
+}
+
+type voucherResponse struct {
+ Vouchers []awsvmlite.Voucher `json:"vouchers"`
+ // Stock is what remains unpromised after this pull, so the edge can widen or
+ // narrow its next request instead of guessing.
+ Stock int `json:"stock"`
+}
+
+// publishVouchers handles GET /internal/pool/vouchers?colo=&n=.
+//
+// Fewer than n — including zero — is a normal answer, not an error. The edge
+// serves whatever it got and falls back to the control-plane create path when
+// its book runs dry, which is exactly the path this mechanism exists to skip but
+// which stays correct on its own.
+func (s *Server) publishVouchers(c echo.Context) error {
+ vp, ok := s.voucherBackend()
+ if !ok {
+ // This cell does not run the direct-exec backend. Not an error — the
+ // edge asks every cell it routes to and expects some to say no.
+ return c.JSON(http.StatusOK, voucherResponse{Vouchers: []awsvmlite.Voucher{}})
+ }
+ colo := c.QueryParam("colo")
+ if colo == "" {
+ colo = "unknown"
+ }
+ n, _ := strconv.Atoi(c.QueryParam("n"))
+ if n <= 0 {
+ n = 64
+ }
+ if n > maxVoucherBatch {
+ n = maxVoucherBatch
+ }
+ out := vp.Vouchers(colo, n)
+ if out == nil {
+ out = []awsvmlite.Voucher{}
+ }
+ return c.JSON(http.StatusOK, voucherResponse{Vouchers: out, Stock: s.voucherStock()})
+}
+
+// There is deliberately no edge-initiated release endpoint. The edge cannot
+// assert that a voucher was never handed to a customer — under a shared book,
+// the box behind a losing claim is live under someone else's sandbox — so
+// reclaiming is the cell's job, and it verifies with the box first. See
+// awsvmlite.ReconcileVouchers.
+
+// voucherStock reports unpromised stock, or -1 when this cell has no lite
+// backend to ask.
+func (s *Server) voucherStock() int {
+ b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})
+ if !ok {
+ return -1
+ }
+ lb, ok := b.(*liteBackend)
+ if !ok || lb == nil || lb.mgr == nil {
+ return -1
+ }
+ return lb.mgr.Depth()
+}
+
+// voucherRedeemer is the backend half of a voucher finalize: the thing that can
+// turn (box, sandbox) into a binding. Separate from edgeClaimer because the
+// voucher path has no reservation — the box was promised, not reserved.
+type voucherRedeemer interface {
+ RedeemVoucher(microvmID, sandboxID string, cfg types.SandboxConfig) (workerID string, rebound bool, err error)
+}
+
+func (s *Server) voucherRedeemer() (voucherRedeemer, bool) {
+ b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})
+ if !ok {
+ return nil, false
+ }
+ vr, ok := b.(voucherRedeemer)
+ return vr, ok
+}
+
+// cachePeerPublisher is a backend that runs an in-region voucher cache.
+type cachePeerPublisher interface {
+ CachePeers() []awsvmlite.CachePeer
+}
+
+// publishCachePeers handles GET /internal/pool/cache-peers.
+//
+// The edge's COLD path only. In steady state it learns the instance set from
+// the peer list echoed on every pop, so rotation never costs a create anything;
+// this exists for an isolate that has never popped and has nothing cached, and
+// for the case where every known instance has gone away at once.
+//
+// An empty list is a normal answer — a cell with no cache configured, or one
+// whose first instance is still filling. The edge treats it as "no fast path
+// available" and takes the control-plane create.
+func (s *Server) publishCachePeers(c echo.Context) error {
+ b, ok := s.claimBackend(placement{runtime: runtimeMicrovm})
+ if !ok {
+ return c.JSON(http.StatusOK, map[string]any{"peers": []awsvmlite.CachePeer{}})
+ }
+ cp, ok := b.(cachePeerPublisher)
+ if !ok {
+ return c.JSON(http.StatusOK, map[string]any{"peers": []awsvmlite.CachePeer{}})
+ }
+ peers := cp.CachePeers()
+ if peers == nil {
+ peers = []awsvmlite.CachePeer{}
+ }
+ return c.JSON(http.StatusOK, map[string]any{"peers": peers})
+}
diff --git a/internal/auth/apikey_cache.go b/internal/auth/apikey_cache.go
new file mode 100644
index 00000000..b48a4858
--- /dev/null
+++ b/internal/auth/apikey_cache.go
@@ -0,0 +1,129 @@
+package auth
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "os"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// apiKeyValidator is the slice of the store this cache needs. Narrowing it to
+// an interface is what lets the caching and expiry rules be tested without a
+// live Postgres.
+type apiKeyValidator interface {
+ ValidateAPIKey(ctx context.Context, keyPlaintext string) (uuid.UUID, *uuid.UUID, error)
+}
+
+// apikey_cache.go — memoized API-key validation.
+//
+// Every authenticated request used to cost two Postgres round trips before any
+// handler ran: a SELECT to resolve the key and an inline UPDATE to stamp
+// last_used. Under a burst-100 that is 200+ queries arriving at once against a
+// pool that idles at five connections, so most requests pay for a fresh
+// connection — TCP plus a Postgres auth handshake — before they can even ask
+// the question.
+//
+// Measured on dev (eastus2 CP, burst-100, direct to Go, Caddy bypassed):
+//
+// create gotot=309ms auth=309ms tot=0ms
+// exec gotot=449ms auth=429ms mgrexec=18ms
+//
+// The handler work was already at zero. Authentication was the entire cost.
+//
+// The tradeoff this makes explicit: a revoked or deleted key stays valid for up
+// to the TTL. That is why the TTL is short and tunable rather than generous,
+// and why failures are cached far more briefly than successes — a key that was
+// just created must not be locked out.
+type apiKeyCache struct {
+ mu sync.RWMutex
+ m map[string]apiKeyEntry
+ ttl time.Duration
+}
+
+type apiKeyEntry struct {
+ orgID uuid.UUID
+ userID *uuid.UUID
+ ok bool
+ exp time.Time
+}
+
+// negTTL bounds how long a rejection is remembered. Short enough that a
+// freshly minted key works almost immediately, long enough that a client
+// looping on a bad key cannot use it to hammer Postgres.
+const negTTL = 2 * time.Second
+
+// defaultAPIKeyTTL is the positive-entry lifetime, and therefore the worst-case
+// window in which a revoked key still works.
+const defaultAPIKeyTTL = 30 * time.Second
+
+func newAPIKeyCache() *apiKeyCache {
+ ttl := defaultAPIKeyTTL
+ if v := os.Getenv("OPENSANDBOX_APIKEY_CACHE_TTL_MS"); v != "" {
+ if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
+ ttl = time.Duration(ms) * time.Millisecond
+ }
+ }
+ return &apiKeyCache{m: make(map[string]apiKeyEntry), ttl: ttl}
+}
+
+// validate resolves a key, consulting the cache first.
+//
+// A TTL of zero disables caching entirely, which keeps the old behaviour
+// available without a rebuild if revocation latency ever matters more than
+// burst latency.
+func (c *apiKeyCache) validate(ctx context.Context, store apiKeyValidator, key string) (uuid.UUID, *uuid.UUID, bool) {
+ if c.ttl <= 0 {
+ orgID, userID, err := store.ValidateAPIKey(ctx, key)
+ return orgID, userID, err == nil
+ }
+
+ // Key the map by digest rather than the secret itself, so a heap dump of a
+ // long-lived process does not hand over live API keys.
+ ck := hashFor(key)
+
+ now := time.Now()
+ c.mu.RLock()
+ e, found := c.m[ck]
+ c.mu.RUnlock()
+ if found && now.Before(e.exp) {
+ if e.ok {
+ // last_used is refreshed only on a miss, so it now tracks the key
+ // to TTL resolution instead of being rewritten on every request.
+ // That is a deliberate loss of precision in exchange for removing
+ // a database write from the hot path.
+ return e.orgID, e.userID, true
+ }
+ return uuid.Nil, nil, false
+ }
+
+ orgID, userID, err := store.ValidateAPIKey(ctx, key)
+ ent := apiKeyEntry{orgID: orgID, userID: userID, ok: err == nil}
+ if ent.ok {
+ ent.exp = now.Add(c.ttl)
+ } else {
+ ent.exp = now.Add(negTTL)
+ }
+
+ c.mu.Lock()
+ // Bound the map. Keys are per-org and few, but an attacker spraying random
+ // keys would otherwise grow it without limit; dropping everything is
+ // cheaper than tracking an eviction order and costs one slow request.
+ if len(c.m) > 4096 {
+ c.m = make(map[string]apiKeyEntry, 64)
+ }
+ c.m[ck] = ent
+ c.mu.Unlock()
+
+ return orgID, userID, ent.ok
+}
+
+// hashFor digests a key for use as a map key.
+func hashFor(key string) string {
+ sum := sha256.Sum256([]byte(key))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/internal/auth/apikey_cache_test.go b/internal/auth/apikey_cache_test.go
new file mode 100644
index 00000000..aaf4357f
--- /dev/null
+++ b/internal/auth/apikey_cache_test.go
@@ -0,0 +1,124 @@
+package auth
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type fakeValidator struct {
+ mu sync.Mutex
+ calls int
+ org uuid.UUID
+ err error
+}
+
+func (f *fakeValidator) ValidateAPIKey(ctx context.Context, key string) (uuid.UUID, *uuid.UUID, error) {
+ f.mu.Lock()
+ f.calls++
+ f.mu.Unlock()
+ if f.err != nil {
+ return uuid.Nil, nil, f.err
+ }
+ return f.org, nil, nil
+}
+
+func (f *fakeValidator) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls
+}
+
+func TestAPIKeyCache_HitAvoidsStore(t *testing.T) {
+ fv := &fakeValidator{org: uuid.New()}
+ c := &apiKeyCache{m: map[string]apiKeyEntry{}, ttl: time.Minute}
+
+ for i := 0; i < 5; i++ {
+ org, _, ok := c.validate(context.Background(), fv, "k")
+ if !ok || org != fv.org {
+ t.Fatalf("iteration %d: got ok=%v org=%v", i, ok, org)
+ }
+ }
+ if fv.count() != 1 {
+ t.Fatalf("expected 1 store call across 5 validations, got %d", fv.count())
+ }
+}
+
+// The burst is the whole reason this cache exists, so the concurrent case is
+// the one that matters: many goroutines hitting a cold entry at once must all
+// get the right answer.
+func TestAPIKeyCache_ConcurrentColdStart(t *testing.T) {
+ fv := &fakeValidator{org: uuid.New()}
+ c := &apiKeyCache{m: map[string]apiKeyEntry{}, ttl: time.Minute}
+
+ var wg sync.WaitGroup
+ errs := make(chan error, 100)
+ for i := 0; i < 100; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ org, _, ok := c.validate(context.Background(), fv, "k")
+ if !ok || org != fv.org {
+ errs <- fmt.Errorf("ok=%v org=%v", ok, org)
+ }
+ }()
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Fatal(err)
+ }
+}
+
+func TestAPIKeyCache_Expiry(t *testing.T) {
+ fv := &fakeValidator{org: uuid.New()}
+ c := &apiKeyCache{m: map[string]apiKeyEntry{}, ttl: 20 * time.Millisecond}
+
+ c.validate(context.Background(), fv, "k")
+ c.validate(context.Background(), fv, "k")
+ if fv.count() != 1 {
+ t.Fatalf("expected the second call to hit cache, got %d store calls", fv.count())
+ }
+ time.Sleep(30 * time.Millisecond)
+ c.validate(context.Background(), fv, "k")
+ if fv.count() != 2 {
+ t.Fatalf("expected re-validation after TTL, got %d store calls", fv.count())
+ }
+}
+
+// A rejection must not be remembered for the full positive TTL, or a key
+// created moments after a failed probe would stay locked out.
+func TestAPIKeyCache_RejectionExpiresFast(t *testing.T) {
+ fv := &fakeValidator{err: fmt.Errorf("invalid API key")}
+ c := &apiKeyCache{m: map[string]apiKeyEntry{}, ttl: time.Hour}
+
+ if _, _, ok := c.validate(context.Background(), fv, "bad"); ok {
+ t.Fatal("expected rejection")
+ }
+ if _, _, ok := c.validate(context.Background(), fv, "bad"); ok {
+ t.Fatal("expected cached rejection")
+ }
+ if fv.count() != 1 {
+ t.Fatalf("expected the rejection to be cached, got %d store calls", fv.count())
+ }
+ if got := c.m[hashFor("bad")].exp.Sub(time.Now()); got > negTTL {
+ t.Fatalf("rejection cached for %v, want <= %v", got, negTTL)
+ }
+}
+
+// TTL zero must bypass the cache entirely, so revocation latency can be traded
+// back for correctness without a rebuild.
+func TestAPIKeyCache_DisabledByZeroTTL(t *testing.T) {
+ fv := &fakeValidator{org: uuid.New()}
+ c := &apiKeyCache{m: map[string]apiKeyEntry{}, ttl: 0}
+
+ c.validate(context.Background(), fv, "k")
+ c.validate(context.Background(), fv, "k")
+ if fv.count() != 2 {
+ t.Fatalf("expected caching disabled, got %d store calls", fv.count())
+ }
+}
diff --git a/internal/auth/middleware.go b/internal/auth/middleware.go
index 657fdfa9..51b4f731 100644
--- a/internal/auth/middleware.go
+++ b/internal/auth/middleware.go
@@ -3,10 +3,12 @@ package auth
import (
"net/http"
"strings"
+ "time"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/reqtime"
)
type contextKey string
@@ -123,6 +125,9 @@ func GetUserID(c echo.Context) *uuid.UUID {
// The JWT can arrive in `Authorization: Bearer <jwt>` or as the X-API-Key
// value (detected by the two-dot signature pattern).
func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer, capTokenIssuer *JWTIssuer, cellID string) echo.MiddlewareFunc {
+ // Built once per middleware construction, which is once per server, so the
+ // cache is shared across every request rather than per-connection.
+ keyCache := newAPIKeyCache()
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// Try static API key first (backward compat for combined mode)
@@ -204,8 +209,10 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer,
// Validate against PG if store is available
if store != nil {
- orgID, userID, err := store.ValidateAPIKey(c.Request().Context(), key)
- if err != nil {
+ authStart := time.Now()
+ orgID, userID, ok := keyCache.validate(c.Request().Context(), store, key)
+ reqtime.AddAuth(c, time.Since(authStart))
+ if !ok {
return c.JSON(http.StatusForbidden, map[string]string{
"error": "invalid API key",
})
diff --git a/internal/awsvmlite/cache_fleet.go b/internal/awsvmlite/cache_fleet.go
new file mode 100644
index 00000000..7151f2f1
--- /dev/null
+++ b/internal/awsvmlite/cache_fleet.go
@@ -0,0 +1,355 @@
+package awsvmlite
+
+// The in-region voucher cache, from the control plane's side.
+//
+// What this manages: a small set of boxes, each running cmd/voucher-cache, that
+// hold vouchers in RAM in us-east-1 so the edge can pop one in ~13ms instead of
+// drawing from a Cloudflare colo cache that is non-atomic, per-colo and — the
+// part that actually hurt — evictable. A colo that lost its book rebuilt it from
+// here, in westus2, and burst TTI went from ~300ms to 1498ms.
+//
+// Three things this side is responsible for, and they are all consequences of
+// where the cache lives rather than of what it does:
+//
+// FILLING. The cache never restocks itself on a pop; if it did, a customer's
+// create would again be waiting on a control-plane round trip, which is the
+// coupling that caused the cliff. So stock arrives by push, on a timer.
+//
+// KEEPING IT WARM. A box with no inbound proxy traffic suspends, and the
+// first request after that pays the restore. Measured against an idle box:
+// 1305ms cold and repeated 190-450ms spikes, against 13ms p50 warm. The fill
+// tick is itself inbound proxy traffic, so filling frequently enough IS the
+// keepalive — there is deliberately no separate ping.
+//
+// ROTATION. Boxes die at the 8h service cap. A replacement is stood up and
+// confirmed stocked BEFORE the incumbent is retired, so there is no moment
+// where the edge's only known instance is gone. The edge learns the new one
+// from the peer list it gets back on ordinary pops.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+// CacheConfig configures the cache fleet. Zero Replicas disables it entirely.
+type CacheConfig struct {
+ // Enabled turns the fleet on. The service itself ships inside the guest
+ // agent (internal/vouchercache), so there is nothing to install — a cache
+ // instance is an ordinary box that the control plane happens to fill.
+ Enabled bool
+ // Replicas is how many stocked instances to keep. Two is the useful
+ // minimum: rotation needs somewhere for traffic to go while a replacement
+ // fills.
+ Replicas int
+ // Target is how many vouchers each instance should hold.
+ Target int
+ // FillInterval is both the restock period and the keepalive. Must stay
+ // comfortably under the box's idle timeout.
+ FillInterval time.Duration
+ // MaxLifetime is when an instance is retired. Must be under the 8h AWS
+ // service cap with enough room to stand up and stock a replacement.
+ MaxLifetime time.Duration
+ // Colo is the holder id vouchers are issued under. Not a real Cloudflare
+ // colo — the cache serves every colo, which is the point.
+ Colo string
+}
+
+func (c *CacheConfig) applyDefaults() {
+ if c.Replicas == 0 {
+ c.Replicas = 2
+ }
+ if c.Target == 0 {
+ c.Target = 256
+ }
+ if c.FillInterval == 0 {
+ c.FillInterval = 10 * time.Second
+ }
+ if c.MaxLifetime == 0 {
+ // The cap is 8h. Leaving 45 minutes is enough for several launch
+ // retries against the 5/s RunMicrovm quota without ever racing it.
+ c.MaxLifetime = 7*time.Hour + 15*time.Minute
+ }
+ if c.Colo == "" {
+ c.Colo = "region-cache"
+ }
+}
+
+type cacheInstance struct {
+ box *Box
+ startedAt time.Time
+ ready bool
+ // fails counts consecutive fill failures. An instance that stops answering
+ // is retired rather than left in the peer list, where the edge would keep
+ // paying a timeout per create to discover it.
+ fails int
+}
+
+// CacheFleet owns the cache instances. Safe for concurrent use.
+type CacheFleet struct {
+ m *Manager
+ cfg CacheConfig
+
+ mu sync.Mutex
+ insts []*cacheInstance
+ inflight bool
+}
+
+func NewCacheFleet(m *Manager, cfg CacheConfig) *CacheFleet {
+ cfg.applyDefaults()
+ return &CacheFleet{m: m, cfg: cfg}
+}
+
+// maxFillFails is how many consecutive failures retire an instance. Small,
+// because the fill tick is frequent and a healthy instance never misses.
+const maxFillFails = 3
+
+// Peers reports the currently stocked instances, newest deadline first.
+//
+// This is the edge's cold-start path only. In steady state the edge learns the
+// set from pop responses and never asks the control plane at all — which is
+// what keeps rotation off the create path.
+func (f *CacheFleet) Peers() []CachePeer {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ out := make([]CachePeer, 0, len(f.insts))
+ for _, in := range f.insts {
+ if !in.ready {
+ continue
+ }
+ out = append(out, CachePeer{
+ Endpoint: in.box.Endpoint,
+ Token: in.box.Token,
+ Port: in.box.Port,
+ RetireAtUnix: in.startedAt.Add(f.cfg.MaxLifetime).Unix(),
+ })
+ }
+ return out
+}
+
+// CachePeer is one cache instance as the edge addresses it.
+type CachePeer struct {
+ Endpoint string `json:"endpoint"`
+ Token string `json:"token"`
+ Port int32 `json:"port"`
+ RetireAtUnix int64 `json:"retireAtUnix,omitempty"`
+}
+
+// Run drives the fleet until ctx is done.
+func (f *CacheFleet) Run(ctx context.Context) {
+ if !f.cfg.Enabled {
+ log.Printf("awsvmlite/cache: disabled")
+ return
+ }
+ log.Printf("awsvmlite/cache: starting (replicas=%d target=%d fill=%s lifetime=%s)",
+ f.cfg.Replicas, f.cfg.Target, f.cfg.FillInterval, f.cfg.MaxLifetime)
+
+ fill := time.NewTicker(f.cfg.FillInterval)
+ defer fill.Stop()
+ reconcile := time.NewTicker(30 * time.Second)
+ defer reconcile.Stop()
+
+ f.reconcile(ctx)
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-fill.C:
+ f.fillAll(ctx)
+ case <-reconcile.C:
+ f.reconcile(ctx)
+ }
+ }
+}
+
+// reconcile keeps Replicas young, stocked instances alive and retires aged ones.
+//
+// Order matters and is the whole of the rotation story: a replacement is
+// launched while the incumbent is still serving, and the incumbent is only
+// terminated once enough YOUNG instances are ready to take over. The fleet
+// briefly runs at Replicas+1, which is the cost of never having a gap.
+func (f *CacheFleet) reconcile(ctx context.Context) {
+ now := time.Now()
+ f.mu.Lock()
+ young := 0
+ for _, in := range f.insts {
+ if in.ready && now.Sub(in.startedAt) < f.cfg.MaxLifetime {
+ young++
+ }
+ }
+ need := young < f.cfg.Replicas && !f.inflight
+ if need {
+ f.inflight = true
+ }
+ // Retire only what is genuinely surplus.
+ var retire []*cacheInstance
+ keep := f.insts[:0]
+ for _, in := range f.insts {
+ aged := now.Sub(in.startedAt) >= f.cfg.MaxLifetime
+ broken := in.fails >= maxFillFails
+ if (aged || broken) && young >= f.cfg.Replicas {
+ retire = append(retire, in)
+ continue
+ }
+ keep = append(keep, in)
+ }
+ f.insts = keep
+ f.mu.Unlock()
+
+ for _, in := range retire {
+ log.Printf("awsvmlite/cache: retiring %s (age=%s fails=%d)",
+ in.box.MicrovmID, now.Sub(in.startedAt).Truncate(time.Second), in.fails)
+ go f.m.terminate(in.box.MicrovmID)
+ }
+ if need {
+ go func() {
+ defer func() {
+ f.mu.Lock()
+ f.inflight = false
+ f.mu.Unlock()
+ }()
+ if err := f.launch(ctx); err != nil {
+ log.Printf("awsvmlite/cache: launch failed: %v", err)
+ }
+ }()
+ }
+}
+
+// launch stands up one cache instance and does not return until it is stocked.
+//
+// Readiness is depth-gated on the service side, so returning here means the
+// instance can actually serve — publishing it earlier would put an instance
+// that answers 204 into the peer list and silently push creates onto the slow
+// path.
+func (f *CacheFleet) launch(ctx context.Context) error {
+ runCtx, cancel := context.WithTimeout(ctx, 4*time.Minute)
+ defer cancel()
+
+ box, err := f.m.client.Run(runCtx, "")
+ if err != nil {
+ return fmt.Errorf("run: %w", err)
+ }
+ ready, err := f.m.client.WaitRunning(runCtx, box.ID, f.m.cfg.ReadyTimeout)
+ if err != nil {
+ go f.m.terminate(box.ID)
+ return fmt.Errorf("wait running: %w", err)
+ }
+ token, err := f.m.client.AuthToken(runCtx, ready.ID)
+ if err != nil {
+ go f.m.terminate(ready.ID)
+ return fmt.Errorf("auth token: %w", err)
+ }
+ b := &Box{
+ MicrovmID: ready.ID,
+ Endpoint: ready.Endpoint,
+ Token: token,
+ Port: f.m.client.Config().AgentPort,
+ }
+ in := &cacheInstance{box: b, startedAt: time.Now()}
+ // Stock it before anyone can see it.
+ if err := f.fill(runCtx, in); err != nil {
+ go f.m.terminate(ready.ID)
+ return fmt.Errorf("first fill on %s: %w", ready.ID, err)
+ }
+ if !in.ready {
+ go f.m.terminate(ready.ID)
+ return fmt.Errorf("%s did not become ready after first fill", ready.ID)
+ }
+
+ f.mu.Lock()
+ f.insts = append(f.insts, in)
+ n := len(f.insts)
+ f.mu.Unlock()
+ log.Printf("awsvmlite/cache: instance %s READY (%d live)", b.MicrovmID, n)
+ return nil
+}
+
+func (f *CacheFleet) fillAll(ctx context.Context) {
+ f.mu.Lock()
+ insts := append([]*cacheInstance(nil), f.insts...)
+ f.mu.Unlock()
+ for _, in := range insts {
+ if err := f.fill(ctx, in); err != nil {
+ log.Printf("awsvmlite/cache: fill %s failed (%d consecutive): %v", in.box.MicrovmID, in.fails, err)
+ }
+ }
+}
+
+// fill pushes the current promised set to one instance.
+//
+// It sends the WHOLE set every time, not a delta. The instance dedups by box
+// id, and re-sending is what lets a replacement come up full — see
+// ColoVouchers. A delta protocol would make the cache's memory authoritative,
+// which it must never be: losing it has to stay a throughput event.
+func (f *CacheFleet) fill(ctx context.Context, in *cacheInstance) error {
+ vouchers := f.m.ColoVouchers(f.cfg.Colo, f.cfg.Target)
+ peers := f.Peers()
+ // A launching instance is not in Peers() yet; include it so the very first
+ // pop already advertises the right set.
+ self := CachePeer{
+ Endpoint: in.box.Endpoint,
+ Token: in.box.Token,
+ Port: in.box.Port,
+ RetireAtUnix: in.startedAt.Add(f.cfg.MaxLifetime).Unix(),
+ }
+ found := false
+ for _, p := range peers {
+ if p.Endpoint == self.Endpoint {
+ found = true
+ break
+ }
+ }
+ if !found {
+ peers = append(peers, self)
+ }
+
+ body, err := json.Marshal(map[string]any{
+ "vouchers": vouchers,
+ "peers": peers,
+ "target": f.cfg.Target,
+ })
+ if err != nil {
+ return err
+ }
+
+ reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
+ defer cancel()
+ resp, err := f.doCache(reqCtx, in.box, http.MethodPost, "fill", body)
+ if err != nil {
+ in.fails++
+ return err
+ }
+ defer resp.Body.Close()
+ raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ if resp.StatusCode != http.StatusOK {
+ in.fails++
+ return fmt.Errorf("http %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
+ }
+ var out struct {
+ Depth int `json:"depth"`
+ Added int `json:"added"`
+ }
+ _ = json.Unmarshal(raw, &out)
+ in.fails = 0
+ // Ready once it holds a workable share of target — mirrors the service's
+ // own gate so this side does not publish an instance the service would
+ // still 503.
+ if !in.ready && out.Depth*2 >= f.cfg.Target && out.Depth > 0 {
+ in.ready = true
+ }
+ return nil
+}
+
+// cachePath is where the guest agent mounts the cache. It shares the agent's
+// listener because the proxy forwards only to the declared port.
+const cachePath = "/osb/cache/"
+
+func (f *CacheFleet) doCache(ctx context.Context, b *Box, method, path string, body []byte) (*http.Response, error) {
+ return f.m.do(ctx, b, method, cachePath+path, body)
+}
diff --git a/internal/awsvmlite/lite.go b/internal/awsvmlite/lite.go
index e750c808..33f7e2b4 100644
--- a/internal/awsvmlite/lite.go
+++ b/internal/awsvmlite/lite.go
@@ -188,6 +188,12 @@ type Manager struct {
mu sync.Mutex
warm []*Box
bound map[string]*Box // sandboxID → box
+ // vouchered holds boxes promised to a colo but not yet redeemed — see
+ // voucher.go. Deliberately a third state, not a flavour of bound: these can
+ // still be taken back, and bound ones never can.
+ vouchered map[string]*voucherEntry
+ // lastStateLog rate-limits the periodic state line — see logState.
+ lastStateLog time.Time
// inflight counts launches in progress, so the filler targets committed
// boxes rather than landed ones and does not overshoot WarmTarget by
// however many are mid-launch.
@@ -219,10 +225,16 @@ func New(client *awsvm.Client, cfg Config) *Manager {
}
// Depth reports how many boxes are ready to hand out.
+// Depth is unclaimed stock: warm PLUS vouchered.
+//
+// Vouchered boxes have left m.warm but nobody owns them, so counting only warm
+// would make the filler manufacture a replacement for every box the edge is
+// merely holding a promise on — turning a 100-box target into a fleet bounded
+// by the account quota instead.
func (m *Manager) Depth() int {
m.mu.Lock()
defer m.mu.Unlock()
- return len(m.warm)
+ return len(m.warm) + len(m.vouchered)
}
// Run drives the warm set: top it up, and keep every box in it non-idle.
@@ -248,7 +260,8 @@ func (m *Manager) Run(ctx context.Context) {
return
case <-launch.C:
m.mu.Lock()
- committed := len(m.warm) + m.inflight
+ // Vouchered boxes are stock too — see Depth.
+ committed := len(m.warm) + len(m.vouchered) + m.inflight
m.mu.Unlock()
if committed >= m.cfg.WarmTarget {
continue
@@ -259,6 +272,22 @@ func (m *Manager) Run(ctx context.Context) {
}
}()
case <-touch.C:
+ // Periodic state line.
+ //
+ // Added because this backend was diagnosable only when something
+ // happened: counts were logged on voucher issue and on reconcile,
+ // so a QUIET manager was completely opaque. That cost real time —
+ // the keepalive touching 49 boxes while AWS showed 100 running was
+ // impossible to explain without knowing how many were vouchered,
+ // and nothing was printing it. A steady heartbeat of the three
+ // states is what makes "the filler thinks it is at target" and
+ // "half the fleet is promised" distinguishable at a glance.
+ m.logState()
+ // Settle expired promises before touching. This ASKS each box who
+ // owns it rather than assuming an unredeemed voucher means an
+ // unclaimed box — see ReconcileVouchers for why that distinction is
+ // load-bearing. Own goroutine: it makes network calls.
+ go m.ReconcileVouchers(ctx)
// In its own goroutine: a touch against an already-suspended box is
// held by Lambda for the length of a restore, and blocking the tick
// on that would stall the filler behind it.
@@ -499,9 +528,25 @@ func (m *Manager) Alive(ctx context.Context, sandboxID string) (bool, error) {
// BoxFor returns the box bound to a sandbox.
func (m *Manager) BoxFor(sandboxID string) (*Box, bool) {
m.mu.Lock()
- defer m.mu.Unlock()
b, ok := m.bound[sandboxID]
- return b, ok
+ m.mu.Unlock()
+ if ok {
+ return b, true
+ }
+ // A vouchered box is NOT redeemable from here, and that is deliberate.
+ //
+ // A voucher is keyed by BOX, because the edge mints the sandbox id and the
+ // cell has never seen it until a finalize arrives carrying both. So there is
+ // nothing to look up: this process genuinely does not know which box that
+ // sandbox drew.
+ //
+ // The window this used to paper over is now closed at the source — finalize
+ // redeems the voucher for real (it previously could not, and logged 473
+ // consecutive losses against zero successes). What remains is the narrow case
+ // of an exec reaching the cell BEFORE its finalize lands, which only happens
+ // when the edge's direct-to-box path has already failed. It surfaces as a
+ // clean not-found rather than a wrong box.
+ return nil, false
}
// Exec runs one command in a sandbox and returns its result.
@@ -600,6 +645,18 @@ func (m *Manager) DrainWarm(ctx context.Context) int {
m.mu.Lock()
warm := m.warm
m.warm = nil
+ // Vouchered boxes drain too. They are unclaimed stock that simply left
+ // m.warm when it was promised to a colo, and the promise dies with this
+ // process — the edge's book is about to be answered by a CP that has never
+ // heard of these boxes. Draining only m.warm abandoned every one of them on
+ // each restart, which is a leak with no upper bound but the account quota.
+ //
+ // Bound boxes are still left alone: they belong to customers, and the
+ // reconciler re-adopts them on the way back up.
+ for id, e := range m.vouchered {
+ warm = append(warm, e.box)
+ delete(m.vouchered, id)
+ }
m.mu.Unlock()
var wg sync.WaitGroup
@@ -677,6 +734,14 @@ func (m *Manager) touchIdle(ctx context.Context) {
due = append(due, b)
}
}
+ // Vouchered boxes sit idle exactly like warm ones and need the same touch;
+ // skipping them would let AWS suspend the very stock the edge is about to
+ // hand out.
+ for _, b := range m.voucherBoxesLocked() {
+ if b.lastTouch.IsZero() || now.Sub(b.lastTouch) >= m.cfg.TouchInterval {
+ due = append(due, b)
+ }
+ }
for _, b := range m.bound {
if b.lastTouch.IsZero() || now.Sub(b.lastTouch) >= m.cfg.TouchInterval {
due = append(due, b)
diff --git a/internal/awsvmlite/voucher.go b/internal/awsvmlite/voucher.go
new file mode 100644
index 00000000..66f26ee2
--- /dev/null
+++ b/internal/awsvmlite/voucher.go
@@ -0,0 +1,486 @@
+package awsvmlite
+
+// Voucher publication: how a box gets to the edge without the edge asking.
+//
+// The measured problem this exists to solve: at burst-100 a create spent 310ms
+// in the edge→control-plane call while the CP's own handler took 75
+// MICROSECONDS and absorbed the whole burst inside 30ms. The time is not work.
+// It is a Cloudflare Worker isolate waiting to be scheduled — an invocation may
+// hold only six open connections, and every subrequest and waitUntil takes one.
+// So the fix is not to make the call faster. It is to not make the call.
+//
+// A voucher is a box, pre-paired with a sandbox ID and pre-authenticated,
+// published to the edge BEFORE any customer asks. The edge caches a book of
+// them per colo and answers a create out of that book with zero subrequests.
+//
+// The voucher confers nothing. It is a hint that a box is probably free. Two
+// colos, two isolates, or a stale cache can all name the same box; ownership is
+// settled at the box by an idempotent compare-and-swap (see
+// cmd/microvm-hooks/claim.go). That is what lets this side be sloppy and fast.
+//
+// Three states, and a box is in exactly one:
+//
+// warm nobody has been promised it
+// vouchered promised to a colo, not yet redeemed — still ours to take back
+// bound a customer owns it
+//
+// vouchered is NOT bound. A vouchered box may expire back to warm; a bound one
+// never does. Conflating the two is how the previous attempt stranded stock.
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strconv"
+ "time"
+)
+
+// voucherReserve is how many warm boxes are never vouchered.
+//
+// The control-plane create path still exists — an org without the flag, a
+// non-default shape, an edge that missed its book — and it claims from `warm`.
+// Vouchering the last box would make that path fail while the fleet sat idle
+// holding promises nobody had redeemed yet. Small, because the lite lane sends
+// essentially everything through vouchers.
+const voucherReserve = 4
+
+// coloFraction is the share of stock one colo's book may hold.
+//
+// The default stays at 0.8 because the ceiling is real when traffic arrives in
+// several colos — see the two failures documented at the cap below. It is a knob
+// because it is NOT real when one colo serves everything: at a 150-box pool the
+// default caps the book at 120, and a burst of 100 into 120 slots is a load
+// factor of 0.83, where the free-list draw has to walk further to find an
+// unclaimed box. A single-colo dev cell can safely run this near 1.
+func coloFraction() float64 {
+ if v := os.Getenv("OPENSANDBOX_MICROVM_VOUCHER_COLO_FRACTION"); v != "" {
+ if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 && f <= 1 {
+ return f
+ }
+ }
+ return 0.8
+}
+
+// voucherTTL bounds how long a promise ties up a box.
+//
+// LONG on purpose, and it is ReconcileVouchers that makes long safe: expiry no
+// longer re-pools on an assumption, it asks the box who owns it. So the cost of
+// a generous TTL is idle stock, not a correctness risk — and the colo cap bounds
+// how much stock any one colo can hold idle.
+//
+// Short was actively harmful. At 180s against a 45s book, a burst arriving after
+// any idle gap found the book aged out, so all 100 creates missed, fell through
+// to the control plane at once, and drove it to 5.1s of D1 and 35 rate-limit
+// 503s — measured 2026-08-26, TTI p50 8.7s, i.e. WORSE than having no voucher
+// path at all. A cold book must never be the common case.
+//
+// Must still comfortably exceed the edge's book TTL (30 min), so a voucher
+// cannot expire while it is still being handed out. Well inside the 8h box
+// service cap, so a promise never outlives the box it names.
+const voucherTTL = 60 * time.Minute
+
+// Voucher is what the edge caches: everything needed to reach a box, and
+// nothing else.
+//
+// Deliberately NO sandbox ID. Pre-pairing one here is what made burst unsafe —
+// a book of N serving a burst of B>N means, by pigeonhole, that several creates
+// draw the same voucher, and a sandbox id inside it turns that into two
+// customers holding the SAME sandbox. The guest CAS cannot catch that: it sees
+// one id claiming its box twice and correctly calls it an idempotent replay.
+//
+// The edge mints the sandbox id per create instead, so a duplicate draw is two
+// different sandboxes racing for one box — the case the CAS exists to settle.
+// A voucher is therefore a hint about a BOX, and the box is its only identity.
+type Voucher struct {
+ MicrovmID string `json:"microvmID"`
+ Endpoint string `json:"endpoint"`
+ Token string `json:"token"`
+ Port int32 `json:"port"`
+ // ExpiresAtUnix lets the edge skip a voucher that is about to be reaped
+ // rather than hand out one that will lose its race.
+ ExpiresAtUnix int64 `json:"expiresAtUnix"`
+}
+
+type voucherEntry struct {
+ box *Box
+ colo string
+ exp time.Time
+}
+
+// Vouchers promises up to n warm boxes to one colo.
+//
+// Each colo gets a DISJOINT set: a box leaves `warm` the moment it is promised,
+// so no two colos can be handed the same one. That removes the largest source of
+// avoidable claim conflicts, leaving only the ones the CAS is actually there for
+// (two isolates in the SAME colo drawing the same index from a shared book).
+//
+// Returning fewer than n is normal and not an error — the edge tops its book up
+// again on its next off-path refresh, and a create that finds the book empty
+// falls back to the control plane, which is the path this whole mechanism exists
+// to skip but which remains correct.
+func (m *Manager) Vouchers(colo string, n int) []Voucher {
+ if m == nil || n <= 0 {
+ return nil
+ }
+ now := time.Now()
+ exp := now.Add(voucherTTL)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.vouchered == nil {
+ m.vouchered = map[string]*voucherEntry{}
+ }
+
+ // Never promise the reserve away — see voucherReserve.
+ avail := len(m.warm) - voucherReserve
+ if avail <= 0 {
+ return nil
+ }
+ if n > avail {
+ n = avail
+ }
+ // Bound what ONE colo may hold, without making its book useless.
+ //
+ // Two failures shaped this number, in opposite directions:
+ //
+ // Unbounded — a few probe creates from a laptop pulled 96 of 100 boxes
+ // into an SJC book nobody would ever draw from, and the real client in
+ // IAD found nothing for a full voucher TTL.
+ //
+ // Half — a burst of 100 against a book of 50 could only ever serve half
+ // its creates from vouchers, and the constant refilling that caused
+ // rotated the book out from under its own in-flight execs.
+ //
+ // So: generous enough that a colo's book can cover a burst the size of the
+ // pool, but never the whole supply. Unused promises come back on their own —
+ // ReconcileVouchers asks each box and re-pools the genuinely idle ones — so
+ // the cost of being generous is bounded and self-healing, whereas the cost
+ // of being stingy is a book that cannot do its job.
+ if cap := int(float64(len(m.warm)+len(m.vouchered)) * coloFraction()); n > cap && cap > 0 {
+ n = cap
+ }
+
+ out := make([]Voucher, 0, n)
+ for i := 0; i < n; i++ {
+ last := len(m.warm) - 1
+ b := m.warm[last]
+ m.warm = m.warm[:last]
+
+ // Keyed by BOX. A promise is about a box; which sandbox redeems it is
+ // not knowable here, and pretending otherwise was the defect.
+ m.vouchered[b.MicrovmID] = &voucherEntry{box: b, colo: colo, exp: exp}
+ out = append(out, Voucher{
+ MicrovmID: b.MicrovmID,
+ Endpoint: b.Endpoint,
+ Token: b.Token,
+ Port: m.agentPort(),
+ ExpiresAtUnix: exp.Unix(),
+ })
+ }
+ log.Printf("awsvmlite: vouchered %d box(es) to colo %s (asked %d, warm=%d vouchered=%d)",
+ len(out), colo, n, len(m.warm), len(m.vouchered))
+ return out
+}
+
+// RedeemVoucher converts a promise into ownership, and is the ONLY way a
+// vouchered box becomes bound.
+//
+// Takes the BOX and the sandbox that won it. The edge minted that sandbox id, so
+// this is the first time the cell sees it — which is why the pairing has to
+// arrive from outside rather than be looked up.
+//
+// Idempotent, mirroring the guest CAS: redeeming an already-redeemed sandbox
+// returns its box again rather than failing, because the edge retries and a
+// finalize can arrive twice.
+func (m *Manager) RedeemVoucher(microvmID, sandboxID string, meta Meta) (*Box, bool, bool) {
+ if m == nil || microvmID == "" || sandboxID == "" {
+ return nil, false, false
+ }
+ meta = m.delivered(meta)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if b, ok := m.bound[sandboxID]; ok {
+ if b.MicrovmID == microvmID {
+ // Already redeemed against this box. Refresh the meta — the first
+ // redeem may have run before the real config was known — and report
+ // success.
+ b.Meta = meta
+ return b, true, false
+ }
+ // A REBIND. The edge could not use the box the create announced (it was
+ // dead, or already owned) and moved this sandbox to another one, then
+ // re-sent the finalize naming the box that actually took the claim.
+ //
+ // This has to be honoured, not treated as a duplicate: whatever we have
+ // recorded here is what a destroy will terminate, so leaving the old box
+ // in place would eventually kill a box belonging to someone else.
+ e, ok := m.vouchered[microvmID]
+ if !ok {
+ // The edge claimed a box we no longer have promised. Keep the old
+ // record rather than inventing one; reconciliation will ask the
+ // boxes themselves who owns what.
+ log.Printf("awsvmlite: rebind for %s named unvouchered box %s — keeping %s", sandboxID, microvmID, b.MicrovmID)
+ return b, false, false
+ }
+ delete(m.vouchered, microvmID)
+ e.box.Meta = meta
+ e.box.boundAt = time.Now()
+ m.bound[sandboxID] = e.box
+ // The old box is deliberately NOT re-pooled. It is either gone or live
+ // under a different sandbox, and the edge is in no position to assert
+ // which — see ReconcileVouchers, which asks each box directly.
+ log.Printf("awsvmlite: rebound %s from box %s to %s", sandboxID, b.MicrovmID, microvmID)
+ return e.box, true, true
+ }
+ e, ok := m.vouchered[microvmID]
+ if !ok {
+ return nil, false, false
+ }
+ delete(m.vouchered, microvmID)
+ e.box.Meta = meta
+ e.box.boundAt = time.Now()
+ m.bound[sandboxID] = e.box
+ return e.box, true, false
+}
+
+// ReconcileVouchers settles promises that ran out of time.
+//
+// THE TRAP THIS EXISTS FOR. "Unredeemed" does NOT mean "unclaimed". The edge
+// serves a book that several isolates read at once, so two creates can draw box
+// B and arrive at it as S1 and S2. The box's CAS picks one; the loser retries
+// elsewhere. Meanwhile B's promise here may sit unredeemed — while B is being
+// used by a paying customer. Re-pooling it on that basis would hand a live
+// sandbox to the next person who asked, which is the single worst thing this
+// system could do.
+//
+// The same duplicate draw can also leave this cell's bookkeeping naming the
+// wrong box: both creates enqueue a finalize for B before either has raced, so
+// the first finalize binds B to whichever sandbox it belongs to, which may not
+// be the one the box chose. Ownership is still decided exactly once, at the box,
+// so no customer ever reaches another's sandbox — but the cell's view can lag,
+// and the adopt case below is what converges it back to what the box says.
+//
+// So an expired voucher is not evidence of anything. We ask the BOX, which is
+// the only authority on who owns it (/healthz reports claimedBy, written by the
+// same CAS that decided it), and then:
+//
+// unclaimed → genuinely nobody's; return it to the warm set
+// claimed by S' → adopt the binding we did not know about
+// cannot tell → leave it promised and retry on the next tick
+//
+// The last case is why this is idempotent and safe to call on a timer: a box we
+// could not reach keeps its promise rather than being guessed about.
+func (m *Manager) ReconcileVouchers(ctx context.Context) {
+ if m == nil {
+ return
+ }
+ now := time.Now()
+ type pending struct {
+ id string
+ e *voucherEntry
+ }
+ var expired []pending
+
+ m.mu.Lock()
+ for id, e := range m.vouchered {
+ if now.Before(e.exp) {
+ continue
+ }
+ delete(m.vouchered, id)
+ expired = append(expired, pending{id, e})
+ }
+ m.mu.Unlock()
+ if len(expired) == 0 {
+ return
+ }
+
+ repooled, adopted, unknown := 0, 0, 0
+ for _, x := range expired {
+ owner, ok := m.boxClaimedBy(ctx, x.e.box)
+ switch {
+ case !ok:
+ // Could not ask. Re-promise with a short extension so the next tick
+ // tries again rather than resolving this on a guess.
+ m.mu.Lock()
+ x.e.exp = now.Add(30 * time.Second)
+ m.vouchered[x.id] = x.e
+ m.mu.Unlock()
+ unknown++
+ case owner == "":
+ m.mu.Lock()
+ m.warm = append(m.warm, x.e.box)
+ m.mu.Unlock()
+ repooled++
+ default:
+ // Claimed under a sandbox id we never redeemed — the edge drew this
+ // box from the book twice, or its finalize was lost. The box says
+ // who owns it; believe the box.
+ m.mu.Lock()
+ x.e.box.Meta = m.delivered(x.e.box.Meta)
+ x.e.box.boundAt = now
+ m.bound[owner] = x.e.box
+ m.mu.Unlock()
+ adopted++
+ }
+ }
+ log.Printf("awsvmlite: voucher reconcile — %d re-pooled, %d adopted, %d unresolved (warm=%d vouchered=%d)",
+ repooled, adopted, unknown, m.warmCount(), m.VoucherStock())
+}
+
+// boxClaimedBy asks a box who owns it. ok=false means we could not find out,
+// which is deliberately distinct from "nobody" — see ReconcileVouchers.
+func (m *Manager) boxClaimedBy(ctx context.Context, b *Box) (owner string, ok bool) {
+ reqCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ resp, err := m.do(reqCtx, b, http.MethodGet, "/healthz", nil)
+ if err != nil {
+ return "", false
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return "", false
+ }
+ var h struct {
+ Claimed bool `json:"claimed"`
+ ClaimedBy string `json:"claimedBy"`
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&h); err != nil {
+ return "", false
+ }
+ if !h.Claimed {
+ return "", true
+ }
+ return h.ClaimedBy, true
+}
+
+func (m *Manager) warmCount() int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return len(m.warm)
+}
+
+// VoucherStock reports promises outstanding, for the filler and for telemetry.
+func (m *Manager) VoucherStock() int {
+ if m == nil {
+ return 0
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return len(m.vouchered)
+}
+
+// vvoucherBoxesLocked lists vouchered boxes so the keepalive can touch them.
+// Caller holds m.mu.
+//
+// Vouchered boxes are live boxes sitting idle, so they need the touch exactly as
+// warm ones do. Missing them was the shape of an earlier outage: stock that AWS
+// suspended underneath us because nothing was keeping its idle timer fed.
+func (m *Manager) voucherBoxesLocked() []*Box {
+ out := make([]*Box, 0, len(m.vouchered))
+ for _, e := range m.vouchered {
+ out = append(out, e.box)
+ }
+ return out
+}
+
+// agentPort is nil-safe on the client, matching delivered(): voucher minting is
+// reached from tests that never talk to AWS, and a missing client should degrade
+// rather than panic.
+func (m *Manager) agentPort() int32 {
+ if m == nil || m.client == nil {
+ return 0
+ }
+ return m.client.Config().AgentPort
+}
+
+// logState prints the warm/vouchered/bound split on every touch tick.
+//
+// Rate-limited to once a minute: the tick is every few seconds, and the useful
+// signal is a trend, not a stream. Logged even when nothing changed — a stuck
+// count IS the symptom worth seeing.
+func (m *Manager) logState() {
+ m.mu.Lock()
+ warm, vouch, bound := len(m.warm), len(m.vouchered), len(m.bound)
+ last := m.lastStateLog
+ now := time.Now()
+ if now.Sub(last) < time.Minute {
+ m.mu.Unlock()
+ return
+ }
+ m.lastStateLog = now
+ // Oldest outstanding promise, so a pool pinned by a long voucher TTL is
+ // visible as such rather than as unexplained missing stock.
+ oldest := time.Duration(0)
+ for _, e := range m.vouchered {
+ if age := now.Sub(e.exp.Add(-voucherTTL)); age > oldest {
+ oldest = age
+ }
+ }
+ m.mu.Unlock()
+ log.Printf("awsvmlite: state warm=%d vouchered=%d bound=%d depth=%d/%d oldest-voucher=%s",
+ warm, vouch, bound, warm+vouch, m.cfg.WarmTarget, oldest.Round(time.Second))
+}
+
+// ColoVouchers is Vouchers for a holder that keeps its stock in RAM.
+//
+// The difference is re-listing. Vouchers only ever hands out boxes from `warm`,
+// which is right for a colo book that persists in Cloudflare's cache: a box
+// already promised to that colo is already in its book, and re-issuing it would
+// duplicate the entry.
+//
+// The in-region cache is not like that. It holds stock in memory, so a restart
+// or an 8h rotation loses every promise it was holding while this side still
+// believes those boxes are spoken for. With only Vouchers, the replacement
+// instance would come up nearly empty and stay that way until each promise aged
+// out — minutes of creates falling through to the slow path, on exactly the
+// event (rotation) the design exists to make invisible.
+//
+// So this returns everything currently promised to `colo`, with a refreshed
+// expiry, and tops up from warm to n. Re-listing is safe because the holder is
+// the same one that already had them: it cannot double-issue a box the cache is
+// simultaneously handing out, since the cache dedups by box id and this side
+// hands the whole set to one holder.
+//
+// Redeemed boxes cannot appear here: RedeemVoucher removes the entry when it
+// binds, so `vouchered` is by construction the un-redeemed set.
+func (m *Manager) ColoVouchers(colo string, n int) []Voucher {
+ if m == nil || n <= 0 {
+ return nil
+ }
+ now := time.Now()
+ exp := now.Add(voucherTTL)
+
+ m.mu.Lock()
+ if m.vouchered == nil {
+ m.vouchered = map[string]*voucherEntry{}
+ }
+ out := make([]Voucher, 0, n)
+ for _, e := range m.vouchered {
+ if e.colo != colo || e.box == nil {
+ continue
+ }
+ e.exp = exp
+ out = append(out, Voucher{
+ MicrovmID: e.box.MicrovmID,
+ Endpoint: e.box.Endpoint,
+ Token: e.box.Token,
+ Port: m.agentPort(),
+ ExpiresAtUnix: exp.Unix(),
+ })
+ if len(out) >= n {
+ break
+ }
+ }
+ m.mu.Unlock()
+
+ if len(out) >= n {
+ return out
+ }
+ // Top up through the normal path so the reserve and the per-colo cap are
+ // enforced in exactly one place.
+ return append(out, m.Vouchers(colo, n-len(out))...)
+}
diff --git a/internal/awsvmlite/voucher_test.go b/internal/awsvmlite/voucher_test.go
new file mode 100644
index 00000000..880b6d93
--- /dev/null
+++ b/internal/awsvmlite/voucher_test.go
@@ -0,0 +1,285 @@
+package awsvmlite
+
+import (
+ "context"
+ "net/http"
+ "testing"
+ "time"
+)
+
+func mgrWithWarm(n int) *Manager {
+ m := &Manager{bound: map[string]*Box{}}
+ for i := 0; i < n; i++ {
+ m.warm = append(m.warm, &Box{MicrovmID: "mvm-" + itoa(i), Endpoint: "e", Token: "t"})
+ }
+ return m
+}
+
+func itoa(i int) string {
+ if i == 0 {
+ return "0"
+ }
+ var b []byte
+ for i > 0 {
+ b = append([]byte{byte('0' + i%10)}, b...)
+ i /= 10
+ }
+ return string(b)
+}
+
+// Two colos must never be handed the same box. This is the property that keeps
+// CAS conflicts down to the same-colo case the CAS actually exists for.
+func TestVouchersAreDisjointAcrossColos(t *testing.T) {
+ m := mgrWithWarm(30)
+ a := m.Vouchers("IAD", 10)
+ b := m.Vouchers("SJC", 10)
+ if len(a) != 10 || len(b) != 10 {
+ t.Fatalf("got %d and %d vouchers, want 10 each", len(a), len(b))
+ }
+ seen := map[string]string{}
+ for _, v := range a {
+ seen[v.MicrovmID] = "IAD"
+ }
+ for _, v := range b {
+ if other, dup := seen[v.MicrovmID]; dup {
+ t.Fatalf("box %s vouchered to both %s and SJC", v.MicrovmID, other)
+ }
+ }
+}
+
+// The reserve is what keeps the control-plane fallback path alive while the
+// edge holds promises on everything else.
+// One colo must not be able to drain the supply — traffic arrives in several,
+// and a book only helps the colo holding it.
+func TestOneColoCannotTakeEverything(t *testing.T) {
+ m := mgrWithWarm(100)
+ first := m.Vouchers("SJC", 1000)
+ if len(first) > 80 {
+ t.Fatalf("one colo took %d of 100, want <= 80", len(first))
+ }
+ // ...and still large enough to cover a pool-sized burst, which half was not.
+ if len(first) < 64 {
+ t.Fatalf("one colo got only %d of 100 — too thin to serve a burst", len(first))
+ }
+ if got := m.Vouchers("IAD", 1000); len(got) == 0 {
+ t.Fatal("second colo was starved by the first")
+ }
+}
+
+func TestVouchersKeepAReserve(t *testing.T) {
+ m := mgrWithWarm(voucherReserve + 3)
+ got := m.Vouchers("IAD", 100)
+ // Bounded by BOTH the reserve (avail = 3) and the half-of-stock colo cap.
+ if len(got) == 0 || len(got) > 3 {
+ t.Fatalf("vouchered %d, want 1..3 (reserve %d held back)", len(got), voucherReserve)
+ }
+ if m.Depth() != voucherReserve+3 {
+ t.Fatalf("Depth = %d, want %d — vouchered stock must still count", m.Depth(), voucherReserve+3)
+ }
+ // At or below the reserve, nothing is promised.
+ m2 := mgrWithWarm(voucherReserve)
+ if got := m2.Vouchers("IAD", 10); len(got) != 0 {
+ t.Fatalf("vouchered %d from a reserve-only pool, want 0", len(got))
+ }
+}
+
+func TestRedeemBindsAndIsIdempotent(t *testing.T) {
+ m := mgrWithWarm(10)
+ v := m.Vouchers("IAD", 1)[0]
+
+ box, ok, _ := m.RedeemVoucher(v.MicrovmID, "sb-cust1", Meta{Template: "t1"})
+ if !ok || box == nil {
+ t.Fatal("first redeem failed")
+ }
+ if m.VoucherStock() != 0 {
+ t.Fatalf("voucher still outstanding after redeem")
+ }
+ // Redeem again — finalize can arrive twice.
+ box2, ok, _ := m.RedeemVoucher(v.MicrovmID, "sb-cust1", Meta{Template: "t2"})
+ if !ok || box2 != box {
+ t.Fatal("redeem is not idempotent")
+ }
+ // An unknown box must not invent a binding.
+ if _, ok, _ := m.RedeemVoucher("mvm-nope", "sb-nope", Meta{}); ok {
+ t.Fatal("redeemed a voucher that was never issued")
+ }
+}
+
+// Expiry alone must NOT re-pool: an unredeemed voucher is not evidence the box
+// is free. ReconcileVouchers asks the box, and with no box reachable here it
+// must leave the promise in place rather than guess.
+func TestExpiredVoucherIsNotRepooledWithoutAsking(t *testing.T) {
+ m := mgrWithWarm(10)
+ m.http = &http.Client{Timeout: time.Millisecond}
+ vs := m.Vouchers("IAD", 3)
+ warmBefore := len(m.warm)
+
+ m.mu.Lock()
+ for _, e := range m.vouchered {
+ e.exp = time.Now().Add(-time.Second)
+ }
+ m.mu.Unlock()
+
+ m.ReconcileVouchers(context.Background())
+
+ if len(m.warm) != warmBefore {
+ t.Fatalf("warm = %d, want %d — an unverified box must never be re-pooled", len(m.warm), warmBefore)
+ }
+ if m.VoucherStock() != len(vs) {
+ t.Fatalf("vouchered = %d, want %d — unresolved promises must be retried, not dropped",
+ m.VoucherStock(), len(vs))
+ }
+}
+
+// A redeemed voucher is a customer's box and is never touched by reconciliation.
+func TestReconcileLeavesRedeemedAlone(t *testing.T) {
+ m := mgrWithWarm(10)
+ m.http = &http.Client{Timeout: time.Millisecond}
+ vs := m.Vouchers("IAD", 2)
+ if _, ok, _ := m.RedeemVoucher(vs[0].MicrovmID, "sb-kept", Meta{}); !ok {
+ t.Fatal("redeem failed")
+ }
+ m.mu.Lock()
+ for _, e := range m.vouchered {
+ e.exp = time.Now().Add(-time.Second)
+ }
+ m.mu.Unlock()
+
+ m.ReconcileVouchers(context.Background())
+
+ if _, ok := m.bound["sb-kept"]; !ok {
+ t.Fatal("reconciliation disturbed a redeemed binding")
+ }
+}
+
+// A voucher must not carry a sandbox identity, and two creates drawing the same
+// box must be able to arrive as DIFFERENT sandboxes.
+//
+// This is the defect that made burst unusable. The book is finite, so a burst
+// larger than it forces duplicate draws by pigeonhole; when the sandbox id came
+// from the voucher, a duplicate draw meant two customers holding the same
+// sandbox, and nothing downstream could tell — the guest CAS saw one id claiming
+// its box twice and correctly reported an idempotent replay. With the id minted
+// per create, the same duplicate is two sandboxes racing for one box, which the
+// CAS settles.
+func TestVoucherCarriesNoSandboxIdentity(t *testing.T) {
+ m := mgrWithWarm(10)
+ v := m.Vouchers("IAD", 1)[0]
+
+ // The same box, redeemed by the sandbox that actually won it.
+ if _, ok, _ := m.RedeemVoucher(v.MicrovmID, "sb-winner", Meta{}); !ok {
+ t.Fatal("redeem by box failed")
+ }
+ if _, ok := m.bound["sb-winner"]; !ok {
+ t.Fatal("binding was not recorded under the edge-minted sandbox id")
+ }
+ // A second create that drew the same voucher finalizes too. It must not
+ // invent a second binding for a box already spoken for.
+ if _, ok, _ := m.RedeemVoucher(v.MicrovmID, "sb-loser", Meta{}); ok {
+ t.Fatal("a spent voucher was redeemed twice under different sandboxes")
+ }
+ if _, ok := m.bound["sb-loser"]; ok {
+ t.Fatal("loser got a binding to a box it does not own")
+ }
+}
+
+// A rebind is the exec ladder telling the cell it could not use the box the
+// create announced. It has to MOVE the binding: whatever is recorded here is
+// what a destroy terminates, so keeping the first box would eventually kill one
+// belonging to someone else.
+func TestRebindMovesTheBindingToTheBoxThatWon(t *testing.T) {
+ m := mgrWithWarm(10)
+ vs := m.Vouchers("IAD", 2)
+ if len(vs) < 2 {
+ t.Fatalf("want 2 vouchers, got %d", len(vs))
+ }
+
+ if _, ok, rebound := m.RedeemVoucher(vs[0].MicrovmID, "sb-x", Meta{}); !ok || rebound {
+ t.Fatalf("first redeem: ok=%v rebound=%v, want true/false", ok, rebound)
+ }
+
+ box, ok, rebound := m.RedeemVoucher(vs[1].MicrovmID, "sb-x", Meta{})
+ if !ok || !rebound {
+ t.Fatalf("rebind: ok=%v rebound=%v, want true/true", ok, rebound)
+ }
+ if box.MicrovmID != vs[1].MicrovmID {
+ t.Fatalf("bound to %s, want the box that won (%s)", box.MicrovmID, vs[1].MicrovmID)
+ }
+
+ // The abandoned box is NOT re-pooled. It is either gone or live under
+ // another sandbox, and only the box itself can say which.
+ if got, ok := m.BoxFor("sb-x"); !ok || got.MicrovmID != vs[1].MicrovmID {
+ t.Fatalf("BoxFor: %v %v, want %s", got, ok, vs[1].MicrovmID)
+ }
+}
+
+// The rotation-survival property. A cache instance holds its stock in RAM, so
+// an 8h rotation or a restart loses every promise while this side still thinks
+// those boxes are spoken for. If the replacement could only draw from `warm` it
+// would come up nearly empty and stay that way until each promise aged out —
+// minutes of creates falling through on precisely the event rotation is meant
+// to hide.
+func TestColoVouchersRelistsSoAReplacementComesUpFull(t *testing.T) {
+ m := mgrWithWarm(100)
+ first := m.ColoVouchers("cache", 60)
+ if len(first) == 0 {
+ t.Fatal("no vouchers issued")
+ }
+ warmAfter := len(m.warm)
+
+ // The instance holding these dies; a fresh one asks for the same set.
+ second := m.ColoVouchers("cache", 60)
+ if len(second) != len(first) {
+ t.Fatalf("replacement got %d, want the same %d — it must come up full", len(second), len(first))
+ }
+ if len(m.warm) != warmAfter {
+ t.Fatalf("warm = %d, want %d — re-listing must not consume more stock", len(m.warm), warmAfter)
+ }
+ ids := map[string]bool{}
+ for _, v := range first {
+ ids[v.MicrovmID] = true
+ }
+ for _, v := range second {
+ if !ids[v.MicrovmID] {
+ t.Fatalf("box %s appeared only on the re-list", v.MicrovmID)
+ }
+ }
+}
+
+// Re-listing must refresh expiry, or a long-lived cache would be handed
+// vouchers that its own expiry guard immediately discards.
+func TestColoVouchersRefreshesExpiry(t *testing.T) {
+ m := mgrWithWarm(20)
+ first := m.ColoVouchers("cache", 5)
+ if len(first) == 0 {
+ t.Fatal("no vouchers")
+ }
+ m.mu.Lock()
+ for _, e := range m.vouchered {
+ e.exp = time.Now().Add(30 * time.Second)
+ }
+ m.mu.Unlock()
+
+ second := m.ColoVouchers("cache", 5)
+ for _, v := range second {
+ if time.Until(time.Unix(v.ExpiresAtUnix, 0)) < time.Minute {
+ t.Fatalf("box %s re-listed with a stale expiry", v.MicrovmID)
+ }
+ }
+}
+
+// A second holder must not be handed boxes already promised to the cache.
+func TestColoVouchersDoesNotLeakAcrossHolders(t *testing.T) {
+ m := mgrWithWarm(100)
+ mine := m.ColoVouchers("cache", 40)
+ other := m.ColoVouchers("SJC", 40)
+ seen := map[string]bool{}
+ for _, v := range mine {
+ seen[v.MicrovmID] = true
+ }
+ for _, v := range other {
+ if seen[v.MicrovmID] {
+ t.Fatalf("box %s promised to both holders", v.MicrovmID)
+ }
+ }
+}
diff --git a/internal/db/migrations/055_orgs_runtime.down.sql b/internal/db/migrations/055_orgs_runtime.down.sql
new file mode 100644
index 00000000..127d1bb2
--- /dev/null
+++ b/internal/db/migrations/055_orgs_runtime.down.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs DROP COLUMN IF EXISTS runtime;
diff --git a/internal/db/migrations/055_orgs_runtime.up.sql b/internal/db/migrations/055_orgs_runtime.up.sql
new file mode 100644
index 00000000..c0bdbf76
--- /dev/null
+++ b/internal/db/migrations/055_orgs_runtime.up.sql
@@ -0,0 +1,12 @@
+-- Per-org runtime for the direct-to-cell create path.
+--
+-- D1's orgs.runtime stays authoritative: the edge stamps it onto every
+-- capability token, and a cap-token create reads it from there without
+-- touching this column. But a create that authenticates with an API key
+-- straight against this cell has no token to carry it, and org runtime is not
+-- otherwise knowable here. This is that value, synced from the token whenever
+-- an edge create comes through.
+--
+-- '' is the QEMU fleet, matching runtimeFor's documented default, so adding
+-- this column changes nothing for any existing org until it is set.
+ALTER TABLE orgs ADD COLUMN IF NOT EXISTS runtime TEXT NOT NULL DEFAULT '';
diff --git a/internal/db/store.go b/internal/db/store.go
index b3ef98be..8e45bc5f 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -97,7 +97,11 @@ func NewStore(ctx context.Context, databaseURL string) (*Store, error) {
// Default pool is 4 connections — far too low for proxy-per-request pattern.
// Each proxied exec/file/pty call does a DB lookup before forwarding.
poolCfg.MaxConns = 50
- poolCfg.MinConns = 5
+ // A burst arrives all at once, so a pool that idles low makes most of those
+ // requests wait on a fresh TCP connection plus a Postgres auth handshake
+ // before doing any work. Holding connections open costs almost nothing on a
+ // single control plane and removes that stampede.
+ poolCfg.MinConns = 20
// Recycle connections periodically to prevent stale/leaked connections from
// piling up on the Postgres server (e.g. after worker restarts/deletions).
poolCfg.MaxConnLifetime = 30 * time.Minute
@@ -202,6 +206,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{52, "migrations/052_paused_hibernation_mode.up.sql"},
{53, "migrations/053_default_org_concurrency_50.up.sql"},
{54, "migrations/054_sandbox_pool.up.sql"},
+ {55, "migrations/055_orgs_runtime.up.sql"},
}
for _, m := range migrations {
@@ -375,7 +380,24 @@ func (s *Store) GetOrgPlan(ctx context.Context, orgID string) (string, error) {
// Plan from the cap-token wins on insert; on conflict we update plan so a
// pro-upgrade reflected at the edge propagates to the cell on the next
// sandbox-create round-trip without a separate sync job.
-func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan, billingProvider string) error {
+// GetOrgRuntime returns the runtime this org's sandboxes should be placed on,
+// or "" (the QEMU fleet) when the org is unknown or unset.
+//
+// Only the direct-to-cell create path needs this — a create that came through
+// the edge carries the runtime on its capability token and never reads here.
+func (s *Store) GetOrgRuntime(ctx context.Context, orgID uuid.UUID) (string, error) {
+ var runtime string
+ err := s.pool.QueryRow(ctx, `SELECT runtime FROM orgs WHERE id = $1`, orgID).Scan(&runtime)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", nil
+ }
+ return "", fmt.Errorf("get org runtime: %w", err)
+ }
+ return runtime, nil
+}
+
+func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan, billingProvider, runtime string) error {
if plan != "pro" {
plan = "free"
}
@@ -384,16 +406,21 @@ func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan
// that doesn't set it) → keep the existing cell-PG value, and default a
// brand-new row to 'legacy'. So a wake/preview token can never clobber an
// org that the create path or backfill already flipped to 'autumn'.
+ // runtime follows the same "empty means keep" rule as billing_provider, and
+ // for the same reason: a token minted before runtime rode on it must not
+ // reset an org that is already flipped to a non-QEMU backend.
_, err := s.pool.Exec(ctx,
- `INSERT INTO orgs (id, name, slug, plan, billing_provider)
- VALUES ($1, $2, $3, $4, COALESCE(NULLIF($5, ''), 'legacy'))
+ `INSERT INTO orgs (id, name, slug, plan, billing_provider, runtime)
+ VALUES ($1, $2, $3, $4, COALESCE(NULLIF($5, ''), 'legacy'), COALESCE(NULLIF($6, ''), ''))
ON CONFLICT (id) DO UPDATE SET
plan = EXCLUDED.plan,
billing_provider = CASE WHEN NULLIF($5, '') IS NULL THEN orgs.billing_provider ELSE $5 END,
+ runtime = CASE WHEN NULLIF($6, '') IS NULL THEN orgs.runtime ELSE $6 END,
updated_at = NOW()
WHERE orgs.plan IS DISTINCT FROM EXCLUDED.plan
- OR (NULLIF($5, '') IS NOT NULL AND orgs.billing_provider IS DISTINCT FROM $5)`,
- orgID, "org-"+orgID.String()[:8], orgID.String(), plan, billingProvider,
+ OR (NULLIF($5, '') IS NOT NULL AND orgs.billing_provider IS DISTINCT FROM $5)
+ OR (NULLIF($6, '') IS NOT NULL AND orgs.runtime IS DISTINCT FROM $6)`,
+ orgID, "org-"+orgID.String()[:8], orgID.String(), plan, billingProvider, runtime,
)
if err != nil {
return fmt.Errorf("upsert org from cap-token: %w", err)
@@ -733,8 +760,16 @@ func (s *Store) ValidateAPIKey(ctx context.Context, keyPlaintext string) (uuid.U
if expiresAt != nil && expiresAt.Before(time.Now()) {
return uuid.Nil, nil, fmt.Errorf("API key expired")
}
- // Update last_used
- _, _ = s.pool.Exec(ctx, `UPDATE api_keys SET last_used = now() WHERE key_hash = $1`, hash)
+ // last_used is stamped off the request's critical path. Done inline it was
+ // a second Postgres round trip on every authenticated call — a write, on
+ // the hot path, whose only consumer is a dashboard column. The request
+ // context is deliberately not reused: it is cancelled the moment the
+ // response is written, which would abort this most of the time.
+ go func() {
+ bg, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _, _ = s.pool.Exec(bg, `UPDATE api_keys SET last_used = now() WHERE key_hash = $1`, hash)
+ }()
return orgID, createdBy, nil
}
@@ -902,6 +937,29 @@ func (s *Store) CreateSandboxSessionWithStatus(ctx context.Context, sandboxID st
return session, nil
}
+// UpdateSandboxSessionWorker moves a running sandbox to a different worker.
+//
+// The voucher path needs this: the edge finalizes a create against the box it
+// drew, but the exec ladder can end up on a DIFFERENT box (the first one was
+// dead, or already owned) and re-sends the finalize naming the box that actually
+// took the claim. Without this the row keeps pointing at the first box, and
+// destroying the sandbox would terminate one belonging to someone else.
+//
+// Guarded on status='running' so a finalize arriving after a destroy cannot
+// resurrect or re-point a terminated row.
+func (s *Store) UpdateSandboxSessionWorker(ctx context.Context, sandboxID, workerID string) error {
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET worker_id = $2 WHERE sandbox_id = $1 AND status = 'running'`,
+ sandboxID, workerID)
+ if err != nil {
+ return fmt.Errorf("failed to rebind sandbox worker: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("no running sandbox %s to rebind", sandboxID)
+ }
+ return nil
+}
+
func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, status string, errorMsg *string) error {
return s.updateSandboxSessionStatus(ctx, sandboxID, status, errorMsg, "")
}
diff --git a/internal/reqtime/reqtime.go b/internal/reqtime/reqtime.go
new file mode 100644
index 00000000..f9b2bff5
--- /dev/null
+++ b/internal/reqtime/reqtime.go
@@ -0,0 +1,79 @@
+// Package reqtime carries per-request timing that spans the middleware chain.
+//
+// The create trace starts inside the handler, which is exactly the wrong place
+// to answer the question it was built for. Instrumenting the create path showed
+// every in-handler mark at 0.0ms — including `tot` — while the client measured
+// a 215ms create. A handler that finishes in under a millisecond cannot be the
+// thing costing 215ms, so the cost is upstream of it, and the trace as built
+// cannot see upstream of itself.
+//
+// This package covers the gap between Go accepting the request and the handler
+// being entered: the middleware chain, and specifically the API-key validation
+// that does two Postgres round trips before any handler runs. It lives in its
+// own package because both internal/api and internal/auth need it and neither
+// may import the other.
+package reqtime
+
+import (
+ "sync/atomic"
+ "time"
+
+ "github.com/labstack/echo/v4"
+)
+
+// ctxKey is the echo-context key. A string rather than a struct{} because
+// echo.Context.Set takes a string.
+const ctxKey = "osb_reqtime"
+
+// T accumulates timings for one request.
+type T struct {
+ // Start is when the outermost middleware saw the request. Everything
+ // before it — accept queue, TCP, TLS — is by construction invisible here,
+ // and that invisibility is itself the signal: if Start-to-response is
+ // near zero and the client still measured hundreds of ms, the queue is in
+ // front of Go and no server-side change will move it.
+ Start time.Time
+
+ authNanos atomic.Int64
+}
+
+// Middleware installs a T on the context. Register it outermost.
+func Middleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ c.Set(ctxKey, &T{Start: time.Now()})
+ return next(c)
+ }
+ }
+}
+
+// From returns the request's T, or nil if the middleware is not installed
+// (which is the case in unit tests that build a bare echo context).
+func From(c echo.Context) *T {
+ t, _ := c.Get(ctxKey).(*T)
+ return t
+}
+
+// AddAuth records time spent authenticating. Additive because a request can
+// take more than one validation path before one succeeds.
+func AddAuth(c echo.Context, d time.Duration) {
+ if t := From(c); t != nil {
+ t.authNanos.Add(int64(d))
+ }
+}
+
+// Auth is the accumulated authentication time.
+func (t *T) Auth() time.Duration {
+ if t == nil {
+ return 0
+ }
+ return time.Duration(t.authNanos.Load())
+}
+
+// Since is time elapsed inside Go's handler chain so far.
+func (t *T) Since() time.Duration {
+ if t == nil {
+ return 0
+ }
+ return time.Since(t.Start)
+}
diff --git a/internal/vouchercache/server.go b/internal/vouchercache/server.go
new file mode 100644
index 00000000..6b9b4bb1
--- /dev/null
+++ b/internal/vouchercache/server.go
@@ -0,0 +1,304 @@
+// Package vouchercache is the in-region voucher store the edge pops from.
+//
+// It runs INSIDE the guest agent rather than as its own process, and that is
+// not a packaging preference — it is forced. The AWS proxy forwards only to the
+// port declared in the image's hook config, and the auth token it mints is
+// scoped to that single port (see internal/awsvm/agent.go). A second listener
+// on a box is unreachable: a standalone build of this answered every request
+// with "403 Access to port denied". So the cache is mounted by the process that
+// already owns the allowed port.
+//
+// Why it exists at all: the previous store was Cloudflare's colo Cache API,
+// which is not atomic, is per-colo, and — the part that actually hurt — is
+// EVICTABLE. A colo that lost its book rebuilt it from the control plane in
+// westus2, and burst TTI went from ~300ms to 1498ms. A benchmark arriving cold
+// paid that every time. Holding the stock in RAM in us-east-1 removes all
+// three properties at once: one mutex makes a pop atomic, one instance serves
+// every colo, and a process does not evict.
+//
+// Two invariants, and everything else follows from them:
+//
+// 1. A POP NEVER REFILLS. Stock arrives by push from the control plane on a
+// timer, off the hot path. An empty cache answers 204 immediately and the
+// edge falls through to the (slower, correct) control-plane create. No
+// customer request ever waits behind a restock — that coupling is exactly
+// what made the colo book cliff.
+//
+// 2. THE CACHE IS NEVER AUTHORITATIVE ON OWNERSHIP. A voucher is a hint that a
+// box is probably free; the guest CAS settles it. That is what lets this
+// side hand one out with no durable write, and why losing every voucher in
+// a restart is a throughput event rather than a correctness one.
+//
+// The control plane pushes rather than this side pulling, so the cell's signing
+// secret never has to live on a box.
+
+package vouchercache
+
+import (
+ "encoding/json"
+ "log"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/awsvmlite"
+)
+
+// Peer is one instance of this service, as the control plane sees it.
+//
+// It is echoed back on every pop so the edge relearns the current set on
+// ordinary traffic. Rotation depends on this: boxes die at the 8h service cap,
+// so the control plane stands a replacement up and adds it here BEFORE retiring
+// the incumbent, and the edge follows along without ever asking anyone where to
+// go. Only a completely cold edge has to fall back to the control plane.
+type Peer struct {
+ Endpoint string `json:"endpoint"`
+ Token string `json:"token"`
+ Port int32 `json:"port"`
+ // RetireAtUnix lets the edge prefer an instance that is not about to
+ // vanish, rather than discovering it the hard way on a pop.
+ RetireAtUnix int64 `json:"retireAtUnix,omitempty"`
+}
+
+type fillRequest struct {
+ Vouchers []awsvmlite.Voucher `json:"vouchers"`
+ Peers []Peer `json:"peers,omitempty"`
+ // Target is the depth the control plane is aiming for. Reported on health
+ // so the filler's own view and this process's view can be compared without
+ // correlating two logs.
+ Target int `json:"target,omitempty"`
+}
+
+type popResponse struct {
+ Voucher *awsvmlite.Voucher `json:"voucher"`
+ Peers []Peer `json:"peers,omitempty"`
+ Depth int `json:"depth"`
+}
+
+type Server struct {
+ secret string
+
+ mu sync.Mutex
+ stock []awsvmlite.Voucher
+ // held dedups fills. The control plane re-sends its whole warm set on
+ // every tick (it is stateless about what we already have), so without this
+ // a box would appear several times and be handed to several sandboxes —
+ // survivable, since the CAS settles it, but it wastes a create's ladder.
+ held map[string]struct{}
+ peers []Peer
+ target int
+ lastFill time.Time
+ ready bool
+
+ pops int64
+ empties int64
+ fills int64
+}
+
+// expiryGuard drops a voucher this close to its reaper deadline rather than
+// handing out one that will lose its race with ReconcileVouchers.
+const expiryGuard = 120 * time.Second
+
+func (s *Server) authed(w http.ResponseWriter, r *http.Request) bool {
+ if s.secret == "" || r.Header.Get("X-osb-cache-auth") == s.secret {
+ return true
+ }
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return false
+}
+
+// handleFill replaces what we hold with what the control plane currently
+// believes is free.
+//
+// Additive, not authoritative: a voucher already in stock is left where it is
+// (so a fill does not reorder the queue under a concurrent pop), and one the
+// control plane has stopped listing is NOT removed — it may be sitting in an
+// edge isolate about to be redeemed, and dropping it here would not recall it
+// anyway. Expiry is what removes stock, and the reaper on the cell side is what
+// makes that safe.
+func (s *Server) handleFill(w http.ResponseWriter, r *http.Request) {
+ if !s.authed(w, r) {
+ return
+ }
+ var req fillRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ http.Error(w, "bad json", http.StatusBadRequest)
+ return
+ }
+ now := time.Now()
+ s.mu.Lock()
+ added := 0
+ for _, v := range req.Vouchers {
+ if v.MicrovmID == "" || v.Endpoint == "" {
+ continue
+ }
+ if time.Unix(v.ExpiresAtUnix, 0).Sub(now) <= expiryGuard {
+ continue
+ }
+ if _, dup := s.held[v.MicrovmID]; dup {
+ continue
+ }
+ s.held[v.MicrovmID] = struct{}{}
+ s.stock = append(s.stock, v)
+ added++
+ }
+ s.dropExpiredLocked(now)
+ if len(req.Peers) > 0 {
+ s.peers = req.Peers
+ }
+ if req.Target > 0 {
+ s.target = req.Target
+ }
+ s.lastFill = now
+ s.fills++
+ // Readiness is depth-gated, not fill-gated. A fresh instance must not take
+ // traffic on an empty or half-filled first push — it would answer 204 to
+ // creates that the outgoing instance could have served, which is exactly
+ // the gap a rotation is supposed to hide.
+ if !s.ready && len(s.stock) > 0 && (s.target == 0 || len(s.stock)*2 >= s.target) {
+ s.ready = true
+ log.Printf("voucher-cache: READY depth=%d target=%d", len(s.stock), s.target)
+ }
+ depth := len(s.stock)
+ s.mu.Unlock()
+
+ writeJSON(w, map[string]any{"ok": true, "added": added, "depth": depth})
+}
+
+// dropExpiredLocked prunes stock that aged out while it sat here. Callers hold
+// s.mu.
+func (s *Server) dropExpiredLocked(now time.Time) {
+ keep := s.stock[:0]
+ for _, v := range s.stock {
+ if time.Unix(v.ExpiresAtUnix, 0).Sub(now) > expiryGuard {
+ keep = append(keep, v)
+ continue
+ }
+ delete(s.held, v.MicrovmID)
+ }
+ s.stock = keep
+}
+
+// handlePop hands out exactly one voucher.
+//
+// This is the whole point of the service: the mutex makes "which caller gets
+// this box" a decision rather than a race. The colo cache could not do that —
+// concurrent draws collided by birthday (37 of 100 at a 120-slot book), and the
+// free-list claim that fixed it cost a probe loop per create.
+//
+// It does NOT refill on empty. See the file header.
+func (s *Server) handlePop(w http.ResponseWriter, r *http.Request) {
+ if !s.authed(w, r) {
+ return
+ }
+ now := time.Now()
+ s.mu.Lock()
+ if !s.ready {
+ s.mu.Unlock()
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ s.dropExpiredLocked(now)
+ var out *awsvmlite.Voucher
+ if len(s.stock) > 0 {
+ v := s.stock[0]
+ s.stock = s.stock[1:]
+ delete(s.held, v.MicrovmID)
+ out = &v
+ s.pops++
+ } else {
+ s.empties++
+ }
+ resp := popResponse{Voucher: out, Peers: s.peers, Depth: len(s.stock)}
+ empties, pops := s.empties, s.pops
+ s.mu.Unlock()
+
+ if out == nil {
+ // Said out loud: an empty cache is a sizing failure, and it is silent
+ // from the edge's side (the create just takes the slow path and still
+ // succeeds). Without this line the only symptom is a latency
+ // regression nobody can attribute.
+ if empties%50 == 1 {
+ log.Printf("voucher-cache: EMPTY pops=%d empties=%d — stock exhausted, creates falling through", pops, empties)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ writeJSON(w, resp)
+}
+
+// handleRelease takes a voucher back.
+//
+// Only for a voucher the edge is certain it never handed to a customer — it
+// drew one and then failed before the claim. A box that lost a CAS is NOT
+// released here: it is live under someone else's sandbox, and re-pooling it
+// would hand a running box to a second customer. The edge cannot tell those
+// apart, so it only calls this on its own local failures.
+func (s *Server) handleRelease(w http.ResponseWriter, r *http.Request) {
+ if !s.authed(w, r) {
+ return
+ }
+ var v awsvmlite.Voucher
+ if err := json.NewDecoder(r.Body).Decode(&v); err != nil || v.MicrovmID == "" {
+ http.Error(w, "bad json", http.StatusBadRequest)
+ return
+ }
+ s.mu.Lock()
+ if _, dup := s.held[v.MicrovmID]; !dup && time.Unix(v.ExpiresAtUnix, 0).Sub(time.Now()) > expiryGuard {
+ s.held[v.MicrovmID] = struct{}{}
+ s.stock = append(s.stock, v)
+ }
+ depth := len(s.stock)
+ s.mu.Unlock()
+ writeJSON(w, map[string]any{"ok": true, "depth": depth})
+}
+
+func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
+ s.mu.Lock()
+ age := int64(-1)
+ if !s.lastFill.IsZero() {
+ age = time.Since(s.lastFill).Milliseconds()
+ }
+ out := map[string]any{
+ "ready": s.ready,
+ "depth": len(s.stock),
+ "target": s.target,
+ "pops": s.pops,
+ "empties": s.empties,
+ "fills": s.fills,
+ "lastFillAgeMs": age,
+ "peers": len(s.peers),
+ }
+ s.mu.Unlock()
+ writeJSON(w, out)
+}
+
+func writeJSON(w http.ResponseWriter, v any) {
+ w.Header().Set("content-type", "application/json")
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+// New builds an empty cache. It serves nothing until the control plane fills
+// it — see the readiness gate in handleFill.
+func New(secret string) *Server {
+ return &Server{secret: secret, held: map[string]struct{}{}}
+}
+
+// Mount attaches the cache under prefix on the guest agent's mux.
+//
+// Sharing the agent's listener is what makes this reachable at all, and it also
+// means a cache instance is an ordinary box: no extra binary to install, no
+// second port, and the same proxy keepalive already keeps it warm.
+func (s *Server) Mount(mux *http.ServeMux, prefix string) {
+ mux.HandleFunc(prefix+"fill", s.handleFill)
+ mux.HandleFunc(prefix+"pop", s.handlePop)
+ mux.HandleFunc(prefix+"release", s.handleRelease)
+ mux.HandleFunc(prefix+"stats", s.handleHealth)
+}
+
+// Depth reports current stock, for the agent's own logging.
+func (s *Server) Depth() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.stock)
+}
diff --git a/internal/vouchercache/server_test.go b/internal/vouchercache/server_test.go
new file mode 100644
index 00000000..82be6aa1
--- /dev/null
+++ b/internal/vouchercache/server_test.go
@@ -0,0 +1,261 @@
+package vouchercache
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/awsvmlite"
+)
+
+func newTestServer() *Server {
+ return New("")
+}
+
+func vouchers(n int) []awsvmlite.Voucher {
+ exp := time.Now().Add(time.Hour).Unix()
+ out := make([]awsvmlite.Voucher, 0, n)
+ for i := 0; i < n; i++ {
+ out = append(out, awsvmlite.Voucher{
+ MicrovmID: "mvm-" + strconvItoa(i),
+ Endpoint: "e.example",
+ Token: "t",
+ Port: 8080,
+ ExpiresAtUnix: exp,
+ })
+ }
+ return out
+}
+
+func strconvItoa(i int) string {
+ if i == 0 {
+ return "0"
+ }
+ var b []byte
+ for i > 0 {
+ b = append([]byte{byte('0' + i%10)}, b...)
+ i /= 10
+ }
+ return string(b)
+}
+
+func fill(t *testing.T, s *Server, req fillRequest) {
+ t.Helper()
+ body, _ := json.Marshal(req)
+ rec := httptest.NewRecorder()
+ s.handleFill(rec, httptest.NewRequest(http.MethodPost, "/fill", bytes.NewReader(body)))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("fill: %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+func pop(s *Server) (*awsvmlite.Voucher, int) {
+ rec := httptest.NewRecorder()
+ s.handlePop(rec, httptest.NewRequest(http.MethodPost, "/pop", nil))
+ if rec.Code != http.StatusOK {
+ return nil, rec.Code
+ }
+ var r popResponse
+ _ = json.Unmarshal(rec.Body.Bytes(), &r)
+ return r.Voucher, rec.Code
+}
+
+// THE property. The colo cache could not give us this: concurrent draws
+// collided by birthday, and the free-list claim that patched it cost a probe
+// loop on every create. A mutex makes it a decision.
+func TestPopNeverHandsTheSameBoxTwice(t *testing.T) {
+ s := newTestServer()
+ fill(t, s, fillRequest{Vouchers: vouchers(200), Target: 200})
+
+ var mu sync.Mutex
+ seen := map[string]int{}
+ var wg sync.WaitGroup
+ for i := 0; i < 200; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ v, _ := pop(s)
+ if v == nil {
+ return
+ }
+ mu.Lock()
+ seen[v.MicrovmID]++
+ mu.Unlock()
+ }()
+ }
+ wg.Wait()
+
+ if len(seen) != 200 {
+ t.Fatalf("got %d distinct boxes from 200 concurrent pops, want 200", len(seen))
+ }
+ for id, n := range seen {
+ if n != 1 {
+ t.Fatalf("box %s handed out %d times", id, n)
+ }
+ }
+}
+
+// An empty cache must answer immediately, not restock. A pop that refilled
+// would put a control-plane round trip back on a customer's create — the exact
+// coupling that made a lost colo book cost 1498ms.
+func TestPopOnEmptyIsImmediateAndDoesNotRefill(t *testing.T) {
+ s := newTestServer()
+ fill(t, s, fillRequest{Vouchers: vouchers(1), Target: 1})
+ if v, _ := pop(s); v == nil {
+ t.Fatal("first pop should have served the only voucher")
+ }
+ for i := 0; i < 3; i++ {
+ rec := httptest.NewRecorder()
+ s.handlePop(rec, httptest.NewRequest(http.MethodPost, "/pop", nil))
+ if rec.Code != http.StatusNoContent {
+ t.Fatalf("empty pop: %d, want 204", rec.Code)
+ }
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.fills != 1 {
+ t.Fatalf("fills = %d, want 1 — a pop refilled", s.fills)
+ }
+}
+
+// A fresh instance must not take traffic before it has stock. Answering 204
+// during a rotation would strand creates the outgoing instance could still
+// have served, which is the gap rotation exists to hide.
+func TestNotReadyUntilStocked(t *testing.T) {
+ s := newTestServer()
+ rec := httptest.NewRecorder()
+ s.handlePop(rec, httptest.NewRequest(http.MethodPost, "/pop", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("cold pop: %d, want 503", rec.Code)
+ }
+ // A first push that only half-covers target is still not ready.
+ fill(t, s, fillRequest{Vouchers: vouchers(3), Target: 100})
+ s.mu.Lock()
+ ready := s.ready
+ s.mu.Unlock()
+ if ready {
+ t.Fatal("ready on 3 of a 100 target — a rotation would open a hole")
+ }
+ fill(t, s, fillRequest{Vouchers: vouchers(60), Target: 100})
+ if v, code := pop(s); v == nil {
+ t.Fatalf("pop after adequate fill: code %d", code)
+ }
+}
+
+// The control plane re-sends its whole warm set every tick. Without dedup the
+// same box accumulates and gets handed to several sandboxes — survivable (the
+// CAS settles it) but it burns a create's retry ladder for nothing.
+func TestFillIsIdempotent(t *testing.T) {
+ s := newTestServer()
+ for i := 0; i < 5; i++ {
+ fill(t, s, fillRequest{Vouchers: vouchers(10), Target: 10})
+ }
+ s.mu.Lock()
+ depth := len(s.stock)
+ s.mu.Unlock()
+ if depth != 10 {
+ t.Fatalf("depth = %d after 5 identical fills, want 10", depth)
+ }
+}
+
+// A voucher near its reaper deadline is worse than no voucher: the create
+// spends its ladder on a box the cell is about to take back.
+func TestExpiredStockIsNeverHandedOut(t *testing.T) {
+ s := newTestServer()
+ good := vouchers(2)
+ stale := vouchers(2)
+ for i := range stale {
+ stale[i].MicrovmID = "stale-" + strconvItoa(i)
+ stale[i].ExpiresAtUnix = time.Now().Add(10 * time.Second).Unix()
+ }
+ fill(t, s, fillRequest{Vouchers: append(append([]awsvmlite.Voucher{}, good...), stale...), Target: 4})
+
+ seen := map[string]bool{}
+ for i := 0; i < 4; i++ {
+ v, _ := pop(s)
+ if v == nil {
+ break
+ }
+ seen[v.MicrovmID] = true
+ }
+ for id := range seen {
+ if len(id) > 5 && id[:5] == "stale" {
+ t.Fatalf("handed out %s, which expires inside the guard", id)
+ }
+ }
+ if len(seen) != 2 {
+ t.Fatalf("served %d vouchers, want the 2 live ones", len(seen))
+ }
+}
+
+// Release is for a voucher the edge drew and never used. It must come back —
+// otherwise every edge-side failure permanently shrinks the pool.
+func TestReleaseReturnsStock(t *testing.T) {
+ s := newTestServer()
+ fill(t, s, fillRequest{Vouchers: vouchers(2), Target: 2})
+ v, _ := pop(s)
+ if v == nil {
+ t.Fatal("pop failed")
+ }
+ body, _ := json.Marshal(v)
+ rec := httptest.NewRecorder()
+ s.handleRelease(rec, httptest.NewRequest(http.MethodPost, "/release", bytes.NewReader(body)))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("release: %d", rec.Code)
+ }
+ s.mu.Lock()
+ depth := len(s.stock)
+ s.mu.Unlock()
+ if depth != 2 {
+ t.Fatalf("depth = %d after release, want 2", depth)
+ }
+ // ...and releasing the same voucher twice must not duplicate it.
+ rec2 := httptest.NewRecorder()
+ s.handleRelease(rec2, httptest.NewRequest(http.MethodPost, "/release", bytes.NewReader(body)))
+ s.mu.Lock()
+ depth = len(s.stock)
+ s.mu.Unlock()
+ if depth != 2 {
+ t.Fatalf("depth = %d after double release, want 2", depth)
+ }
+}
+
+// Rotation hinges on this: the edge learns the replacement instance from
+// ordinary pop traffic, so it is already talking to the new box before the old
+// one hits the 8h cap.
+func TestPopCarriesThePeerList(t *testing.T) {
+ s := newTestServer()
+ peers := []Peer{{Endpoint: "a.example", Token: "t1", Port: 8079}, {Endpoint: "b.example", Token: "t2", Port: 8079}}
+ fill(t, s, fillRequest{Vouchers: vouchers(4), Target: 4, Peers: peers})
+
+ rec := httptest.NewRecorder()
+ s.handlePop(rec, httptest.NewRequest(http.MethodPost, "/pop", nil))
+ var r popResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &r); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(r.Peers) != 2 || r.Peers[1].Endpoint != "b.example" {
+ t.Fatalf("peers = %+v, want both instances", r.Peers)
+ }
+}
+
+func TestSecretIsEnforced(t *testing.T) {
+ s := newTestServer()
+ s.secret = "shh"
+ rec := httptest.NewRecorder()
+ s.handlePop(rec, httptest.NewRequest(http.MethodPost, "/pop", nil))
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("unauthenticated pop: %d, want 401", rec.Code)
+ }
+ req := httptest.NewRequest(http.MethodPost, "/pop", nil)
+ req.Header.Set("X-osb-cache-auth", "shh")
+ rec2 := httptest.NewRecorder()
+ s.handlePop(rec2, req)
+ if rec2.Code == http.StatusUnauthorized {
+ t.Fatal("correct secret was rejected")
+ }
+}