An open-source, faster Devin alternative
TypeScript
fix: CommittedMemoryMB propagation, drain/destroy, scale-down thrashing, orphan NIC cleanup
Brian Reardon1094a349579b
diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.ymlindex e8911493..73a615d5 100644--- a/.github/workflows/deploy-worker.yml+++ b/.github/workflows/deploy-worker.yml@@ -13,6 +13,9 @@ jobs:deploy:name: Build & Deploy Workerruns-on: ubuntu-latest+ permissions:+ id-token: write+ contents: readsteps:- uses: actions/checkout@v4@@ -26,26 +29,40 @@ jobs:- name: Build agent binaryrun: CGO_ENABLED=0 GOOS=linux GOARCH=${{ env.GOARCH }} go build -o bin/osb-agent ./cmd/agent/+ - name: Azure Login+ uses: azure/login@v2+ with:+ client-id: ${{ secrets.AZURE_CLIENT_ID }}+ tenant-id: ${{ secrets.AZURE_TENANT_ID }}+ subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}++ - name: Discover control plane+ run: |+ CP_IP=$(az vm list --resource-group ${{ secrets.AZURE_RESOURCE_GROUP }} --show-details \+ --query "[?contains(name,'controlplane')].publicIps" -o tsv | head -1)+ echo "CP_IP=$CP_IP" >> $GITHUB_ENV+ echo "Discovered control plane: $CP_IP"+- name: Configure SSHrun: |mkdir -p ~/.ssh- echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/deploy.pem+ echo "$SSH_KEY" | base64 -d > ~/.ssh/deploy.pemchmod 600 ~/.ssh/deploy.pem- echo "${{ secrets.WORKER_SSH_KEY }}" > ~/.ssh/worker.pem- chmod 600 ~/.ssh/worker.pem- ssh-keyscan -H ${{ secrets.CP1_IP }} >> ~/.ssh/known_hosts 2>/dev/null+ echo -e "Host *\n StrictHostKeyChecking no\n UserKnownHostsFile /dev/null" >> ~/.ssh/config+ env:+ SSH_KEY: ${{ secrets.SSH_PRIVATE_KEY_B64 }}- name: Stage SSH key on control plane for worker accessrun: |scp -i ~/.ssh/deploy.pem ~/.ssh/deploy.pem \- ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/deploy.pem- ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }} 'chmod 600 /tmp/deploy.pem'+ ${{ env.SSH_USER }}@${{ env.CP_IP }}:/tmp/deploy.pem+ ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ env.CP_IP }} 'chmod 600 /tmp/deploy.pem'- name: Upload binaries and rootfs context to control planerun: |# Upload binaries to control plane as staging areascp -i ~/.ssh/deploy.pem bin/opensandbox-worker bin/osb-agent \- ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/+ ${{ env.SSH_USER }}@${{ env.CP_IP }}:/tmp/# Sync rootfs build contextrsync -az \@@ -58,11 +75,11 @@ jobs:--include='deploy/firecracker/' \--include='scripts/' \--exclude='*' \- ./ ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }}:/tmp/osb-rootfs-ctx/+ ./ ${{ env.SSH_USER }}@${{ env.CP_IP }}:/tmp/osb-rootfs-ctx/- name: Discover workers and deployrun: |- ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ secrets.SERVER_IP }} '+ ssh -i ~/.ssh/deploy.pem ${{ env.SSH_USER }}@${{ env.CP_IP }} 'set -euo pipefailAPI_KEY=$(grep OPENSANDBOX_API_KEY /etc/opensandbox/server.env | cut -d= -f2-)diff --git a/cmd/server/main.go b/cmd/server/main.goindex 76f18a35..d32213d4 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -199,7 +199,8 @@ func main() {"OPENSANDBOX_S3_REGION=%s\n"+"OPENSANDBOX_S3_ENDPOINT=%s\n"+"OPENSANDBOX_S3_ACCESS_KEY_ID=%s\n"+- "OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n",+ "OPENSANDBOX_S3_SECRET_ACCESS_KEY=%s\n"++ "OPENSANDBOX_S3_FORCE_PATH_STYLE=%v\n",cfg.JWTSecret,cfg.Region,cfg.MaxCapacity,@@ -212,6 +213,7 @@ func main() {cfg.S3Endpoint,cfg.S3AccessKeyID,cfg.S3SecretAccessKey,+ cfg.S3ForcePathStyle,)workerEnvB64 := base64.StdEncoding.EncodeToString([]byte(workerEnv))diff --git a/deploy/azure/postgres-backup.sh b/deploy/azure/postgres-backup.shnew file mode 100644index 00000000..3639cdc4--- /dev/null+++ b/deploy/azure/postgres-backup.sh@@ -0,0 +1,37 @@+#!/usr/bin/env bash+# postgres-backup.sh — Daily PostgreSQL backup with rotation+# Install as cron: 0 3 * * * /opt/opensandbox/postgres-backup.sh+set -euo pipefail++BACKUP_DIR="/data/backups"+DB_NAME="opensandbox"+DB_USER="opensandbox"+KEEP_DAYS=7++mkdir -p "$BACKUP_DIR"++TIMESTAMP=$(date +%Y%m%d_%H%M%S)+BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_${TIMESTAMP}.sql.gz"++echo "$(date): Starting backup to $BACKUP_FILE"++# Dump and compress+sudo -u postgres pg_dump "$DB_NAME" | gzip > "$BACKUP_FILE"++SIZE=$(ls -lh "$BACKUP_FILE" | awk '{print $5}')+echo "$(date): Backup complete ($SIZE)"++# Rotate old backups+find "$BACKUP_DIR" -name "${DB_NAME}_*.sql.gz" -mtime +$KEEP_DAYS -delete+REMAINING=$(ls "$BACKUP_DIR"/${DB_NAME}_*.sql.gz 2>/dev/null | wc -l)+echo "$(date): Rotated old backups, $REMAINING remaining"++# Optional: upload to Azure Blob Storage (uncomment when configured)+# STORAGE_ACCOUNT="opensandboxbackups"+# CONTAINER="pg-backups"+# az storage blob upload \+# --account-name "$STORAGE_ACCOUNT" \+# --container-name "$CONTAINER" \+# --file "$BACKUP_FILE" \+# --name "$(basename $BACKUP_FILE)" \+# --auth-mode login 2>/dev/null && echo "Uploaded to Azure Blob" || echo "Blob upload skipped"diff --git a/internal/api/admin_events_test.go b/internal/api/admin_events_test.gonew file mode 100644index 00000000..cea6ecd0--- /dev/null+++ b/internal/api/admin_events_test.go@@ -0,0 +1,206 @@+package api++import (+ "sync"+ "testing"+ "time"+)++func TestPublishAndHistory(t *testing.T) {+ bus := NewAdminEventBus()++ bus.Publish("create", "sb-1", "w-1", "created sandbox")+ bus.Publish("destroy", "sb-2", "w-1", "destroyed sandbox")++ history := bus.History()+ if len(history) != 2 {+ t.Fatalf("expected 2 events in history, got %d", len(history))+ }+ if history[0].Type != "create" {+ t.Errorf("expected first event type 'create', got '%s'", history[0].Type)+ }+ if history[0].Sandbox != "sb-1" {+ t.Errorf("expected first event sandbox 'sb-1', got '%s'", history[0].Sandbox)+ }+ if history[1].Type != "destroy" {+ t.Errorf("expected second event type 'destroy', got '%s'", history[1].Type)+ }+}++func TestPublishEventFields(t *testing.T) {+ bus := NewAdminEventBus()++ bus.Publish("scale", "sb-99", "w-5", "scaled up")++ history := bus.History()+ if len(history) != 1 {+ t.Fatalf("expected 1 event, got %d", len(history))+ }+ evt := history[0]+ if evt.Type != "scale" {+ t.Errorf("expected type 'scale', got '%s'", evt.Type)+ }+ if evt.Sandbox != "sb-99" {+ t.Errorf("expected sandbox 'sb-99', got '%s'", evt.Sandbox)+ }+ if evt.Worker != "w-5" {+ t.Errorf("expected worker 'w-5', got '%s'", evt.Worker)+ }+ if evt.Detail != "scaled up" {+ t.Errorf("expected detail 'scaled up', got '%s'", evt.Detail)+ }+ if evt.Time == "" {+ t.Error("expected non-empty time")+ }+}++func TestSubscribeReceivesEvents(t *testing.T) {+ bus := NewAdminEventBus()++ ch, cleanup := bus.subscribe()+ defer cleanup()++ bus.Publish("create", "sb-1", "w-1", "test")++ select {+ case evt := <-ch:+ if evt.Type != "create" {+ t.Errorf("expected event type 'create', got '%s'", evt.Type)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for event on subscriber channel")+ }+}++func TestSubscribeCleanup(t *testing.T) {+ bus := NewAdminEventBus()++ ch, cleanup := bus.subscribe()++ // Verify client was registered+ bus.mu.RLock()+ clientCount := len(bus.clients)+ bus.mu.RUnlock()+ if clientCount != 1 {+ t.Fatalf("expected 1 client, got %d", clientCount)+ }++ cleanup()++ // Verify client was removed+ bus.mu.RLock()+ clientCount = len(bus.clients)+ bus.mu.RUnlock()+ if clientCount != 0 {+ t.Fatalf("expected 0 clients after cleanup, got %d", clientCount)+ }++ // Channel should be closed+ _, ok := <-ch+ if ok {+ t.Fatal("expected channel to be closed after cleanup")+ }+}++func TestHistoryBufferCap(t *testing.T) {+ bus := NewAdminEventBus()++ // Publish more than the 2000-event cap+ for i := 0; i < 2050; i++ {+ bus.Publish("create", "sb", "w", "event")+ }++ history := bus.History()+ if len(history) != 2000 {+ t.Fatalf("expected history capped at 2000, got %d", len(history))+ }+}++func TestHistoryReturnsCopy(t *testing.T) {+ bus := NewAdminEventBus()++ bus.Publish("create", "sb-1", "w-1", "first")++ history1 := bus.History()+ history1[0].Type = "modified"++ history2 := bus.History()+ if history2[0].Type != "create" {+ t.Error("History() should return a copy; modifying the result should not affect internal state")+ }+}++func TestEmptyHistory(t *testing.T) {+ bus := NewAdminEventBus()++ history := bus.History()+ if len(history) != 0 {+ t.Fatalf("expected empty history, got %d events", len(history))+ }+}++func TestMultipleSubscribers(t *testing.T) {+ bus := NewAdminEventBus()++ ch1, cleanup1 := bus.subscribe()+ defer cleanup1()+ ch2, cleanup2 := bus.subscribe()+ defer cleanup2()++ bus.Publish("error", "sb-1", "w-1", "something broke")++ for i, ch := range []chan AdminEvent{ch1, ch2} {+ select {+ case evt := <-ch:+ if evt.Type != "error" {+ t.Errorf("subscriber %d: expected type 'error', got '%s'", i, evt.Type)+ }+ case <-time.After(time.Second):+ t.Fatalf("subscriber %d: timed out waiting for event", i)+ }+ }+}++func TestConcurrentPublish(t *testing.T) {+ bus := NewAdminEventBus()++ var wg sync.WaitGroup+ for i := 0; i < 100; i++ {+ wg.Add(1)+ go func(n int) {+ defer wg.Done()+ bus.Publish("create", "sb", "w", "concurrent")+ }(i)+ }+ wg.Wait()++ history := bus.History()+ if len(history) != 100 {+ t.Fatalf("expected 100 events after concurrent publish, got %d", len(history))+ }+}++func TestSlowSubscriberDoesNotBlock(t *testing.T) {+ bus := NewAdminEventBus()++ // Subscribe but never read from the channel+ _, cleanup := bus.subscribe()+ defer cleanup()++ // Publish more events than the channel buffer (50)+ // This should not block thanks to non-blocking send+ done := make(chan struct{})+ go func() {+ for i := 0; i < 100; i++ {+ bus.Publish("create", "sb", "w", "flood")+ }+ close(done)+ }()++ select {+ case <-done:+ // Good, did not block+ case <-time.After(2 * time.Second):+ t.Fatal("Publish blocked on slow subscriber")+ }+}diff --git a/internal/compute/azure.go b/internal/compute/azure.goindex 48e96b82..61944952 100644--- a/internal/compute/azure.go+++ b/internal/compute/azure.go@@ -343,6 +343,43 @@ func (p *AzurePool) DrainMachine(ctx context.Context, machineID string) error {return err}+// 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+ 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)+ }+ for _, nic := range page.Value {+ if nic.Properties == nil || nic.Properties.VirtualMachine != nil {+ continue // attached to a VM, skip+ }+ name := ""+ if nic.Name != nil {+ name = *nic.Name+ }+ if !strings.HasPrefix(name, "osb-worker-") {+ continue // not ours+ }+ log.Printf("azure: cleaning orphaned NIC %s", name)+ poller, err := p.nicClient.BeginDelete(ctx, p.cfg.ResourceGroup, name, nil)+ if err != nil {+ log.Printf("azure: failed to delete orphaned NIC %s: %v", name, err)+ continue+ }+ if _, err := poller.PollUntilDone(ctx, nil); err != nil {+ log.Printf("azure: orphaned NIC %s delete poll failed: %v", name, err)+ } else {+ cleaned+++ }+ }+ }+ return cleaned, nil+}+// RefreshAMI checks Azure Key Vault for a new worker image ID and version.// Satisfies the controlplane.AMIRefresher interface.// If Key Vault is not configured, returns the static image ID with no error.diff --git a/internal/controlplane/leader_test.go b/internal/controlplane/leader_test.gonew file mode 100644index 00000000..11d4e43d--- /dev/null+++ b/internal/controlplane/leader_test.go@@ -0,0 +1,221 @@+package controlplane++import (+ "context"+ "sync/atomic"+ "testing"+ "time"++ "github.com/redis/go-redis/v9"+)++func newTestRedisClient(t *testing.T) *redis.Client {+ t.Helper()+ rdb := redis.NewClient(&redis.Options{+ Addr: "localhost:6379",+ DB: 15, // use DB 15 for tests to avoid collisions+ })+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if err := rdb.Ping(ctx).Err(); err != nil {+ t.Skipf("skipping: Redis not available at localhost:6379: %v", err)+ }+ // Clean up the leader key before and after+ rdb.Del(ctx, leaderKey)+ t.Cleanup(func() {+ rdb.Del(context.Background(), leaderKey)+ rdb.Close()+ })+ return rdb+}++func TestLeaderElectorAcquire(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "test-instance-1")++ if le.IsLeader() {+ t.Fatal("should not be leader before starting")+ }++ le.tryAcquire()++ if !le.IsLeader() {+ t.Fatal("should be leader after acquiring")+ }++ // Verify Redis key holds our instance ID+ ctx := context.Background()+ val, err := rdb.Get(ctx, leaderKey).Result()+ if err != nil {+ t.Fatalf("expected leader key in Redis, got error: %v", err)+ }+ if val != "test-instance-1" {+ t.Fatalf("expected leader key value 'test-instance-1', got '%s'", val)+ }+}++func TestLeaderElectorRelease(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "test-instance-1")+ le.tryAcquire()+ if !le.IsLeader() {+ t.Fatal("should be leader after acquiring")+ }++ le.release()++ if le.IsLeader() {+ t.Fatal("should not be leader after releasing")+ }++ // Verify key is gone+ ctx := context.Background()+ exists, err := rdb.Exists(ctx, leaderKey).Result()+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if exists != 0 {+ t.Fatal("leader key should be deleted after release")+ }+}++func TestLeaderElectorCallbacks(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "test-instance-cb")++ var becameLeader int32+ var lostLeadership int32++ le.OnBecomeLeader(func() {+ atomic.AddInt32(&becameLeader, 1)+ })+ le.OnLoseLeadership(func() {+ atomic.AddInt32(&lostLeadership, 1)+ })++ le.tryAcquire()+ if atomic.LoadInt32(&becameLeader) != 1 {+ t.Fatalf("expected OnBecomeLeader to fire once, got %d", atomic.LoadInt32(&becameLeader))+ }++ // Acquiring again while already leader should not fire callback again+ le.tryAcquire()+ if atomic.LoadInt32(&becameLeader) != 1 {+ t.Fatalf("expected OnBecomeLeader to still be 1 after re-acquire, got %d", atomic.LoadInt32(&becameLeader))+ }++ le.release()+ if atomic.LoadInt32(&lostLeadership) != 1 {+ t.Fatalf("expected OnLoseLeadership to fire once, got %d", atomic.LoadInt32(&lostLeadership))+ }+}++func TestLeaderElectorTwoCompeting(t *testing.T) {+ rdb := newTestRedisClient(t)++ // Create a second Redis client on the same DB+ rdb2 := redis.NewClient(&redis.Options{+ Addr: "localhost:6379",+ DB: 15,+ })+ t.Cleanup(func() { rdb2.Close() })++ le1 := NewLeaderElector(rdb, "instance-A")+ le2 := NewLeaderElector(rdb2, "instance-B")++ // Instance A acquires first+ le1.tryAcquire()+ if !le1.IsLeader() {+ t.Fatal("instance-A should be leader")+ }++ // Instance B tries to acquire — should fail+ le2.tryAcquire()+ if le2.IsLeader() {+ t.Fatal("instance-B should not be leader while instance-A holds it")+ }++ // Instance A releases+ le1.release()+ if le1.IsLeader() {+ t.Fatal("instance-A should no longer be leader after release")+ }++ // Now instance B can acquire+ le2.tryAcquire()+ if !le2.IsLeader() {+ t.Fatal("instance-B should be leader after instance-A released")+ }+}++func TestLeaderElectorStartStop(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "test-start-stop")++ var becameLeader int32+ le.OnBecomeLeader(func() {+ atomic.StoreInt32(&becameLeader, 1)+ })++ le.Start()++ // Give the goroutine time to acquire+ time.Sleep(200 * time.Millisecond)++ if !le.IsLeader() {+ t.Fatal("should be leader after Start()")+ }+ if atomic.LoadInt32(&becameLeader) != 1 {+ t.Fatal("OnBecomeLeader should have fired")+ }++ le.Stop()++ if le.IsLeader() {+ t.Fatal("should not be leader after Stop()")+ }+}++func TestLeaderElectorDefaultInstanceID(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "")+ if le.InstanceID() == "" {+ t.Fatal("instance ID should not be empty when defaulting")+ }+}++func TestLeaderElectorRefreshTTL(t *testing.T) {+ rdb := newTestRedisClient(t)++ le := NewLeaderElector(rdb, "test-refresh")+ le.tryAcquire()+ if !le.IsLeader() {+ t.Fatal("should be leader")+ }++ // Get initial TTL+ ctx := context.Background()+ ttl1, err := rdb.TTL(ctx, leaderKey).Result()+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ // Wait a bit, then re-acquire (refresh)+ time.Sleep(100 * time.Millisecond)+ le.tryAcquire()++ ttl2, err := rdb.TTL(ctx, leaderKey).Result()+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }++ // TTL should have been refreshed (ttl2 >= ttl1 or close to original)+ if ttl2 < ttl1-time.Second {+ t.Fatalf("expected TTL to be refreshed, got ttl1=%v ttl2=%v", ttl1, ttl2)+ }+}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex bbee1a62..28d3c9b9 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -210,6 +210,8 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {existing.CPUPct = entry.CPUPctexisting.MemPct = entry.MemPctexisting.DiskPct = entry.DiskPct+ existing.TotalMemoryMB = entry.TotalMemoryMB+ existing.CommittedMemoryMB = entry.CommittedMemoryMBif entry.GoldenVersion != "" {existing.GoldenVersion = entry.GoldenVersion}diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex bd841af7..95a3c0a8 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -56,6 +56,12 @@ type AMIRefresher interface {RefreshAMI(ctx context.Context) (amiID string, version string, err error)}+// OrphanCleaner is an optional interface a Pool can implement to clean up orphaned resources+// (NICs, disks) left by failed VM creates. Called periodically by the scaler.+type OrphanCleaner interface {+ CleanupOrphanedResources(ctx context.Context) (int, error)+}+// ScalerConfig configures the autoscaler.type ScalerConfig struct {Pool compute.Pool@@ -208,6 +214,17 @@ func (s *Scaler) evaluate() {}}+ // Clean up orphaned NICs/disks every ~5 min (every 10th tick)+ if s.refreshCount%10 == 0 {+ if cleaner, ok := s.pool.(OrphanCleaner); ok {+ if cleaned, err := cleaner.CleanupOrphanedResources(ctx); err != nil {+ log.Printf("scaler: orphan cleanup failed: %v", err)+ } else if cleaned > 0 {+ log.Printf("scaler: cleaned %d orphaned resources", cleaned)+ }+ }+ }+// Use discovered regions from workers, or fall back to the pool's regionregions := s.registry.Regions()log.Printf("scaler: evaluate tick (regions=%v)", regions)@@ -604,6 +621,20 @@ func (s *Scaler) evacuateBatch(sourceWorkerID, targetWorkerID string, count int)// smartScaleDown initiates draining of the least-loaded autoscaler-created worker// by live-migrating its sandboxes to other workers before destroying the machine.func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*WorkerInfo) {+ // Don't scale down while there are pending launches (workers still booting)+ if len(s.state.GetPendingLaunches(region)) > 0 {+ return+ }++ // Don't scale down while a rolling replace is in progress+ if s.targetWorkerVersion != "" {+ for _, w := range workers {+ if w.WorkerVersion != s.targetWorkerVersion && w.WorkerVersion != "" {+ return // stale workers still exist, let rolling replace handle it+ }+ }+ }+// Find the least-loaded worker that was created by the autoscaler.var target *WorkerInfofor _, w := range workers {@@ -644,7 +675,7 @@ func (s *Scaler) smartScaleDown(_ context.Context, region string, workers []*Wor// rollingReplace drains workers running an old version one at a time,// allowing the scaler to replace them with new-AMI workers.-func (s *Scaler) rollingReplace(_ context.Context, region string, workers []*WorkerInfo) {+func (s *Scaler) rollingReplace(ctx context.Context, region string, workers []*WorkerInfo) {if s.targetWorkerVersion == "" {return}@@ -677,10 +708,19 @@ func (s *Scaler) rollingReplace(_ context.Context, region string, workers []*Worreturn}- // Don't drain if no current-version workers exist yet — scale up first+ // 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 {- log.Printf("scaler: region %s has %d stale workers but 0 current-version, waiting for new workers to register",- region, len(stale))+ 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))+ return+ }+ log.Printf("scaler: rolling replace: all %d workers stale — launching replacement with new version",+ len(stale))+ s.scaleUp(ctx, region)return}diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.goindex 102cb7d9..1332bf47 100644--- a/internal/controlplane/scaler_test.go+++ b/internal/controlplane/scaler_test.go@@ -155,6 +155,7 @@ func (p *mockPool) DrainMachine(_ context.Context, _ string) errorfunc (p *mockPool) StartMachine(_ context.Context, _ string) error { return nil }func (p *mockPool) StopMachine(_ context.Context, _ string) error { return nil }func (p *mockPool) HealthCheck(_ context.Context, _ string) error { return nil }+func (p *mockPool) CleanupOrphanedResources(_ context.Context) (int, error) { return 0, nil }func (p *mockPool) ListMachines(_ context.Context) ([]*compute.Machine, error) { return nil, nil }func (p *mockPool) SupportedRegions(_ context.Context) ([]string, error) {return []string{"us-east-1"}, nil@@ -1266,3 +1267,350 @@ func TestInFlightCleanup(t *testing.T) {t.Errorf("expected 0 in-flight after final decrement, got %d", got)}}++// =============================================+// InMemoryScalerState unit tests+// =============================================++func TestInMemoryScalerState_LastScaleUp(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially no value+ _, ok := m.GetLastScaleUp("us-east-1")+ if ok {+ t.Fatal("expected no last scale up initially")+ }++ now := time.Now()+ m.SetLastScaleUp("us-east-1", now, 30*time.Second)++ got, ok := m.GetLastScaleUp("us-east-1")+ if !ok {+ t.Fatal("expected last scale up to be set")+ }+ if !got.Equal(now) {+ t.Fatalf("expected %v, got %v", now, got)+ }++ // Different region should be independent+ _, ok = m.GetLastScaleUp("eu-west-1")+ if ok {+ t.Fatal("expected no last scale up for different region")+ }+}++func TestInMemoryScalerState_PendingLaunches(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially empty+ pending := m.GetPendingLaunches("us-east-1")+ if len(pending) != 0 {+ t.Fatalf("expected 0 pending launches, got %d", len(pending))+ }++ p1 := pendingLaunch{MachineID: "m-1", LaunchedAt: time.Now()}+ p2 := pendingLaunch{MachineID: "m-2", LaunchedAt: time.Now()}++ m.AddPendingLaunch("us-east-1", p1)+ m.AddPendingLaunch("us-east-1", p2)++ pending = m.GetPendingLaunches("us-east-1")+ if len(pending) != 2 {+ t.Fatalf("expected 2 pending launches, got %d", len(pending))+ }++ // Remove one+ m.RemovePendingLaunch("us-east-1", "m-1")+ pending = m.GetPendingLaunches("us-east-1")+ if len(pending) != 1 {+ t.Fatalf("expected 1 pending launch after removal, got %d", len(pending))+ }+ if pending[0].MachineID != "m-2" {+ t.Fatalf("expected remaining launch to be m-2, got %s", pending[0].MachineID)+ }++ // Remove non-existent should be no-op+ m.RemovePendingLaunch("us-east-1", "m-999")+ pending = m.GetPendingLaunches("us-east-1")+ if len(pending) != 1 {+ t.Fatalf("expected 1 pending launch after removing non-existent, got %d", len(pending))+ }+}++func TestInMemoryScalerState_SetPendingLaunches(t *testing.T) {+ m := NewInMemoryScalerState()++ m.AddPendingLaunch("us-east-1", pendingLaunch{MachineID: "old-1", LaunchedAt: time.Now()})++ newLaunches := []pendingLaunch{+ {MachineID: "new-1", LaunchedAt: time.Now()},+ {MachineID: "new-2", LaunchedAt: time.Now()},+ }+ m.SetPendingLaunches("us-east-1", newLaunches)++ pending := m.GetPendingLaunches("us-east-1")+ if len(pending) != 2 {+ t.Fatalf("expected 2 pending launches after set, got %d", len(pending))+ }+ if pending[0].MachineID != "new-1" || pending[1].MachineID != "new-2" {+ t.Fatalf("unexpected pending launches: %+v", pending)+ }+}++func TestInMemoryScalerState_GetPendingLaunchesReturnsCopy(t *testing.T) {+ m := NewInMemoryScalerState()+ m.AddPendingLaunch("r1", pendingLaunch{MachineID: "m-1", LaunchedAt: time.Now()})++ result := m.GetPendingLaunches("r1")+ result[0].MachineID = "modified"++ original := m.GetPendingLaunches("r1")+ if original[0].MachineID != "m-1" {+ t.Fatal("GetPendingLaunches should return a copy")+ }+}++func TestInMemoryScalerState_Draining(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially not draining+ _, ok := m.GetDraining("m-1")+ if ok {+ t.Fatal("expected no drain state initially")+ }+ if m.IsDraining("m-1") {+ t.Fatal("expected IsDraining to be false initially")+ }++ ds := &drainState{+ WorkerID: "w-1",+ MachineID: "m-1",+ Region: "us-east-1",+ StartedAt: time.Now(),+ }+ m.SetDraining("m-1", ds)++ got, ok := m.GetDraining("m-1")+ if !ok {+ t.Fatal("expected drain state to be set")+ }+ if got.WorkerID != "w-1" {+ t.Fatalf("expected worker ID 'w-1', got '%s'", got.WorkerID)+ }+ if !m.IsDraining("m-1") {+ t.Fatal("expected IsDraining to be true")+ }++ // Remove+ m.RemoveDraining("m-1")+ _, ok = m.GetDraining("m-1")+ if ok {+ t.Fatal("expected drain state to be removed")+ }+ if m.IsDraining("m-1") {+ t.Fatal("expected IsDraining to be false after removal")+ }+}++func TestInMemoryScalerState_AllDraining(t *testing.T) {+ m := NewInMemoryScalerState()++ ds1 := &drainState{WorkerID: "w-1", MachineID: "m-1", Region: "us-east-1", StartedAt: time.Now()}+ ds2 := &drainState{WorkerID: "w-2", MachineID: "m-2", Region: "us-east-1", StartedAt: time.Now()}++ m.SetDraining("m-1", ds1)+ m.SetDraining("m-2", ds2)++ all := m.AllDraining()+ if len(all) != 2 {+ t.Fatalf("expected 2 draining workers, got %d", len(all))+ }+ if all["m-1"].WorkerID != "w-1" {+ t.Errorf("expected w-1, got %s", all["m-1"].WorkerID)+ }+ if all["m-2"].WorkerID != "w-2" {+ t.Errorf("expected w-2, got %s", all["m-2"].WorkerID)+ }++ // Returned map should be a copy+ delete(all, "m-1")+ if len(m.AllDraining()) != 2 {+ t.Fatal("AllDraining should return a copy")+ }+}++func TestInMemoryScalerState_Evacuation(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially no value+ _, ok := m.GetLastEvacuation("w-1")+ if ok {+ t.Fatal("expected no last evacuation initially")+ }++ now := time.Now()+ m.SetLastEvacuation("w-1", now)++ got, ok := m.GetLastEvacuation("w-1")+ if !ok {+ t.Fatal("expected last evacuation to be set")+ }+ if !got.Equal(now) {+ t.Fatalf("expected %v, got %v", now, got)+ }++ // Different worker is independent+ _, ok = m.GetLastEvacuation("w-2")+ if ok {+ t.Fatal("expected no last evacuation for different worker")+ }+}++func TestInMemoryScalerState_MigrationLock(t *testing.T) {+ m := NewInMemoryScalerState()++ // First acquire should succeed+ if !m.AcquireMigrationLock("sb-1") {+ t.Fatal("expected first acquire to succeed")+ }++ // Second acquire for same sandbox should fail+ if m.AcquireMigrationLock("sb-1") {+ t.Fatal("expected second acquire for same sandbox to fail")+ }++ // Different sandbox should succeed+ if !m.AcquireMigrationLock("sb-2") {+ t.Fatal("expected acquire for different sandbox to succeed")+ }++ // Release and re-acquire+ m.ReleaseMigrationLock("sb-1")+ if !m.AcquireMigrationLock("sb-1") {+ t.Fatal("expected acquire after release to succeed")+ }+}++func TestInMemoryScalerState_InFlight(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially zero+ if got := m.GetInFlight("w-1"); got != 0 {+ t.Fatalf("expected 0 in-flight initially, got %d", got)+ }++ m.IncrInFlight("w-1")+ if got := m.GetInFlight("w-1"); got != 1 {+ t.Fatalf("expected 1 in-flight after incr, got %d", got)+ }++ m.IncrInFlight("w-1")+ m.IncrInFlight("w-1")+ if got := m.GetInFlight("w-1"); got != 3 {+ t.Fatalf("expected 3 in-flight after 3 incrs, got %d", got)+ }++ m.DecrInFlight("w-1")+ if got := m.GetInFlight("w-1"); got != 2 {+ t.Fatalf("expected 2 in-flight after decr, got %d", got)+ }++ // Decr to zero should clean up+ m.DecrInFlight("w-1")+ m.DecrInFlight("w-1")+ if got := m.GetInFlight("w-1"); got != 0 {+ t.Fatalf("expected 0 in-flight after full decr, got %d", got)+ }++ // Different workers are independent+ m.IncrInFlight("w-2")+ if got := m.GetInFlight("w-1"); got != 0 {+ t.Fatalf("expected 0 for w-1, got %d", got)+ }+ if got := m.GetInFlight("w-2"); got != 1 {+ t.Fatalf("expected 1 for w-2, got %d", got)+ }+}++func TestInMemoryScalerState_DecrBelowZero(t *testing.T) {+ m := NewInMemoryScalerState()++ // Decrement from zero should clean up (go to 0 or negative and delete)+ m.DecrInFlight("w-1")+ if got := m.GetInFlight("w-1"); got != 0 {+ t.Fatalf("expected 0 after decr below zero, got %d", got)+ }+}++func TestInMemoryScalerState_SandboxCount(t *testing.T) {+ m := NewInMemoryScalerState()++ // Initially no value+ _, ok := m.GetLastSandboxCount("us-east-1")+ if ok {+ t.Fatal("expected no sandbox count initially")+ }++ m.SetLastSandboxCount("us-east-1", 42)+ got, ok := m.GetLastSandboxCount("us-east-1")+ if !ok {+ t.Fatal("expected sandbox count to be set")+ }+ if got != 42 {+ t.Fatalf("expected 42, got %d", got)+ }++ // Update+ m.SetLastSandboxCount("us-east-1", 100)+ got, ok = m.GetLastSandboxCount("us-east-1")+ if !ok {+ t.Fatal("expected sandbox count to be set")+ }+ if got != 100 {+ t.Fatalf("expected 100, got %d", got)+ }++ // Different region+ _, ok = m.GetLastSandboxCount("eu-west-1")+ if ok {+ t.Fatal("expected no sandbox count for different region")+ }+}++func TestInMemoryScalerState_ConcurrentAccess(t *testing.T) {+ m := NewInMemoryScalerState()++ var wg sync.WaitGroup+ for i := 0; i < 50; i++ {+ wg.Add(1)+ go func(n int) {+ defer wg.Done()+ region := fmt.Sprintf("region-%d", n%5)+ workerID := fmt.Sprintf("w-%d", n%10)++ m.SetLastScaleUp(region, time.Now(), time.Second)+ m.GetLastScaleUp(region)++ m.AddPendingLaunch(region, pendingLaunch{MachineID: fmt.Sprintf("m-%d", n), LaunchedAt: time.Now()})+ m.GetPendingLaunches(region)++ m.SetDraining(fmt.Sprintf("m-%d", n), &drainState{WorkerID: workerID})+ m.IsDraining(fmt.Sprintf("m-%d", n))+ m.AllDraining()++ m.SetLastEvacuation(workerID, time.Now())+ m.GetLastEvacuation(workerID)++ m.AcquireMigrationLock(fmt.Sprintf("sb-%d", n))+ m.ReleaseMigrationLock(fmt.Sprintf("sb-%d", n))++ m.IncrInFlight(workerID)+ m.GetInFlight(workerID)+ m.DecrInFlight(workerID)++ m.SetLastSandboxCount(region, n)+ m.GetLastSandboxCount(region)+ }(i)+ }+ wg.Wait()+}