An open-source, faster Devin alternative
TypeScript
respect tier, reset on reboot, leader CP controlers, correct hotplug on reset
Brian Reardona558f72bf3d0
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 8a2ed920..54d7deb2 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -166,6 +166,13 @@ func main() {}}+ // Hoisted at function scope so the per-sandbox autoscaler (created+ // later, after the API server) can consult IsLeader() each tick — keeps+ // a single elector authoritative across both the cluster scaler and the+ // per-sandbox autoscaler in HA setups. nil when there's no compute pool+ // (combined / dev mode) — autoscaler then runs unconditionally.+ var leaderElector *controlplane.LeaderElector+// Initialize compute pool + autoscaler (server mode)if cfg.Mode == "server" && redisRegistry != nil {var pool compute.Pool@@ -302,19 +309,22 @@ func main() {})defer scaler.Stop()- // Leader election: only the leader runs the scaler- elector := controlplane.NewLeaderElector(redisRegistry.RedisClient(), cfg.WorkerID)- elector.OnBecomeLeader(func() {+ // Leader election: only the leader runs the scaler. The+ // per-sandbox autoscaler (created later) consults this same+ // elector via IsLeader() to skip ticks when not leader, so we+ // don't double-fire scale decisions across CPs in HA setups.+ leaderElector = controlplane.NewLeaderElector(redisRegistry.RedisClient(), cfg.WorkerID)+ leaderElector.OnBecomeLeader(func() {scaler.Start()log.Printf("opensandbox: became leader, autoscaler started (%s)", poolName)})- elector.OnLoseLeadership(func() {+ leaderElector.OnLoseLeadership(func() {scaler.Stop()log.Println("opensandbox: lost leadership, autoscaler stopped")})- elector.Start()- defer elector.Stop()- log.Printf("opensandbox: leader election started (instance=%s)", elector.InstanceID())+ leaderElector.Start()+ defer leaderElector.Stop()+ log.Printf("opensandbox: leader election started (instance=%s)", leaderElector.InstanceID())}}@@ -382,16 +392,25 @@ func main() {server := 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.+ // sandbox via PUT /api/sandboxes/:id/autoscale.+ //+ // Leader-gated when an elector exists. With HA (multiple CPs) we don't+ // want two instances both reading stats and double-firing scale events.+ // SetSandboxLimits is technically idempotent for memory targets, but+ // the cooldown CAS races and the cooldown timestamp gets clobbered if+ // both CPs UPDATE — see ClaimAutoscaleEvent. Gating on the leader is+ // cheaper than relying on the CAS alone. When there's no elector+ // (single-CP / no cloud pool), isLeader is nil and the loop runs+ // unconditionally.if opts.Store != nil && redisRegistry != nil {- autoscaler := controlplane.NewAutoscaler(opts.Store, redisRegistry, api.NewAutoscalerSetter(server))+ var isLeader func() bool+ if leaderElector != nil {+ isLeader = leaderElector.IsLeader+ }+ autoscaler := controlplane.NewAutoscaler(opts.Store, redisRegistry, api.NewAutoscalerSetter(server), isLeader)autoscaler.Start(ctx)defer autoscaler.Stop()- log.Println("opensandbox: per-sandbox autoscaler started (interval=30s)")+ log.Println("opensandbox: per-sandbox autoscaler started (interval=30s, leader-gated)")}// Start usage reporter — reports Pro org usage to Stripe and deductsdiff --git a/internal/api/sandbox_autoscale.go b/internal/api/sandbox_autoscale.goindex f08e1cfd..bb34b2db 100644--- a/internal/api/sandbox_autoscale.go+++ b/internal/api/sandbox_autoscale.go@@ -7,6 +7,7 @@ import ("time""github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/pkg/types"pbw "github.com/opensandbox/opensandbox/proto/worker")@@ -53,6 +54,19 @@ func (s *Server) setAutoscale(c echo.Context) error {if req.MinMemoryMB > req.MaxMemoryMB {return c.JSON(http.StatusBadRequest, map[string]string{"error": "minMemoryMB must be ≤ maxMemoryMB"})}+ // Plan cap: free tier is bounded at 4 GB just like manual /scale.+ // Without this a free-tier user could PUT max=16GB and the+ // autoscaler would obediently scale them past their plan. Mirror the+ // same check we apply in scaleSandbox so the two paths can't diverge.+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg {+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org.Plan == "free" {+ if req.MaxMemoryMB > 4096 {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "free plan caps autoscale at 4096 MB — upgrade to pro for larger instances",+ })+ }+ }+ }}if err := s.store.SetSandboxAutoscale(c.Request().Context(), sandboxID, req.Enabled, req.MinMemoryMB, req.MaxMemoryMB); err != nil {@@ -105,7 +119,12 @@ func NewAutoscalerSetter(server *Server) *AutoscalerSetter {// 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 {+//+// On success we also emit an admin event so the operator dashboard sees+// every autoscaler-driven scale event ("why did sandbox X grow last+// night?" — answer is now visible without grepping logs).+func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID string, fromMB, toMB int) error {+ memoryMB := toMBvcpus, err := types.ValidateMemoryMB(memoryMB)if err != nil {return fmt.Errorf("invalid memoryMB %d: %w", memoryMB, err)@@ -124,6 +143,14 @@ func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID strreturn nil}+ // Defense in depth: re-check the org plan cap here in case the autoscale+ // row was set before a downgrade or the cap was raised by another path.+ // The PUT /autoscale handler already enforces this; this is the second+ // gate so an obsolete row can't keep scaling past plan limits.+ if org, err := a.server.store.GetOrg(ctx, session.OrgID); err == nil && org.Plan == "free" && memoryMB > 4096 {+ return fmt.Errorf("plan cap: free plan limited to 4096 MB, refusing autoscale to %d", memoryMB)+ }+client, err := a.server.workerRegistry.GetWorkerClient(session.WorkerID)if err != nil {return fmt.Errorf("get worker client: %w", err)@@ -140,5 +167,13 @@ func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID strCpuMaxUsec: int64(cpuPercent) * 1000,CpuPeriodUsec: 100000,})- return err+ if err != nil {+ return err+ }+ // Audit event — visible in /admin/events SSE + /admin/events/history.+ if a.server.adminEvents != nil {+ a.server.adminEvents.Publish("autoscale", sandboxID, session.WorkerID,+ fmt.Sprintf("autoscaler: %dMB → %dMB", fromMB, toMB))+ }+ return nil}diff --git a/internal/controlplane/autoscaler.go b/internal/controlplane/autoscaler.goindex 5786bfee..d1496419 100644--- a/internal/controlplane/autoscaler.go+++ b/internal/controlplane/autoscaler.go@@ -84,15 +84,18 @@ type AutoscalerRegistry interface {// AutoscalerScaleSetter applies a scale decision via the existing setLimits// machinery (worker gRPC SetSandboxLimits). Decoupled so we can test without-// a real worker.+// a real worker. The from→to pair is passed so implementations can emit+// audit events (admin dashboard, structured logs) showing the transition,+// not just the new size.type AutoscalerScaleSetter interface {- SetSandboxMemoryMB(ctx context.Context, sandboxID string, memoryMB int) error+ SetSandboxMemoryMB(ctx context.Context, sandboxID string, fromMB, toMB int) error}type Autoscaler struct {store AutoscalerSandboxStoreregistry AutoscalerRegistrysetter AutoscalerScaleSetter+ isLeader func() bool // optional: skip ticks when not leader (HA setup)mu sync.Mutexstats map[string]*sandboxStats // sandboxID → samples@@ -104,11 +107,17 @@ type sandboxStats struct {}// NewAutoscaler wires up the loop. Caller invokes Start to begin ticking.-func NewAutoscaler(store AutoscalerSandboxStore, registry AutoscalerRegistry, setter AutoscalerScaleSetter) *Autoscaler {+//+// isLeader (optional) is consulted at the top of each tick. When non-nil and+// returning false, the tick is skipped entirely — used in HA setups where+// only one CP should drive scaling decisions. Passing nil makes the loop+// run unconditionally (single-CP / dev / no-leader-election deployments).+func NewAutoscaler(store AutoscalerSandboxStore, registry AutoscalerRegistry, setter AutoscalerScaleSetter, isLeader func() bool) *Autoscaler {return &Autoscaler{store: store,registry: registry,setter: setter,+ isLeader: isLeader,stats: make(map[string]*sandboxStats),stop: make(chan struct{}),}@@ -138,6 +147,9 @@ func (a *Autoscaler) run(ctx context.Context) {}func (a *Autoscaler) tick(ctx context.Context) {+ if a.isLeader != nil && !a.isLeader() {+ return+ }sandboxes, err := a.store.ListAutoscaleEnabled(ctx)if err != nil {log.Printf("autoscaler: ListAutoscaleEnabled failed: %v", err)@@ -176,7 +188,15 @@ func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {log.Printf("autoscaler: %s no MemLimit in heartbeat; skipping", sb.SandboxID)return}- sb.CurrentMB = int(stats.MemLimit / (1024 * 1024))+ // MemLimit comes from the guest's /proc/meminfo MemTotal — which is+ // ~10% smaller than the QEMU -m due to kernel reservations (e.g. a+ // sandbox configured at 1024 MB shows 896 MB). Round UP to the nearest+ // tier so the autoscaler reasons about the *configured* size, not the+ // kernel-visible size. Without this, a 1 GB sandbox with mem pressure+ // loops forever scaling 896→1024 (which is a no-op on virtio-mem+ // because base=1024 already), never reaching the next real tier.+ rawMB := int(stats.MemLimit / (1024 * 1024))+ sb.CurrentMB = roundUpToTier(rawMB)memPct := stats.MemPct// 2. Record sample.@@ -203,12 +223,14 @@ func (a *Autoscaler) evaluateOne(ctx context.Context, sb db.AutoscaleSandbox) {// 5. Apply. Cooldown is already burned (intentional — gRPC failures// shouldn't retry-storm at every tick; wait the cooldown out).- if err := a.setter.SetSandboxMemoryMB(ctx, sb.SandboxID, target); err != nil {+ if err := a.setter.SetSandboxMemoryMB(ctx, sb.SandboxID, sb.CurrentMB, target); err != nil {log.Printf("autoscaler: %s scale %d→%d MB failed: %v", sb.SandboxID, sb.CurrentMB, target, err)return}- 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)+ // Structured audit log line — `autoscaler: scaled` is greppable. Setter+ // also emits this to the admin event bus so the dashboard surfaces it.+ log.Printf("autoscaler: scaled sandbox=%s from=%dMB to=%dMB mem_pct=%.1f min=%d max=%d worker=%s",+ sb.SandboxID, sb.CurrentMB, target, memPct, sb.MinMB, sb.MaxMB, sb.WorkerID)}func (a *Autoscaler) recordSample(sandboxID string, memPct float64) {@@ -317,6 +339,23 @@ func prevTier(currentMB, minMB int) int {return currentMB}+// roundUpToTier returns the smallest tier ≥ mb. If mb is already at or above+// the highest tier, returns the highest. If mb ≤ 0, returns the lowest tier.+// Used to reconcile guest-reported MemTotal (which is ~10% below QEMU -m)+// to the operator-configured tier.+func roundUpToTier(mb int) int {+ tiers := tierMBs()+ if len(tiers) == 0 {+ return mb+ }+ for _, t := range tiers {+ if mb <= t {+ return t+ }+ }+ return tiers[len(tiers)-1]+}+// 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 {diff --git a/internal/db/sandbox_autoscale.go b/internal/db/sandbox_autoscale.goindex 53011140..68feb619 100644--- a/internal/db/sandbox_autoscale.go+++ b/internal/db/sandbox_autoscale.go@@ -62,12 +62,19 @@ func (s *Store) GetSandboxAutoscale(ctx context.Context, sandboxID string) (enabreturn enabled, minMB, maxMB, nil}-// ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true.-// The partial index added in migration 035 keeps this scan cheap regardless-// of total session count.+// ListAutoscaleEnabled returns running sandboxes with autoscale_enabled=true+// that are NOT currently being migrated. We exclude rows with a non-empty+// migrating_to_worker because:+// - the worker_id column is the source worker but the gRPC routes there+// would land on a sandbox that's mid-handoff+// - the heartbeat stats are racey across the source/dest workers during+// the cutover, so a scaling decision based on either is unreliable+// - autoscaling resumes naturally on the next tick after the migration+// completes (CompleteMigration clears migrating_to_worker)//-// CurrentMB is left at zero — populated by the caller from live heartbeat-// stats. See the AutoscaleSandbox doc comment.+// The partial index added in migration 035 keeps this scan cheap regardless+// of total session count. CurrentMB is left at zero — populated by the+// caller from live heartbeat stats. See the AutoscaleSandbox doc comment.func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, error) {rows, err := s.pool.Query(ctx, `SELECT sandbox_id, worker_id, org_id::text,@@ -75,7 +82,9 @@ func (s *Store) ListAutoscaleEnabled(ctx context.Context) ([]AutoscaleSandbox, eCOALESCE(autoscale_max_mb, 0) AS max_mb,COALESCE(autoscale_last_event_at, '1970-01-01'::timestamptz) AS last_event_atFROM sandbox_sessions- WHERE autoscale_enabled = TRUE AND status = 'running'+ WHERE autoscale_enabled = TRUE+ AND status = 'running'+ AND migrating_to_worker = ''`)if err != nil {return nil, fmt.Errorf("list autoscale-enabled: %w", err)diff --git a/internal/qemu/reset.go b/internal/qemu/reset.goindex 0e0e4eab..299a2a62 100644--- a/internal/qemu/reset.go+++ b/internal/qemu/reset.go@@ -172,10 +172,20 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (hostif cpus <= 0 {cpus = m.cfg.DefaultCPUs}- memMB := vm.MemoryMB- if memMB <= 0 {- memMB = m.cfg.DefaultMemoryMB+ // Boot the new QEMU at the ORIGINAL base memory and re-plug virtio-mem+ // to the prior amount after the agent comes up. Booting at vm.MemoryMB+ // (current total) bakes the scaled-up size into the QEMU `-m` flag,+ // which means subsequent shrinks below that size only adjust the cgroup+ // limit (additional clamps to 0) — the host can never give back the+ // memory until the sandbox is destroyed. Booting at base + re-plug+ // preserves the user-visible size while keeping virtio-mem unplug+ // available going forward.+ bootMemMB := vm.baseMemoryMB+ if bootMemMB <= 0 {+ bootMemMB = m.cfg.DefaultMemoryMB}+ prevPlugMB := vm.virtioMemRequestedMB+ memMB := bootMemMBguestPort := vm.GuestPortif guestPort == 0 {guestPort = meta.GuestPort@@ -260,8 +270,29 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (hostlog.Printf("qemu: PowerCycleSandbox %s: clock sync failed: %v", sandboxID, err)}+ // Step 5b: Re-plug virtio-mem to match the size the sandbox had before+ // the cycle. The fresh QEMU boots at base; we now bring it back to the+ // pre-cycle total so the user doesn't perceive a memory shrink. If the+ // re-plug fails, log loudly and continue at base — the sandbox is+ // alive and the user can re-scale via the API.+ finalMemMB := bootMemMB+ finalPlugMB := 0+ if prevPlugMB > 0 {+ if err := qmpClient.SetVirtioMemSize(prevPlugMB); err != nil {+ log.Printf("qemu: PowerCycleSandbox %s: virtio-mem re-plug %dMB failed: %v — sandbox alive at %dMB",+ sandboxID, prevPlugMB, err, bootMemMB)+ } else {+ finalPlugMB = prevPlugMB+ finalMemMB = bootMemMB + prevPlugMB+ log.Printf("qemu: PowerCycleSandbox %s: virtio-mem re-plugged %dMB (total %dMB)",+ sandboxID, prevPlugMB, finalMemMB)+ }+ }+// Step 6: Swap fresh state into the existing VMInstance so callers- // holding pointers to it continue to see a live sandbox.+ // holding pointers to it continue to see a live sandbox. baseMemoryMB+ // stays at the original boot mem (preserves virtio-mem flexibility);+ // MemoryMB and virtioMemRequestedMB reflect the post-replug total.vm.cmd = cmdvm.qmp = qmpClientvm.agent = agentClient@@ -272,6 +303,9 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (hostvm.guestMAC = guestMACvm.bootArgs = bootArgsvm.pid = cmd.Process.Pid+ vm.MemoryMB = finalMemMB+ vm.baseMemoryMB = bootMemMB+ vm.virtioMemRequestedMB = finalPlugMBlog.Printf("qemu: PowerCycleSandbox %s: complete (%dms, port=%d, tap=%s)",sandboxID, time.Since(t0).Milliseconds(), freshPort, netCfg.TAPName)