An open-source, faster Devin alternative
TypeScript
fix(edge): stop GET /sandboxes/:id 404ing during the finalize window, and keep the pool warm between bursts
Brian Reardona2498026bf7e
diff --git a/benchmarks/tti/bench.mjs b/benchmarks/tti/bench.mjsindex 6962c7b7..d33ff499 100644--- a/benchmarks/tti/bench.mjs+++ b/benchmarks/tti/bench.mjs@@ -314,6 +314,50 @@ for (const m of toRun) {// measurement of the breakage instead.const REQUIRE_POOL = Number(flag('require-pool', 'REQUIRE_POOL', '0'));+/**+ * Locate an installed package's root and version.+ *+ * Deliberately NOT `require('<pkg>/package.json')`: both of these packages ship+ * an "exports" map that does not expose ./package.json, so that throws+ * ERR_PACKAGE_PATH_NOT_EXPORTED even when the package is installed and fine.+ * Reading it that way is how the version assert silently turned into "unknown"+ * and stopped asserting anything. Resolve the entry point instead — which the+ * exports map does cover — then walk up to the package root.+ */+async function pkgInfo(name) {+ const fs = await import('node:fs');+ const path = await import('node:path');+ const { fileURLToPath } = await import('node:url');++ // Walk node_modules by hand rather than going through the resolver. Both+ // packages here defeat the resolver in a different way: the adapter's+ // "exports" map omits ./package.json (ERR_PACKAGE_PATH_NOT_EXPORTED), and the+ // SDK defines no "exports" main at all (ERR_PACKAGE_PATH_NOT_EXPORTED again,+ // from the other direction). Neither is a real problem with the install, but+ // both turn a version assert into "unknown" — which is how this check quietly+ // stopped checking anything. The directory layout is not ambiguous, so use it.+ let dir = path.dirname(fileURLToPath(import.meta.url));+ for (let i = 0; i < 8; i++) {+ const root = path.join(dir, 'node_modules', ...name.split('/'));+ const p = path.join(root, 'package.json');+ if (fs.existsSync(p)) {+ const j = JSON.parse(fs.readFileSync(p, 'utf8'));+ return { version: j.version, dir: root, fs, path };+ }+ const up = path.dirname(dir);+ if (up === dir) break;+ dir = up;+ }+ throw new Error(`${name} not found in any node_modules above ${path.dirname(fileURLToPath(import.meta.url))}`);+}++// The SDK build this bench is required to exercise. Pinned rather than merely+// reported: the adapter's own dependency range is ^0.12.4, which on a 0.x+// version resolves below 0.13, so a plain install quietly runs a client that+// predates every change being measured. package.json forces the resolution and+// this asserts the force actually took.+const REQUIRE_SDK = flag('require-sdk', 'REQUIRE_SDK', '0.15.6');+async function preflight() {const problems = [];@@ -321,32 +365,36 @@ async function preflight() {// node_modules measures something nobody else will ever run.let adapterVersion = 'unknown';try {- const { createRequire } = await import('node:module');- const req = createRequire(import.meta.url);- adapterVersion = req('@computesdk/opencomputer/package.json').version;- } catch {- problems.push('cannot resolve @computesdk/opencomputer — is node_modules installed?');+ adapterVersion = (await pkgInfo('@computesdk/opencomputer')).version;+ } catch (e) {+ problems.push(`cannot resolve @computesdk/opencomputer (${e.message}) — run npm install`);}- // 2. Connection prewarm. Without it the first create in a burst pays TLS +- // HTTP/2 setup and the whole distribution shifts; with it the cost is paid- // at import. Which of the two we are measuring must never be a surprise —- // a silently-absent prewarm was worth hundreds of ms and went unnoticed- // for a month.- let prewarm = 'absent';+ // 2. The SDK underneath it, and its connection prewarm. Without prewarm the+ // first create in a burst pays TLS + HTTP/2 setup and the whole+ // distribution shifts; with it the cost is paid at import. Which of the two+ // we are measuring must never be a surprise — a silently-absent prewarm was+ // worth hundreds of ms and went unnoticed for a month.+ let sdkVersion = 'unknown';+ let prewarm = 'unknown';try {- const { createRequire } = await import('node:module');- const req = createRequire(import.meta.url);- const fs = await import('node:fs');- const path = await import('node:path');- const sdkPkg = req.resolve('@opencomputer/sdk/package.json');- const dist = path.join(path.dirname(sdkPkg), 'dist');- const hit = ['sandbox.js', 'http2.js'].every(- (f) => fs.existsSync(path.join(dist, f)) && fs.readFileSync(path.join(dist, f), 'utf8').includes('prewarmConnections'),- );+ const { version, dir, fs, path } = await pkgInfo('@opencomputer/sdk');+ sdkVersion = version;+ const hit = ['sandbox.js', 'http2.js'].every((f) => {+ const p = path.join(dir, 'dist', f);+ return fs.existsSync(p) && fs.readFileSync(p, 'utf8').includes('prewarmConnections');+ });prewarm = hit ? 'present' : 'absent';- } catch {- prewarm = 'unknown';+ if (REQUIRE_SDK && REQUIRE_SDK !== '0' && version !== REQUIRE_SDK) {+ problems.push(+ `@opencomputer/sdk is ${version}, required ${REQUIRE_SDK} — the adapter's ^0.12.4 range pins it below 0.13 unless package.json overrides it. Delete node_modules and npm install.`,+ );+ }+ if (prewarm !== 'present') {+ problems.push(`@opencomputer/sdk ${version} has no prewarmConnections — this is not the client we ship`);+ }+ } catch (e) {+ problems.push(`cannot resolve @opencomputer/sdk (${e.message}) — run npm install`);}// 3. Pool depth. This is the one that invalidated an entire measurement@@ -369,12 +417,9 @@ async function preflight() {}console.log(- `preflight: adapter=${adapterVersion} sdk-prewarm=${prewarm}` ++ `preflight: adapter=${adapterVersion} sdk=${sdkVersion} prewarm=${prewarm}` +(poolDepth !== null ? ` pool-reserved=${poolDepth}` : ' pool-check=skipped'),);- if (prewarm !== 'present') {- console.log(` NOTE: SDK connection prewarm is ${prewarm} — create p50 will include per-connection setup.`);- }if (REQUIRE_POOL <= 0) {console.log(' NOTE: pool-depth check skipped. Set REQUIRE_POOL=144 to refuse to run against a depleted pool.');}diff --git a/benchmarks/tti/package-lock.json b/benchmarks/tti/package-lock.jsonindex c62be639..fc2c22c2 100644--- a/benchmarks/tti/package-lock.json+++ b/benchmarks/tti/package-lock.json@@ -6,8 +6,8 @@"": {"name": "opencomputer-tti-bench","dependencies": {- "@computesdk/opencomputer": "^1.0.1",- "computesdk": "^4.1.4"+ "@computesdk/opencomputer": "latest",+ "computesdk": "latest"}},"node_modules/@computesdk/cmd": {@@ -17,20 +17,20 @@"license": "MIT"},"node_modules/@computesdk/opencomputer": {- "version": "1.0.1",- "resolved": "https://registry.npmjs.org/@computesdk/opencomputer/-/opencomputer-1.0.1.tgz",- "integrity": "sha512-430gMhj2kFbxZZvcCINJFgTBroG60VIOa67CQuGK5vbTwK3babHdOLiND5JK6P60m5QNwWw1jnPaq4PQLWHfnA==",+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/@computesdk/opencomputer/-/opencomputer-1.0.3.tgz",+ "integrity": "sha512-Y34k/HLwDmD46gY2XD1un0WChV2qriL1OHeU5ojongqWsJ3xDXdAC+26tMA3kjJfVg0NWJ4BLkHXLxiiCFsgAg==","license": "MIT","dependencies": {- "@computesdk/provider": "2.1.4",- "@opencomputer/sdk": "^0.12.4",+ "@computesdk/provider": "2.1.5",+ "@opencomputer/sdk": "latest","computesdk": "4.1.4"}},"node_modules/@computesdk/provider": {- "version": "2.1.4",- "resolved": "https://registry.npmjs.org/@computesdk/provider/-/provider-2.1.4.tgz",- "integrity": "sha512-abTZS8kpif4QpLZ7Jzo6hmlje2b3YB4VRC8hVkrb/tKXwt0QcU7Nao7tM1phRru0HxVrfHycb/vZtdJSlNFGeA==",+ "version": "2.1.5",+ "resolved": "https://registry.npmjs.org/@computesdk/provider/-/provider-2.1.5.tgz",+ "integrity": "sha512-y1vmqZui7pQDzfCrZErUmNi6Ny7x76p8sz4J1iPl+ueuLX/teysyrrng6B3OZCiyrknzB4AtLXlDkzWmNnP8DA==","license": "MIT","dependencies": {"@computesdk/cmd": "0.4.1",@@ -39,10 +39,13 @@}},"node_modules/@opencomputer/sdk": {- "version": "0.12.4",- "resolved": "https://registry.npmjs.org/@opencomputer/sdk/-/sdk-0.12.4.tgz",- "integrity": "sha512-/BpMJMHxskkSI2GUri27xej9eXMrjlvu85NxIz/luiEKJ6lJKFF3w6uTY0IweZlB50SqIt7/dsC5ksZFXkyPzA==",+ "version": "0.15.6",+ "resolved": "https://registry.npmjs.org/@opencomputer/sdk/-/sdk-0.15.6.tgz",+ "integrity": "sha512-4FLK2Mjz1iqxWSloPXbDXoJLKnEk3rI1jcojzAEpAoR2hO8S7CjjL8yck0GHaaQjn7vob80doMFLWVUMsHzKgg==","license": "MIT",+ "dependencies": {+ "undici": "^6.0.0 || ^7.0.0"+ },"engines": {"node": ">=18"}@@ -69,6 +72,15 @@"engines": {"node": ">=18.0.0"}+ },+ "node_modules/undici": {+ "version": "7.29.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz",+ "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==",+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }}}}diff --git a/benchmarks/tti/package.json b/benchmarks/tti/package.jsonindex 0f246b68..b7ef4f0e 100644--- a/benchmarks/tti/package.json+++ b/benchmarks/tti/package.json@@ -10,7 +10,11 @@"bench:burst": "node bench.mjs --mode burst"},"dependencies": {- "@computesdk/opencomputer": "^1.0.1",- "computesdk": "^4.1.4"+ "@computesdk/opencomputer": "latest",+ "computesdk": "latest"+ },+ "//overrides": "The adapter's own dependency range is ^0.12.4, which on a 0.x version means <0.13 — so a plain install pins the SDK to 0.12.x no matter what has been published since. This bench exists to measure the client we actually ship, so the resolution is forced to latest here. Without it the bench and the raw harness run different SDKs and their numbers are not comparable.",+ "overrides": {+ "@opencomputer/sdk": "latest"}}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 6c4852bb..a1340799 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1389,6 +1389,56 @@ async function claimPoolBox(return null;}+// runPoolKeepWarm touches every shard of every active cell so the stock never+// idle-decommissions between bursts.+//+// The shard's own idle policy is right for a shard nobody uses and wrong for the+// traffic this pool actually serves. Stock is released after+// IDLE_DECOMMISSION_MS (30 min) and the alarm stops entirely after+// WARM_MAX_IDLE_MS (6h). But the workloads that care about create latency are+// exactly the ones that arrive after a long quiet period AND arrive all at once:+// a weekly benchmark, a nightly CI fan-out, an hourly cron. Each of those lands+// on a shard set that has been fully cold for far longer than six hours, so all+// N concurrent creates miss every shard together and fall through to+// control-plane cold launches paced by the RunMicrovm quota — the exact 25s tail+// the pool exists to prevent. The pool was being handed back precisely when it+// was about to be needed.+//+// This creates NOTHING. It refreshes the idle clock and re-arms the alarm; the+// alarm's ordinary restock does the reserving. That distinction is the whole+// design: a keep-warm that created sandboxes to stay warm would leak a box every+// tick forever, which is worse than the problem.+//+// Cost is one DO wake per shard per cron tick (8 shards × 1 cell = 8 wakes / 5+// min). Failures are logged and swallowed: a cron that throws would take the+// other scheduled jobs down with it, and a missed tick just means the next one+// does the work.+async function runPoolKeepWarm(env: Env): Promise<void> {+ const cells = await listActiveCells(env);+ if (cells.length === 0) return;+ let ok = 0;+ let failed = 0;+ await Promise.all(+ cells.flatMap((cell) =>+ POOL_STOCK_SHARD_IDS.map(async (shard) => {+ try {+ const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/touch", {+ method: "POST",+ body: JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } }),+ });+ if (r.ok) ok++;+ else failed++;+ } catch {+ failed++;+ }+ }),+ ),+ );+ if (failed > 0) {+ console.error(`pool-keepwarm: touched ${ok} shard(s), ${failed} FAILED — stock may idle-decommission before the next burst`);+ }+}+// edgeClaimEligible: a create qualifies for the edge fast path only when it// asks for exactly what pool boxes are manufactured as — base template at the// default shape (4GB/1cpu/default disk), no guest-side customization (envs,@@ -1874,7 +1924,46 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>).bind(id).first<SandboxRow & { org_id: string }>();- if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);+ if (!row) {+ // No index row yet. That does NOT mean the sandbox doesn't exist: an+ // edge-claimed create answers 201 before its sandboxes_index row is written,+ // because finalize runs off the hot path through FINALIZE_QUEUE. Measured on+ // prod, the row can trail the 201 by more than 2.6s — far longer than the+ // ~1s a client needs to create, exec and then tear down.+ //+ // Returning 404 in that window is not a harmless "not yet". Our own+ // published adapter calls connect() (this route) before kill(), and treats a+ // 404 as "already gone" — so it skips the DELETE and reports success. Every+ // sandbox created and destroyed inside the finalize window therefore LEAKED,+ // holding a pool box until the 8h AWS cap. A burst-100 leaked all 100 and+ // pinned the cell at its box budget, which then degraded every subsequent+ // run. That is the whole reason this fallback exists.+ //+ // Exec and DELETE never had the bug because they resolve through+ // sandboxRouteCache / the colo route entry, both seeded at create. This+ // route just never consulted them. So consult them: a route entry is proof+ // the create happened and carries the owning org, which is all the+ // authorization check needs.+ const route = await resolveSandboxRoute(env, id);+ if (!route || route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);+ const cell = await lookupCell(env, route.cellID);+ // Deliberately minimal, and deliberately NOT invented: only the fields a+ // claim proves. status is "running" because a claimed box is running — the+ // finalize that would tell us otherwise is exactly what hasn't landed yet.+ return json({+ sandboxID: id,+ templateID: "",+ cellID: route.cellID,+ workerID: "",+ status: "running",+ cpuCount: 0,+ memoryMB: 0,+ startedAt: null,+ endAt: null,+ cellEndpoint: cell ? cell.base_url : null,+ });+ }+ if (row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);const cell = await lookupCell(env, row.cell_id);return json({ ...sandboxRowToJSON(row), cellEndpoint: cell ? cell.base_url : null });}@@ -4759,6 +4848,13 @@ export default {ctx.waitUntil(runRetentionSweep(env).catch((err) => console.error("retention: run failed", err)),);+ // Pool keep-warm. Deliberately ABOVE the billing-config early return below:+ // create latency must not depend on whether Autumn happens to be configured,+ // and a cell whose stock has decommissioned serves every create through the+ // slow path. Creates nothing — see runPoolKeepWarm.+ ctx.waitUntil(+ runPoolKeepWarm(env).catch((err) => console.error("pool-keepwarm: run failed", err)),+ );if (!env.AUTUMN_SECRET_KEY) return;ctx.waitUntil(runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),diff --git a/cloudflare-workers/api-edge/src/pool_stock.test.ts b/cloudflare-workers/api-edge/src/pool_stock.test.tsindex cc55d22c..0fcd8b47 100644--- a/cloudflare-workers/api-edge/src/pool_stock.test.ts+++ b/cloudflare-workers/api-edge/src/pool_stock.test.ts@@ -198,6 +198,44 @@ describe("PoolStock", () => {err.mockRestore();});+ it("keep-warm defers decommission without reserving a single box", async () => {+ // Two properties, and the second matters more than the first. A keep-warm+ // that created sandboxes to stay warm would leak one per tick forever —+ // worse than the idle decommission it fixes — so /touch must reserve+ // nothing. What it may do is move the idle clock, which is what stops the+ // shard dumping its stock 30 minutes into a quiet period.+ origin.supply = [+ { sandboxID: "sb-1", workerID: "w-1" },+ { sandboxID: "sb-2", workerID: "w-2" },+ ];+ const { doInstance, state } = makeDO(origin, "2", "1");+ await claimBatch(doInstance, state, ORG_A, 0); // prime+ const reserveCallsAfterPrime = origin.reserved.length;++ // Past the 30-minute idle window, but touched along the way.+ vi.setSystemTime(Date.now() + 25 * 60_000);+ await post(doInstance, "/touch", { cell: CELL });+ await state.settle();+ expect(origin.reserved.length).toBe(reserveCallsAfterPrime); // reserved NOTHING++ // Now run the alarm. The shard is 25 minutes past its last real claim, so+ // without the touch it would be in the decommission branch: release+ // everything and drop to the warm-only tick. With it, the ordinary path+ // runs and the shard tops itself back up.+ //+ // Asserting on "did it restock" rather than "did it release" on purpose:+ // entries also expire on ENTRY_TTL_MS (10 min), so a release here proves+ // nothing about which branch ran, while a restock only happens on the live+ // path. Conflating the two is what made the first version of this test fail.+ origin.supply = [+ { sandboxID: "sb-3", workerID: "w-3" },+ { sandboxID: "sb-4", workerID: "w-4" },+ ];+ await doInstance.alarm();+ await state.settle();+ expect(origin.reserved.length).toBeGreaterThan(reserveCallsAfterPrime);+ });+it("hands a box out exactly once", async () => {origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];const { doInstance, state } = makeDO(origin);diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.tsindex f4bf4bd3..e5d13642 100644--- a/cloudflare-workers/api-edge/src/pool_stock.ts+++ b/cloudflare-workers/api-edge/src/pool_stock.ts@@ -295,6 +295,32 @@ export class PoolStock {if (req.method === "GET" && url.pathname === "/status") {return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });}+ // Keep-warm touch: refresh the idle clock and make sure the alarm is armed,+ // WITHOUT handing out a box.+ //+ // A shard decommissions its whole stock after IDLE_DECOMMISSION_MS and stops+ // ticking entirely after WARM_MAX_IDLE_MS, which is correct for a shard+ // nobody is using but wrong for the traffic pattern this pool actually+ // serves. The benchmark that grades us runs WEEKLY; a CI tenant runs nightly+ // and a cron tenant hourly. All of them arrive after the shard has gone+ // fully cold, and all of them arrive as a BURST — so the first hundred+ // creates race one empty shard set, miss all eight, and fall through to+ // control-plane cold launches paced by the RunMicrovm quota. The pool exists+ // precisely to make that not happen, and idle decommission was handing back+ // the stock that would have prevented it.+ //+ // Touching from the cron keeps lastClaim inside the idle window, so stock+ // stays at target between visits. It reserves nothing on its own — the+ // alarm's normal restock does that — so a shard that has genuinely gone+ // unused costs one DO wake per cron tick and nothing else.+ if (req.method === "POST" && url.pathname === "/touch") {+ const body = (await req.json().catch(() => ({}))) as { cell?: { cellID: string; baseURL: string } };+ if (body.cell?.cellID) this.cell = body.cell;+ this.lastClaimMs = Date.now();+ await this.state.storage.put("lastClaim", this.lastClaimMs);+ await this.ensureAlarm();+ return Response.json({ stock: this.stock.length, target: this.targetStock, cell: this.cell?.cellID ?? null });+ }// Placement probe. A DO pins to a colo at first touch, permanently, and// locationHint only picks a REGION — four generations of shards were armed// from an in-metro client and still scattered across five colos inside