An open-source, faster Devin alternative
TypeScript
bring back 608 basically since we haven't tested bleeding edge and reconfiguring
Brian Reardonf25be7735966
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 2a29e2d4..e24858f8 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -233,11 +233,35 @@ function hmacSignKey(secret: string): Promise<CryptoKey> {return key;}-// NOTE: the sandbox-scoped JWT that the create response carries is now minted in-// the PoolStock DO (mintSandboxTokenDO), once per batch rather than once per-// create — see the magazine below. It stays byte-compatible with Go's-// auth.IssueSandboxToken (same secret, iss="opensandbox", same claim names, 24h-// TTL), so cells/workers validate it identically.+// Mint the sandbox-scoped JWT the create response carries (direct worker+// access: exec WS, PTY, files). Byte-compatible with Go's+// auth.IssueSandboxToken — same shared secret, iss="opensandbox", same claim+// names — so cells/workers validate edge-minted tokens identically to+// CP-minted ones. 24h TTL mirrors the CP.+async function mintSandboxToken(+ secret: string,+ orgID: string,+ sandboxID: string,+ workerID: string,+): Promise<string> {+ const now = Math.floor(Date.now() / 1000);+ const enc = new TextEncoder();+ const header = { alg: "HS256", typ: "JWT" };+ const payload = {+ sub: orgID,+ iat: now,+ exp: now + 24 * 3600,+ iss: "opensandbox",+ org_id: orgID,+ sandbox_id: sandboxID,+ worker_id: workerID,+ };+ const signingInput =+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));+ const key = await hmacSignKey(secret);+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));+ return signingInput + "." + b64url(sig);+}interface Caller {orgID: string;@@ -330,20 +354,8 @@ interface AuthEntry {expiresAt: number | null;cachedAtMs: number;lastBumpMs: number;- // SHA-256 of the key, carried so a cache HIT never has to recompute it- // (bumpLastUsed + the colo tier are keyed by hash).- hash: string;}-// Keyed by the RAW api key, not its hash: hashing costs a crypto.subtle SHA-256-// plus a 32-byte hex encode on EVERY request, and at burst-100 that CPU-// serializes on the isolate's single JS thread — pure overhead when the answer-// is already cached. The raw key is per-isolate memory only (it arrived in this-// request's header); the SHARED colo tier stays hash-keyed, so a key is never-// persisted in plaintext.const authCache = new Map<string, AuthEntry>();-// In-flight auth misses, keyed by raw api key — single-flights concurrent cold-// lookups so a burst doesn't fan out N identical colo/D1 reads (see authenticate).-const authInflight = new Map<string, Promise<Caller | null>>();const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: number }>();// The create concurrency cap counts running sandboxes from the global// sandboxes_index — a per-create D1 read. That index already trails events, so@@ -420,43 +432,17 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {) {return verifyProvisionToken(env.OC_PROVISION_SECRET, apiKey);}+ const hash = await hashAPIKey(apiKey);const nowMs = Date.now();const nowSec = Math.floor(nowMs / 1000);- // Warm path: one Map lookup, ZERO crypto. (The hash is only needed on a miss.)- const cached = authCache.get(apiKey);+ const cached = authCache.get(hash);if (cached && nowMs - cached.cachedAtMs < AUTH_TTL_MS) {if (cached.expiresAt && cached.expiresAt < nowSec) return null;- bumpLastUsed(env, cached.hash, cached, nowMs);+ bumpLastUsed(env, hash, cached, nowMs);return cached.caller;}- // Single-flight the cold miss: a burst-100 of a fresh (uncached) key otherwise- // fires ~100 identical SHA-256s + colo-gets + api_keys D1 reads from this one- // isolate, piling onto the concurrent-subrequest fan-out that gates burst- // creates. Coalesce by key so only the leader hashes and touches colo/D1; the- // rest await it. Deleted on settle, so a revoked key still re-checks within- // AUTH_TTL_MS.- let inflight = authInflight.get(apiKey);- if (!inflight) {- inflight = resolveAuthMiss(env, apiKey);- authInflight.set(apiKey, inflight);- void inflight.finally(() => {- if (authInflight.get(apiKey) === inflight) authInflight.delete(apiKey);- });- }- return inflight;-}--// resolveAuthMiss is the (coalesced) cold path for authenticate(): hash → colo-// tier → D1 → populate both caches. Kept separate so authenticate() can-// single-flight it per key, and so the SHA-256 is paid ONCE per miss instead of-// once per request. Negatives are never cached (a freshly-created key must work-// at once).-async function resolveAuthMiss(env: Env, apiKey: string): Promise<Caller | null> {- const hash = await hashAPIKey(apiKey);- const nowMs = Date.now();- const nowSec = Math.floor(nowMs / 1000);// Colo tier: a fresh box's sub-ops usually land on isolates that never saw// this key. cachedAtMs travels with the entry so the total staleness bound// (revocation lag) stays AUTH_TTL_MS, not colo-TTL + isolate-TTL stacked.@@ -464,8 +450,8 @@ async function resolveAuthMiss(env: Env, apiKey: string): Promise<Caller | null>if (shared && nowMs - shared.cachedAtMs < AUTH_TTL_MS) {if (shared.expiresAt && shared.expiresAt < nowSec) return null;if (authCache.size >= CACHE_MAX) authCache.clear();- const entry: AuthEntry = { caller: shared.caller, expiresAt: shared.expiresAt, cachedAtMs: shared.cachedAtMs, lastBumpMs: 0, hash };- authCache.set(apiKey, entry);+ const entry: AuthEntry = { caller: shared.caller, expiresAt: shared.expiresAt, cachedAtMs: shared.cachedAtMs, lastBumpMs: 0 };+ authCache.set(hash, entry);bumpLastUsed(env, hash, entry, nowMs);return shared.caller;}@@ -480,8 +466,8 @@ async function resolveAuthMiss(env: Env, apiKey: string): Promise<Caller | null>const caller: Caller = { orgID: row.org_id, userID: row.created_by };if (authCache.size >= CACHE_MAX) authCache.clear();- const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0, hash };- authCache.set(apiKey, entry);+ const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };+ authCache.set(hash, entry);await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_TTL_MS / 1000);bumpLastUsed(env, hash, entry, nowMs);return caller;@@ -520,53 +506,13 @@ async function listActiveCells(env: Env): Promise<CellRow[]> {return cells;}-// In-flight create-context loads, keyed by org — single-flights concurrent cold-// loads so a burst-100 for one org does ONE org/count/cells load instead of 100-// (see loadCreateContext).-const createCtxInflight = new Map<- string,- Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }>->();--// loadCreateContext is a thin coalescing wrapper over loadCreateContextCold: a-// fully-warm isolate returns immediately (no map churn); otherwise concurrent-// cold loads for the same org share one in-flight load. The concurrency-count-// snapshot is shared across the coalesced creates — no weaker than the existing-// gate, which already reads low under burst (the sandboxes_index count trails-// create events), so a same-instant burst overshoots identically today.-async function loadCreateContext(- env: Env,- orgID: string,- ctx?: ExecutionContext,-): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {- const nowMs = Date.now();- const oc = orgPolicyCache.get(orgID);- const cc = concurrencyCountCache.get(orgID);- if (- oc !== undefined && nowMs - oc.cachedAtMs < ORG_POLICY_TTL_MS &&- cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS &&- activeCellsCache !== null && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS- ) {- return { org: oc.policy, activeCount: cc.count, cells: activeCellsCache.cells };- }- let inflight = createCtxInflight.get(orgID);- if (!inflight) {- inflight = loadCreateContextCold(env, orgID, ctx);- createCtxInflight.set(orgID, inflight);- void inflight.finally(() => {- if (createCtxInflight.get(orgID) === inflight) createCtxInflight.delete(orgID);- });- }- return inflight;-}--// loadCreateContextCold fetches the three org-keyed reads the create hot path-// needs — org policy, running-sandbox count, active-cells list — in a SINGLE D1-// round trip via db.batch(), instead of three sequential awaits. Under a cold-// burst (fresh isolates, caches empty) that collapses ~3×D1-latency into one.-// Each piece still honours + populates its existing per-isolate cache, so warm/+// loadCreateContext fetches the three org-keyed reads the create hot path needs+// — org policy, running-sandbox count, active-cells list — in a SINGLE D1 round+// trip via db.batch(), instead of three sequential awaits. Under a cold burst+// (fresh isolates, caches empty) that collapses ~3×D1-latency into one. Each+// piece still honours + populates its existing per-isolate cache, so warm/// sustained traffic skips D1 entirely and only the cold misses are batched.-async function loadCreateContextCold(+async function loadCreateContext(env: Env,orgID: string,ctx?: ExecutionContext,@@ -1175,211 +1121,6 @@ function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStreturn env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name), { locationHint: "enam" });}-// ----------------------------------------------------------------------------// Magazine: isolate-local inventory of pre-claimed, pre-tokened pool boxes.-//-// Every create used to cost one PoolStock DO subrequest + one HMAC on the create-// isolate. Prod attribution showed the burst-100 gate is isolate admission/CPU-// (create wall ~420ms against ~10ms of server-side claim), so the win is to stop-// doing per-create work at all: one /claim-batch call fetches N boxes WITH their-// tokens already minted in the DO, and the next N-1 creates are pure memory —-// zero subrequests, zero crypto. Classic magazine/thread-local free-list.-//-// Sizing is ADAPTIVE so this never wastes boxes on low traffic: the refill asks-// for exactly as many creates as are currently waiting (clamped to-// MAGAZINE_MAX). A lone create asks for 1 — byte-identical to the old behaviour.-// A 100-way burst asks for MAGAZINE_MAX and serves the rest from memory.-//-// Safety: a magazine is keyed by cell AND org, and its boxes are already tokened-// for that org, so a box can only ever be handed to the org it was minted for —-// no cross-tenant exposure. pop() is atomic w.r.t. other tasks (single-threaded-// JS), so two concurrent creates can never take the same box. The residual cost-// is waste: boxes held by an isolate that gets evicted are stranded until the-// cell's reaper reclaims them, which is why the TTL is short and the batch is-// sized to demand rather than a fixed constant.-interface MagazineBox {- id: string;- workerID: string;- region: string;- sandboxDomain: string;- token: string;- atMs: number;-}-// Must cover a full burst in ONE refill. The refill is single-flighted per-// (cell,org), so a cap below the burst width serializes: with MAX=24 and 100-// concurrent creates, waiters go through ~5 sequential refill rounds and the-// ones that exhaust their 3 attempts fall through to the CP create — the slow-// path (measured ~1.6s at 100-way). Sized to the leaderboard burst width; the-// batch is still demand-sized (`want = waiters`), so a lone create asks for 1.-const MAGAZINE_MAX = 100;-const MAGAZINE_TTL_MS = 60_000;-const magazines = new Map<string, MagazineBox[]>();-const magazineInflight = new Map<string, Promise<void>>();-const magazineWaiters = new Map<string, number>();-// Stock depth reported by the most recent refill (telemetry only).-const magazineLastStock = new Map<string, number>();--// refillMagazine pulls one batch into this isolate's magazine, walking shards the-// same way a single claim does (random start + stride, 3 tries) so a drained or-// unlucky shard falls through instead of failing the create.-async function refillMagazine(- env: Env,- cell: CellRow,- orgID: string,- key: string,- want: number,-): Promise<void> {- // Fan out to every shard in parallel, but RESOLVE ON THE FIRST one that- // returns stock — do not await the slowest of eight.- //- // Measured on dev (N=20, 30-box pool), the two earlier shapes each got half- // of this right. A single-shard claim (`?nomag=1`) is fast per call (min- // 139-197ms) but misses often when that shard is empty (9-14 of 20 served).- // Awaiting all eight shards covered the pool (17 of 20 served) but made the- // FASTEST possible create 258-410ms, because every claim paid for the slowest- // shard. First-responder gives the single-shard latency and the all-shard- // coverage: the caller unblocks on whichever shard answers first, and the- // stragglers still land — they top the magazine up in the background, so- // their boxes serve the next create instead of being wasted.- const per = Math.max(1, Math.ceil(want / POOL_STOCK_SHARDS));- const start = Math.floor(Math.random() * POOL_STOCK_SHARDS);-- // Deposit boxes into the magazine as each shard answers, whenever it answers.- const deposit = (data: { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number } | null): number => {- if (!data) return 0;- if (data.stock !== undefined) magazineLastStock.set(key, data.stock);- const boxes = data.boxes ?? [];- if (boxes.length === 0) return 0;- const arr = magazines.get(key) ?? [];- const at = Date.now();- for (const b of boxes) arr.push({ ...b, atMs: at });- magazines.set(key, arr);- return boxes.length;- };-- const shardCall = async (i: number): Promise<number> => {- const shard = (start + i) % POOL_STOCK_SHARDS;- try {- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {- method: "POST",- body: JSON.stringify({- cell: { cellID: cell.cell_id, baseURL: cell.base_url },- orgID,- count: per,- }),- });- if (!r.ok) return 0;- return deposit((await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number });- } catch {- return 0;- }- };-- // Settle as soon as one shard has produced stock. The losers keep running and- // deposit on their own — they are never awaited by this caller, so a slow or- // empty shard can't hold up the create. shardCall never rejects, so no- // unhandled rejection can escape the un-awaited tail.- const calls = Array.from({ length: POOL_STOCK_SHARDS }, (_, i) => shardCall(i));- await new Promise<void>((resolve) => {- let pending = calls.length;- let settled = false;- const finish = (): void => {- if (settled) return;- settled = true;- resolve();- };- for (const c of calls) {- void c.then((n) => {- if (n > 0) finish(); // first shard with boxes unblocks the caller- if (--pending === 0) finish(); // all shards empty — fall through to CP- });- }- });-}--// claimDirectBox is the CONTROL arm for the magazine A/B (`?nomag=1`): exactly-// one claim-batch(count:1) per request, no isolate-local inventory, no-// single-flight. This is the pre-magazine shape — 100 concurrent creates issue-// 100 parallel DO claims — so the two arms differ only in the batching strategy.-async function claimDirectBox(- env: Env,- cell: CellRow,- orgID: string,-): Promise<{ box: MagazineBox; amortized: boolean; stock: number } | null> {- const body = JSON.stringify({- cell: { cellID: cell.cell_id, baseURL: cell.base_url },- orgID,- count: 1,- });- let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);- const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));- for (let attempt = 0; attempt < 3; attempt++) {- try {- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {- method: "POST",- body,- });- shard = (shard + stride) % POOL_STOCK_SHARDS;- if (!r.ok) continue;- const data = (await r.json()) as { boxes?: Omit<MagazineBox, "atMs">[]; stock?: number };- const b = data.boxes?.[0];- if (!b) continue;- return { box: { ...b, atMs: Date.now() }, amortized: false, stock: data.stock ?? -1 };- } catch {- shard = (shard + stride) % POOL_STOCK_SHARDS;- }- }- return null;-}--// claimMagazineBox returns a ready-to-serve box (token already minted) or null to-// fall through to the CP create. `amortized` reports that this create did NOT-// perform a DO call of its own — it either popped a box already in memory or-// rode someone else's in-flight batch. That ratio IS the fan-out reduction: in a-// burst of N served by one batch, one create pays and N-1 are amortized.-async function claimMagazineBox(- env: Env,- cell: CellRow,- orgID: string,-): Promise<{ box: MagazineBox; amortized: boolean; stock: number } | null> {- const key = `${cell.cell_id}|${orgID}`;- magazineWaiters.set(key, (magazineWaiters.get(key) ?? 0) + 1);- let didRefill = false;- try {- for (let attempt = 0; attempt < 3; attempt++) {- const mag = magazines.get(key);- if (mag && mag.length > 0) {- const box = mag.pop()!;- // Held too long (idle isolate): drop the whole batch rather than serve a- // box the cell may be about to reap. Rare — TTL is far under the DO's- // 10-min entry TTL and the cell's 15-min destroy backstop.- if (Date.now() - box.atMs < MAGAZINE_TTL_MS) {- return { box, amortized: !didRefill, stock: magazineLastStock.get(key) ?? -1 };- }- magazines.set(key, []);- }- let inflight = magazineInflight.get(key);- if (!inflight) {- didRefill = true;- // Size the batch to demand: how many creates are waiting on this org's- // magazine right now (1 for a lone create → no over-fetch, no waste).- const want = Math.min(MAGAZINE_MAX, Math.max(1, magazineWaiters.get(key) ?? 1));- inflight = refillMagazine(env, cell, orgID, key, want);- magazineInflight.set(key, inflight);- void inflight.finally(() => {- if (magazineInflight.get(key) === inflight) magazineInflight.delete(key);- });- }- await inflight;- }- return null;- } finally {- const n = (magazineWaiters.get(key) ?? 1) - 1;- if (n <= 0) magazineWaiters.delete(key);- else magazineWaiters.set(key, n);- }-}-// 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,@@ -1574,26 +1315,27 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro// the pre-sharding DO (holding the fleet's stock at cutover) drains as a// first-class shard instead of hoarding reservations until TTL. One empty// shard (404) gets one retry on a different shard before the CP fallback.+ const claimBody = JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } });mark("cap");- // Magazine claim: a hit is pure isolate memory (no subrequest, no HMAC —- // the DO minted the token when it filled the batch). A miss single-flights- // one /claim-batch sized to the number of creates currently waiting, so a- // burst pays ~N/MAGAZINE_MAX DO calls instead of N.- // `?nomag=1` bypasses the isolate magazine and does the pre-magazine- // thing: one direct DO claim for this request. Kept so magazine-vs-direct- // can be A/B'd against a SINGLE deploy — otherwise the two arms differ by- // a deploy as well as by the variable, which is not a controlled test.- const claimed = req.url.includes("nomag=1")- ? await claimDirectBox(env, cell, caller.orgID)- : await claimMagazineBox(env, cell, caller.orgID);- const box = claimed?.box ?? null;- if (box && claimed) {+ // Sample up to 3 distinct shards (random walk with a random stride+ // coprime-ish to 8) — at full stock the first hit ends it; under sparse+ // stock (small cells, mid-battery drain) 3 samples cut the false-fallback+ // rate from ~(empty/8)² to ~(empty/8)³ for ~10ms per extra probe.+ let box: { id: string; workerID: string; region: string; sandboxDomain: string } | null = null;+ let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);+ const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));+ for (let attempt = 0; attempt < 3 && !box; attempt++) {+ const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim", {+ method: "POST",+ body: claimBody,+ });+ shard = (shard + stride) % POOL_STOCK_SHARDS;+ if (!r.ok) continue;+ box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };+ }+ if (box) {mark("claim");- // Telemetry (#7): whether this create was served from the magazine (no- // origin work at all) and the stock left in the shard at last refill.- // `dur` is a value here, not a duration.- phases.push(`mag;dur=${claimed.amortized ? 1 : 0}`, `stock;dur=${claimed.stock}`);- const token = box.token;+ const token = await mintSandboxToken(env.SESSION_JWT_SECRET, caller.orgID, box.id, box.workerID);if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });// Seed the colo-shared route so the first exec — which usually lands on@@ -1610,13 +1352,17 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): ProworkerID: box.workerID,};if (box.sandboxDomain) resp.sandboxDomain = box.sandboxDomain;- // NOTE: the VmSession pre-wake was MOVED off this create hot path to- // stock-prep (pool_stock.ts reserveOnce). At burst-100 the per-create- // prewake fanned out ~100 DO /status subrequests from the create- // isolate, saturating its subrequest budget — create p100 549ms at- // 100-way vs ~140ms at 30-way. Warming at reserve keeps the DO hot for- // the common case; a box that re-hibernates before claim wakes on the- // host dial / first exec as before.+ // Pre-wake the box's VmSession OFF the response path: the DO hibernated+ // after the manufacture dial, and its isolate wake (~180ms, measured via+ // do−doin) otherwise lands on the customer's first exec. waitUntil runs+ // after the 201 is sent, so unlike the reverted inline /status verify+ // this cannot tax create latency.+ ctx.waitUntil(+ env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(box.id))+ .fetch("https://do/status")+ .then(() => {})+ .catch(() => {}),+ );// Finalize off the create isolate: enqueue a tiny message (one cheap// send) instead of running the CP fetch + D1 insert here. ~100 inline// finalizes otherwise accumulate on the isolate and stall the burst (devdiff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.tsindex 2e9cf5ca..95e1a0d7 100644--- a/cloudflare-workers/api-edge/src/pool_stock.ts+++ b/cloudflare-workers/api-edge/src/pool_stock.ts@@ -30,17 +30,6 @@ interface StockEntry {interface PoolStockEnv {SESSION_JWT_SECRET: string;- // Per-shard stock sizing, overridable per environment (wrangler.toml [vars]).- // Defaults below are the prod values; dev sets these DOWN because its cell- // holds ~30 boxes total, an order of magnitude under the 8×38 fleet target —- // see the sizing invariant in the block comment below.- POOL_STOCK_TARGET?: string;- POOL_STOCK_LOW_WATER?: string;- // VmSession DOs are pre-woken here at stock-prep (see reserveOnce) instead of- // on the create hot path — a burst-100 otherwise fires ~100 prewake- // subrequests from the create isolate, saturating its subrequest budget.- // Optional so the binding can be absent mid-cutover (prewake just skips).- VM_SESSIONS?: DurableObjectNamespace;}// Stock tuning. TARGET_STOCK mirrors ~the whole per-cell hot pool so every@@ -59,18 +48,11 @@ const ENTRY_TTL_MS = 10 * 60_000;// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 304 — deep// enough that a sustained ~300-create drain (sequential or 100-way burst) is// served entirely from seasoned stock, never from mid-drain refill manufacture-// (freshly-restored boxes are the p99 tail).-//-// SIZING INVARIANT: SHARDS × TARGET_STOCK must be ≤ the cell's actual pool-// (OPENSANDBOX_POOL_TARGET × workers). If it exceeds the pool, every shard-// permanently believes it is below LOW_WATER, restocks on every claim, and the-// shards compete for a supply that can never satisfy them — boxes concentrate-// in whichever shards win, creates that hash to an empty shard fall through to-// the ~10× slower CP path, and the measured burst latency becomes a function of-// shard luck rather than of the system under test. Dev hit exactly this (30-box-// cell against a 304 target), which is why these are env-overridable.-const DEFAULT_LOW_WATER = 18;-const DEFAULT_TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)+// (freshly-restored boxes are the p99 tail). CP pool (OPENSANDBOX_POOL_TARGET ×+// workers) and refill pacing must stay ≥ this.+const LOW_WATER = 18;+const RESTOCK_BATCH = 38; // max boxes reserved per single edge-reserve call+const TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)const ALARM_INTERVAL_MS = 10_000; // proactive top-up cadenceconst RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls ≥ TARGET)// Self-decommission: a shard that hasn't served a claim in this long releases@@ -85,14 +67,6 @@ const IDLE_DECOMMISSION_MS = 30 * 60_000;// but the middleware wants a parseable org UUID.const POOL_ORG_ID = "00000000-0000-4000-8000-000000000001";-// Parse a positive integer from a wrangler [vars] string, falling back to the-// prod default when unset/blank/garbage — a bad var must never zero the stock.-function intFromEnv(raw: string | undefined, fallback: number): number {- if (raw === undefined || raw === "") return fallback;- const n = Number.parseInt(raw, 10);- return Number.isFinite(n) && n > 0 ? n : fallback;-}-const b64url = (buf: ArrayBuffer | Uint8Array): string => {const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);let s = "";@@ -103,52 +77,6 @@ const b64url = (buf: ArrayBuffer | Uint8Array): string => {// Minimal cap-token mint for the DO's own cell calls (reserve/release).// Duplicates index.ts's mintCapToken rather than importing it — the DO must// not pull in the Worker's module graph (circular import, isolate bloat).-// Cached HMAC key for sandbox-token minting (see mintSandboxTokenDO).-let doSignKey: Promise<CryptoKey> | null = null;-function doHmacKey(secret: string): Promise<CryptoKey> {- if (!doSignKey) {- doSignKey = crypto.subtle.importKey(- "raw",- new TextEncoder().encode(secret),- { name: "HMAC", hash: "SHA-256" },- false,- ["sign"],- );- }- return doSignKey;-}--// The JWT header is constant — encode it once per isolate instead of-// JSON.stringify + base64 on every mint.-const JWT_HEADER_B64 = b64url(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));--// mintSandboxTokenDO mints the customer-facing sandbox token INSIDE this DO, so-// a batch claim returns ready-to-serve tokens and the create isolate performs no-// HMAC at all. Byte-identical to index.ts's mintSandboxToken (same secret, same-// claims) — the create path just hands this through. Duplicated rather than-// imported: the DO must not pull in the Worker's module graph.-async function mintSandboxTokenDO(- secret: string,- orgID: string,- sandboxID: string,- workerID: string,-): Promise<string> {- const now = Math.floor(Date.now() / 1000);- const enc = new TextEncoder();- const payload = {- sub: orgID,- iat: now,- exp: now + 24 * 3600,- iss: "opensandbox",- org_id: orgID,- sandbox_id: sandboxID,- worker_id: workerID,- };- const signingInput = JWT_HEADER_B64 + "." + b64url(enc.encode(JSON.stringify(payload)));- const sig = await crypto.subtle.sign("HMAC", await doHmacKey(secret), enc.encode(signingInput));- return signingInput + "." + b64url(sig);-}-async function mintPoolCapToken(secret: string, cellID: string): Promise<string> {const now = Math.floor(Date.now() / 1000);const enc = new TextEncoder();@@ -180,24 +108,11 @@ export class PoolStock {// without waiting for the next claim (a fresh DO after eviction still knows// which cell to reserve from).private cell: { cellID: string; baseURL: string } | null = null;- // Resolved once per isolate from env (see the sizing invariant above).- private readonly targetStock: number;- private readonly lowWater: number;- private readonly restockBatch: number;constructor(private state: DurableObjectState,private env: PoolStockEnv,) {- this.targetStock = intFromEnv(env.POOL_STOCK_TARGET, DEFAULT_TARGET_STOCK);- // Low-water must stay under target or a restock is triggered on every claim.- this.lowWater = Math.min(- this.targetStock - 1,- intFromEnv(env.POOL_STOCK_LOW_WATER, DEFAULT_LOW_WATER),- );- // One reserve call per restock pass was sized to cover the whole target- // (batch × RESTOCK_MAX_CALLS ≥ target); keep that relationship as target moves.- this.restockBatch = this.targetStock;this.state.blockConcurrencyWhile(async () => {this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];this.cell = (await this.state.storage.get<{ cellID: string; baseURL: string }>("cell")) ?? null;@@ -209,9 +124,6 @@ export class PoolStock {if (req.method === "POST" && url.pathname === "/claim") {return this.claim(req);}- if (req.method === "POST" && url.pathname === "/claim-batch") {- return this.claimBatch(req);- }if (req.method === "GET" && url.pathname === "/status") {return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });}@@ -257,75 +169,14 @@ export class PoolStock {// Ensure the proactive top-up loop is running, and kick an immediate restock// if this claim dropped us below the low-water mark (don't wait for the tick).this.state.waitUntil(this.ensureAlarm());- if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {+ if (cell && !this.restockInFlight && this.stock.length < LOW_WATER) {this.state.waitUntil(this.restockToTarget(cell));}if (!entry) {return new Response(JSON.stringify({ error: "stock empty" }), { status: 404 });}- // `stock` = entries left in this shard after the pop (telemetry #7): lets the- // create path surface shard depletion via Server-Timing.- return Response.json({ ...entry, stock: this.stock.length });- }-- // claimBatch pops up to `count` entries in ONE call and returns them with- // their sandbox tokens already minted. This is the magazine refill (see- // index.ts): instead of a burst doing one DO subrequest + one HMAC per create- // on the saturated create isolate, one call serves ~N creates from isolate- // memory with zero further subrequests and zero edge crypto. Popped entries- // are TOKENED, so — exactly like /claim — they must never return to the pool;- // an isolate that dies holding them leaves them to the cell's reaper.- private async claimBatch(req: Request): Promise<Response> {- let cell: { cellID: string; baseURL: string } | null = null;- let orgID = "";- let count = 1;- try {- const body = (await req.json()) as {- cell?: { cellID: string; baseURL: string };- orgID?: string;- count?: number;- };- cell = body.cell ?? null;- orgID = typeof body.orgID === "string" ? body.orgID : "";- count = Math.max(1, Math.min(Number(body.count) || 1, this.targetStock));- } catch {- /* fall through with defaults */- }- if (!orgID) return new Response(JSON.stringify({ error: "orgID required" }), { status: 400 });- if (cell) this.rememberCell(cell);-- // Same inline stale-expiry as claim(), synchronous over the in-memory array- // so a concurrent claim can't double-pop across an await.- const now = Date.now();- const fresh: StockEntry[] = [];- const stale: StockEntry[] = [];- for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);- this.stock = fresh;- if (stale.length > 0) this.state.waitUntil(this.release(stale));-- const entries = this.stock.splice(0, Math.min(count, this.stock.length));- this.lastClaimMs = Date.now();- void this.state.storage.put("lastClaim", this.lastClaimMs, { allowUnconfirmed: true });- this.persist();-- this.state.waitUntil(this.ensureAlarm());- if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {- this.state.waitUntil(this.restockToTarget(cell));- }-- // Mint every token here (one isolate, N signs) rather than N times on the- // create isolate. Parallel — crypto.subtle.sign is async.- const boxes = await Promise.all(- entries.map(async (e) => ({- id: e.id,- workerID: e.workerID,- region: e.region,- sandboxDomain: e.sandboxDomain,- token: await mintSandboxTokenDO(this.env.SESSION_JWT_SECRET, orgID, e.id, e.workerID),- })),- );- return Response.json({ boxes, stock: this.stock.length });+ return Response.json(entry);}// rememberCell persists the cell coordinates so the alarm can restock even on@@ -372,33 +223,16 @@ export class PoolStock {// pool. This is how the pre-sharding legacy DO (which becomes shard 0 and// held the whole fleet's stock) sheds down to TARGET_STOCK so the other// shards can reserve those boxes; it also self-heals any future oversizing.- if (this.stock.length > this.targetStock) {- const surplus = this.stock.splice(this.targetStock);+ if (this.stock.length > TARGET_STOCK) {+ const surplus = this.stock.splice(TARGET_STOCK);await this.release(surplus);}- if (this.stock.length < this.targetStock) await this.restockToTarget(cell);+ if (this.stock.length < TARGET_STOCK) await this.restockToTarget(cell);this.persist();- // NOTE: deliberately NO periodic re-prewake of sitting stock here. Warming- // every entry each tick costs 8 shards × TARGET_STOCK DO pokes every- // ALARM_INTERVAL — sustained background load on the vm-do worker plus- // waitUntil work competing with this DO's own claim serving — and prod- // measurement showed the burst gate is edge-isolate admission, not DO- // coldness (exec held ~48ms with 100% VM-DO). Fresh boxes are warmed once in- // reserveOnce; a box that re-hibernates while it sits wakes on the host dial- // or first exec, as it always did.+ // Keep the loop alive — stock stays full and fresh between bursts.await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);}- // prewakeBox wakes one box's VmSession DO isolate (best-effort, off any hot- // path). Called from reserveOnce when a box enters the stock.- private prewakeBox(sandboxID: string): void {- const vs = this.env.VM_SESSIONS;- if (!vs) return;- this.state.waitUntil(- vs.get(vs.idFromName(sandboxID)).fetch("https://do/status").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@@ -418,7 +252,7 @@ export class PoolStock {this.restockInFlight = true;try {for (let call = 0; call < RESTOCK_MAX_CALLS; call++) {- const want = Math.min(this.restockBatch, this.targetStock - this.stock.length);+ const want = Math.min(RESTOCK_BATCH, TARGET_STOCK - this.stock.length);if (want <= 0) return;const got = await this.reserveOnce(cell, want);if (got < want) return; // pool drained (or error) — don't spin@@ -462,10 +296,6 @@ export class PoolStock {atMs: now,});added++;- // 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.- this.prewakeBox(b.sandboxID);}this.persist();return added;diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 64834fb4..db926e5f 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -160,15 +160,6 @@ WORKER_ENV = "dev"# Dev override of the per-org paused-sandbox cap (prod defaults to 100) so the# promotion path can be exercised without pausing hundreds of boxes.PAUSED_CAP = "10"-# PoolStock sizing, scaled to THIS cell's pool. The DO defaults (38 per shard ×-# 8 shards = 304) are sized for prod's 320-box pool; dev's cell holds ~30, so the-# defaults put every shard permanently below low-water, restocking on every claim-# and competing for a supply that can never satisfy them — creates that hash to a-# starved shard fall through to the ~10× slower CP path and dev burst numbers-# stop measuring anything real. 8 × 3 = 24 keeps the fleet target under the 30-# available with headroom. See the SIZING INVARIANT in src/pool_stock.ts.-POOL_STOCK_TARGET = "3"-POOL_STOCK_LOW_WATER = "2"# Cells eligible for new-org home assignment are NOT configured here anymore —# it's the `accepts_new_orgs` column on the D1 `cells` table (single source of# truth, toggled per-row without a deploy). See pickHomeCell in src/index.ts.