Skip to content

An open-source, faster Devin alternative

TypeScript

add exponential backoff and smarter cleanup methods

Brian Reardonbf7ac32b9ab0
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index 228164d7..41e00447 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -8,6 +8,7 @@ import (
"log"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
@@ -187,28 +188,12 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machi
}, nil)
if err != nil {
log.Printf("azure: VM %s BeginCreateOrUpdate error detail: %+v", vmName, err)
- // Clean up orphaned NIC
- go func() {
- cleanCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if delPoller, delErr := p.nicClient.BeginDelete(cleanCtx, p.cfg.ResourceGroup, nicName, nil); delErr == nil {
- delPoller.PollUntilDone(cleanCtx, nil)
- log.Printf("azure: cleaned up orphaned NIC %s", nicName)
- }
- }()
+ go p.cleanupNIC(nicName, "create failed")
return nil, fmt.Errorf("azure: create VM %s failed: %w", vmName, err)
}
vmResp, err := vmPoller.PollUntilDone(ctx, nil)
if err != nil {
- // Clean up orphaned NIC on poll failure too
- go func() {
- cleanCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if delPoller, delErr := p.nicClient.BeginDelete(cleanCtx, p.cfg.ResourceGroup, nicName, nil); delErr == nil {
- delPoller.PollUntilDone(cleanCtx, nil)
- log.Printf("azure: cleaned up orphaned NIC %s after poll failure", nicName)
- }
- }()
+ go p.cleanupNIC(nicName, "poll failed")
return nil, fmt.Errorf("azure: VM %s poll failed: %w", vmName, err)
}
log.Printf("azure: VM %s created successfully", vmName)
@@ -343,41 +328,82 @@ func (p *AzurePool) DrainMachine(ctx context.Context, machineID string) error {
return err
}
+// cleanupNIC deletes a single orphaned NIC in the background with a generous timeout.
+func (p *AzurePool) cleanupNIC(nicName, reason string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ poller, err := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, nicName, nil)
+ if err != nil {
+ log.Printf("azure: failed to start NIC cleanup for %s (%s): %v", nicName, reason, err)
+ return
+ }
+ if _, err := poller.PollUntilDone(ctx, nil); err != nil {
+ log.Printf("azure: NIC cleanup poll failed for %s (%s): %v", nicName, reason, err)
+ return
+ }
+ log.Printf("azure: cleaned up orphaned NIC %s (%s)", nicName, reason)
+}
+
// CleanupOrphanedResources finds and deletes NICs not attached to any VM.
-// These accumulate when VM creation fails partway through.
-func (p *AzurePool) CleanupOrphanedResources(ctx context.Context) (int, error) {
- cleaned := 0
+// Uses its own long-lived context and deletes in parallel to handle large backlogs.
+func (p *AzurePool) CleanupOrphanedResources(_ context.Context) (int, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ defer cancel()
+
+ var orphaned []string
pager := p.nicClient.NewListPager(p.cfg.ResourceGroup, nil)
for pager.More() {
page, err := pager.NextPage(ctx)
if err != nil {
- return cleaned, fmt.Errorf("azure: list NICs: %w", err)
+ return 0, fmt.Errorf("azure: list NICs: %w", err)
}
for _, nic := range page.Value {
if nic.Properties == nil || nic.Properties.VirtualMachine != nil {
- continue // attached to a VM, skip
+ continue
}
name := ""
if nic.Name != nil {
name = *nic.Name
}
if !strings.HasPrefix(name, "osb-worker-") {
- continue // not ours
+ continue
}
- log.Printf("azure: cleaning orphaned NIC %s", name)
- poller, err := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, name, nil)
+ orphaned = append(orphaned, name)
+ }
+ }
+
+ if len(orphaned) == 0 {
+ return 0, nil
+ }
+
+ log.Printf("azure: found %d orphaned NICs, cleaning up in parallel", len(orphaned))
+
+ var (
+ cleaned int64
+ wg sync.WaitGroup
+ sem = make(chan struct{}, 10)
+ )
+ for _, name := range orphaned {
+ wg.Add(1)
+ sem <- struct{}{}
+ go func(nicName string) {
+ defer wg.Done()
+ defer func() { <-sem }()
+ poller, err := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, nicName, nil)
if err != nil {
- log.Printf("azure: failed to delete orphaned NIC %s: %v", name, err)
- continue
+ log.Printf("azure: failed to delete orphaned NIC %s: %v", nicName, err)
+ return
}
if _, err := poller.PollUntilDone(ctx, nil); err != nil {
- log.Printf("azure: orphaned NIC %s delete poll failed: %v", name, err)
- } else {
- cleaned++
+ log.Printf("azure: orphaned NIC %s delete poll failed: %v", nicName, err)
+ return
}
- }
+ atomic.AddInt64(&cleaned, 1)
+ }(name)
}
- return cleaned, nil
+ wg.Wait()
+
+ return int(cleaned), nil
}
// RefreshAMI checks Azure Key Vault for a new worker image ID and version.
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 78e7d9e1..a80514b9 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -37,6 +37,10 @@ const (
evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
drainTimeout = 15 * time.Minute // max time to drain a worker via live migration
+
+ creationFailureThreshold = 3 // consecutive failures before exponential backoff
+ creationBackoffMin = 1 * time.Minute // initial backoff after threshold hit
+ creationBackoffMax = 10 * time.Minute // cap on exponential backoff
)
// ScalerRegistry is the interface the Scaler uses to query worker state.
@@ -310,9 +314,14 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
}
// Ensure minimum workers are running (pre-provisioned capacity).
- // Ignores cooldowns — if we're below minimum, launch immediately.
+ // Ignores cooldowns but respects creation failure backoff.
totalWorkers := len(workers) + len(s.state.GetPendingLaunches(region))
if totalWorkers < s.minWorkers {
+ if until, ok := s.state.GetCreationBackoffUntil(region); ok {
+ log.Printf("scaler: region %s below minimum workers (%d/%d) but creation backoff active until %s",
+ region, totalWorkers, s.minWorkers, until.Format(time.RFC3339))
+ return
+ }
deficit := s.minWorkers - totalWorkers
log.Printf("scaler: region %s below minimum workers (%d/%d), launching %d",
region, totalWorkers, s.minWorkers, deficit)
@@ -388,11 +397,24 @@ func (s *Scaler) evaluateRegion(ctx context.Context, region string) {
}
func (s *Scaler) scaleUp(_ context.Context, region string) {
+ // Check creation failure backoff
+ if until, ok := s.state.GetCreationBackoffUntil(region); ok {
+ log.Printf("scaler: region %s creation backoff active until %s, skipping scale-up",
+ region, until.Format(time.RFC3339))
+ return
+ }
+
// Record scale-up intent immediately (prevents duplicate launches)
s.state.SetLastScaleUp(region, time.Now(), s.cooldown)
+ // Register a placeholder pending launch so other code paths see it in-flight.
+ placeholderID := fmt.Sprintf("osb-worker-pending-%d", time.Now().UnixNano())
+ s.state.AddPendingLaunch(region, pendingLaunch{
+ MachineID: placeholderID,
+ LaunchedAt: time.Now(),
+ })
+
// Run VM creation in background — Azure/EC2 can take 2-5 minutes.
- // Uses a 5-minute timeout independent of the evaluation cycle.
go func() {
createCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
@@ -405,13 +427,28 @@ func (s *Scaler) scaleUp(_ context.Context, region string) {
machine, err := s.pool.CreateMachine(createCtx, opts)
if err != nil {
log.Printf("scaler: failed to create machine in %s: %v", region, err)
+ s.state.RemovePendingLaunch(region, placeholderID)
+
+ failures := s.state.IncrCreationFailures(region)
+ if failures >= creationFailureThreshold {
+ backoff := creationBackoffMin * time.Duration(1<<(failures-creationFailureThreshold))
+ if backoff > creationBackoffMax {
+ backoff = creationBackoffMax
+ }
+ s.state.SetCreationBackoffUntil(region, time.Now().Add(backoff))
+ log.Printf("scaler: region %s hit %d consecutive creation failures, backing off %s",
+ region, failures, backoff)
+ }
return
}
+ // Swap placeholder for real machine ID
+ s.state.RemovePendingLaunch(region, placeholderID)
s.state.AddPendingLaunch(region, pendingLaunch{
MachineID: machine.ID,
LaunchedAt: time.Now(),
})
+ s.state.ResetCreationFailures(region)
log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)
}()
}
diff --git a/internal/controlplane/scaler_state.go b/internal/controlplane/scaler_state.go
index f4e20e29..3ecc73d4 100644
--- a/internal/controlplane/scaler_state.go
+++ b/internal/controlplane/scaler_state.go
@@ -46,6 +46,12 @@ type ScalerStateStore interface {
// Rate-of-change tracking
GetLastSandboxCount(region string) (int, bool)
SetLastSandboxCount(region string, count int)
+
+ // Creation failure backoff
+ IncrCreationFailures(region string) int
+ ResetCreationFailures(region string)
+ GetCreationBackoffUntil(region string) (time.Time, bool)
+ SetCreationBackoffUntil(region string, until time.Time)
}
// RedisScalerState implements ScalerStateStore backed by Redis.
@@ -280,18 +286,60 @@ func (r *RedisScalerState) SetLastSandboxCount(region string, count int) {
r.rdb.Set(ctx, "scaler:sandboxcount:"+region, fmt.Sprintf("%d", count), 2*time.Minute)
}
+// --- Creation failure backoff (Redis) ---
+
+func (r *RedisScalerState) IncrCreationFailures(region string) int {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ n, err := r.rdb.Incr(ctx, "scaler:createfail:"+region).Result()
+ if err != nil {
+ return 0
+ }
+ r.rdb.Expire(ctx, "scaler:createfail:"+region, 30*time.Minute)
+ return int(n)
+}
+
+func (r *RedisScalerState) ResetCreationFailures(region string) {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ r.rdb.Del(ctx, "scaler:createfail:"+region)
+ r.rdb.Del(ctx, "scaler:createbackoff:"+region)
+}
+
+func (r *RedisScalerState) GetCreationBackoffUntil(region string) (time.Time, bool) {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ val, err := r.rdb.Get(ctx, "scaler:createbackoff:"+region).Result()
+ if err != nil {
+ return time.Time{}, false
+ }
+ t, err := time.Parse(time.RFC3339, val)
+ if err != nil || time.Now().After(t) {
+ return time.Time{}, false
+ }
+ return t, true
+}
+
+func (r *RedisScalerState) SetCreationBackoffUntil(region string, until time.Time) {
+ ctx, cancel := r.ctx()
+ defer cancel()
+ r.rdb.Set(ctx, "scaler:createbackoff:"+region, until.Format(time.RFC3339), time.Until(until))
+}
+
// --- In-memory fallback (for dev/combined mode) ---
// InMemoryScalerState provides the same interface backed by Go maps (current behavior).
type InMemoryScalerState struct {
- mu sync.Mutex
- lastScaleUp map[string]time.Time
- pending map[string][]pendingLaunch
- draining map[string]*drainState
- lastEvacuation map[string]time.Time
- migrating sync.Map
- inFlight map[string]int
- sandboxCount map[string]int
+ mu sync.Mutex
+ lastScaleUp map[string]time.Time
+ pending map[string][]pendingLaunch
+ draining map[string]*drainState
+ lastEvacuation map[string]time.Time
+ migrating sync.Map
+ inFlight map[string]int
+ sandboxCount map[string]int
+ createFailures map[string]int
+ createBackoff map[string]time.Time
}
// NewInMemoryScalerState creates an in-memory state store.
@@ -303,6 +351,8 @@ func NewInMemoryScalerState() *InMemoryScalerState {
lastEvacuation: make(map[string]time.Time),
inFlight: make(map[string]int),
sandboxCount: make(map[string]int),
+ createFailures: make(map[string]int),
+ createBackoff: make(map[string]time.Time),
}
}
@@ -422,6 +472,38 @@ func (m *InMemoryScalerState) SetLastSandboxCount(region string, count int) {
m.sandboxCount[region] = count
}
+// --- Creation failure backoff (in-memory) ---
+
+func (m *InMemoryScalerState) IncrCreationFailures(region string) int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.createFailures[region]++
+ return m.createFailures[region]
+}
+
+func (m *InMemoryScalerState) ResetCreationFailures(region string) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.createFailures, region)
+ delete(m.createBackoff, region)
+}
+
+func (m *InMemoryScalerState) GetCreationBackoffUntil(region string) (time.Time, bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ t, ok := m.createBackoff[region]
+ if !ok || time.Now().After(t) {
+ return time.Time{}, false
+ }
+ return t, true
+}
+
+func (m *InMemoryScalerState) SetCreationBackoffUntil(region string, until time.Time) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.createBackoff[region] = until
+}
+
// Ensure both implementations satisfy the interface.
var _ ScalerStateStore = (*RedisScalerState)(nil)
var _ ScalerStateStore = (*InMemoryScalerState)(nil)