Skip to content

An open-source, faster Devin alternative

TypeScript

wip 328

Brian Reardonfc3b6eec77da
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 7590dcc3..6838c65f 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -112,6 +112,9 @@ export interface Env extends DashboardEnv {
// The host's /connect is authed by a per-sandbox HMAC over SESSION_JWT_SECRET
// (see the /internal/vms/:id/connect route) — no dedicated secret.
VM_SESSIONS: DurableObjectNamespace;
+ // MicroVM exec data plane — the DO dials the box's agent directly, so exec
+ // never touches the control plane. See vm-do/src/microvm_session.ts.
+ MICROVM_SESSIONS: DurableObjectNamespace;
// Off-isolate edge-claim finalize. finalizeEdgeClaim (CP claim-finalize fetch +
// D1 index insert) was the dominant burst-create cost: run per create in
// waitUntil, ~100 of them accumulate on the create isolate and saturate its
@@ -1485,18 +1488,11 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// race-safe here: the client can't send that exec until the 201 crosses
// the network (≥ one RTT), and the put lands in ~5ms.
ctx.waitUntil(coloPut("route", box.id, { cellID: cell.cell_id, orgID: caller.orgID }, ROUTE_COLO_TTL_SEC));
- // Warm the edge→cell connection for the exec that is about to follow.
- //
- // Measured on dev: a create's first exec spends 200ms in `origin` against
- // 102ms steady — TLS + CF Tunnel setup on the first outbound request,
- // paid once and then free. TTI measures exactly that first exec.
- //
- // EXPERIMENT, and its result is not obvious: the exec usually lands on a
- // DIFFERENT isolate than the create, so this only helps if Workers pool
- // outbound connections more broadly than per-isolate. If the first-exec
- // `origin` does not fall toward 102ms after this ships, that hypothesis
- // is dead and the warming has to live somewhere shared instead.
- ctx.waitUntil(warmCellConnection(cell));
+ // NOTE: the MicroVM exec channel is deliberately NOT warmed here. It is
+ // warmed at stock-prep in pool_stock.ts, where the box sits idle for
+ // minutes — warming from this path both loses the race against the
+ // customer's first exec and fans out a DO subrequest per create under
+ // burst. See PoolStock.warmMicrovmBox.
mark("mintseed");
const resp: Record<string, unknown> = {
sandboxID: box.id,
@@ -1724,7 +1720,7 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
// MicroVM exec — 79% of benchmark TTI, against a control plane that served
// the exec itself in 10ms. Skip straight to the tunnel.
const orgPolicy = await loadOrgPolicy(env, caller.orgID);
- if (orgPolicy?.runtime === RUNTIME_MICROVM) return null;
+ if (orgPolicy?.runtime === RUNTIME_MICROVM) return tryMicrovmDoExec(req, env, caller, id, authMs);
const tRoute = Date.now();
const route = await resolveSandboxRoute(env, id);
const routeMs = Date.now() - tRoute;
@@ -1790,6 +1786,150 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
return null;
}
+// tryMicrovmDoExec is the MicroVM counterpart of tryVmDoExec: it routes
+// POST /:id/exec/run-async through a MicrovmSession DO that holds the agent
+// tunnel open, instead of the tunnel→control-plane→box chain.
+//
+// The saving is not marginal. Measured on dev from a Worker in IAD: the
+// edge→control-plane hop alone is ~70ms round trip before the control plane
+// even starts talking to the box, while edge→guest through the DO's tunnel is
+// ~4-5ms. Today's exec pays the former plus the control plane's own hop.
+//
+// Same contract as tryVmDoExec: a Response when the DO served it, null to fall
+// back to the tunnel. Authz mirrors proxyToCellSDK (route lookup plus
+// org-ownership) so this path cannot exec on another org's sandbox.
+async function tryMicrovmDoExec(req: Request, env: Env, caller: Caller, id: string, authMs = 0): Promise<Response | null> {
+ if (!env.MICROVM_SESSIONS) return null; // binding absent mid-cutover → tunnel
+ const tRoute = Date.now();
+ const route = await resolveSandboxRoute(env, id);
+ const routeMs = Date.now() - tRoute;
+ if (!route) return json({ error: "sandbox not found" }, 404);
+ if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+
+ let body: Record<string, unknown>;
+ try {
+ body = JSON.parse((await req.clone().text()) || "{}") as Record<string, unknown>;
+ } catch {
+ return json({ error: "invalid body" }, 400);
+ }
+ // The SDK sends a single shell string; the agent's Exec takes an argv. Match
+ // what the control plane does for this backend rather than word-splitting
+ // here, where quoting and redirection would be silently mangled.
+ const cmd = typeof body.cmd === "string" ? body.cmd : typeof body.command === "string" ? body.command : "";
+ if (!cmd) return null;
+ const payload = {
+ command: "/bin/sh",
+ args: ["-lc", cmd],
+ cwd: typeof body.cwd === "string" ? body.cwd : undefined,
+ env: (body.env as Record<string, string> | undefined) ?? undefined,
+ timeoutSeconds: typeof body.timeoutSeconds === "number" ? body.timeoutSeconds : undefined,
+ };
+
+ // enam keeps the DO in eastern North America, next to the us-east-1 boxes it
+ // dials. Without the hint the DO is placed near whoever touched it first,
+ // which for a west-coast client would put a cross-country leg back in.
+ const ns = env.MICROVM_SESSIONS;
+ const stub = ns.get(ns.idFromName(id), { locationHint: "enam" });
+
+ // Hard deadline on the whole DO attempt. The value of this path is that it is
+ // FAST; if it is not, the tunnel is right there. Without a bound, any stall in
+ // the DO (cold dial to a suspended box, a half-open tunnel) becomes the
+ // customer's stall instead of a fallback — which is worse than never having
+ // built it. Generous next to the ~5ms this costs when healthy.
+ const DO_DEADLINE_MS = 1500;
+ const deadline = <T>(p: Promise<T>, ms: number): Promise<T> =>
+ Promise.race([
+ p,
+ new Promise<T>((_, rej) => setTimeout(() => rej(new Error(`DO deadline ${ms}ms`)), ms)),
+ ]);
+
+ const call = async (): Promise<Response> =>
+ deadline(
+ stub.fetch("https://do/exec", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(payload),
+ }),
+ DO_DEADLINE_MS,
+ );
+
+ try {
+ const tDo = Date.now();
+ let doResp = await call();
+ let attachMs = 0;
+ if (doResp.status === 409) {
+ // Not attached, or the stored credential no longer works. Fetch fresh
+ // reach-info from the control plane and retry once. This costs a CP round
+ // trip on the FIRST exec only; attaching at create time (where the pool
+ // already holds endpoint and token) removes it from the hot path.
+ const tAttach = Date.now();
+ const ok = await deadline(attachMicrovmSession(env, caller, route.cellID, id, stub), DO_DEADLINE_MS).catch(
+ (e) => {
+ console.log(`microvm-do-exec ${id}: attach ${e}`);
+ return false;
+ },
+ );
+ attachMs = Date.now() - tAttach;
+ if (!ok) {
+ console.log(`microvm-do-exec ${id}: attach failed — tunnel`);
+ return null;
+ }
+ doResp = await call();
+ }
+ const doMs = Date.now() - tDo;
+ if (doResp.status === 200) {
+ return new Response(doResp.body, {
+ status: 200,
+ headers: {
+ "content-type": "application/json",
+ "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, attach;dur=${attachMs}, do;dur=${doMs}`,
+ },
+ });
+ }
+ console.log(`microvm-do-exec ${id}: DO ${doResp.status} — tunnel fallback`);
+ } catch (e) {
+ console.log(`microvm-do-exec ${id}: ${e} — tunnel fallback`);
+ }
+ return null;
+}
+
+// attachMicrovmSession teaches a DO how to reach its box. Temporary shape: the
+// control plane is asked for endpoint+token on demand. The pool already holds
+// both (awsvm.StockEntry), so the durable version delivers them with the box at
+// claim time and this call disappears.
+async function attachMicrovmSession(
+ env: Env,
+ caller: Caller,
+ cellID: string,
+ id: string,
+ stub: DurableObjectStub,
+ dial = false,
+): Promise<boolean> {
+ const cell = await lookupCell(env, cellID);
+ if (!cell) return false;
+ const org = await loadOrgPolicy(env, caller.orgID);
+ const capToken = await cachedCapToken(
+ env.SESSION_JWT_SECRET,
+ caller.orgID,
+ cellID,
+ "",
+ org?.billing_provider ?? "",
+ org?.runtime ?? "",
+ caller.userID,
+ );
+ const resp = await fetch(`${cell.base_url.replace(/\/$/, "")}/internal/microvm/direct/${id}`, {
+ headers: { authorization: "Bearer " + capToken },
+ });
+ if (!resp.ok) return false;
+ const info = await resp.json<{ endpoint: string; token: string; port: number }>();
+ const att = await stub.fetch("https://do/attach", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ ...info, dial }),
+ });
+ return att.ok;
+}
+
// Proxy the request to the owning cell's CP. Used for SDK runtime calls
// (`/api/sandboxes/:id/exec`, `/files`, `/pty`, etc.). The caller has been
// authenticated at the edge against D1; we mint a short-lived IdentityToken
@@ -1797,20 +1937,6 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
// and stream the response back. Pre-fix this was a 307 redirect, which broke
// when the SDK's API key didn't exist in cell PG (api_keys are global in D1
// now, not mirrored per-cell).
-// warmCellConnection opens (and discards) a cheap request to a cell so the
-// TLS + tunnel handshake is already paid when the real one arrives. Best-effort
-// by construction: it runs in waitUntil, and a failure just means the next
-// request pays what it would have paid anyway.
-async function warmCellConnection(cell: CellRow): Promise<void> {
- try {
- await fetch(cell.base_url.replace(/\/$/, "") + "/health", {
- method: "GET",
- signal: AbortSignal.timeout(2000),
- });
- } catch {
- /* best-effort */
- }
-}
async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, vmdoMs = 0): Promise<Response> {
// Step timing for the data-plane path. Measured on dev, an exec through here
@@ -1887,6 +2013,21 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
if (req.method === "DELETE" && path === `/api/sandboxes/${id}`) {
postUpdate = { status: "stopped", setStopped: true, mode: null };
sandboxRouteCache.delete(id); // route is dead once the sandbox is destroyed
+ // Tell the box's session DO to stop keeping itself warm. Without this its
+ // alarm keeps re-dialing a terminated endpoint until the failure counter
+ // gives up — bounded, but pointless work against AWS for every destroy.
+ // MicroVM only: other runtimes have no MicrovmSession, and asking for one
+ // by id would instantiate a Durable Object just to tear it down.
+ if (env.MICROVM_SESSIONS && orgPol?.runtime === RUNTIME_MICROVM) {
+ const ns = env.MICROVM_SESSIONS;
+ ctx.waitUntil(
+ ns
+ .get(ns.idFromName(id), { locationHint: "enam" })
+ .fetch("https://do/detach", { method: "POST" })
+ .then(() => undefined)
+ .catch(() => undefined),
+ );
+ }
} else if (req.method === "POST" && path === `/api/sandboxes/${id}/hibernate`) {
postUpdate = { status: "hibernated", setStopped: false, mode: "paused" };
} else if (req.method === "POST" && path === `/api/sandboxes/${id}/wake`) {
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index afbbfb14..be0da0ce 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -26,6 +26,12 @@ interface StockEntry {
region: string;
sandboxDomain: string;
atMs: number;
+ // MicroVM reach-info, when the cell supplies it. Present means exec can go
+ // straight from the edge to the box's agent; absent means this cell routes
+ // through a worker and exec uses the control-plane path.
+ endpoint?: string;
+ token?: string;
+ port?: number;
}
interface PoolStockEnv {
@@ -41,6 +47,11 @@ interface PoolStockEnv {
// subrequests from the create isolate, saturating its subrequest budget.
// Optional so the binding can be absent mid-cutover (prewake just skips).
VM_SESSIONS?: DurableObjectNamespace;
+ // MicroVM exec data plane. Warmed here at stock-prep for the same reason
+ // VM_SESSIONS is: doing it on the create path would fan out a subrequest per
+ // box from the create isolate, and — more importantly — would lose the race
+ // against the customer's first exec.
+ MICROVM_SESSIONS?: DurableObjectNamespace;
}
// Stock tuning. TARGET_STOCK mirrors ~the whole per-cell hot pool so every
@@ -406,6 +417,51 @@ export class PoolStock {
);
}
+ // warmMicrovmBox hands a box's reach-info to its MicrovmSession DO and has it
+ // open the agent tunnel, best-effort and off every hot path.
+ //
+ // Doing this at stock-prep rather than at create is the whole point. The
+ // WebSocket 101 comes from the AWS proxy, which only connects to the guest
+ // port when payload first arrives — so the ~1.1s cost of actually reaching the
+ // agent lands on whoever sends first. Warming at create loses that race (the
+ // customer's exec arrives one RTT after the 201), and warming lazily on first
+ // exec IS the race. Here there is no race: the box sits in stock for minutes.
+ private warmMicrovmBox(b: { sandboxID: string; endpoint?: string; token?: string; port?: number }): void {
+ const ns = this.env.MICROVM_SESSIONS;
+ if (!ns || !b.endpoint || !b.token || !b.port) return;
+ this.state.waitUntil(
+ ns
+ .get(ns.idFromName(b.sandboxID), { locationHint: "enam" })
+ .fetch("https://do/attach", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ endpoint: b.endpoint, token: b.token, port: b.port, dial: true }),
+ })
+ .then(() => {})
+ .catch(() => {}),
+ );
+ }
+
+ // coolMicrovmBox drops a DO's channel when its box leaves this stock without
+ // ever reaching a customer.
+ //
+ // Not just tidiness: the box goes back to anonymous pool stock and will be
+ // reissued under a DIFFERENT sandbox id, so a DO still holding a live tunnel
+ // under the OLD id is a channel into a box that now belongs to someone else.
+ // The id stops resolving in D1, which is the real guard, but leaving an armed
+ // channel behind it is not a thing to rely on.
+ private coolMicrovmBox(sandboxID: string): void {
+ const ns = this.env.MICROVM_SESSIONS;
+ if (!ns) return;
+ this.state.waitUntil(
+ ns
+ .get(ns.idFromName(sandboxID), { locationHint: "enam" })
+ .fetch("https://do/detach", { method: "POST" })
+ .then(() => {})
+ .catch(() => {}),
+ );
+ }
+
private persist(): void {
// allowUnconfirmed skips the output gate: the claim response leaves ~10ms
// sooner instead of waiting for the write to be durable. Failure window
@@ -454,7 +510,9 @@ export class PoolStock {
region: string;
sandboxDomain: string;
epoch?: string;
- boxes: Array<{ sandboxID: string; workerID: string }>;
+ // endpoint/token/port are present only for cells whose backend can be
+ // reached directly (MicroVM); worker-backed cells omit them.
+ boxes: Array<{ sandboxID: string; workerID: string; endpoint?: string; token?: string; port?: number }>;
};
// Epoch fence. A cell that stamps an epoch is telling us its edge
// reservations live in that process's memory, not in Postgres — so when
@@ -490,8 +548,14 @@ export class PoolStock {
region: data.region,
sandboxDomain: data.sandboxDomain,
atMs: now,
+ endpoint: b.endpoint,
+ token: b.token,
+ port: b.port,
});
added++;
+ // Open and guest-attach this box's agent tunnel NOW, while it is still
+ // stock and nobody is waiting on it.
+ this.warmMicrovmBox(b);
// Pre-wake the box's VmSession DO now (stock-prep), off any hot path, so
// the create burst doesn't fan out ~100 prewake subrequests from the
// create isolate. The alarm (prewakeStock) keeps it warm while it sits.
@@ -506,6 +570,9 @@ export class PoolStock {
}
private async release(entries: StockEntry[]): Promise<void> {
+ // Tear down any agent tunnel first — this box is about to be reissued under
+ // a different sandbox id. See coolMicrovmBox.
+ for (const e of entries) if (e.endpoint) this.coolMicrovmBox(e.id);
// Group by cell (entries could straddle a base_url change).
const byCell = new Map<string, { cellID: string; ids: string[] }>();
for (const e of entries) {
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index 5326e2c2..b272b595 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -104,6 +104,13 @@ name = "VM_SESSIONS"
class_name = "VmSession"
script_name = "opensandbox-vmdo-dev"
+# MicroVM exec data plane. Same worker, same reasoning; the DO dials the box's
+# agent endpoint directly so exec never traverses the control plane.
+[[durable_objects.bindings]]
+name = "MICROVM_SESSIONS"
+class_name = "MicrovmSession"
+script_name = "opensandbox-vmdo-dev"
+
[[migrations]]
tag = "v1"
new_sqlite_classes = ["CreditAccount"]
diff --git a/cloudflare-workers/vm-do/src/h2grpc.ts b/cloudflare-workers/vm-do/src/h2grpc.ts
new file mode 100644
index 00000000..ad7265e6
--- /dev/null
+++ b/cloudflare-workers/vm-do/src/h2grpc.ts
@@ -0,0 +1,518 @@
+// h2grpc.ts — just enough HTTP/2 to make unary gRPC calls over a raw byte
+// stream, so a Durable Object can talk straight to a MicroVM's in-guest agent.
+//
+// WHY THIS EXISTS
+//
+// A MicroVM's agent speaks gRPC on a guest port, reachable through a public TLS
+// endpoint with a port-scoped header credential. Cloudflare's fetch() cannot be
+// used for it: Lambda's proxy strips HTTP/2 trailers, and gRPC carries its
+// status there, so a direct fetch runs the command and then loses the result.
+// The tunnel the control plane uses works because a WebSocket forwards opaque
+// frames — trailers included — and inside that tunnel is plain cleartext HTTP/2.
+// So to reach the agent from the edge we have to speak HTTP/2 ourselves.
+//
+// Measured on dev from an IAD Worker: 4-5ms round trip to the guest agent
+// through this tunnel, against ~70ms just for the edge→control-plane hop the
+// current exec path pays before it even starts talking to the box.
+//
+// WHAT THIS DELIBERATELY DOES NOT DO
+//
+// It never HPACK-DECODES. Encoding our own headers needs only literal-without-
+// indexing entries, which are a length-prefixed name and value and nothing else
+// — no dynamic table, no Huffman. Decoding the server's headers would need
+// both, and we do not need them: a unary response is DATA frames plus an
+// END_STREAM flag, all of which live in frame headers we can read directly.
+// grpc-status rides in the trailers we skip, so "no DATA arrived" is the only
+// failure signal this client reports — and the caller's answer to that is to
+// fall back to the tunnel path, which is the same answer it would have for a
+// non-zero status. Trading a precise error for ~600 lines of HPACK is the right
+// trade while this path handles one-shot Exec only.
+//
+// Streaming RPCs, PTY and file transfer are NOT supported here on purpose; they
+// stay on the control-plane path.
+
+const FRAME_HEADER = 9;
+
+const TYPE_DATA = 0x0;
+const TYPE_HEADERS = 0x1;
+const TYPE_RST_STREAM = 0x3;
+const TYPE_SETTINGS = 0x4;
+const TYPE_PING = 0x6;
+const TYPE_GOAWAY = 0x7;
+const TYPE_WINDOW_UPDATE = 0x8;
+
+const FLAG_ACK = 0x1;
+const FLAG_END_STREAM = 0x1;
+const FLAG_END_HEADERS = 0x4;
+
+// Big windows so a normal command's output never blocks on flow control and we
+// never have to implement incremental WINDOW_UPDATE bookkeeping per stream.
+// 8MB is far past anything one-shot Exec should return; larger outputs belong
+// on the streaming path, which is not served here.
+const WINDOW = 8 * 1024 * 1024;
+const SETTINGS_INITIAL_WINDOW_SIZE = 0x4;
+
+const PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
+
+/** One in-flight unary call. */
+interface Call {
+ chunks: Uint8Array[];
+ resolve: (body: Uint8Array) => void;
+ reject: (e: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+/**
+ * H2Grpc drives one HTTP/2 connection over a WebSocket that carries a raw byte
+ * stream. One instance per open tunnel; not safe to share across tunnels.
+ */
+export class H2Grpc {
+ private ws: WebSocket;
+ private authority: string;
+ private buf: Uint8Array<ArrayBufferLike> = new Uint8Array(0);
+ private calls = new Map<number, Call>();
+ private pings = new Map<string, { resolve: () => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>();
+ private pingSeq = 0;
+ private nextStream = 1;
+ private dead: Error | null = null;
+ private readyResolve: (() => void) | null = null;
+ private readyReject: ((e: Error) => void) | null = null;
+ /**
+ * ready settles when the GUEST has spoken — its SETTINGS frame is the first
+ * proof the far end exists.
+ *
+ * This matters more than it looks. The WebSocket 101 comes from the AWS proxy,
+ * not from the guest: the proxy only opens its own connection to the guest
+ * port when payload first arrives. So an "open" tunnel says nothing about
+ * whether the agent is reachable, and the cost of finding out lands on
+ * whoever sends first — measured at ~1.1s on a freshly claimed pool box,
+ * against ~26ms once the guest is attached. Awaiting this in the warm path
+ * spends it while nobody is waiting.
+ */
+ readonly ready: Promise<void>;
+
+ constructor(ws: WebSocket, authority: string) {
+ this.ws = ws;
+ this.authority = authority;
+ this.ready = new Promise<void>((res, rej) => {
+ this.readyResolve = res;
+ this.readyReject = rej;
+ });
+ // Binary, explicitly. The default binaryType is not guaranteed to be
+ // "arraybuffer" in every WebSocket implementation, and a Blob here silently
+ // yields a zero-length Uint8Array: no frame ever completes, we never ACK the
+ // server's SETTINGS, and it closes the connection on us — which presents as
+ // "tunnel closed" with no clue as to why.
+ try {
+ (ws as unknown as { binaryType: string }).binaryType = "arraybuffer";
+ } catch {
+ /* not settable on this implementation — the guard below still reports it */
+ }
+ ws.addEventListener("message", (ev: MessageEvent) => {
+ const data = ev.data;
+ if (typeof data === "string") return; // the agent never sends text
+ if (!(data instanceof ArrayBuffer)) {
+ console.log(`h2: NON-ARRAYBUFFER message ${Object.prototype.toString.call(data)}`);
+ this.kill(new Error("h2grpc: websocket delivered non-binary data"));
+ return;
+ }
+ this.onBytes(new Uint8Array(data));
+ });
+ ws.addEventListener("close", () => this.kill(new Error("h2grpc: tunnel closed")));
+ ws.addEventListener("error", () => this.kill(new Error("h2grpc: tunnel error")));
+
+ // Preface, our SETTINGS, and a connection-level window bump, sent eagerly.
+ // We deliberately do NOT wait for the server's SETTINGS before issuing the
+ // first request: HTTP/2 permits it, and waiting would put an extra round
+ // trip on the very call this whole path exists to make fast.
+ const hello = concat([
+ enc(PREFACE),
+ settingsFrame(),
+ windowUpdateFrame(0, WINDOW),
+ ]);
+ ws.send(hello);
+ }
+
+ get closed(): boolean {
+ return this.dead !== null;
+ }
+
+ private kill(e: Error): void {
+ if (this.dead) return;
+ this.dead = e;
+ if (this.readyReject) {
+ this.readyReject(e);
+ this.readyReject = null;
+ this.readyResolve = null;
+ }
+ for (const [, call] of this.calls) {
+ clearTimeout(call.timer);
+ call.reject(e);
+ }
+ this.calls.clear();
+ for (const [, p] of this.pings) {
+ clearTimeout(p.timer);
+ p.reject(e);
+ }
+ this.pings.clear();
+ }
+
+ /**
+ * ping round-trips an HTTP/2 PING and resolves when its ACK comes back.
+ *
+ * This is the keepalive's liveness proof, and it is stronger than "the
+ * WebSocket is still open". The 101 comes from the AWS proxy, which will hold
+ * a socket open whether or not it is still attached to the guest; only a frame
+ * the GUEST's HTTP/2 stack has to answer proves the whole chain — proxy,
+ * guest port, agent server — is intact. PING is the cheapest such frame and,
+ * unlike a real RPC, it runs no code inside the sandbox.
+ */
+ ping(timeoutMs = 5000): Promise<void> {
+ if (this.dead) return Promise.reject(this.dead);
+ // Opaque 8 bytes, echoed verbatim in the ACK. A counter is enough to pair
+ // request with reply — these never leave one connection.
+ const payload = new Uint8Array(8);
+ new DataView(payload.buffer).setUint32(4, ++this.pingSeq);
+ const key = keyOf(payload);
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pings.delete(key);
+ reject(new Error("h2grpc: ping timeout"));
+ }, timeoutMs);
+ this.pings.set(key, { resolve, reject, timer });
+ try {
+ this.ws.send(frame(TYPE_PING, 0, 0, payload));
+ } catch (e) {
+ clearTimeout(timer);
+ this.pings.delete(key);
+ reject(e instanceof Error ? e : new Error(String(e)));
+ }
+ });
+ }
+
+ /**
+ * unary issues one request and resolves with the response message bytes
+ * (gRPC length-prefix already stripped).
+ */
+ unary(path: string, message: Uint8Array, timeoutMs: number): Promise<Uint8Array> {
+ if (this.dead) return Promise.reject(this.dead);
+ const id = this.nextStream;
+ this.nextStream += 2; // client streams are odd
+
+ return new Promise<Uint8Array>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.calls.delete(id);
+ reject(new Error("h2grpc: call timeout"));
+ }, timeoutMs);
+ this.calls.set(id, { chunks: [], resolve, reject, timer });
+
+ // gRPC frames its message as a 1-byte compression flag plus a 4-byte
+ // big-endian length. `te: trailers` is mandatory — servers reject a gRPC
+ // request without it.
+ const body = new Uint8Array(5 + message.length);
+ body[0] = 0;
+ new DataView(body.buffer).setUint32(1, message.length);
+ body.set(message, 5);
+
+ const headers = hpack([
+ [":method", "POST"],
+ [":scheme", "http"],
+ [":path", path],
+ [":authority", this.authority],
+ ["content-type", "application/grpc"],
+ ["te", "trailers"],
+ ["grpc-timeout", `${Math.max(1, Math.floor(timeoutMs))}m`],
+ ]);
+
+ try {
+ this.ws.send(
+ concat([
+ frame(TYPE_HEADERS, FLAG_END_HEADERS, id, headers),
+ frame(TYPE_DATA, FLAG_END_STREAM, id, body),
+ ]),
+ );
+ } catch (e) {
+ clearTimeout(timer);
+ this.calls.delete(id);
+ reject(e instanceof Error ? e : new Error(String(e)));
+ }
+ });
+ }
+
+ private onBytes(chunk: Uint8Array): void {
+ this.buf = this.buf.length === 0 ? chunk : concat([this.buf, chunk]);
+ for (;;) {
+ if (this.buf.length < FRAME_HEADER) return;
+ const len = (this.buf[0] << 16) | (this.buf[1] << 8) | this.buf[2];
+ if (this.buf.length < FRAME_HEADER + len) return;
+ const type = this.buf[3];
+ const flags = this.buf[4];
+ const id = new DataView(this.buf.buffer, this.buf.byteOffset + 5, 4).getUint32(0) & 0x7fffffff;
+ const payload = this.buf.subarray(FRAME_HEADER, FRAME_HEADER + len);
+ this.onFrame(type, flags, id, payload);
+ this.buf = this.buf.subarray(FRAME_HEADER + len);
+ }
+ }
+
+ private onFrame(type: number, flags: number, id: number, payload: Uint8Array): void {
+ switch (type) {
+ case TYPE_SETTINGS:
+ if (!(flags & FLAG_ACK)) this.ws.send(frame(TYPE_SETTINGS, FLAG_ACK, 0, new Uint8Array(0)));
+ if (this.readyResolve) {
+ this.readyResolve();
+ this.readyResolve = null;
+ this.readyReject = null;
+ }
+ return;
+ case TYPE_PING: {
+ if (!(flags & FLAG_ACK)) {
+ this.ws.send(frame(TYPE_PING, FLAG_ACK, 0, payload.slice()));
+ return;
+ }
+ const p = this.pings.get(keyOf(payload));
+ if (p) {
+ this.pings.delete(keyOf(payload));
+ clearTimeout(p.timer);
+ p.resolve();
+ }
+ return;
+ }
+ case TYPE_GOAWAY:
+ this.kill(new Error("h2grpc: server sent GOAWAY"));
+ return;
+ case TYPE_WINDOW_UPDATE:
+ return;
+ case TYPE_RST_STREAM: {
+ const call = this.calls.get(id);
+ if (call) {
+ clearTimeout(call.timer);
+ this.calls.delete(id);
+ call.reject(new Error("h2grpc: stream reset by server"));
+ }
+ return;
+ }
+ case TYPE_DATA: {
+ const call = this.calls.get(id);
+ if (call) call.chunks.push(payload.slice());
+ // Give the window straight back. Cheaper than tracking consumption, and
+ // a unary response is never large enough for the extra frames to matter.
+ if (payload.length > 0) {
+ this.ws.send(
+ concat([windowUpdateFrame(0, payload.length), windowUpdateFrame(id, payload.length)]),
+ );
+ }
+ if (flags & FLAG_END_STREAM) this.finish(id);
+ return;
+ }
+ case TYPE_HEADERS:
+ // Response headers or trailers. Never decoded — see the file docstring.
+ // Only the END_STREAM flag matters, and it is right here in the frame.
+ if (flags & FLAG_END_STREAM) this.finish(id);
+ return;
+ default:
+ return;
+ }
+ }
+
+ private finish(id: number): void {
+ const call = this.calls.get(id);
+ if (!call) return;
+ clearTimeout(call.timer);
+ this.calls.delete(id);
+ const body = concat(call.chunks);
+ if (body.length < 5) {
+ // No message came back, so the call failed and the reason is in trailers
+ // we do not read. The caller's move either way is the tunnel fallback.
+ call.reject(new Error("h2grpc: empty response (see grpc-status in trailers)"));
+ return;
+ }
+ const msgLen = new DataView(body.buffer, body.byteOffset + 1, 4).getUint32(0);
+ call.resolve(body.subarray(5, 5 + msgLen));
+ }
+}
+
+// --- frame helpers ---
+
+function frame(type: number, flags: number, streamID: number, payload: Uint8Array): Uint8Array {
+ const out = new Uint8Array(FRAME_HEADER + payload.length);
+ out[0] = (payload.length >> 16) & 0xff;
+ out[1] = (payload.length >> 8) & 0xff;
+ out[2] = payload.length & 0xff;
+ out[3] = type;
+ out[4] = flags;
+ new DataView(out.buffer).setUint32(5, streamID);
+ out.set(payload, FRAME_HEADER);
+ return out;
+}
+
+function settingsFrame(): Uint8Array {
+ const p = new Uint8Array(6);
+ new DataView(p.buffer).setUint16(0, SETTINGS_INITIAL_WINDOW_SIZE);
+ new DataView(p.buffer).setUint32(2, WINDOW);
+ return frame(TYPE_SETTINGS, 0, 0, p);
+}
+
+function windowUpdateFrame(streamID: number, n: number): Uint8Array {
+ const p = new Uint8Array(4);
+ new DataView(p.buffer).setUint32(0, n);
+ return frame(TYPE_WINDOW_UPDATE, 0, streamID, p);
+}
+
+/**
+ * hpack encodes headers as literal-without-indexing with literal names — the
+ * one HPACK form that needs neither the static/dynamic tables nor Huffman. It
+ * is more bytes on the wire than a real encoder would use, and for a handful of
+ * short headers that is irrelevant next to not carrying an HPACK implementation.
+ */
+function hpack(headers: Array<[string, string]>): Uint8Array {
+ const parts: Uint8Array[] = [];
+ for (const [name, value] of headers) {
+ const n = enc(name);
+ const v = enc(value);
+ parts.push(new Uint8Array([0x00]), lenPrefixed(n), lenPrefixed(v));
+ }
+ return concat(parts);
+}
+
+/** HPACK string literal: 7-bit length prefix, Huffman bit clear, then bytes. */
+function lenPrefixed(b: Uint8Array): Uint8Array {
+ if (b.length < 127) {
+ const out = new Uint8Array(1 + b.length);
+ out[0] = b.length;
+ out.set(b, 1);
+ return out;
+ }
+ // Lengths ≥127 use a continuation varint. Only :path can realistically get
+ // there, and not for the RPCs served here, but truncating silently would be
+ // a nasty bug so it is handled rather than assumed away.
+ const varint: number[] = [127];
+ let rest = b.length - 127;
+ while (rest >= 128) {
+ varint.push((rest & 0x7f) | 0x80);
+ rest >>= 7;
+ }
+ varint.push(rest);
+ const out = new Uint8Array(varint.length + b.length);
+ out.set(varint, 0);
+ out.set(b, varint.length);
+ return out;
+}
+
+/** Map key for a PING payload — 8 opaque bytes as hex. */
+function keyOf(b: Uint8Array): string {
+ let s = "";
+ for (const x of b) s += x.toString(16).padStart(2, "0");
+ return s;
+}
+
+function enc(s: string): Uint8Array {
+ return new TextEncoder().encode(s);
+}
+
+function concat(parts: Uint8Array[]): Uint8Array {
+ let n = 0;
+ for (const p of parts) n += p.length;
+ const out = new Uint8Array(n);
+ let off = 0;
+ for (const p of parts) {
+ out.set(p, off);
+ off += p.length;
+ }
+ return out;
+}
+
+// --- protobuf for agent.SandboxAgent/Exec ---
+//
+// Hand-rolled rather than generated: two messages with six scalar fields
+// between them, against pulling a protobuf runtime into a Worker bundle that
+// has to stay small and cold-start fast.
+
+export interface ExecReq {
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+ cwd?: string;
+ timeoutSeconds?: number;
+ runAsRoot?: boolean;
+}
+
+export interface ExecRes {
+ exitCode: number;
+ stdout: string;
+ stderr: string;
+}
+
+export function encodeExecRequest(r: ExecReq): Uint8Array {
+ const parts: Uint8Array[] = [];
+ parts.push(pbString(1, r.command));
+ for (const a of r.args ?? []) parts.push(pbString(2, a));
+ for (const [k, v] of Object.entries(r.env ?? {})) {
+ // map<string,string> is a repeated message of {1: key, 2: value}.
+ parts.push(pbBytes(3, concat([pbString(1, k), pbString(2, v)])));
+ }
+ if (r.cwd) parts.push(pbString(4, r.cwd));
+ if (r.timeoutSeconds) parts.push(pbVarint(5, r.timeoutSeconds));
+ if (r.runAsRoot) parts.push(pbVarint(6, 1));
+ return concat(parts);
+}
+
+export function decodeExecResponse(b: Uint8Array): ExecRes {
+ const out: ExecRes = { exitCode: 0, stdout: "", stderr: "" };
+ const dec = new TextDecoder();
+ let i = 0;
+ while (i < b.length) {
+ const [tag, n1] = varint(b, i);
+ i = n1;
+ const field = tag >>> 3;
+ const wire = tag & 0x7;
+ if (wire === 0) {
+ const [v, n2] = varint(b, i);
+ i = n2;
+ if (field === 1) out.exitCode = v | 0;
+ } else if (wire === 2) {
+ const [len, n2] = varint(b, i);
+ const s = dec.decode(b.subarray(n2, n2 + len));
+ i = n2 + len;
+ if (field === 2) out.stdout = s;
+ else if (field === 3) out.stderr = s;
+ } else {
+ break; // unknown wire type — nothing safe left to read
+ }
+ }
+ return out;
+}
+
+function pbString(field: number, s: string): Uint8Array {
+ return pbBytes(field, enc(s));
+}
+
+function pbBytes(field: number, b: Uint8Array): Uint8Array {
+ return concat([uvarint((field << 3) | 2), uvarint(b.length), b]);
+}
+
+function pbVarint(field: number, v: number): Uint8Array {
+ return concat([uvarint(field << 3), uvarint(v)]);
+}
+
+function uvarint(v: number): Uint8Array {
+ const out: number[] = [];
+ let x = v;
+ while (x >= 128) {
+ out.push((x & 0x7f) | 0x80);
+ x >>>= 7;
+ }
+ out.push(x);
+ return new Uint8Array(out);
+}
+
+function varint(b: Uint8Array, i: number): [number, number] {
+ let v = 0;
+ let shift = 0;
+ let j = i;
+ for (; j < b.length; j++) {
+ v |= (b[j] & 0x7f) << shift;
+ if ((b[j] & 0x80) === 0) return [v >>> 0, j + 1];
+ shift += 7;
+ }
+ return [v >>> 0, j];
+}
diff --git a/cloudflare-workers/vm-do/src/index.ts b/cloudflare-workers/vm-do/src/index.ts
index 8e43aa47..c39e25ab 100644
--- a/cloudflare-workers/vm-do/src/index.ts
+++ b/cloudflare-workers/vm-do/src/index.ts
@@ -14,6 +14,10 @@
// /internal/vms/:id/connect and routes /exec) — this worker has no routes and
// its own fetch handler serves nothing.
export { VmSession } from "./vm_session";
+// MicrovmSession is the AWS MicroVM counterpart: same persistent-channel idea,
+// but it dials OUT to the box because that runtime has no host process of ours
+// to dial in. See microvm_session.ts.
+export { MicrovmSession } from "./microvm_session";
export default {
async fetch(): Promise<Response> {
diff --git a/cloudflare-workers/vm-do/src/microvm_session.ts b/cloudflare-workers/vm-do/src/microvm_session.ts
new file mode 100644
index 00000000..b05d0732
--- /dev/null
+++ b/cloudflare-workers/vm-do/src/microvm_session.ts
@@ -0,0 +1,313 @@
+// microvm_session.ts — one Durable Object per MicroVM sandbox, holding an open
+// agent tunnel so exec is a single round trip from the edge to the guest.
+//
+// The QEMU sibling in vm_session.ts is HOST-DIALED: a worker process we own
+// opens a WebSocket out to the DO. MicroVM has no host process — AWS runs the
+// box — so this one dials IN, to the MicroVM's public endpoint, using the same
+// port-scoped credential the control plane uses. Everything else about the
+// shape is the same: a persistent channel, request/reply over it, and a caller
+// that falls back to the control-plane path whenever the channel isn't there.
+//
+// WHY IT IS WORTH THE MACHINERY (measured on dev, Worker confirmed in IAD):
+//
+// edge → control plane (CF tunnel), round trip ~70ms
+// edge → guest agent, through this tunnel ~4-5ms
+// opening the tunnel (one-time, off the hot path) ~30-45ms
+//
+// Today every exec pays the first line plus the control-plane's own hop to the
+// box. This replaces both with the second line.
+//
+// SCOPE: one-shot Exec only. Streaming, PTY and file transfer stay on the
+// control-plane path — they are not implemented here and calls for them should
+// never be routed to this DO.
+
+import { H2Grpc, encodeExecRequest, decodeExecResponse, type ExecReq } from "./h2grpc";
+
+const EXEC_PATH = "/agent.SandboxAgent/Exec";
+const AGENT_TUNNEL_PATH = "/osb/agent-grpc"; // must match internal/awsvm.AgentTunnelPath
+// Bounded well below the caller's own deadline: a call that outlives it is a
+// call the caller has already given up on and re-run through the tunnel.
+const DEFAULT_TIMEOUT_MS = 10_000;
+
+// KEEPALIVE — see alarm().
+//
+// Cloudflare evicts an idle Durable Object after roughly ten seconds, and an
+// outbound WebSocket is NOT hibernatable: it dies with the object. That is what
+// made the stock-time warm dial worthless in practice — a box sits in stock for
+// minutes, the DO is long gone by the time a customer arrives, and the first
+// exec pays the full re-dial plus the AWS proxy's guest attach (measured: 632
+// -1395ms, against ~26ms on a channel that is already up).
+//
+// An alarm every 5s keeps the object inside that eviction window, and the ping
+// it sends keeps the proxy→guest attachment from going idle too. 5s rather than
+// 9s because alarm delivery has jitter and the cost of being wrong is paying the
+// whole re-dial on a customer's first exec.
+const KEEPALIVE_MS = 5_000;
+// How long an attached box is kept warm without being used. Deliberately long:
+// stock can sit for a while and the whole point is that the customer never waits
+// for a dial. Refreshed by every attach and every exec.
+const KEEPALIVE_TTL_MS = 60 * 60 * 1000;
+// Consecutive failed keepalives before we stop. A box that has been destroyed
+// or whose credential expired will never answer, and pinging it forever would
+// leave one alarm loop running per dead sandbox.
+const MAX_KEEPALIVE_FAILURES = 5;
+const PING_TIMEOUT_MS = 3_000;
+
+interface Creds {
+ endpoint: string;
+ token: string;
+ port: number;
+}
+
+export class MicrovmSession {
+ private state: DurableObjectState;
+ private creds: Creds | null = null;
+ private conn: H2Grpc | null = null;
+ private ws: WebSocket | null = null;
+ private dialing: Promise<H2Grpc> | null = null;
+ private failures = 0;
+ // In memory only. Persisting it would put a storage write on the exec path to
+ // save an alarm loop that costs nothing; an eviction just restarts the clock,
+ // and the alarm re-reads the durable deadline set at attach.
+ private warmUntil = 0;
+
+ constructor(state: DurableObjectState) {
+ this.state = state;
+ }
+
+ async fetch(req: Request): Promise<Response> {
+ const path = new URL(req.url).pathname;
+ try {
+ if (path === "/attach") return await this.attach(req);
+ if (path === "/exec") return await this.exec(req);
+ if (path === "/status")
+ return json({
+ attached: this.creds !== null,
+ live: this.live(),
+ warmUntil: this.warmUntil,
+ failures: this.failures,
+ });
+ if (path === "/detach") return await this.detach();
+ } catch (e) {
+ return json({ error: String(e) }, 500);
+ }
+ return json({ error: "not found" }, 404);
+ }
+
+ private live(): boolean {
+ return this.conn !== null && !this.conn.closed;
+ }
+
+ /**
+ * attach records how to reach this sandbox's box. Called on the create path
+ * with the endpoint and token the pool already holds, so nothing here needs
+ * to talk to AWS or to the control plane.
+ *
+ * Deliberately does NOT dial unless asked: create is latency-critical, and the
+ * dial can happen on the first exec (~35ms) or be warmed separately.
+ *
+ * Whether or not it dials, it arms the keepalive — that is what makes the warm
+ * dial survive to the customer rather than being evicted a few seconds later.
+ */
+ private async attach(req: Request): Promise<Response> {
+ const c = (await req.json()) as Creds & { dial?: boolean };
+ if (!c?.endpoint || !c?.token || !c?.port) return json({ error: "endpoint, token and port required" }, 400);
+ this.creds = { endpoint: c.endpoint, token: c.token, port: c.port };
+ this.failures = 0;
+ this.warmUntil = Date.now() + KEEPALIVE_TTL_MS;
+ // Persisted so an evicted DO can re-dial without a round trip back to the
+ // control plane. Credentials expire, which is why a dial failure has to be
+ // reported plainly rather than retried forever — see exec().
+ await this.state.storage.put({ creds: this.creds, warmUntil: this.warmUntil });
+ await this.armKeepalive();
+ // Opening the tunnel costs ~30-45ms. Doing it here, off the create path,
+ // means the first exec — the one time-to-first-command actually measures —
+ // finds a live channel instead of paying for it.
+ if (c.dial) {
+ try {
+ await this.dial(this.creds);
+ } catch (e) {
+ // Not fatal: exec re-dials on demand, and a box that refuses now may
+ // simply be mid-resume. The keepalive will retry in KEEPALIVE_MS.
+ console.log(`mvm-do: warm dial failed: ${e}`);
+ }
+ }
+ return json({ ok: true, live: this.live() });
+ }
+
+ private async detach(): Promise<Response> {
+ this.creds = null;
+ this.conn = null;
+ this.warmUntil = 0;
+ try {
+ this.ws?.close();
+ } catch {
+ /* already gone */
+ }
+ this.ws = null;
+ // Deleting the alarm matters as much as dropping the credentials: without
+ // it a released box would keep an alarm loop dialing an endpoint that has
+ // been handed to a different tenant.
+ await this.state.storage.deleteAlarm();
+ await this.state.storage.delete(["creds", "warmUntil"]);
+ return json({ ok: true });
+ }
+
+ private async armKeepalive(): Promise<void> {
+ // setAlarm overwrites, so this is also the re-arm. Only skip when one is
+ // already due sooner than we would set it — a burst of attaches must not
+ // push the next tick further out.
+ const due = await this.state.storage.getAlarm();
+ const next = Date.now() + KEEPALIVE_MS;
+ if (due !== null && due <= next) return;
+ await this.state.storage.setAlarm(next);
+ }
+
+ /**
+ * alarm keeps this object — and the tunnel it owns — alive.
+ *
+ * Two things decay on their own and both are fixed here. The Durable Object
+ * is evicted once it goes idle, taking its non-hibernatable outbound
+ * WebSocket with it; and the AWS proxy's attachment to the guest port goes
+ * cold if nothing crosses it. Waking on a timer handles the first, and the
+ * HTTP/2 PING — which the guest's own stack has to answer — handles the
+ * second. The whole point is that this cost is paid on a timer nobody is
+ * waiting on, instead of on the customer's first exec.
+ *
+ * Never throws: a Durable Object alarm that throws is retried on the
+ * platform's schedule, not ours, and we would rather re-arm deliberately.
+ */
+ async alarm(): Promise<void> {
+ const creds = await this.loadCreds();
+ if (!creds) return; // detached — let the loop end
+ if (!this.warmUntil) this.warmUntil = (await this.state.storage.get<number>("warmUntil")) ?? 0;
+ if (this.warmUntil && Date.now() > this.warmUntil) {
+ // Unused long enough that holding a socket open for it is waste. Exec
+ // still works — it just pays for its own dial.
+ console.log("mvm-do: keepalive expired, going cold");
+ return;
+ }
+ try {
+ const conn = await this.channel();
+ await conn.ping(PING_TIMEOUT_MS);
+ this.failures = 0;
+ } catch (e) {
+ this.conn = null;
+ this.failures++;
+ console.log(`mvm-do: keepalive failed (${this.failures}/${MAX_KEEPALIVE_FAILURES}): ${e}`);
+ if (this.failures >= MAX_KEEPALIVE_FAILURES) {
+ // Destroyed box, or a credential that has aged out. Either way nothing
+ // here can fix it, and a permanent retry loop per dead sandbox is worse
+ // than a cold first exec.
+ console.log("mvm-do: keepalive giving up");
+ return;
+ }
+ }
+ await this.state.storage.setAlarm(Date.now() + KEEPALIVE_MS);
+ }
+
+ private async loadCreds(): Promise<Creds | null> {
+ if (this.creds) return this.creds;
+ this.creds = (await this.state.storage.get<Creds>("creds")) ?? null;
+ return this.creds;
+ }
+
+ /**
+ * dial opens the agent tunnel and wraps it in an HTTP/2 client.
+ *
+ * Single-flighted: a burst of execs arriving at a cold DO must produce one
+ * tunnel, not one per request. Without this the first exec after eviction
+ * would open N sockets against the box and leak all but one.
+ */
+ private dial(creds: Creds): Promise<H2Grpc> {
+ if (this.dialing) return this.dialing;
+ const p = (async (): Promise<H2Grpc> => {
+ const tDial = Date.now();
+ const host = creds.endpoint.replace(/^https?:\/\//, "").split("/")[0];
+ const resp = await fetch(`https://${host}${AGENT_TUNNEL_PATH}`, {
+ signal: AbortSignal.timeout(3000),
+ headers: {
+ Upgrade: "websocket",
+ "X-aws-proxy-auth": creds.token,
+ "X-aws-proxy-port": String(creds.port),
+ },
+ });
+ const ws = (resp as unknown as { webSocket: WebSocket | null }).webSocket;
+ if (!ws) throw new Error(`agent tunnel upgrade failed (http ${resp.status})`);
+ ws.accept();
+ this.ws = ws;
+ const conn = new H2Grpc(ws, host);
+ this.conn = conn;
+ // Wait for the guest, not just the proxy — see H2Grpc.ready.
+ await Promise.race([
+ conn.ready,
+ new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), 8000)),
+ ]);
+ // Logged rather than dropped: a dial here is the ~1.1s guest-attach the
+ // keepalive exists to keep off the customer's path, so a run of them is
+ // the signal that the keepalive is not holding.
+ console.log(`mvm-do: dial+ready in ${Date.now() - tDial}ms`);
+ return conn;
+ })();
+ this.dialing = p;
+ p.catch(() => undefined).then(() => {
+ if (this.dialing === p) this.dialing = null;
+ });
+ return p;
+ }
+
+ private async channel(): Promise<H2Grpc> {
+ const creds = await this.loadCreds();
+ if (!creds) throw new Error("not attached");
+ if (this.conn && !this.conn.closed) return this.conn;
+ this.conn = null;
+ return this.dial(creds);
+ }
+
+ private async exec(req: Request): Promise<Response> {
+ const body = (await req.json()) as ExecReq & { timeoutMs?: number };
+ if (!body?.command) return json({ error: "command required" }, 400);
+
+ let conn: H2Grpc;
+ try {
+ conn = await this.channel();
+ } catch (e) {
+ // 409 is the caller's cue to use the control-plane path. Every reason we
+ // can't reach the box lands here — never attached, DO evicted with stale
+ // credentials, box suspended, tunnel refused — and the answer to all of
+ // them is the same, so they deliberately are not distinguished.
+ return json({ error: `channel unavailable: ${e}`, fallback: true }, 409);
+ }
+
+ const timeoutMs = body.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ try {
+ const tU = Date.now();
+ const res = await conn.unary(EXEC_PATH, encodeExecRequest(body), timeoutMs);
+ // Kept deliberately. This is the only number that separates transport
+ // from the guest actually running the command: everything else the edge
+ // can see lumps them together, which is how ~700ms of shell startup spent
+ // a whole session being mistaken for a slow tunnel.
+ console.log(`mvm-do: unary ${Date.now() - tU}ms`);
+ // Being used is the strongest signal the box is worth keeping warm, so
+ // each exec pushes the deadline out and restarts the loop if it had
+ // lapsed (TTL expiry, or a run of failures while the box was resuming).
+ this.warmUntil = Date.now() + KEEPALIVE_TTL_MS;
+ this.failures = 0;
+ await this.state.storage.put("warmUntil", this.warmUntil);
+ await this.armKeepalive();
+ return json(decodeExecResponse(res));
+ } catch (e) {
+ // The channel is suspect once a call fails on it: drop it so the next
+ // exec re-dials rather than inheriting a half-dead connection.
+ this.conn = null;
+ return json({ error: `exec failed: ${e}`, fallback: true }, 409);
+ }
+ }
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
diff --git a/cloudflare-workers/vm-do/wrangler.toml b/cloudflare-workers/vm-do/wrangler.toml
index 0de6f581..f1e5f67b 100644
--- a/cloudflare-workers/vm-do/wrangler.toml
+++ b/cloudflare-workers/vm-do/wrangler.toml
@@ -17,6 +17,14 @@ account_id = "1241f114453e32d292197e3fb36210b2"
name = "VM_SESSIONS"
class_name = "VmSession"
+[[durable_objects.bindings]]
+name = "MICROVM_SESSIONS"
+class_name = "MicrovmSession"
+
[[migrations]]
tag = "v1"
new_sqlite_classes = ["VmSession"]
+
+[[migrations]]
+tag = "v2"
+new_sqlite_classes = ["MicrovmSession"]
diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.go
index e9d09abc..40d34b09 100644
--- a/internal/api/edge_claim.go
+++ b/internal/api/edge_claim.go
@@ -3,6 +3,7 @@ package api
import (
"context"
"encoding/json"
+ "errors"
"log"
"net/http"
"time"
@@ -47,6 +48,85 @@ var processEpoch = uuid.New().String()
// DO dies without releasing).
const edgeReserveTTL = 15 * time.Minute
+// THE FINALIZE RACE
+//
+// The edge answers a create from stock and returns the 201 before this process
+// has heard of the sandbox: the claim is finalized afterwards, off the create
+// path and (on the queue-backed edge) off the create's isolate entirely. So the
+// customer holds a usable sandbox id for a window in which GetSandboxSession
+// still misses, and their first exec — which the SDK fires immediately — used
+// to come back "sandbox <id> not found". Measured on dev: 3 of 8 creates in a
+// back-to-back create→exec run.
+//
+// A 404 is the wrong answer to "the row is a few hundred milliseconds behind",
+// and worse than wrong for a benchmark, where a fast failure reads as a fast
+// exec. So a reservation registers a pending claim here, and any sub-op that
+// arrives during the window waits for the finalize instead of being told the
+// box does not exist. It is not a retry loop and it is not a sleep: the waiter
+// is released the moment claim-finalize completes.
+//
+// It is deliberately bounded on both ends. edgePendingWait caps how long any
+// one caller waits, after which the normal lookup runs and answers 404 exactly
+// as before — a broken finalize must not turn into a hung request. And a
+// pending entry is dropped on finalize, on release, and by the stale-reservation
+// reaper, so an id that never becomes a sandbox cannot accumulate.
+const edgePendingWait = 5 * time.Second
+
+// edgePending is one reserved-but-not-yet-finalized sandbox id.
+type edgePending struct {
+ done chan struct{} // closed when the claim resolves, either way
+ err error // set before closing done; non-nil = the claim failed
+}
+
+// registerEdgePending records that sandboxID has been reserved for the edge and
+// that a claim-finalize for it may arrive. Idempotent: a re-reserve of the same
+// id keeps the existing waiter rather than orphaning it.
+func (s *Server) registerEdgePending(sandboxID string) {
+ s.pendingEdgeClaims.LoadOrStore(sandboxID, &edgePending{done: make(chan struct{})})
+}
+
+// resolveEdgePending releases anyone waiting on sandboxID and forgets it. Called
+// on every terminal outcome for a reservation — finalized, released back to the
+// pool, or reaped — so the map tracks only claims that are genuinely in flight.
+//
+// Forgetting it means err reaches only callers ALREADY parked. Someone arriving
+// afterwards gets the ordinary lookup, which by then is authoritative: the row
+// exists if the claim worked, and 404s if it didn't. Keeping failures around as
+// tombstones would buy a better message at the cost of a second thing to expire.
+func (s *Server) resolveEdgePending(sandboxID string, err error) {
+ val, ok := s.pendingEdgeClaims.LoadAndDelete(sandboxID)
+ if !ok {
+ return
+ }
+ p := val.(*edgePending)
+ p.err = err
+ close(p.done)
+}
+
+// waitEdgeFinalize blocks until sandboxID's claim-finalize resolves, or gives up
+// and lets the caller take the normal (404) path. Returns nil for an id that was
+// never an edge reservation, so it is safe to call for every lookup miss.
+func (s *Server) waitEdgeFinalize(ctx context.Context, sandboxID string) error {
+ val, ok := s.pendingEdgeClaims.Load(sandboxID)
+ if !ok {
+ return nil
+ }
+ p := val.(*edgePending)
+ timer := time.NewTimer(edgePendingWait)
+ defer timer.Stop()
+ select {
+ case <-p.done:
+ // A failed finalize is reported rather than swallowed: the box never
+ // bound, and a clean error beats a phantom the customer keeps poking.
+ return p.err
+ case <-timer.C:
+ log.Printf("sandbox: edge claim %s still unfinalized after %s — proceeding without it", sandboxID, edgePendingWait)
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
// edgeReservePool handles POST /internal/pool/edge-reserve {count} — flips up
// to count pooled boxes to edge_reserved and returns them for the DO's stock.
func (s *Server) edgeReservePool(c echo.Context) error {
@@ -82,9 +162,22 @@ func (s *Server) edgeReservePool(c echo.Context) error {
// which bounds the exposure to one restock cycle.
if ec, ok := s.edgeClaimBackend(); ok {
boxes := ec.EdgeReserve(req.Count)
- out := make([]map[string]string, 0, len(boxes))
+ out := make([]map[string]interface{}, 0, len(boxes))
for _, b := range boxes {
- out = append(out, map[string]string{"sandboxID": b.SandboxID, "workerID": b.WorkerID})
+ // From here the edge may hand this id to a customer at any moment,
+ // so anything that arrives for it before claim-finalize waits
+ // rather than 404s. See THE FINALIZE RACE above.
+ s.registerEdgePending(b.SandboxID)
+ e := map[string]interface{}{"sandboxID": b.SandboxID, "workerID": b.WorkerID}
+ // Reach-info, when the backend has it (see edgeBox). Lets the edge
+ // warm the box's agent tunnel while it is still stock, so the first
+ // exec doesn't pay for attaching to the guest.
+ if b.Endpoint != "" && b.Token != "" {
+ e["endpoint"] = b.Endpoint
+ e["token"] = b.Token
+ e["port"] = b.Port
+ }
+ out = append(out, e)
}
return c.JSON(http.StatusOK, map[string]interface{}{
"region": region,
@@ -100,6 +193,7 @@ func (s *Server) edgeReservePool(c echo.Context) error {
}
out := make([]map[string]string, 0, len(boxes))
for _, b := range boxes {
+ s.registerEdgePending(b.SandboxID)
out = append(out, map[string]string{"sandboxID": b.SandboxID, "workerID": b.WorkerID})
}
log.Printf("pool: edge-reserved %d box(es) (asked %d)", len(out), req.Count)
@@ -119,6 +213,12 @@ func (s *Server) edgeReleasePool(c echo.Context) error {
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})
}
+ // Released stock was never handed to a customer, so nobody can be waiting on
+ // it — but the pending entry must go either way or the id lingers in the map
+ // until the reaper notices.
+ for _, id := range req.SandboxIDs {
+ s.resolveEdgePending(id, nil)
+ }
if ec, ok := s.edgeClaimBackend(); ok {
return c.JSON(http.StatusOK, map[string]int{"released": ec.EdgeRelease(req.SandboxIDs)})
}
@@ -159,6 +259,12 @@ func (s *Server) claimFinalize(c echo.Context) error {
}
cfg := req.SandboxConfig
cfg.SandboxID = req.SandboxID
+ // Release anyone whose sub-op is parked waiting for this claim, whatever the
+ // outcome — a finalize that fails has to wake them with the failure rather
+ // than leave them waiting out edgePendingWait for a box that never bound.
+ // Defaults to an error so an unexpected return path still reports one.
+ finalizeErr := errors.New("claim-finalize did not complete")
+ defer func() { s.resolveEdgePending(cfg.SandboxID, finalizeErr) }()
// Edge eligibility should have filtered these; enforce anyway so finalize
// can't silently skip a capability the box was never given.
if cfg.SecretStore != "" {
@@ -184,6 +290,7 @@ func (s *Server) claimFinalize(c echo.Context) error {
// The reservation is gone (reaped, or a duplicate delivery of a
// finalize that already ran). Nothing to bind and nothing to undo.
log.Printf("sandbox: EDGE CLAIM FINALIZE LOST %s (%v)", cfg.SandboxID, err)
+ finalizeErr = err
return c.JSON(http.StatusConflict, map[string]string{"error": "reservation lost"})
}
template := cfg.Template
@@ -198,11 +305,13 @@ func (s *Server) claimFinalize(c echo.Context) error {
// orphan sweep reclaim a box with no row — the mechanism that
// exists for exactly this hole.
log.Printf("sandbox: edge claim-finalize row insert %s failed: %v", cfg.SandboxID, err)
+ finalizeErr = err
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
}
s.emitEvent("create", cfg.SandboxID, workerID, "claimed from warm pool (edge)")
log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", cfg.SandboxID, workerID)
+ finalizeErr = nil
return c.JSON(http.StatusOK, map[string]string{
"sandboxID": cfg.SandboxID,
"workerID": workerID,
@@ -214,6 +323,7 @@ func (s *Server) claimFinalize(c echo.Context) error {
// Reservation lost (reaped/drained). Nothing is bound; make sure the
// row can never be claimed by anyone else and report the loss.
log.Printf("sandbox: EDGE CLAIM FINALIZE LOST %s (%v)", cfg.SandboxID, err)
+ finalizeErr = err
_ = s.store.WipePooled(ctx, cfg.SandboxID)
return c.JSON(http.StatusConflict, map[string]string{"error": "reservation lost"})
}
@@ -221,6 +331,7 @@ func (s *Server) claimFinalize(c echo.Context) error {
client, err := s.workerRegistry.GetWorkerClient(box.WorkerID)
if err != nil {
msg := "pool worker unreachable at claim-finalize"
+ finalizeErr = errors.New(msg)
_ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "failed", &msg)
return c.JSON(http.StatusBadGateway, map[string]string{"error": msg})
}
@@ -236,6 +347,7 @@ func (s *Server) claimFinalize(c echo.Context) error {
})
if err != nil {
log.Printf("sandbox: edge claim-finalize ClaimSandbox %s failed: %v", box.SandboxID, err)
+ finalizeErr = err
msg := err.Error()
_ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "failed", &msg)
return c.JSON(http.StatusBadGateway, map[string]string{"error": msg})
@@ -276,6 +388,7 @@ func (s *Server) claimFinalize(c echo.Context) error {
s.emitEvent("create", box.SandboxID, box.WorkerID, "claimed from warm pool (edge)")
log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", box.SandboxID, box.WorkerID)
+ finalizeErr = nil
return c.JSON(http.StatusOK, map[string]string{
"sandboxID": box.SandboxID,
"workerID": box.WorkerID,
@@ -299,6 +412,9 @@ func (s *Server) reapStaleEdgeReservations(ctx context.Context) {
cancel()
}
_ = s.store.WipePooled(ctx, b.SandboxID)
+ // The box is gone, so a waiter must be told rather than left to time
+ // out — and the pending entry must not outlive the reservation.
+ s.resolveEdgePending(b.SandboxID, errors.New("edge reservation expired before it was claimed"))
}
if len(boxes) > 0 {
log.Printf("pool: reaped %d stale edge reservation(s)", len(boxes))
diff --git a/internal/api/edge_claim_microvm.go b/internal/api/edge_claim_microvm.go
index 88f2cf0f..0b417b95 100644
--- a/internal/api/edge_claim_microvm.go
+++ b/internal/api/edge_claim_microvm.go
@@ -1,9 +1,12 @@
package api
import (
+ "context"
+ "errors"
"fmt"
"log"
"sync"
+ "time"
"github.com/google/uuid"
@@ -45,6 +48,24 @@ import (
type edgeBox struct {
SandboxID string
WorkerID string
+
+ // Reach-info: how to talk to this box WITHOUT going through this process.
+ // The endpoint is a public TLS host and the token is a port-scoped header
+ // credential, so handing them to the edge lets it hold the agent tunnel
+ // itself and take the control plane out of the exec data path entirely.
+ //
+ // Delivered here, at reserve, rather than fetched later on purpose: the
+ // sandbox id is already assigned at this point, so the edge can open and
+ // guest-attach the tunnel while the box is still sitting in stock — before
+ // any customer exists. Measured, that is the difference between a first exec
+ // of ~30ms and one of ~1.1s, because the AWS proxy only connects to the
+ // guest when payload first arrives and somebody has to pay for that.
+ //
+ // Empty on the Postgres path: those cells route through a worker, and this
+ // is a MicroVM-only shortcut.
+ Endpoint string
+ Token string
+ Port int32
}
// edgeClaimer is a backend that serves edge-claim from its own stock instead of
@@ -136,7 +157,13 @@ func (b *microvmBackend) EdgeReserve(n int) []edgeBox {
// real config once there is one.
b.manager.TrackClaimed(sandboxID, e, types.SandboxConfig{})
b.edgeReserved.put(e.MicrovmID, sandboxID)
- out = append(out, edgeBox{SandboxID: sandboxID, WorkerID: microvmWorkerID(e.MicrovmID)})
+ out = append(out, edgeBox{
+ SandboxID: sandboxID,
+ WorkerID: microvmWorkerID(e.MicrovmID),
+ Endpoint: e.Endpoint,
+ Token: e.Token,
+ Port: b.pool.AgentPort(),
+ })
}
log.Printf("microvm: edge-reserved %d box(es) (asked %d, %d left in stock)", len(out), n, b.pool.Depth())
return out
@@ -223,6 +250,9 @@ func (b *microvmBackend) forgetExpiredReservation(microvmID string) {
return
}
b.manager.Forget(sandboxID)
+ if b.onReservationLost != nil {
+ b.onReservationLost(sandboxID, errors.New("edge reservation expired before it was claimed"))
+ }
log.Printf("microvm: edge reservation %s (box %s) expired unclaimed — binding dropped", sandboxID, microvmID)
}
@@ -301,4 +331,13 @@ func (b *microvmBackend) warmReservedTunnels() {
if n := b.manager.WarmAgents(reserved); n > 0 {
log.Printf("microvm: re-warmed %d idle tunnel(s) across %d edge reservation(s)", n, len(reserved))
}
+ // Reconnecting the channel is not enough to keep the box awake — only guest
+ // traffic is. Edge reservations matter most here: they are the boxes a
+ // customer is about to claim, so a suspended one turns into ~1s on the very
+ // first exec. See the keepalive block in internal/awsvm/agent.go.
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if ok, failed := b.manager.PingAgents(ctx, reserved); ok+failed > 0 {
+ log.Printf("microvm: keepalive pinged %d reserved box(es) (%d failed)", ok, failed)
+ }
}
diff --git a/internal/api/edge_claim_pending_test.go b/internal/api/edge_claim_pending_test.go
new file mode 100644
index 00000000..02059cab
--- /dev/null
+++ b/internal/api/edge_claim_pending_test.go
@@ -0,0 +1,135 @@
+package api
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+// The behaviour under test is the one that produced "sandbox <id> not found" on
+// a create→exec run: a sub-op arriving between the edge's 201 and the claim
+// finalizing. It must wait for the finalize rather than answer 404, and it must
+// come back the instant the finalize lands — not on a poll interval.
+func TestWaitEdgeFinalizeReleasesOnFinalize(t *testing.T) {
+ s := &Server{}
+ s.registerEdgePending("sb-race")
+
+ done := make(chan error, 1)
+ go func() { done <- s.waitEdgeFinalize(context.Background(), "sb-race") }()
+
+ // Give the waiter a moment to park, then finalize.
+ time.Sleep(20 * time.Millisecond)
+ start := time.Now()
+ s.resolveEdgePending("sb-race", nil)
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("waiter got %v, want nil", err)
+ }
+ if elapsed := time.Since(start); elapsed > time.Second {
+ t.Errorf("waiter released after %s — it is polling, not waiting on the finalize", elapsed)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("waiter never released after the claim finalized")
+ }
+
+ // Resolved entries are forgotten, so a later sub-op takes the normal path
+ // instead of waiting on a claim that already happened.
+ if err := s.waitEdgeFinalize(context.Background(), "sb-race"); err != nil {
+ t.Fatalf("post-finalize wait returned %v, want nil", err)
+ }
+}
+
+// A finalize that fails must wake anyone already parked WITH the failure,
+// rather than releasing them to a lookup that 404s — the box never bound, and
+// "creation failed: reservation lost" is a far more useful answer than "no such
+// sandbox".
+func TestWaitEdgeFinalizeReportsFailureToParkedWaiter(t *testing.T) {
+ s := &Server{}
+ s.registerEdgePending("sb-lost")
+ want := errors.New("reservation lost")
+
+ done := make(chan error, 1)
+ go func() { done <- s.waitEdgeFinalize(context.Background(), "sb-lost") }()
+ time.Sleep(20 * time.Millisecond)
+ s.resolveEdgePending("sb-lost", want)
+
+ select {
+ case got := <-done:
+ if !errors.Is(got, want) {
+ t.Fatalf("waiter got %v, want %v", got, want)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("waiter never released after the claim failed")
+ }
+}
+
+// A caller that arrives AFTER a failed claim was resolved takes the normal
+// path, not the stored error. Resolving forgets the id, deliberately — see the
+// note on resolveEdgePending. This pins that contract: the gate's job is to
+// stop callers racing an in-flight finalize, and once one is no longer in
+// flight the ordinary lookup is authoritative.
+func TestWaitEdgeFinalizeFallsThroughAfterResolve(t *testing.T) {
+ s := &Server{}
+ s.registerEdgePending("sb-lost-late")
+ s.resolveEdgePending("sb-lost-late", errors.New("reservation lost"))
+
+ if got := s.waitEdgeFinalize(context.Background(), "sb-lost-late"); got != nil {
+ t.Fatalf("late caller got %v, want nil so the normal lookup answers", got)
+ }
+}
+
+// An id that was never an edge reservation must not wait at all — this runs on
+// every lookup miss, including genuinely unknown sandboxes.
+func TestWaitEdgeFinalizeIgnoresUnknownID(t *testing.T) {
+ s := &Server{}
+ start := time.Now()
+ if err := s.waitEdgeFinalize(context.Background(), "sb-never-reserved"); err != nil {
+ t.Fatalf("got %v, want nil", err)
+ }
+ if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
+ t.Fatalf("waited %s on an unknown id — every 404 would now be slow", elapsed)
+ }
+}
+
+// A finalize that never arrives must not hold the request open. The waiter
+// gives up and lets the normal lookup answer, which is exactly today's
+// behaviour — the gate can only make things better, never hang them.
+func TestWaitEdgeFinalizeGivesUp(t *testing.T) {
+ s := &Server{}
+ s.registerEdgePending("sb-stuck")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ err := s.waitEdgeFinalize(ctx, "sb-stuck")
+ if elapsed := time.Since(start); elapsed >= edgePendingWait {
+ t.Fatalf("waited %s — the caller's own deadline should have cut it short", elapsed)
+ }
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("got %v, want the caller's deadline", err)
+ }
+}
+
+// Re-reserving an id must not orphan a waiter already parked on it.
+func TestRegisterEdgePendingIsIdempotent(t *testing.T) {
+ s := &Server{}
+ s.registerEdgePending("sb-dup")
+ done := make(chan error, 1)
+ go func() { done <- s.waitEdgeFinalize(context.Background(), "sb-dup") }()
+ time.Sleep(20 * time.Millisecond)
+
+ s.registerEdgePending("sb-dup") // second reserve of the same id
+ s.resolveEdgePending("sb-dup", nil)
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("waiter got %v, want nil", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("re-registering stranded the existing waiter")
+ }
+}
diff --git a/internal/api/microvm_backend.go b/internal/api/microvm_backend.go
index 25bb70ad..791030b2 100644
--- a/internal/api/microvm_backend.go
+++ b/internal/api/microvm_backend.go
@@ -85,6 +85,12 @@ type microvmBackend struct {
// reserve time, so an expiring reservation can drop that binding. See
// edge_claim_microvm.go for why the binding happens that early.
edgeReserved edgeReservedMap
+
+ // onReservationLost tells the control plane that a reserved sandbox id will
+ // never finalize, so anything parked waiting for that claim is released
+ // with the failure instead of waiting the window out. Set by the Server at
+ // wiring time; nil in tests, where nobody is waiting.
+ onReservationLost func(sandboxID string, err error)
}
// microvmEnabled reports whether this cell serves MicroVM-backed sandboxes.
diff --git a/internal/api/microvm_direct.go b/internal/api/microvm_direct.go
new file mode 100644
index 00000000..dc39b04c
--- /dev/null
+++ b/internal/api/microvm_direct.go
@@ -0,0 +1,39 @@
+package api
+
+import (
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/awsvm"
+)
+
+// microvm_direct.go — hands the edge what it needs to talk to a MicroVM without
+// going through this process.
+//
+// Every exec today travels edge → (CF tunnel) → control plane → agent tunnel →
+// guest, and the control plane leg alone is the majority of time-to-first-exec
+// because the CP lives in a different region from the boxes. Nothing about that
+// leg is load-bearing: a MicroVM's endpoint is a public TLS host and its
+// credential is a plain, port-scoped header token, so the edge can hold the
+// agent tunnel itself and the CP drops out of the data path entirely.
+//
+// This route exists to measure that claim before building on it. It is
+// read-only and mints nothing the CP does not already mint for its own dials.
+
+// microvmDirectInfo handles GET /internal/microvm/direct/:id.
+func (s *Server) microvmDirectInfo(c echo.Context) error {
+ if s.microvm == nil || s.microvm.manager == nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "microvm backend not enabled on this cell"})
+ }
+ endpoint, token, port, err := s.microvm.manager.DirectInfo(c.Request().Context(), c.Param("id"))
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusOK, map[string]any{
+ "endpoint": endpoint,
+ "token": token,
+ "port": port,
+ "path": awsvm.AgentTunnelPath,
+ })
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index c3276a4f..4ebdee7e 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -67,6 +67,7 @@ type Server struct {
sandboxDomain string // base domain for sandbox subdomains
cfClient *cloudflare.Client // nil if Cloudflare not configured
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
+ pendingEdgeClaims sync.Map // map[sandboxID]*edgePending — edge-claimed boxes awaiting claim-finalize
mountSvc *mounts.Service // shared with worker.HTTPServer; nil disables the mounts API
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
wsGateway *wsgateway.Gateway // nil disables the broker; WS data-plane routes fall back to sandboxAPIProxy
@@ -236,7 +237,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.sandboxAPIProxy.SetWaitForReady(func(ctx context.Context, sandboxID string) error {
val, ok := s.pendingCreates.Load(sandboxID)
if !ok {
- return nil // not a pending create — proceed normally
+ // Not an async create. It may still be an edge claim whose
+ // finalize hasn't landed — the other way a caller can hold
+ // a sandbox id this process cannot yet look up.
+ return s.waitEdgeFinalize(ctx, sandboxID)
}
pending := val.(*pendingCreate)
select {
@@ -358,6 +362,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
internal.POST("/pool/edge-reserve", s.edgeReservePool)
internal.POST("/pool/edge-release", s.edgeReleasePool)
internal.POST("/sandboxes/claim-finalize", s.claimFinalize)
+ // 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)
// Cross-cell paused-cap enforcement: the edge (which has the org-global
// view via D1) calls this to promote a specific paused sandbox to deep
// hibernation, reclaiming its worker RAM.
@@ -808,6 +815,9 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
log.Fatalf("opensandbox: microvm backend: %v", err)
} else if mvm != nil {
s.microvm = mvm
+ // A reservation that dies unclaimed must wake anything parked on its
+ // finalize — see THE FINALIZE RACE in edge_claim.go.
+ mvm.onReservationLost = s.resolveEdgePending
// Registering it is what makes every claim/route site find it. Before
// this the sites each hardcoded their own check, and any new one
// silently defaulted to the worker path.
diff --git a/internal/awsvm/agent.go b/internal/awsvm/agent.go
index 0ec00ff6..15553814 100644
--- a/internal/awsvm/agent.go
+++ b/internal/awsvm/agent.go
@@ -64,6 +64,10 @@ type agentConn struct {
// cmd/microvm-hooks.
const agentTunnelPath = "/osb/agent-grpc"
+// AgentTunnelPath exposes the tunnel path to callers outside this package that
+// dial the same endpoint themselves — see Manager.DirectInfo.
+const AgentTunnelPath = agentTunnelPath
+
// dialAgent opens a gRPC channel to the agent behind a MicroVM endpoint.
//
// The channel runs over a WebSocket rather than straight HTTP/2, because
@@ -324,3 +328,109 @@ func (p *agentPool) closeAll() {
_ = c.Close()
}
}
+
+// --- keepalive ---
+//
+// Pool boxes are idle by definition: they exist so that nobody has to wait for
+// one. But AWS SUSPENDS an idle MicroVM, and the next payload pays the resume —
+// measured at ~1s on the first exec against a box that has been sitting, and
+// paid identically by the control-plane path and by the edge's direct path,
+// because it is the platform waking the VM rather than anything in our
+// transport. An overnight gap suspends the entire pool.
+//
+// A Ping is real guest traffic, so it resets the idle timer in a way that a
+// merely-open connection does not. It also keeps the AWS proxy's own connection
+// to the guest port attached, which is the OTHER thing a first payload pays for
+// (the WebSocket 101 comes from the proxy; the proxy only dials the guest when
+// payload first arrives).
+
+const (
+ pingConcurrency = 16
+ pingTimeout = 5 * time.Second
+)
+
+func (a *agentConn) ping(ctx context.Context) error {
+ if a == nil || a.client == nil {
+ return nil
+ }
+ _, err := a.client.Ping(ctx, &pb.PingRequest{})
+ return err
+}
+
+// warmShellTimeout bounds the manufacture-time warm-up. Generous, because it
+// runs on a box nobody is waiting for and the whole point is to absorb a slow
+// first shell rather than skip it.
+const warmShellTimeout = 20 * time.Second
+
+// warmShell runs one throwaway command so the customer's first exec doesn't
+// have to be the one that pays for a cold box.
+//
+// Every exec arrives as `/bin/sh -lc <cmd>`, and on a box that has never run one
+// the login shell has to fault in the shell itself and source the whole profile
+// chain. Measured on dev across 6 fresh boxes: the FIRST exec costs 928ms median
+// even when the command is `true`, while the second is 143ms — and `node -v`
+// against a warm shell is 144ms, indistinguishable. So the ~800ms is entirely
+// first-shell startup, not the command, and it is paid exactly once per box.
+//
+// Paying it here means it lands on a pool box during manufacture instead of on
+// a customer's first command. `node --version` is folded in because it is the
+// default template's runtime and costs another ~100ms cold; the `|| true` keeps
+// this correct on an image without node, where warming the shell is still the
+// point.
+func (a *agentConn) warmShell(ctx context.Context) error {
+ if a == nil || a.client == nil {
+ return nil
+ }
+ _, err := a.client.Exec(ctx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-lc", "node --version >/dev/null 2>&1 || true"},
+ TimeoutSeconds: int32(warmShellTimeout / time.Second),
+ })
+ return err
+}
+
+// pingAll pings every channel, bounded so a large pool cannot open hundreds of
+// concurrent RPCs on a maintenance tick. Failures are counted, not returned: a
+// box that does not answer is the tick's problem to report, not to fix.
+func pingAll(ctx context.Context, conns []*agentConn) (ok, failed int) {
+ if len(conns) == 0 {
+ return 0, 0
+ }
+ sem := make(chan struct{}, pingConcurrency)
+ var mu sync.Mutex
+ var wg sync.WaitGroup
+ for _, c := range conns {
+ wg.Add(1)
+ go func(c *agentConn) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+ pctx, cancel := context.WithTimeout(ctx, pingTimeout)
+ defer cancel()
+ err := c.ping(pctx)
+ mu.Lock()
+ if err != nil {
+ failed++
+ } else {
+ ok++
+ }
+ mu.Unlock()
+ }(c)
+ }
+ wg.Wait()
+ return ok, failed
+}
+
+// pingTracked pings the channels held for the given sandbox ids (edge
+// reservations, which are the boxes customers actually claim).
+func (p *agentPool) pingTracked(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed int) {
+ p.mu.Lock()
+ conns := make([]*agentConn, 0, len(sandboxIDs))
+ for id := range sandboxIDs {
+ if c, found := p.conns[id]; found && c.conn != nil {
+ conns = append(conns, c)
+ }
+ }
+ p.mu.Unlock()
+ return pingAll(ctx, conns)
+}
diff --git a/internal/awsvm/manager.go b/internal/awsvm/manager.go
index 6dd1780c..d28eef0f 100644
--- a/internal/awsvm/manager.go
+++ b/internal/awsvm/manager.go
@@ -938,3 +938,31 @@ func (m *Manager) Forget(sandboxID string) {
m.mu.Unlock()
m.agents.drop(sandboxID)
}
+
+// DirectInfo returns everything a caller OUTSIDE this process needs to reach a
+// sandbox's agent itself: the MicroVM's public endpoint, a proxy auth token,
+// and the guest port that token is scoped to.
+//
+// This is the seam for taking the control plane out of the exec data path. The
+// endpoint is a public TLS host and the token is a plain header credential — the
+// same one dialAgent presents on the WebSocket upgrade — so a caller that
+// speaks the tunnel protocol gets an identical channel without relaying through
+// here. Tokens are cached and port-scoped by AuthToken, so this is cheap to call
+// and cannot widen access beyond the agent port.
+func (m *Manager) DirectInfo(ctx context.Context, sandboxID string) (endpoint, token string, port int32, err error) {
+ e, err := m.lookup(sandboxID)
+ if err != nil {
+ return "", "", 0, err
+ }
+ tok, err := m.client.AuthToken(ctx, e.microvmID)
+ if err != nil {
+ return "", "", 0, err
+ }
+ return e.endpoint, tok, m.client.Config().AgentPort, nil
+}
+
+// PingAgents keeps the given sandboxes' boxes out of AWS's idle policy. See the
+// keepalive block in agent.go for why an open connection is not enough.
+func (m *Manager) PingAgents(ctx context.Context, sandboxIDs map[string]struct{}) (ok, failed int) {
+ return m.agents.pingTracked(ctx, sandboxIDs)
+}
diff --git a/internal/awsvm/pool.go b/internal/awsvm/pool.go
index 00835433..b24cace3 100644
--- a/internal/awsvm/pool.go
+++ b/internal/awsvm/pool.go
@@ -244,6 +244,11 @@ type Pool struct {
inflight int
}
+// AgentPort is the guest port this pool's tokens are scoped to. Callers handing
+// a box's reach-info to something outside this process need it, because the
+// credential is only valid for that one port.
+func (p *Pool) AgentPort() int32 { return p.client.Config().AgentPort }
+
func NewPool(client *Client, cfg PoolConfig) *Pool {
cfg.applyDefaults()
p := &Pool{client: client, cfg: cfg}
@@ -643,6 +648,15 @@ func (p *Pool) launchOne(ctx context.Context) error {
log.Printf("awsvm: pool pre-dial %s failed, box still usable cold: %v", box.ID, derr)
} else {
agent = a
+ // Spend the box's first-shell cost here rather than on the
+ // customer's first command — see agentConn.warmShell. Best effort:
+ // a box that fails to warm is still a perfectly good box, it just
+ // starts cold like it did before.
+ warmCtx, cancelWarm := context.WithTimeout(runCtx, warmShellTimeout)
+ if werr := agent.warmShell(warmCtx); werr != nil {
+ log.Printf("awsvm: pool warm-up exec %s failed, box starts cold: %v", box.ID, werr)
+ }
+ cancelWarm()
}
}
@@ -765,6 +779,14 @@ func (p *Pool) warmTunnels(ctx context.Context) {
}
p.mu.Unlock()
+ // Keepalive: touch every stocked box so it never goes idle long enough for
+ // AWS to suspend it. This is the expensive-on-purpose half of the trade —
+ // an unsuspended box bills compute while it waits — and it is what keeps a
+ // claim's first exec off the ~1s resume path.
+ if ok, failed := pingAll(ctx, conns); ok+failed > 0 {
+ log.Printf("awsvm: pool keepalive pinged %d stocked box(es) (%d failed)", ok, failed)
+ }
+
if p.preDial != nil {
for _, e := range missing {
dialCtx, cancel := context.WithTimeout(ctx, p.cfg.PreDialTimeout)