An open-source, faster Devin alternative
TypeScript
add RAM-resident pause tier with promotion to deep (1h idle / pressure / 100-per-org cap)
Brian Reardon78b0f1132d8b
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 3f3783f5..e1d932e5 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -37,6 +37,9 @@ export interface Env extends DashboardEnv {CF_ADMIN_SECRET: string;STRIPE_WEBHOOK_SECRET: string;EVENT_SECRET: string;+ // Per-org cross-cell paused-sandbox cap (default 100). Set lower on dev to+ // exercise the promotion path without paused hundreds of boxes.+ PAUSED_CAP?: string;// Autumn (useautumn.com) billing. AUTUMN_WEBHOOK_SECRET is the Svix signing// secret (whsec_…) for /webhooks/autumn. AUTUMN_SECRET_KEY / AUTUMN_BASE_URL// are inherited from DashboardEnv. Unset on deployments not yet on Autumn.@@ -849,13 +852,17 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal// changes on DELETE / hibernate / wake. Otherwise the dashboard accumulates// phantoms — D1 rows stuck at "running" after the actual sandbox stopped.const path = url.pathname;- let postUpdate: { status: string; setStopped: boolean } | null = null;+ // mode mirrors hibernation_mode: customer hibernate = the paused tier, wake =+ // running (NULL). Set it here (authoritative + immediate) so the cross-cell+ // paused-cap sees the box right away; the cell's async "paused" event would+ // otherwise no-op against this write's newer last_event_at.+ let postUpdate: { status: string; setStopped: boolean; mode: string | null } | null = null;if (req.method === "DELETE" && path === `/api/sandboxes/${id}`) {- postUpdate = { status: "stopped", setStopped: true };+ postUpdate = { status: "stopped", setStopped: true, mode: null };} else if (req.method === "POST" && path === `/api/sandboxes/${id}/hibernate`) {- postUpdate = { status: "hibernated", setStopped: false };+ postUpdate = { status: "hibernated", setStopped: false, mode: "paused" };} else if (req.method === "POST" && path === `/api/sandboxes/${id}/wake`) {- postUpdate = { status: "running", setStopped: false };+ postUpdate = { status: "running", setStopped: false, mode: null };// Halt-gate the wake. D1 is authoritative for is_halted. The cell-side// gate that used to do this read the dropped orgs table post-041 and// silently fell through, letting halted orgs wake. Mirror the create@@ -902,13 +909,13 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, calif (postUpdate && resp.status >= 200 && resp.status < 300) {const nowSec = Math.floor(Date.now() / 1000);const updateSQL = postUpdate.setStopped- ? "UPDATE sandboxes_index SET status = ?1, stopped_at = ?2, last_event_at = ?2 WHERE id = ?3"- : "UPDATE sandboxes_index SET status = ?1, last_event_at = ?2 WHERE id = ?3";+ ? "UPDATE sandboxes_index SET status = ?1, hibernation_mode = ?4, stopped_at = ?2, last_event_at = ?2 WHERE id = ?3"+ : "UPDATE sandboxes_index SET status = ?1, hibernation_mode = ?4, last_event_at = ?2 WHERE id = ?3";// ctx.waitUntil keeps the background D1 write alive after the response// returns. Without it the Worker terminates the in-flight Promise and// the UPDATE never runs — sandboxes_index drifts behind cell PG.ctx.waitUntil(- env.OPENCOMPUTER_DB.prepare(updateSQL).bind(postUpdate.status, nowSec, id).run().catch((e) => {+ env.OPENCOMPUTER_DB.prepare(updateSQL).bind(postUpdate.status, nowSec, id, postUpdate.mode).run().catch((e) => {console.error(`sandboxes_index ${postUpdate!.status} update failed for ${id}:`, e);}),);@@ -1743,6 +1750,58 @@ async function verifyStripeSignature(secret: string, header: string, body: strin// ── entrypoint ───────────────────────────────────────────────────────────+// DEFAULT_PAUSED_CAP is the max RAM-resident paused sandboxes an org may hold+// across all cells. Paused boxes are free + off-quota, so this bounds per-tenant+// paused RAM; the oldest excess is promoted to deep hibernation (evicted to a+// checkpoint). Overridable per-deployment via env.PAUSED_CAP (dev lowers it to+// exercise the path). Enforced here because only D1 has the cross-cell view.+const DEFAULT_PAUSED_CAP = 100;++// runPausedCapEnforcer promotes each over-cap org's oldest paused sandboxes to+// deep hibernation, by calling the cell that hosts each one. Runs on the 5-min+// cron; the cell endpoint is idempotent (no-ops if the box already resumed or+// was promoted), so redundant calls are safe.+async function runPausedCapEnforcer(env: Env): Promise<void> {+ const cap = Number(env.PAUSED_CAP) || DEFAULT_PAUSED_CAP;+ const overCap = await env.OPENCOMPUTER_DB.prepare(+ `SELECT org_id, COUNT(*) AS n FROM sandboxes_index+ WHERE hibernation_mode = 'paused'+ GROUP BY org_id HAVING n > ?1`,+ )+ .bind(cap)+ .all<{ org_id: string; n: number }>();++ for (const org of overCap.results ?? []) {+ const excess = org.n - cap;+ const victims = await env.OPENCOMPUTER_DB.prepare(+ `SELECT s.id, s.cell_id, c.base_url+ FROM sandboxes_index s+ JOIN cells c ON s.cell_id = c.cell_id+ WHERE s.org_id = ?1 AND s.hibernation_mode = 'paused'+ ORDER BY s.last_event_at ASC+ LIMIT ?2`,+ )+ .bind(org.org_id, excess)+ .all<{ id: string; cell_id: string; base_url: string }>();++ let promoted = 0;+ for (const v of victims.results ?? []) {+ try {+ const token = await mintCapToken(env.SESSION_JWT_SECRET, org.org_id, v.cell_id, "", "", null);+ const resp = await fetch(+ v.base_url.replace(/\/$/, "") + `/internal/sandboxes/${v.id}/deep-hibernate`,+ { method: "POST", headers: { authorization: "Bearer " + token } },+ );+ if (resp.ok) promoted++;+ else console.error(`paused-cap: deep-hibernate ${v.id} on ${v.cell_id} → ${resp.status}`);+ } catch (err) {+ console.error(`paused-cap: deep-hibernate ${v.id} failed`, err);+ }+ }+ console.log(`paused-cap: org ${org.org_id} at ${org.n}/${cap} paused, promoted ${promoted} oldest to deep`);+ }+}+export default {async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {const url = new URL(req.url);@@ -1782,6 +1841,13 @@ export default {await runAutumnMeter(env, Date.now());return json({ ok: true });}+ // Dev-only: force a paused-cap enforcement run (cron is */5). Deterministic+ // testing aid for the promotion path.+ if (path === "/internal/run-paused-cap" && req.method === "POST") {+ if (env.WORKER_ENV === "prod") return new Response("not found", { status: 404 });+ await runPausedCapEnforcer(env);+ return json({ ok: true });+ }// Force a model-meter run (token billing §5.4). HMAC-auth'd (CF_ADMIN_SECRET) so// it's safe to run in prod for testing/ops — useful to debit + push caps right// after a Managed turn instead of waiting for the cron.@@ -2199,6 +2265,10 @@ export default {// key's spend → debit Autumn `model_spend` → push the markup-correct cap + halt.// Dormant unless OPENROUTER_PROVISIONING_KEY is set + managed keys exist.async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {+ // Cross-cell paused-cap enforcement runs regardless of billing config.+ ctx.waitUntil(+ runPausedCapEnforcer(env).catch((err) => console.error("paused-cap: run failed", err)),+ );if (!env.AUTUMN_SECRET_KEY) return;ctx.waitUntil(runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 8ac8d6e6..87fcb4b5 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -102,6 +102,9 @@ crons = ["*/5 * * * *"][vars]WORKER_ENV = "dev"+# Dev override of the per-org paused-sandbox cap (prod defaults to 100) so the+# promotion path can be exercised without pausing hundreds of boxes.+PAUSED_CAP = "10"# Cells eligible for new-org home assignment are NOT configured here anymore —# it's the `accepts_new_orgs` column on the D1 `cells` table (single source of# truth, toggled per-row without a deploy). See pickHomeCell in src/index.ts.diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.tsindex 9d26bec2..950f7e6c 100644--- a/cloudflare-workers/events-ingest/src/index.ts+++ b/cloudflare-workers/events-ingest/src/index.ts@@ -152,7 +152,14 @@ export default {);const lifecycleHibernated = env.OPENCOMPUTER_DB.prepare(`UPDATE sandboxes_index- SET status = 'hibernated', last_event_at = ?1+ SET status = 'hibernated', hibernation_mode = 'deep', last_event_at = ?1+ WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,+ );+ // Paused tier: customer status is "hibernated", internal mode "paused".+ // last_event_at doubles as the pause time for the cap's oldest-first order.+ const lifecyclePaused = env.OPENCOMPUTER_DB.prepare(+ `UPDATE sandboxes_index+ SET status = 'hibernated', hibernation_mode = 'paused', last_event_at = ?1WHERE id = ?2 AND (last_event_at IS NULL OR last_event_at < ?1)`,);// INSERT ON CONFLICT, not plain UPDATE — the previous UPDATE-only shape@@ -177,6 +184,7 @@ export default {VALUES (?2, ?3, ?4, ?5, 'running', ?1, ?1)ON CONFLICT(id) DO UPDATE SETstatus = 'running',+ hibernation_mode = NULL,worker_id = COALESCE(excluded.worker_id, sandboxes_index.worker_id),stopped_at = NULL,last_event_at = ?1@@ -188,7 +196,7 @@ export default {// not worker_id otherwise).const lifecycleMigrated = env.OPENCOMPUTER_DB.prepare(`UPDATE sandboxes_index- SET status = 'running', worker_id = ?1, stopped_at = NULL, last_event_at = ?2+ SET status = 'running', hibernation_mode = NULL, worker_id = ?1, stopped_at = NULL, last_event_at = ?2WHERE id = ?3 AND (last_event_at IS NULL OR last_event_at < ?2)`,);const capacityBatches = fresh@@ -211,10 +219,15 @@ export default {});const lifecycleBatches = fresh- .filter((e) => e.sandbox_id && (e.type === "stopped" || e.type === "hibernated" || e.type === "running" || e.type === "woke" || e.type === "created" || e.type === "migrated"))+ .filter((e) => e.sandbox_id && (e.type === "stopped" || e.type === "hibernated" || e.type === "paused" || e.type === "running" || e.type === "woke" || e.type === "created" || e.type === "migrated")).map((e) => {const tsSec = Math.floor((Date.parse(e.timestamp) || Date.now()) / 1000);if (e.type === "stopped") return lifecycleStopped.bind(tsSec, e.sandbox_id);+ // Two-tier hibernation: "paused" = RAM-resident tier (mode=paused),+ // "hibernated" = deep tier (mode=deep — now only deep hibernation emits+ // it; the pause tier emits "paused"). Both keep customer status+ // "hibernated"; the mode feeds the cross-cell paused cap.+ if (e.type === "paused") return lifecyclePaused.bind(tsSec, e.sandbox_id);if (e.type === "hibernated") return lifecycleHibernated.bind(tsSec, e.sandbox_id);if (e.type === "migrated" || e.type === "woke") {// worker_id moves with the sandbox. For "migrated" the scalerdiff --git a/cloudflare-workers/schema_phase11_paused_hibernation_mode.sql b/cloudflare-workers/schema_phase11_paused_hibernation_mode.sqlnew file mode 100644index 00000000..b7e78234--- /dev/null+++ b/cloudflare-workers/schema_phase11_paused_hibernation_mode.sql@@ -0,0 +1,22 @@+-- Phase 11: two-tier hibernation on sandboxes_index (cross-cell paused cap).+--+-- sandboxes_index.status stays customer-facing (running | hibernated | stopped).+-- hibernation_mode is the internal tier, mirrored from the cell:+-- 'paused' — RAM-resident on its worker (instant resume, unbilled)+-- 'deep' — savevm'd + evicted to a checkpoint+-- NULL — running+-- Only D1 has the org-global, cross-cell view (an org is best-effort single+-- cell, not guaranteed), so the api-edge uses this column to enforce the+-- per-org paused cap. events-ingest maintains it on paused/hibernated/woke.+--+-- Apply with:+-- wrangler d1 execute opencomputer-prod --remote --file cloudflare-workers/schema_phase11_paused_hibernation_mode.sql+--+-- SQLite/D1 has no ADD COLUMN IF NOT EXISTS, so this is one-shot.+ALTER TABLE sandboxes_index ADD COLUMN hibernation_mode TEXT;++-- The cap enforcer scans an org's paused rows oldest-first. last_event_at is+-- ~the pause time, so it doubles as the promotion ordering key.+CREATE INDEX IF NOT EXISTS idx_sandboxes_paused+ ON sandboxes_index(org_id, last_event_at)+ WHERE hibernation_mode = 'paused';diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 47191aca..05120d11 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -561,6 +561,25 @@ func main() {_ = sandboxDBMgr.Remove(sandboxID)}},+ OnPause: func(sandboxID string) {+ // RAM-resident pause tier. The VM stays on this worker, so keep the+ // per-sandbox SQLite; just emit "paused" so events-ingest flips D1+ // sandboxes_index to hibernated/mode=paused (kept in sync + feeds the+ // cross-cell paused cap). DB session status/mode is written by the+ // router (SetSandboxPaused) already.+ if sandboxDBMgr != nil {+ if sdb, dbErr := sandboxDBMgr.Get(sandboxID); dbErr == nil {+ _ = sdb.LogEvent("paused", map[string]string{"sandbox_id": sandboxID})+ }+ }+ },+ OnResume: func(sandboxID string) {+ if sandboxDBMgr != nil {+ if sdb, dbErr := sandboxDBMgr.Get(sandboxID); dbErr == nil {+ _ = sdb.LogEvent("woke", map[string]string{"sandbox_id": sandboxID, "reason": "resume"})+ }+ }+ },OnKill: func(sandboxID string) {log.Printf("opensandbox-worker: sandbox %s killed on timeout", sandboxID)execMgr.RemoveSessions(sandboxID)diff --git a/internal/api/router.go b/internal/api/router.goindex e39d4a65..84d6de00 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -335,6 +335,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oif s.capTokenIssuer != nil && s.workerRegistry != nil {internal := e.Group("/internal", s.capTokenMiddleware)internal.POST("/sandboxes/create", s.internalCreateSandbox)+ // 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.+ internal.POST("/sandboxes/:id/deep-hibernate", s.internalDeepHibernate)// Edge-proxied dashboard routes. Same handler functions as// /api/dashboard/* (gated below by WorkOS session cookie), exposeddiff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 492af6c4..ae2320a1 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1956,6 +1956,46 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error})}+// internalDeepHibernate promotes a specific paused sandbox to deep hibernation.+// Called by the api-edge cross-cell paused-cap enforcer (which has the org-global+// view via D1) against the cell that currently hosts the sandbox. Only acts on+// paused boxes; a no-op if the box already resumed or was promoted, so it's safe+// to call redundantly.+func (s *Server) internalDeepHibernate(c echo.Context) error {+ id := c.Param("id")+ if s.store == nil || s.workerRegistry == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not available in this mode"})+ }+ session, err := s.store.GetSandboxSession(c.Request().Context(), id)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ // Only promote boxes still in the paused tier.+ if session.HibernationMode == nil || *session.HibernationMode != "paused" {+ mode := "none"+ if session.HibernationMode != nil {+ mode = *session.HibernationMode+ }+ return c.JSON(http.StatusOK, map[string]string{"sandboxID": id, "status": "skipped", "mode": mode})+ }+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "worker unreachable"})+ }+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), 120*time.Second)+ defer cancel()+ // The worker's HibernateSandbox un-freezes the paused VM, savevm's + evicts,+ // records the checkpoint, and sets mode=deep.+ if _, err := client.HibernateSandbox(grpcCtx, &pb.HibernateSandboxRequest{SandboxId: id}); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "deep hibernate failed: " + err.Error()})+ }+ // Wake may land the box on a different worker — drop the cached route.+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.InvalidateRouteCache(id)+ }+ return c.JSON(http.StatusOK, map[string]string{"sandboxID": id, "status": "hibernated", "mode": "deep"})+}+func (s *Server) wakeSandbox(c echo.Context) error {id := c.Param("id")ctx := c.Request().Context()diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 4e996268..b722f7b8 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -62,6 +62,18 @@ type SnapshotMeta struct {func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStore *storage.CheckpointStore) (*sandbox.HibernateResult, error) {t0 := time.Now()+ // Deep-hibernating a VM that's in the paused tier: its vCPUs are frozen and+ // guest RAM is paged out. Un-freeze (raw QMP cont — no billing change, both+ // tiers are unbilled) so the guest can quiesce (agent sync) before savevm;+ // the paged-out RAM faults back in as savevm reads it. Handles every deep+ // entrypoint uniformly (idle promotion, emergency, cross-cell cap).+ if !vm.pausedAt.IsZero() && vm.qmp != nil {+ if err := vm.qmp.Cont(); err != nil {+ return nil, fmt.Errorf("hibernate %s: un-pause before savevm: %w", vm.ID, err)+ }+ vm.pausedAt = time.Time{}+ }+snapshotDir := filepath.Join(vm.sandboxDir, "snapshot")if err := os.MkdirAll(snapshotDir, 0755); err != nil {return nil, fmt.Errorf("mkdir snapshot dir: %w", err)diff --git a/internal/sandbox/router.go b/internal/sandbox/router.goindex 5d9cd82a..7b0bbed8 100644--- a/internal/sandbox/router.go+++ b/internal/sandbox/router.go@@ -67,6 +67,8 @@ type RouterConfig struct {DefaultTimeout time.DurationOnHibernate func(sandboxID string, result *HibernateResult)OnKill func(sandboxID string) // called when a sandbox is killed on timeout (hibernate failed or no checkpoint store)+ OnPause func(sandboxID string) // entered the RAM-resident paused tier (emit "paused" for D1 sync + cap input)+ OnResume func(sandboxID string) // resumed from paused (emit "woke")}// SandboxRouter routes sandbox interactions through a state machine,@@ -82,6 +84,8 @@ type SandboxRouter struct {defaultTimeout time.DurationonHibernate func(sandboxID string, result *HibernateResult)onKill func(sandboxID string)+ onPause func(sandboxID string)+ onResume func(sandboxID string)// pausePromoteAfter is how long a box may stay in the RAM-resident paused// tier before it's promoted to deep hibernation (savevm + evict), reclaiming@@ -113,6 +117,8 @@ func NewSandboxRouter(cfg RouterConfig) *SandboxRouter {defaultTimeout: dt,onHibernate: cfg.OnHibernate,onKill: cfg.OnKill,+ onPause: cfg.OnPause,+ onResume: cfg.OnResume,pausePromoteAfter: promoteAfter,sandboxes: make(map[string]*sandboxEntry),}@@ -552,6 +558,9 @@ func (r *SandboxRouter) MarkPaused(sandboxID string) {entry.state = StatePausedentry.mu.Unlock()r.armPromoteTimer(sandboxID)+ if r.onPause != nil {+ r.onPause(sandboxID)+ }}// armPromoteTimer (re)arms the per-box timer that promotes a paused VM to deep@@ -600,22 +609,9 @@ func (r *SandboxRouter) promoteToDeep(sandboxID string) {ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)defer cancel()- // Fully un-pause through the tested Resume path (QMP cont) and let the guest- // fault its RAM back from swap and settle, THEN run the normal Hibernate.- // This routes promotion through the exact savevm path a running-box hibernate- // uses, instead of a Cont-then-immediately-savevm special case that could- // capture the disk mid-flush.- if pm, ok := r.manager.(pausableManager); ok {- if err := pm.Resume(ctx, sandboxID); err != nil {- log.Printf("router: promote %s: resume-before-hibernate failed, keeping paused: %v", sandboxID, err)- entry.mu.Lock()- entry.state = StatePaused- entry.mu.Unlock()- return- }- time.Sleep(time.Second) // let the guest settle after faulting RAM back in- }-+ // manager.Hibernate un-freezes a paused VM internally before savevm, so all+ // deep-hibernate entrypoints (this promotion, emergency, the cross-cell cap)+ // go through the same path.result, err := r.manager.Hibernate(ctx, sandboxID, r.checkpointStore)if err != nil {log.Printf("router: promote %s to deep failed, keeping paused: %v", sandboxID, err)@@ -676,6 +672,9 @@ func (r *SandboxRouter) doResume(_ context.Context, sandboxID string, entry *sanif r.store != nil {_ = r.store.SetSandboxResumed(resumeCtx, sandboxID)}+ if r.onResume != nil {+ r.onResume(sandboxID)+ }log.Printf("router: auto-resumed paused sandbox %s", sandboxID)}@@ -747,6 +746,9 @@ func (r *SandboxRouter) onTimeout(sandboxID string) {entry.timer = nilentry.mu.Unlock()r.armPromoteTimer(sandboxID)+ if r.onPause != nil {+ r.onPause(sandboxID)+ }log.Printf("router: sandbox %s paused on idle (RAM-resident)", sandboxID)return} else {