Skip to content

An open-source, faster Devin alternative

TypeScript

add mitigations for production bugs to go in this gv/agent upgrade

Brian Reardonfe9ec5da1b6b
diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.go
index a6b2895b..e1fd25a2 100644
--- a/cmd/agent/listen_linux.go
+++ b/cmd/agent/listen_linux.go
@@ -72,6 +72,13 @@ type virtioSerialListener struct {
closed chan struct{}
mu sync.Mutex
active bool // true when a connection is being served
+ // activeConn tracks the conn handed to gRPC so PrepareHibernate can
+ // force-close it before savevm captures state. Without this, the
+ // gRPC server's HTTP/2 parser state survives savevm/loadvm and gets
+ // fed garbage from the next worker's handshake — the post-loadvm
+ // "agent not ready" race that surfaces ~5% under fork stress and
+ // indefinitely on prod-style restore.
+ activeConn *virtioSerialConn
}
func listenVirtioSerial(path string) (net.Listener, error) {
@@ -111,6 +118,11 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {
}
l.mu.Unlock()
+ // Clear any read deadline left over from PrepareHibernate's conn
+ // teardown — without this, poll/Read on this fd would immediately
+ // return ErrDeadlineExceeded forever.
+ _ = l.f.SetReadDeadline(time.Time{})
+
// Drain any stale data from the previous gRPC session.
// After a gRPC connection drops, the serial port may have leftover
// bytes (GOAWAY frames, partial HTTP/2 frames). If we hand these to
@@ -128,17 +140,22 @@ func (l *virtioSerialListener) Accept() (net.Conn, error) {
l.mu.Unlock()
continue
}
- l.active = true
- l.mu.Unlock()
- log.Printf("agent: virtio-serial Accept: port readable, accepting connection")
- return &virtioSerialConn{
+ conn := &virtioSerialConn{
f: l.f,
onClose: func() {
l.mu.Lock()
l.active = false
+ if l.activeConn != nil {
+ l.activeConn = nil
+ }
l.mu.Unlock()
},
- }, nil
+ }
+ l.active = true
+ l.activeConn = conn
+ l.mu.Unlock()
+ log.Printf("agent: virtio-serial Accept: port readable, accepting connection")
+ return conn, nil
}
}
@@ -181,14 +198,41 @@ func waitForReadable(f *os.File, timeout time.Duration) bool {
return fds[0].Revents&(unix.POLLIN|unix.POLLHUP) != 0
}
-// PrepareHibernate resets the active flag so that after migration restore,
-// the Accept loop will poll for a new host-side connection instead of
-// thinking the old connection is still active.
+// PrepareHibernate resets the active flag AND wakes up the gRPC server's
+// blocked Read goroutine via a past read deadline, then clears the deadline
+// before the next Accept cycle.
+//
+// Why this matters: without forcing the gRPC server to release the conn, its
+// HTTP/2 parser state (in-flight frames, keepalive pings) gets captured by
+// savevm. On the next worker's loadvm + reconnect, that captured parser
+// tries to interpret fresh HTTP/2 SETTINGS frames as continuation of the
+// old stream, consumes bytes but fails at semantics, and stays in the bad
+// state past the worker's 30s agent-connect timeout. By setting the read
+// deadline in the past, the blocked Read returns ErrDeadlineExceeded, gRPC
+// treats it as a conn error and drops the stream cleanly. Now savevm
+// captures an idle, drained chardev with no parser in flight.
+//
+// The deadline reset happens at the top of Accept (see resetReadDeadline)
+// so future connections are unaffected.
func (l *virtioSerialListener) PrepareHibernate() {
l.mu.Lock()
+ conn := l.activeConn
+ l.activeConn = nil
l.active = false
l.mu.Unlock()
log.Printf("agent: virtio-serial: prepared for hibernate (active=false)")
+ if conn == nil {
+ return
+ }
+ // Give the PrepareHibernate response time to flush before disrupting
+ // the conn. 50ms is more than enough on a virtio-serial pipe.
+ go func() {
+ time.Sleep(50 * time.Millisecond)
+ // SetReadDeadline in the past wakes up the blocked Read goroutine
+ // inside gRPC's HTTP/2 transport with os.ErrDeadlineExceeded.
+ _ = conn.f.SetReadDeadline(time.Now().Add(-1 * time.Second))
+ log.Printf("agent: virtio-serial: triggered conn teardown (frees gRPC parser state for clean savevm)")
+ }()
}
func (l *virtioSerialListener) Close() error {
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 6b94c893..8a7a380b 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
+ "sort"
"strings"
"sync"
"sync/atomic"
@@ -560,37 +561,86 @@ func (s *Scaler) hibernateBatch(workerID string, count int) {
// --- Pressure Evacuation ---
-// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical thresholds.
+// evacuateHotWorkers live-migrates sandboxes off workers that exceed critical
+// thresholds.
+//
+// Two scheduling rules that matter under quota pressure:
+//
+// 1. **One source at a time.** Earlier versions spawned a goroutine per hot
+// source in parallel, which under quota constraints (e.g. eastus2 prod
+// where the Dadsv7 family is at ~60% of limit) means every source races
+// for the same one or two viable target workers. The first migration
+// wins, the others stall on capacity, and we get the imbalance pattern
+// we saw on prod: 60 sandboxes piled onto a single worker while the
+// others stayed lightly loaded. Serializing means we drain one source
+// completely before starting the next.
+//
+// 2. **Lightest source first.** A 5-sandbox source drains in seconds and
+// the now-empty worker becomes a viable target for subsequent drains.
+// A 60-sandbox source drained first would block all subsequent
+// evacuations behind it. Going lightest-first organically grows our
+// target pool from drained sources, so by the time we reach the
+// heaviest source we have N workers worth of target capacity instead
+// of 1.
+//
+// Per-sandbox target selection (inside evacuateBatch via liveMigrateSandbox)
+// remains in place — it spreads the migrations within a single source's
+// drain across whatever targets exist at the moment.
func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []*WorkerInfo) {
+ // If an evacuation is already in flight, skip this tick — the active
+ // drain will finish and release the lock; the next tick picks up.
+ if !s.state.TryAcquireEvacuationLock() {
+ return
+ }
+ releaseLock := true
+ defer func() {
+ if releaseLock {
+ s.state.ReleaseEvacuationLock()
+ }
+ }()
+
+ // Collect hot, non-draining workers off cooldown.
+ hot := make([]*WorkerInfo, 0)
for _, w := range workers {
if w.CPUPct < evacuationCPUThreshold && w.MemPct < evacuationMemThreshold && w.DiskPct < evacuationDiskThreshold {
continue
}
- // Skip if already being drained for scale-down
if s.state.IsDraining(w.MachineID) {
continue
}
- // Cooldown — don't evacuate the same worker every tick
if last, ok := s.state.GetLastEvacuation(w.ID); ok && time.Since(last) < evacuationCooldown {
continue
}
+ hot = append(hot, w)
+ }
+ if len(hot) == 0 {
+ return
+ }
- // Find target: least-loaded worker that isn't the hot one and isn't draining.
- // Pass 0 for requiredMemMB — evacuateBatch migrates whatever fits; individual
- // over-size sandboxes fail their own prepare and are retried elsewhere.
- target := s.findMigrationTarget(region, w.ID, 0)
- if target == nil {
- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%) but no migration target available",
- w.ID, w.CPUPct, w.MemPct, w.DiskPct)
- continue
- }
+ // Sort lightest first — see rule 2 in the function comment.
+ sort.Slice(hot, func(i, j int) bool {
+ return hot[i].Current < hot[j].Current
+ })
+ src := hot[0]
+
+ // Pre-flight: confirm SOME viable target exists in the region. Pass 0 for
+ // requiredMemMB; per-sandbox memory fit is checked inside liveMigrateSandbox
+ // after PreCopyDrives reports the real RSS.
+ if probe := s.findMigrationTarget(region, src.ID, 0); probe == nil {
+ log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%, current=%d) but no migration target available — letting scale-up handle this",
+ src.ID, src.CPUPct, src.MemPct, src.DiskPct, src.Current)
+ return
+ }
- log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%), evacuating up to %d sandboxes to %s",
- w.ID, w.CPUPct, w.MemPct, w.DiskPct, evacuationBatchSize, target.ID)
+ log.Printf("scaler: worker %s selected for evacuation (lightest of %d hot, current=%d, cpu=%.1f%% mem=%.1f%% disk=%.1f%%) — draining serially",
+ src.ID, len(hot), src.Current, src.CPUPct, src.MemPct, src.DiskPct)
- s.state.SetLastEvacuation(w.ID, time.Now())
- go s.evacuateBatch(w.ID, target.ID, evacuationBatchSize)
- }
+ s.state.SetLastEvacuation(src.ID, time.Now())
+ releaseLock = false // goroutine will release on its own
+ go func() {
+ defer s.state.ReleaseEvacuationLock()
+ s.evacuateBatch(src.ID, evacuationBatchSize)
+ }()
}
// findMigrationTarget returns the best worker to receive migrated sandboxes.
@@ -646,8 +696,18 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string, requiredMem
return best
}
-// evacuateBatch live-migrates up to count sandboxes from sourceWorker to targetWorker.
-func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int) {
+// evacuateBatch live-migrates up to count sandboxes off sourceWorker, picking
+// a fresh target per sandbox.
+//
+// Why per-sandbox target selection: an earlier version pinned all migrations
+// in a batch to one target (chosen up front by evacuateHotWorkers). Result —
+// during the prod event where 60 sandboxes were rehydrating, every batch
+// piled onto whichever worker was least-loaded at batch start, blowing past
+// it while the other targets stayed nearly empty. By passing "" to
+// liveMigrateSandbox (which then calls findMigrationTarget after PreCopyDrives
+// reports actual RSS), each migration sees up-to-date in-flight counts and
+// the load distributes naturally across all viable targets.
+func (s *Scaler) evacuateBatch(sourceWorkerID string, count int) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
@@ -671,15 +731,18 @@ func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int)
if sb.Status != "running" {
continue
}
- if err := s.liveMigrateSandbox(ctx, sb.SandboxId, sourceWorkerID, targetWorkerID); err != nil {
+ // Empty targetWorkerID → liveMigrateSandbox re-picks per call. This is
+ // what produces the load-distribution behavior described in the
+ // function comment.
+ if err := s.liveMigrateSandbox(ctx, sb.SandboxId, sourceWorkerID, ""); err != nil {
log.Printf("scaler: evacuate: migrate %s failed: %v", sb.SandboxId, err)
continue
}
migrated++
}
- log.Printf("scaler: evacuation batch complete for %s: %d/%d migrated to %s",
- sourceWorkerID, migrated, count, targetWorkerID)
+ log.Printf("scaler: evacuation batch complete for %s: %d/%d migrated (per-sandbox target selection)",
+ sourceWorkerID, migrated, count)
}
// --- Smart Scale-Down ---
diff --git a/internal/controlplane/scaler_state.go b/internal/controlplane/scaler_state.go
index 3ecc73d4..88f1d162 100644
--- a/internal/controlplane/scaler_state.go
+++ b/internal/controlplane/scaler_state.go
@@ -38,6 +38,12 @@ type ScalerStateStore interface {
AcquireMigrationLock(sandboxID string) bool
ReleaseMigrationLock(sandboxID string)
+ // Evacuation serialization — only one source worker drains at a time
+ // (see evacuateHotWorkers). Held across goroutine boundaries; TTL'd so
+ // a crashed CP doesn't permanently block evacuations on restart.
+ TryAcquireEvacuationLock() bool
+ ReleaseEvacuationLock()
+
// In-flight migration tracking
IncrInFlight(workerID string)
DecrInFlight(workerID string)
@@ -243,6 +249,25 @@ func (r *RedisScalerState) ReleaseMigrationLock(sandboxID string) {
r.rdb.Del(ctx, "scaler:migrating:"+sandboxID)
}
+// TryAcquireEvacuationLock takes a region-wide (actually global, single-key)
+// lock that serializes evacuateHotWorkers across CPs. 10-min TTL so a CP
+// crash doesn't pin the lock — evacuations can resume on the next tick.
+func (r *RedisScalerState) TryAcquireEvacuationLock() bool {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ ok, err := r.rdb.SetArgs(ctx, "scaler:evacuating", "1", redis.SetArgs{
+ Mode: "NX",
+ TTL: 10 * time.Minute,
+ }).Result()
+ return err == nil && ok == "OK"
+}
+
+func (r *RedisScalerState) ReleaseEvacuationLock() {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ r.rdb.Del(ctx, "scaler:evacuating")
+}
+
// --- In-flight ---
func (r *RedisScalerState) IncrInFlight(workerID string) {
@@ -442,6 +467,13 @@ func (m *InMemoryScalerState) AcquireMigrationLock(sandboxID string) bool {
func (m *InMemoryScalerState) ReleaseMigrationLock(sandboxID string) {
m.migrating.Delete(sandboxID)
}
+func (m *InMemoryScalerState) TryAcquireEvacuationLock() bool {
+ _, loaded := m.migrating.LoadOrStore("__evacuation__", struct{}{})
+ return !loaded
+}
+func (m *InMemoryScalerState) ReleaseEvacuationLock() {
+ m.migrating.Delete("__evacuation__")
+}
func (m *InMemoryScalerState) IncrInFlight(workerID string) {
m.mu.Lock()
defer m.mu.Unlock()
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 8e43c3c8..7b331248 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -3004,13 +3004,15 @@ func (m *Manager) GetAgent(sandboxID string) (*AgentClient, error) {
return vm.agent, nil
}
-// GetWorkspacePath returns the host path to a sandbox's workspace.ext4.
+// GetWorkspacePath returns the host path to a sandbox's workspace qcow2.
+// Used by the autosave loop to gate SyncFS on mtime — no point syncing if
+// the workspace hasn't been touched since the last successful sync.
func (m *Manager) GetWorkspacePath(sandboxID string) (string, error) {
vm, err := m.getVM(sandboxID)
if err != nil {
return "", err
}
- return filepath.Join(vm.sandboxDir, "workspace.ext4"), nil
+ return filepath.Join(vm.sandboxDir, "workspace.qcow2"), nil
}
// SyncFS flushes filesystem buffers inside the VM.
diff --git a/internal/worker/autosave.go b/internal/worker/autosave.go
index 092baf2f..b3f02f92 100644
--- a/internal/worker/autosave.go
+++ b/internal/worker/autosave.go
@@ -3,21 +3,39 @@ package worker
import (
"context"
"log"
+ "os"
"sync"
"time"
"github.com/opensandbox/opensandbox/internal/sandbox"
)
-// SyncFSer is implemented by any VM manager that can flush filesystem buffers.
+// SyncFSer is implemented by any VM manager that can flush filesystem buffers
+// and report the workspace path so we can gate sync on mtime.
type SyncFSer interface {
SyncFS(ctx context.Context, sandboxID string) error
+ GetWorkspacePath(sandboxID string) (string, error)
}
+// maxConsecutiveFailures: after this many failed sync attempts in a row for
+// the same sandbox, we stop trying. Prevents a wedged sandbox (e.g. agent
+// stuck after savevm/loadvm protocol confusion) from emitting an autosave
+// failure log every 5 minutes forever, and stops us churning the broken
+// gRPC channel — which is itself part of the post-loadvm flake surface.
+// Operator can re-enable by reviving the sandbox or restarting the worker.
+const maxConsecutiveFailures = 5
+
// WorkspaceAutosaver periodically flushes filesystem buffers inside each
-// running VM. This ensures workspace.ext4 on the host NVMe is crash-consistent.
-// On hard kill recovery, the worker cold-boots from template + existing
-// workspace.ext4 on disk (processes lost, but user files in /workspace are safe).
+// running VM so workspace.qcow2 on the host NVMe is crash-consistent for
+// cold-boot recovery on worker death.
+//
+// Two correctness/cost gates:
+// - skip a sandbox if its workspace.qcow2 hasn't been modified since the
+// last successful sync (idle sandboxes are common and a sync per tick
+// is wasted work and gRPC roundtrip).
+// - circuit-breaker after N consecutive failures: stop trying for a
+// sandbox where the agent is wedged. Prevents log flood and churn on
+// the broken control channel.
type WorkspaceAutosaver struct {
manager sandbox.Manager
syncer SyncFSer
@@ -25,6 +43,15 @@ type WorkspaceAutosaver struct {
concurrency int
stop chan struct{}
done chan struct{}
+
+ mu sync.Mutex
+ state map[string]*sandboxSyncState // keyed by sandboxID
+}
+
+type sandboxSyncState struct {
+ lastSyncedMtime time.Time // mtime of workspace.qcow2 at last successful sync
+ consecutiveFails int
+ disabled bool // circuit-breaker tripped — skip until restart
}
// NewWorkspaceAutosaver creates a new autosaver.
@@ -40,13 +67,15 @@ func NewWorkspaceAutosaver(
concurrency: 10,
stop: make(chan struct{}),
done: make(chan struct{}),
+ state: map[string]*sandboxSyncState{},
}
}
// Start begins the periodic SyncFS loop.
func (a *WorkspaceAutosaver) Start() {
go a.loop()
- log.Printf("autosave: started (interval=%s, concurrency=%d)", a.interval, a.concurrency)
+ log.Printf("autosave: started (interval=%s, concurrency=%d, fail-threshold=%d)",
+ a.interval, a.concurrency, maxConsecutiveFailures)
}
// Stop signals the loop to exit and waits for it to finish.
@@ -70,6 +99,29 @@ func (a *WorkspaceAutosaver) loop() {
}
}
+func (a *WorkspaceAutosaver) getOrCreateState(sandboxID string) *sandboxSyncState {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ s, ok := a.state[sandboxID]
+ if !ok {
+ s = &sandboxSyncState{}
+ a.state[sandboxID] = s
+ }
+ return s
+}
+
+// pruneState removes per-sandbox state for sandboxes no longer in the active
+// set. Without this the map grows unbounded across the worker's lifetime.
+func (a *WorkspaceAutosaver) pruneState(active map[string]struct{}) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for id := range a.state {
+ if _, ok := active[id]; !ok {
+ delete(a.state, id)
+ }
+ }
+}
+
func (a *WorkspaceAutosaver) syncAll() {
sandboxes, err := a.manager.List(context.Background())
if err != nil {
@@ -77,18 +129,25 @@ func (a *WorkspaceAutosaver) syncAll() {
return
}
if len(sandboxes) == 0 {
+ a.pruneState(map[string]struct{}{})
return
}
+ active := make(map[string]struct{}, len(sandboxes))
+ for _, sb := range sandboxes {
+ active[sb.ID] = struct{}{}
+ }
+ a.pruneState(active)
+
sem := make(chan struct{}, a.concurrency)
var wg sync.WaitGroup
- var successCount, failCount int32
+ var successCount, skipCount, failCount, disabledCount int32
var mu sync.Mutex
for _, sb := range sandboxes {
select {
case <-a.stop:
- break
+ return
default:
}
@@ -98,23 +157,88 @@ func (a *WorkspaceAutosaver) syncAll() {
defer wg.Done()
defer func() { <-sem }()
- syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- if err := a.syncer.SyncFS(syncCtx, sandboxID); err != nil {
- log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)
- mu.Lock()
- failCount++
- mu.Unlock()
- } else {
- mu.Lock()
+ outcome := a.syncOne(sandboxID)
+ mu.Lock()
+ switch outcome {
+ case syncOK:
successCount++
- mu.Unlock()
+ case syncSkipped:
+ skipCount++
+ case syncFailed:
+ failCount++
+ case syncDisabled:
+ disabledCount++
}
+ mu.Unlock()
}(sb.ID)
}
wg.Wait()
- if failCount > 0 {
- log.Printf("autosave: syncfs complete (%d ok, %d failed)", successCount, failCount)
+ if failCount > 0 || disabledCount > 0 {
+ log.Printf("autosave: tick complete (ok=%d skip=%d fail=%d disabled=%d)",
+ successCount, skipCount, failCount, disabledCount)
+ }
+}
+
+type syncOutcome int
+
+const (
+ syncOK syncOutcome = iota
+ syncSkipped // workspace unchanged since last sync
+ syncFailed // sync attempted, returned error
+ syncDisabled // circuit-breaker tripped — skipped without attempting
+)
+
+func (a *WorkspaceAutosaver) syncOne(sandboxID string) syncOutcome {
+ state := a.getOrCreateState(sandboxID)
+
+ a.mu.Lock()
+ if state.disabled {
+ a.mu.Unlock()
+ return syncDisabled
+ }
+ lastMtime := state.lastSyncedMtime
+ a.mu.Unlock()
+
+ // Gate on workspace mtime — skip if nothing changed since last successful sync.
+ wsPath, err := a.syncer.GetWorkspacePath(sandboxID)
+ if err == nil && wsPath != "" {
+ if stat, statErr := os.Stat(wsPath); statErr == nil {
+ if !lastMtime.IsZero() && !stat.ModTime().After(lastMtime) {
+ return syncSkipped
+ }
+ }
+ }
+
+ syncCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := a.syncer.SyncFS(syncCtx, sandboxID); err != nil {
+ a.mu.Lock()
+ state.consecutiveFails++
+ hitThreshold := state.consecutiveFails >= maxConsecutiveFailures
+ if hitThreshold {
+ state.disabled = true
+ }
+ fails := state.consecutiveFails
+ a.mu.Unlock()
+
+ if hitThreshold {
+ log.Printf("autosave: %s disabled after %d consecutive failures (last=%v) — operator must intervene to re-enable",
+ sandboxID, fails, err)
+ } else if fails == 1 {
+ log.Printf("autosave: syncfs failed for %s: %v", sandboxID, err)
+ }
+ return syncFailed
+ }
+
+ // Success — record current mtime to gate next tick.
+ a.mu.Lock()
+ state.consecutiveFails = 0
+ if wsPath != "" {
+ if stat, err := os.Stat(wsPath); err == nil {
+ state.lastSyncedMtime = stat.ModTime()
+ }
}
+ a.mu.Unlock()
+ return syncOK
}