An open-source, faster Devin alternative
TypeScript
cut create + burst latency in worker claim path and edge prework
Brian Reardon256187ff1b6b
diff --git a/benchmarks/tti/corr.mjs b/benchmarks/tti/corr.mjsnew file mode 100644index 00000000..0c9091da--- /dev/null+++ b/benchmarks/tti/corr.mjs@@ -0,0 +1,63 @@+#!/usr/bin/env node+/**+ * Correlation harness: fire a burst of concurrent creates, and for EACH request+ * record (a) when it was actually sent relative to burst t0 (sendOffset), (b) its+ * client wall-time (createMs), and (c) the sandbox id. Then grep the CP TIMING+ * logs for each id to see server-side `total` — so we can locate where the burst+ * latency lives (client/edge queue vs server).+ *+ * OPENCOMPUTER_API_KEY=osb_xxx node corr.mjs [--concurrency 20]+ */+import { opencomputer } from '@computesdk/opencomputer';++const flag = (n, e, d) => {+ const i = process.argv.indexOf(`--${n}`);+ if (i !== -1 && process.argv[i + 1] !== undefined) return process.argv[i + 1];+ return process.env[e] ?? d;+};+const API_URL = flag('api-url', 'OPENCOMPUTER_API_URL', 'https://app.opencomputer.dev');+const API_KEY = flag('api-key', 'OPENCOMPUTER_API_KEY', '');+const CONC = parseInt(flag('concurrency', 'CONCURRENCY', '20'), 10);+if (!API_KEY) { console.error('OPENCOMPUTER_API_KEY required'); process.exit(2); }++if (process.env.HICONN) {+ const { setGlobalDispatcher, Agent } = await import('undici');+ setGlobalDispatcher(new Agent({ connections: 256, pipelining: 0 }));+ console.log('(undici hi-conn dispatcher: 256 connections)');+}++const now = () => performance.now();+const idOf = (s) => s?.sandboxId ?? s?.id ?? s?.sandbox?.sandboxId ?? s?.data?.sandboxId ?? 'unknown';++const t0 = now();+const tasks = [];+for (let i = 0; i < CONC; i++) {+ tasks.push((async () => {+ const compute = opencomputer({ apiKey: API_KEY, apiUrl: API_URL });+ const sendOffset = now() - t0;+ const s0 = now();+ try {+ const sandbox = await compute.sandbox.create({ timeout: 600_000 });+ const createMs = now() - s0;+ const id = idOf(sandbox);+ sandbox.destroy().catch(() => {});+ return { i, id, sendOffset, createMs, ok: true };+ } catch (e) {+ return { i, id: 'ERR', sendOffset, createMs: now() - s0, ok: false, err: String(e?.message || e) };+ }+ })());+}+const res = (await Promise.all(tasks)).sort((a, b) => a.createMs - b.createMs);++// dump keys of nothing here; just print rows+console.log(`burst conc=${CONC} → ${API_URL}\n`);+console.log(' idx sendOffset createMs id');+for (const r of res) {+ console.log(+ ` ${String(r.i).padStart(3)} ${String(Math.round(r.sendOffset)).padStart(7)}ms ${String(Math.round(r.createMs)).padStart(6)}ms ${r.id}${r.ok ? '' : ' ERR:' + r.err}`,+ );+}+const cs = res.filter((r) => r.ok).map((r) => r.createMs).sort((a, b) => a - b);+const pct = (q) => Math.round(cs[Math.min(cs.length - 1, Math.ceil(q * cs.length) - 1)]);+console.log(`\n client createMs: min=${Math.round(cs[0])} med=${pct(0.5)} p95=${pct(0.95)} max=${Math.round(cs[cs.length - 1])}`);+console.log(` ids: ${res.filter((r) => r.ok).map((r) => r.id).join(' ')}`);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 2243f287..6690ea46 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -290,6 +290,88 @@ interface CellRow {// cells. Cache per-isolate for a short window.const CELL_TTL_MS = 5_000;const cellCache = new Map<string, { cell: CellRow | null; cachedAtMs: number }>();+// Per-isolate cache of the active-cells list. pickCell ran this SELECT uncached+// on every no-cellId create — ~65ms of the burst prework. Cells change rarely,+// so a short TTL is safe and the routing decision recomputes from cached rows.+let activeCellsCache: { cells: CellRow[]; cachedAtMs: number } | null = null;++async function listActiveCells(env: Env): Promise<CellRow[]> {+ const nowMs = Date.now();+ if (activeCellsCache && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS) return activeCellsCache.cells;+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at+ FROM cells WHERE status = 'active'`,+ ).all<CellRow>();+ const cells = results ?? [];+ activeCellsCache = { cells, cachedAtMs: nowMs };+ return cells;+}++// loadCreateContext fetches the three org-keyed reads the create hot path needs+// — org policy, running-sandbox count, active-cells list — in a SINGLE D1 round+// trip via db.batch(), instead of three sequential awaits. Under a cold burst+// (fresh isolates, caches empty) that collapses ~3×D1-latency into one. Each+// piece still honours + populates its existing per-isolate cache, so warm/+// sustained traffic skips D1 entirely and only the cold misses are batched.+async function loadCreateContext(+ env: Env,+ orgID: string,+): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[] }> {+ const nowMs = Date.now();+ const oc = orgPolicyCache.get(orgID);+ const cc = concurrencyCountCache.get(orgID);+ const orgWarm = oc !== undefined && nowMs - oc.cachedAtMs < ORG_POLICY_TTL_MS;+ const cntWarm = cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS;+ const cellsWarm = activeCellsCache !== null && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS;++ let org = orgWarm ? oc!.policy : null;+ let activeCount = cntWarm ? cc!.count : 0;+ let cells = cellsWarm ? activeCellsCache!.cells : [];++ const stmts: D1PreparedStatement[] = [];+ const kinds: Array<"org" | "count" | "cells"> = [];+ if (!orgWarm) {+ stmts.push(+ env.OPENCOMPUTER_DB.prepare(+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",+ ).bind(orgID),+ );+ kinds.push("org");+ }+ if (!cntWarm) {+ stmts.push(+ env.OPENCOMPUTER_DB.prepare("SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'").bind(orgID),+ );+ kinds.push("count");+ }+ if (!cellsWarm) {+ stmts.push(+ env.OPENCOMPUTER_DB.prepare(+ "SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at FROM cells WHERE status = 'active'",+ ),+ );+ kinds.push("cells");+ }++ if (stmts.length > 0) {+ const res = await env.OPENCOMPUTER_DB.batch(stmts);+ for (let i = 0; i < kinds.length; i++) {+ if (kinds[i] === "org") {+ org = ((res[i].results?.[0] as OrgPolicy) ?? null);+ if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();+ orgPolicyCache.set(orgID, { policy: org, cachedAtMs: nowMs });+ } else if (kinds[i] === "count") {+ activeCount = (res[i].results?.[0] as { n: number } | undefined)?.n ?? 0;+ if (concurrencyCountCache.size >= CACHE_MAX) concurrencyCountCache.clear();+ concurrencyCountCache.set(orgID, { count: activeCount, cachedAtMs: nowMs });+ } else {+ cells = (res[i].results as CellRow[]) ?? [];+ activeCellsCache = { cells, cachedAtMs: nowMs };+ }+ }+ }+ return { org, activeCount, cells };+}async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {const nowMs = Date.now();@@ -367,6 +449,7 @@ async function pickCell(env: Env,homeCell: string,requestedCellID: string | null,+ prefetchedCells?: CellRow[],): Promise<CellRow | null> {const nowSec = Math.floor(Date.now() / 1000);@@ -376,15 +459,17 @@ async function pickCell(return c && isHealthy(c, nowSec) ? c : null;}- // Look up home regardless of health — we still want its {cloud, region}- // as the distance anchor even if home itself is currently loaded.- const home = await lookupCell(env, homeCell);+ // Active-cells list: use the batch-prefetched rows on the create hot path+ // (loadCreateContext), else fetch (cached).+ const results = prefetchedCells ?? (await listActiveCells(env));- const { results } = await env.OPENCOMPUTER_DB.prepare(- `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at- FROM cells WHERE status = 'active'`,- ).all<CellRow>();- const healthy = (results ?? []).filter((c) => isHealthy(c, nowSec));+ // Home anchor for distance ranking. Derive it from the active list when+ // present (no extra read); only fall back to a direct lookup if home isn't+ // active — we still want its {cloud, region} as the anchor in that case.+ let home = results.find((c) => c.cell_id === homeCell) ?? null;+ if (!home) home = await lookupCell(env, homeCell);++ const healthy = results.filter((c) => isHealthy(c, nowSec));if (healthy.length === 0) return null;if (home) {@@ -521,6 +606,7 @@ async function enforceCreatePolicy(orgID: string,org: OrgPolicy,sizes: { cpuCount: number; memoryMB: number; diskMB: number },+ activeCount: number,): Promise<Response | null> {const plan = org.plan === "pro" ? "pro" : "free";@@ -577,21 +663,9 @@ async function enforceCreatePolicy(// every cell via the global sandboxes_index, which is the whole reason it// must live at the edge and not on any single cell.const limit = org.max_concurrent_sandboxes ?? DEFAULT_MAX_CONCURRENT_SANDBOXES;- const nowMs = Date.now();- let active: number;- const cc = concurrencyCountCache.get(orgID);- if (cc && nowMs - cc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS) {- active = cc.count;- } else {- const countRow = await env.OPENCOMPUTER_DB.prepare(- "SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'",- )- .bind(orgID)- .first<{ n: number }>();- active = countRow?.n ?? 0;- if (concurrencyCountCache.size >= CACHE_MAX) concurrencyCountCache.clear();- concurrencyCountCache.set(orgID, { count: active, cachedAtMs: nowMs });- }+ // active count is pre-fetched by loadCreateContext (batched with org+cells)+ // and cached there; enforceCreatePolicy no longer reads it itself.+ const active = activeCount;if (active >= limit) {return json({ error: `concurrent sandbox limit reached (${active}/${limit}) — hibernate or delete one before creating another`, active, limit },@@ -633,6 +707,7 @@ async function insertSandboxIndex(function indexSandboxFromSSE(resp: Response,env: Env,+ ctx: ExecutionContext,caller: Caller,cellID: string,fallbackCpuCount: number,@@ -660,9 +735,17 @@ function indexSandboxFromSSE(try {const parsed = JSON.parse(data) as SandboxCreateResult;- await insertSandboxIndex(env, caller, cellID, parsed, fallbackCpuCount, fallbackMemoryMB);+ // Fire the D1 index write off the response path (waitUntil keeps it alive+ // after we return). Under a burst these serialize on D1's single writer,+ // so awaiting them here stretches the create tail; the index is also+ // reconciled by events-ingest, so a slightly-late row is harmless.+ ctx.waitUntil(+ insertSandboxIndex(env, caller, cellID, parsed, fallbackCpuCount, fallbackMemoryMB).catch((e) =>+ console.error("sandboxes_index SSE create insert failed:", e),+ ),+ );} catch (e) {- console.error("sandboxes_index SSE create insert failed:", e);+ console.error("sandboxes_index SSE create parse failed:", e);}};@@ -703,11 +786,13 @@ function indexSandboxFromSSE(return new Response(resp.body.pipeThrough(stream), resp);}-async function createSandbox(req: Request, env: Env): Promise<Response> {+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);- const org = await loadOrgPolicy(env, caller.orgID);+ // One batched D1 round-trip for org + running-count + active-cells (was three+ // serial reads on the create hot path). Cache-aware: warm isolates skip D1.+ const { org, activeCount, cells } = await loadCreateContext(env, caller.orgID);if (!org) return json({ error: "org not found" }, 401);const plan = org.plan === "pro" ? "pro" : "free";@@ -759,14 +844,18 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {// enforced here against D1. Cells trust the cap-token and no longer// re-check — see enforceCreatePolicy for why the concurrent limit in// particular can only be correct at the edge.- const gate = await enforceCreatePolicy(env, caller.orgID, org, {- cpuCount: bodyCpuCount,- memoryMB: bodyMemoryMB,- diskMB: bodyDiskMB,- });+ // The org-policy gate and cell selection both depend only on `org`, so run+ // them concurrently — under a burst these were two serial D1 round-trips+ // (~90ms) sitting on the create hot path.+ const [gate, cell] = await Promise.all([+ enforceCreatePolicy(env, caller.orgID, org, {+ cpuCount: bodyCpuCount,+ memoryMB: bodyMemoryMB,+ diskMB: bodyDiskMB,+ }, activeCount),+ pickCell(env, org.home_cell, requestedCellID, cells),+ ]);if (gate) return gate;-- const cell = await pickCell(env, org.home_cell, requestedCellID);if (!cell) {return json(requestedCellID@@ -790,7 +879,7 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {headers: { authorization: "Bearer " + capToken, "content-type": "application/json", accept: "text/event-stream" },body: bodyText || "{}",});- return indexSandboxFromSSE(cpResp, env, caller, cell.cell_id, bodyCpuCount, bodyMemoryMB);+ return indexSandboxFromSSE(cpResp, env, ctx, caller, cell.cell_id, bodyCpuCount, bodyMemoryMB);} catch (e) {return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);}@@ -815,7 +904,13 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {} catch {/* leave parsed empty — still record what we can */}- await insertSandboxIndex(env, caller, cell.cell_id, parsed, bodyCpuCount, bodyMemoryMB);+ // Off the response path (see indexSandboxFromSSE) — waitUntil keeps the D1+ // write alive after we return; events-ingest reconciles the row anyway.+ ctx.waitUntil(+ insertSandboxIndex(env, caller, cell.cell_id, parsed, bodyCpuCount, bodyMemoryMB).catch((e) =>+ console.error("sandboxes_index create insert failed:", e),+ ),+ );}// Pass the CP's response through verbatim (status + body).return new Response(cpText, {@@ -2826,7 +2921,7 @@ export default {// /api/sandboxes and /api/sandboxes/:id[/...]if (path === "/api/sandboxes") {- if (req.method === "POST") return createSandbox(req, env);+ if (req.method === "POST") return createSandbox(req, env, ctx);if (req.method === "GET") return listSandboxes(req, env);return json({ error: "method not allowed" }, 405);}@@ -2852,7 +2947,7 @@ export default {if (cpRow.org_id !== caller.orgID) return json({ error: "checkpoint not in your org" }, 403);const cell = await lookupCell(env, cpRow.owner_cell_id);if (!cell) return json({ error: `cell ${cpRow.owner_cell_id} not registered` }, 503);- const org = await loadOrgPolicy(env, caller.orgID);+ const { org, activeCount: fcActive } = await loadCreateContext(env, caller.orgID);if (!org) return json({ error: "org not found" }, 401);// Read the body so we can size-gate, forward it, and record cpu/mem to// register the forked sandbox in sandboxes_index — same as createSandbox.@@ -2874,7 +2969,7 @@ export default {// previously ungated at the edge and leaned on a cell-side concurrent// check that read stale cell PG and could only ever count one cell's// sandboxes — wrong once an org spans cells. Enforce from D1 here.- const fcGate = await enforceCreatePolicy(env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk });+ 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";const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, caller.userID);diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex a50a1090..95ef8768 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -888,11 +888,11 @@ func (m *Manager) agentFsThawViaExec(ctx context.Context, sandboxID string, agen}}-// usePrepareResume gates the folded single-RPC post-restore path (idea #1:-// collapse network+clock+env into one native PrepareResume call). Env-flagged so-// we can A/B it on dev against the legacy per-op sequence. Off by default.+// usePrepareResume gates the folded single-RPC post-restore path: collapse+// network+clock+env into one native PrepareResume call instead of the legacy+// per-op sequence. Default ON; set OPENSANDBOX_PREPARE_RESUME=0 to fall back.func (m *Manager) usePrepareResume() bool {- return os.Getenv("OPENSANDBOX_PREPARE_RESUME") == "1"+ return os.Getenv("OPENSANDBOX_PREPARE_RESUME") != "0"}// agentPrepareResume performs the post-golden-restore guest setup — network +@@ -914,7 +914,13 @@ func (m *Manager) agentPrepareResume(ctx context.Context, id string, agent *AgenClockUnixNanos: time.Now().UnixNano(),Envs: envs,}- rpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ // Short timeout (not 30s): the folded rebind is ~15ms on a live channel, so a+ // multi-second wait means the channel is stale. Failing fast here — well+ // inside the CP's claim deadline — lets the redial-and-retry below actually+ // run (a 30s wait would blow the CP deadline first, turning a recoverable+ // stale channel into a hard cold-create). ensureAgentLive already refreshed+ // the channel before this; this is the second line of defense.+ rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second)resp, err := agent.PrepareResume(rpcCtx, req)cancel()// One redial-and-retry on the known post-loadvm stale-connection case, exactly@@ -924,7 +930,7 @@ func (m *Manager) agentPrepareResume(ctx context.Context, id string, agent *Agenif rdErr := agent.Redial(); rdErr != nil {return fmt.Errorf("PrepareResume redial: %w (orig: %v)", rdErr, err)}- rpcCtx2, cancel2 := context.WithTimeout(ctx, 30*time.Second)+ rpcCtx2, cancel2 := context.WithTimeout(ctx, 5*time.Second)resp, err = agent.PrepareResume(rpcCtx2, req)cancel2()}@@ -2854,24 +2860,30 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi//// Fail-closed on stats errors during a shrink — better to bounce back// to the caller (who can retry) than apply a limit we can't validate.+ // The OOM-floor guard only matters when SHRINKING — a grow (or same-size)+ // can never land below the guest's working set. Fetching guest Stats() is a+ // ~50-100ms in-VM round-trip; skipping it on grows is 0-impact (the guard+ // can't fire) and removes that round-trip from the create hot path, where+ // every pool claim scales the box up from its base to the default size.if maxMemoryBytes > 0 && vm.agent != nil {newTotalMB := int(maxMemoryBytes / (1024 * 1024))- shrinking := newTotalMB < vm.MemoryMB- statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)- stats, statsErr := vm.agent.Stats(statsCtx)- cancel()- switch {- case statsErr != nil && shrinking:- log.Printf("qemu: %s shrink to %dMB refused: stats fetch failed: %v", sandboxID, newTotalMB, statsErr)- return fmt.Errorf("oom_floor: cannot verify guest working set: %w", statsErr)- case stats != nil && stats.MemUsage > 0:- usedMB := int(stats.MemUsage / (1024 * 1024))- floorMB := usedMB * 105 / 100- if newTotalMB < floorMB {- log.Printf("qemu: %s: refusing memory limit %dMB — working set %dMB requires ≥%dMB",- sandboxID, newTotalMB, usedMB, floorMB)- return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",- newTotalMB, usedMB, floorMB)+ if newTotalMB < vm.MemoryMB { // shrinking+ statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ stats, statsErr := vm.agent.Stats(statsCtx)+ cancel()+ if statsErr != nil {+ log.Printf("qemu: %s shrink to %dMB refused: stats fetch failed: %v", sandboxID, newTotalMB, statsErr)+ return fmt.Errorf("oom_floor: cannot verify guest working set: %w", statsErr)+ }+ if stats != nil && stats.MemUsage > 0 {+ usedMB := int(stats.MemUsage / (1024 * 1024))+ floorMB := usedMB * 105 / 100+ if newTotalMB < floorMB {+ log.Printf("qemu: %s: refusing memory limit %dMB — working set %dMB requires ≥%dMB",+ sandboxID, newTotalMB, usedMB, floorMB)+ return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",+ newTotalMB, usedMB, floorMB)+ }}}}diff --git a/internal/qemu/pool.go b/internal/qemu/pool.goindex a93e5227..5210b4e2 100644--- a/internal/qemu/pool.go+++ b/internal/qemu/pool.go@@ -4,11 +4,32 @@ import ("context""fmt""log"+ "os"+ "strconv""time""github.com/opensandbox/opensandbox/pkg/types")+// wakeSem bounds how many pool boxes may resume (Cont + guest-RAM swap-in) at+// once on this worker. A warm-pool burst can land dozens of simultaneous claims+// on a single worker; without a cap they all fault paged-out guest RAM back from+// the zram/swap tier at the same instant and thrash, inflating every box's wake+// and blowing the burst tail. Serializing to a small width — paired with+// prefetchGuestRAM's eager, batched swap-in — keeps each resume fast so the tail+// stays tight. There is exactly one Manager per worker process, so a package+// singleton is per-worker. Sized from OPENSANDBOX_WAKE_CONCURRENCY (default 8).+var wakeSem = make(chan struct{}, wakeConcurrency())++func wakeConcurrency() int {+ if v := os.Getenv("OPENSANDBOX_WAKE_CONCURRENCY"); v != "" {+ if n, err := strconv.Atoi(v); err == nil && n > 0 {+ return n+ }+ }+ return 8+}+// ClaimPooled binds a parked pool box (manufactured via Create + Pause +// MarkPooled) to a customer: QMP cont to resume the vCPUs, then re-apply the// customer's env/secrets + network/clock via the same post-restore bind@@ -39,9 +60,25 @@ func (m *Manager) ClaimPooled(ctx context.Context, sandboxID string, cfg types.Sreturn nil, fmt.Errorf("no agent client for pooled sandbox %s", sandboxID)}+ // Bound concurrent wakes on this worker so a burst of claims doesn't thrash+ // the swap tier all at once (see wakeSem). Wait here counts toward the claim,+ // but a bounded queue beats every box swapping in simultaneously.+ select {+ case wakeSem <- struct{}{}:+ defer func() { <-wakeSem }()+ case <-ctx.Done():+ return nil, ctx.Err()+ }+t0 := time.Now()// Resume vCPUs. No billing hook — see doc comment.if !vm.pausedAt.IsZero() {+ // Eagerly swap the paged-out guest RAM back in (batched readahead) so the+ // guest doesn't lazy-fault it page-by-page on first touch after Cont —+ // the swap-in stall that otherwise dominates a warm-pool wake.+ if _, err := prefetchGuestRAM(vm.pid, pauseReclaimMinRegionBytes); err != nil {+ log.Printf("qemu: claim %s: guest-RAM prefetch best-effort failed: %v", sandboxID, err)+ }if err := vm.qmp.Cont(); err != nil {return nil, fmt.Errorf("claim %s: qmp cont: %w", sandboxID, err)}@@ -50,6 +87,15 @@ func (m *Manager) ClaimPooled(ctx context.Context, sandboxID string, cfg types.Svm.Status = types.SandboxStatusRunningvm.billingSuppressed = false+ // A pooled box sits paused until claimed; a long pause dwell can let gRPC+ // keepalive tear down the agent control channel (or leave it wedged), so the+ // first real RPC after Cont would otherwise hang until its deadline. Refresh+ // the channel up front — cheap Ping, redial only if it's actually stale, both+ // on short timeouts — so every customer-facing agent op below (secret cert+ // write, PrepareResume) runs on a known-live conn instead of eating a+ // multi-second stall + hard claim failure on the create critical path.+ m.ensureAgentLive(ctx, sandboxID, vm.agent)+// Re-bind customer state onto the resumed box: envs + secrets + network +// clock, folded through PrepareResume (falls back to the legacy per-op path).envsToInject := m.sealSandboxEnvs(ctx, sandboxID, vm.network, vm.agent, cfg)@@ -74,3 +120,35 @@ func (m *Manager) ClaimPooled(ctx context.Context, sandboxID string, cfg types.SGoldenVersion: vm.goldenVersion,}, nil}++// ensureAgentLive verifies the agent control channel is responsive after a pool+// box is un-paused, and redials once if it isn't. Both the probe and the+// post-redial re-probe use short timeouts so a stale/wedged channel is turned+// into a fast redial (~single-digit ms on a healthy conn, ~1-2s worst case on a+// stale one) rather than a multi-second hang on the first customer-facing RPC+// that trips the CP's claim deadline into a hard failure + cold create.+//+// Best-effort: on a box whose agent is genuinely wedged this can't help, but it+// costs one cheap Ping on the healthy path and recovers the common+// "paused-dwell keepalive dropped the conn" case transparently.+func (m *Manager) ensureAgentLive(ctx context.Context, sandboxID string, agent *AgentClient) {+ if agent == nil {+ return+ }+ pingCtx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond)+ _, err := agent.Ping(pingCtx)+ cancel()+ if err == nil {+ return // channel healthy — no redial+ }+ log.Printf("qemu: claim %s: agent ping failed (%v) — redialing stale channel", sandboxID, err)+ if rdErr := agent.Redial(); rdErr != nil {+ log.Printf("qemu: claim %s: agent redial failed: %v", sandboxID, rdErr)+ return+ }+ pingCtx2, cancel2 := context.WithTimeout(ctx, 1500*time.Millisecond)+ if _, perr := agent.Ping(pingCtx2); perr != nil {+ log.Printf("qemu: claim %s: agent still unresponsive after redial: %v", sandboxID, perr)+ }+ cancel2()+}diff --git a/internal/qemu/reclaim_linux.go b/internal/qemu/reclaim_linux.goindex 2a03576f..0ba0e4f0 100644--- a/internal/qemu/reclaim_linux.go+++ b/internal/qemu/reclaim_linux.go@@ -35,6 +35,24 @@ type iovec struct {// re-faults the pages) and the caller has CAP_SYS_NICE + ptrace access to pid// (the worker runs as root). Best-effort — returns the bytes advised.func reclaimGuestRAM(pid int, minRegionBytes uint64) (uint64, error) {+ return madviseGuestRAM(pid, minRegionBytes, unix.MADV_PAGEOUT)+}++// prefetchGuestRAM is the inverse of reclaimGuestRAM: it MADV_WILLNEEDs the+// paged-out guest-RAM regions so the kernel eagerly swaps them back in (batched+// readahead) instead of the guest lazy-faulting them page-by-page after Cont.+// Called on the claim/wake path to cut the swap-in stall that dominates a+// warm-pool resume — most importantly under a burst, where a per-worker gate+// (see ClaimPooled) keeps these prefetches from thrashing the swap tier all at+// once. Best-effort — returns bytes advised.+func prefetchGuestRAM(pid int, minRegionBytes uint64) (uint64, error) {+ return madviseGuestRAM(pid, minRegionBytes, unix.MADV_WILLNEED)+}++// madviseGuestRAM applies advice (MADV_PAGEOUT to reclaim, MADV_WILLNEED to+// prefetch) to pid's large anonymous rw-p guest-RAM mappings via+// process_madvise. Best-effort — returns the bytes advised.+func madviseGuestRAM(pid int, minRegionBytes uint64, advice int) (uint64, error) {iovs, total, err := guestRAMRegions(pid, minRegionBytes)if err != nil {return 0, err@@ -57,7 +75,7 @@ func reclaimGuestRAM(pid int, minRegionBytes uint64) (uint64, error) {pidfd,uintptr(unsafe.Pointer(&iovs[off])),uintptr(len(iovs)-off),- uintptr(unix.MADV_PAGEOUT),+ uintptr(advice),0, 0)if errno != 0 {return total, fmt.Errorf("process_madvise: %w", errno)diff --git a/internal/qemu/reclaim_other.go b/internal/qemu/reclaim_other.goindex 968b3297..e3c70733 100644--- a/internal/qemu/reclaim_other.go+++ b/internal/qemu/reclaim_other.go@@ -9,3 +9,9 @@ import "fmt"func reclaimGuestRAM(pid int, minRegionBytes uint64) (uint64, error) {return 0, fmt.Errorf("guest RAM reclaim not supported on this platform")}++// prefetchGuestRAM is Linux-only (process_madvise + /proc/<pid>/maps). No-op+// error elsewhere so the package still builds for local dev.+func prefetchGuestRAM(pid int, minRegionBytes uint64) (uint64, error) {+ return 0, fmt.Errorf("guest RAM prefetch not supported on this platform")+}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 69b76254..270fdf84 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -492,9 +492,19 @@ func (s *GRPCServer) ClaimSandbox(ctx context.Context, req *pb.ClaimSandboxReque// Bind the customer-facing side now (deferred at manufacture): D1 "created",// billing scale_event (reads org from the cell-PG row the CP just rebound via// ClaimPooledSession), and logship. Mirrors the CreateSandbox success tail.+ //+ // initSandboxDB is local SQLite and load-bearing (the customer's first exec+ // logs into it), so it stays synchronous. The other two are provider-side+ // accounting with no bearing on when the box is usable — under a 100-claim+ // burst their synchronous cell-PG round-trips (scale-event: org lookup ++ // insert; logship: org lookup + guest config RPC) pile onto the CP conn pool+ // and stretch the claim tail. Detach both (context.Background — the RPC ctx+ // dies once we return). The scale event still lands within a few ms, well+ // before any realistic destroy; the terminal-status EndScaleEvent close+ // backstops the pathological immediate-destroy race.s.initSandboxDB(sb.ID, sb.Template)- s.recordInitialScaleEvent(ctx, sb.ID, cfg)- s.configureLogshipForSandbox(ctx, sb.ID)+ go s.recordInitialScaleEvent(context.Background(), sb.ID, cfg)+ go s.configureLogshipForSandbox(context.Background(), sb.ID)log.Printf("grpc: claimed pool box %s (template=%s)", sb.ID, sb.Template)return &pb.ClaimSandboxResponse{