Skip to content

An open-source, faster Devin alternative

TypeScript

Verify+pre-warm exec channel at claim with box-swap, async bounded destroys

Brian Reardon26539736384e
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 312b5d69..19a95f26 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1220,19 +1220,38 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
// coprime-ish to 8) — at full stock the first hit ends it; under sparse
// stock (small cells, mid-battery drain) 3 samples cut the false-fallback
// rate from ~(empty/8)² to ~(empty/8)³ for ~10ms per extra probe.
- let r: Response | null = null;
+ //
+ // Each popped box is then VERIFIED: one /status call to its VmSession —
+ // which doubles as the pre-warm (it wakes the DO hibernated since the
+ // manufacture dial, so the customer's first exec never pays the isolate
+ // wake) and as the liveness gate (dead host channel → swap to another
+ // box instead of letting the first exec discover it and tunnel ~1.3s).
+ // A rejected box stays edge_reserved; the cell's 15-min reaper collects it.
+ let box: { id: string; workerID: string; region: string; sandboxDomain: string } | null = null;
let shard = Math.floor(Math.random() * POOL_STOCK_SHARDS);
const stride = 1 + Math.floor(Math.random() * (POOL_STOCK_SHARDS - 1));
- for (let attempt = 0; attempt < 3; attempt++) {
- r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim", {
+ for (let attempt = 0; attempt < 3 && !box; attempt++) {
+ const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim", {
method: "POST",
body: claimBody,
});
- if (r.ok) break;
shard = (shard + stride) % POOL_STOCK_SHARDS;
+ if (!r.ok) continue;
+ const candidate = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };
+ try {
+ const st = (await env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(candidate.id))
+ .fetch("https://do/status")
+ .then((sr) => sr.json())) as { connected?: boolean };
+ if (st.connected) {
+ box = candidate;
+ } else {
+ console.log(`edge-claim: ${candidate.id} exec channel down — swapping box`);
+ }
+ } catch {
+ console.log(`edge-claim: ${candidate.id} status check failed — swapping box`);
+ }
}
- if (r && r.ok) {
- const box = (await r.json()) as { id: string; workerID: string; region: string; sandboxDomain: string };
+ if (box) {
mark("claim");
const token = await mintSandboxToken(env.SESSION_JWT_SECRET, caller.orgID, box.id, box.workerID);
if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
@@ -1422,7 +1441,8 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
const body = await req.clone().text();
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 }
+ | { ok: true; exitCode: number; stdout: string; stderr: string; agentMs: number; internalMs?: number }
+ | { ok: false; error: string }
>;
};
const tDo = Date.now();
@@ -1442,7 +1462,7 @@ async function tryVmDoExec(req: Request, env: Env, caller: Caller, id: string, a
status: 200,
headers: {
"content-type": "application/json",
- "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, do;dur=${doMs}, agent;dur=${res.agentMs}`,
+ "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, do;dur=${doMs}, doin;dur=${res.internalMs ?? -1}, agent;dur=${res.agentMs}`,
},
});
}
diff --git a/cloudflare-workers/vm-do/src/vm_session.ts b/cloudflare-workers/vm-do/src/vm_session.ts
index 2bdd1085..f8f36814 100644
--- a/cloudflare-workers/vm-do/src/vm_session.ts
+++ b/cloudflare-workers/vm-do/src/vm_session.ts
@@ -61,8 +61,12 @@ export class VmSession extends DurableObject {
// 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 }
+ | { ok: true; exitCode: number; stdout: string; stderr: string; agentMs: number; internalMs: number }
+ | { ok: false; error: string }
> {
+ // internalMs = time spent INSIDE this method. The edge's do;dur minus this
+ // = isolate wake + edge→DO transit — the unattributed gap in the exec tail.
+ const tEntry = Date.now();
const socks = this.state.getWebSockets("vm");
console.log(`exec sid=${sid ?? "?"} sockets=${socks.length} states=[${socks.map((s) => s.readyState).join(",")}]`);
if (!this.connectedSocket()) {
@@ -78,7 +82,14 @@ export class VmSession extends DurableObject {
body.envs ?? {},
Math.max(1, body.timeout ?? 60) * 1000,
);
- return { ok: true, exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr, agentMs: result.durationMs };
+ return {
+ ok: true,
+ exitCode: result.exitCode,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ agentMs: result.durationMs,
+ internalMs: Date.now() - tEntry,
+ };
} catch (e) {
return { ok: false, error: String((e as Error)?.message ?? e) };
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index cf0a6769..54093d0e 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -570,6 +570,13 @@ func (s *GRPCServer) ClaimSandbox(ctx context.Context, req *pb.ClaimSandboxReque
GoldenVersion: sb.GoldenVersion}, nil
}
+// destroySem bounds background teardown concurrency. A bench/agent-shaped
+// workload destroys dozens of boxes in seconds; each Kill is QEMU-teardown +
+// overlay-unlink heavy, and running them foreground-concurrent competes with
+// live execs on the same host (measured as exec-tail blips). Three at a time
+// keeps the disk quiet while draining a 100-destroy burst in ~30s.
+var destroySem = make(chan struct{}, 3)
+
func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxRequest) (*pb.DestroySandboxResponse, error) {
// Tear the VM-DO exec channel down first so an in-flight exec can't land on
// a box we're about to kill (it falls back to the tunnel, which 404s cleanly).
@@ -582,26 +589,35 @@ func (s *GRPCServer) DestroySandbox(ctx context.Context, req *pb.DestroySandboxR
}
}
- if err := s.manager.Kill(ctx, req.SandboxId); err != nil {
- return nil, fmt.Errorf("failed to destroy sandbox: %w", err)
- }
-
// Unregister from sandbox router
if s.router != nil {
s.router.Unregister(req.SandboxId)
}
- // Emit terminal lifecycle event BEFORE removing the per-sandbox SQLite.
- // The SandboxDBManager's OnRemove hook synchronously flushes any unsynced
- // events to Redis, so this event makes it upstream to events-ingest, which
- // updates D1 sandboxes_index. Without this, terminations leak as phantoms
- // in the global view.
- if s.sandboxDBs != nil {
- if sdb, dbErr := s.sandboxDBs.Get(req.SandboxId); dbErr == nil {
- _ = sdb.LogEvent("stopped", map[string]string{"sandbox_id": req.SandboxId})
+ // The heavy teardown (QEMU kill + overlay unlink + SQLite flush) runs in the
+ // background, bounded by destroySem — the caller gets an immediate ack, and
+ // the CP's PG row is gone regardless. A failed/stuck Kill is collected by
+ // the orphan reaper, so deferring loses no safety, only foreground I/O.
+ go func(id string) {
+ destroySem <- struct{}{}
+ defer func() { <-destroySem }()
+ killCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ if err := s.manager.Kill(killCtx, id); err != nil {
+ log.Printf("grpc: background destroy %s: %v (orphan reaper will collect)", id, err)
}
- _ = s.sandboxDBs.Remove(req.SandboxId)
- }
+ // Emit terminal lifecycle event BEFORE removing the per-sandbox SQLite.
+ // The SandboxDBManager's OnRemove hook synchronously flushes any unsynced
+ // events to Redis, so this event makes it upstream to events-ingest, which
+ // updates D1 sandboxes_index. Without this, terminations leak as phantoms
+ // in the global view.
+ if s.sandboxDBs != nil {
+ if sdb, dbErr := s.sandboxDBs.Get(id); dbErr == nil {
+ _ = sdb.LogEvent("stopped", map[string]string{"sandbox_id": id})
+ }
+ _ = s.sandboxDBs.Remove(id)
+ }
+ }(req.SandboxId)
return &pb.DestroySandboxResponse{}, nil
}