Skip to content

An open-source, faster Devin alternative

TypeScript

remove the voucher stuff

Brian Reardon323350d15cee
diff --git a/cloudflare-workers/api-edge/src/colo_cache.ts b/cloudflare-workers/api-edge/src/colo_cache.ts
index 9d3631de..eb071679 100644
--- a/cloudflare-workers/api-edge/src/colo_cache.ts
+++ b/cloudflare-workers/api-edge/src/colo_cache.ts
@@ -76,7 +76,7 @@ export async function coloPut(kind: string, key: string, value: unknown, ttlSec:
// 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.
+// a colo-shared free list.
export async function coloDelete(kind: string, key: string): Promise<boolean> {
const cache = cacheOrNull();
if (!cache) return false;
diff --git a/cloudflare-workers/api-edge/src/create_batch.test.ts b/cloudflare-workers/api-edge/src/create_batch.test.ts
deleted file mode 100644
index 35575cee..00000000
--- a/cloudflare-workers/api-edge/src/create_batch.test.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
-import { createViaCell, __resetCreateBatchState } from "./create_batch";
-
-const BASE = "https://cp.example.com";
-const TOKEN = "tok-a";
-/** Captured before any test stubs setTimeout, so a stub can still schedule. */
-const realSetTimeout = globalThis.setTimeout;
-
-interface Sent {
- url: string;
- auth: string;
- body: string;
-}
-
-/**
- * Stands in for the control plane. `hold` lets a test keep creates in flight,
- * which is the only way to reach the batching path: a create with nothing else
- * outstanding is deliberately sent alone.
- */
-function installFetch(opts: {
- hold?: Promise<void>;
- batchStatus?: number;
- batchBody?: (items: unknown[]) => unknown;
-}): { sent: Sent[] } {
- const sent: Sent[] = [];
- vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
- const body = String(init.body);
- sent.push({ url, auth: String((init.headers as Record<string, string>).authorization), body });
- if (url.endsWith("/create-batch")) {
- if (opts.hold) await opts.hold;
- const status = opts.batchStatus ?? 200;
- if (status !== 200) return new Response("nope", { status });
- const items = (JSON.parse(body) as { items: unknown[] }).items;
- const payload = opts.batchBody
- ? opts.batchBody(items)
- : { results: items.map((it) => ({ status: 201, body: { echo: it } })) };
- return new Response(JSON.stringify(payload), { status: 200 });
- }
- if (opts.hold) await opts.hold;
- // Tolerant of a non-JSON body: one test deliberately sends one.
- let echo: unknown = body;
- try {
- echo = JSON.parse(body || "{}");
- } catch {
- /* keep the raw text */
- }
- return new Response(JSON.stringify({ echo }), { status: 201 });
- });
- return { sent };
-}
-
-beforeEach(() => __resetCreateBatchState());
-afterEach(() => vi.unstubAllGlobals());
-
-describe("createViaCell", () => {
- // Sequential traffic is already fast and has nobody to batch with. If it ever
- // starts paying a coalescing window, this fix has made the common case worse.
- it("sends a lone create immediately and unbatched", async () => {
- const { sent } = installFetch({});
- const r = await createViaCell(BASE, TOKEN, '{"n":1}', true);
- expect(r.batched).toBe(false);
- expect(r.batchSize).toBe(1);
- expect(r.waitMs).toBe(0);
- expect(sent).toHaveLength(1);
- expect(sent[0].url).toBe(BASE + "/internal/sandboxes/create");
- });
-
- // The whole point: N concurrent creates cost ONE connection, not N.
- it("coalesces concurrent creates into a single request", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold });
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 20 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- const results = await Promise.all([first, ...rest]);
-
- // One lone create (it arrived first, with nothing in flight) plus exactly one
- // batch carrying the other twenty.
- expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);
- expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(1);
- expect(results.filter((r) => r.batched)).toHaveLength(20);
- expect(results[1].batchSize).toBe(20);
- });
-
- // Results are positional. A shuffle hands caller A the sandbox caller B asked
- // for — silently, and with no error anywhere.
- it("returns each waiter its own result", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold });
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 10 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- const results = await Promise.all([first, ...rest]);
-
- results.forEach((r, i) => {
- expect(JSON.parse(r.text).echo).toEqual({ n: i });
- });
- });
-
- // The CP verifies the cap-token ONCE and every item in the batch inherits
- // those claims. Two callers sharing a request would mean one org's create
- // authorized by another org's token.
- it("never batches creates carrying different cap-tokens", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold });
-
- // n=0 arrives with nothing in flight and so goes out alone; the rest split
- // into one batch per token.
- const all = [
- createViaCell(BASE, "tok-a", '{"n":0}', true),
- createViaCell(BASE, "tok-a", '{"n":1}', true),
- createViaCell(BASE, "tok-a", '{"n":2}', true),
- createViaCell(BASE, "tok-b", '{"n":3}', true),
- createViaCell(BASE, "tok-b", '{"n":4}', true),
- ];
- await vi.waitFor(() => expect(sent.filter((s) => s.url.endsWith("/create-batch")).length).toBe(2));
- release();
- await Promise.all(all);
-
- for (const s of sent.filter((s) => s.url.endsWith("/create-batch"))) {
- const items = (JSON.parse(s.body) as { items: { n: number }[] }).items;
- const expected = s.auth === "Bearer tok-a" ? [1, 2] : [3, 4];
- expect(items.map((i) => i.n).sort()).toEqual(expected);
- }
- });
-
- // A failing envelope says nothing about the individual creates — none of them
- // ran. Every waiter must still get a real sandbox.
- it("falls back to single creates when the batch request fails", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold, batchStatus: 500 });
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 5 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- const results = await Promise.all([first, ...rest]);
-
- expect(results.every((r) => r.status === 201)).toBe(true);
- results.forEach((r, i) => expect(JSON.parse(r.text).echo).toEqual({ n: i }));
- expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(6);
- });
-
- // A result count that does not match the item count means we cannot tell whose
- // sandbox is whose. Guessing is worse than redoing the work.
- it("discards a mismatched result set rather than guessing", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold, batchBody: () => ({ results: [{ status: 201, body: {} }] }) });
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 4 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- const results = await Promise.all([first, ...rest]);
-
- results.forEach((r, i) => expect(JSON.parse(r.text).echo).toEqual({ n: i }));
- });
-
- // A control plane that predates the endpoint must not make every burst pay a
- // doomed batch on top of the fallback.
- it("stops batching after the endpoint 404s", async () => {
- let release!: () => void;
- let hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold, batchStatus: 404 });
-
- const burst = async (): Promise<void> => {
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 3 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- await Promise.all([first, ...rest]);
- };
-
- await burst();
- expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);
-
- hold = new Promise<void>((r) => (release = r));
- release();
- await burst();
- // Still one: the second burst never attempted the endpoint again.
- expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(1);
- });
-
- // The failure that took 18% of a burst-100 to HTTP 500 on dev: the request
- // owning a batch dies, so its timer never fires and its waiters are never
- // resolved. The Workers runtime then cancels every one of them as hung. No
- // waiter may depend on another request surviving — each must be able to
- // answer on its own.
- it("still answers every waiter when the batch never dispatches", async () => {
- const sent: string[] = [];
- vi.stubGlobal("fetch", async (url: string, init: RequestInit) => {
- sent.push(url);
- return new Response(JSON.stringify({ echo: JSON.parse(String(init.body) || "{}") }), { status: 201 });
- });
- // Simulate the dead owner: the window timer is armed but never runs.
- vi.stubGlobal("setTimeout", ((fn: () => void, ms?: number) => {
- // Only the batch window is suppressed; each waiter's own deadline must
- // still fire, or this test would prove nothing.
- if (ms === 5) return 0 as unknown as ReturnType<typeof setTimeout>;
- return realSetTimeout(fn, ms);
- }) as typeof setTimeout);
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const rest = Array.from({ length: 5 }, (_, i) => createViaCell(BASE, TOKEN, `{"n":${i + 1}}`, true));
- const results = await Promise.all([first, ...rest]);
-
- // Every waiter got a real create rather than hanging forever.
- expect(results).toHaveLength(6);
- results.forEach((r, i) => {
- expect(r.status).toBe(201);
- expect(JSON.parse(r.text).echo).toEqual({ n: i });
- });
- expect(sent.filter((u) => u.endsWith("/create-batch"))).toHaveLength(0);
- });
-
- // Item bodies are spliced into the envelope as raw JSON to stay byte-identical
- // to a single create. A body that is not a JSON object would corrupt every
- // other item in the batch, not just its own.
- it("sends an unparseable body on its own", async () => {
- let release!: () => void;
- const hold = new Promise<void>((r) => (release = r));
- const { sent } = installFetch({ hold });
-
- const first = createViaCell(BASE, TOKEN, '{"n":0}', true);
- const bad = createViaCell(BASE, TOKEN, "not json at all", true);
- await vi.waitFor(() => expect(sent.length).toBeGreaterThanOrEqual(2));
- release();
- await Promise.all([first, bad]);
-
- expect(sent.filter((s) => s.url.endsWith("/create-batch"))).toHaveLength(0);
- expect(sent.filter((s) => s.url.endsWith("/sandboxes/create"))).toHaveLength(2);
- });
-});
diff --git a/cloudflare-workers/api-edge/src/create_batch.ts b/cloudflare-workers/api-edge/src/create_batch.ts
deleted file mode 100644
index a838a0a6..00000000
--- a/cloudflare-workers/api-edge/src/create_batch.ts
+++ /dev/null
@@ -1,350 +0,0 @@
-// create_batch.ts — collapse a burst of concurrent creates into ONE request to
-// the control plane.
-//
-// STATUS: BUILT, MEASURED, FALSIFIED. Gated behind the CREATE_BATCH env and
-// DEFAULT OFF. Keep it that way unless something below changes.
-//
-// The hypothesis in "WHY" was tested on dev and did not survive. Coalescing
-// worked exactly as designed — `cellbatch` p50 was 26 creates per request — and
-// bought nothing: the `cell` mark was 132ms batched vs 126ms for a lone create.
-// 26x fewer connections, no improvement, so the edge→cell hop is round-trip
-// bound rather than connection bound. The burst cost turned out to be time spent
-// queued BEFORE our handler is given a CPU, which no amount of batching touches.
-//
-// It is kept rather than deleted for two reasons: the CP endpoint is harmless
-// and already deployed, and the "SURVIVING THE OWNER" section below documents a
-// Workers constraint that cost us 18% of a burst to learn and that applies to
-// any future cross-request coalescing.
-//
-// WHY (the original hypothesis — recorded because it was wrong, not because it
-// was right). A burst of 100 creates costs ~115ms each in the create handler's `cell`
-// mark while the CP answers every one of them in ~59us. Practically none of that
-// hop is work: it is the connection. `cp-uswest2.opensandbox.ai` resolves to an
-// Azure address that is NOT behind Cloudflare's proxy, so a Worker subrequest
-// dials it directly and a concurrent burst opens a pile of fresh connections,
-// each paying a TLS handshake to westus2. The same hop served serially is ~30ms
-// — one warm connection, one round trip.
-//
-// The protocol knob that would fix this is not available to us: `fetch()` in a
-// Worker exposes no way to force HTTP/2, and the zone-level "HTTP/2 to Origin"
-// setting only applies to proxied hostnames, which this origin is not. So the
-// only reliable way to stop paying ~100 handshakes is to stop making ~100
-// requests. The CP side is POST /internal/sandboxes/create-batch.
-//
-// WHEN IT ENGAGES. A fixed coalescing window would tax every create, including
-// the sequential ones that are already fast (~194ms end to end) and have nobody
-// to batch with. So batching is gated on observed concurrency instead: a create
-// that arrives when this isolate has none in flight is alone by definition and
-// goes straight out, unchanged and undelayed. Only a create that arrives while
-// another is already in flight joins a batch. Sequential traffic therefore never
-// pays the window, and a burst self-clocks into it — the first create leaves
-// immediately and its neighbours accumulate behind it.
-//
-// Coalescing is per-isolate on purpose. It needs no Durable Object, no shard
-// map, and no cross-isolate coordination: an isolate can only batch requests it
-// is already holding. If a burst spreads across several isolates each one
-// batches its own share, which is a smaller win but never a wrong one.
-//
-// SURVIVING THE OWNER. Batching means one request's work answers several
-// requests, and the Workers runtime is unforgiving about that: it cancels any
-// request it decides "had hung and would never generate a response". A waiter
-// whose result depends entirely on ANOTHER request's timer and fetch has no
-// pending I/O of its own, so if that other request dies — cancelled client,
-// abandoned connection, anything — its timer never fires, its waiters are never
-// resolved, and the runtime kills every one of them. Measured on dev at
-// burst-100: 18% of creates returned HTTP 500 (Cloudflare error 1101) that way,
-// while burst-30 was clean, because one dead request takes its whole batch with
-// it and bursts produce more of them.
-//
-// So no waiter may depend on another request surviving. Each one arms its own
-// deadline in its own context and, if the batch has not answered by then, does
-// its own single create. The batch becomes an optimisation that can fail
-// silently instead of a shared point of failure.
-
-import type { CreateCallResult } from "./create_batch_types";
-
-// The window only ever delays a create that already has a peer in flight, so it
-// trades a few ms of that create's latency for the whole burst's handshakes.
-const BATCH_WINDOW_MS = 5;
-
-// Mirrors maxBatchItems on the CP. Reaching it flushes early rather than
-// truncating: no create is ever silently dropped from a batch.
-const BATCH_MAX_ITEMS = 256;
-
-// How long to stop trying after the CP rejects the endpoint itself (404/405 =
-// a control plane that predates this). Without it every burst would pay a
-// failed batch plus the full fallback, which is strictly worse than not
-// batching at all.
-const BATCH_DISABLE_MS = 60_000;
-
-// How long a waiter will trust the batch before doing the work itself. Well
-// clear of a healthy batch round trip (~30-130ms to the cell), so in normal
-// operation this never fires; it exists so that a batch whose owning request
-// died cannot hang anyone. The cost of it firing is one ordinary create.
-const WAITER_DEADLINE_MS = 400;
-
-interface Waiter {
- /** The exact bytes a single create would have sent. */
- body: string;
- resolve: (r: CreateCallResult) => void;
- reject: (e: unknown) => void;
- queuedAt: number;
- /**
- * Set once this waiter has an answer, from whichever path got there first.
- * The batch and the waiter's own deadline race, and both must be harmless
- * after the other has won.
- */
- settled: boolean;
-}
-
-interface OpenBatch {
- cellBase: string;
- capToken: string;
- waiters: Waiter[];
- timer: ReturnType<typeof setTimeout> | null;
-}
-
-const openBatches = new Map<string, OpenBatch>();
-
-/** Creates this isolate is currently holding — the concurrency signal. */
-let createsInFlight = 0;
-
-/** Set when the CP tells us the batch endpoint does not exist. */
-let batchDisabledUntil = 0;
-
-/**
- * postCreate issues one ordinary single create, exactly as the handler did
- * before batching existed. Every fallback in this module lands here, so a
- * degraded batch path is never worse than no batch path.
- */
-async function postCreate(cellBase: string, capToken: string, body: string): Promise<CreateCallResult> {
- const resp = await fetch(cellBase.replace(/\/$/, "") + "/internal/sandboxes/create", {
- method: "POST",
- headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },
- body: body || "{}",
- });
- return { status: resp.status, text: await resp.text(), batched: false, batchSize: 1, waitMs: 0 };
-}
-
-/**
- * createViaCell is the entry point the create handler calls in place of its
- * direct fetch. It either sends immediately (nothing else in flight) or joins
- * the batch forming for this exact destination.
- */
-export function createViaCell(
- cellBase: string,
- capToken: string,
- body: string,
- // Off unless the deployment turns it on. Measured on dev 2026-08-26 with a
- // settled 100/100 pool: coalescing worked (26 creates per request, p50) and
- // bought nothing — `cell` was 132ms batched vs 126ms for a lone create. That
- // says the edge->cell hop is not connection-bound after all; a batch of 26
- // just costs what the slowest of 26 pool claims costs. Kept behind a flag
- // rather than deleted so the A/B is one env change, not a redeploy.
- enabled: boolean,
-): Promise<CreateCallResult> {
- createsInFlight++;
- const alone = createsInFlight === 1;
- const done = (): void => {
- createsInFlight--;
- };
-
- // Disabled, nothing else in flight, endpoint missing, or a body we could not
- // validate: take the untouched single-create path.
- if (!enabled || alone || Date.now() < batchDisabledUntil || !isJSONObject(body)) {
- return postCreate(cellBase, capToken, body).finally(done);
- }
-
- // The cap-token is the batch key, not just part of it. The CP verifies the
- // token ONCE for the batch and every item inherits those claims, so two
- // creates may only share a request if they would have presented byte-identical
- // credentials. Keying on the token makes that structural: a different org,
- // user, plan, runtime, or cell cannot land in the same batch.
- const key = cellBase + "" + capToken;
-
- let self: Waiter;
- const joined = new Promise<CreateCallResult>((resolve, reject) => {
- let batch = openBatches.get(key);
- if (!batch) {
- batch = { cellBase, capToken, waiters: [], timer: null };
- openBatches.set(key, batch);
- batch.timer = setTimeout(() => {
- void flush(key);
- }, BATCH_WINDOW_MS);
- }
- self = { body, resolve, reject, queuedAt: Date.now(), settled: false };
- batch.waiters.push(self);
- if (batch.waiters.length >= BATCH_MAX_ITEMS) void flush(key);
- });
-
- // The waiter's own timer, armed in the waiter's own request context. This is
- // what makes the batch non-fatal: whatever happens to the request that owns
- // the batch, this request still wakes up and still has work it can do.
- return withOwnDeadline(joined, () => {
- // Losing the race means the batch never answered — its owner is gone. Leave
- // the batch (if it has not dispatched, this also stops it creating a sandbox
- // nobody is waiting for) and do the create here, in this request's context.
- dropWaiter(key, self);
- console.error("create-batch: batch owner never answered, creating solo");
- return postCreate(cellBase, capToken, body);
- }).finally(done);
-}
-
-/**
- * withOwnDeadline resolves from `p` if it answers in time, otherwise from
- * `fallback` — with the timer living in the caller's own request context.
- */
-async function withOwnDeadline(
- p: Promise<CreateCallResult>,
- fallback: () => Promise<CreateCallResult>,
-): Promise<CreateCallResult> {
- const LATE = Symbol("late");
- let timer: ReturnType<typeof setTimeout> | undefined;
- const deadline = new Promise<typeof LATE>((resolve) => {
- timer = setTimeout(() => resolve(LATE), WAITER_DEADLINE_MS);
- });
- try {
- const winner = await Promise.race([p, deadline]);
- if (winner !== LATE) return winner;
- return await fallback();
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/**
- * dropWaiter removes a waiter from its batch if that batch has not dispatched
- * yet, so an abandoned waiter does not get a sandbox created for it that no one
- * will ever receive. A batch already on the wire cannot be recalled; that item's
- * result is simply discarded when it lands.
- */
-function dropWaiter(key: string, w: Waiter): void {
- w.settled = true;
- const batch = openBatches.get(key);
- if (!batch) return;
- const i = batch.waiters.indexOf(w);
- if (i >= 0) batch.waiters.splice(i, 1);
- if (batch.waiters.length === 0) {
- if (batch.timer !== null) clearTimeout(batch.timer);
- openBatches.delete(key);
- }
-}
-
-/**
- * flush dispatches whatever has accumulated under `key`. It detaches the batch
- * from the map first, so creates arriving during the round trip start a fresh
- * one rather than joining a batch that is already on the wire.
- */
-async function flush(key: string): Promise<void> {
- const batch = openBatches.get(key);
- if (!batch) return;
- openBatches.delete(key);
- if (batch.timer !== null) clearTimeout(batch.timer);
-
- const waiters = batch.waiters;
- // A batch of one is just a create wearing an envelope: send it as itself. This
- // is the common outcome when concurrency is low, and it keeps the near-idle
- // path free of any dependency on the batch endpoint.
- if (waiters.length === 1) {
- await settleIndividually(batch, waiters);
- return;
- }
-
- const started = Date.now();
- let results: unknown;
- try {
- const resp = await fetch(batch.cellBase.replace(/\/$/, "") + "/internal/sandboxes/create-batch", {
- method: "POST",
- headers: { authorization: "Bearer " + batch.capToken, "content-type": "application/json" },
- body: '{"items":[' + waiters.map((w) => w.body || "{}").join(",") + "]}",
- });
- if (resp.status === 404 || resp.status === 405) {
- // The control plane does not have the endpoint. Stop asking.
- batchDisabledUntil = Date.now() + BATCH_DISABLE_MS;
- console.log(`create-batch: endpoint absent on ${batch.cellBase} (${resp.status}), disabling for ${BATCH_DISABLE_MS}ms`);
- await settleIndividually(batch, waiters);
- return;
- }
- if (resp.status < 200 || resp.status >= 300) {
- // A failing envelope says nothing about the individual creates — none of
- // them ran. Retrying them singly is safe and is what would have happened
- // without batching.
- console.error(`create-batch: envelope status ${resp.status}, falling back to ${waiters.length} single creates`);
- await settleIndividually(batch, waiters);
- return;
- }
- results = ((await resp.json()) as { results?: unknown }).results;
- } catch (e) {
- console.error("create-batch: dispatch failed, falling back to single creates:", e);
- await settleIndividually(batch, waiters);
- return;
- }
-
- // Results are positional and the CP guarantees one per item. If that does not
- // hold we cannot tell whose sandbox is whose, and handing caller A the box
- // caller B asked for is far worse than being slow — so discard and redo.
- if (!Array.isArray(results) || results.length !== waiters.length) {
- console.error(`create-batch: got ${Array.isArray(results) ? results.length : "non-array"} results for ${waiters.length} items, falling back`);
- await settleIndividually(batch, waiters);
- return;
- }
-
- const elapsed = Date.now() - started;
- for (let i = 0; i < waiters.length; i++) {
- // Gave up while the batch was on the wire and is creating its own sandbox.
- // Its slot in the response is dead weight; dropping it is the only option,
- // since the create already happened at the cell.
- if (waiters[i].settled) continue;
- const r = results[i] as { status?: number; body?: unknown };
- waiters[i].settled = true;
- waiters[i].resolve({
- status: typeof r?.status === "number" ? r.status : 502,
- text: r?.body === undefined ? "{}" : JSON.stringify(r.body),
- batched: true,
- batchSize: waiters.length,
- waitMs: Date.now() - waiters[i].queuedAt - elapsed,
- });
- }
-}
-
-/** settleIndividually runs every waiter as its own single create. */
-async function settleIndividually(batch: OpenBatch, waiters: Waiter[]): Promise<void> {
- await Promise.all(
- waiters.map(async (w) => {
- if (w.settled) return;
- try {
- const r = await postCreate(batch.cellBase, batch.capToken, w.body);
- if (w.settled) return;
- w.settled = true;
- w.resolve({ ...r, waitMs: Date.now() - w.queuedAt });
- } catch (e) {
- if (w.settled) return;
- w.settled = true;
- w.reject(e);
- }
- }),
- );
-}
-
-/**
- * isJSONObject guards the envelope. Item bodies are spliced in as raw JSON to
- * keep them byte-identical to what a single create would have carried, so a body
- * that is not a well-formed JSON object would corrupt the whole batch — not just
- * its own item. Anything unparseable goes out on its own instead.
- */
-function isJSONObject(body: string): boolean {
- if (!body) return true; // empty body becomes "{}" downstream
- try {
- const v: unknown = JSON.parse(body);
- return typeof v === "object" && v !== null && !Array.isArray(v);
- } catch {
- return false;
- }
-}
-
-/** Test seam: reset module state between cases. */
-export function __resetCreateBatchState(): void {
- openBatches.clear();
- createsInFlight = 0;
- batchDisabledUntil = 0;
-}
diff --git a/cloudflare-workers/api-edge/src/create_batch_types.ts b/cloudflare-workers/api-edge/src/create_batch_types.ts
deleted file mode 100644
index 0877e3de..00000000
--- a/cloudflare-workers/api-edge/src/create_batch_types.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-/** What one create call returned, however it was actually sent. */
-export interface CreateCallResult {
- status: number;
- /** The CP's response body, verbatim for a single create. */
- text: string;
- /** True when this create shared a request with others. */
- batched: boolean;
- /** How many creates shared that request (1 when sent alone). */
- batchSize: number;
- /** Time this create spent waiting to be dispatched, in ms. */
- waitMs: number;
-}
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index e84a1eac..fe81adb6 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -25,26 +25,12 @@ export { CreditAccount } from "../../shared/credit_account";
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
// touching web/ or edge code) can't reset the DOs and sever the host-dialed
// VM WebSockets.
import { coloDelete, coloGet, coloPut } from "./colo_cache";
-import { createViaCell } from "./create_batch";
-import type { CreateCallResult } from "./create_batch_types";
import {
ACTIVE_CELLS_SQL,
CELL_STALE_MAX_MS,
@@ -165,14 +151,6 @@ 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
@@ -181,9 +159,6 @@ export interface Env extends DashboardEnv {
// 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.
@@ -216,7 +191,6 @@ export interface FinalizeMsg {
sandboxID: string;
workerID: string;
/** Voucher creates only: the box to redeem against. Absent on every other path. */
- microvmID?: string;
bodyText: string;
}
@@ -1894,7 +1868,6 @@ 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
@@ -1913,11 +1886,6 @@ 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;
@@ -1928,14 +1896,6 @@ async function finalizeEdgeClaim(
});
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));
@@ -2115,153 +2075,6 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
// 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" &&
@@ -2433,13 +2246,19 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
}
}
- // Not a bare fetch: concurrent creates on this isolate coalesce into one
- // request to the cell. A create with nothing else in flight still goes out
- // immediately and alone, so sequential latency is unchanged — see
- // create_batch.ts for why the gate is concurrency rather than a fixed window.
- let cpCall: CreateCallResult;
+ // One request per create, always. Coalescing concurrent creates into a
+ // shared request was tried and falsified: batching 26 creates left the
+ // edge→cell hop unchanged (132ms vs 126ms solo), so that hop is round-trip
+ // bound rather than connection bound, and making one Worker request depend
+ // on another's I/O cost 18% of a burst to CF error 1101.
+ let cpCall: { status: number; text: string };
try {
- cpCall = await createViaCell(cell.base_url, capToken, bodyText, env.CREATE_BATCH === "1");
+ const r = await fetch(`${cell.base_url}/internal/sandboxes/create`, {
+ method: "POST",
+ headers: { "content-type": "application/json", authorization: `Bearer ${capToken}` },
+ body: bodyText,
+ });
+ cpCall = { status: r.status, text: await r.text() };
} catch (e) {
return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);
}
@@ -2454,7 +2273,6 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
// it waited to be dispatched. Without these a batched burst and an unbatched
// one are indistinguishable in the timing header, and `cell` alone cannot say
// whether a slow create was queued or just slow.
- phases.push(`cellbatch;dur=${cpCall.batchSize}`, `cellwait;dur=${cpCall.waitMs}`);
mark("cellbody");
if (cpCall.status >= 200 && cpCall.status < 300) {
let parsed: SandboxCreateResult = {};
@@ -2655,153 +2473,7 @@ const descSafe = (s: string): string => s.replace(/[^\w.:/-]+/g, "_").slice(0, 8
// 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
@@ -5140,80 +4812,7 @@ 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
@@ -5803,18 +5402,6 @@ 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
@@ -5958,7 +5545,6 @@ 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/voucher_book.test.ts b/cloudflare-workers/api-edge/src/voucher_book.test.ts
deleted file mode 100644
index e4f7ea04..00000000
--- a/cloudflare-workers/api-edge/src/voucher_book.test.ts
+++ /dev/null
@@ -1,408 +0,0 @@
-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
deleted file mode 100644
index b108c2b3..00000000
--- a/cloudflare-workers/api-edge/src/voucher_book.ts
+++ /dev/null
@@ -1,744 +0,0 @@
-// 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
deleted file mode 100644
index dfc7d3b1..00000000
--- a/cloudflare-workers/api-edge/src/voucher_cache.test.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-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
deleted file mode 100644
index b6cd0ef2..00000000
--- a/cloudflare-workers/api-edge/src/voucher_cache.ts
+++ /dev/null
@@ -1,318 +0,0 @@
-// 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 5299b591..3732f669 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -164,14 +164,6 @@ 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/main.go b/cmd/microvm-hooks/main.go
index 324dda94..411c8e13 100644
--- a/cmd/microvm-hooks/main.go
+++ b/cmd/microvm-hooks/main.go
@@ -41,8 +41,6 @@ import (
"google.golang.org/grpc/credentials/insecure"
pb "github.com/opensandbox/opensandbox/proto/agent"
-
- "github.com/opensandbox/opensandbox/internal/vouchercache"
)
const (
@@ -78,9 +76,6 @@ 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.
@@ -161,11 +156,6 @@ 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())
@@ -275,16 +265,6 @@ func main() {
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)
diff --git a/internal/api/create_batch.go b/internal/api/create_batch.go
deleted file mode 100644
index c407a600..00000000
--- a/internal/api/create_batch.go
+++ /dev/null
@@ -1,162 +0,0 @@
-package api
-
-import (
- "bytes"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "sync"
-
- "github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/internal/auth"
-)
-
-// create_batch.go — serve N creates on ONE edge→control-plane request.
-//
-// WHY. A burst of 100 creates costs ~115ms EACH in the edge's `cell` mark while
-// this control plane answers every one of them in ~59us. Practically none of
-// that hop is work: it is the connection. The cell's origin
-// (cp-uswest2.opensandbox.ai → 20.64.208.62) is NOT behind Cloudflare's proxy,
-// so a Worker subrequest dials the Azure box directly and a concurrent burst
-// opens a pile of fresh connections, each paying a TLS handshake to westus2.
-// Serially the same hop is ~30ms — one warm connection, one round trip.
-//
-// The protocol knob that would fix this does not exist for us: `fetch()` in a
-// Worker exposes no way to force HTTP/2, and zone-level "HTTP/2 to Origin"
-// applies only to proxied hostnames, which this origin is not. So the only
-// reliable way to stop paying ~100 handshakes is to stop making ~100 requests.
-//
-// This is the same shape as the fix that took the template lookup from 580ms to
-// nothing earlier: collapse a herd of identical concurrent calls into one.
-// There the herd was per-key and the answer was a single flight; here the calls
-// are distinct but the TRANSPORT is the contended resource, so the answer is a
-// single request carrying all of them.
-//
-// HOW. Deliberately NOT a reimplementation of the create path. Each item is run
-// through the very same internalCreateSandbox handler via a child echo context
-// with a recorder, so batched and unbatched creates cannot drift in behaviour —
-// there is exactly one create implementation, and this calls it. The cost is a
-// synthetic request per item, which is allocation, not I/O.
-
-// maxBatchItems bounds one request. The window that fills a batch is small, so
-// a batch this large means something is very wrong upstream; the cap keeps a
-// bad or hostile caller from turning one request into unbounded work.
-const maxBatchItems = 256
-
-type createBatchRequest struct {
- // Items are raw create bodies, byte-identical to what a single
- // POST /internal/sandboxes/create would carry.
- Items []json.RawMessage `json:"items"`
-}
-
-type createBatchResult struct {
- Status int `json:"status"`
- Body json.RawMessage `json:"body"`
-}
-
-type createBatchResponse struct {
- // Results is positional: results[i] answers items[i]. Callers fan these
- // back out to the waiters they batched, so order is load-bearing.
- Results []createBatchResult `json:"results"`
-}
-
-// internalCreateSandboxBatch runs every item through the single-create handler
-// and returns their responses positionally. An item that fails fails alone: its
-// own status and body are reported and the rest still land, because these are
-// unrelated customer creates that happen to share a connection.
-func (s *Server) internalCreateSandboxBatch(c echo.Context) error {
- var req createBatchRequest
- if err := c.Bind(&req); err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid batch body: " + err.Error()})
- }
- if len(req.Items) == 0 {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "batch has no items"})
- }
- if len(req.Items) > maxBatchItems {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "batch too large"})
- }
-
- // The cap-token was verified once, by the middleware, for the batch request.
- // Every item inherits it: they were authenticated as one request and they
- // are all for the caller the token names.
- claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)
- if claims == nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "missing capability claims"})
- }
-
- parent := c.Request()
- results := make([]createBatchResult, len(req.Items))
-
- // Concurrent, because the whole point is that these do not queue behind each
- // other. The single-create path already runs concurrently for ordinary
- // traffic, so nothing here is newly shared.
- var wg sync.WaitGroup
- for i, item := range req.Items {
- wg.Add(1)
- go func(i int, body []byte) {
- defer wg.Done()
- results[i] = s.runBatchedCreate(parent, claims, body)
- }(i, item)
- }
- wg.Wait()
-
- return c.JSON(http.StatusOK, createBatchResponse{Results: results})
-}
-
-// runBatchedCreate executes one item on the real create handler and captures
-// what it wrote.
-func (s *Server) runBatchedCreate(parent *http.Request, claims *auth.CapabilityClaims, body []byte) createBatchResult {
- // Carry the parent's context so a client disconnect or deadline cancels the
- // whole batch rather than leaving items running with nothing to answer.
- sub := httptest.NewRequest(http.MethodPost, "/internal/sandboxes/create", bytes.NewReader(body)).
- WithContext(parent.Context())
- sub.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
- // Region selection reads this header (see createSandboxRemote).
- if r := parent.Header.Get("Fly-Region"); r != "" {
- sub.Header.Set("Fly-Region", r)
- }
-
- rec := httptest.NewRecorder()
- cc := s.echo.NewContext(sub, rec)
- // The child never passes through capTokenMiddleware — it is not a real
- // request — so hand it the claims the middleware would have set. This is the
- // ONLY request-scoped value that needs carrying: the create path reads the
- // runtime off these claims (runtimeFor), and internalCreateSandbox derives
- // org and user identity from them too. Anything added to the middleware
- // chain that the create path later reads must be copied here as well, or a
- // batched create will quietly behave differently from an unbatched one.
- cc.Set(capClaimsKey, claims)
-
- if err := s.batchedCreateHandler()(cc); err != nil {
- // The handler returns its errors as responses; a non-nil error here is
- // echo-level and would normally be rendered by the error handler.
- return createBatchResult{
- Status: http.StatusInternalServerError,
- Body: mustJSON(map[string]string{"error": err.Error()}),
- }
- }
-
- raw, _ := io.ReadAll(rec.Result().Body)
- if len(raw) == 0 {
- raw = []byte("{}")
- }
- return createBatchResult{Status: rec.Code, Body: json.RawMessage(raw)}
-}
-
-// batchedCreateHandler is the handler each item runs on: the real single-create
-// path in production, and only ever something else under test.
-func (s *Server) batchedCreateHandler() func(echo.Context) error {
- if s.createOverrideForTest != nil {
- return s.createOverrideForTest
- }
- return s.internalCreateSandbox
-}
-
-func mustJSON(v any) json.RawMessage {
- b, err := json.Marshal(v)
- if err != nil {
- return json.RawMessage(`{"error":"marshal failed"}`)
- }
- return b
-}
diff --git a/internal/api/create_batch_test.go b/internal/api/create_batch_test.go
deleted file mode 100644
index 9e4cbacf..00000000
--- a/internal/api/create_batch_test.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package api
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "net/http/httptest"
- "strings"
- "sync"
- "testing"
-
- "github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/internal/auth"
-)
-
-// newBatchTestServer returns a Server whose echo can mint child contexts, with a
-// stub standing in for the single-create handler so these tests exercise the
-// batching contract rather than the create path.
-func newBatchTestServer(handler func(echo.Context) error) *Server {
- s := &Server{echo: echo.New()}
- s.createOverrideForTest = handler
- return s
-}
-
-func batchReq(t *testing.T, s *Server, body string, claims *auth.CapabilityClaims) *httptest.ResponseRecorder {
- t.Helper()
- req := httptest.NewRequest(http.MethodPost, "/internal/sandboxes/create-batch", strings.NewReader(body))
- req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
- rec := httptest.NewRecorder()
- c := s.echo.NewContext(req, rec)
- if claims != nil {
- c.Set(capClaimsKey, claims)
- }
- if err := s.internalCreateSandboxBatch(c); err != nil {
- t.Fatalf("handler error: %v", err)
- }
- return rec
-}
-
-// Results are positional — callers fan them back to the waiters they batched, so
-// a shuffled response silently hands sandbox A to the caller who asked for B.
-// Concurrency makes completion order deliberately non-sequential here.
-func TestCreateBatchResultsArePositional(t *testing.T) {
- var mu sync.Mutex
- s := newBatchTestServer(func(c echo.Context) error {
- var in struct {
- N int `json:"n"`
- }
- _ = json.NewDecoder(c.Request().Body).Decode(&in)
- mu.Lock()
- defer mu.Unlock()
- return c.JSON(http.StatusOK, map[string]int{"got": in.N})
- })
-
- const n = 25
- items := make([]string, n)
- for i := range items {
- items[i] = fmt.Sprintf(`{"n":%d}`, i)
- }
- rec := batchReq(t, s, `{"items":[`+strings.Join(items, ",")+`]}`,
- &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"})
-
- var resp createBatchResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v (body=%s)", err, rec.Body.String())
- }
- if len(resp.Results) != n {
- t.Fatalf("got %d results, want %d", len(resp.Results), n)
- }
- for i, r := range resp.Results {
- var got struct {
- Got int `json:"got"`
- }
- if err := json.Unmarshal(r.Body, &got); err != nil {
- t.Fatalf("result %d: decode %v", i, err)
- }
- if got.Got != i {
- t.Fatalf("result %d carries item %d — results are not positional", i, got.Got)
- }
- }
-}
-
-// One item failing must not take the batch down: these are unrelated customer
-// creates that merely share a connection.
-func TestCreateBatchIsolatesPerItemFailure(t *testing.T) {
- s := newBatchTestServer(func(c echo.Context) error {
- var in struct {
- Fail bool `json:"fail"`
- }
- _ = json.NewDecoder(c.Request().Body).Decode(&in)
- if in.Fail {
- return c.JSON(http.StatusNotFound, map[string]string{"error": "nope"})
- }
- return c.JSON(http.StatusOK, map[string]string{"ok": "yes"})
- })
-
- rec := batchReq(t, s, `{"items":[{"fail":false},{"fail":true},{"fail":false}]}`,
- &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"})
-
- var resp createBatchResponse
- if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v", err)
- }
- want := []int{http.StatusOK, http.StatusNotFound, http.StatusOK}
- for i, w := range want {
- if resp.Results[i].Status != w {
- t.Fatalf("result %d status=%d want %d — a failing item changed its neighbours",
- i, resp.Results[i].Status, w)
- }
- }
-}
-
-func TestCreateBatchRejectsEmptyOversizeAndUnauthenticated(t *testing.T) {
- s := newBatchTestServer(func(c echo.Context) error {
- return c.JSON(http.StatusOK, map[string]string{"ok": "yes"})
- })
- claims := &auth.CapabilityClaims{OrgID: "11111111-1111-1111-1111-111111111111"}
-
- if rec := batchReq(t, s, `{"items":[]}`, claims); rec.Code != http.StatusBadRequest {
- t.Fatalf("empty batch: got %d want 400", rec.Code)
- }
-
- big := make([]string, maxBatchItems+1)
- for i := range big {
- big[i] = `{}`
- }
- if rec := batchReq(t, s, `{"items":[`+strings.Join(big, ",")+`]}`, claims); rec.Code != http.StatusBadRequest {
- t.Fatalf("oversize batch: got %d want 400", rec.Code)
- }
-
- // No claims == the middleware did not run. Must never fall through to
- // creating sandboxes for an unauthenticated caller.
- if rec := batchReq(t, s, `{"items":[{}]}`, nil); rec.Code != http.StatusInternalServerError {
- t.Fatalf("missing claims: got %d want 500", rec.Code)
- }
-}
diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.go
index 4bc6822f..40d34b09 100644
--- a/internal/api/edge_claim.go
+++ b/internal/api/edge_claim.go
@@ -250,9 +250,6 @@ 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()})
@@ -282,67 +279,6 @@ 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/lite_backend.go b/internal/api/lite_backend.go
index 70563e20..ad1aff83 100644
--- a/internal/api/lite_backend.go
+++ b/internal/api/lite_backend.go
@@ -52,9 +52,6 @@ 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
@@ -86,20 +83,6 @@ 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
@@ -495,50 +478,3 @@ 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 48c4addf..b99dcd64 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -403,26 +403,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
if s.capTokenIssuer != nil && s.workerRegistry != nil {
internal := e.Group("/internal", s.capTokenMiddleware)
internal.POST("/sandboxes/create", s.internalCreateSandbox)
- // Same creates, one request. Serves the edge-side coalescer, which is
- // DEFAULT OFF (CREATE_BATCH) because measurement falsified the premise:
- // batching 26 creates into one request left the edge→cell hop unchanged
- // (132ms vs 126ms solo), so that hop is round-trip bound, not connection
- // bound. Endpoint kept because it is harmless and already deployed — see
- // create_batch.go and the edge's create_batch.ts.
- internal.POST("/sandboxes/create-batch", s.internalCreateSandboxBatch)
// Edge claim (see edge_claim.go): the api-edge PoolStock DO reserves
// pool boxes ahead of time and finalizes claims asynchronously.
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/voucher_claim.go b/internal/api/voucher_claim.go
deleted file mode 100644
index d67196bf..00000000
--- a/internal/api/voucher_claim.go
+++ /dev/null
@@ -1,154 +0,0 @@
-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/awsvmlite/cache_fleet.go b/internal/awsvmlite/cache_fleet.go
deleted file mode 100644
index 7151f2f1..00000000
--- a/internal/awsvmlite/cache_fleet.go
+++ /dev/null
@@ -1,355 +0,0 @@
-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 33f7e2b4..e98a6404 100644
--- a/internal/awsvmlite/lite.go
+++ b/internal/awsvmlite/lite.go
@@ -188,10 +188,6 @@ 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
@@ -224,17 +220,12 @@ 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.
+// Depth reports how many boxes are ready to hand out — the warm set, which is
+// the only unclaimed state a box can be in.
func (m *Manager) Depth() int {
m.mu.Lock()
defer m.mu.Unlock()
- return len(m.warm) + len(m.vouchered)
+ return len(m.warm)
}
// Run drives the warm set: top it up, and keep every box in it non-idle.
@@ -260,8 +251,7 @@ func (m *Manager) Run(ctx context.Context) {
return
case <-launch.C:
m.mu.Lock()
- // Vouchered boxes are stock too — see Depth.
- committed := len(m.warm) + len(m.vouchered) + m.inflight
+ committed := len(m.warm) + m.inflight
m.mu.Unlock()
if committed >= m.cfg.WarmTarget {
continue
@@ -275,19 +265,12 @@ func (m *Manager) Run(ctx context.Context) {
// 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.
+ // happened, so a QUIET manager was completely opaque. That cost
+ // real time — a keepalive touching 49 boxes while AWS showed 100
+ // running was impossible to explain with nothing printing the
+ // split. A steady heartbeat is what makes "the filler thinks it is
+ // at target" and "the pool is empty" 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.
@@ -533,19 +516,10 @@ func (m *Manager) BoxFor(sandboxID string) (*Box, bool) {
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.
+ // Not found, and deliberately not guessed at. An exec can reach the cell
+ // BEFORE its finalize lands, and the only honest answer then is that this
+ // process does not yet know which box the sandbox holds. Surfacing a clean
+ // not-found is what keeps it from returning somebody else's box.
return nil, false
}
@@ -645,18 +619,8 @@ 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)
- }
+ // Bound boxes are left alone: they belong to customers, and the reconciler
+ // re-adopts them on the way back up.
m.mu.Unlock()
var wg sync.WaitGroup
@@ -734,14 +698,6 @@ 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)
@@ -833,3 +789,25 @@ func hostOnly(endpoint string) string {
}
return h
}
+
+// logState prints the warm/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, and a filler that believes it is at target
+// while the pool is empty looks identical to a healthy one without this line.
+func (m *Manager) logState() {
+ m.mu.Lock()
+ warm, bound := len(m.warm), len(m.bound)
+ last := m.lastStateLog
+ now := time.Now()
+ if now.Sub(last) < time.Minute {
+ m.mu.Unlock()
+ return
+ }
+ m.lastStateLog = now
+ inflight := m.inflight
+ m.mu.Unlock()
+ log.Printf("awsvmlite: state warm=%d bound=%d inflight=%d depth=%d/%d",
+ warm, bound, inflight, warm, m.cfg.WarmTarget)
+}
diff --git a/internal/awsvmlite/voucher.go b/internal/awsvmlite/voucher.go
deleted file mode 100644
index 66f26ee2..00000000
--- a/internal/awsvmlite/voucher.go
+++ /dev/null
@@ -1,486 +0,0 @@
-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
deleted file mode 100644
index 880b6d93..00000000
--- a/internal/awsvmlite/voucher_test.go
+++ /dev/null
@@ -1,285 +0,0 @@
-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/store.go b/internal/db/store.go
index 8e45bc5f..c7f5e489 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -937,29 +937,6 @@ 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/vouchercache/server.go b/internal/vouchercache/server.go
deleted file mode 100644
index 6b9b4bb1..00000000
--- a/internal/vouchercache/server.go
+++ /dev/null
@@ -1,304 +0,0 @@
-// 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
deleted file mode 100644
index 82be6aa1..00000000
--- a/internal/vouchercache/server_test.go
+++ /dev/null
@@ -1,261 +0,0 @@
-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")
- }
-}
diff --git a/wrangler.jsonc b/wrangler.jsonc
deleted file mode 100644
index 4d7aa82d..00000000
--- a/wrangler.jsonc
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "$schema": "node_modules/wrangler/config-schema.json",
- "name": "opencomputer3",
- "compatibility_date": "2026-08-25",
- "observability": {
- "enabled": true
- },
- "assets": {
- "directory": "."
- },
- "compatibility_flags": [
- "nodejs_compat"
- ]
-}