An open-source, faster Devin alternative
TypeScript
perf(edge,sdk): hold the pre-dialed agent connection instead of closing it; prewarm 48
Brian Reardonc8ebe6766c77
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 78ff52a2..713f9075 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1630,7 +1630,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro// Net for the benchmark, which scores create+exec together, this is a// win. It stays in waitUntil and swallows its errors, so the worst case// is the first exec dialling cold exactly as it does today.- if (routeEntry.reach) ctx.waitUntil(warmEdgeTunnel(routeEntry.reach));+ if (routeEntry.reach) ctx.waitUntil(warmEdgeTunnel(box.id, routeEntry.reach));//// 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@@ -2017,13 +2017,43 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContex}const reachMs = Date.now() - tReach;+ // heldHit is reported as a mark so the hit RATE is observable, not just the+ // latency it produces — a warm-connection optimisation that silently stops+ // hitting looks exactly like one that never worked.+ let heldHit = "miss";const run = async (r: MvmReach): Promise<Response> => {+ const held = takeHeldAgent(id);+ if (held) {+ try {+ const res = await held.unary("/agent.SandboxAgent/Exec", encodeExecRequest(execReq), MVM_EXEC_TIMEOUT_MS);+ heldHit = "hit";+ holdAgent(id, held); // keep it for this box's next exec+ return json(decodeExecResponse(res));+ } catch {+ // A held connection the proxy has since dropped fails here and only+ // here. Discard it and dial fresh rather than failing the exec.+ try {+ held.close();+ } catch {+ /* already gone */+ }+ heldHit = "stale";+ }+ }const conn = await dialAgent(r);try {const res = await conn.unary("/agent.SandboxAgent/Exec", encodeExecRequest(execReq), MVM_EXEC_TIMEOUT_MS);+ // Hold only on success: a connection whose exec threw is exactly the one+ // not to hand to the next caller. Bounded by HELD_MAX / HELD_TTL_MS.+ holdAgent(id, conn);return json(decodeExecResponse(res));- } finally {- conn.close();+ } catch (e) {+ try {+ conn.close();+ } catch {+ /* already gone */+ }+ throw e;}};@@ -2052,7 +2082,7 @@ async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContexstatus: 200,headers: {"content-type": "application/json",- "server-timing": `auth;dur=${authMs}, pol;dur=${polMs}, route;dur=${routeMs}, reach;dur=${reachMs}, exec;dur=${execMs}, up;dur=${lastUpgradeMs}, ready;dur=${lastReadyMs}`,+ "server-timing": `auth;dur=${authMs}, pol;dur=${polMs}, route;dur=${routeMs}, reach;dur=${reachMs}, exec;dur=${execMs}, up;dur=${lastUpgradeMs}, ready;dur=${lastReadyMs}, held;desc=${heldHit}`,},});} catch (e) {@@ -2076,10 +2106,68 @@ const MVM_EXEC_TIMEOUT_MS = 10_000;* path, and a box that refuses now simply means the first exec pays what it* would have paid anyway.*/-async function warmEdgeTunnel(r: MvmReach): Promise<void> {+// Held agent connections, keyed by sandbox id.+//+// warmEdgeTunnel used to dial and immediately close(), which paid the handshake+// at create time and then threw away the only thing that made it worth paying.+// Measured on prod twice: ~20% of a burst-100 arrive with an unpaid first touch+// costing ~300ms, and the SAME box answers its second exec in ~50ms. The CP+// pings all 144 reserved boxes over its own gRPC channels (0 failed), so that+// warmth demonstrably does not transfer — the cost is bound to the edge's own+// connection. Holding it is therefore the whole fix.+//+// Bounded on purpose: an unclosed connection per create under burst is a leak.+const HELD_MAX = 256;+const HELD_TTL_MS = 60_000;+const heldAgents = new Map<string, { conn: H2Grpc; atMs: number }>();++// takeHeldAgent removes and returns a usable connection. Ownership transfers to+// the caller — a connection must never be handed to two concurrent execs.+function takeHeldAgent(id: string): H2Grpc | null {+ const e = heldAgents.get(id);+ if (!e) return null;+ heldAgents.delete(id);+ if (Date.now() - e.atMs > HELD_TTL_MS) {+ try {+ e.conn.close();+ } catch {+ /* already gone */+ }+ return null;+ }+ return e.conn;+}++function holdAgent(id: string, conn: H2Grpc): void {+ if (heldAgents.has(id)) {+ // Someone else re-held first; keep theirs and drop this one rather than+ // leaking the replaced connection.+ try {+ conn.close();+ } catch {+ /* already gone */+ }+ return;+ }+ // Map iteration is insertion-ordered, so the first key is the oldest.+ while (heldAgents.size >= HELD_MAX) {+ const oldest = heldAgents.keys().next().value as string | undefined;+ if (oldest === undefined) break;+ const victim = heldAgents.get(oldest);+ heldAgents.delete(oldest);+ try {+ victim?.conn.close();+ } catch {+ /* already gone */+ }+ }+ heldAgents.set(id, { conn, atMs: Date.now() });+}++async function warmEdgeTunnel(id: string, r: MvmReach): Promise<void> {try {const conn = await dialAgent(r);- conn.close();+ holdAgent(id, conn);} catch {/* first exec dials cold, exactly as it would have */}diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex c3e4d149..4e1de98d 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.15.3",+ "version": "0.15.4","description": "TypeScript SDK for OpenComputer - cloud sandbox platform","type": "module","main": "dist/index.js",diff --git a/sdks/typescript/src/http2.ts b/sdks/typescript/src/http2.tsindex 62537265..8714d076 100644--- a/sdks/typescript/src/http2.ts+++ b/sdks/typescript/src/http2.ts@@ -33,19 +33,28 @@ let configurePromise: Promise<void> | null = null;// How many connections to hold open, and how often to keep them alive.//-// OFF by default. The original default was 100 — sized to a 100-way burst on-// the theory that anything less just warms fewer connections. Measured against-// prod from an IAD runner (4 vCPU), the opposite is true: opening 100 TLS-// connections while 100 creates are already in flight starves the event loop-// and every request unblocks together at the end.+// 48. Swept against prod from an IAD runner (4 vCPU) at burst-100, TTI p50://-// prewarm=100 wall 24,040ms create p50 994ms exec p50 22,991ms TTI p50 23,990ms-// prewarm=0 wall 1,203ms create p50 573ms exec p50 107ms TTI p50 709ms+// prewarm=100 23,990ms opening 100 TLS connections while 100 creates are+// in flight starves the event loop; everything+// unblocks together at the end+// prewarm=0 624ms the opposite failure — undici marks an h2 session+// busy per in-flight POST, so 100 concurrent creates+// queue behind each other on one connection+// prewarm=32 338ms+// prewarm=48 301ms / 328ms (two runs)+// prewarm=64 312ms//-// A 34x regression in exactly the shape it was written to help, so it does not-// get to be the default. Opt in with OPENCOMPUTER_PREWARM_CONNECTIONS=N once a-// value has been measured to beat 0 on the workload in question.-const DEFAULT_PREWARM = 0;+// The curve is flat between 32 and 64 — run-to-run variance on TTI p50 is ~27ms,+// so 48 vs 64 is not a real difference — and turns back up past that because+// establishing the pool starts costing more than it saves (424ms to open 64+// versus 153ms for 48, paid inside the measured window). 48 sits at the bottom+// with margin on both sides.+//+// Note the 100 figure is not a typo: this was shipped as the default on the+// theory that a smaller pool merely warms fewer connections. It is worth 34x in+// the exact shape it was written for.+const DEFAULT_PREWARM = 48;const KEEPALIVE_INTERVAL_MS = 30_000;// Above undici's 4s default so an idle connection survives between phases of a// workload; still far below any sane server-side idle close.