Skip to content

An open-source, faster Devin alternative

TypeScript

revert: return the edge to the #668 state to re-establish a clean baseline

Brian Reardon241780e79ca9
diff --git a/cloudflare-workers/api-edge/src/auth_singleflight.test.ts b/cloudflare-workers/api-edge/src/auth_singleflight.test.ts
deleted file mode 100644
index ccb8a50c..00000000
--- a/cloudflare-workers/api-edge/src/auth_singleflight.test.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// A cold-cache burst must collapse onto ONE api_keys lookup.
-//
-// This is a latency contract, not a correctness one, which is exactly why it
-// needs a test: without single-flight everything still returns the right
-// answer, just slowly, so nothing fails and the regression is invisible until
-// someone runs a burst. Measured on prod at burst-100 against a freshly
-// deployed worker, the un-collapsed version put `auth` at 15,026ms median with
-// all 100 requests inside a 48ms band — one shared round trip to a D1 primary
-// that lives in WNAM while the burst runs in IAD.
-import { describe, expect, it, vi } from "vitest";
-import worker, { type Env } from "./index";
-
-const orgID = "22222222-2222-4222-8222-222222222222";
-const userID = "11111111-1111-4111-8111-111111111111";
-
-class CountingDB {
- apiKeyLookups = 0;
-
- prepare(sql: string) {
- const db = this;
- return {
- bind() {
- return this;
- },
- async first<T>(): Promise<T | null> {
- if (sql.includes("FROM api_keys WHERE key_hash")) {
- db.apiKeyLookups++;
- // A real D1 read from IAD to a WNAM primary is ~300ms. Any await at
- // all is enough to let the other requests in the burst reach the
- // in-flight map, which is the behaviour under test.
- await new Promise((r) => setTimeout(r, 5));
- return { org_id: orgID, created_by: userID, expires_at: null } as T;
- }
- return null;
- },
- async all<T>(): Promise<{ results: T[] }> {
- return { results: [] as T[] };
- },
- async run(): Promise<Record<string, never>> {
- return {};
- },
- };
- }
-
- async batch<T>(stmts: { first(): Promise<T> }[]): Promise<{ results: T[] }[]> {
- return Promise.all(stmts.map(async (s) => ({ results: [await s.first()] })));
- }
-}
-
-function testEnv(db: CountingDB): Env {
- return {
- OPENCOMPUTER_DB: db,
- SESSIONS_KV: {},
- WORKER_ENV: "test",
- CF_ADMIN_SECRET: "",
- EVENT_SECRET: "",
- } as unknown as Env;
-}
-
-const ctx = {
- waitUntil: vi.fn(),
- passThroughOnException: vi.fn(),
-} as unknown as ExecutionContext;
-
-describe("authenticate single-flight", () => {
- it("collapses a concurrent cold-cache burst onto one api_keys lookup", async () => {
- const db = new CountingDB();
- const env = testEnv(db);
- // Unique per run: authCache is module-global, so a key another test already
- // authenticated would be served from cache and never reach D1 at all.
- const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
-
- await Promise.all(
- Array.from({ length: 50 }, () =>
- worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- headers: { "X-API-Key": key },
- }),
- env,
- ctx,
- ),
- ),
- );
-
- expect(db.apiKeyLookups).toBe(1);
- });
-
- it("does not collapse distinct keys onto one another", async () => {
- const db = new CountingDB();
- const env = testEnv(db);
- const keys = Array.from(
- { length: 3 },
- () => `osb_${crypto.randomUUID().replace(/-/g, "")}`,
- );
-
- await Promise.all(
- keys.flatMap((key) =>
- Array.from({ length: 5 }, () =>
- worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- headers: { "X-API-Key": key },
- }),
- env,
- ctx,
- ),
- ),
- ),
- );
-
- expect(db.apiKeyLookups).toBe(keys.length);
- });
-
- it("releases the in-flight entry so a later miss still reaches D1", async () => {
- const db = new CountingDB();
- const env = testEnv(db);
- const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
- const call = (): Promise<Response> =>
- worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- headers: { "X-API-Key": key },
- }),
- env,
- ctx,
- );
-
- await call();
- expect(db.apiKeyLookups).toBe(1);
- // Second call is served by the isolate cache, not by a second query — and
- // critically it must not hang on a stale in-flight promise.
- await call();
- expect(db.apiKeyLookups).toBe(1);
- });
-});
diff --git a/cloudflare-workers/api-edge/src/auth_warm.test.ts b/cloudflare-workers/api-edge/src/auth_warm.test.ts
deleted file mode 100644
index bde2dbea..00000000
--- a/cloudflare-workers/api-edge/src/auth_warm.test.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-// The warmed auth entry must be readable by authenticate().
-//
-// This is a shape contract between two files, and the failure mode if it drifts
-// is silence: authenticate() simply misses, falls through to D1, and everything
-// still returns the right answer. Nothing throws, no test fails, and the only
-// symptom is that the first request from a cold isolate goes back to costing
-// what it cost before — measured on prod from IAD, 16,723ms.
-//
-// So the assertion here is the round trip, not the written bytes: warm, then
-// authenticate, then require that D1 was never touched.
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import worker, { type Env } from "./index";
-import { warmCreateContextColo } from "./create_context_cache";
-
-const orgID = "22222222-2222-4222-8222-222222222222";
-const userID = "11111111-1111-4111-8111-111111111111";
-
-async function sha256Hex(s: string): Promise<string> {
- const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));
- return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
-}
-
-// Minimal stand-in for caches.default — vitest has no Cache API, and without one
-// coloPut/coloGet no-op and this test would pass vacuously.
-function installCacheStub(): Map<string, string> {
- const store = new Map<string, string>();
- (globalThis as unknown as { caches: unknown }).caches = {
- default: {
- async match(url: string): Promise<Response | undefined> {
- const v = store.get(String(url));
- return v === undefined ? undefined : new Response(v);
- },
- async put(url: string, res: Response): Promise<void> {
- store.set(String(url), await res.text());
- },
- },
- };
- return store;
-}
-
-class WarmDB {
- apiKeyLookups = 0;
- constructor(private readonly keys: { key_hash: string; expires_at: number | null }[]) {}
-
- prepare(sql: string) {
- const db = this;
- const stmt = {
- bind() {
- return stmt;
- },
- async first<T>(): Promise<T | null> {
- if (sql.includes("FROM api_keys WHERE key_hash")) db.apiKeyLookups++;
- return null;
- },
- async all<T>(): Promise<{ results: T[] }> {
- return { results: [] as T[] };
- },
- async run(): Promise<Record<string, never>> {
- return {};
- },
- _sql: sql,
- };
- return stmt;
- }
-
- async batch(stmts: { _sql: string }[]): Promise<{ results: unknown[] }[]> {
- return stmts.map((s) => {
- if (s._sql.includes("FROM api_keys WHERE org_id")) {
- return {
- results: this.keys.map((k) => ({
- key_hash: k.key_hash,
- org_id: orgID,
- created_by: userID,
- expires_at: k.expires_at,
- })),
- };
- }
- if (s._sql.includes("FROM cells")) {
- return {
- results: [
- {
- cell_id: "azure-us-east-2-a",
- cloud: "azure",
- region: "us-east-2",
- base_url: "https://cell.example",
- status: "active",
- available_workers: 4,
- capacity_updated_at: null,
- },
- ],
- };
- }
- if (s._sql.includes("FROM orgs")) {
- return {
- results: [
- {
- home_cell: "azure-us-east-2-a",
- plan: "pro",
- is_halted: 0,
- max_concurrent_sandboxes: 100,
- max_disk_mb: 100000,
- billing_provider: "autumn",
- runtime: "microvm",
- },
- ],
- };
- }
- return { results: [{ n: 0 }] };
- });
- }
-}
-
-function testEnv(db: WarmDB): Env {
- return {
- OPENCOMPUTER_DB: db,
- SESSIONS_KV: {},
- WORKER_ENV: "test",
- CF_ADMIN_SECRET: "",
- EVENT_SECRET: "",
- } as unknown as Env;
-}
-
-const ctx = {
- waitUntil: vi.fn(),
- passThroughOnException: vi.fn(),
-} as unknown as ExecutionContext;
-
-describe("warmed auth entries", () => {
- beforeEach(() => {
- installCacheStub();
- });
-
- it("are accepted by authenticate without touching D1", async () => {
- const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
- const db = new WarmDB([{ key_hash: await sha256Hex(key), expires_at: null }]);
-
- await warmCreateContextColo(db as unknown as D1Database, [orgID]);
-
- const res = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- headers: { "X-API-Key": key },
- }),
- testEnv(db),
- ctx,
- );
-
- expect(res.status).not.toBe(401);
- expect(db.apiKeyLookups).toBe(0);
- });
-
- it("skips expired keys rather than publishing them as valid", async () => {
- const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
- const expired = Math.floor(Date.now() / 1000) - 60;
- const db = new WarmDB([{ key_hash: await sha256Hex(key), expires_at: expired }]);
-
- await warmCreateContextColo(db as unknown as D1Database, [orgID]);
-
- await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- headers: { "X-API-Key": key },
- }),
- testEnv(db),
- ctx,
- );
-
- // No warmed entry to hit, so the request must fall through to D1 — which is
- // the safe direction: an expired key gets re-checked, never served warm.
- expect(db.apiKeyLookups).toBe(1);
- });
-});
diff --git a/cloudflare-workers/api-edge/src/create_context_cache.ts b/cloudflare-workers/api-edge/src/create_context_cache.ts
index 5bf53258..0a6123bf 100644
--- a/cloudflare-workers/api-edge/src/create_context_cache.ts
+++ b/cloudflare-workers/api-edge/src/create_context_cache.ts
@@ -73,23 +73,6 @@ export const RUNNING_COUNT_SQL =
"SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'";
export const ACTIVE_CELLS_SQL =
"SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at FROM cells WHERE status = 'active'";
-// The org's API keys, so the auth entry can be warmed alongside the rest of the
-// create context. Bounded and most-recently-used first: an org may hold many
-// keys but a burst arrives on one, and this rides inside a 10s alarm.
-export const ORG_KEYS_SQL =
- "SELECT key_hash, org_id, created_by, expires_at FROM api_keys WHERE org_id = ?1 ORDER BY last_used DESC LIMIT 8";
-
-// How long a warmed auth entry stays usable. Must equal index.ts's AUTH_TTL_MS
-// — authenticate() reads these entries and applies that bound itself, so a
-// longer TTL here would only produce entries it rejects on arrival.
-export const AUTH_TTL_MS = 60_000;
-
-interface KeyRow {
- key_hash: string;
- org_id: string;
- created_by: string | null;
- expires_at: number | null;
-}
// How many recently-serving orgs one warm pass refreshes. The point is to cover
// whoever is actually creating through this shard, not the whole customer base:
@@ -160,7 +143,6 @@ export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): P
for (const id of orgs) {
stmts.push(db.prepare(ORG_POLICY_SQL).bind(id));
stmts.push(db.prepare(RUNNING_COUNT_SQL).bind(id));
- stmts.push(db.prepare(ORG_KEYS_SQL).bind(id));
}
// One round trip for everything: the whole reason this is worth doing from
// a 10s alarm rather than N separate reads.
@@ -176,36 +158,9 @@ export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): P
puts.push(coloPut("cells", "active", { cells, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000));
}
- const nowSec = Math.floor(at / 1000);
for (let i = 0; i < orgs.length; i++) {
- const policy = (res[1 + i * 3]?.results?.[0] as OrgPolicy | undefined) ?? null;
- const n = (res[2 + i * 3]?.results?.[0] as { n: number } | undefined)?.n ?? 0;
- // Auth entries, in the shape authenticate() reads. This is the one read on
- // the create path that no warmer covered, and it is the most expensive to
- // miss: measured on prod from IAD, a cold isolate's FIRST D1 touch cost
- // 16,723ms while the same read from SJC — where the primary lives — cost
- // 57ms. authenticate() runs before everything else, so it pays that
- // establishment and every later read on the request rides the open
- // connection (`ctx` was 125ms on the very same request).
- //
- // Revocation is unaffected: a deleted key simply stops coming back from
- // this query, so its entry lapses within AUTH_TTL_MS exactly as it does
- // today. Expired keys are skipped rather than published as valid.
- for (const k of (res[3 + i * 3]?.results as KeyRow[] | undefined) ?? []) {
- if (k.expires_at !== null && k.expires_at < nowSec) continue;
- puts.push(
- coloPut(
- "auth",
- k.key_hash,
- {
- caller: { orgID: k.org_id, userID: k.created_by },
- expiresAt: k.expires_at,
- cachedAtMs: at,
- },
- AUTH_TTL_MS / 1000,
- ),
- );
- }
+ const policy = (res[1 + i * 2]?.results?.[0] as OrgPolicy | undefined) ?? null;
+ const n = (res[2 + i * 2]?.results?.[0] as { n: number } | undefined)?.n ?? 0;
// A null policy is a real answer (org deleted), but publishing it from a
// background pass would hand the create path a "no such org" it did not
// ask for. Let the create path establish that itself.
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index f5ac7feb..0a70307c 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -32,7 +32,6 @@ export { PoolStock } from "./pool_stock";
import { coloGet, coloPut } from "./colo_cache";
import {
ACTIVE_CELLS_SQL,
- AUTH_TTL_MS,
CELL_STALE_MAX_MS,
CELL_TTL_MS,
CONCURRENCY_COUNT_TTL_MS,
@@ -376,6 +375,7 @@ function stripApiKeyQueryParam(target: string): string {
// per-isolate for a few seconds so a burst collapses to a handful of D1 reads,
// and throttle the last_used bump. Isolates recycle so entries are naturally
// bounded; CACHE_MAX guards pathological key cardinality.
+const AUTH_TTL_MS = 60_000;
// SWR window for org policy in the colo tier: a ≤60s-stale not-halted policy
// may gate a create while a background refresh runs (see loadCreateContext).
const LAST_USED_BUMP_MS = 60_000; // at most once/min/key/isolate
@@ -388,9 +388,6 @@ interface AuthEntry {
lastBumpMs: number;
}
const authCache = new Map<string, AuthEntry>();
-// In-flight D1 auth lookups, keyed by key hash — see authenticate(). Collapses a
-// cold-cache burst onto one query instead of one per request.
-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
@@ -503,46 +500,21 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
return shared.caller;
}
- // Single-flight the D1 read. Both cache tiers are empty on a fresh isolate,
- // and a burst arrives before either can fill, so without this N concurrent
- // creates issue N identical queries against a primary that sits in WNAM while
- // the burst runs in IAD.
- //
- // Measured on prod at burst-100 against a just-deployed worker: `auth` median
- // 15,026ms, with all 100 requests inside a 48ms band — the tight band is the
- // tell, since it means they were not queueing behind each other's work but
- // waiting on one shared round trip that D1 serialized. Same isolate warm, the
- // mark is 0ms. loadOrgPolicy already does this; auth was the last read on the
- // create path that did not.
- //
- // Keyed on the hash, so distinct keys still proceed in parallel, and the
- // entry is removed as soon as it settles — this collapses a stampede, it is
- // not a cache tier of its own.
- const inflight = authInflight.get(hash);
- if (inflight) return inflight;
- const pending = (async (): Promise<Caller | null> => {
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",
- )
- .bind(hash)
- .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
- if (!row) return null; // never cache negatives — a freshly-created key must work at once
- if (row.expires_at && row.expires_at < nowSec) return 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 };
- 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;
- })();
- authInflight.set(hash, pending);
- try {
- return await pending;
- } finally {
- authInflight.delete(hash);
- }
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",
+ )
+ .bind(hash)
+ .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();
+ if (!row) return null; // never cache negatives — a freshly-created key must work at once
+ if (row.expires_at && row.expires_at < nowSec) return 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 };
+ 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;
}
// Cell rows are semi-static (base_url is fixed; capacity refreshes ~30s and
@@ -1291,41 +1263,11 @@ function indexSandboxFromSSE(
// a region, not a metro, so within enam the placement still falls out of which
// colo touches the object first. That is the part only the arming run controls
// — see the note above about first-touching from the cell's own metro.
-// g5 stops trying to AIM placement and starts SELECTING it. Four generations
-// were armed exactly as the note above prescribes — first-touched from a
-// sandbox inside the cell's own metro — and all four still scattered across
-// five colos. The conclusion is that first-touch-colo does not decide placement
-// within a region; Cloudflare spreads inside enam and the arming client cannot
-// override that. So placement is not something to get right, it is something to
-// measure: mint far more candidate shard names than we need, ask each one where
-// it landed (GET /internal/pool/colo-probe), and keep only the indices that
-// answer IAD. Selection is deterministic where placement is not, and it is
-// permanent for the same reason placement was a trap — a placed DO never moves.
-//
-// POOL_STOCK_SHARD_IDS is therefore a MEASUREMENT, not a configuration. Re-run
-// the probe and re-pick if the shard set is ever regenerated; do not hand-edit
-// it to indices nobody has verified.
-// Probed on prod 2026-08-21 from the control plane (IAD ingress), 64 g5
-// candidates: IAD 27, EWR 17, ATL 9, MIA 7, ORD 4. Confirms the diagnosis —
-// every candidate was first-touched by the same request, from one colo, and
-// they still scattered five ways. Placement inside enam is not ours to aim.
-//
-// The eight below are the first eight that answered IAD. There is nothing
-// special about these indices; they are simply the ones that landed where we
-// want, which is the entire idea.
-const POOL_STOCK_SHARD_GEN = "g5";
-const POOL_STOCK_SHARD_IDS = [1, 4, 6, 12, 13, 14, 16, 17];
-const POOL_STOCK_SHARDS = POOL_STOCK_SHARD_IDS.length;
-// How many candidate names the probe route sweeps. Only the ones that report
-// the target colo get promoted into POOL_STOCK_SHARD_IDS above.
-const POOL_STOCK_CANDIDATES = 64;
-
-function poolStockShardName(cellID: string, id: number): string {
- return `${cellID}#${POOL_STOCK_SHARD_GEN}#${id}`;
-}
+const POOL_STOCK_SHARDS = 8;
+const POOL_STOCK_SHARD_GEN = "g4";
function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStub {
- const name = poolStockShardName(cellID, POOL_STOCK_SHARD_IDS[shard] ?? shard);
+ const name = `${cellID}#${POOL_STOCK_SHARD_GEN}#${shard}`;
// Deterministic placement hint: pin the stock DO to eastern North America
// (covers eastus2 / the IAD leaderboard runner) so a claim never eats a
// cross-colo hop even if the first touch comes from an off-metro edge. A
@@ -4208,50 +4150,6 @@ export default {
await runPausedCapEnforcer(env);
return json({ ok: true });
}
- // Placement probe for the pool shards. HMAC-auth'd (CF_ADMIN_SECRET) so it
- // is safe to run against prod, which is the only place the answer matters —
- // the colo a DO lands in is a property of the account and region, and dev
- // cannot stand in for it.
- //
- // Touching a candidate PLACES it, permanently. That is the point: this
- // sweep is how a generation of shards gets minted, and its output is the
- // POOL_STOCK_SHARD_IDS list. Sweeping a gen that is already live is
- // harmless (the candidates beyond the selected ones just sit empty and
- // never claim), but do not sweep with a `target` you are not about to ship.
- //
- // ?child=1 also asks each candidate to parent a throwaway MicrovmSession
- // and report where the CHILD landed — the one measurement that decides
- // whether pinning shards also pins the session DOs warmed from them.
- if (path === "/internal/pool/colo-probe" && req.method === "GET") {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- const expected = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${path}${url.search}`);
- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
- if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300)
- return json({ error: "timestamp out of window" }, 401);
- const cellID = url.searchParams.get("cell") ?? "";
- if (!cellID) return json({ error: "cell required" }, 400);
- const gen = url.searchParams.get("gen") ?? POOL_STOCK_SHARD_GEN;
- const n = Math.min(Number(url.searchParams.get("n")) || POOL_STOCK_CANDIDATES, 256);
- const wantChild = url.searchParams.get("child") === "1";
- const probe = async (i: number) => {
- const name = `${cellID}#${gen}#${i}`;
- const q = wantChild ? `?child=${encodeURIComponent(`probe-${gen}-${i}`)}` : "";
- try {
- const r = await env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name), {
- locationHint: "enam",
- }).fetch(`https://pool-stock/colo${q}`);
- const j = (await r.json()) as { colo: string; stock: number; child: string | null };
- return { i, colo: j.colo, stock: j.stock, child: j.child };
- } catch (e) {
- return { i, colo: "err", stock: -1, child: String(e).slice(0, 60) };
- }
- };
- const results = await Promise.all(Array.from({ length: n }, (_, i) => probe(i)));
- const byColo: Record<string, number[]> = {};
- for (const r of results) (byColo[r.colo] ??= []).push(r.i);
- return json({ cell: cellID, gen, edgeColo: req.headers.get("cf-ray")?.split("-")[1] ?? "?", byColo, results });
- }
// Force a model-meter run (token billing §5.4). HMAC-auth'd (CF_ADMIN_SECRET) so
// it's safe to run in prod for testing/ops — useful to debit + push caps right
// after a Managed turn instead of waiting for the cron.
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 854715a5..572efccd 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -217,19 +217,6 @@ export class PoolStock {
// Resolved once per isolate alongside coloLogged; reported on every claim so
// the create path can see whether its stock DO is even in the same colo.
private colo = "?";
- // Blocking form, for the /colo probe only — never on a claim, which must not
- // wait on a diagnostic round trip.
- private async coloNow(): Promise<string> {
- if (this.colo !== "?") return this.colo;
- this.coloLogged = true;
- try {
- const t = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
- this.colo = (t.match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
- } catch {
- /* leave "?" — the probe reports unknown rather than failing */
- }
- return this.colo;
- }
// Last cell seen on a /claim, persisted so the proactive alarm can restock
// without waiting for the next claim (a fresh DO after eviction still knows
// which cell to reserve from).
@@ -282,39 +269,6 @@ export class PoolStock {
if (req.method === "GET" && url.pathname === "/status") {
return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });
}
- // 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
- // enam. So placement is not something to aim; it is something to measure
- // and then select on. /colo reports where this object actually landed.
- //
- // ?child=<name> additionally asks a MicrovmSession this shard parents where
- // IT landed. That is the load-bearing question for stock-prep warming: if a
- // child inherits its parent's colo, pinning the shards pins every session
- // DO with them; if it does not, session placement needs its own lever.
- //
- // ANSWERED, on prod 2026-08-21 over 64 parent/child pairs: it does not.
- // A child matches its parent's colo 34/64 of the time, and parent-IAD
- // yields child-IAD only 12/27 (44%) against a 30% background rate. So
- // parentage biases placement without deciding it. Pinning the shards is
- // still worth doing — deterministic for the claim hop, and it lifts the
- // session DOs from 21% IAD to ~44% for free — but the other half of them
- // need a lever this has now ruled out.
- if (req.method === "GET" && url.pathname === "/colo") {
- const self = await this.coloNow();
- const child = url.searchParams.get("child");
- const ns = this.env.MICROVM_SESSIONS;
- let childColo: string | null = null;
- if (child && ns) {
- childColo = await ns
- .get(ns.idFromName(child), { locationHint: "enam" })
- .fetch("https://do/colo")
- .then((r) => r.json() as Promise<{ colo: string }>)
- .then((j) => j.colo)
- .catch(() => "err");
- }
- return Response.json({ colo: self, stock: this.stock.length, child: childColo });
- }
return new Response("not found", { status: 404 });
}
diff --git a/cloudflare-workers/vm-do/src/microvm_session.ts b/cloudflare-workers/vm-do/src/microvm_session.ts
index be33a504..dd52e16b 100644
--- a/cloudflare-workers/vm-do/src/microvm_session.ts
+++ b/cloudflare-workers/vm-do/src/microvm_session.ts
@@ -96,11 +96,6 @@ export class MicrovmSession {
warmUntil: this.warmUntil,
failures: this.failures,
});
- // Awaited colo, unlike resolveColo()'s fire-and-forget. Placement is
- // decided at first touch and is permanent, so the only way to get a shard
- // set that is actually in one metro is to mint candidates, ask each where
- // it landed, and keep the ones that answer correctly. This is the "ask".
- if (path === "/colo") return json({ colo: await this.coloNow() });
if (path === "/detach") return await this.detach();
} catch (e) {
return json({ error: String(e) }, 500);
@@ -300,20 +295,6 @@ export class MicrovmSession {
.catch(() => {});
}
- // Blocking form of resolveColo, for /colo only. Never used on the exec path:
- // an exec must not wait on a diagnostic round trip to cdn-cgi/trace.
- private async coloNow(): Promise<string> {
- if (this.colo !== "?") return this.colo;
- this.coloResolved = true;
- try {
- const t = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
- this.colo = (t.match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
- } catch {
- /* leave "?" — the probe reports it as unknown rather than failing */
- }
- return this.colo;
- }
-
private async exec(req: Request): Promise<Response> {
// Everything the caller cannot see from outside. do;dur on the edge is one
// opaque number covering the hop to this object, this object's cold start,
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index b056674a..4e1de98d 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.5",
+ "version": "0.15.4",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.ts
index da0ee32a..180427b1 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -1,4 +1,4 @@
-import { configureHttp2, prewarmConnections } from "./http2.js";
+import { configureHttp2 } from "./http2.js";
// Switch the Node global fetch dispatcher to HTTP/2 on import (browser-safe
// no-op). Multiplexes concurrent requests over one connection — a large burst
@@ -10,21 +10,6 @@ import { configureHttp2, prewarmConnections } from "./http2.js";
// configureHttp2 never rejects. See http2.ts.
await configureHttp2();
-// Open the connection pool at IMPORT, not at the first create.
-//
-// prewarmConnections used to fire from Sandbox.create(), which put the pool's
-// own setup INSIDE the window a burst measures — 48 connections cost ~153ms to
-// establish, and the first creates race them. Starting here means an importer
-// that loads the SDK before its timing loop (the leaderboard adapter does) has
-// the pool ready by the time it matters. Same connection count, just earlier.
-//
-// Deliberately NOT awaited: import must not block on the network. It is
-// memoized (warmPromise), so Sandbox.create()'s own call remains as the path
-// that covers a programmatically-supplied apiUrl, and becomes a no-op here.
-void prewarmConnections(
- (process.env?.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev").replace(/\/api\/?$/, ""),
-);
-
export {
Sandbox,
ScalingLockedError,