Skip to content

An open-source, faster Devin alternative

TypeScript

route creates by the calling SDK's major instead of a D1 row — @opencomputer/sdk 1.x lands on MicroVM, every published 0.x stays on QEMU, and orgs.runtime becomes a pin that overrides both, so a customer migrates by upgrading the package and rolls back by pinning the old major without us touching anything; also carries the same decision through the snapshot path (a template built on the wrong runtime is unusable) and routes exec by the sandbox's own worker_id rather than its org's runtime, because SDK routing makes a mixed org the steady state

Brian Reardonb3eec96911f7
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index b2f09471..ab65ebab 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -31,6 +31,12 @@ import { mintPoolCapToken } from "./pool_stock";
// touching web/ or edge code) can't reset the DOs and sever the host-dialed
// VM WebSockets.
import { coloDelete, coloGet, coloPut } from "./colo_cache";
+import {
+ RUNTIME_MICROVM,
+ SDK_VERSION_HEADER,
+ effectiveRuntime,
+ isMicrovmWorkerID,
+} from "./runtime_gate";
import {
ACTIVE_CELLS_SQL,
CELL_STALE_MAX_MS,
@@ -98,6 +104,12 @@ export interface Env extends DashboardEnv {
// secret (whsec_…) for /webhooks/autumn. AUTUMN_SECRET_KEY / AUTUMN_BASE_URL
// are inherited from DashboardEnv. Unset on deployments not yet on Autumn.
AUTUMN_WEBHOOK_SECRET: string;
+ // SDK-version routing (see runtime_gate.ts). SDK_RUNTIME_GATE="0" pins every
+ // unpinned org back to QEMU — the kill switch for self-service migration,
+ // without touching any org row. SDK_RUNTIME_MIN_MAJOR overrides the major at
+ // which an SDK counts as v2 (default 2).
+ SDK_RUNTIME_GATE?: string;
+ SDK_RUNTIME_MIN_MAJOR?: string;
// HMAC secret used by Browser API to submit runtime usage. Falls back to
// EVENT_SECRET in the handler when unset for compatibility during rollout.
BROWSER_USAGE_HMAC_SECRET?: string;
@@ -462,7 +474,7 @@ const concurrencyCountCache = new Map<string, { count: number; cachedAtMs: numbe
// dropped on DELETE and bounded by CACHE_MAX + isolate recycling. Populated at
// create, which also closes the same-isolate race where a sub-op lands before
// the waitUntil-deferred insertSandboxIndex write does. Never caches misses.
-const sandboxRouteCache = new Map<string, { cellID: string; orgID: string }>();
+const sandboxRouteCache = new Map<string, SandboxRoute>();
// The route is immutable for a sandbox's lifetime, but a destroyed sandbox's
// entry can linger — same semantics as the isolate Map (the cell 404s). 15 min
@@ -491,16 +503,35 @@ interface MvmReach {
// SDK's create → exec shape: the exec routinely lands on a different isolate
// than the create that seeded the Map, and this read is the exec path's only
// blocking D1 dependency.
-async function resolveSandboxRoute(env: Env, id: string): Promise<{ cellID: string; orgID: string } | null> {
+// `microvm` records which RUNTIME this sandbox landed on.
+//
+// It has to be per-sandbox. Routing a live sandbox by its ORG's runtime was
+// correct only while an org was entirely on one runtime; once creates are routed
+// by SDK version (runtime_gate.ts) a mixed org is the steady state rather than a
+// migration window, and the same org has QEMU sandboxes from one service and
+// MicroVM sandboxes from another for as long as the migration takes.
+//
+// `undefined` means UNKNOWN, not "no" — a route cached by an older deployment,
+// or a row whose worker_id is not written yet. Callers must fall back to the org
+// policy there rather than reading it as QEMU, or a MicroVM box would be sent to
+// a Durable Object that can never hold a channel for it.
+type SandboxRoute = { cellID: string; orgID: string; microvm?: boolean };
+
+async function resolveSandboxRoute(env: Env, id: string): Promise<SandboxRoute | null> {
const warm = sandboxRouteCache.get(id);
if (warm) return warm;
- let route = await coloGet<{ cellID: string; orgID: string }>("route", id);
+ let route = await coloGet<SandboxRoute>("route", id);
if (!route) {
- const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id, worker_id FROM sandboxes_index WHERE id = ?1")
.bind(id)
- .first<{ cell_id: string; org_id: string }>();
+ .first<{ cell_id: string; org_id: string; worker_id: string | null }>();
if (!row) return null;
route = { cellID: row.cell_id, orgID: row.org_id };
+ // Only claim to know when worker_id is actually populated. A create still in
+ // flight has none, and this entry has no TTL in the isolate map — writing
+ // "not MicroVM" from a blank column would pin that wrong answer for the life
+ // of the isolate.
+ if (row.worker_id) route.microvm = isMicrovmWorkerID(row.worker_id);
await coloPut("route", id, route, ROUTE_COLO_TTL_SEC);
}
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
@@ -1231,10 +1262,6 @@ async function handlePreviewURL(
// ── route handlers ───────────────────────────────────────────────────────
-// OrgPolicy is the subset of the D1 `orgs` row the create/fork paths gate on.
-// Mirrors runtimeMicrovm in internal/api/backend.go — the value stored in
-// orgs.runtime that routes an org's creates to the AWS MicroVM backend.
-const RUNTIME_MICROVM = "microvm";
// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null
// when the org doesn't exist (callers 401).
@@ -2005,6 +2032,15 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
);
if (!org) return json({ error: "org not found" }, 401);
const plan = org.plan === "pro" ? "pro" : "free";
+ // Which runtime this create lands on. orgs.runtime is a PIN; when it is unset
+ // the calling SDK's major decides, so upgrading @opencomputer/sdk to 1.x IS
+ // the migration and pinning the old major is the rollback. See runtime_gate.ts.
+ //
+ // Resolved once, here, and used for every runtime decision below — the
+ // edge-claim gate, the finalize message, and the capability token the cell
+ // reads its backend off. Reading org.runtime directly at any of those points
+ // again would route the create one way and label it another.
+ const runtime = effectiveRuntime(env, org.runtime, req.headers.get(SDK_VERSION_HEADER));
// Read body once — used for size-gating, the hard-pin cell peek, and the
// verbatim forward to the CP.
@@ -2106,7 +2142,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
const edgeClaimOn =
env.EDGE_CLAIM !== "0" &&
- !(org.runtime === RUNTIME_MICROVM && env.MICROVM_EDGE_CLAIM === "0");
+ !(runtime === RUNTIME_MICROVM && env.MICROVM_EDGE_CLAIM === "0");
if (edgeClaimOn && env.POOL_STOCK && edgeClaimEligible(bodyText, parsedBody)) {
try {
// Sharded stock (see pool_stock.ts): a single DO serializes burst claims
@@ -2134,7 +2170,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
phases.push(`dotry;dur=${claimed.attempts}`);
const token = box.token;
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });
+ sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID, microvm: isMicrovmWorkerID(box.workerID) });
// Seed the colo-shared route so the first exec — which usually lands on
// a different isolate — skips its blocking D1 route read. waitUntil is
// race-safe here: the client can't send that exec until the 201 crosses
@@ -2152,9 +2188,16 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
// TTL is the reach TTL (the longer of the two). resolveRoute's own put
// writes this key without `reach`; that costs the next exec one cell
// lookup and then self-heals via the mvmreach put on the exec path.
- const routeEntry: { cellID: string; orgID: string; reach?: MvmReach } = {
+ const routeEntry: SandboxRoute & { reach?: MvmReach } = {
cellID: cell.cell_id,
orgID: caller.orgID,
+ // Recorded at birth so the first exec never has to guess. Without it
+ // the first exec on a freshly-created MicroVM box reads an unknown
+ // route, falls back to the org policy — which for an org migrating by
+ // SDK version says nothing — and pays the VmSession DO's 400ms entry
+ // grace before giving up. That is the whole latency this routing
+ // exists to avoid, on the one request most likely to be measured.
+ microvm: isMicrovmWorkerID(box.workerID),
};
if (box.agentEndpoint && box.agentToken && box.agentPort) {
routeEntry.reach = { endpoint: box.agentEndpoint, token: box.agentToken, port: box.agentPort };
@@ -2215,7 +2258,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
baseURL: cell.base_url,
plan,
billingProvider: org.billing_provider,
- runtime: org.runtime ?? "",
+ runtime,
sandboxID: box.id,
workerID: box.workerID,
bodyText,
@@ -2224,11 +2267,11 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
env.FINALIZE_QUEUE.send(msg).catch((e) => {
// Enqueue failed — finalize inline so the box still binds.
console.error(`edge-claim: finalize enqueue failed for ${box.id}, running inline:`, e);
- return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, org.runtime ?? "", box.id, box.workerID, bodyText);
+ return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText);
}),
);
} else {
- ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, org.runtime ?? "", box.id, box.workerID, bodyText));
+ ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText));
}
// Total in-handler wall time. With `pre`, the client's own measurement
// splits three ways: pre (getting here) + hdl (this handler) + the rest
@@ -2253,7 +2296,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
// CP fallback from here on — mint the cap-token the cell requires (the
// edge-claim path above returns without ever needing it).
- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);
+ const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, runtime, caller.userID);
mark("capmint");
// SSE build streaming: image/snapshot creates can take minutes (apt installs,
@@ -2313,8 +2356,12 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop
// the sandboxes_index read — and don't race the deferred insert below.
if (parsed.sandboxID) {
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- sandboxRouteCache.set(parsed.sandboxID, { cellID: cell.cell_id, orgID: caller.orgID });
- ctx.waitUntil(coloPut("route", parsed.sandboxID, { cellID: cell.cell_id, orgID: caller.orgID }, ROUTE_COLO_TTL_SEC));
+ // `runtime` is the decision THIS handler just made and the cell just
+ // acted on, so it is authoritative here — more so than worker_id, which
+ // the sandboxes_index row may not carry yet.
+ const seeded: SandboxRoute = { cellID: cell.cell_id, orgID: caller.orgID, microvm: runtime === RUNTIME_MICROVM };
+ sandboxRouteCache.set(parsed.sandboxID, seeded);
+ ctx.waitUntil(coloPut("route", parsed.sandboxID, seeded, ROUTE_COLO_TTL_SEC));
}
// Off the response path (see indexSandboxFromSSE) — waitUntil keeps the D1
// write alive after we return; events-ingest reconciles the row anyway.
@@ -2539,10 +2586,26 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
// backend cannot have. Measured on prod: that grace was ~437ms of every
// MicroVM exec — 79% of benchmark TTI, against a control plane that served
// the exec itself in 10ms. Skip straight to the tunnel.
- const tPol = Date.now();
- const orgPolicy = await loadOrgPolicy(env, caller.orgID, ctx);
- const polMs = Date.now() - tPol;
- if (orgPolicy?.runtime === RUNTIME_MICROVM) {
+ //
+ // Asked of the SANDBOX, not the org. Creates are routed by the calling SDK's
+ // version (runtime_gate.ts), so one org runs sandboxes on both runtimes for as
+ // long as its migration takes, and "this org is on MicroVM" no longer answers
+ // "is this box on MicroVM". The route carries the answer and usually already
+ // has it cached; the org policy is only consulted when the route predates this
+ // field or the row has no worker_id yet.
+ const tRt = Date.now();
+ const rt = await resolveSandboxRoute(env, id);
+ let polMs = Date.now() - tRt;
+ if (!rt) return json({ error: "sandbox not found" }, 404);
+ if (rt.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+ let microvm = rt.microvm;
+ if (microvm === undefined) {
+ const tPol = Date.now();
+ const orgPolicy = await loadOrgPolicy(env, caller.orgID, ctx);
+ polMs += Date.now() - tPol;
+ microvm = orgPolicy?.runtime === RUNTIME_MICROVM;
+ }
+ if (microvm) {
// MICROVM_EDGE_EXEC=0 hands exec to the cell, skipping BOTH Durable
// Objects.
//
@@ -2561,11 +2624,9 @@ async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller
if (env.MICROVM_EDGE_EXEC === "0") return fallback(fall, "cell-owns-exec");
return tryMicrovmDirectExec(req, env, ctx, caller, id, authMs, polMs, fall);
}
- const tRoute = Date.now();
- const route = await resolveSandboxRoute(env, id);
- const routeMs = Date.now() - tRoute;
- if (!route) return json({ error: "sandbox not found" }, 404);
- if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+ // Resolved and authorized above — the runtime question needed it first.
+ const route = rt;
+ const routeMs = 0;
try {
// clone() so the original request body stays readable for the tunnel
// fallback when the DO reports the channel isn't connected.
@@ -3185,7 +3246,11 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// gives up — bounded, but pointless work against AWS for every destroy.
// MicroVM only: other runtimes have no MicrovmSession, and asking for one
// by id would instantiate a Durable Object just to tear it down.
- if (env.MICROVM_SESSIONS && orgPol?.runtime === RUNTIME_MICROVM) {
+ // Per-SANDBOX, for the same reason as tryVmDoExec: a mixed org is normal
+ // once creates are routed by SDK version. `route.microvm` is undefined only
+ // for a route cached before the field existed, where the org policy is the
+ // best remaining answer.
+ if (env.MICROVM_SESSIONS && (route.microvm ?? orgPol?.runtime === RUNTIME_MICROVM)) {
const ns = env.MICROVM_SESSIONS;
ctx.waitUntil(
ns
@@ -3302,17 +3367,24 @@ async function proxyToCellAuthed(
opts: { cellId?: string; pathOverride?: string } = {},
): Promise<Response> {
const org = await env.OPENCOMPUTER_DB.prepare(
- "SELECT home_cell, plan FROM orgs WHERE id = ?1",
- ).bind(caller.orgID).first<{ home_cell: string; plan: string }>();
+ "SELECT home_cell, plan, runtime FROM orgs WHERE id = ?1",
+ ).bind(caller.orgID).first<{ home_cell: string; plan: string; runtime: string | null }>();
if (!org) return json({ error: "org not found" }, 401);
const plan = org.plan === "pro" ? "pro" : "free";
+ // POST /api/snapshots comes through here, and a template is built DIFFERENTLY
+ // per runtime — a whole-disk checkpoint on QEMU, a machine image on MicroVM.
+ // Minting a blank runtime (what this did) meant a 1.x SDK's sandboxes went to
+ // MicroVM while its templates were built as checkpoints MicroVM cannot
+ // restore: a customer would migrate successfully and then find every template
+ // they built unusable. Same decision, same inputs as createSandbox.
+ const runtime = effectiveRuntime(env, org.runtime, req.headers.get(SDK_VERSION_HEADER));
const cell = opts.cellId
? await lookupCell(env, opts.cellId)
: await pickCell(env, org.home_cell, null);
if (!cell) return json({ error: "no cell available to serve request" }, 503);
- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", "", caller.userID);
+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", runtime, caller.userID);
const url = new URL(req.url);
const target = cell.base_url.replace(/\/$/, "") + (opts.pathOverride ?? url.pathname) + url.search;
@@ -5406,6 +5478,11 @@ export default {
const fcGate = await enforceCreatePolicy(env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);
if (fcGate) return fcGate;
const plan = org.plan === "pro" ? "pro" : "free";
+ // org.runtime, deliberately NOT the SDK-version routing createSandbox
+ // uses. A fork restores a checkpoint, and only the QEMU fleet produces
+ // checkpoints — routing a fork by the caller's SDK version would send it
+ // to a runtime that has nothing to restore. It follows the org's pin or
+ // nothing, exactly as before.
const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);
const fcResp = await fetch(cell.base_url.replace(/\/$/, "") + path, {
method: "POST",
diff --git a/cloudflare-workers/api-edge/src/runtime_gate.test.ts b/cloudflare-workers/api-edge/src/runtime_gate.test.ts
new file mode 100644
index 00000000..e8212824
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/runtime_gate.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect } from "vitest";
+import {
+ RUNTIME_MICROVM,
+ RUNTIME_QEMU,
+ effectiveRuntime,
+ isMicrovmWorkerID,
+ sdkMajor,
+} from "./runtime_gate";
+
+const on = {}; // gate enabled, default threshold
+const off = { SDK_RUNTIME_GATE: "0" };
+
+// The cutoff is the package's first stable major, not the "v2" the docs use for
+// the platform generation. Every version ever published is 0.x.
+const NEW = "1.0.0";
+const OLD = "0.15.7";
+
+describe("sdkMajor", () => {
+ it("reads the major", () => {
+ expect(sdkMajor("2.0.0")).toBe(2);
+ expect(sdkMajor("10.4.1")).toBe(10);
+ expect(sdkMajor(" 2.1.0 ")).toBe(2);
+ });
+
+ // Everything unrecognisable is an SDK that does not announce itself, and that
+ // population must land on QEMU. A parse that fell through to "new runtime"
+ // would migrate every curl user and every old SDK at once.
+ it("is 0 for anything it cannot read", () => {
+ for (const bad of [null, undefined, "", " ", "v2", "abc", "-3", "0.1.0"]) {
+ expect(sdkMajor(bad)).toBe(0);
+ }
+ });
+});
+
+describe("effectiveRuntime", () => {
+ it("routes an unpinned org by the calling SDK — this is the migration", () => {
+ expect(effectiveRuntime(on, null, NEW)).toBe(RUNTIME_MICROVM);
+ expect(effectiveRuntime(on, "", NEW)).toBe(RUNTIME_MICROVM);
+ expect(effectiveRuntime(on, null, OLD)).toBe("");
+ expect(effectiveRuntime(on, null, null)).toBe("");
+ });
+
+ // Every 0.x release in npm's history has to land on QEMU. Getting this wrong
+ // migrates the entire existing customer base on the next deploy.
+ it("holds the whole published 0.x line on the fleet", () => {
+ for (const v of ["0.15.7", "0.15.0", "0.14.0", "0.13.1", "0.9.9", "0.0.1"]) {
+ expect(effectiveRuntime(on, null, v), v).toBe("");
+ }
+ });
+
+ // A migrated org must not be dragged back by one stale service still on an
+ // old SDK — its templates and checkpoints only exist on the runtime it moved
+ // to.
+ it("keeps a microvm-pinned org on microvm for old SDKs", () => {
+ expect(effectiveRuntime(on, RUNTIME_MICROVM, OLD)).toBe(RUNTIME_MICROVM);
+ expect(effectiveRuntime(on, RUNTIME_MICROVM, null)).toBe(RUNTIME_MICROVM);
+ });
+
+ // ...and the opt-out has to survive an upgrade, or an org that needs
+ // checkpoints loses them by bumping a dependency.
+ it("keeps a qemu-pinned org on qemu for new SDKs", () => {
+ expect(effectiveRuntime(on, RUNTIME_QEMU, NEW)).toBe(RUNTIME_QEMU);
+ });
+
+ // The token carries this value. Synthesising "qemu" for an org that never set
+ // it would have the token assert a decision nobody made.
+ it("never invents an explicit qemu for an unset org", () => {
+ expect(effectiveRuntime(on, null, OLD)).toBe("");
+ expect(effectiveRuntime(off, null, NEW)).toBe("");
+ });
+
+ it("SDK_RUNTIME_GATE=0 turns the whole thing off without touching pins", () => {
+ expect(effectiveRuntime(off, null, NEW)).toBe("");
+ expect(effectiveRuntime(off, RUNTIME_MICROVM, OLD)).toBe(RUNTIME_MICROVM);
+ });
+
+ it("honours a configured threshold", () => {
+ const env = { SDK_RUNTIME_MIN_MAJOR: "3" };
+ expect(effectiveRuntime(env, null, "2.9.0")).toBe("");
+ expect(effectiveRuntime(env, null, "3.0.0")).toBe(RUNTIME_MICROVM);
+ // Garbage falls back to the default rather than to 0, which would route
+ // EVERY versioned SDK to microvm.
+ expect(effectiveRuntime({ SDK_RUNTIME_MIN_MAJOR: "junk" }, null, OLD)).toBe("");
+ expect(effectiveRuntime({ SDK_RUNTIME_MIN_MAJOR: "junk" }, null, NEW)).toBe(RUNTIME_MICROVM);
+ });
+});
+
+describe("isMicrovmWorkerID", () => {
+ it("recognises both prefixes internal/api/microvm_common.go writes", () => {
+ expect(isMicrovmWorkerID("vmhost:microvm-abc123")).toBe(true);
+ expect(isMicrovmWorkerID("microvm:abc123")).toBe(true);
+ });
+
+ it("does not claim a QEMU worker or an unknown row", () => {
+ for (const other of ["worker-eastus2-3", "oc-worker-01", "", null, undefined]) {
+ expect(isMicrovmWorkerID(other)).toBe(false);
+ }
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/runtime_gate.ts b/cloudflare-workers/api-edge/src/runtime_gate.ts
new file mode 100644
index 00000000..d2e5a7c8
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/runtime_gate.ts
@@ -0,0 +1,130 @@
+// Which runtime serves a create, and how a customer moves between them.
+//
+// Before this, the answer was one D1 column: orgs.runtime, set by us, one org
+// at a time. That works for a handful of design partners and does not work for
+// a migration — every customer who wants to move has to ask, and every customer
+// we move has to be moved back by hand if it goes badly.
+//
+// So the column now expresses a PIN, and the calling SDK's major version
+// decides for everyone who is not pinned:
+//
+// orgs.runtime = 'microvm' -> MicroVM, whatever SDK is calling
+// orgs.runtime = 'qemu' -> QEMU, whatever SDK is calling
+// orgs.runtime NULL or '' -> the SDK decides: 1.x+ MicroVM, 0.x QEMU
+//
+// The unpinned case is the new one and it is the whole point: `npm i
+// @opencomputer/sdk@1` is the migration, and pinning the previous major is the
+// rollback. Neither needs us.
+//
+// The pins are not vestigial. 'microvm' is how an org that has FINISHED
+// migrating stays migrated even when one script in their fleet is still on an
+// old version — without it, a single stale dependency would quietly start
+// creating sandboxes on the other runtime, against templates that do not exist
+// there. 'qemu' is the opt-out for an org that needs something MicroVM does not
+// have yet (checkpoints, fork) and should not be moved by upgrading a package.
+
+/**
+ * Header the SDK sends its own version in (sdks/typescript/src/version.ts).
+ * Duplicated rather than imported: the Worker does not depend on the SDK
+ * package, and runtime_gate.test.ts pins the string on this side.
+ */
+export const SDK_VERSION_HEADER = "x-oc-sdk-version";
+
+/** orgs.runtime value routing to the AWS MicroVM backend. */
+export const RUNTIME_MICROVM = "microvm";
+
+/** orgs.runtime value pinning an org to the QEMU worker fleet. */
+export const RUNTIME_QEMU = "qemu";
+
+/**
+ * Default major at which an SDK routes to MicroVM.
+ *
+ * 1, because every version @opencomputer/sdk has ever published is 0.x — so the
+ * first stable release is also, for free, an exact split between "everything
+ * that exists today" and "the new one". The docs call this platform generation
+ * v2; the package major is 1. They are not the same number and nothing here
+ * should assume they are.
+ *
+ * Overridable (SDK_RUNTIME_MIN_MAJOR) because the version this ships under is a
+ * release decision that can change after this code is written, and getting it
+ * wrong should cost an env var rather than a re-release of the SDK.
+ */
+export const DEFAULT_MIN_SDK_MAJOR = 1;
+
+/**
+ * Major version from the SDK's x-oc-sdk-version header, or 0.
+ *
+ * 0 for absent, malformed, or non-numeric — every one of which means "an SDK
+ * that does not announce itself", which is exactly the population that must
+ * keep landing on QEMU. Unparseable input therefore has to fail toward the old
+ * runtime, never toward the new one.
+ */
+export function sdkMajor(header: string | null | undefined): number {
+ if (!header) return 0;
+ const major = Number.parseInt(header.trim().split(".")[0] ?? "", 10);
+ // A 0.x SDK reports 0, which is also what an unreadable header reports. That
+ // is deliberate and not a collision worth removing: both mean "not a caller we
+ // route to MicroVM", and the threshold is >= 1.
+ return Number.isFinite(major) && major > 0 ? major : 0;
+}
+
+export interface RuntimeGateEnv {
+ /** "0" disables SDK-version routing; every unpinned org stays on QEMU. */
+ SDK_RUNTIME_GATE?: string;
+ /** Major at and above which an SDK routes to MicroVM. Default 2. */
+ SDK_RUNTIME_MIN_MAJOR?: string;
+}
+
+function minMajor(env: RuntimeGateEnv): number {
+ const configured = Number.parseInt(env.SDK_RUNTIME_MIN_MAJOR ?? "", 10);
+ return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MIN_SDK_MAJOR;
+}
+
+/**
+ * The runtime this create belongs on: "microvm", "qemu", or "" (the QEMU
+ * fleet, unstated — what the cap token has always carried for an unset org).
+ *
+ * "" and "qemu" are both the fleet and are deliberately NOT collapsed: the
+ * value is echoed into the capability token, and rewriting an org's unset
+ * runtime to an explicit "qemu" would make the token claim a decision nobody
+ * made. Only the MicroVM answer is ever synthesised here.
+ */
+export function effectiveRuntime(
+ env: RuntimeGateEnv,
+ orgRuntime: string | null | undefined,
+ sdkVersionHeader: string | null | undefined,
+): string {
+ const pinned = (orgRuntime ?? "").trim();
+ if (pinned) return pinned; // pin wins, in both directions
+ if (env.SDK_RUNTIME_GATE === "0") return "";
+ return sdkMajor(sdkVersionHeader) >= minMajor(env) ? RUNTIME_MICROVM : "";
+}
+
+// ── which runtime an EXISTING sandbox is on ──────────────────────────────────
+
+// Prefixes internal/api/microvm_common.go writes into sandboxes_index.worker_id
+// (microvmWorkerPrefix and legacyWorkerPrefix). A sandbox's worker_id names the
+// box that holds it, so it is the only per-sandbox record of which runtime that
+// sandbox actually landed on — D1 has no runtime column on the sandbox row.
+const MICROVM_WORKER_PREFIXES = ["vmhost:", "microvm:"];
+
+/**
+ * Whether an existing sandbox is MicroVM-backed, from its worker_id.
+ *
+ * Routing a request for a LIVE sandbox by its org's runtime was correct only
+ * while an org was entirely on one runtime. Under SDK-version routing a mixed
+ * org is the steady state, not a migration window — the same org creates
+ * MicroVM sandboxes from a v2 service and QEMU sandboxes from a v1 one, for as
+ * long as the migration takes. Asking the sandbox rather than the org is what
+ * keeps both working: a QEMU box never gets dialled as if it had a MicroVM
+ * proxy, and a MicroVM box never pays the VmSession DO's 400ms entry grace
+ * waiting for a channel that cannot exist.
+ *
+ * `undefined` (worker_id not yet known — an in-flight create, or a route cached
+ * before this field was recorded) returns false, which routes through the
+ * generic path. That path works for both runtimes; it is merely slower.
+ */
+export function isMicrovmWorkerID(workerID: string | null | undefined): boolean {
+ if (!workerID) return false;
+ return MICROVM_WORKER_PREFIXES.some((p) => workerID.startsWith(p));
+}
diff --git a/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts b/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts
new file mode 100644
index 00000000..b8a6f7ec
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts
@@ -0,0 +1,195 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import worker, { type Env } from "./index";
+import { SDK_VERSION_HEADER } from "./runtime_gate";
+
+// runtime_gate.test.ts covers the decision. This covers the WIRING, which is
+// where the equivalent work has failed before: a rule that is correct in
+// isolation and simply never consulted on the path that matters. The assertion
+// is deliberately made on the capability token the cell actually reads its
+// backend off, not on any intermediate value.
+
+// A fresh org per case. loadCreateContext memoises the org row in a
+// module-level isolate cache that outlives a single test, so reusing one id
+// would have the second case read the first case's runtime.
+let seq = 0;
+let orgID = "org-0";
+let apiKey = "osb_test_0";
+function freshOrg(runtime: string | null): void {
+ seq += 1;
+ orgID = `org-${seq}`;
+ apiKey = `osb_test_${seq}`;
+ orgRuntime = runtime;
+}
+
+const cellID = "azure-us-east-2-a";
+const cellURL = "https://cp-us-east-2.opencomputer.dev";
+
+let orgRuntime: string | null = null;
+
+class FakeStatement {
+ constructor(private sql: string) {}
+ bind(..._args: unknown[]) {
+ return this;
+ }
+ async first<T>(): Promise<T | null> {
+ if (this.sql.includes("FROM api_keys")) {
+ return { org_id: orgID, created_by: "user-1", expires_at: null } as T;
+ }
+ if (this.sql.includes("FROM cells WHERE cell_id")) return cellRow<T>();
+ if (this.sql.includes("SELECT home_cell, plan, runtime FROM orgs")) {
+ return { home_cell: cellID, plan: "pro", runtime: orgRuntime } as T;
+ }
+ if (this.sql.includes("SELECT home_cell, plan, is_halted")) {
+ return {
+ home_cell: cellID,
+ plan: "pro",
+ is_halted: 0,
+ max_concurrent_sandboxes: 10,
+ max_disk_mb: 262144,
+ runtime: orgRuntime,
+ } as T;
+ }
+ if (this.sql.includes("COUNT(*) AS n FROM sandboxes_index")) return { n: 0 } as T;
+ return null;
+ }
+ async all<T>() {
+ if (this.sql.includes("FROM cells WHERE status = 'active'")) {
+ return { results: [await cellRow<T>()] } as { results: T[] };
+ }
+ return { results: [] as T[] };
+ }
+ async run() {
+ return {};
+ }
+ async batchResult<T>(): Promise<{ results: T[] }> {
+ if (this.sql.includes("WHERE status = 'active'")) return (await this.all<T>()) as { results: T[] };
+ const row = await this.first<T>();
+ return { results: row ? [row] : [] };
+ }
+}
+
+function cellRow<T>(): T {
+ return {
+ cell_id: cellID,
+ cloud: "azure",
+ region: "us-east-2",
+ base_url: cellURL,
+ status: "active",
+ available_workers: 1,
+ capacity_updated_at: Math.floor(Date.now() / 1000),
+ } as T;
+}
+
+function makeEnv(extra: Partial<Env> = {}): Env {
+ return {
+ OPENCOMPUTER_DB: {
+ prepare: (sql: string) => new FakeStatement(sql),
+ batch: async (stmts: FakeStatement[]) => Promise.all(stmts.map((s) => s.batchResult())),
+ },
+ SESSION_JWT_SECRET: "test-secret",
+ WORKER_ENV: "test",
+ // No POOL_STOCK binding: edge-claim is structurally unavailable, so the
+ // create takes the CP-fallback path and mints the cap token we assert on.
+ ...extra,
+ } as unknown as Env;
+}
+
+const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() } as unknown as ExecutionContext;
+
+/** The `runtime` claim from the Bearer token the edge sent the cell. */
+function runtimeClaim(headers: HeadersInit | undefined): string {
+ const auth = new Headers(headers).get("authorization") ?? "";
+ const payload = auth.replace(/^Bearer /, "").split(".")[1];
+ if (!payload) throw new Error(`no JWT in authorization header: ${auth}`);
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
+ return (JSON.parse(json).runtime as string) ?? "";
+}
+
+async function createWith(
+ sdkVersion: string | null,
+ opts: { runtime?: string | null; env?: Env } = {},
+): Promise<string> {
+ freshOrg(opts.runtime ?? null);
+ const env = opts.env ?? makeEnv();
+ const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) =>
+ new Response(JSON.stringify({ sandboxID: "sb-1" }), { status: 201 }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ const headers: Record<string, string> = { "X-API-Key": apiKey, "content-type": "application/json" };
+ if (sdkVersion) headers[SDK_VERSION_HEADER] = sdkVersion;
+ const resp = await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", { method: "POST", headers, body: "{}" }),
+ env,
+ ctx,
+ );
+ expect(resp.status, `create failed: ${await resp.clone().text()}`).toBe(201);
+ expect(fetchSpy).toHaveBeenCalled();
+ return runtimeClaim(fetchSpy.mock.calls[0][1]?.headers);
+}
+
+describe("create routes by SDK version", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ orgRuntime = null;
+ });
+
+ it("sends an unpinned org's v2 create to microvm", async () => {
+ expect(await createWith("1.0.0")).toBe("microvm");
+ });
+
+ it("leaves an unpinned org's older create on the fleet", async () => {
+ expect(await createWith("0.15.7")).toBe("");
+ expect(await createWith(null)).toBe("");
+ });
+
+ it("honours both pins over the calling SDK", async () => {
+ expect(await createWith("0.15.7", { runtime: "microvm" })).toBe("microvm");
+ expect(await createWith("1.0.0", { runtime: "qemu" })).toBe("qemu");
+ });
+
+ it("SDK_RUNTIME_GATE=0 holds every unpinned create on the fleet", async () => {
+ expect(await createWith("1.0.0", { env: makeEnv({ SDK_RUNTIME_GATE: "0" } as Partial<Env>) })).toBe("");
+ });
+});
+
+// A template is built differently per runtime, so the snapshot path has to make
+// the same decision the create path does. It did not: it minted a blank runtime
+// unconditionally, which would have let a customer migrate their sandboxes and
+// then build every template as a checkpoint the new runtime cannot restore.
+describe("snapshot builds route by SDK version", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ orgRuntime = null;
+ });
+
+ async function snapshotWith(sdkVersion: string | null, runtime: string | null = null): Promise<string> {
+ freshOrg(runtime);
+ const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+ const headers: Record<string, string> = { "X-API-Key": apiKey, "content-type": "application/json" };
+ if (sdkVersion) headers[SDK_VERSION_HEADER] = sdkVersion;
+ const resp = await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/snapshots", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({ name: "tools", image: {} }),
+ }),
+ makeEnv(),
+ ctx,
+ );
+ expect(resp.status, `snapshot create failed: ${await resp.clone().text()}`).toBe(200);
+ return runtimeClaim(fetchSpy.mock.calls[0][1]?.headers);
+ }
+
+ it("builds a v2 caller's template on microvm", async () => {
+ expect(await snapshotWith("1.0.0")).toBe("microvm");
+ });
+
+ it("leaves an older caller's template on the fleet", async () => {
+ expect(await snapshotWith("0.15.7")).toBe("");
+ });
+
+ it("honours the org pin", async () => {
+ expect(await snapshotWith("1.0.0", "qemu")).toBe("qemu");
+ });
+});
diff --git a/internal/api/backend.go b/internal/api/backend.go
index 2740fe17..18edbcb7 100644
--- a/internal/api/backend.go
+++ b/internal/api/backend.go
@@ -583,13 +583,23 @@ func (s *Server) claimBackend(p placement) (Placer, bool) {
return nil, false
}
-// orgRuntime reads the runtime this org is assigned to off the capability
-// token the edge minted for this request.
-//
-// Empty whenever there is no token — combined mode, and any path that did not
-// come through the edge. That resolves to the QEMU fleet, which is the only
-// safe default: a create whose runtime we cannot establish must land on the
-// backend that can serve anything, never on a specialised one.
+// runtimeFor reads the runtime this request's create belongs on.
+//
+// Three sources, in order of authority:
+//
+// 1. The capability token, when the edge minted one. The edge has already
+// applied both the org pin and SDK-version routing, so its answer is final
+// — including its decision to send nothing.
+// 2. orgs.runtime, synced into this cell's Postgres. This is the PIN, and it
+// wins over the calling SDK in both directions.
+// 3. The calling SDK's major version, for an unpinned org on the
+// direct-to-cell path. See runtime_gate.go: this is what lets a customer
+// migrate by upgrading @opencomputer/sdk and roll back by pinning the old
+// major, without us touching a row.
+//
+// Empty resolves to the QEMU fleet, which is the only safe default: a create
+// whose runtime we cannot establish must land on the backend that can serve
+// anything, never on a specialised one.
func (s *Server) runtimeFor(c echo.Context) string {
claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)
if claims != nil && claims.Runtime != "" {
@@ -609,16 +619,26 @@ func (s *Server) runtimeFor(c echo.Context) string {
if !ok || orgID == uuid.Nil || s.store == nil {
return ""
}
- if rt, ok := s.orgRuntime.get(orgID); ok {
- return rt
+ rt, ok := s.orgRuntime.get(orgID)
+ if !ok {
+ var err error
+ if rt, err = s.store.GetOrgRuntime(c.Request().Context(), orgID); err != nil {
+ // Unknown runtime resolves to QEMU, the backend that serves anything.
+ return ""
+ }
+ s.orgRuntime.put(orgID, rt)
+ }
+ if rt != "" {
+ return rt // pinned, in either direction
}
- rt, err := s.store.GetOrgRuntime(c.Request().Context(), orgID)
- if err != nil {
- // Unknown runtime resolves to QEMU, the backend that serves anything.
+ // Unpinned. If a cap token got this far it carried an empty runtime, which
+ // is the EDGE's answer for this org and this SDK — including when the gate
+ // is switched off there. Re-deciding here would defeat that kill switch and
+ // route the same call two different ways depending on which door it came in.
+ if claims != nil {
return ""
}
- s.orgRuntime.put(orgID, rt)
- return rt
+ return runtimeForSDK(c)
}
// orgRuntimeTTL bounds how long a runtime flip in Postgres takes to reach this
diff --git a/internal/api/runtime_gate.go b/internal/api/runtime_gate.go
new file mode 100644
index 00000000..c4b45411
--- /dev/null
+++ b/internal/api/runtime_gate.go
@@ -0,0 +1,92 @@
+package api
+
+// runtime_gate.go — routing a create by the SDK that asked for it.
+//
+// orgs.runtime used to be the only answer to "which runtime serves this org",
+// and we set it by hand, one org at a time. That is not a migration: it makes us
+// the bottleneck for every customer who wants to move and every customer who
+// wants to move back.
+//
+// So the column is now a PIN, and the calling SDK's major version decides for
+// everyone who is not pinned:
+//
+// orgs.runtime = 'microvm' -> MicroVM, whatever SDK is calling
+// orgs.runtime = 'qemu' -> QEMU, whatever SDK is calling
+// orgs.runtime empty -> the SDK decides: 1.x+ MicroVM, 0.x QEMU
+//
+// This file is the CELL's half. The edge decides first and puts the answer in
+// the capability token (cloudflare-workers/api-edge/src/runtime_gate.ts); this
+// only fires for a create that reached a cell WITHOUT a token — the
+// direct-to-cell path, authenticated with an API key against this cell. Both
+// halves have to agree, or the same SDK gets a different runtime depending on
+// which door it came in.
+
+import (
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+)
+
+// sdkVersionHeader is what the TypeScript SDK sends its own version in. Kept in
+// sync with sdks/typescript/src/version.ts by hand — there is no shared
+// artifact between a Go binary and an npm package, and runtime_gate_test.go
+// pins the string on this side.
+const sdkVersionHeader = "X-OC-SDK-Version"
+
+// defaultMinSDKMajor is the major at and above which an SDK routes to MicroVM.
+//
+// 1, because every version @opencomputer/sdk has ever published is 0.x — the
+// first stable release is therefore also an exact split between everything that
+// exists today and the new one. The docs call this platform generation "v2";
+// the package major is 1, and nothing here should assume they match.
+//
+// Overridable because the version this ships under is a release decision that
+// can change after this code is written, and getting it wrong should cost an
+// env var rather than a re-release of the SDK.
+const defaultMinSDKMajor = 1
+
+// sdkMajor is the major version from the request's SDK header, or 0.
+//
+// 0 for absent, malformed, or non-numeric — every one of which means "a client
+// that does not announce itself", which is exactly the population that must keep
+// landing on QEMU. Unparseable input has to fail toward the old runtime.
+func sdkMajor(c echo.Context) int {
+ raw := strings.TrimSpace(c.Request().Header.Get(sdkVersionHeader))
+ if raw == "" {
+ return 0
+ }
+ major, err := strconv.Atoi(strings.SplitN(raw, ".", 2)[0])
+ if err != nil || major <= 0 {
+ return 0
+ }
+ return major
+}
+
+// sdkRuntimeGateEnabled reports whether SDK-version routing is on.
+//
+// OPENSANDBOX_SDK_RUNTIME_GATE=0 pins every unpinned org back to QEMU without
+// touching a single org row — the kill switch for self-service migration.
+func sdkRuntimeGateEnabled() bool {
+ return os.Getenv("OPENSANDBOX_SDK_RUNTIME_GATE") != "0"
+}
+
+// runtimeForSDK returns the runtime an UNPINNED org's create belongs on, given
+// only the calling SDK. "" means the QEMU fleet.
+//
+// Callers must have established that the org has no pin first: a pin wins in
+// both directions, and this function cannot see one.
+func runtimeForSDK(c echo.Context) string {
+ if !sdkRuntimeGateEnabled() {
+ return ""
+ }
+ min := envInt("OPENSANDBOX_SDK_RUNTIME_MIN_MAJOR", defaultMinSDKMajor)
+ if min <= 0 {
+ min = defaultMinSDKMajor
+ }
+ if sdkMajor(c) >= min {
+ return runtimeMicrovm
+ }
+ return ""
+}
diff --git a/internal/api/runtime_gate_test.go b/internal/api/runtime_gate_test.go
new file mode 100644
index 00000000..0301bc58
--- /dev/null
+++ b/internal/api/runtime_gate_test.go
@@ -0,0 +1,185 @@
+package api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// The cutoff is the package's first stable major, not the "v2" the docs use for
+// the platform generation: every version ever published is 0.x.
+const (
+ sdkNew = "1.0.0"
+ sdkOld = "0.15.7"
+)
+
+// ctxWithSDK builds a direct-to-cell create carrying the SDK's version header.
+func ctxWithSDK(version string) echo.Context {
+ req := httptest.NewRequest(http.MethodPost, "/api/sandboxes", nil)
+ if version != "" {
+ req.Header.Set(sdkVersionHeader, version)
+ }
+ return echo.New().NewContext(req, httptest.NewRecorder())
+}
+
+// serverForOrg returns a Server whose runtime answer for orgID is already
+// memoised, so runtimeFor never reaches Postgres. Priming the cache with "" is
+// the UNPINNED org — the case the SDK gate exists for.
+func serverForOrg(t *testing.T, orgID uuid.UUID, pinned string) *Server {
+ t.Helper()
+ s := &Server{orgRuntime: newOrgRuntimeCache(orgRuntimeTTL), store: &db.Store{}}
+ s.orgRuntime.put(orgID, pinned)
+ return s
+}
+
+func TestSDKMajor(t *testing.T) {
+ for _, tc := range []struct {
+ header string
+ want int
+ }{
+ {"1.0.0", 1}, {"2.0.0", 2}, {"10.4.1", 10}, {" 1.1.0 ", 1},
+ // Everything unreadable is a client that does not announce itself, and
+ // that population must stay on QEMU. A parse falling through to "new
+ // runtime" would migrate every curl user at once.
+ {"", 0}, {" ", 0}, {"v2", 0}, {"abc", 0}, {"-3", 0}, {"0.1.0", 0},
+ } {
+ if got := sdkMajor(ctxWithSDK(tc.header)); got != tc.want {
+ t.Errorf("sdkMajor(%q) = %d, want %d", tc.header, got, tc.want)
+ }
+ }
+}
+
+// Every 0.x release in npm's history must land on QEMU. Getting this wrong
+// migrates the entire existing customer base on the next deploy.
+func TestWholePublished0xLineStaysOnTheFleet(t *testing.T) {
+ for _, v := range []string{"0.15.7", "0.15.0", "0.14.0", "0.13.1", "0.9.9", "0.0.1"} {
+ org := uuid.New()
+ c := ctxWithSDK(v)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("SDK %s routed away from the fleet: got %q", v, got)
+ }
+ }
+}
+
+// The headline behaviour: an unpinned org migrates by upgrading the SDK, and
+// rolls back by pinning the old major. Neither needs a row changed.
+func TestUnpinnedOrgIsRoutedByTheCallingSDK(t *testing.T) {
+ org := uuid.New()
+
+ c := ctxWithSDK(sdkNew)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != runtimeMicrovm {
+ t.Errorf("1.x SDK did not route to microvm: got %q", got)
+ }
+
+ for _, old := range []string{sdkOld, ""} {
+ c := ctxWithSDK(old)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("SDK %q routed away from the fleet: got %q", old, got)
+ }
+ }
+}
+
+// A migrated org must not be dragged back by one stale service still on an old
+// SDK — its templates only exist on the runtime it moved to. And the opt-out
+// has to survive an upgrade, or an org that needs checkpoints loses them by
+// bumping a dependency.
+func TestPinWinsOverTheSDKInBothDirections(t *testing.T) {
+ for _, tc := range []struct{ pin, sdk, want string }{
+ {runtimeMicrovm, sdkOld, runtimeMicrovm},
+ {runtimeMicrovm, "", runtimeMicrovm},
+ {"qemu", sdkNew, "qemu"},
+ } {
+ org := uuid.New()
+ c := ctxWithSDK(tc.sdk)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, tc.pin).runtimeFor(c); got != tc.want {
+ t.Errorf("pin %q + SDK %q = %q, want %q", tc.pin, tc.sdk, got, tc.want)
+ }
+ }
+}
+
+// A cap token means the EDGE already decided, including its decision to send
+// nothing. Re-deciding here would defeat the edge's kill switch and route the
+// same call two different ways depending on which door it came in.
+func TestCapTokenSuppressesTheSDKGate(t *testing.T) {
+ org := uuid.New()
+ c := ctxWithSDK(sdkNew)
+ auth.SetOrgID(c, org)
+ c.Set(capClaimsKey, &auth.CapabilityClaims{Runtime: ""})
+
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("cell overrode the edge's empty runtime: got %q", got)
+ }
+}
+
+func TestGateKillSwitch(t *testing.T) {
+ t.Setenv("OPENSANDBOX_SDK_RUNTIME_GATE", "0")
+ org := uuid.New()
+
+ c := ctxWithSDK(sdkNew)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("kill switch did not hold a 1.x SDK on the fleet: got %q", got)
+ }
+
+ // ...and it must not disturb an org that was explicitly moved.
+ c = ctxWithSDK(sdkOld)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, runtimeMicrovm).runtimeFor(c); got != runtimeMicrovm {
+ t.Errorf("kill switch un-pinned a migrated org: got %q", got)
+ }
+}
+
+func TestMinMajorIsConfigurable(t *testing.T) {
+ t.Setenv("OPENSANDBOX_SDK_RUNTIME_MIN_MAJOR", "3")
+ org := uuid.New()
+
+ c := ctxWithSDK("2.9.0")
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("major 2 routed to microvm under a threshold of 3: got %q", got)
+ }
+
+ c = ctxWithSDK("3.0.0")
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != runtimeMicrovm {
+ t.Errorf("major 3 did not meet a threshold of 3: got %q", got)
+ }
+}
+
+// Garbage in the threshold must fall back to the default, not to 0 — a 0
+// threshold routes EVERY client to microvm, including ones sending no header.
+func TestGarbageThresholdFallsBackToTheDefault(t *testing.T) {
+ t.Setenv("OPENSANDBOX_SDK_RUNTIME_MIN_MAJOR", "junk")
+ org := uuid.New()
+
+ c := ctxWithSDK(sdkOld)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != "" {
+ t.Errorf("a v1 SDK routed to microvm under a junk threshold: got %q", got)
+ }
+
+ c = ctxWithSDK(sdkNew)
+ auth.SetOrgID(c, org)
+ if got := serverForOrg(t, org, "").runtimeFor(c); got != runtimeMicrovm {
+ t.Errorf("a 1.x SDK did not route to microvm under a junk threshold: got %q", got)
+ }
+}
+
+// The header name is a contract with sdks/typescript/src/version.ts, which is a
+// separate artifact with no compiler between them. Renaming one side silently
+// stops every 1.x SDK from being recognised.
+func TestHeaderNameMatchesTheSDK(t *testing.T) {
+ if sdkVersionHeader != "X-OC-SDK-Version" {
+ t.Errorf("header renamed to %q — sdks/typescript/src/version.ts sends x-oc-sdk-version", sdkVersionHeader)
+ }
+}
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index 4d3cba23..f02535fa 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.6",
+ "version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.15.6",
+ "version": "1.0.0",
"license": "MIT",
"dependencies": {
"undici": "^6.0.0 || ^7.0.0"
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 19276e40..71afaf62 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.15.7",
+ "version": "1.0.0",
"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 4fd36271..ff493795 100644
--- a/sdks/typescript/src/index.ts
+++ b/sdks/typescript/src/index.ts
@@ -64,6 +64,7 @@ export { Mounts, type AddMountOpts, type MountInfo, type MountBackend } from "./
export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClosedError } from "./shell.js";
export { Pty, type PtySession, type PtyOpts } from "./pty.js";
export { Templates, type TemplateInfo } from "./template.js";
+export { SDK_VERSION, SDK_VERSION_HEADER } from "./version.js";
export {
Webhooks,
WebhookDeliveries,
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 78f08c60..d76ba484 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -1,4 +1,5 @@
import { SandboxAgent } from "./agent.js";
+import { sdkVersionHeaders } from "./version.js";
import { prewarmConnections } from "./http2.js";
import { Filesystem } from "./filesystem.js";
import { Exec } from "./exec.js";
@@ -373,6 +374,10 @@ export class Sandbox {
const headers: Record<string, string> = {
"Content-Type": "application/json",
+ // Which runtime serves this create. See version.ts: an org that has not
+ // been pinned is routed by the calling SDK's major version, so this
+ // header is how upgrading the dependency performs the migration.
+ ...sdkVersionHeaders(),
...(apiKey ? { "X-API-Key": apiKey } : {}),
};
if (useSSE) {
diff --git a/sdks/typescript/src/snapshot.ts b/sdks/typescript/src/snapshot.ts
index 7678d22a..4e9083b1 100644
--- a/sdks/typescript/src/snapshot.ts
+++ b/sdks/typescript/src/snapshot.ts
@@ -1,4 +1,5 @@
import { Image } from "./image.js";
+import { sdkVersionHeaders } from "./version.js";
import { parseSSEStream } from "./sse.js";
function resolveApiUrl(url: string): string {
@@ -70,7 +71,11 @@ export class Snapshots {
}
private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
+ // Template builds are runtime-specific — a v1 template is a whole-disk
+ // checkpoint, a v2 template is a machine image — so the same version header
+ // the create path sends has to ride along here, or a v2 caller would build
+ // a checkpoint their sandboxes cannot use. See version.ts.
+ const h: Record<string, string> = { "Content-Type": "application/json", ...sdkVersionHeaders() };
if (this.apiKey) h["X-API-Key"] = this.apiKey;
return h;
}
diff --git a/sdks/typescript/src/template.ts b/sdks/typescript/src/template.ts
index a38b1f25..8864cae9 100644
--- a/sdks/typescript/src/template.ts
+++ b/sdks/typescript/src/template.ts
@@ -1,3 +1,5 @@
+import { sdkVersionHeaders } from "./version.js";
+
export interface TemplateInfo {
templateID: string;
name: string;
@@ -12,7 +14,9 @@ export class Templates {
) {}
private get headers(): Record<string, string> {
- const h: Record<string, string> = { "Content-Type": "application/json" };
+ // Same reason as Snapshots.headers — a build is runtime-specific, so the
+ // server has to know which SDK asked for it. See version.ts.
+ const h: Record<string, string> = { "Content-Type": "application/json", ...sdkVersionHeaders() };
if (this.apiKey) h["X-API-Key"] = this.apiKey;
return h;
}
diff --git a/sdks/typescript/src/version.test.ts b/sdks/typescript/src/version.test.ts
new file mode 100644
index 00000000..b54a02ce
--- /dev/null
+++ b/sdks/typescript/src/version.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { SDK_VERSION, SDK_VERSION_HEADER, sdkVersionHeaders } from "./version.js";
+
+describe("SDK version", () => {
+ // The server routes creates by the MAJOR of this value. If the constant drifts
+ // from the published version, a v2 release goes out still announcing whatever
+ // was hardcoded — and every customer who upgrades stays on the old runtime
+ // with no error anywhere.
+ it("matches package.json", () => {
+ const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { version: string };
+ expect(SDK_VERSION).toBe(pkg.version);
+ });
+
+ // HTTP/2 rejects upper-case header names outright, and this SDK speaks h2.
+ it("uses a lower-case header name", () => {
+ expect(SDK_VERSION_HEADER).toBe(SDK_VERSION_HEADER.toLowerCase());
+ });
+
+ // Every previously published version is 0.x, so a major of at least 1 is what
+ // separates a caller routed to MicroVM from one that is not.
+ it("announces a stable major", () => {
+ expect(Number(SDK_VERSION.split(".")[0])).toBeGreaterThanOrEqual(1);
+ expect(sdkVersionHeaders()[SDK_VERSION_HEADER]).toBe(SDK_VERSION);
+ });
+});
diff --git a/sdks/typescript/src/version.ts b/sdks/typescript/src/version.ts
new file mode 100644
index 00000000..c81c574d
--- /dev/null
+++ b/sdks/typescript/src/version.ts
@@ -0,0 +1,35 @@
+// The SDK's own identity, sent on the two requests that decide which runtime
+// serves a customer: creating a sandbox and creating a template.
+//
+// This is what makes self-service migration possible. An org that has not been
+// pinned to a runtime lands on the MicroVM backend when it calls with a 1.x SDK
+// and on the QEMU fleet when it calls with an older one — so upgrading the
+// dependency IS the migration, and pinning the old version is the rollback.
+// Nothing has to be changed in our database for either direction.
+//
+// 1.0.0, not 2.0.0, even though the docs call this platform generation "v2":
+// every version this package has ever published is 0.x, so 1.0.0 is both the
+// first stable release and a clean major break from all of them. The product
+// generation and the package major are not the same number.
+//
+// Only the MAJOR is load-bearing: the server compares it against a minimum, so
+// patch and minor releases never move anyone.
+
+/** Header carrying the version below. Lower-case: HTTP/2 requires it. */
+export const SDK_VERSION_HEADER = "x-oc-sdk-version";
+
+/**
+ * This package's version.
+ *
+ * Kept as a literal rather than read from package.json, because the SDK ships
+ * as an ESM bundle that may be consumed by bundlers where a JSON import is not
+ * resolvable. version.test.ts asserts it matches package.json, which is the
+ * only failure mode that matters — a stale constant here would silently route a
+ * v2 caller to the old runtime.
+ */
+export const SDK_VERSION = "1.0.0";
+
+/** The identifying header, as a spreadable object. */
+export function sdkVersionHeaders(): Record<string, string> {
+ return { [SDK_VERSION_HEADER]: SDK_VERSION };
+}