Skip to content

An open-source, faster Devin alternative

TypeScript

answer default-shape creates at the CF edge via PoolStock DO

Brian Reardonb3bbf0803f51
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 7d45fd8a..2abe04a2 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -20,6 +20,7 @@
// GET /health
export { CreditAccount } from "../../shared/credit_account";
+export { PoolStock } from "./pool_stock";
import { handleDashboard, type DashboardEnv } from "./dashboard";
import {
AGENT_SECURITY_NOTIFICATION_PATH,
@@ -89,6 +90,11 @@ export interface Env extends DashboardEnv {
// DEDICATED HMAC secret for handing a freshly-minted OR key to sessions-api
// (NOT the generic internal-auth — this route carries a live model key). §6.7.5.
OC_MANAGED_CRED_HMAC_SECRET: string;
+ // Edge claim (pool_stock.ts): per-cell Durable Object stocking pre-reserved
+ // hot pool boxes so default-shape creates are answered at the edge with zero
+ // origin round trips. EDGE_CLAIM="0" is the kill switch (default on).
+ POOL_STOCK: DurableObjectNamespace;
+ EDGE_CLAIM?: string;
}
const DEFAULT_MAX_CONCURRENT_SANDBOXES = 50;
@@ -151,6 +157,42 @@ async function mintCapToken(
return signingInput + "." + b64url(sig);
}
+// Mint the sandbox-scoped JWT the create response carries (direct worker
+// access: exec WS, PTY, files). Byte-compatible with Go's
+// auth.IssueSandboxToken — same shared secret, iss="opensandbox", same claim
+// names — so cells/workers validate edge-minted tokens identically to
+// CP-minted ones. 24h TTL mirrors the CP.
+async function mintSandboxToken(
+ secret: string,
+ orgID: string,
+ sandboxID: string,
+ workerID: string,
+): Promise<string> {
+ const now = Math.floor(Date.now() / 1000);
+ const enc = new TextEncoder();
+ const header = { alg: "HS256", typ: "JWT" };
+ const payload = {
+ sub: orgID,
+ iat: now,
+ exp: now + 24 * 3600,
+ iss: "opensandbox",
+ org_id: orgID,
+ sandbox_id: sandboxID,
+ worker_id: workerID,
+ };
+ const signingInput =
+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
+ const key = await crypto.subtle.importKey(
+ "raw",
+ enc.encode(secret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
+ return signingInput + "." + b64url(sig);
+}
+
interface Caller {
orgID: string;
userID: string | null;
@@ -794,6 +836,83 @@ function indexSandboxFromSSE(
return new Response(resp.body.pipeThrough(stream), resp);
}
+// edgeClaimEligible: a create qualifies for the edge fast path only when it
+// asks for exactly what pool boxes are manufactured as — base template at the
+// default shape (4GB/1cpu/default disk), no guest-side customization (envs,
+// secrets, image, snapshot, webhooks, preview auth). Anything else falls
+// through to the cell, which handles it exactly as before (including its own
+// pool claim for claimable shapes). metadata/timeout are pure bookkeeping the
+// finalize call persists, so they don't disqualify.
+function edgeClaimEligible(bodyText: string): boolean {
+ if (!bodyText) return true;
+ let b: Record<string, unknown>;
+ try {
+ b = JSON.parse(bodyText) as Record<string, unknown>;
+ } catch {
+ return false;
+ }
+ const template = typeof b.templateID === "string" ? b.templateID : "";
+ if (template !== "" && template !== "base") return false;
+ if (b.envs && Object.keys(b.envs as object).length > 0) return false;
+ if (b.secretStore || b.image || b.snapshot || b.previewAuth || b.burst) return false;
+ if (Array.isArray(b.webhooks) && b.webhooks.length > 0) return false;
+ if (b.sandboxFamily || b.alias || b.cellId || b.networkEnabled != null) return false;
+ if (typeof b.port === "number" && b.port !== 0 && b.port !== 80) return false;
+ if (typeof b.cpuCount === "number" && b.cpuCount !== 0 && b.cpuCount !== 1) return false;
+ if (typeof b.memoryMB === "number" && b.memoryMB !== 0 && b.memoryMB !== 4096) return false;
+ if (typeof b.diskMB === "number" && b.diskMB !== 0 && b.diskMB !== 20480) return false;
+ return true;
+}
+
+// finalizeEdgeClaim runs off the response path (waitUntil): D1 index row so
+// the dashboard/GET sees the box, then the cell's claim-finalize (PG rebind +
+// worker ClaimSandbox: billing on, idle timeout). On failure the box is dead —
+// mark the index row error and drop the route so the customer's next op
+// surfaces a clean failure instead of a phantom.
+async function finalizeEdgeClaim(
+ env: Env,
+ caller: Caller,
+ cell: CellRow,
+ capToken: string,
+ sandboxID: string,
+ workerID: string,
+ bodyText: string,
+): Promise<void> {
+ try {
+ await insertSandboxIndex(env, caller, cell.cell_id, { sandboxID, workerID, status: "running", memoryMB: 4096 }, 1, 4096);
+ } catch (e) {
+ console.error(`edge-claim: index insert failed for ${sandboxID}:`, e);
+ }
+ try {
+ let body: Record<string, unknown> = {};
+ try {
+ body = bodyText ? (JSON.parse(bodyText) as Record<string, unknown>) : {};
+ } catch {
+ /* eligibility already vetted the body; belt-and-braces */
+ }
+ body.sandboxID = sandboxID;
+ // Bill/grow at the default create shape the box was manufactured as.
+ if (!body.memoryMB) body.memoryMB = 4096;
+ if (!body.cpuCount) body.cpuCount = 1;
+ const r = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/claim-finalize", {
+ method: "POST",
+ headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
+ } catch (e) {
+ console.error(`edge-claim: FINALIZE FAILED for ${sandboxID} — marking error:`, e);
+ sandboxRouteCache.delete(sandboxID);
+ const nowSec = Math.floor(Date.now() / 1000);
+ await env.OPENCOMPUTER_DB.prepare(
+ "UPDATE sandboxes_index SET status='error', last_event_at=?2 WHERE id=?1",
+ )
+ .bind(sandboxID, nowSec)
+ .run()
+ .catch(() => {});
+ }
+}
+
async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const caller = await authenticate(req, env);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
@@ -875,6 +994,40 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, caller.userID);
+ // Edge claim: for a default-shape create, pop a pre-reserved hot box from
+ // this cell's PoolStock DO and answer right here — token minted at the edge,
+ // zero origin round trips. Finalize (billing on, PG rebind, idle timeout)
+ // runs async; exec arriving before it lands routes fine (the cell proxy
+ // resolves by worker_id regardless of claim status). Miss/error falls
+ // through to the normal cell create, which is never worse than before.
+ if (env.EDGE_CLAIM !== "0" && env.POOL_STOCK && edgeClaimEligible(bodyText)) {
+ try {
+ const stub = env.POOL_STOCK.get(env.POOL_STOCK.idFromName(cell.cell_id));
+ const r = await stub.fetch("https://pool-stock/claim", {
+ method: "POST",
+ body: JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } }),
+ });
+ if (r.ok) {
+ const box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };
+ const token = await mintSandboxToken(env.SESSION_JWT_SECRET, caller.orgID, box.id, box.workerID);
+ if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
+ sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID });
+ ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, capToken, box.id, box.workerID, bodyText));
+ const resp: Record<string, unknown> = {
+ sandboxID: box.id,
+ token,
+ status: "running",
+ region: box.region,
+ workerID: box.workerID,
+ };
+ if (box.sandboxDomain) resp.sandboxDomain = box.sandboxDomain;
+ return json(resp, 201);
+ }
+ } catch (e) {
+ console.error("edge-claim: falling back to cell create:", e);
+ }
+ }
+
// SSE build streaming: image/snapshot creates can take minutes (apt installs,
// etc.). Preserve live streaming, but index the final `result` event inline
// before the stream closes. Relying only on async lifecycle events leaves a
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
new file mode 100644
index 00000000..fe85b0bf
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -0,0 +1,206 @@
+// PoolStock — per-cell Durable Object holding pre-reserved hot pool boxes so
+// default-shape sandbox creates are answered entirely at the edge (pop + mint
+// token + 201) with zero origin round trips. The cell reserved these boxes for
+// us (status='edge_reserved' in cell PG — invisible to the CP's own pool-claim
+// path, so a box can never be handed to two customers).
+//
+// Lifecycle safety (see internal/api/edge_claim.go for the server half):
+// - Popped entries get a sandbox token minted by the edge → the box must
+// NEVER return to the pool (a live foreign token on a re-issued box would
+// be cross-tenant access). Popped boxes are finalized or marked failed.
+// - Entries the DO discards UNPOPPED (stale, overshoot) were never tokened →
+// released back to 'pooled' via /internal/pool/edge-release.
+// - If the DO dies without releasing, the cell's reaper destroys the
+// reservations after 15 min (destroy, not re-pool — it can't prove they
+// were never tokened).
+//
+// One instance per cell (idFromName(cellID)); the Worker picks the cell first
+// (home-cell pinning etc.) and asks that cell's stock. All restock/release
+// concurrency is contained here: the Worker only ever calls /claim.
+
+interface StockEntry {
+ id: string;
+ workerID: string;
+ cellID: string;
+ baseURL: string;
+ region: string;
+ sandboxDomain: string;
+ atMs: number;
+}
+
+interface PoolStockEnv {
+ SESSION_JWT_SECRET: string;
+}
+
+// Stock tuning. ENTRY_TTL well under the cell's 15-min destroy backstop so the
+// normal path is always the cheap release, never the destroy.
+const ENTRY_TTL_MS = 4 * 60_000;
+const LOW_WATER = 8;
+const RESTOCK_BATCH = 16;
+const MAX_STOCK = 40;
+
+// Synthetic org that owns parked pool boxes (db.PoolOrgID). Used as the cap
+// token subject for reserve/release calls — those endpoints are org-agnostic,
+// but the middleware wants a parseable org UUID.
+const POOL_ORG_ID = "00000000-0000-4000-8000-000000000001";
+
+const b64url = (buf: ArrayBuffer | Uint8Array): string => {
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
+ let s = "";
+ for (const b of bytes) s += String.fromCharCode(b);
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+};
+
+// Minimal cap-token mint for the DO's own cell calls (reserve/release).
+// Duplicates index.ts's mintCapToken rather than importing it — the DO must
+// not pull in the Worker's module graph (circular import, isolate bloat).
+async function mintPoolCapToken(secret: string, cellID: string): Promise<string> {
+ const now = Math.floor(Date.now() / 1000);
+ const enc = new TextEncoder();
+ const header = { alg: "HS256", typ: "JWT" };
+ const payload = {
+ sub: POOL_ORG_ID,
+ iss: "opensandbox-edge",
+ iat: now,
+ exp: now + 120,
+ org_id: POOL_ORG_ID,
+ cell_id: cellID,
+ plan: "free",
+ };
+ const signingInput =
+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
+ const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
+ return signingInput + "." + b64url(sig);
+}
+
+export class PoolStock {
+ private stock: StockEntry[] = [];
+ private restockInFlight = false;
+
+ constructor(
+ private state: DurableObjectState,
+ private env: PoolStockEnv,
+ ) {
+ this.state.blockConcurrencyWhile(async () => {
+ this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];
+ });
+ }
+
+ async fetch(req: Request): Promise<Response> {
+ const url = new URL(req.url);
+ if (req.method === "POST" && url.pathname === "/claim") {
+ return this.claim(req);
+ }
+ if (req.method === "GET" && url.pathname === "/status") {
+ return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });
+ }
+ return new Response("not found", { status: 404 });
+ }
+
+ private async claim(req: Request): Promise<Response> {
+ let cell: { cellID: string; baseURL: string } | null = null;
+ try {
+ const body = (await req.json()) as { cell?: { cellID: string; baseURL: string } };
+ cell = body.cell ?? null;
+ } catch {
+ /* no cell hint — claim still works, restock doesn't */
+ }
+
+ // Expire stale entries (never handed out → safe to release back to the
+ // pool). Done inline, synchronously over the in-memory array, so a
+ // concurrent claim can't double-pop across an await.
+ const now = Date.now();
+ const fresh: StockEntry[] = [];
+ const stale: StockEntry[] = [];
+ for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);
+ this.stock = fresh;
+ if (stale.length > 0) {
+ this.state.waitUntil(this.release(stale));
+ }
+
+ const entry = this.stock.shift(); // FIFO — oldest first keeps the stock young
+ this.persist();
+
+ if (cell && !this.restockInFlight && this.stock.length < LOW_WATER) {
+ this.state.waitUntil(this.restock(cell));
+ }
+
+ if (!entry) {
+ return new Response(JSON.stringify({ error: "stock empty" }), { status: 404 });
+ }
+ return Response.json(entry);
+ }
+
+ private persist(): void {
+ // storage.put without await — the DO's output gate holds the response
+ // until the write is durable, so this is both safe and non-blocking.
+ void this.state.storage.put("stock", this.stock);
+ }
+
+ private async restock(cell: { cellID: string; baseURL: string }): Promise<void> {
+ if (this.restockInFlight) return;
+ this.restockInFlight = true;
+ try {
+ const want = Math.min(RESTOCK_BATCH, MAX_STOCK - this.stock.length);
+ if (want <= 0) return;
+ const token = await mintPoolCapToken(this.env.SESSION_JWT_SECRET, cell.cellID);
+ const r = await fetch(cell.baseURL.replace(/\/$/, "") + "/internal/pool/edge-reserve", {
+ method: "POST",
+ headers: { authorization: "Bearer " + token, "content-type": "application/json" },
+ body: JSON.stringify({ count: want }),
+ });
+ if (!r.ok) {
+ console.error(`pool-stock ${cell.cellID}: reserve failed ${r.status} ${await r.text()}`);
+ return;
+ }
+ const data = (await r.json()) as {
+ region: string;
+ sandboxDomain: string;
+ boxes: Array<{ sandboxID: string; workerID: string }>;
+ };
+ const now = Date.now();
+ const have = new Set(this.stock.map((e) => e.id));
+ for (const b of data.boxes) {
+ if (have.has(b.sandboxID)) continue;
+ this.stock.push({
+ id: b.sandboxID,
+ workerID: b.workerID,
+ cellID: cell.cellID,
+ baseURL: cell.baseURL,
+ region: data.region,
+ sandboxDomain: data.sandboxDomain,
+ atMs: now,
+ });
+ }
+ this.persist();
+ } catch (e) {
+ console.error(`pool-stock ${cell.cellID}: restock error:`, e);
+ } finally {
+ this.restockInFlight = false;
+ }
+ }
+
+ private async release(entries: StockEntry[]): Promise<void> {
+ // Group by cell (entries could straddle a base_url change).
+ const byCell = new Map<string, { cellID: string; ids: string[] }>();
+ for (const e of entries) {
+ const g = byCell.get(e.baseURL) ?? { cellID: e.cellID, ids: [] };
+ g.ids.push(e.id);
+ byCell.set(e.baseURL, g);
+ }
+ for (const [baseURL, g] of byCell) {
+ try {
+ const token = await mintPoolCapToken(this.env.SESSION_JWT_SECRET, g.cellID);
+ await fetch(baseURL.replace(/\/$/, "") + "/internal/pool/edge-release", {
+ method: "POST",
+ headers: { authorization: "Bearer " + token, "content-type": "application/json" },
+ body: JSON.stringify({ sandboxIDs: g.ids }),
+ });
+ } catch (e) {
+ // Best-effort — the cell's stale-reservation reaper is the backstop.
+ console.error(`pool-stock: release to ${baseURL} failed:`, e);
+ }
+ }
+ }
+}
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index ccb513d3..a9ab750b 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -86,10 +86,22 @@ name = "CREDIT_ACCOUNT"
class_name = "CreditAccount"
script_name = "opensandbox-edge-dev"
+# Edge claim (src/pool_stock.ts): per-cell stock of pre-reserved hot pool
+# boxes so default-shape creates are answered at the edge. Kill switch:
+# EDGE_CLAIM = "0" in [vars].
+[[durable_objects.bindings]]
+name = "POOL_STOCK"
+class_name = "PoolStock"
+script_name = "opensandbox-edge-dev"
+
[[migrations]]
tag = "v1"
new_sqlite_classes = ["CreditAccount"]
+[[migrations]]
+tag = "v2"
+new_sqlite_classes = ["PoolStock"]
+
# v2 / v3 reconciliation entries were dropped after a clean `wrangler delete`
# reset the migration ledger to v1. If you ever apply a DO change out-of-band
# again, re-add the placeholder pattern (see git log for the old comments) or
diff --git a/internal/api/edge_claim.go b/internal/api/edge_claim.go
new file mode 100644
index 00000000..d60faabf
--- /dev/null
+++ b/internal/api/edge_claim.go
@@ -0,0 +1,224 @@
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/labstack/echo/v4"
+
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// Edge claim: the api-edge Worker's PoolStock Durable Object reserves parked
+// pool boxes ahead of time (edge-reserve), answers default-shape creates
+// entirely at the edge (pop + mint token + 201), then finalizes the claim
+// asynchronously here (claim-finalize). The cell never sits on a create's
+// critical path for a stocked default-shape request.
+//
+// Reservation lifecycle and why the states matter:
+// pooled → edge_reserved edge-reserve (batch, SKIP LOCKED)
+// edge_reserved → pending claim-finalize (by id; ClaimSandbox rebinds worker)
+// edge_reserved → pooled edge-release — ONLY for stock the DO discarded
+// before handing to a customer (never tokened)
+// edge_reserved → destroyed reapStaleEdgeReservations backstop — the CP
+// can't prove a stale reservation was never tokened,
+// and a re-issued box with a live foreign token
+// would be cross-tenant access.
+
+// edgeReserveTTL is the backstop age after which an unclaimed reservation is
+// destroyed. Must comfortably exceed the DO's own stock-entry TTL (the DO
+// discards + releases entries well before this; the reaper only fires when a
+// DO dies without releasing).
+const edgeReserveTTL = 15 * time.Minute
+
+// edgeReservePool handles POST /internal/pool/edge-reserve {count} — flips up
+// to count pooled boxes to edge_reserved and returns them for the DO's stock.
+func (s *Server) edgeReservePool(c echo.Context) error {
+ var req struct {
+ Count int `json:"count"`
+ }
+ if err := c.Bind(&req); err != nil || req.Count <= 0 {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "count must be > 0"})
+ }
+ if req.Count > 50 {
+ req.Count = 50
+ }
+ region := s.region
+ if region == "" {
+ region = "local"
+ }
+ boxes, err := s.store.ReservePooledForEdge(c.Request().Context(), region, poolTemplateName(), req.Count)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ out := make([]map[string]string, 0, len(boxes))
+ for _, b := range boxes {
+ out = append(out, map[string]string{"sandboxID": b.SandboxID, "workerID": b.WorkerID})
+ }
+ log.Printf("pool: edge-reserved %d box(es) (asked %d)", len(out), req.Count)
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "region": region,
+ "sandboxDomain": s.sandboxDomain,
+ "boxes": out,
+ })
+}
+
+// edgeReleasePool handles POST /internal/pool/edge-release {sandboxIDs} — the
+// DO returning stock it discarded without ever handing out (safe to re-pool).
+func (s *Server) edgeReleasePool(c echo.Context) error {
+ var req struct {
+ SandboxIDs []string `json:"sandboxIDs"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})
+ }
+ n, err := s.store.ReleaseEdgeReservations(c.Request().Context(), req.SandboxIDs)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ if n > 0 {
+ log.Printf("pool: edge released %d reservation(s) back to pool", n)
+ }
+ return c.JSON(http.StatusOK, map[string]int{"released": n})
+}
+
+// claimFinalize handles POST /internal/sandboxes/claim-finalize — the async
+// bookkeeping half of an edge claim. The edge has ALREADY returned the 201
+// (token minted, route cache seeded); this binds the box to the customer:
+// PG rebind, worker ClaimSandbox (billing suppression off, idle timeout,
+// envs), pending→running promote, and the resource grow if the request isn't
+// the pre-grown default shape. Mirrors tryClaimPooled minus the HTTP response.
+//
+// Failure here means the customer holds a token for a box that never bound —
+// rare (reservation reaped or worker died in the window). We mark the session
+// failed so the box is never re-issued and the customer's first op surfaces a
+// clean error instead of a phantom.
+func (s *Server) claimFinalize(c echo.Context) error {
+ // SandboxConfig.SandboxID is json:"-" (it's an internal pre-assignment
+ // field), so carry the id in a wrapper — the outer field shadows the
+ // embedded one for JSON binding.
+ var req struct {
+ types.SandboxConfig
+ SandboxID string `json:"sandboxID"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})
+ }
+ if req.SandboxID == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandboxID required"})
+ }
+ cfg := req.SandboxConfig
+ cfg.SandboxID = req.SandboxID
+ // Edge eligibility should have filtered these; enforce anyway so finalize
+ // can't silently skip a capability the box was never given.
+ if cfg.SecretStore != "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "secret stores are not edge-claimable"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusForbidden, map[string]string{"error": "no org in capability token"})
+ }
+ ctx := c.Request().Context()
+
+ cfgJSON, _ := json.Marshal(cfgForPersistence(cfg))
+ metadataJSON, _ := json.Marshal(cfg.Metadata)
+ box, err := s.store.ClaimReservedSession(ctx, cfg.SandboxID, orgID, auth.GetUserID(c), cfgJSON, metadataJSON, nil)
+ if err != nil {
+ // Reservation lost (reaped/drained). Nothing is bound; make sure the
+ // row can never be claimed by anyone else and report the loss.
+ log.Printf("sandbox: EDGE CLAIM FINALIZE LOST %s (%v)", cfg.SandboxID, err)
+ _ = s.store.WipePooled(ctx, cfg.SandboxID)
+ return c.JSON(http.StatusConflict, map[string]string{"error": "reservation lost"})
+ }
+
+ client, err := s.workerRegistry.GetWorkerClient(box.WorkerID)
+ if err != nil {
+ msg := "pool worker unreachable at claim-finalize"
+ _ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "failed", &msg)
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": msg})
+ }
+ grpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ claimResp, err := client.ClaimSandbox(grpcCtx, &pb.ClaimSandboxRequest{
+ SandboxId: box.SandboxID,
+ Timeout: int32(cfg.Timeout),
+ Envs: cfg.Envs,
+ SecretEnvs: cfg.SecretEnvs,
+ MemoryMb: int32(cfg.MemoryMB),
+ CpuCount: int32(cfg.CpuCount),
+ })
+ if err != nil {
+ log.Printf("sandbox: edge claim-finalize ClaimSandbox %s failed: %v", box.SandboxID, err)
+ msg := err.Error()
+ _ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "failed", &msg)
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": msg})
+ }
+
+ _ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "running", nil)
+ if g := claimResp.GetGoldenVersion(); g != "" {
+ _ = s.store.SetSandboxGoldenVersion(ctx, box.SandboxID, g)
+ }
+
+ // Grow past the pre-grown default shape if asked (mirrors tryClaimPooled).
+ // Boxes are manufactured at the default create shape, so this is a no-op
+ // for edge-eligible requests; kept general for safety.
+ if cfg.MemoryMB > 0 || cfg.CpuCount > 0 {
+ scaleMB := cfg.MemoryMB
+ if scaleMB <= 0 {
+ scaleMB = 1024
+ }
+ cpuCount := cfg.CpuCount
+ if cpuCount <= 0 {
+ cpuCount = scaleMB / 4096
+ if cpuCount < 1 {
+ cpuCount = 1
+ }
+ }
+ scaleCtx, scaleCancel := context.WithTimeout(ctx, 10*time.Second)
+ _, scaleErr := client.SetSandboxLimits(scaleCtx, &pb.SetSandboxLimitsRequest{
+ SandboxId: box.SandboxID,
+ MaxMemoryBytes: int64(scaleMB) * 1024 * 1024,
+ CpuMaxUsec: int64(cpuCount) * 100000,
+ CpuPeriodUsec: 100000,
+ })
+ scaleCancel()
+ if scaleErr != nil {
+ log.Printf("sandbox: edge claim-finalize post-scale %s failed: %v (continuing)", box.SandboxID, scaleErr)
+ }
+ }
+
+ s.emitEvent("create", box.SandboxID, box.WorkerID, "claimed from warm pool (edge)")
+ log.Printf("sandbox: EDGE CLAIM FINALIZED %s (worker=%s)", box.SandboxID, box.WorkerID)
+ return c.JSON(http.StatusOK, map[string]string{
+ "sandboxID": box.SandboxID,
+ "workerID": box.WorkerID,
+ "status": "running",
+ })
+}
+
+// reapStaleEdgeReservations destroys edge_reserved boxes older than
+// edgeReserveTTL — the backstop for a Durable Object that died without
+// releasing its stock. Destroyed, never re-pooled: see the lifecycle note.
+func (s *Server) reapStaleEdgeReservations(ctx context.Context) {
+ boxes, err := s.store.ListStaleEdgeReservations(ctx, edgeReserveTTL)
+ if err != nil {
+ log.Printf("pool: list stale edge reservations failed: %v", err)
+ return
+ }
+ for _, b := range boxes {
+ if client, cerr := s.workerRegistry.GetWorkerClient(b.WorkerID); cerr == nil {
+ dctx, cancel := context.WithTimeout(ctx, 15*time.Second)
+ _, _ = client.DestroySandbox(dctx, &pb.DestroySandboxRequest{SandboxId: b.SandboxID})
+ cancel()
+ }
+ _ = s.store.WipePooled(ctx, b.SandboxID)
+ }
+ if len(boxes) > 0 {
+ log.Printf("pool: reaped %d stale edge reservation(s)", len(boxes))
+ }
+}
diff --git a/internal/api/pool.go b/internal/api/pool.go
index d49b3e5b..e512e76a 100644
--- a/internal/api/pool.go
+++ b/internal/api/pool.go
@@ -165,6 +165,9 @@ func (s *Server) StartPoolReconciler(ctx context.Context, isLeader func() bool)
if target := s.poolTarget(); target > 0 {
s.reconcilePool(ctx, region, template, target)
}
+ // Backstop: destroy edge reservations a dead DO never released
+ // (see edge_claim.go for why destroy, not re-pool).
+ s.reapStaleEdgeReservations(ctx)
}
}
}
diff --git a/internal/api/router.go b/internal/api/router.go
index 6ccdd2a8..28a03d3f 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -341,6 +341,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
if s.capTokenIssuer != nil && s.workerRegistry != nil {
internal := e.Group("/internal", s.capTokenMiddleware)
internal.POST("/sandboxes/create", s.internalCreateSandbox)
+ // Edge claim (see edge_claim.go): the api-edge PoolStock DO reserves
+ // pool boxes ahead of time and finalizes claims asynchronously.
+ internal.POST("/pool/edge-reserve", s.edgeReservePool)
+ internal.POST("/pool/edge-release", s.edgeReleasePool)
+ internal.POST("/sandboxes/claim-finalize", s.claimFinalize)
// Cross-cell paused-cap enforcement: the edge (which has the org-global
// view via D1) calls this to promote a specific paused sandbox to deep
// hibernation, reclaiming its worker RAM.
diff --git a/internal/controlplane/capacity_reporter.go b/internal/controlplane/capacity_reporter.go
index e0fc19a6..cfdfaa37 100644
--- a/internal/controlplane/capacity_reporter.go
+++ b/internal/controlplane/capacity_reporter.go
@@ -19,10 +19,14 @@ import (
// row in D1 with healthy_workers / available_workers / running_sandboxes /
// capacity_updated_at, which the api-edge consults in its pickCell() cascade.
//
-// "available" = worker whose CommittedMemoryMB / TotalMemoryMB is below the
-// pressure threshold (~85%). Single-worker-below-threshold is the right
-// placement gate because a sandbox lands on one worker — aggregating across
-// the cell would wrongly skip a cell with 1 free worker and 9 loaded ones.
+// "available" = worker whose REAL memory usage (MemPct, RSS-based) is below
+// the pressure threshold (~85%) — the same signal the routing hard-caps use.
+// NOT committed memory: virtio-mem boxes are demand-backed, so a pre-grown
+// warm pool commits pool_target×4GB while touching a fraction of it — gating
+// on committed read a 9%-used dev fleet as full (available_workers=0 → every
+// create 503'd). Single-worker-below-threshold is the right placement gate
+// because a sandbox lands on one worker — aggregating across the cell would
+// wrongly skip a cell with 1 free worker and 9 loaded ones.
//
// Reuses the existing event pipe so there's no second transport, no new HMAC
// path, no new ingest endpoint. Cost: one extra event per cell per
@@ -146,7 +150,7 @@ func (r *CapacityReporter) emit(ctx context.Context) {
}
healthy++
running += w.Current
- if w.TotalMemoryMB > 0 && (w.CommittedMemoryMB*100)/w.TotalMemoryMB < memPressureThresholdPct {
+ if w.MemPct < memPressureThresholdPct {
available++
}
}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index a5dfbf01..61068bfd 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -1001,15 +1001,17 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Wor
}
// Refuse to drain if doing so would leave zero workers with placement room.
- // The capacity reporter classifies a worker as "available" only when
- // committed_memory_mb / total_memory_mb < memPressureThresholdPct. Picking
- // the lightest-load worker as a drain target is fine when the rest of the
- // fleet has spare memory, but if every other worker is already over the
- // pressure line, draining the only low-pressure worker leaves the cell
+ // The capacity reporter classifies a worker as "available" only when its
+ // REAL memory usage (MemPct, RSS-based) < memPressureThresholdPct — mirror
+ // that here so the drain guard and the availability signal can't disagree.
+ // (Was committed-based; a pre-grown warm pool keeps committed near 100%
+ // permanently, which would have refused every future rolling replace.)
+ // Picking the lightest-load worker as a drain target is fine when the rest
+ // of the fleet has spare memory, but if every other worker is already over
+ // the pressure line, draining the only low-pressure worker leaves the cell
// reporting available_workers=0. The edge then rejects every new
// /api/sandboxes with "no cells available with capacity" — exactly the
- // outage we hit on 2026-05-27 (4 workers, 2 overcommitted at 89%/137%,
- // scaler drained the only 2 healthy ones).
+ // outage we hit on 2026-05-27 (scaler drained the only healthy workers).
availableAfter := 0
for _, w := range workers {
if w == nil || w.MachineID == target.MachineID {
@@ -1018,15 +1020,12 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Wor
if s.state.IsDraining(w.MachineID) {
continue
}
- if w.TotalMemoryMB <= 0 {
- continue
- }
- if (w.CommittedMemoryMB*100)/w.TotalMemoryMB < memPressureThresholdPct {
+ if w.MemPct < memPressureThresholdPct {
availableAfter++
}
}
if availableAfter < 1 {
- log.Printf("scaler: refusing smart drain of %s — would leave 0 workers under memory pressure threshold (%d%% committed cutoff); fleet has %d worker(s) but the rest are over the placement line",
+ log.Printf("scaler: refusing smart drain of %s — would leave 0 workers under memory pressure threshold (%d%% real-usage cutoff); fleet has %d worker(s) but the rest are over the placement line",
target.MachineID, memPressureThresholdPct, len(workers))
return
}
diff --git a/internal/db/pool.go b/internal/db/pool.go
index f4488beb..5201889c 100644
--- a/internal/db/pool.go
+++ b/internal/db/pool.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -99,7 +100,7 @@ func (s *Store) CountPooled(ctx context.Context, region, template string) (int,
func (s *Store) CountPooledOnWorker(ctx context.Context, workerID, template string) (int, error) {
var n int
err := s.pool.QueryRow(ctx,
- `SELECT COUNT(*) FROM sandbox_sessions WHERE status='pooled' AND worker_id=$1 AND template=$2`,
+ `SELECT COUNT(*) FROM sandbox_sessions WHERE status IN ('pooled','edge_reserved') AND worker_id=$1 AND template=$2`,
workerID, template,
).Scan(&n)
return n, err
@@ -111,7 +112,7 @@ func (s *Store) CountPooledOnWorker(ctx context.Context, workerID, template stri
// must not block the worker's termination.
func (s *Store) ListPooledOnWorker(ctx context.Context, workerID string) ([]string, error) {
rows, err := s.pool.Query(ctx,
- `SELECT sandbox_id FROM sandbox_sessions WHERE status='pooled' AND worker_id=$1`, workerID)
+ `SELECT sandbox_id FROM sandbox_sessions WHERE status IN ('pooled','edge_reserved') AND worker_id=$1`, workerID)
if err != nil {
return nil, err
}
@@ -127,11 +128,123 @@ func (s *Store) ListPooledOnWorker(ctx context.Context, workerID string) ([]stri
return ids, rows.Err()
}
-// WipePooled marks a pooled box stopped (worker drain). Guarded on
-// status='pooled' so a box claimed in the meantime is never clobbered.
+// WipePooled marks a pooled box stopped (worker drain). Guarded on the parked
+// statuses (pooled / edge_reserved) so a box claimed in the meantime is never
+// clobbered.
func (s *Store) WipePooled(ctx context.Context, sandboxID string) error {
_, err := s.pool.Exec(ctx,
`UPDATE sandbox_sessions SET status='stopped', stopped_at=now(), hibernation_mode=NULL
- WHERE sandbox_id=$1 AND status='pooled'`, sandboxID)
+ WHERE sandbox_id=$1 AND status IN ('pooled','edge_reserved')`, sandboxID)
return err
}
+
+// ReservePooledForEdge flips up to n pooled boxes to status='edge_reserved' and
+// returns them — the edge PoolStock Durable Object's restock call. Reserved
+// boxes are invisible to ClaimPooledSession (which filters status='pooled'), so
+// the edge and CP claim paths can never hand the same box to two customers.
+// A reservation that is never claimed is returned to the pool by
+// ReleaseStaleEdgeReservations (updated_at is bumped by the status trigger).
+func (s *Store) ReservePooledForEdge(ctx context.Context, region, template string, n int) ([]ClaimedBox, error) {
+ rows, err := s.pool.Query(ctx,
+ `UPDATE sandbox_sessions SET status='edge_reserved'
+ WHERE sandbox_id IN (
+ SELECT sandbox_id FROM sandbox_sessions
+ WHERE status='pooled' AND region=$1 AND template=$2
+ ORDER BY started_at ASC
+ LIMIT $3 FOR UPDATE SKIP LOCKED
+ )
+ RETURNING sandbox_id, worker_id`,
+ region, template, n,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("reserve pooled for edge: %w", err)
+ }
+ defer rows.Close()
+ var boxes []ClaimedBox
+ for rows.Next() {
+ var b ClaimedBox
+ if err := rows.Scan(&b.SandboxID, &b.WorkerID); err != nil {
+ return nil, err
+ }
+ boxes = append(boxes, b)
+ }
+ return boxes, rows.Err()
+}
+
+// ClaimReservedSession binds a specific edge_reserved box to a customer —
+// the finalize half of an edge claim (the edge already returned the 201; this
+// is the async bookkeeping). Mirrors ClaimPooledSession's rebind but by
+// sandbox_id: the status guard means a stale-reservation reap or a worker
+// drain in the window loses the race cleanly (we error, the caller marks the
+// customer-visible session failed).
+func (s *Store) ClaimReservedSession(ctx context.Context, sandboxID string, orgID uuid.UUID, userID *uuid.UUID, config, metadata json.RawMessage, secretStoreID *uuid.UUID) (*ClaimedBox, error) {
+ if len(config) == 0 {
+ config = json.RawMessage(`{}`)
+ }
+ if len(metadata) == 0 {
+ metadata = json.RawMessage(`{}`)
+ }
+ var box ClaimedBox
+ err := s.pool.QueryRow(ctx,
+ `UPDATE sandbox_sessions SET
+ org_id = $1, user_id = $2, secret_store_id = $3, config = $4, metadata = $5,
+ status = 'pending', hibernation_mode = NULL, paused_at = NULL
+ WHERE sandbox_id = $6 AND status = 'edge_reserved'
+ RETURNING sandbox_id, worker_id`,
+ orgID, userID, secretStoreID, config, metadata, sandboxID,
+ ).Scan(&box.SandboxID, &box.WorkerID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, ErrPoolEmpty
+ }
+ if err != nil {
+ return nil, fmt.Errorf("claim reserved session: %w", err)
+ }
+ return &box, nil
+}
+
+// ReleaseEdgeReservations returns specific edge_reserved boxes to the pool.
+// ONLY safe for boxes the edge explicitly discarded from its stock BEFORE
+// handing them to any customer — a popped entry has a minted sandbox token in
+// the wild, and a re-pooled box with a live foreign token would be a
+// cross-tenant hole. The status guard skips anything already claimed.
+func (s *Store) ReleaseEdgeReservations(ctx context.Context, sandboxIDs []string) (int, error) {
+ if len(sandboxIDs) == 0 {
+ return 0, nil
+ }
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions SET status='pooled'
+ WHERE sandbox_id = ANY($1) AND status='edge_reserved'`,
+ sandboxIDs,
+ )
+ if err != nil {
+ return 0, fmt.Errorf("release edge reservations: %w", err)
+ }
+ return int(tag.RowsAffected()), nil
+}
+
+// ListStaleEdgeReservations returns edge_reserved boxes older than ttl — the
+// destroy-backstop reaper's input. Unlike ReleaseEdgeReservations these are
+// DESTROYED, not re-pooled: the CP can't prove the edge never minted a token
+// for them (a dead Durable Object can't release its stock), and a re-issued
+// box with a live foreign token would be cross-tenant access. Remanufacture
+// is cheap; the hole is not.
+func (s *Store) ListStaleEdgeReservations(ctx context.Context, ttl time.Duration) ([]ClaimedBox, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT sandbox_id, worker_id FROM sandbox_sessions
+ WHERE status='edge_reserved' AND updated_at < now() - $1::interval`,
+ fmt.Sprintf("%d seconds", int(ttl.Seconds())),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("list stale edge reservations: %w", err)
+ }
+ defer rows.Close()
+ var boxes []ClaimedBox
+ for rows.Next() {
+ var b ClaimedBox
+ if err := rows.Scan(&b.SandboxID, &b.WorkerID); err != nil {
+ return nil, err
+ }
+ boxes = append(boxes, b)
+ }
+ return boxes, rows.Err()
+}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 2101641d..9e1eee45 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -366,6 +366,15 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
if w, ok := s.manager.(guestWarmer); ok {
w.WarmGuest(ctx, sb.ID)
}
+ // Pre-grow to the default create shape (4GB/1cpu) so an edge claim
+ // of a default-shape request needs ZERO worker calls — the box is
+ // already the right size. virtio-mem is demand-backed, so guest-
+ // visible 4GB costs only the pages actually touched. No scale event:
+ // pool boxes are unbilled; billing opens at claim. Best-effort — a
+ // failed grow leaves a 1GB box the claim path grows as before.
+ if err := s.manager.SetResourceLimits(ctx, sb.ID, 0, 4096*1024*1024, 100000, 100000); err != nil {
+ log.Printf("grpc: pool pre-grow %s failed: %v (claim will grow)", sb.ID, err)
+ }
parked = "hot (running)"
} else if _, perr := pm.Pause(ctx, sb.ID); perr != nil {
_ = s.manager.Kill(context.Background(), sb.ID) // a box that won't pause is useless as a pool entry
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index ba8b8d24..7b3215c9 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -11,6 +11,7 @@ import (
"net/http"
"os"
"strconv"
+ "strings"
"sync"
"time"
@@ -449,11 +450,22 @@ func (s *HTTPServer) execRunAsync(c echo.Context) error {
// returned). ensureRunning (the wake/restore) and the command both
// run here, off the connection.
t0 := time.Now()
- var err error
- if s.router != nil {
- err = s.router.Route(context.Background(), id, "execRun", routeOp)
- } else {
- err = routeOp(context.Background())
+ route := func() error {
+ if s.router != nil {
+ return s.router.Route(context.Background(), id, "execRun", routeOp)
+ }
+ return routeOp(context.Background())
+ }
+ err := route()
+ // Transient per-sandbox op conflict — e.g. an exec racing the async
+ // claim-finalize of an edge-claimed box (ClaimSandbox holds the
+ // sandbox lock for ~100ms) or any in-flight pause/resume. We're in a
+ // background goroutine, so wait it out instead of failing the exec:
+ // polls report waking meanwhile, and a conflict that clears inside
+ // the run-async inline hold still returns single-round-trip.
+ for attempt := 0; err != nil && strings.Contains(err.Error(), "another operation is in progress") && attempt < 20; attempt++ {
+ time.Sleep(150 * time.Millisecond)
+ err = route()
}
wakeMs := time.Since(t0).Milliseconds() - createMs
if wakeMs < 0 {