Skip to content

An open-source, faster Devin alternative

TypeScript

bump and cache

Brian Reardonab61beb3f21e
diff --git a/cloudflare-workers/api-edge/src/create_context_cache.ts b/cloudflare-workers/api-edge/src/create_context_cache.ts
new file mode 100644
index 00000000..0a6123bf
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/create_context_cache.ts
@@ -0,0 +1,176 @@
+// The create hot path's three D1 reads — org policy, running-sandbox count,
+// active-cells list — and the colo-cache entries that keep them off D1.
+//
+// This module exists so those entries have exactly ONE definition. They are
+// written from two places now: the create path itself (index.ts, on a miss) and
+// the PoolStock alarm (pool_stock.ts, proactively). A second copy of the shapes
+// or the TTLs in the DO would drift silently — the reader would just stop
+// finding hits and quietly go back to paying D1, which is invisible in every
+// signal except latency.
+//
+// Why anything writes them proactively: the colo tier only helps if something
+// touched that colo recently. A burst-100 arrives on ~100 isolates at once,
+// they all miss together, and single-flight cannot collapse across isolates —
+// so a cold burst pays the full read on every request (measured: `ctx` 376ms
+// median across all 100 on prod, where the D1 primary is in WNAM and creates
+// run in IAD).
+//
+// Two writers, and the difference between them is which colo they can reach:
+//
+// - keepCreateContextWarm, from the request path. Runs in the colo that will
+// serve the next request, so it is always the right one. Needs traffic.
+// - warmCreateContextColo, from the PoolStock alarm. Needs no traffic, but a
+// DO can only write the cache of the colo IT runs in — which is not
+// reliably the request's colo (measured on dev: shards in IAD/MIA, requests
+// served in SJC). Useful where a shard and the traffic do share a colo;
+// never something to rely on alone.
+//
+// Neither covers a genuinely cold colo — the first request after a long silence
+// still pays the read. Only moving the data closer (D1 read replication in
+// ENAM) removes that floor.
+
+import { coloGet, coloPut } from "./colo_cache";
+
+export interface CellRow {
+ cell_id: string;
+ cloud: string;
+ region: string;
+ base_url: string;
+ status: string;
+ available_workers: number;
+ capacity_updated_at: number | null;
+}
+
+export interface OrgPolicy {
+ home_cell: string;
+ plan: string;
+ is_halted: number;
+ max_concurrent_sandboxes: number;
+ max_disk_mb: number;
+ billing_provider: string;
+ // Which sandbox runtime this org's creates belong on. NULL/"" is the QEMU
+ // fleet — so every org that predates this column keeps its current runtime
+ // and opting one in is a single-row change.
+ runtime: string | null;
+}
+
+// Freshness windows. The TTL is how long a value is used outright; the STALE
+// window is how long it may still gate a create while a refresh runs behind it.
+export const ORG_POLICY_TTL_MS = 5_000; // short: bounds is_halted / cap staleness
+export const ORG_STALE_MAX_MS = 60_000;
+export const CONCURRENCY_COUNT_TTL_MS = 1_500;
+export const CONCURRENCY_STALE_MAX_MS = 30_000;
+export const CELL_TTL_MS = 5_000;
+// See the isHealthy() interaction noted at the cells stale-serve branch in
+// index.ts: reading capacity_updated_at from a ≤30s-stale snapshot stretches
+// the effective 120s freshness window to ~150s, still ~5× the CP's ~30s
+// capacity cadence.
+export const CELL_STALE_MAX_MS = 30_000;
+
+export const ORG_POLICY_SQL =
+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1";
+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'";
+
+// 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:
+// each org costs two statements in the batch, and an unbounded list would turn a
+// 10s alarm into a scan of every org that ever touched this shard.
+export const WARM_ORG_LIMIT = 4;
+
+// Refresh threshold for the request-driven keep-warm below: act once an entry
+// is past half its stale window, so it is replaced well before it can lapse
+// rather than exactly as it does.
+const REFRESH_AT_MS = CELL_STALE_MAX_MS / 2;
+
+// One in-flight refresh per org per isolate. The whole point is to fire on
+// ordinary traffic, and ordinary traffic is concurrent — without this a burst
+// would kick one background batch per request.
+const keepWarmInflight = new Map<string, Promise<void>>();
+
+// keepCreateContextWarm refreshes this COLO's create-context entries off the
+// back of any authenticated request for that org.
+//
+// This is the colo-correct half of the warming story, and it is why it does not
+// live in the PoolStock alarm. A Durable Object can only write the Cache API of
+// the colo IT runs in, which is not reliably the colo serving the request — dev
+// shards sit in IAD/MIA while requests land in SJC, so a shard-driven warm is
+// invisible to them. A request handler, by construction, runs in exactly the
+// colo whose cache the next request will read.
+//
+// Every authenticated call counts, not just creates: exec, delete, and list all
+// keep the create path warm for the same org, which is what carries an org
+// through the gap between its last request and its next burst.
+export function keepCreateContextWarm(
+ db: D1Database | undefined,
+ ctx: ExecutionContext | undefined,
+ orgID: string,
+): void {
+ if (!db || !ctx || !orgID) return;
+ if (keepWarmInflight.has(orgID)) return;
+ const p = (async () => {
+ try {
+ const [org, count, cells] = await Promise.all([
+ coloGet<{ cachedAtMs: number }>("org", orgID),
+ coloGet<{ cachedAtMs: number }>("count", orgID),
+ coloGet<{ cachedAtMs: number }>("cells", "active"),
+ ]);
+ const now = Date.now();
+ const aging = (e: { cachedAtMs: number } | null) => e === null || now - e.cachedAtMs > REFRESH_AT_MS;
+ if (!aging(org) && !aging(count) && !aging(cells)) return;
+ await warmCreateContextColo(db, [orgID]);
+ } catch {
+ /* best-effort */
+ } finally {
+ keepWarmInflight.delete(orgID);
+ }
+ })();
+ keepWarmInflight.set(orgID, p);
+ ctx.waitUntil(p);
+}
+
+// warmCreateContextColo refreshes the colo entries the create path reads.
+//
+// Best-effort by construction: it runs off every hot path, and a failure just
+// means the next create pays the read it would have paid anyway. It must never
+// throw into the alarm, or a D1 blip would stop the stock top-up as collateral.
+export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): Promise<void> {
+ try {
+ const orgs = orgIDs.slice(0, WARM_ORG_LIMIT);
+ const stmts: D1PreparedStatement[] = [db.prepare(ACTIVE_CELLS_SQL)];
+ for (const id of orgs) {
+ stmts.push(db.prepare(ORG_POLICY_SQL).bind(id));
+ stmts.push(db.prepare(RUNNING_COUNT_SQL).bind(id));
+ }
+ // One round trip for everything: the whole reason this is worth doing from
+ // a 10s alarm rather than N separate reads.
+ const res = await db.batch(stmts);
+ const at = Date.now();
+ const puts: Promise<void>[] = [];
+
+ const cells = (res[0]?.results as CellRow[] | undefined) ?? [];
+ // Never publish an empty cells list. A blip that cached one would 503 every
+ // create in this colo until it aged out — strictly worse than the stale
+ // read this is meant to replace.
+ if (cells.length > 0) {
+ puts.push(coloPut("cells", "active", { cells, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000));
+ }
+
+ for (let i = 0; i < orgs.length; i++) {
+ 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.
+ if (policy) {
+ puts.push(coloPut("org", orgs[i], { policy, cachedAtMs: at }, ORG_STALE_MAX_MS / 1000));
+ }
+ puts.push(coloPut("count", orgs[i], { count: n, cachedAtMs: at }, CONCURRENCY_STALE_MAX_MS / 1000));
+ }
+ await Promise.all(puts);
+ } catch {
+ /* best-effort: the next create pays the read, exactly as it does today */
+ }
+}
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 7697b0bc..84eb94e2 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -30,6 +30,20 @@ export { PoolStock } from "./pool_stock";
// touching web/ or edge code) can't reset the DOs and sever the host-dialed
// VM WebSockets.
import { coloGet, coloPut } from "./colo_cache";
+import {
+ ACTIVE_CELLS_SQL,
+ CELL_STALE_MAX_MS,
+ CELL_TTL_MS,
+ CONCURRENCY_COUNT_TTL_MS,
+ CONCURRENCY_STALE_MAX_MS,
+ ORG_POLICY_SQL,
+ ORG_POLICY_TTL_MS,
+ ORG_STALE_MAX_MS,
+ RUNNING_COUNT_SQL,
+ keepCreateContextWarm,
+ type CellRow,
+ type OrgPolicy,
+} from "./create_context_cache";
import { handleDashboard, type DashboardEnv } from "./dashboard";
import {
AGENT_SECURITY_NOTIFICATION_PATH,
@@ -362,10 +376,8 @@ function stripApiKeyQueryParam(target: string): string {
// 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;
-const ORG_POLICY_TTL_MS = 5_000; // short: bounds is_halted / cap staleness
// 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 ORG_STALE_MAX_MS = 60_000;
const LAST_USED_BUMP_MS = 60_000; // at most once/min/key/isolate
const CACHE_MAX = 10_000;
@@ -383,11 +395,9 @@ const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: n
// short window so a burst fires ~one COUNT/isolate/window instead of one per
// create. Under burst the cached value reads low (index lag), so it stays
// permissive — no spurious 429s.
-const CONCURRENCY_COUNT_TTL_MS = 1_500;
// Optimistic-gate stale window + headroom: a count up to 30s old may gate a
// create IF it sits at least HEADROOM below the org's limit (see
// loadCreateContext). Bounds the worst-case cap overshoot to ~HEADROOM boxes.
-const CONCURRENCY_STALE_MAX_MS = 30_000;
const CONCURRENCY_STALE_HEADROOM = 8;
const concurrencyCountCache = new Map<string, { count: number; cachedAtMs: number }>();
// Sandbox → owning-cell route. proxyToCellSDK otherwise pays a blocking D1
@@ -507,21 +517,10 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {
return caller;
}
-interface CellRow {
- cell_id: string;
- cloud: string;
- region: string;
- base_url: string;
- status: string;
- available_workers: number;
- capacity_updated_at: number | null;
-}
-
// Cell rows are semi-static (base_url is fixed; capacity refreshes ~30s and
// isHealthy already tolerates 120s staleness). Every create AND every exec/
// sub-op resolves the cell — a burst does 100 identical reads for the same 1-2
// cells. Cache per-isolate for a short window.
-const CELL_TTL_MS = 5_000;
const cellCache = new Map<string, { cell: CellRow | null; cachedAtMs: number }>();
// Per-isolate cache of the active-cells list. pickCell ran this SELECT uncached
// on every no-cellId create — ~65ms of the burst prework. Cells change rarely,
@@ -622,7 +621,7 @@ async function loadCreateContextUncoalesced(
if (ctx) {
ctx.waitUntil(
env.OPENCOMPUTER_DB.prepare(
- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",
+ ORG_POLICY_SQL,
)
.bind(orgID)
.first<OrgPolicy>()
@@ -648,6 +647,33 @@ async function loadCreateContextUncoalesced(
cells = scl.cells;
cellsHave = true;
activeCellsCache = { cells: scl.cells, cachedAtMs: scl.cachedAtMs };
+ } else if (scl && scl.cells.length > 0 && nowMs - scl.cachedAtMs < CELL_STALE_MAX_MS) {
+ // Stale-while-revalidate, mirroring the org-policy gate above. Only ever
+ // from a NON-EMPTY snapshot: serving a stale empty list would 503 every
+ // create in this colo for the length of the stale window, which is a
+ // strictly worse failure than routing on slightly old capacity numbers.
+ cells = scl.cells;
+ cellsHave = true;
+ activeCellsCache = { cells: scl.cells, cachedAtMs: scl.cachedAtMs };
+ if (ctx) {
+ ctx.waitUntil(
+ env.OPENCOMPUTER_DB.prepare(
+ ACTIVE_CELLS_SQL,
+ )
+ .all<CellRow>()
+ .then(async ({ results }) => {
+ const fresh = results ?? [];
+ // An empty read here is far more likely to be a blip than a fleet
+ // with no active cells, and caching it would take the colo down
+ // for the whole window. Leave the last good list in place.
+ if (fresh.length === 0) return;
+ const at = Date.now();
+ activeCellsCache = { cells: fresh, cachedAtMs: at };
+ await coloPut("cells", "active", { cells: fresh, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000);
+ })
+ .catch(() => {}),
+ );
+ }
}
}
@@ -666,7 +692,7 @@ async function loadCreateContextUncoalesced(
activeCount = staleCount.count;
cntHave = true;
const refresh = env.OPENCOMPUTER_DB.prepare(
- "SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'",
+ RUNNING_COUNT_SQL,
)
.bind(orgID)
.first<{ n: number }>()
@@ -691,21 +717,21 @@ async function loadCreateContextUncoalesced(
if (!orgWarm2) {
stmts.push(
env.OPENCOMPUTER_DB.prepare(
- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",
+ ORG_POLICY_SQL,
).bind(orgID),
);
kinds.push("org");
}
if (!cntWarm2) {
stmts.push(
- env.OPENCOMPUTER_DB.prepare("SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'").bind(orgID),
+ env.OPENCOMPUTER_DB.prepare(RUNNING_COUNT_SQL).bind(orgID),
);
kinds.push("count");
}
if (!cellsWarm2) {
stmts.push(
env.OPENCOMPUTER_DB.prepare(
- "SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at FROM cells WHERE status = 'active'",
+ ACTIVE_CELLS_SQL,
),
);
kinds.push("cells");
@@ -728,7 +754,10 @@ async function loadCreateContextUncoalesced(
} else {
cells = (res[i].results as CellRow[]) ?? [];
activeCellsCache = { cells, cachedAtMs: nowMs };
- puts.push(coloPut("cells", "active", { cells, cachedAtMs: nowMs }, CELL_TTL_MS / 1000));
+ // Entry TTL is the STALE window, not CELL_TTL_MS: an entry that expires
+ // at 5s can never be served stale, which is the whole point of the
+ // branch above. Freshness is decided by cachedAtMs on read.
+ puts.push(coloPut("cells", "active", { cells, cachedAtMs: nowMs }, CELL_STALE_MAX_MS / 1000));
}
}
await Promise.all(puts);
@@ -930,19 +959,6 @@ async function handlePreviewURL(
// orgs.runtime that routes an org's creates to the AWS MicroVM backend.
const RUNTIME_MICROVM = "microvm";
-interface OrgPolicy {
- home_cell: string;
- plan: string;
- is_halted: number;
- max_concurrent_sandboxes: number;
- max_disk_mb: number;
- billing_provider: string;
- // Which sandbox runtime this org's creates belong on. NULL/"" is the QEMU
- // fleet — so every org that predates this column keeps its current runtime
- // and opting one in is a single-row change.
- runtime: string | null;
-}
-
// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null
// when the org doesn't exist (callers 401).
async function loadOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null> {
@@ -950,7 +966,7 @@ async function loadOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null>
const cached = orgPolicyCache.get(orgID);
if (cached && nowMs - cached.cachedAtMs < ORG_POLICY_TTL_MS) return cached.policy;
const policy = await env.OPENCOMPUTER_DB.prepare(
- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1",
+ ORG_POLICY_SQL,
)
.bind(orgID)
.first<OrgPolicy>();
@@ -4421,6 +4437,10 @@ export default {
const caller = await authenticate(req, env);
const authMs = Date.now() - tAuth;
if (!caller) return json({ error: "missing or invalid API key" }, 401);
+ // Exec/delete traffic is what keeps an org's create-context entries warm
+ // in THIS colo between its bursts. Off the hot path (waitUntil) and a
+ // no-op unless an entry is actually aging.
+ keepCreateContextWarm(env.OPENCOMPUTER_DB, ctx, caller.orgID);
// VM-DO exec fast path: route POST /:id/exec/run-async through the
// sandbox's VmSession DO. Automatic tunnel fallback (no flag) whenever the
// channel isn't live (DO 409) — so this is safe even before/while workers
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 1e85f590..85501e72 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -34,6 +34,8 @@ interface StockEntry {
port?: number;
}
+import { WARM_ORG_LIMIT, warmCreateContextColo } from "./create_context_cache";
+
interface PoolStockEnv {
SESSION_JWT_SECRET: string;
// Per-shard stock sizing, overridable per environment (wrangler.toml [vars]).
@@ -52,6 +54,21 @@ interface PoolStockEnv {
// box from the create isolate, and — more importantly — would lose the race
// against the customer's first exec.
MICROVM_SESSIONS?: DurableObjectNamespace;
+ // Read-only here, and only from the alarm: the shard refreshes the colo-cache
+ // entries the create path reads (see warmCreateContextColo) so a cold burst
+ // finds them already populated instead of 100 isolates all missing at once.
+ // Optional so a binding-less deployment just skips the warm.
+ OPENCOMPUTER_DB?: D1Database;
+ // Org ids (comma-separated) whose create-context entries are kept warm
+ // ALWAYS, not just while they are actively claiming.
+ //
+ // recentOrgs alone cannot cover the case this exists for. A benchmark org is
+ // silent for an hour and then fires 100 concurrent creates — by then the
+ // shard has idle-decommissioned and its alarm has lapsed, so nothing has
+ // refreshed the colo entries and every one of those 100 isolates misses
+ // together. Pinning the org keeps the ~1 D1 batch per shard per tick running
+ // through the quiet period so the burst lands on a warm cache.
+ WARM_ORG_IDS?: string;
}
// Stock tuning. TARGET_STOCK mirrors ~the whole per-cell hot pool so every
@@ -90,6 +107,15 @@ const RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls
// after a placement mistake) drain instead of hoarding reservations forever,
// and returns idle cells' boxes to the pool for non-default-shape creates.
const IDLE_DECOMMISSION_MS = 30 * 60_000;
+// Cadence for the warm-only tick once the stock has been decommissioned. Slower
+// than ALARM_INTERVAL_MS because nothing is being restocked, but still inside
+// the shortest window it refreshes (count/cells, 30s) so an entry never lapses.
+const IDLE_WARM_INTERVAL_MS = 20_000;
+// Hard stop for warm-only ticking. A shard idle this long is not between bursts,
+// it is out of service, and warming it is pure cost.
+const WARM_MAX_IDLE_MS = 6 * 3600_000;
+// Warmed before traffic teaches a shard who to warm. Overridden by WARM_ORG_IDS.
+const DEFAULT_WARM_ORG_IDS = "1f92e6ca-fe5d-4cf4-ab3e-00fa7bedef4f";
// Synthetic org that owns parked pool boxes (db.PoolOrgID). Used as the cap
// token subject for reserve/release calls — those endpoints are org-agnostic,
@@ -194,6 +220,13 @@ 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;
+ // Orgs that have recently claimed through this shard, most-recent first.
+ // The alarm refreshes their create-context colo entries; whoever is actually
+ // bursting through this shard is exactly who benefits from a warm cache, and
+ // the list is capped so this can't grow into a scan of every org that ever
+ // touched it. Persisted so a shard re-created after eviction warms the right
+ // orgs on its FIRST alarm rather than after the next claim.
+ private recentOrgs: string[] = [];
// The control-plane process that issued the stock we are holding, when that
// cell's reservations are process-local (see edge_claim.go processEpoch).
// Persisted alongside the stock because it is only meaningful paired with it.
@@ -220,6 +253,7 @@ export class PoolStock {
this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];
this.cell = (await this.state.storage.get<{ cellID: string; baseURL: string }>("cell")) ?? null;
this.epoch = (await this.state.storage.get<string>("epoch")) ?? null;
+ this.recentOrgs = (await this.state.storage.get<string[]>("recentOrgs")) ?? [];
});
}
@@ -328,6 +362,7 @@ export class PoolStock {
}
if (!orgID) return new Response(JSON.stringify({ error: "orgID required" }), { status: 400 });
if (cell) this.rememberCell(cell);
+ this.rememberOrg(orgID);
// Same inline stale-expiry as claim(), synchronous over the in-memory array
// so a concurrent claim can't double-pop across an await.
@@ -382,6 +417,43 @@ export class PoolStock {
void this.state.storage.put("cell", cell);
}
+ // rememberOrg moves an org to the front of the warm list. Only persists when
+ // the ORDER actually changed — a burst is thousands of claims from the same
+ // org, and writing storage on each one would add a disk write to the hottest
+ // path this DO has for information that did not change.
+ private rememberOrg(orgID: string): void {
+ if (this.recentOrgs[0] === orgID) return;
+ this.recentOrgs = [orgID, ...this.recentOrgs.filter((o) => o !== orgID)].slice(0, WARM_ORG_LIMIT);
+ void this.state.storage.put("recentOrgs", this.recentOrgs, { allowUnconfirmed: true });
+ }
+
+ // warmOrgs is who this shard refreshes: configured pins first, then the orgs
+ // that have actually claimed here. Pins exist so a shard that has never served
+ // a claim — a fresh deploy, a re-placed shard — still warms something useful;
+ // in steady state recentOrgs is what carries this.
+ private warmOrgs(): string[] {
+ const pinned = (this.env.WARM_ORG_IDS ?? DEFAULT_WARM_ORG_IDS)
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const id of [...pinned, ...this.recentOrgs]) {
+ if (seen.has(id)) continue;
+ seen.add(id);
+ out.push(id);
+ }
+ return out.slice(0, WARM_ORG_LIMIT);
+ }
+
+ private async warmColo(): Promise<void> {
+ const db = this.env.OPENCOMPUTER_DB;
+ if (!db) return;
+ const orgs = this.warmOrgs();
+ if (orgs.length === 0) return;
+ await warmCreateContextColo(db, orgs);
+ }
+
private async ensureAlarm(): Promise<void> {
if ((await this.state.storage.getAlarm()) === null) {
await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
@@ -395,16 +467,31 @@ export class PoolStock {
async alarm(): Promise<void> {
const cell = this.cell;
if (!cell) return; // no cell known yet → nothing to reserve; a claim will arm it
- // Idle self-decommission (see IDLE_DECOMMISSION_MS): release everything and
- // let the alarm lapse. A future claim re-arms and restocks.
+ // Idle self-decommission (see IDLE_DECOMMISSION_MS): release the stock, but
+ // keep the cheap half of the tick running.
+ //
+ // Stock and cache warmth decommission on different schedules because they
+ // cost different things. Held boxes are real capacity another shard could
+ // use, so they go back immediately. The create-context colo entries cost one
+ // D1 batch per tick and holding them is what makes a bursty-after-idle
+ // tenant — CI, crons, agent workloads, a weekly benchmark — land on a warm
+ // cache instead of having ~100 isolates all miss at once. Dropping both
+ // together is what made the first create after a quiet period the most
+ // expensive one a customer ever sees.
const lastClaim = this.lastClaimMs || ((await this.state.storage.get<number>("lastClaim")) ?? 0);
- if (Date.now() - lastClaim > IDLE_DECOMMISSION_MS) {
+ const idleMs = Date.now() - lastClaim;
+ if (idleMs > IDLE_DECOMMISSION_MS) {
if (this.stock.length > 0) {
const all = this.stock.splice(0);
await this.release(all);
this.persist();
}
- return; // no reschedule — decommissioned until the next claim
+ // Past WARM_MAX_IDLE_MS nobody is coming back and this stops entirely —
+ // otherwise a shard that served one create last month would warm forever.
+ if (idleMs > WARM_MAX_IDLE_MS || this.warmOrgs().length === 0) return;
+ await this.warmColo();
+ await this.state.storage.setAlarm(Date.now() + IDLE_WARM_INTERVAL_MS);
+ return;
}
// Expire+release anything past TTL before topping up, so held boxes go back
// to the pool well before the cell's 15-min destroy backstop.
@@ -424,6 +511,14 @@ export class PoolStock {
}
if (this.stock.length < this.targetStock) await this.restockToTarget(cell);
this.persist();
+ // Keep the create path's colo entries warm. Ordered AFTER the top-up on
+ // purpose: stock is what a create cannot proceed without, and this is a
+ // latency optimization — it must never delay or fail the restock. The 10s
+ // cadence sits inside every window it refreshes (cells 30s, count 30s, org
+ // 60s), so an entry written here is always current when the next burst
+ // lands, and the shard is placed in-metro with the traffic it serves, so
+ // the colo it warms is the colo that will read it.
+ await this.warmColo();
// 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
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 17290bed..7318ee98 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.1",
+ "version": "0.15.2",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",