Skip to content

An open-source, faster Devin alternative

TypeScript

Exec fast-path: inline result fold + long-poll, kill the SDK poll ladder

Brian Reardon27d15181c947
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 6690ea46..7d45fd8a 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -223,6 +223,14 @@ const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: n
// permissive — no spurious 429s.
const CONCURRENCY_COUNT_TTL_MS = 1_500;
const concurrencyCountCache = new Map<string, { count: number; cachedAtMs: number }>();
+// Sandbox → owning-cell route. proxyToCellSDK otherwise pays a blocking D1
+// read per sub-op (exec run-async + each result poll = 2-3 reads per SDK
+// runCommand). The route is immutable for a sandbox's lifetime — cells never
+// hand off sandboxes and org ownership never changes — so no TTL: entries are
+// dropped on DELETE and bounded by CACHE_MAX + isolate recycling. Populated at
+// create, which also closes the same-isolate race where a sub-op lands before
+// the waitUntil-deferred insertSandboxIndex write does. Never caches misses.
+const sandboxRouteCache = new Map<string, { cellID: string; orgID: string }>();
function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number): void {
if (nowMs - entry.lastBumpMs < LAST_USED_BUMP_MS) return;
@@ -904,6 +912,12 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext): Pro
} catch {
/* leave parsed empty — still record what we can */
}
+ // Seed the route cache so this isolate's sub-ops (exec/files/delete) skip
+ // the sandboxes_index read — and don't race the deferred insert below.
+ if (parsed.sandboxID) {
+ if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
+ sandboxRouteCache.set(parsed.sandboxID, { cellID: cell.cell_id, orgID: caller.orgID });
+ }
// Off the response path (see indexSandboxFromSSE) — waitUntil keeps the D1
// write alive after we return; events-ingest reconciles the row anyway.
ctx.waitUntil(
@@ -1000,16 +1014,25 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
// when the SDK's API key didn't exist in cell PG (api_keys are global in D1
// now, not mirrored per-cell).
async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string): Promise<Response> {
- const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
- .bind(id)
- .first<{ cell_id: string; org_id: string }>();
+ // Route cache first — the sandbox→cell mapping is immutable, and the D1 read
+ // it replaces is a blocking per-sub-op cost (2-3× per SDK runCommand).
+ let route = sandboxRouteCache.get(id);
+ if (!route) {
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
+ .bind(id)
+ .first<{ cell_id: string; org_id: string }>();
+ if (!row) return json({ error: "sandbox not found" }, 404);
+ route = { cellID: row.cell_id, orgID: row.org_id };
+ if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
+ sandboxRouteCache.set(id, route);
+ }
// Authorization: the sandbox must belong to the caller's org. Without this,
// any authenticated org could exec/files/pty/delete/hibernate/wake another
// org's sandbox by id (the cell trusts the edge for authz). 404 not 403 so
// we don't leak which sandbox ids exist.
- if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- const cell = await lookupCell(env, row.cell_id);
- if (!cell) return json({ error: `cell ${row.cell_id} not registered` }, 503);
+ if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+ const cell = await lookupCell(env, route.cellID);
+ if (!cell) return json({ error: `cell ${route.cellID} not registered` }, 503);
const url = new URL(req.url);
const target = stripApiKeyQueryParam(cell.base_url.replace(/\/$/, "") + url.pathname + url.search);
@@ -1024,7 +1047,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// tokens and API keys), so the same handler chain that runs for SDK
// X-API-Key auth runs here. cell_id in the token guards against replay
// against a different cell.
- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, row.cell_id, orgPol?.plan ?? "free", "", caller.userID);
+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, route.cellID, orgPol?.plan ?? "free", "", caller.userID);
const headers = new Headers();
for (const [k, v] of req.headers.entries()) {
@@ -1051,6 +1074,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
let postUpdate: { status: string; setStopped: boolean; mode: string | null } | null = null;
if (req.method === "DELETE" && path === `/api/sandboxes/${id}`) {
postUpdate = { status: "stopped", setStopped: true, mode: null };
+ sandboxRouteCache.delete(id); // route is dead once the sandbox is destroyed
} else if (req.method === "POST" && path === `/api/sandboxes/${id}/hibernate`) {
postUpdate = { status: "hibernated", setStopped: false, mode: "paused" };
} else if (req.method === "POST" && path === `/api/sandboxes/${id}/wake`) {
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 84e2879e..73ffb932 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -5,6 +5,8 @@ import (
"encoding/binary"
"fmt"
"net/http"
+ "os"
+ "strconv"
"time"
"github.com/gorilla/websocket"
@@ -265,6 +267,18 @@ func (s *Server) execRun(c echo.Context) error {
return c.JSON(http.StatusOK, result)
}
+// execHoldMs reads a hold duration override (milliseconds) from env, falling
+// back to def. "0" disables the hold. Default-on so the fast-exec path needs
+// no config; the env exists as an escape hatch.
+func execHoldMs(env string, def time.Duration) time.Duration {
+ if v := os.Getenv(env); v != "" {
+ if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
+ return time.Duration(ms) * time.Millisecond
+ }
+ }
+ return def
+}
+
// execRunAsyncRoute handles POST /exec/run-async — the async exec entrypoint.
// It binds the request and dispatches a background exec session, returning a
// handle immediately. Newer SDKs poll GET /exec/:execId/result for completion;
@@ -370,6 +384,28 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
}
}
+ // Fast-exec fold: hold the response briefly and, if the command exits inside
+ // the window, return the legacy inline result shape (no execId). The SDK's
+ // run() short-circuits on that shape, so short commands cost one round trip
+ // instead of run-async + a result poll (and its 200/400ms retry ladder).
+ // session.Done closes only after consumeExecOutput has captured ExitCode,
+ // so the GetResult read below is final. Truncated output falls through to
+ // the handle shape — ProcessResult can't carry the truncated flag.
+ if hold := execHoldMs("OPENSANDBOX_EXEC_INLINE_HOLD_MS", 400*time.Millisecond); hold > 0 && session.Done != nil {
+ select {
+ case <-session.Done:
+ if res, err := s.execSessionManager.GetResult(id, session.ID); err == nil && !res.Running && res.ExitCode != nil && !res.Truncated {
+ return c.JSON(http.StatusOK, types.ProcessResult{
+ ExitCode: *res.ExitCode,
+ Stdout: string(res.Stdout),
+ Stderr: string(res.Stderr),
+ })
+ }
+ case <-time.After(hold):
+ case <-c.Request().Context().Done():
+ }
+ }
+
return c.JSON(http.StatusAccepted, types.ExecRunResponse{
ExecID: session.ID,
Running: true,
@@ -378,10 +414,11 @@ func (s *Server) execRunAsync(c echo.Context, id string, req types.ProcessConfig
}
// execResult returns the current state of an async exec/run session — the
-// load-bearing poll endpoint behind SDK exec.run(). Returns immediately with
-// running/exitCode/stdout/stderr; the result is read straight from the in-VM
-// agent (authoritative), so a dropped worker attach stream can't leave it
-// stuck reporting running:true forever.
+// load-bearing poll endpoint behind SDK exec.run(). Long-polls: a still-running
+// command holds the response up to OPENSANDBOX_EXEC_RESULT_HOLD_MS (default
+// 500ms) before answering, so fast commands land on the first poll. The result
+// is read straight from the in-VM agent (authoritative), so a dropped worker
+// attach stream can't leave it stuck reporting running:true forever.
func (s *Server) execResult(c echo.Context) error {
if s.execSessionManager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
@@ -408,6 +445,30 @@ func (s *Server) execResult(c echo.Context) error {
}
}
+ // Long-poll: if the command is still running, hold until it exits (or the
+ // hold elapses) and re-read, so the SDK's first poll catches commands that
+ // outran the run-async inline hold instead of falling onto its 200/400ms
+ // retry ladder. Done closes only after ExitCode is captured, so the re-read
+ // is final. Route already ensured the sandbox is running; the re-read is a
+ // local scrollback+exit-code snapshot, no re-route needed.
+ if res.Running {
+ if hold := execHoldMs("OPENSANDBOX_EXEC_RESULT_HOLD_MS", 500*time.Millisecond); hold > 0 {
+ if sess, serr := s.execSessionManager.GetSession(sessionID); serr == nil && sess.Done != nil {
+ select {
+ case <-sess.Done:
+ case <-time.After(hold):
+ case <-c.Request().Context().Done():
+ }
+ if res2, rerr := s.execSessionManager.GetResult(id, sessionID); rerr == nil {
+ res = res2
+ }
+ if s.router != nil {
+ s.router.Touch(id) // the hold was interaction; keep the idle timer honest
+ }
+ }
+ }
+ }
+
return c.JSON(http.StatusOK, types.ExecRunResult{
Running: res.Running,
ExitCode: res.ExitCode,
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index ae578946..3cf4b72f 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -100,53 +100,21 @@ func (s *Server) createSandbox(c echo.Context) error {
}
}
- // Check org quota and plan enforcement
+ // Org policy — billing/credits, plan size ceilings, the concurrent-sandbox
+ // limit, and the per-org disk cap — is enforced authoritatively at the EDGE
+ // via the cap-token before the request ever reaches the cell. Cells trust the
+ // cap-token and no longer re-read the org row or re-count sandboxes here:
+ // those were two uncached cell-PG reads (GetOrg + CountActiveSandboxes) on
+ // every create that serialized the hot path and dominated the create
+ // round-trip under burst — and the cell-local count was wrong for the global
+ // limit anyway (only the edge sees every cell). See enforceCreatePolicy in
+ // api-edge.
orgID, hasOrg := auth.GetOrgID(c)
- var org *db.Org
- var effPlan string
- var effProvider string
- if hasOrg && s.store != nil {
- var err error
- org, err = s.store.GetOrg(ctx, orgID)
- if err == nil {
- // Plan is a global signal — resolve it authoritatively (cap-token
- // → D1 org-policy → cell-PG last resort), never trusting the stale
- // cell-PG org row outright. See effectivePlan.
- effPlan = s.effectivePlan(c, orgID)
- effProvider = s.effectiveBillingProvider(c, orgID)
-
- // Concurrent sandbox limit applies to all plans.
- count, err := s.store.CountActiveSandboxes(ctx, orgID)
- if err == nil && count >= org.MaxConcurrentSandboxes {
- return c.JSON(http.StatusTooManyRequests, map[string]string{
- "error": "concurrent sandbox limit reached",
- })
- }
- // Free-tier gate (legacy only): trial-credit + machine-size limit.
- // Autumn orgs pay per GB-second and are gated at the edge
- // (balance/halt), so neither the credit check nor the size ceiling
- // applies — they may launch any size (disk still bounded by the
- // per-org MaxDiskMB knob below).
- if effPlan == "free" && effProvider != "autumn" {
- if org.FreeCreditsRemainingCents <= 0 {
- return c.JSON(http.StatusPaymentRequired, map[string]string{
- "error": "free trial credits exhausted — upgrade to pro to create new sandboxes",
- })
- }
- if cfg.MemoryMB > 4096 || cfg.CpuCount > 1 {
- return c.JSON(http.StatusPaymentRequired, map[string]string{
- "error": "upgrade to pro for larger instances",
- })
- }
- }
-
- // Default to 4GB/1vCPU if not specified (all plans)
- if cfg.MemoryMB == 0 {
- cfg.MemoryMB = 4096
- cfg.CpuCount = 1
- }
- }
+ // Default to 4GB/1vCPU if not specified (all plans).
+ if cfg.MemoryMB == 0 {
+ cfg.MemoryMB = 4096
+ cfg.CpuCount = 1
}
// Disk size validation
@@ -163,22 +131,8 @@ func (s *Server) createSandbox(c echo.Context) error {
"error": "diskMB cannot exceed 262144 (256GB)",
})
}
- if org != nil {
- if effPlan == "free" && effProvider != "autumn" && cfg.DiskMB > 20480 {
- return c.JSON(http.StatusPaymentRequired, map[string]string{
- "error": "upgrade to pro for larger disk sizes",
- })
- }
- maxDisk := org.MaxDiskMB
- if maxDisk == 0 {
- maxDisk = 20480
- }
- if cfg.DiskMB > maxDisk {
- return c.JSON(http.StatusForbidden, map[string]string{
- "error": fmt.Sprintf("disk size %dMB exceeds org limit of %dMB", cfg.DiskMB, maxDisk),
- })
- }
- }
+ // Per-org disk cap + free-tier disk ceiling are enforced at the edge (see
+ // enforceCreatePolicy); only the global 20-256GB bounds above apply here.
// Declarative image or named snapshot → resolve to checkpoint and use createFromCheckpoint flow
if len(cfg.ImageManifest) > 0 || cfg.Snapshot != "" {
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index d6943463..ba8b8d24 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -9,6 +9,8 @@ import (
"log"
"log/slog"
"net/http"
+ "os"
+ "strconv"
"sync"
"time"
@@ -370,6 +372,19 @@ func (s *HTTPServer) execRun(c echo.Context) error {
return c.JSON(http.StatusOK, result)
}
+// execHoldMs reads a hold duration override (milliseconds) from env, falling
+// back to def. "0" disables the hold. Default-on so the fast-exec path needs
+// no config; the env exists as an escape hatch. Mirrors the identical helper
+// in internal/api for the combined-mode server.
+func execHoldMs(env string, def time.Duration) time.Duration {
+ if v := os.Getenv(env); v != "" {
+ if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
+ return time.Duration(ms) * time.Millisecond
+ }
+ }
+ return def
+}
+
// execRunAsync is the async exec endpoint (POST /exec/run-async). It registers a
// handle synchronously and returns immediately, then does the wake +
// session-create + command run in a background goroutine. Because the connection
@@ -402,6 +417,18 @@ func (s *HTTPServer) execRunAsync(c echo.Context) error {
Timeout: req.Timeout,
}
+ // wasHibernated read up front (not in the goroutine): it feeds both the
+ // 524-attribution log and the inline-hold decision below — a waking box
+ // must get its handle immediately (holding would re-create the slow-wake
+ // connection hold this async design exists to avoid).
+ wasHibernated := false
+ if s.router != nil {
+ if st, ok := s.router.GetState(id); ok {
+ wasHibernated = st != sandbox.StateRunning
+ }
+ }
+ dispatched := make(chan struct{})
+
go func() {
// 524-attribution timing. wake_ms = checkpoint restore latency (the
// dominant cause of the old synchronous exec/run 524s); create_ms =
@@ -409,12 +436,6 @@ func (s *HTTPServer) execRunAsync(c echo.Context) error {
// logged separately on session exit (exec_session_exit). routeOp
// stamps when the session create begins, so the time inside Route
// before it is the wake (+ any queue wait).
- wasHibernated := false
- if s.router != nil {
- if st, ok := s.router.GetState(id); ok {
- wasHibernated = st != sandbox.StateRunning
- }
- }
var session *sandbox.ExecSessionHandle
var createMs int64
routeOp := func(_ context.Context) error {
@@ -454,11 +475,50 @@ func (s *HTTPServer) execRunAsync(c echo.Context) error {
ae.sessionID = session.ID
}
ae.mu.Unlock()
+ close(dispatched)
// Reap the handle after the underlying session's own retention
// window has comfortably passed.
time.AfterFunc(10*time.Minute, func() { s.asyncExecs.Delete(execID) })
}()
+ // Fast-exec fold: for a box that's already running, hold the response
+ // briefly and, if the command exits inside the window, return the legacy
+ // inline result shape (no execId). The SDK's run() short-circuits on that
+ // shape, so short commands cost one round trip instead of run-async + a
+ // result poll (and the poll's 200/400ms retry ladder — the dominant
+ // benchmark tail). Failures and slow commands fall through to the handle
+ // unchanged; waking boxes never hold (see wasHibernated above).
+ if hold := execHoldMs("OPENSANDBOX_EXEC_INLINE_HOLD_MS", 400*time.Millisecond); hold > 0 && !wasHibernated {
+ deadline := time.NewTimer(hold)
+ defer deadline.Stop()
+ select {
+ case <-dispatched:
+ ae.mu.Lock()
+ state, sessionID := ae.state, ae.sessionID
+ ae.mu.Unlock()
+ if state == asyncExecRunning {
+ if sess, serr := s.execSessionManager.GetSession(sessionID); serr == nil && sess.Done != nil {
+ select {
+ case <-sess.Done:
+ // Done closes only after the attach stream captured
+ // ExitCode, so this read is final.
+ if res, rerr := s.execSessionManager.GetResult(id, sessionID); rerr == nil && !res.Running && res.ExitCode != nil && !res.Truncated {
+ return c.JSON(http.StatusOK, types.ProcessResult{
+ ExitCode: *res.ExitCode,
+ Stdout: string(res.Stdout),
+ Stderr: string(res.Stderr),
+ })
+ }
+ case <-deadline.C:
+ case <-c.Request().Context().Done():
+ }
+ }
+ }
+ case <-deadline.C:
+ case <-c.Request().Context().Done():
+ }
+ }
+
return c.JSON(http.StatusAccepted, types.ExecRunResponse{
ExecID: execID,
Running: true,
@@ -530,6 +590,25 @@ func (s *HTTPServer) execResult(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
}
+ // Long-poll: a still-running command holds the response until it exits (or
+ // the hold elapses) and re-reads, so the SDK's first poll catches commands
+ // that outran the run-async inline hold instead of falling onto its
+ // 200/400ms retry ladder. Done closes only after the attach stream captured
+ // ExitCode, so the re-read is final.
+ if res.Running {
+ if hold := execHoldMs("OPENSANDBOX_EXEC_RESULT_HOLD_MS", 500*time.Millisecond); hold > 0 {
+ if sess, serr := s.execSessionManager.GetSession(sessionID); serr == nil && sess.Done != nil {
+ select {
+ case <-sess.Done:
+ case <-time.After(hold):
+ case <-c.Request().Context().Done():
+ }
+ if res2, rerr := s.execSessionManager.GetResult(id, sessionID); rerr == nil {
+ res = res2
+ }
+ }
+ }
+ }
return c.JSON(http.StatusOK, types.ExecRunResult{
Running: res.Running,
ExitCode: res.ExitCode,