Skip to content

An open-source, faster Devin alternative

TypeScript

hot claimable pool — running boxes, parallel refill, no slot cap

Brian Reardond035e21b27fc
diff --git a/internal/api/pool.go b/internal/api/pool.go
index 74b0c7d5..d49b3e5b 100644
--- a/internal/api/pool.go
+++ b/internal/api/pool.go
@@ -7,6 +7,8 @@ import (
"log"
"os"
"strconv"
+ "sync"
+ "sync/atomic"
"time"
"github.com/google/uuid"
@@ -36,6 +38,31 @@ func (s *Server) poolTarget() int {
return 10
}
+// poolRefillBatch is the max boxes a worker is topped up per reconcile tick.
+// They're manufactured concurrently (see reconcilePool), so this bounds the
+// burst of simultaneous golden-restores per worker. Default 3 (gentle cold
+// ramp); crank via OPENSANDBOX_POOL_REFILL_BATCH to recover a drained pool fast.
+func poolRefillBatch() int {
+ if v := os.Getenv("OPENSANDBOX_POOL_REFILL_BATCH"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ return n
+ }
+ }
+ return 3
+}
+
+// poolRefillInterval is how often the reconciler tops the pool up. Default 15s;
+// shorten via OPENSANDBOX_POOL_REFILL_INTERVAL_MS so a drained pool recovers
+// between bursts instead of over minutes.
+func poolRefillInterval() time.Duration {
+ if v := os.Getenv("OPENSANDBOX_POOL_REFILL_INTERVAL_MS"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ return time.Duration(n) * time.Millisecond
+ }
+ }
+ return 15 * time.Second
+}
+
// poolMaxMemPct is the host-memory ceiling for pool refill: once a worker's
// memory is above this, the reconciler stops manufacturing pool boxes onto it.
// The pool always yields to real customer load — this matches the scaler's
@@ -125,7 +152,7 @@ func (s *Server) StartPoolReconciler(ctx context.Context, isLeader func() bool)
template := poolTemplateName()
log.Printf("pool: reconciler started (region=%s per_worker_target=%d template=%s, leader-gated)", region, s.poolTarget(), template)
- t := time.NewTicker(15 * time.Second)
+ t := time.NewTicker(poolRefillInterval())
defer t.Stop()
for {
select {
@@ -148,6 +175,7 @@ func (s *Server) StartPoolReconciler(ctx context.Context, isLeader func() bool)
// target 25 warms ~100, and adding/removing a worker adjusts automatically (a
// drained worker's pool is wiped and never refilled here since it's skipped).
func (s *Server) reconcilePool(ctx context.Context, region, template string, perWorkerTarget int) {
+ var wg sync.WaitGroup
for _, w := range s.workerRegistry.GetAllWorkers() {
if w.Region != region || w.Draining {
continue
@@ -169,23 +197,37 @@ func (s *Server) reconcilePool(ctx context.Context, region, template string, per
if deficit <= 0 {
continue
}
- // Cap per worker per tick so a cold start ramps instead of bursting.
+ // Cap per worker per tick. Manufactured concurrently (below) so a cranked
+ // batch actually recovers a drained pool instead of serializing golden
+ // restores; the cap bounds the simultaneous-restore burst per worker.
batch := deficit
- if batch > 3 {
- batch = 3
+ if max := poolRefillBatch(); batch > max {
+ batch = max
}
- made := 0
- for i := 0; i < batch; i++ {
- if err := s.manufacturePoolBoxOn(ctx, w.ID, region, template, w.GoldenVersion); err != nil {
- log.Printf("pool: manufacture on %s failed (%d/%d): %v", w.ID, made, batch, err)
- break
+ w := w
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ var mwg sync.WaitGroup
+ var made int64
+ for i := 0; i < batch; i++ {
+ mwg.Add(1)
+ go func() {
+ defer mwg.Done()
+ if err := s.manufacturePoolBoxOn(ctx, w.ID, region, template, w.GoldenVersion); err != nil {
+ log.Printf("pool: manufacture on %s failed: %v", w.ID, err)
+ return
+ }
+ atomic.AddInt64(&made, 1)
+ }()
}
- made++
- }
- if made > 0 {
- log.Printf("pool: %s refilled %d (had %d, per-worker target %d)", w.ID, made, have, perWorkerTarget)
- }
+ mwg.Wait()
+ if made > 0 {
+ log.Printf("pool: %s refilled %d (had %d, per-worker target %d)", w.ID, made, have, perWorkerTarget)
+ }
+ }()
}
+ wg.Wait()
}
// WipeWorkerPool destroys all pooled boxes parked on a worker — called when the
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 59454be2..ae578946 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -751,11 +751,19 @@ func (s *Server) tryClaimPooled(c echo.Context, ctx context.Context, cfg types.S
return false, nil
}
- // Promote pending→running (emits sandbox.created + sandbox.ready).
- _ = s.store.UpdateSandboxSessionStatus(ctx, box.SandboxID, "running", nil)
- if g := claimResp.GetGoldenVersion(); g != "" {
- _ = s.store.SetSandboxGoldenVersion(ctx, box.SandboxID, g)
- }
+ // Promote pending→running (emits sandbox.created + sandbox.ready) + record the
+ // golden version — off the claim's critical path. Exec/GET route via the
+ // worker-side sandbox router (registered by ClaimSandbox), not PG status, so
+ // the box is usable the instant we return; the PG promote can land a beat
+ // later. Detached ctx — the request ctx is cancelled once we respond.
+ go func(id, golden string) {
+ bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ _ = s.store.UpdateSandboxSessionStatus(bgCtx, id, "running", nil)
+ if golden != "" {
+ _ = s.store.SetSandboxGoldenVersion(bgCtx, id, golden)
+ }
+ }(box.SandboxID, claimResp.GetGoldenVersion())
// Grow to requested resources (virtio-mem + cgroup), mirroring the cold path.
if cfg.MemoryMB > 0 || cfg.CpuCount > 0 {
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index 745fd765..3ed7b821 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -585,7 +585,13 @@ func (r *RedisWorkerRegistry) collectEligibleLocked(region string, anyRegion boo
if w.CPUPct >= routingHardCapPct || w.MemPct >= routingHardCapPct || w.DiskPct >= routingHardCapPct {
continue
}
- if w.Capacity <= 0 || w.Current >= w.Capacity {
+ // Placement is gated by REAL resource pressure (the CPU/mem/disk hard-cap
+ // above), not an arbitrary per-worker sandbox count. The old
+ // `Current >= Capacity` slot cap rejected placement while workers still
+ // had tons of headroom (the "no workers available" 503s under burst).
+ // Capacity is retained only for the scale-up math + placement score; a
+ // worker that hasn't reported it yet still isn't a ready target.
+ if w.Capacity <= 0 {
continue
}
out = append(out, w)
diff --git a/internal/qemu/pool.go b/internal/qemu/pool.go
index 5210b4e2..df3c1775 100644
--- a/internal/qemu/pool.go
+++ b/internal/qemu/pool.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/agent"
)
// wakeSem bounds how many pool boxes may resume (Cont + guest-RAM swap-in) at
@@ -30,6 +31,32 @@ func wakeConcurrency() int {
return 8
}
+// WarmGuest runs a best-effort warm-up command in a running pool box so the
+// interpreter/binary pages the first customer command needs are already resident
+// (page cache warm). Only meaningful for a HOT (unpaused) pool box — a paused
+// box's pages get reclaimed to swap, so warming it is pointless. Best-effort:
+// warm-up failures never fail manufacture. Command from OPENSANDBOX_POOL_WARMUP_CMD
+// (default warms the common runtimes).
+func (m *Manager) WarmGuest(ctx context.Context, sandboxID string) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil || vm.agent == nil {
+ return
+ }
+ cmd := os.Getenv("OPENSANDBOX_POOL_WARMUP_CMD")
+ if cmd == "" {
+ cmd = "node -v; python3 --version"
+ }
+ execCtx, cancel := context.WithTimeout(ctx, 8*time.Second)
+ defer cancel()
+ if _, e := vm.agent.Exec(execCtx, &pb.ExecRequest{
+ Command: "/bin/sh",
+ Args: []string{"-c", cmd + " >/dev/null 2>&1 || true"},
+ RunAsRoot: true,
+ }); e != nil {
+ log.Printf("qemu: warm-guest %s: %v (best-effort)", sandboxID, e)
+ }
+}
+
// 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
@@ -60,19 +87,20 @@ func (m *Manager) ClaimPooled(ctx context.Context, sandboxID string, cfg types.S
return 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.
+ // Resume vCPUs — paused pool boxes only. A HOT pool box (OPENSANDBOX_HOT_POOL)
+ // is already running, so it skips the wake gate, RAM prefetch, and Cont
+ // entirely: the claim is a pure assign + rebind. No billing hook — see doc.
if !vm.pausedAt.IsZero() {
+ // Bound concurrent wakes so a burst doesn't thrash the swap tier all at
+ // once (see wakeSem); held through the claim so the swap-in it kicks off
+ // stays bounded.
+ select {
+ case wakeSem <- struct{}{}:
+ defer func() { <-wakeSem }()
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
// 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.
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 270fdf84..2101641d 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -350,7 +350,24 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
_ = s.manager.Kill(context.Background(), sb.ID)
return nil, fmt.Errorf("pool manufacture: backend does not support pause")
}
- if _, perr := pm.Pause(ctx, sb.ID); perr != nil {
+ parked := "parked paused"
+ if hotPoolEnabled() {
+ // Hot pool: leave the box RUNNING (RAM-resident, agent live) so a claim
+ // is a pure assign — no QMP resume, no swap-in, no wake storm. Two
+ // guardrails vs a normal running box: (1) suppress billing while
+ // unclaimed — the usage ticker skips billingSuppressed boxes, and
+ // ClaimPooled clears the flag so billing starts exactly at claim; (2)
+ // Register(0) below keeps it out of idle-hibernation. Warm the guest so
+ // the first customer command skips cold page-faults.
+ if err := pm.SetBillingSuppressed(sb.ID); err != nil {
+ _ = s.manager.Kill(context.Background(), sb.ID)
+ return nil, fmt.Errorf("pool manufacture: suppress billing %s: %w", sb.ID, err)
+ }
+ if w, ok := s.manager.(guestWarmer); ok {
+ w.WarmGuest(ctx, sb.ID)
+ }
+ parked = "hot (running)"
+ } else if _, perr := pm.Pause(ctx, sb.ID); perr != nil {
_ = s.manager.Kill(context.Background(), sb.ID) // a box that won't pause is useless as a pool entry
return nil, fmt.Errorf("pool manufacture: pause %s: %w", sb.ID, perr)
}
@@ -358,7 +375,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
s.router.Register(sb.ID, 0) // persistent — no idle timeout while parked
s.router.MarkPooled(sb.ID)
}
- log.Printf("grpc: manufactured pool box %s (template=%s) — parked paused", sb.ID, cfg.Template)
+ log.Printf("grpc: manufactured pool box %s (template=%s) — %s", sb.ID, cfg.Template, parked)
return &pb.CreateSandboxResponse{
SandboxId: sb.ID,
Status: string(types.SandboxStatusPooled),
@@ -858,6 +875,20 @@ type pausableManager interface {
ClaimPooled(ctx context.Context, sandboxID string, cfg types.SandboxConfig) (*types.Sandbox, error)
}
+// guestWarmer optionally warms a pool box's guest page cache at manufacture so
+// the first customer command skips cold faults. Only the qemu backend implements
+// it; other backends just skip warming.
+type guestWarmer interface {
+ WarmGuest(ctx context.Context, sandboxID string)
+}
+
+// hotPoolEnabled leaves manufactured pool boxes RUNNING (billing-suppressed)
+// instead of paused, so a claim is a pure assign — no QMP resume / swap-in /
+// wake storm. Default ON; set OPENSANDBOX_HOT_POOL=0 to fall back to a paused pool.
+func hotPoolEnabled() bool {
+ return os.Getenv("OPENSANDBOX_HOT_POOL") != "0"
+}
+
// PauseSandbox freezes the VM's vCPUs and pages its guest RAM out to swap — the
// RAM-resident fast tier. The VM stays on this worker (no checkpoint store
// needed); ResumeSandbox brings it back instantly.