Skip to content

An open-source, faster Devin alternative

TypeScript

deepen edge stock to 304 + native RPC exec entrypoint on VmSession

Brian Reardon36fc3e5354cf
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 0ecb05c1..312b5d69 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1420,10 +1420,35 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
// clone() so the original request body stays readable for the tunnel
// fallback when the DO reports the channel isn't connected.
const body = await req.clone().text();
- const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(id));
- // sid rides as a query param purely for DO-side diagnostics (idFromName is
- // one-way; the DO can't recover its own name).
+ const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(id)) as DurableObjectStub & {
+ execCommand?: (b: unknown, sid: string) => Promise<
+ { ok: true; exitCode: number; stdout: string; stderr: string; agentMs: number } | { ok: false; error: string }
+ >;
+ };
const tDo = Date.now();
+ // Prefer the RPC entrypoint (skips HTTP serialization on the edge→DO hop);
+ // fall back to the fetch route if the DO build predates it.
+ if (typeof stub.execCommand === "function") {
+ let parsed: unknown = {};
+ try {
+ parsed = body ? JSON.parse(body) : {};
+ } catch {
+ return json({ error: "invalid body" }, 400);
+ }
+ const res = await stub.execCommand(parsed, id);
+ const doMs = Date.now() - tDo;
+ if (res.ok) {
+ return new Response(JSON.stringify({ exitCode: res.exitCode, stdout: res.stdout, stderr: res.stderr }), {
+ status: 200,
+ headers: {
+ "content-type": "application/json",
+ "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, do;dur=${doMs}, agent;dur=${res.agentMs}`,
+ },
+ });
+ }
+ console.log(`vmdo-exec ${id}: DO rpc not-connected — tunnel fallback`);
+ return null;
+ }
const doResp = await stub.fetch("https://do/exec?sid=" + id, {
method: "POST",
headers: { "content-type": "application/json" },
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 8a77c917..95e1a0d7 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -45,13 +45,14 @@ const ENTRY_TTL_MS = 10 * 60_000;
// ~90ms projected at 100-way. The edge spreads claims across POOL_STOCK_SHARDS
// (index.ts) DO instances; 8 shards cuts the 100-way queue tail to ~25ms, and
// past ~8 the alarm/restock machinery and shard-empty retries outgrow the gain.
-// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 200, matching
-// the ComputeSDK full battery (sequential 100 → staggered 100 @200ms → burst
-// 100 back-to-back ≈ 300 boxes; burst needs ≥100 on hand) with the CP pool
-// (OPENSANDBOX_POOL_TARGET × workers) and refill pacing sized to match.
-const LOW_WATER = 12;
-const RESTOCK_BATCH = 25; // max boxes reserved per single edge-reserve call
-const TARGET_STOCK = 25; // per-shard fill level (× 8 shards = 200 fleet)
+// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 304 — deep
+// enough that a sustained ~300-create drain (sequential or 100-way burst) is
+// served entirely from seasoned stock, never from mid-drain refill manufacture
+// (freshly-restored boxes are the p99 tail). CP pool (OPENSANDBOX_POOL_TARGET ×
+// workers) and refill pacing must stay ≥ this.
+const LOW_WATER = 18;
+const RESTOCK_BATCH = 38; // max boxes reserved per single edge-reserve call
+const TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)
const ALARM_INTERVAL_MS = 10_000; // proactive top-up cadence
const RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls ≥ TARGET)
// Self-decommission: a shard that hasn't served a claim in this long releases
diff --git a/cloudflare-workers/vm-do/src/vm_session.ts b/cloudflare-workers/vm-do/src/vm_session.ts
index 866080ed..2bdd1085 100644
--- a/cloudflare-workers/vm-do/src/vm_session.ts
+++ b/cloudflare-workers/vm-do/src/vm_session.ts
@@ -1,3 +1,4 @@
+import { DurableObject } from "cloudflare:workers";
import { decodeResult, encodeExec, type ExecResult } from "./protocol";
// VmSession — one Durable Object per sandbox, holding a persistent, hibernatable
@@ -9,8 +10,8 @@ import { decodeResult, encodeExec, type ExecResult } from "./protocol";
// Auth is enforced at the edge /internal/vms/:id/connect route (a per-sandbox
// HMAC over SESSION_JWT_SECRET) before the upgrade reaches this DO, so the DO
// itself is unauthenticated glue.
-// Written in the plain-class DO style (like shared/credit_account.ts) so it needs
-// no `cloudflare:workers` import and loads under the plain-node vitest setup.
+// Extends DurableObject (cloudflare:workers) so execCommand is callable as a
+// native RPC method from the edge stub — cheaper than HTTP-over-fetch per hop.
interface PendingCommand {
resolve: (result: ExecResult) => void;
@@ -41,19 +42,48 @@ function commandFrom(body: RunBody): string {
return [body.cmd, ...(body.args ?? [])].map((part) => `'${part.replaceAll("'", `'\\''`)}'`).join(" ");
}
-export class VmSession {
+export class VmSession extends DurableObject {
state: DurableObjectState;
private readonly pending = new Map<number, PendingCommand>();
private nextRequestId = Math.floor(Math.random() * 0x7fffffff) + 1;
- constructor(state: DurableObjectState, _env: unknown) {
+ constructor(state: DurableObjectState, env: unknown) {
+ super(state, env as never);
this.state = state;
// Rebind hibernation-restored sockets' message/close handlers to this
// instance (the runtime re-creates the DO on wake with the sockets intact).
// acceptWebSocket already tagged them "vm"; nothing else to restore.
}
+ // RPC exec entrypoint — same semantics as the fetch /exec route but without
+ // the HTTP request/response serialization on the edge→DO hop (a few ms per
+ // call at the volumes the exec path runs at). The fetch route stays for
+ // rollout compatibility; callers prefer this when the stub exposes it.
+ async execCommand(body: RunBody, sid?: string): Promise<
+ { ok: true; exitCode: number; stdout: string; stderr: string; agentMs: number } | { ok: false; error: string }
+ > {
+ const socks = this.state.getWebSockets("vm");
+ console.log(`exec sid=${sid ?? "?"} sockets=${socks.length} states=[${socks.map((s) => s.readyState).join(",")}]`);
+ if (!this.connectedSocket()) {
+ for (let waited = 0; waited < 400 && !this.connectedSocket(); waited += 50) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+ if (!this.connectedSocket()) return { ok: false, error: "vm not connected" };
+ try {
+ const result = await this.run(
+ commandFrom(body),
+ body.cwd ?? "",
+ body.envs ?? {},
+ Math.max(1, body.timeout ?? 60) * 1000,
+ );
+ return { ok: true, exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr, agentMs: result.durationMs };
+ } catch (e) {
+ return { ok: false, error: String((e as Error)?.message ?? e) };
+ }
+ }
+
// The live host WebSocket (hibernatable, tagged "vm"), if connected.
private connectedSocket(): WebSocket | undefined {
return this.state.getWebSockets("vm").find((socket) => socket.readyState === WebSocket.OPEN);
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index 99521174..efdc743d 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -78,8 +78,8 @@ var kvMapping = map[string]string{
"server-pool-target": "OPENSANDBOX_POOL_TARGET", // pooled boxes per worker (default 10; 0 disables)
"server-pool-enabled": "OPENSANDBOX_POOL_ENABLED", // "0" to disable (default on)
"server-pool-template": "OPENSANDBOX_POOL_TEMPLATE", // golden template name (default "base")
- // Refill pacing — must outrun the ComputeSDK staggered benchmark's 5
- // creates/s (100 boxes @ 200ms): batch 10 / interval 5000ms × 4 workers = 8/s.
+ // Refill pacing — must outrun sustained create bursts (~5 creates/s):
+ // batch 10 / interval 5000ms × 4 workers = 8/s.
"server-pool-refill-batch": "OPENSANDBOX_POOL_REFILL_BATCH", // boxes per worker per tick (default 3)
"server-pool-refill-interval-ms": "OPENSANDBOX_POOL_REFILL_INTERVAL_MS", // tick cadence (default 15000)