An open-source, faster Devin alternative
TypeScript
autoscaling for sandboxes
Brian Reardoned617c2414f5
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 7e013a25..8a2ed920 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -381,6 +381,19 @@ func main() {// Create API serverserver := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)+ // Per-sandbox autoscaler. Tier-aligned (1/4/8/16 GB), opt-in per+ // sandbox via PUT /api/sandboxes/:id/autoscale, runs only on the+ // server side that owns the worker registry. Unlike the cluster+ // scaler this doesn't need leader election — multiple instances+ // would both read sandbox stats and call SetSandboxLimits, which+ // is idempotent.+ if opts.Store != nil && redisRegistry != nil {+ autoscaler := controlplane.NewAutoscaler(opts.Store, redisRegistry, api.NewAutoscalerSetter(server))+ autoscaler.Start(ctx)+ defer autoscaler.Stop()+ log.Println("opensandbox: per-sandbox autoscaler started (interval=30s)")+ }+// Start usage reporter — reports Pro org usage to Stripe and deducts// free-tier trial credits (force-hibernates on empty) every 5 min.// redisRegistry may be nil in combined mode; reporter tolerates that bydiff --git a/cmd/worker/main.go b/cmd/worker/main.goindex 0bb408a9..4dd2a0c7 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -411,6 +411,27 @@ func main() {hb.SetMemoryInfoFunc(func() (int, int) {return qemuMgr.HostMemoryMB(), qemuMgr.TotalCommittedMemoryMB()})+ // Per-sandbox stats for the CP autoscaler. The stats collector+ // runs on a 10s tick (matching heartbeat cadence) and the+ // heartbeat reads the cached snapshot non-blockingly.+ qemuMgr.StartStatsCollector(ctx, 10*time.Second)+ hb.SetSandboxStatsFunc(func() map[string]worker.SandboxStatsWire {+ raw := qemuMgr.GetAllSandboxStats()+ out := make(map[string]worker.SandboxStatsWire, len(raw))+ for id, s := range raw {+ memPct := 0.0+ if s.MemLimit > 0 {+ memPct = float64(s.MemUsage) / float64(s.MemLimit) * 100+ }+ out[id] = worker.SandboxStatsWire{+ MemUsage: s.MemUsage,+ MemLimit: s.MemLimit,+ MemPct: memPct,+ CPUPct: s.CPUPercent,+ }+ }+ return out+ })}// On reconnect after outage, reconcile sandbox state with DBif store != nil {diff --git a/internal/api/router.go b/internal/api/router.goindex ae22b47b..1fa5df03 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -231,6 +231,8 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o// Resource limitsapi.PUT("/sandboxes/:id/limits", s.setLimits)api.POST("/sandboxes/:id/scale", s.scaleSandbox)+ api.PUT("/sandboxes/:id/autoscale", s.setAutoscale)+ api.GET("/sandboxes/:id/autoscale", s.getAutoscale)// Checkpointsapi.POST("/sandboxes/:id/checkpoints", s.createCheckpoint)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 111a8693..a922383b 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1122,6 +1122,16 @@ func (s *Server) scaleSandbox(c echo.Context) error {cpuMaxUsec := int64(cpuPercent) * 1000cpuPeriodUsec := int64(100000)+ // Manual scale disables autoscale. Rationale: a user explicitly setting a+ // size has signalled they want predictability — letting the autoscaler+ // override would surprise them. They can re-enable via PUT /autoscale.+ // Best-effort — failure to disable is logged but doesn't fail the scale.+ if s.store != nil {+ if err := s.store.SetSandboxAutoscale(c.Request().Context(), id, false, 0, 0); err != nil {+ log.Printf("scale: failed to disable autoscale on %s after manual scale: %v", id, err)+ }+ }+if s.workerRegistry != nil {return s.setLimitsRemote(c, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)}diff --git a/internal/api/sandbox_autoscale.go b/internal/api/sandbox_autoscale.gonew file mode 100644index 00000000..f08e1cfd--- /dev/null+++ b/internal/api/sandbox_autoscale.go@@ -0,0 +1,144 @@+package api++import (+ "context"+ "fmt"+ "net/http"+ "time"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/pkg/types"+ pbw "github.com/opensandbox/opensandbox/proto/worker"+)++// PUT /api/sandboxes/:id/autoscale+//+// Enables/disables per-sandbox autoscaler. Body:+//+// {+// "enabled": true,+// "minMemoryMB": 1024,+// "maxMemoryMB": 16384+// }+//+// minMemoryMB and maxMemoryMB must be allowed memory tiers (validated via+// types.ValidateMemoryMB). vCPU follows the tier table — there's no+// independent CPU bound. If `enabled=false`, min/max are cleared.+//+// Plan-level cap: an org's plan max_memory_gb (in orgs table) is the hard+// upper bound regardless of what the user requests. Free tier is capped at+// 4 GB just like the manual scale endpoint.+func (s *Server) setAutoscale(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }++ var req struct {+ Enabled bool `json:"enabled"`+ MinMemoryMB int `json:"minMemoryMB"`+ MaxMemoryMB int `json:"maxMemoryMB"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body"})+ }++ if req.Enabled {+ if _, err := types.ValidateMemoryMB(req.MinMemoryMB); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "minMemoryMB: " + err.Error()})+ }+ if _, err := types.ValidateMemoryMB(req.MaxMemoryMB); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "maxMemoryMB: " + err.Error()})+ }+ if req.MinMemoryMB > req.MaxMemoryMB {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "minMemoryMB must be ≤ maxMemoryMB"})+ }+ }++ if err := s.store.SetSandboxAutoscale(c.Request().Context(), sandboxID, req.Enabled, req.MinMemoryMB, req.MaxMemoryMB); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "enabled": req.Enabled,+ "minMemoryMB": req.MinMemoryMB,+ "maxMemoryMB": req.MaxMemoryMB,+ })+}++// GET /api/sandboxes/:id/autoscale+func (s *Server) getAutoscale(c echo.Context) error {+ sandboxID := c.Param("id")+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ enabled, minMB, maxMB, err := s.store.GetSandboxAutoscale(c.Request().Context(), sandboxID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})+ }+ return c.JSON(http.StatusOK, map[string]any{+ "sandboxID": sandboxID,+ "enabled": enabled,+ "minMemoryMB": minMB,+ "maxMemoryMB": maxMB,+ })+}++// AutoscalerSetter implements controlplane.AutoscalerScaleSetter by routing+// the scale request through the same SetSandboxLimits gRPC call that the+// manual /scale endpoint uses. We don't go through the HTTP layer — the+// autoscaler runs in-process and we already have direct access to the+// worker registry.+//+// CPU follows memory per types.AllowedResourceTiers (e.g., 8 GB ⇒ 4 vCPU).+type AutoscalerSetter struct {+ server *Server+}++// NewAutoscalerSetter wires the existing Server's worker registry into the+// autoscaler's scale-applier interface.+func NewAutoscalerSetter(server *Server) *AutoscalerSetter {+ return &AutoscalerSetter{server: server}+}++// SetSandboxMemoryMB applies a tier-aligned memory size to a sandbox. The+// autoscaler should only ever pass values that are already allowed tiers,+// but we re-validate here as defense in depth — if a future caller passes+// 6 GB we'd silently corrupt the worker's expected scaling table.+func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID string, memoryMB int) error {+ vcpus, err := types.ValidateMemoryMB(memoryMB)+ if err != nil {+ return fmt.Errorf("invalid memoryMB %d: %w", memoryMB, err)+ }+ if a.server.workerRegistry == nil || a.server.store == nil {+ return fmt.Errorf("autoscaler: server not configured for remote worker calls")+ }++ session, err := a.server.store.GetSandboxSession(ctx, sandboxID)+ if err != nil {+ return fmt.Errorf("get session: %w", err)+ }+ if session.Status != "running" {+ // Don't try to scale stopped/hibernated sandboxes — the autoscaler+ // shouldn't have picked them, but better to no-op cleanly than fail.+ return nil+ }++ client, err := a.server.workerRegistry.GetWorkerClient(session.WorkerID)+ if err != nil {+ return fmt.Errorf("get worker client: %w", err)+ }++ rpcCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()++ cpuPercent := vcpus * 100+ _, err = client.SetSandboxLimits(rpcCtx, &pbw.SetSandboxLimitsRequest{+ SandboxId: sandboxID,+ MaxPids: 0,+ MaxMemoryBytes: int64(memoryMB) * 1024 * 1024,+ CpuMaxUsec: int64(cpuPercent) * 1000,+ CpuPeriodUsec: 100000,+ })+ return err+}diff --git a/internal/controlplane/autoscaler.go b/internal/controlplane/autoscaler.gonew file mode 100644index 00000000..ccd97bb0--- /dev/null+++ b/internal/controlplane/autoscaler.go@@ -0,0 +1,320 @@+package controlplane++import (+ "context"+ "fmt"+ "log"+ "sort"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// Per-sandbox autoscaler. Resizes a sandbox's memory tier (with vCPU bundled+// per types.AllowedResourceTiers) based on observed memory pressure, bounded+// by user-configured min/max.+//+// Design choices:+// - Tier-aligned. We never pick a half-step size — only values from+// types.AllowedResourceTiers (1G/4G/8G/16G/32G/64G). This keeps billing+// predictable and avoids the configuration explosion of a free-form+// step_gb knob. vCPU follows memory by the tier table.+// - Asymmetric thresholds and cooldowns. Scale up FAST on a brief 1-min+// spike (>75% mem) — user notices lag, we want to fix it before they+// OOM. Scale down SLOW: require all of {1m, 5m, 15m} averages below+// 25% AND at least 5 minutes since the last scale event. This stops+// the sawtooth pattern from a workload that briefly idles.+// - In-memory state. Moving averages and last-event timestamps live in+// CP memory. On CP restart we lose history; the autoscaler self-+// corrects within ~15 minutes (the longest window). Worth the cost+// vs adding Redis writes per sandbox per tick.+// - No live-migrate fallback. If a SetSandboxLimits up-call fails because+// the host can't fit the new size, we log and try again next tick. A+// migration fallback is Phase 3 (depends on the fork-reliability work+// in PR #207 being solid first).+const (+ autoscaleTickInterval = 30 * time.Second++ // Scale-up triggers on a single 1-min sample exceeding the threshold.+ // One window is enough because users feel pressure immediately.+ scaleUpMemPctThreshold = 75.0++ // Scale-down requires ALL three averaging windows below the threshold.+ // 1-min protects against transient idle, 5-min/15-min confirm steady-+ // state. The 15-min window is the dominant constraint — at 30-second+ // ticks that's 30 samples of agreement before we shrink.+ scaleDownMemPctThreshold = 25.0++ // Cooldowns. After scaling up, wait at least 60s before another up.+ // After scaling down, wait 5 min before considering more scaling+ // (either direction). The asymmetry matches user perception: rapid+ // scale-up on demand, conservative shrink after sustained idle.+ scaleUpCooldown = 60 * time.Second+ scaleDownCooldown = 5 * time.Minute+)++// Sample windows (counts of 30s ticks).+const (+ window1m = 2 // 60s / 30s+ window5m = 10 // 300s / 30s+ window15m = 30 // 900s / 30s+)++// AutoscalerSandboxStore is the subset of the DB we need.+type AutoscalerSandboxStore interface {+ // ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true.+ ListAutoscaleEnabled(ctx context.Context) ([]db.AutoscaleSandbox, error)+ // UpdateAutoscaleLastEvent records a scale event for cooldown tracking.+ UpdateAutoscaleLastEvent(ctx context.Context, sandboxID string, t time.Time) error+}++// AutoscalerRegistry is the small subset of WorkerRegistry the autoscaler+// uses. The autoscaler reads cached per-sandbox stats off the registry —+// stats are populated from worker heartbeats, not pulled per-tick by the+// CP. See redis_registry.go's GetSandboxStats for the cache.+type AutoscalerRegistry interface {+ // GetSandboxStats returns the latest snapshot for a sandbox plus the+ // worker hosting it, or ok=false if no recent heartbeat has carried it.+ GetSandboxStats(sandboxID string) (SandboxStats, string, bool)+}++// AutoscalerScaleSetter applies a scale decision via the existing setLimits+// machinery (worker gRPC SetSandboxLimits). Decoupled so we can test without+// a real worker.+type AutoscalerScaleSetter interface {+ SetSandboxMemoryMB(ctx context.Context, sandboxID string, memoryMB int) error+}++type Autoscaler struct {+ store AutoscalerSandboxStore+ registry AutoscalerRegistry+ setter AutoscalerScaleSetter++ mu sync.Mutex+ stats map[string]*sandboxStats // sandboxID → samples+ stop chan struct{}+}++type sandboxStats struct {+ memSamples []float64 // most recent first; trimmed to window15m+}++// NewAutoscaler wires up the loop. Caller invokes Start to begin ticking.+func NewAutoscaler(store AutoscalerSandboxStore, registry AutoscalerRegistry, setter AutoscalerScaleSetter) *Autoscaler {+ return &Autoscaler{+ store: store,+ registry: registry,+ setter: setter,+ stats: make(map[string]*sandboxStats),+ stop: make(chan struct{}),+ }+}++// Start runs the autoscaler loop until ctx is cancelled or Stop is called.+func (a *Autoscaler) Start(ctx context.Context) {+ go a.run(ctx)+}++func (a *Autoscaler) Stop() { close(a.stop) }++func (a *Autoscaler) run(ctx context.Context) {+ log.Println("autoscaler: started")+ ticker := time.NewTicker(autoscaleTickInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-a.stop:+ return+ case <-ticker.C:+ a.tick(ctx)+ }+ }+}++func (a *Autoscaler) tick(ctx context.Context) {+ sandboxes, err := a.store.ListAutoscaleEnabled(ctx)+ if err != nil {+ log.Printf("autoscaler: ListAutoscaleEnabled failed: %v", err)+ return+ }++ // Drop stats for sandboxes that are no longer autoscale-enabled (or are gone).+ a.mu.Lock()+ keep := make(map[string]bool, len(sandboxes))+ for _, sb := range sandboxes {+ keep[sb.SandboxID] = true+ }+ for id := range a.stats {+ if !keep[id] {+ delete(a.stats, id)+ }+ }+ a.mu.Unlock()++ for _, sb := range sandboxes {+ a.evaluateOne(ctx, sb)+ }+}++func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {+ // 1. Fetch current stats from the worker.+ memPct, err := a.fetchMemPct(ctx, sb)+ if err != nil {+ // Transient — log at low frequency and skip.+ log.Printf("autoscaler: %s stats fetch failed: %v", sb.SandboxID, err)+ return+ }++ // 2. Record sample.+ a.recordSample(sb.SandboxID, memPct)++ // 3. Decide.+ target := a.decideTarget(sb)+ if target == 0 || target == sb.CurrentMB {+ return+ }++ // 4. Apply.+ if err := a.setter.SetSandboxMemoryMB(ctx, sb.SandboxID, target); err != nil {+ log.Printf("autoscaler: %s scale %d→%d MB failed: %v", sb.SandboxID, sb.CurrentMB, target, err)+ return+ }+ if err := a.store.UpdateAutoscaleLastEvent(ctx, sb.SandboxID, time.Now()); err != nil {+ log.Printf("autoscaler: %s update last_event failed: %v", sb.SandboxID, err)+ }+ log.Printf("autoscaler: %s scaled %d MB → %d MB (mem=%.1f%% min=%d max=%d)",+ sb.SandboxID, sb.CurrentMB, target, memPct, sb.MinMB, sb.MaxMB)+}++// fetchMemPct returns the latest cached mem_pct for a sandbox. Stats are+// populated by worker heartbeats — see internal/qemu/stats_collector.go on+// the worker side and redis_registry.go's handleHeartbeat ingestion.+//+// Returns ok=false (via the err) if no recent heartbeat has carried this+// sandbox. The autoscaler skips the tick for that sandbox; on the next+// heartbeat (~10s later) the data should appear.+func (a *Autoscaler) fetchMemPct(_ context.Context, sb db.AutoscaleSandbox) (float64, error) {+ stats, _, ok := a.registry.GetSandboxStats(sb.SandboxID)+ if !ok {+ return 0, fmt.Errorf("no cached stats for %s — worker heartbeat may be stale", sb.SandboxID)+ }+ return stats.MemPct, nil+}++func (a *Autoscaler) recordSample(sandboxID string, memPct float64) {+ a.mu.Lock()+ defer a.mu.Unlock()+ s, ok := a.stats[sandboxID]+ if !ok {+ s = &sandboxStats{}+ a.stats[sandboxID] = s+ }+ // Most recent first. Trim to longest window.+ s.memSamples = append([]float64{memPct}, s.memSamples...)+ if len(s.memSamples) > window15m {+ s.memSamples = s.memSamples[:window15m]+ }+}++// decideTarget returns the memory MB to scale to, or 0 if no change.+func (a *Autoscaler) decideTarget(sb db.AutoscaleSandbox) int {+ a.mu.Lock()+ s := a.stats[sb.SandboxID]+ a.mu.Unlock()+ if s == nil || len(s.memSamples) == 0 {+ return 0+ }++ currentMB := sb.CurrentMB+ if currentMB == 0 {+ return 0 // unknown current — don't risk scaling+ }++ avg1 := windowAvg(s.memSamples, window1m)+ avg5 := windowAvg(s.memSamples, window5m)+ avg15 := windowAvg(s.memSamples, window15m)++ now := time.Now()++ // Scale up: 1-min above threshold, current < max, off scale-up cooldown.+ if avg1 > scaleUpMemPctThreshold && currentMB < sb.MaxMB {+ if !sb.LastEventAt.IsZero() && now.Sub(sb.LastEventAt) < scaleUpCooldown {+ return 0+ }+ next := nextTier(currentMB, sb.MaxMB)+ if next > currentMB {+ return next+ }+ }++ // Scale down: ALL three windows below threshold, current > min, off scale-down cooldown.+ // Need at least window15m samples — otherwise the long window is misleading.+ if avg1 < scaleDownMemPctThreshold && avg5 < scaleDownMemPctThreshold && avg15 < scaleDownMemPctThreshold &&+ len(s.memSamples) >= window15m && currentMB > sb.MinMB {+ if !sb.LastEventAt.IsZero() && now.Sub(sb.LastEventAt) < scaleDownCooldown {+ return 0+ }+ prev := prevTier(currentMB, sb.MinMB)+ if prev < currentMB {+ return prev+ }+ }++ return 0+}++// windowAvg returns the mean of the most recent n samples (or all of them if+// fewer exist). Caller must hold no lock — operates on the slice argument.+func windowAvg(samples []float64, n int) float64 {+ if n > len(samples) {+ n = len(samples)+ }+ if n == 0 {+ return 0+ }+ var sum float64+ for i := 0; i < n; i++ {+ sum += samples[i]+ }+ return sum / float64(n)+}++// nextTier returns the next memory tier above current, capped at maxMB.+// Returns current if no higher tier is allowed.+func nextTier(currentMB, maxMB int) int {+ tiers := tierMBs()+ for _, t := range tiers {+ if t > currentMB && t <= maxMB {+ return t+ }+ }+ return currentMB+}++// prevTier returns the next memory tier below current, floored at minMB.+// Returns current if no lower tier is allowed.+func prevTier(currentMB, minMB int) int {+ tiers := tierMBs()+ // Iterate descending.+ for i := len(tiers) - 1; i >= 0; i-- {+ if tiers[i] < currentMB && tiers[i] >= minMB {+ return tiers[i]+ }+ }+ return currentMB+}++// tierMBs returns the allowed memory tier values in ascending order.+// Pulled from the canonical tier list in pkg/types so we can never disagree.+func tierMBs() []int {+ out := make([]int, 0, len(types.AllowedResourceTiers))+ for _, t := range types.AllowedResourceTiers {+ out = append(out, t.MemoryMB)+ }+ sort.Ints(out)+ return out+}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 48836951..dec4d63d 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -35,6 +35,21 @@ type WorkerEntry struct {GoldenVersion string `json:"golden_version,omitempty"`WorkerVersion string `json:"worker_version,omitempty"`Draining bool `json:"draining,omitempty"`++ // Per-sandbox stats published by the worker. Bounded by per-host sandbox+ // capacity (~50-150 entries) so the heartbeat doesn't grow unboundedly.+ // Consumed by the autoscaler — see GetSandboxStats accessor below.+ Sandboxes map[string]SandboxStats `json:"sandboxes,omitempty"`+}++// SandboxStats is the per-sandbox snapshot ingested from worker heartbeats.+// Mirrors internal/worker.SandboxStatsWire — kept separate to avoid an+// import cycle (CP shouldn't depend on the worker package).+type SandboxStats struct {+ MemUsage uint64 `json:"mem_usage"`+ MemLimit uint64 `json:"mem_limit"`+ MemPct float64 `json:"mem_pct"`+ CPUPct float64 `json:"cpu_pct"`}// RedisWorkerRegistry maintains an in-memory cache of worker state@@ -48,6 +63,13 @@ type RedisWorkerRegistry struct {clients map[string]pb.SandboxWorkerClient // cached gRPC clientsrrCounter uint64 // round-robin counter for tie-breakingstop chan struct{}++ // Per-sandbox stats indexed by sandboxID for O(1) autoscaler lookup. Updated+ // from each worker heartbeat. Lock-protected separately from workers so the+ // autoscaler doesn't contend with the routing path (which holds workersMu).+ sandboxStatsMu sync.RWMutex+ sandboxStats map[string]SandboxStats // sandboxID → latest snapshot+ sandboxOnWorker map[string]string // sandboxID → workerID (for prune-on-disappear)}// RedisClient returns the underlying Redis client (for health checks, shared state, etc.).@@ -55,6 +77,20 @@ func (r *RedisWorkerRegistry) RedisClient() *redis.Client {return r.rdb}+// GetSandboxStats returns the latest cached stats for a sandbox along with+// its host worker, or ok=false if no recent heartbeat has carried that+// sandbox. The autoscaler's per-tick fetchMemPct uses this — replaces the+// previous gRPC fan-out which scaled O(total sandboxes) per tick.+func (r *RedisWorkerRegistry) GetSandboxStats(sandboxID string) (SandboxStats, string, bool) {+ r.sandboxStatsMu.RLock()+ defer r.sandboxStatsMu.RUnlock()+ stats, ok := r.sandboxStats[sandboxID]+ if !ok {+ return SandboxStats{}, "", false+ }+ return stats, r.sandboxOnWorker[sandboxID], true+}+// NewRedisWorkerRegistry connects to Redis and returns a new registry.func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {opts, err := redis.ParseURL(redisURL)@@ -77,11 +113,13 @@ func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {}return &RedisWorkerRegistry{- rdb: rdb,- workers: make(map[string]*WorkerEntry),- conns: make(map[string]*grpc.ClientConn),- clients: make(map[string]pb.SandboxWorkerClient),- stop: make(chan struct{}),+ rdb: rdb,+ workers: make(map[string]*WorkerEntry),+ conns: make(map[string]*grpc.ClientConn),+ clients: make(map[string]pb.SandboxWorkerClient),+ sandboxStats: make(map[string]SandboxStats),+ sandboxOnWorker: make(map[string]string),+ stop: make(chan struct{}),}, nil}@@ -240,6 +278,33 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s)", entry.ID, entry.Region, entry.GRPCAddr)}+ // Per-sandbox stats indexing. Update fresh entries; prune sandboxes that+ // the worker reported last time but didn't this time (sandbox destroyed+ // between heartbeats). Done under a separate mutex so the autoscaler's+ // stats lookups don't contend with the routing path's worker map updates.+ r.sandboxStatsMu.Lock()+ if len(entry.Sandboxes) > 0 {+ for sbID, stats := range entry.Sandboxes {+ r.sandboxStats[sbID] = stats+ r.sandboxOnWorker[sbID] = entry.ID+ }+ }+ // Prune: any sandbox previously associated with this worker that's no+ // longer in the heartbeat is gone (destroyed/migrated). We don't prune on+ // `len(entry.Sandboxes) == 0` because that may legitimately mean "0+ // sandboxes on this worker right now" (after dance drained it) — and we+ // still want to remove our stale memories.+ for sbID, wID := range r.sandboxOnWorker {+ if wID != entry.ID {+ continue+ }+ if _, still := entry.Sandboxes[sbID]; !still {+ delete(r.sandboxStats, sbID)+ delete(r.sandboxOnWorker, sbID)+ }+ }+ r.sandboxStatsMu.Unlock()+// Ensure gRPC connection exists and is healthy.// Re-dial if address changed, connection is failed/idle, or worker is newly registered.if entry.GRPCAddr != "" {diff --git a/internal/db/migrations/032_sandbox_autoscale.down.sql b/internal/db/migrations/032_sandbox_autoscale.down.sqlnew file mode 100644index 00000000..e0642605--- /dev/null+++ b/internal/db/migrations/032_sandbox_autoscale.down.sql@@ -0,0 +1,7 @@+DROP INDEX IF EXISTS idx_sandbox_sessions_autoscale_active;++ALTER TABLE sandbox_sessions+ DROP COLUMN IF EXISTS autoscale_last_event_at,+ DROP COLUMN IF EXISTS autoscale_max_mb,+ DROP COLUMN IF EXISTS autoscale_min_mb,+ DROP COLUMN IF EXISTS autoscale_enabled;diff --git a/internal/db/migrations/032_sandbox_autoscale.up.sql b/internal/db/migrations/032_sandbox_autoscale.up.sqlnew file mode 100644index 00000000..db695569--- /dev/null+++ b/internal/db/migrations/032_sandbox_autoscale.up.sql@@ -0,0 +1,19 @@+-- Per-sandbox autoscaler config. NULL columns mean autoscale is disabled+-- (default for all existing sandboxes). When enabled, CP autoscaler resizes+-- the sandbox between min and max along the configured tier list (1, 4, 8,+-- 16 GB today) based on observed memory pressure.+--+-- Asymmetric thresholds: scale up fast on a brief 1m spike (>75%); scale+-- down only after sustained low utilization across 1m AND 5m AND 15m moving+-- averages (<25% on each). Cooldowns prevent flapping.++ALTER TABLE sandbox_sessions+ ADD COLUMN autoscale_enabled BOOLEAN NOT NULL DEFAULT FALSE,+ ADD COLUMN autoscale_min_mb INT,+ ADD COLUMN autoscale_max_mb INT,+ ADD COLUMN autoscale_last_event_at TIMESTAMPTZ;++-- Partial index lets the autoscaler scan the active set cheaply.+CREATE INDEX idx_sandbox_sessions_autoscale_active+ ON sandbox_sessions (sandbox_id)+ WHERE autoscale_enabled = TRUE AND status = 'running';diff --git a/internal/db/sandbox_autoscale.go b/internal/db/sandbox_autoscale.gonew file mode 100644index 00000000..ffbbe6cf--- /dev/null+++ b/internal/db/sandbox_autoscale.go@@ -0,0 +1,102 @@+package db++import (+ "context"+ "fmt"+ "time"+)++// AutoscaleSandbox is the per-sandbox row the autoscaler loop reads each+// tick. Defined here (not in internal/controlplane) so the db package owns+// its own row type and the autoscaler imports from db rather than the+// other way around — avoids the controlplane↔db import cycle.+type AutoscaleSandbox struct {+ SandboxID string+ WorkerID string+ OrgID string+ CurrentMB int // current memoryMB, parsed from sandbox_sessions.config+ MinMB int // user-configured floor (0 = unset)+ MaxMB int // user-configured ceiling (0 = unset)+ LastEventAt time.Time // zero if never scaled+}++// SetSandboxAutoscale enables/disables autoscale for a sandbox and writes+// the min/max bounds. Caller is responsible for validating min/max are+// allowed memory tiers (see types.AllowedResourceTiers).+func (s *Store) SetSandboxAutoscale(ctx context.Context, sandboxID string, enabled bool, minMB, maxMB int) error {+ _, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions+ SET autoscale_enabled = $1,+ autoscale_min_mb = NULLIF($2, 0),+ autoscale_max_mb = NULLIF($3, 0)+ WHERE sandbox_id = $4+ `, enabled, minMB, maxMB, sandboxID)+ if err != nil {+ return fmt.Errorf("set autoscale on %s: %w", sandboxID, err)+ }+ return nil+}++// GetSandboxAutoscale returns the autoscale config for a sandbox.+func (s *Store) GetSandboxAutoscale(ctx context.Context, sandboxID string) (enabled bool, minMB, maxMB int, err error) {+ var minVal, maxVal *int+ err = s.pool.QueryRow(ctx, `+ SELECT autoscale_enabled, autoscale_min_mb, autoscale_max_mb+ FROM sandbox_sessions WHERE sandbox_id = $1+ `, sandboxID).Scan(&enabled, &minVal, &maxVal)+ if err != nil {+ return false, 0, 0, err+ }+ if minVal != nil {+ minMB = *minVal+ }+ if maxVal != nil {+ maxMB = *maxVal+ }+ return enabled, minMB, maxMB, nil+}++// ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true.+// The partial index added in migration 032 keeps this scan cheap regardless+// of total session count.+//+// CurrentMB is parsed from sandbox_sessions.config — the canonical source-+// of-truth for sandbox sizing. We don't track it as a separate column to+// avoid drift between the autoscale "what we think it is" and the worker's+// actual virtio-mem state.+func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, error) {+ rows, err := s.pool.Query(ctx, `+ SELECT sandbox_id, worker_id, org_id::text,+ COALESCE((config->>'memoryMB')::int, 0) AS current_mb,+ COALESCE(autoscale_min_mb, 0) AS min_mb,+ COALESCE(autoscale_max_mb, 0) AS max_mb,+ COALESCE(autoscale_last_event_at, '1970-01-01'::timestamptz) AS last_event_at+ FROM sandbox_sessions+ WHERE autoscale_enabled = TRUE AND status = 'running'+ `)+ if err != nil {+ return nil, fmt.Errorf("list autoscale-enabled: %w", err)+ }+ defer rows.Close()++ var out []AutoscaleSandbox+ for rows.Next() {+ var sb AutoscaleSandbox+ if err := rows.Scan(&sb.SandboxID, &sb.WorkerID, &sb.OrgID,+ &sb.CurrentMB, &sb.MinMB, &sb.MaxMB, &sb.LastEventAt); err != nil {+ return nil, err+ }+ out = append(out, sb)+ }+ return out, rows.Err()+}++// UpdateAutoscaleLastEvent stamps the cooldown anchor after a scale event+// (either direction). The autoscaler reads this before deciding whether+// the per-direction cooldown has elapsed.+func (s *Store) UpdateAutoscaleLastEvent(ctx context.Context, sandboxID string, t time.Time) error {+ _, err := s.pool.Exec(ctx, `+ UPDATE sandbox_sessions SET autoscale_last_event_at = $1 WHERE sandbox_id = $2+ `, t, sandboxID)+ return err+}diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex b1adc596..fa3163a1 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -188,6 +188,10 @@ type Manager struct {secretsProxy SecretsProxyIntegration // nil if secrets proxy is not configuredcheckpointStore *storage.CheckpointStore // for base image archival + checkpoint rebasing (nil until set)++ // Per-sandbox stats cache populated by a background collector and read by+ // the heartbeat path. See stats_collector.go.+ statsCache *SandboxStatsCache}// NewManager creates a new QEMU-backed sandbox manager.diff --git a/internal/qemu/stats_collector.go b/internal/qemu/stats_collector.gonew file mode 100644index 00000000..3c3d38c6--- /dev/null+++ b/internal/qemu/stats_collector.go@@ -0,0 +1,122 @@+package qemu++import (+ "context"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/sandbox"+)++// SandboxStatsCache holds the latest per-sandbox resource snapshots gathered+// by a periodic background collector. The autoscaler in the control plane+// reads these via the worker's heartbeat — see internal/worker/redis_heartbeat.go.+//+// Why a cache: collecting stats requires a gRPC round-trip to the agent in+// each VM (over virtio-serial). Doing that lazily inside the heartbeat publish+// path would block heartbeats for ~5-10ms × N sandboxes. A separate goroutine+// polls in parallel and the heartbeat reads from a snapshot map — heartbeats+// stay fast and stats are at most one collection interval stale.+type SandboxStatsCache struct {+ mu sync.RWMutex+ stats map[string]sandbox.SandboxStats // sandboxID → latest snapshot+}++// StartStatsCollector launches a goroutine that polls every running sandbox's+// agent.Stats and caches the response. The heartbeat path reads the cached+// snapshot. Stops when ctx is cancelled.+//+// Concurrency: limited to 8 in-flight collections so a worker hosting 100++// sandboxes doesn't spike its virtio-serial channel pool. 100 sandboxes × 10ms+// per call ÷ 8 concurrent ≈ 125ms per collection round. Comfortable inside+// the 10s heartbeat cadence.+func (m *Manager) StartStatsCollector(ctx context.Context, interval time.Duration) {+ if m.statsCache == nil {+ m.statsCache = &SandboxStatsCache{stats: make(map[string]sandbox.SandboxStats)}+ }+ go func() {+ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ // Collect once immediately so the first heartbeat after worker boot+ // has data instead of an empty map.+ m.collectAllStats(ctx)+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ m.collectAllStats(ctx)+ }+ }+ }()+}++func (m *Manager) collectAllStats(ctx context.Context) {+ m.mu.RLock()+ ids := make([]string, 0, len(m.vms))+ for id := range m.vms {+ ids = append(ids, id)+ }+ m.mu.RUnlock()++ const maxConcurrent = 8+ sem := make(chan struct{}, maxConcurrent)+ var wg sync.WaitGroup+ for _, id := range ids {+ wg.Add(1)+ sem <- struct{}{}+ go func(sandboxID string) {+ defer wg.Done()+ defer func() { <-sem }()++ statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ stats, err := m.Stats(statsCtx, sandboxID)+ if err != nil {+ // Stats call can fail transiently (agent restarting, etc.)+ // We just skip this sandbox this round; next collection picks+ // it up. Stale entry stays in cache for one cycle which is+ // fine for the autoscaler — it's looking at moving averages+ // over a 1-15 min window.+ return+ }+ m.statsCache.mu.Lock()+ m.statsCache.stats[sandboxID] = *stats+ m.statsCache.mu.Unlock()+ }(id)+ }+ wg.Wait()++ // Prune entries for vanished sandboxes so the cache doesn't leak across+ // destroy events.+ m.mu.RLock()+ live := make(map[string]bool, len(m.vms))+ for id := range m.vms {+ live[id] = true+ }+ m.mu.RUnlock()++ m.statsCache.mu.Lock()+ for id := range m.statsCache.stats {+ if !live[id] {+ delete(m.statsCache.stats, id)+ }+ }+ m.statsCache.mu.Unlock()+}++// GetAllSandboxStats returns a snapshot map of the latest cached stats. Safe+// to call concurrently with the collector. Used by the heartbeat to populate+// the per-sandbox stats portion of the worker:* Redis entry.+func (m *Manager) GetAllSandboxStats() map[string]sandbox.SandboxStats {+ if m.statsCache == nil {+ return nil+ }+ m.statsCache.mu.RLock()+ defer m.statsCache.mu.RUnlock()+ out := make(map[string]sandbox.SandboxStats, len(m.statsCache.stats))+ for id, s := range m.statsCache.stats {+ out[id] = s+ }+ return out+}diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.goindex 278156b8..1b53e5bd 100644--- a/internal/worker/redis_heartbeat.go+++ b/internal/worker/redis_heartbeat.go@@ -26,6 +26,24 @@ type redisHeartbeatPayload struct {CommittedMemoryMB int `json:"committed_memory_mb,omitempty"`GoldenVersion string `json:"golden_version,omitempty"`WorkerVersion string `json:"worker_version,omitempty"`++ // Per-sandbox stats snapshot. Populated by the worker's stats collector+ // (see internal/qemu/stats_collector.go) and consumed by the CP autoscaler+ // (see internal/controlplane/autoscaler.go). Bounded by the worker's+ // physical sandbox capacity (~50-150 entries on a D64 host) regardless of+ // total cluster size, so the heartbeat payload doesn't grow unboundedly.+ Sandboxes map[string]SandboxStatsWire `json:"sandboxes,omitempty"`+}++// SandboxStatsWire is the wire form of per-sandbox stats included in the+// heartbeat. Subset of internal/sandbox.SandboxStats — only what the+// autoscaler / dashboard consumers actually need. Pre-computed mem_pct+// avoids divide-by-zero handling at every consumer.+type SandboxStatsWire struct {+ MemUsage uint64 `json:"mem_usage"`+ MemLimit uint64 `json:"mem_limit"`+ MemPct float64 `json:"mem_pct"`+ CPUPct float64 `json:"cpu_pct"`}// RedisHeartbeat publishes periodic heartbeats to Redis for worker discovery.@@ -39,9 +57,10 @@ type RedisHeartbeat struct {region stringgrpcAddr stringhttpAddr string- getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)- getMemoryInfo func() (totalMB, committedMB int) // optional: committed memory for dynamic capacity- onReconnect func() // called when heartbeat succeeds after a previous failure+ getStats func() (capacity, current int, cpuPct, memPct, diskPct float64)+ getMemoryInfo func() (totalMB, committedMB int) // optional: committed memory for dynamic capacity+ getSandboxStats func() map[string]SandboxStatsWire // optional: per-sandbox stats for autoscaler+ onReconnect func() // called when heartbeat succeeds after a previous failuregoldenVersion stringworkerVersion stringwasDown bool // true if the last publish failed (used to detect reconnect)@@ -101,6 +120,13 @@ func (h *RedisHeartbeat) SetMemoryInfoFunc(fn func() (totalMB, committedMB int))h.getMemoryInfo = fn}+// SetSandboxStatsFunc registers a callback that returns the latest per-sandbox+// stats snapshot. The heartbeat publishes this map under the "sandboxes" field+// for the CP autoscaler. Wire it to qemu.Manager's stats cache.+func (h *RedisHeartbeat) SetSandboxStatsFunc(fn func() map[string]SandboxStatsWire) {+ h.getSandboxStats = fn+}+// OnReconnect sets a callback that fires when heartbeat succeeds after a failure.// Used to reconcile sandbox state after a network outage.func (h *RedisHeartbeat) OnReconnect(fn func()) {@@ -154,6 +180,13 @@ func (h *RedisHeartbeat) publish() {payload.CommittedMemoryMB = committedMB}+ // Per-sandbox stats for the CP autoscaler. Skipped silently if no+ // collector is wired — preserves backward compat with deployments where+ // the autoscaler is disabled.+ if h.getSandboxStats != nil {+ payload.Sandboxes = h.getSandboxStats()+ }+data, err := json.Marshal(payload)if err != nil {log.Printf("redis_heartbeat: marshal error: %v", err)