An open-source, faster Devin alternative
TypeScript
carry the SDK-routed runtime as a separate cap-token claim so routing stays reversible — the cell PERSISTS the token's runtime into its own orgs table, so sending the SDK-derived answer there made an unpinned org's first create from a new SDK write itself in as a permanent pin, after which deliberately calling from an older SDK could not move it back; found on dev, where two orgs pinned themselves this way
Brian Reardonfef3d2c1baff
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex ab65ebab..9a538957 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -200,7 +200,14 @@ export interface FinalizeMsg {baseURL: string;plan: string;billingProvider: string;+ /** The runtime this create was ROUTED to (may be SDK-derived). */runtime: string;+ /**+ * The org's pin from D1 — what the cell may persist. Absent on messages+ * enqueued before this field existed; the consumer then falls back to+ * `runtime`, which is exactly the old behaviour.+ */+ runtimePin?: string;sandboxID: string;workerID: string;/** Voucher creates only: the box to redeem against. Absent on every other path. */@@ -243,16 +250,20 @@ async function cachedCapToken(billingProvider: string,runtime: string,userID: string | null,+ effective = runtime,): Promise<string> {- // runtime is in the cache key deliberately. It is the org's sandbox backend+ // Both runtimes are in the cache key deliberately. `runtime` is the org's// assignment, and leaving it out would mean a D1 change did not take effect// until the entry aged out — an org would keep landing on the old runtime for// up to a minute after being reassigned, with nothing to explain why.- const key = `${orgID}|${cellID}|${plan}|${billingProvider}|${runtime}|${userID ?? ""}`;+ // `effective` has to be there for a sharper reason: under SDK-version routing+ // it differs BETWEEN CALLS for the same org, so a key without it would serve+ // one SDK's token to the other and route the create to the wrong backend.+ const key = `${orgID}|${cellID}|${plan}|${billingProvider}|${runtime}|${effective}|${userID ?? ""}`;const hit = capTokenCache.get(key);const nowMs = Date.now();if (hit && nowMs - hit.mintedAtMs < 60_000) return hit.token;- const token = await mintCapToken(secret, orgID, cellID, plan, billingProvider, runtime, userID);+ const token = await mintCapToken(secret, orgID, cellID, plan, billingProvider, runtime, userID, effective);if (capTokenCache.size >= CACHE_MAX) capTokenCache.clear();capTokenCache.set(key, { token, mintedAtMs: nowMs });return token;@@ -266,6 +277,7 @@ async function mintCapToken(billingProvider: string,runtime: string,userID: string | null,+ effective = runtime,): Promise<string> {const now = Math.floor(Date.now() / 1000);const header = { alg: "HS256", typ: "JWT" };@@ -286,6 +298,18 @@ async function mintCapToken(// no assignment, and every token minted before this field existed, resolves// to the backend with the full feature set rather than a specialised one.if (runtime) payload.runtime = runtime;+ // `rt` is the runtime THIS REQUEST was routed to, which for an unpinned org+ // is decided by the calling SDK's major and therefore varies per call. It is+ // deliberately a SEPARATE claim from `runtime` above, because the cell+ // PERSISTS `runtime` into its own orgs table: writing a per-request answer+ // there turns the first create from a new SDK into a permanent org pin, after+ // which deliberately calling from an older SDK cannot move the org back.+ // Measured on dev — two unpinned orgs pinned themselves to microvm on their+ // own first create, and the rollback path stopped working.+ //+ // Omitted when it matches `runtime`, so tokens for pinned orgs are unchanged+ // and the cell's fallback (read `runtime`) is exactly the old behaviour.+ if (effective && effective !== runtime) payload.rt = effective;if (userID) payload.user_id = userID;const enc = new TextEncoder();const signingInput =@@ -1923,6 +1947,10 @@ async function finalizeEdgeClaim(sandboxID: string,workerID: string,bodyText: string,+ // The org's pin. Defaults to `runtime` so callers that have only one value+ // behave as before; the create path passes both because they differ whenever+ // SDK-version routing decided this create.+ runtimePin = runtime,): Promise<void> {// Index insert is DEFERRED below the finalize call + a short delay: D1 has a// single writer, and a create burst otherwise queues ~100 inserts exactly@@ -1933,7 +1961,7 @@ async function finalizeEdgeClaim(// Minted HERE (off the response path) rather than on the create hot path —// only this finalize call ever consumes it on the edge-claim route, and the// HMAC sign was one of the larger CPU items at burst-100 concurrency.- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, billingProvider, runtime, caller.userID);+ const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, billingProvider, runtimePin, caller.userID, runtime);let body: Record<string, unknown> = {};try {body = bodyText ? (JSON.parse(bodyText) as Record<string, unknown>) : {};@@ -2259,6 +2287,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTopplan,billingProvider: org.billing_provider,runtime,+ runtimePin: org.runtime ?? "",sandboxID: box.id,workerID: box.workerID,bodyText,@@ -2267,11 +2296,11 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTopenv.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, runtime, box.id, box.workerID, bodyText);+ return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText, org.runtime ?? "");}),);} else {- ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText));+ ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText, org.runtime ?? ""));}// Total in-handler wall time. With `pre`, the client's own measurement// splits three ways: pre (getting here) + hdl (this handler) + the rest@@ -2296,7 +2325,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, runtime, caller.userID);+ const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID, runtime);mark("capmint");// SSE build streaming: image/snapshot creates can take minutes (apt installs,@@ -3384,7 +3413,7 @@ async function proxyToCellAuthed(: 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, "", runtime, caller.userID);+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", org.runtime ?? "", caller.userID, runtime);const url = new URL(req.url);const target = cell.base_url.replace(/\/$/, "") + (opts.pathOverride ?? url.pathname) + url.search;@@ -5736,6 +5765,7 @@ export default {b.sandboxID,b.workerID,b.bodyText,+ b.runtimePin ?? b.runtime ?? "",);} catch (e) {console.error(`finalize-queue: ${b.sandboxID} failed:`, e);diff --git a/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts b/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.tsindex b8a6f7ec..9ca147fb 100644--- a/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts+++ b/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts@@ -96,15 +96,27 @@ function makeEnv(extra: Partial<Env> = {}): 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 {+/** Decoded claims from the Bearer token the edge sent the cell. */+function claims(headers: HeadersInit | undefined): { runtime?: string; rt?: 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) ?? "";+ return JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));+}++/** The runtime this create was ROUTED to — `rt`, falling back to the pin. */+function runtimeClaim(headers: HeadersInit | undefined): string {+ const c = claims(headers);+ return c.rt ?? c.runtime ?? "";+}++/** The org's PIN — the only value the cell is allowed to persist. */+function pinClaim(headers: HeadersInit | undefined): string {+ return claims(headers).runtime ?? "";}+let lastHeaders: HeadersInit | undefined;+async function createWith(sdkVersion: string | null,opts: { runtime?: string | null; env?: Env } = {},@@ -124,7 +136,8 @@ async function createWith();expect(resp.status, `create failed: ${await resp.clone().text()}`).toBe(201);expect(fetchSpy).toHaveBeenCalled();- return runtimeClaim(fetchSpy.mock.calls[0][1]?.headers);+ lastHeaders = fetchSpy.mock.calls[0][1]?.headers;+ return runtimeClaim(lastHeaders);}describe("create routes by SDK version", () => {@@ -193,3 +206,33 @@ describe("snapshot builds route by SDK version", () => {expect(await snapshotWith("1.0.0", "qemu")).toBe("qemu");});});++// The bug a dev run found, and the reason `rt` exists as a separate claim.+//+// The cell PERSISTS the token's `runtime` into its own orgs table+// (UpsertOrgFromCapToken). When that field carried the SDK-derived answer, an+// unpinned org's very first create from a new SDK wrote itself in as a pin —+// and from then on the org resolved to MicroVM even for a call deliberately+// made from an older SDK. Measured: two dev orgs pinned themselves this way,+// and the rollback path stopped working. Routing must be reversible.+describe("SDK routing does not pin the org", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ orgRuntime = null;+ });++ it("sends an empty pin for an unpinned org routed to microvm by its SDK", async () => {+ expect(await createWith("1.0.0")).toBe("microvm");+ expect(pinClaim(lastHeaders), "the cell would persist this as the org's runtime").toBe("");+ });++ it("still sends a real pin when the org actually has one", async () => {+ expect(await createWith("0.15.7", { runtime: "microvm" })).toBe("microvm");+ expect(pinClaim(lastHeaders)).toBe("microvm");+ });++ it("leaves the pin empty for an old SDK too", async () => {+ expect(await createWith("0.15.7")).toBe("");+ expect(pinClaim(lastHeaders)).toBe("");+ });+});diff --git a/internal/api/backend.go b/internal/api/backend.goindex 18edbcb7..bb6b1d5d 100644--- a/internal/api/backend.go+++ b/internal/api/backend.go@@ -602,8 +602,17 @@ func (s *Server) claimBackend(p placement) (Placer, bool) {// 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 != "" {- return claims.Runtime+ if claims != nil {+ // Effective first: it is the edge's answer for THIS request, which for an+ // unpinned org depends on the calling SDK and so can differ per call.+ // Runtime is the org's pin and is what gets persisted; reading it here+ // when Effective is set would ignore the routing decision entirely.+ if claims.Effective != "" {+ return claims.Effective+ }+ if claims.Runtime != "" {+ return claims.Runtime+ }}// No cap-token: this is the direct-to-cell create, authenticated with an// API key against this cell rather than through the edge. D1 is stilldiff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex 74d79ebc..8f6c28dd 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -161,6 +161,23 @@ type CapabilityClaims struct {// org that predates the field, and every token minted before it existed,// resolves to the runtime with the full feature set.Runtime string `json:"runtime,omitempty"`+ // Effective is the runtime THIS REQUEST was routed to, which is not always+ // the org's pin above: an unpinned org is routed by the calling SDK's major+ // version (cloudflare-workers/api-edge/src/runtime_gate.ts), so the answer+ // can differ from one call to the next for the same org.+ //+ // Separate from Runtime because the two are consumed differently and+ // conflating them is a one-way door. Runtime is PERSISTED into cell-PG by+ // UpsertOrgFromCapToken; Effective must never be, or the first create from a+ // new SDK would write itself into the org row as a pin and every later call+ // — including one deliberately made from an older SDK — would resolve to it.+ // That was measured on dev: two unpinned orgs were pinned to microvm by+ // their own first create, after which downgrading the SDK could not move+ // them back, which defeats the rollback half of SDK-version routing.+ //+ // Empty means "no per-request answer" and the cell falls back to Runtime,+ // so a token minted before this field existed behaves exactly as before.+ Effective string `json:"rt,omitempty"`}// CapabilityIssuer is the Issuer string on capability tokens — lets the CP