An open-source, faster Devin alternative
TypeScript
handle edges discovered in testing
Brian Reardondd0984caf16b
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex a922383b..602cad0d 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1126,11 +1126,18 @@ func (s *Server) scaleSandbox(c echo.Context) error {// 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.+ // We capture whether it WAS enabled so the response can flag the side-+ // effect to SDK callers (otherwise autoscale silently flips off).+ var autoscaleWasEnabled boolif s.store != nil {+ if enabled, _, _, err := s.store.GetSandboxAutoscale(c.Request().Context(), id); err == nil {+ autoscaleWasEnabled = enabled+ }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)}}+ c.Set("autoscaleWasEnabled", autoscaleWasEnabled)if s.workerRegistry != nil {return s.setLimitsRemote(c, id, 0, maxMemoryBytes, cpuMaxUsec, cpuPeriodUsec)@@ -1274,6 +1281,18 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32log.Printf("scale-migrate %s: migrated to %s and scaled to %dMB", sandboxID, workerID, requestedMemMB)} else if err != nil {+ // OOM-floor refusal: returned by the worker when the requested limit+ // is below the guest's current working set. This is a "user can fix+ // it" condition (free memory in the guest, then retry) — surface it+ // as 409 Conflict with a structured code so SDK consumers can branch+ // on it without string-matching the wrapped gRPC error.+ if strings.Contains(err.Error(), "oom_floor:") {+ return c.JSON(http.StatusConflict, map[string]any{+ "error": "memory limit below guest working set — would OOM-kill processes",+ "code": "oom_floor",+ "details": err.Error(),+ })+ }return c.JSON(http.StatusInternalServerError, map[string]string{"error": "set limits failed: " + err.Error(),})@@ -1287,14 +1306,21 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32s.emitEvent("scale", sandboxID, workerID, fmt.Sprintf("scaled to %dMB (migrated=%v)", requestedMemMB, migrated))}- return c.JSON(http.StatusOK, map[string]interface{}{+ resp := map[string]any{"sandboxID": sandboxID,"workerID": workerID,"memoryMB": requestedMemMB,"cpuPercent": int(cpuMaxUsec / 1000),"migrated": migrated,"ok": true,- })+ }+ // Surface the autoscale-was-disabled side-effect when the request came+ // from /scale (scaleSandbox stashes this on the echo context). Quiet+ // when called from /limits (no autoscale toggle there).+ if v := c.Get("autoscaleWasEnabled"); v != nil {+ resp["autoscaleDisabled"] = v.(bool)+ }+ return c.JSON(http.StatusOK, resp)}// findScaleMigrationTargets finds workers with enough memory headroom for a scaled-up sandbox.diff --git a/internal/db/store.go b/internal/db/store.goindex 238f640f..013b1a36 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -125,6 +125,7 @@ func (s *Store) Migrate(ctx context.Context) error {{32, "migrations/029_orgs_max_memory_gb.up.sql"},{33, "migrations/030_billable_events.up.sql"},{34, "migrations/031_orgs_billing_mode.up.sql"},+ {35, "migrations/035_sandbox_autoscale.up.sql"},}for _, m := range migrations {diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex eb0eca62..ee671ed3 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1893,6 +1893,45 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPireturn err}+ // Shrink-safety: refuse any request whose total memory falls below the+ // guest's working set + 5% headroom. This guards against:+ // (a) virtio-mem unplug below resident anon memory → guest OOM-killer,+ // (b) cgroup memory.max set below current RSS → guest OOM-killer,+ // in both directions and across all entry points (manual /scale,+ // per-sandbox autoscaler, post-wake, post-fork). Lifted above the+ // virtio-mem branch so it fires regardless of the worker's own+ // virtioMemRequestedMB bookkeeping (which fork doesn't track and wake+ // only started tracking recently).+ //+ // MemUsage = MemTotal - MemAvailable from /proc/meminfo inside the+ // guest — a conservative upper bound on resident anon (it includes some+ // active page cache, which is fine; we'd rather refuse a few legit+ // shrinks than silently OOM the guest).+ //+ // Fail-closed on stats errors during a shrink — better to bounce back+ // to the caller (who can retry) than apply a limit we can't validate.+ if maxMemoryBytes > 0 && vm.agent != nil {+ newTotalMB := int(maxMemoryBytes / (1024 * 1024))+ shrinking := newTotalMB < vm.MemoryMB+ statsCtx, cancel := context.WithTimeout(ctx, 3*time.Second)+ stats, statsErr := vm.agent.Stats(statsCtx)+ cancel()+ switch {+ case statsErr != nil && shrinking:+ log.Printf("qemu: %s shrink to %dMB refused: stats fetch failed: %v", sandboxID, newTotalMB, statsErr)+ return fmt.Errorf("oom_floor: cannot verify guest working set: %w", statsErr)+ case stats != nil && stats.MemUsage > 0:+ usedMB := int(stats.MemUsage / (1024 * 1024))+ floorMB := usedMB * 105 / 100+ if newTotalMB < floorMB {+ log.Printf("qemu: %s: refusing memory limit %dMB — working set %dMB requires ≥%dMB",+ sandboxID, newTotalMB, usedMB, floorMB)+ return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",+ newTotalMB, usedMB, floorMB)+ }+ }+ }+// virtio-mem: adjust pluggable memory to match requested totalif maxMemoryBytes > 0 && vm.qmp != nil {totalDesiredMB := int(maxMemoryBytes) / (1024 * 1024)@@ -1921,26 +1960,6 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi}if additionalMB != vm.virtioMemRequestedMB {- // Shrink-safety: if we're reducing memory, ensure the new total- // won't be below the guest's working set. virtio-mem unplug below- // resident anon memory will OOM-kill processes inside the guest.- // We use MemUsage (= MemTotal - MemAvailable from /proc/meminfo- // inside the guest) as a conservative upper bound on anon — it- // includes some active page cache but is always ≥ resident anon.- // 5% headroom covers transient growth during the unplug window.- if additionalMB < vm.virtioMemRequestedMB && vm.agent != nil {- newTotalMB := vm.baseMemoryMB + additionalMB- if stats, statsErr := vm.agent.Stats(ctx); statsErr == nil && stats != nil && stats.MemUsage > 0 {- usedMB := int(stats.MemUsage / (1024 * 1024))- floorMB := usedMB * 105 / 100- if newTotalMB < floorMB {- log.Printf("qemu: virtio-mem %s: refusing shrink to %dMB — working set %dMB requires ≥%dMB",- sandboxID, newTotalMB, usedMB, floorMB)- return fmt.Errorf("oom_floor: target %dMB below guest working set (%dMB used, %dMB floor)",- newTotalMB, usedMB, floorMB)- }- }- }if err := vm.qmp.SetVirtioMemSize(additionalMB); err != nil {log.Printf("qemu: virtio-mem %s: set %dMB failed: %v — returning insufficient capacity error", sandboxID, additionalMB, err)return fmt.Errorf("insufficient_capacity: cannot hotplug %dMB on this worker: %w", additionalMB, err)diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 803b232e..9e7b140f 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -524,6 +524,14 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cbootArgs: bootArgs,goldenVersion: m.goldenVersion, // set on wake — VM runs on the current worker's base}+ // Recompute virtio-mem amount from the meta. Without this the field+ // stays at zero on wake, which would (a) make grow deltas under-charge+ // the host capacity check and (b) make the shrink-OOM-floor in+ // SetResourceLimits silently no-op since `additional == requested == 0`+ // is treated as "no change" and skips the check entirely.+ if meta.MemoryMB > baseMem {+ vm.virtioMemRequestedMB = meta.MemoryMB - baseMem+ }vm.agent = agentClient// Agent binary updates happen via qemu-img rebase of the rootfs, not via