An open-source, faster Devin alternative
TypeScript
fix migration worst case
Brian Reardondcee08385b5b
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 8a7a380b..d0172c2b 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -813,15 +813,42 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Worgo s.drainWorker(target.ID, target.MachineID, region)}-// rollingReplace drains workers running an old version one at a time,-// allowing the scaler to replace them with new-AMI workers.+// rollingReplace executes a quota-aware rolling replacement of stale workers+// (workers whose WorkerVersion != targetWorkerVersion).+//+// The dance under quota pressure (e.g., eastus2 prod with 1-2 spare worker+// slots in the Dadsv7 family quota):+//+// loop {+// pick lightest stale worker S+// drain S (sandboxes migrate onto current-version workers)+// once S is empty: terminate S — frees one quota slot+// if more stale workers remain: scaleUp (consume the freed slot)+// next tick: repeat+// }+//+// At any moment in the dance the cluster holds at most N+1 workers (N stale+// before the dance starts + 1 freshly-launched). The number of new-version+// workers grows by one each cycle: cycle 1 lands all of S1 onto NV1; cycle 2+// lands S2 across {NV1, NV2}; cycle 3 across {NV1, NV2, NV3}; etc. By the+// time we drain the heaviest stale worker, our target pool is N-1 workers+// wide and per-sandbox findMigrationTarget can spread the load evenly.+//+// Without this dance (the prior implementation): drain ran async per tick,+// terminate happened via the separate idle-scale-down path on a different+// tick, and replacement scaleUp only triggered when current==0. So all+// stale workers' sandboxes piled onto whichever single new-version worker+// existed first, overloading it and triggering the agent-reconnect-timeout+// failure modes that this PR also addresses elsewhere.+//+// Serialized via Redis lock so concurrent ticks across CPs don't double-fire.func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*WorkerInfo) {if s.targetWorkerVersion == "" {return}var stale []*WorkerInfo- var current int+ var current []*WorkerInfofor _, w := range workers {// Skip workers already being drainedif s.state.IsDraining(w.MachineID) {@@ -838,7 +865,7 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*Wcontinue // static worker, not autoscaled}if w.WorkerVersion == s.targetWorkerVersion {- current+++ current = append(current, w)} else {stale = append(stale, w)}@@ -848,23 +875,35 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*Wreturn}- // If no current-version workers exist, try to launch a replacement first.- // If launch fails (e.g., quota), fall back to draining one stale worker- // to free capacity — the min-workers check will launch a replacement next tick.- if current < 1 {+ // Take the rolling-replace lock so concurrent ticks (or the other CP)+ // don't pick a different stale worker and double-drain. Released after+ // the synchronous dance returns.+ if !s.state.TryAcquireReplacingLock() {+ return+ }+ releaseLock := true+ defer func() {+ if releaseLock {+ s.state.ReleaseReplacingLock()+ }+ }()++ // Need at least one current-version worker (or pending one) to migrate+ // onto. If none, scale up first and wait for next tick.+ if len(current) == 0 {pendingCount := len(s.state.GetPendingLaunches(region))if pendingCount > 0 {- log.Printf("scaler: region %s has %d stale workers, waiting for pending replacement to register",- region, len(stale))+ log.Printf("scaler: rolling replace: %d stale workers, waiting for pending replacement to register",+ len(stale))return}- log.Printf("scaler: rolling replace: all %d workers stale — launching replacement with new version",+ log.Printf("scaler: rolling replace: all %d workers stale — launching first replacement",len(stale))s.scaleUp(ctx, region)return}- // Only drain one stale worker at a time (conservative rolling update)+ // Pick lightest stale — see header comment.target := stale[0]for _, w := range stale[1:] {if w.Current < target.Current {@@ -872,8 +911,9 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*W}}- log.Printf("scaler: rolling replace: draining stale worker %s (version=%q, want=%q, sandboxes=%d)",- target.ID, target.WorkerVersion, s.targetWorkerVersion, target.Current)+ moreStaleAfter := len(stale) > 1+ log.Printf("scaler: rolling replace: draining stale worker %s (version=%q, want=%q, sandboxes=%d, %d stale total, %d current)",+ target.ID, target.WorkerVersion, s.targetWorkerVersion, target.Current, len(stale), len(current))s.state.SetDraining(target.MachineID, &drainState{WorkerID: target.ID,@@ -882,7 +922,55 @@ func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*WStartedAt: time.Now(),})- go s.drainWorker(target.ID, target.MachineID, region)+ // Run the dance in a goroutine so we don't block the scaler tick.+ // The lock is held for the duration via releaseLock = false here.+ releaseLock = false+ go func() {+ defer s.state.ReleaseReplacingLock()+ s.replaceOneStale(ctx, region, target, moreStaleAfter)+ }()+}++// replaceOneStale executes one cycle of the rolling-replace dance:+// drain the target stale worker, terminate it (freeing one quota slot),+// then if more stale workers remain, immediately scale up a replacement+// so the next tick has somewhere to drain to.+//+// Synchronous within the goroutine so the next scaler tick observes the+// post-terminate state cleanly. Lock is held by the caller across this+// function via the defer in rollingReplace.+func (s *Scaler) replaceOneStale(ctx context.Context, region string, target *WorkerInfo, moreStaleAfter bool) {+ // 1. Drain — synchronous; returns when the worker is empty or drainTimeout+ // fires. drainWorker handles per-sandbox findMigrationTarget so each+ // sandbox lands on whichever current-version worker has the most room+ // at that exact moment.+ s.drainWorker(target.ID, target.MachineID, region)++ // 2. Terminate the (now-empty) stale worker. Frees the quota slot for the+ // replacement scaleUp below. We do this even on partial drain — the+ // natural-expiry path will catch any stragglers on the source via+ // sandbox timeouts; better to free quota and unblock the dance than+ // keep an old-version worker around.+ if s.pool != nil && target.MachineID != "" {+ termCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ if err := s.pool.DestroyMachine(termCtx, target.MachineID); err != nil {+ log.Printf("scaler: rolling replace: failed to terminate drained worker %s (%s): %v — letting natural expiry take it",+ target.ID, target.MachineID, err)+ } else {+ log.Printf("scaler: rolling replace: terminated drained worker %s (%s)", target.ID, target.MachineID)+ }+ cancel()+ }++ // 3. If more stale workers remain, fire the next replacement now so it's+ // boot-warm by the time the next tick picks the next stale source.+ // Without this, the next tick would either drain another stale onto+ // the same single new-version worker (the "killer" pile-up) or stall+ // waiting for organic scale-up.+ if moreStaleAfter {+ log.Printf("scaler: rolling replace: more stale workers remain, launching next replacement")+ s.scaleUp(ctx, region)+ }}// drainWorker attempts to live-migrate sandboxes off a worker. If migration failsdiff --git a/internal/controlplane/scaler_state.go b/internal/controlplane/scaler_state.goindex 88f1d162..348d4496 100644--- a/internal/controlplane/scaler_state.go+++ b/internal/controlplane/scaler_state.go@@ -44,6 +44,16 @@ type ScalerStateStore interface {TryAcquireEvacuationLock() boolReleaseEvacuationLock()+ // Rolling-replace serialization — only one stale-worker replacement is+ // in flight at a time (see rollingReplace). Without this, two ticks+ // could each pick a different stale worker to drain, both targeting the+ // single new-version worker, piling sandboxes onto it and starving the+ // rest of the cluster of capacity. 30-min TTL — a single replacement+ // (drain + terminate + scaleUp + new-worker boot) is bounded but can+ // take 5-10 minutes.+ TryAcquireReplacingLock() bool+ ReleaseReplacingLock()+// In-flight migration trackingIncrInFlight(workerID string)DecrInFlight(workerID string)@@ -268,6 +278,25 @@ func (r *RedisScalerState) ReleaseEvacuationLock() {r.rdb.Del(ctx, "scaler:evacuating")}+// TryAcquireReplacingLock serializes rollingReplace across CPs. 30-min TTL+// so a CP crash doesn't pin the lock indefinitely — but long enough that a+// real drain+terminate+scaleUp cycle (5-10 min normally) won't expire it.+func (r *RedisScalerState) TryAcquireReplacingLock() bool {+ ctx, cancel := r.ctx()+ defer cancel()+ ok, err := r.rdb.SetArgs(ctx, "scaler:replacing", "1", redis.SetArgs{+ Mode: "NX",+ TTL: 30 * time.Minute,+ }).Result()+ return err == nil && ok == "OK"+}++func (r *RedisScalerState) ReleaseReplacingLock() {+ ctx, cancel := r.ctx()+ defer cancel()+ r.rdb.Del(ctx, "scaler:replacing")+}+// --- In-flight ---func (r *RedisScalerState) IncrInFlight(workerID string) {@@ -474,6 +503,13 @@ func (m *InMemoryScalerState) TryAcquireEvacuationLock() bool {func (m *InMemoryScalerState) ReleaseEvacuationLock() {m.migrating.Delete("__evacuation__")}+func (m *InMemoryScalerState) TryAcquireReplacingLock() bool {+ _, loaded := m.migrating.LoadOrStore("__replacing__", struct{}{})+ return !loaded+}+func (m *InMemoryScalerState) ReleaseReplacingLock() {+ m.migrating.Delete("__replacing__")+}func (m *InMemoryScalerState) IncrInFlight(workerID string) {m.mu.Lock()defer m.mu.Unlock()