Skip to content

An open-source, faster Devin alternative

TypeScript

scaler fixes (#209)

Brian Reardonda5220cfe1b6
diff --git a/cmd/server/main.go b/cmd/server/main.go
index a6d9db78..8eea8537 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -311,17 +311,31 @@ func main() {
}
if pool != nil {
+ // Pick the per-provider ranked size list. Empty → scaler defers to
+ // the pool's single configured default (cfg.AzureVMSize / cfg.EC2InstanceType).
+ var machineSizes []string
+ switch {
+ case len(cfg.AzureVMSizes) > 0 && cfg.AzureSubscriptionID != "":
+ machineSizes = cfg.AzureVMSizes
+ case len(cfg.EC2InstanceTypes) > 0 && (cfg.EC2AMI != "" || cfg.EC2SSMParameterName != ""):
+ machineSizes = cfg.EC2InstanceTypes
+ }
+ if len(machineSizes) > 0 {
+ log.Printf("opensandbox: scaler size fallback ranked: %v", machineSizes)
+ }
+
scalerState := controlplane.NewRedisScalerState(redisRegistry.RedisClient())
scaler := controlplane.NewScaler(controlplane.ScalerConfig{
- Pool: pool,
- Registry: redisRegistry,
- Store: opts.Store,
- StateStore: scalerState,
- WorkerImage: cfg.EC2WorkerImage,
- Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,
- MinWorkers: cfg.MinWorkersPerRegion,
- MaxWorkers: cfg.MaxWorkersPerRegion,
- IdleReserve: cfg.IdleReserveWorkers,
+ Pool: pool,
+ Registry: redisRegistry,
+ Store: opts.Store,
+ StateStore: scalerState,
+ WorkerImage: cfg.EC2WorkerImage,
+ Cooldown: time.Duration(cfg.ScaleCooldownSec) * time.Second,
+ MinWorkers: cfg.MinWorkersPerRegion,
+ MaxWorkers: cfg.MaxWorkersPerRegion,
+ IdleReserve: cfg.IdleReserveWorkers,
+ MachineSizes: machineSizes,
})
defer scaler.Stop()
diff --git a/internal/compute/azure.go b/internal/compute/azure.go
index a8aa0d4b..464ed210 100644
--- a/internal/compute/azure.go
+++ b/internal/compute/azure.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/rand"
"encoding/base64"
+ "errors"
"fmt"
"log"
"strings"
@@ -18,6 +19,51 @@ import (
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets"
)
+// azureQuotaCodes are the error-message fragments the Azure ARM API uses for
+// quota and SKU-availability rejections. Detected via substring match against
+// the wrapped error string because the SDK surfaces these through several
+// layers (BeginCreateOrUpdate immediate failure, PollUntilDone async failure,
+// nested ResponseError) and pinning to a single concrete type misses cases.
+// All of these are recoverable by retrying with a different VM size, so the
+// autoscaler treats them as the ErrQuotaExceeded class.
+var azureQuotaCodes = []string{
+ "QuotaExceeded",
+ "OperationNotAllowed",
+ "SkuNotAvailable",
+ "AllocationFailed",
+ "ZonalAllocationFailed",
+ "OverconstrainedAllocationRequest",
+ "exceeding approved quota",
+ "exceeding approved Total Regional Cores quota",
+ "exceeding approved Standard",
+}
+
+// isAzureQuotaErr reports whether err matches one of the documented quota /
+// capacity rejection codes from Azure ARM.
+func isAzureQuotaErr(err error) bool {
+ if err == nil {
+ return false
+ }
+ msg := err.Error()
+ for _, code := range azureQuotaCodes {
+ if strings.Contains(msg, code) {
+ return true
+ }
+ }
+ return false
+}
+
+// wrapAzureCreateErr tags createMachine errors with ErrQuotaExceeded when the
+// underlying ARM failure was a quota/capacity rejection, so the scaler can
+// fall through to the next VM size in its ranked list.
+func wrapAzureCreateErr(err error, format string, args ...any) error {
+ wrapped := fmt.Errorf(format, args...)
+ if isAzureQuotaErr(err) {
+ return errors.Join(ErrQuotaExceeded, wrapped)
+ }
+ return wrapped
+}
+
const (
azureTagRole = "opensandbox-role"
azureTagDraining = "opensandbox-draining"
@@ -213,12 +259,12 @@ func (p *AzurePool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machi
if err != nil {
log.Printf("azure: VM %s BeginCreateOrUpdate error detail: %+v", vmName, err)
go p.cleanupNIC(nicName, "create failed")
- return nil, fmt.Errorf("azure: create VM %s failed: %w", vmName, err)
+ return nil, wrapAzureCreateErr(err, "azure: create VM %s failed: %w", vmName, err)
}
vmResp, err := vmPoller.PollUntilDone(ctx, nil)
if err != nil {
go p.cleanupNIC(nicName, "poll failed")
- return nil, fmt.Errorf("azure: VM %s poll failed: %w", vmName, err)
+ return nil, wrapAzureCreateErr(err, "azure: VM %s poll failed: %w", vmName, err)
}
log.Printf("azure: VM %s created successfully", vmName)
diff --git a/internal/compute/ec2.go b/internal/compute/ec2.go
index e3f11173..052daa85 100644
--- a/internal/compute/ec2.go
+++ b/internal/compute/ec2.go
@@ -3,6 +3,7 @@ package compute
import (
"context"
"encoding/base64"
+ "errors"
"fmt"
"log"
"strings"
@@ -16,6 +17,39 @@ import (
"github.com/aws/aws-sdk-go-v2/service/ssm"
)
+// ec2QuotaCodes are the AWS EC2 error codes that indicate a vCPU quota,
+// per-account instance limit, or AZ-level capacity exhaustion. All of these
+// are recoverable by retrying with a different instance type, so the
+// autoscaler treats them as the ErrQuotaExceeded class.
+var ec2QuotaCodes = []string{
+ "VcpuLimitExceeded",
+ "InstanceLimitExceeded",
+ "InsufficientInstanceCapacity",
+ "MaxSpotInstanceCountExceeded",
+ "Unsupported", // returned when a region/AZ doesn't offer the requested type
+}
+
+func isEC2QuotaErr(err error) bool {
+ if err == nil {
+ return false
+ }
+ msg := err.Error()
+ for _, code := range ec2QuotaCodes {
+ if strings.Contains(msg, code) {
+ return true
+ }
+ }
+ return false
+}
+
+func wrapEC2CreateErr(err error, format string, args ...any) error {
+ wrapped := fmt.Errorf(format, args...)
+ if isEC2QuotaErr(err) {
+ return errors.Join(ErrQuotaExceeded, wrapped)
+ }
+ return wrapped
+}
+
const (
tagRole = "opensandbox:role"
tagInstanceType = "opensandbox:instance-type"
@@ -129,7 +163,7 @@ func (p *EC2Pool) CreateMachine(ctx context.Context, opts MachineOpts) (*Machine
result, err := p.client.RunInstances(ctx, input)
if err != nil {
- return nil, fmt.Errorf("ec2: RunInstances failed: %w", err)
+ return nil, wrapEC2CreateErr(err, "ec2: RunInstances failed: %w", err)
}
if len(result.Instances) == 0 {
diff --git a/internal/compute/pool.go b/internal/compute/pool.go
index 944d49af..d8d1ecef 100644
--- a/internal/compute/pool.go
+++ b/internal/compute/pool.go
@@ -1,6 +1,17 @@
package compute
-import "context"
+import (
+ "context"
+ "errors"
+)
+
+// ErrQuotaExceeded indicates a provider quota or capacity constraint that may
+// be resolved by trying a different machine size. Pool implementations wrap
+// (via errors.Join or fmt.Errorf %w) when they detect provider-specific quota
+// or "no capacity in this SKU/zone" failures. The autoscaler uses errors.Is to
+// decide whether to fall through to the next size in a ranked list versus
+// abort the launch.
+var ErrQuotaExceeded = errors.New("quota or capacity exceeded")
// Machine represents a worker machine in the compute pool.
type Machine struct {
diff --git a/internal/compute/quota_test.go b/internal/compute/quota_test.go
new file mode 100644
index 00000000..422bd84c
--- /dev/null
+++ b/internal/compute/quota_test.go
@@ -0,0 +1,96 @@
+package compute
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+)
+
+func TestIsAzureQuotaErr(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ isQuota bool
+ }{
+ {"nil", nil, false},
+ {"unrelated", errors.New("network timeout"), false},
+ {"QuotaExceeded code", errors.New("ERROR CODE: QuotaExceeded\noperation failed"), true},
+ {"OperationNotAllowed", errors.New("OperationNotAllowed: regional cores"), true},
+ {"SkuNotAvailable", errors.New("SkuNotAvailable: Standard_D16ads_v7 in eastus2"), true},
+ {"AllocationFailed", errors.New("AllocationFailed: capacity unavailable"), true},
+ {"ZonalAllocationFailed", errors.New("ZonalAllocationFailed in zone 1"), true},
+ {"OverconstrainedAllocationRequest", errors.New("OverconstrainedAllocationRequest"), true},
+ {"approved quota text", errors.New("operation results in exceeding approved quota"), true},
+ {"regional cores phrasing", errors.New("Operation could not be completed as it results in exceeding approved Total Regional Cores quota"), true},
+ {"wrapped quota", fmt.Errorf("azure: create VM failed: %w", errors.New("QuotaExceeded")), true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := isAzureQuotaErr(tc.err)
+ if got != tc.isQuota {
+ t.Fatalf("isAzureQuotaErr(%v) = %v, want %v", tc.err, got, tc.isQuota)
+ }
+ })
+ }
+}
+
+func TestIsEC2QuotaErr(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ isQuota bool
+ }{
+ {"nil", nil, false},
+ {"unrelated", errors.New("connection reset"), false},
+ {"VcpuLimitExceeded", errors.New("VcpuLimitExceeded: max 32 in region"), true},
+ {"InstanceLimitExceeded", errors.New("InstanceLimitExceeded"), true},
+ {"InsufficientInstanceCapacity", errors.New("InsufficientInstanceCapacity in us-east-1a"), true},
+ {"MaxSpotInstanceCountExceeded", errors.New("MaxSpotInstanceCountExceeded"), true},
+ {"Unsupported in AZ", errors.New("Unsupported: c7gd.metal not offered in this AZ"), true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := isEC2QuotaErr(tc.err)
+ if got != tc.isQuota {
+ t.Fatalf("isEC2QuotaErr(%v) = %v, want %v", tc.err, got, tc.isQuota)
+ }
+ })
+ }
+}
+
+func TestWrapAzureCreateErrTagsQuota(t *testing.T) {
+ quotaSrc := errors.New("AllocationFailed: no capacity")
+ wrapped := wrapAzureCreateErr(quotaSrc, "azure: create VM foo failed: %w", quotaSrc)
+ if !errors.Is(wrapped, ErrQuotaExceeded) {
+ t.Fatalf("expected wrapped quota error to match ErrQuotaExceeded, got %v", wrapped)
+ }
+ // The original error chain must remain reachable so callers can still log
+ // the underlying provider message.
+ if !errors.Is(wrapped, quotaSrc) {
+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)
+ }
+}
+
+func TestWrapAzureCreateErrPassesThroughNonQuota(t *testing.T) {
+ src := errors.New("network unreachable")
+ wrapped := wrapAzureCreateErr(src, "azure: create VM foo failed: %w", src)
+ if errors.Is(wrapped, ErrQuotaExceeded) {
+ t.Fatalf("non-quota error should not be tagged as ErrQuotaExceeded: %v", wrapped)
+ }
+ if !errors.Is(wrapped, src) {
+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)
+ }
+}
+
+func TestWrapEC2CreateErrTagsQuota(t *testing.T) {
+ src := errors.New("VcpuLimitExceeded: max 32 in us-east-1")
+ wrapped := wrapEC2CreateErr(src, "ec2: RunInstances failed: %w", src)
+ if !errors.Is(wrapped, ErrQuotaExceeded) {
+ t.Fatalf("expected wrapped quota error to match ErrQuotaExceeded, got %v", wrapped)
+ }
+ if !errors.Is(wrapped, src) {
+ t.Fatalf("expected wrapped error to preserve original chain, got %v", wrapped)
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 7497551d..9b691401 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -73,7 +73,8 @@ type Config struct {
// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)
EC2AMI string // Custom AMI for worker instances
- EC2InstanceType string // e.g. "c7gd.metal", "r6gd.metal", "r7gd.metal"
+ EC2InstanceType string // single fallback type; used only when EC2InstanceTypes is empty
+ EC2InstanceTypes []string // ranked list of instance types tried in order on quota/capacity errors
EC2SubnetID string // VPC subnet for worker instances
EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
EC2KeyName string // SSH key pair name (for debugging)
@@ -84,7 +85,8 @@ type Config struct {
// Azure compute pool (server mode — for auto-scaling worker VMs)
AzureSubscriptionID string // Azure subscription ID
AzureResourceGroup string // Resource group for worker VMs
- AzureVMSize string // e.g. "Standard_D16s_v5"
+ AzureVMSize string // single fallback size; used only when AzureVMSizes is empty
+ AzureVMSizes []string // ranked list of VM sizes tried in order on quota/capacity errors
AzureImageID string // Custom image ID or URN
AzureSubnetID string // Full resource ID of the VNet subnet
AzureSSHPublicKey string // SSH public key for worker VMs
@@ -204,6 +206,7 @@ func Load() (*Config, error) {
EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),
EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),
+ EC2InstanceTypes: splitCSV(os.Getenv("OPENSANDBOX_EC2_INSTANCE_TYPES")),
EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),
EC2SecurityGroupID: os.Getenv("OPENSANDBOX_EC2_SECURITY_GROUP_ID"),
EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),
@@ -214,6 +217,7 @@ func Load() (*Config, error) {
AzureSubscriptionID: os.Getenv("OPENSANDBOX_AZURE_SUBSCRIPTION_ID"),
AzureResourceGroup: os.Getenv("OPENSANDBOX_AZURE_RESOURCE_GROUP"),
AzureVMSize: envOrDefault("OPENSANDBOX_AZURE_VM_SIZE", "Standard_D16s_v5"),
+ AzureVMSizes: splitCSV(os.Getenv("OPENSANDBOX_AZURE_VM_SIZES")),
AzureImageID: os.Getenv("OPENSANDBOX_AZURE_IMAGE_ID"),
AzureSubnetID: os.Getenv("OPENSANDBOX_AZURE_SUBNET_ID"),
AzureSSHPublicKey: os.Getenv("OPENSANDBOX_AZURE_SSH_PUBLIC_KEY"),
@@ -277,6 +281,27 @@ func envOrDefault(key, fallback string) string {
return fallback
}
+// splitCSV parses a comma-separated value into a non-empty trimmed slice.
+// Empty input or all-whitespace entries return nil so callers can use len() == 0
+// to detect "not configured." Leaves the order intact since rank matters
+// for the autoscaler's machine-size fallback list.
+func splitCSV(s string) []string {
+ if s == "" {
+ return nil
+ }
+ parts := strings.Split(s, ",")
+ out := make([]string, 0, len(parts))
+ for _, p := range parts {
+ if trimmed := strings.TrimSpace(p); trimmed != "" {
+ out = append(out, trimmed)
+ }
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
func envOrDefaultInt(key string, fallback int) int {
if v := os.Getenv(key); v != "" {
if n, err := strconv.Atoi(v); err == nil {
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index 574d09b4..284551ea 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -2,9 +2,55 @@ package config
import (
"os"
+ "reflect"
"testing"
)
+func TestSplitCSV(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want []string
+ }{
+ {"empty", "", nil},
+ {"whitespace only", " , ,", nil},
+ {"single", "Standard_D16ads_v7", []string{"Standard_D16ads_v7"}},
+ {"multiple", "Standard_D16ads_v7,Standard_D16ds_v6,Standard_D16s_v5",
+ []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}},
+ {"trim whitespace", " Standard_D16ads_v7 , Standard_D16ds_v6 ",
+ []string{"Standard_D16ads_v7", "Standard_D16ds_v6"}},
+ {"drop empty entries", "a,,b,,,c", []string{"a", "b", "c"}},
+ {"order preserved", "c7gd.metal,r7gd.metal,r6gd.metal",
+ []string{"c7gd.metal", "r7gd.metal", "r6gd.metal"}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := splitCSV(tc.in)
+ if !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("splitCSV(%q) = %v, want %v", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestLoadParsesMachineSizeLists(t *testing.T) {
+ t.Setenv("OPENSANDBOX_AZURE_VM_SIZES", "Standard_D16ads_v7, Standard_D16ds_v6 ,Standard_D16s_v5")
+ t.Setenv("OPENSANDBOX_EC2_INSTANCE_TYPES", "c7gd.metal,r7gd.metal")
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() error: %v", err)
+ }
+ wantAzure := []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}
+ if !reflect.DeepEqual(cfg.AzureVMSizes, wantAzure) {
+ t.Errorf("AzureVMSizes = %v, want %v", cfg.AzureVMSizes, wantAzure)
+ }
+ wantEC2 := []string{"c7gd.metal", "r7gd.metal"}
+ if !reflect.DeepEqual(cfg.EC2InstanceTypes, wantEC2) {
+ t.Errorf("EC2InstanceTypes = %v, want %v", cfg.EC2InstanceTypes, wantEC2)
+ }
+}
+
func TestLoadDefaults(t *testing.T) {
// Clear env to test defaults
os.Unsetenv("OPENSANDBOX_PORT")
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index b37eefce..9438f050 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -44,6 +44,12 @@ var secretMapping = map[string]string{
"server-stripe-secret-key": "STRIPE_SECRET_KEY",
"server-stripe-webhook-secret": "STRIPE_WEBHOOK_SECRET",
"server-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",
+ // Machine-size fallback lists (PR #209). Comma-separated ranked
+ // instance types the autoscaler tries in order on quota / capacity
+ // errors. Empty value = use the single VMSize / InstanceType
+ // configured on the pool (pre-fallback behavior).
+ "server-azure-vm-sizes": "OPENSANDBOX_AZURE_VM_SIZES",
+ "server-ec2-instance-types": "OPENSANDBOX_EC2_INSTANCE_TYPES",
// Legacy Axiom mappings — kept for backwards compat with existing prod
// KVs that pre-date the `shared-` prefix. New deploys should use
// `shared-axiom-*` instead. Safe to leave: in server mode only
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index dec4d63d..35b1eda3 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -18,6 +18,37 @@ import (
pb "github.com/opensandbox/opensandbox/proto/worker"
)
+const (
+ // routingCountTTL bounds how long a per-worker placement counter survives
+ // without further increments. Heartbeat reconciles every 10s; 60s gives the
+ // counter enough headroom to bridge several heartbeat windows so a quiet
+ // stretch between placements doesn't drop us back to heartbeat-only data.
+ routingCountTTL = 60 * time.Second
+
+ // routingHardCapPct excludes workers whose actual CPU/mem/disk pressure is
+ // at or above this level. The score below handles the gradient up to this
+ // cap, so 0–85%-loaded workers are ranked smoothly; only at 85% do we stop
+ // considering a worker entirely. Aligned with the scaler's 80% evacuation
+ // threshold — by the time a worker is being evacuated we should have
+ // already stopped sending it traffic.
+ routingHardCapPct = 85.0
+
+ // drainKeyPrefix is the Redis key prefix used to publish per-worker drain
+ // state across all control planes. SetDraining writes this key; every
+ // heartbeat applies it to the in-memory worker entry so any CP's view of
+ // "is this worker draining?" stays consistent regardless of which CP
+ // initiated the drain.
+ drainKeyPrefix = "drain:"
+
+ // drainKeyTTL bounds how long a drain marker survives without renewal.
+ // Longer than any reasonable drain (45min drainTimeout in scaler.go) so
+ // long-running drains don't unexpectedly re-route traffic to the worker,
+ // but short enough that a forgotten "drain forever" doesn't outlive the
+ // worker's lifetime — pending operator clearing, the worker will rejoin
+ // the pool after 24h.
+ drainKeyTTL = 24 * time.Hour
+)
+
// WorkerEntry represents a worker in the Redis-backed registry.
type WorkerEntry struct {
ID string `json:"worker_id"`
@@ -244,6 +275,16 @@ func (r *RedisWorkerRegistry) reconcileAndPrune() {
// handleHeartbeat updates the in-memory worker map and dials gRPC if this is a new worker.
func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
+ // Read drain state outside the lock — this is a network call and we don't
+ // want to block other registry ops on Redis latency. The drain key is the
+ // cross-CP source of truth; per-CP SetDraining writes it on the admin
+ // path or scaler-initiated drain, and every CP's heartbeat applies it
+ // here so all CPs converge on the same view.
+ drainCtx, drainCancel := context.WithTimeout(context.Background(), time.Second)
+ drainExists, _ := r.rdb.Exists(drainCtx, drainKeyPrefix+entry.ID).Result()
+ drainCancel()
+ drainOverride := drainExists > 0
+
r.mu.Lock()
defer r.mu.Unlock()
@@ -257,6 +298,7 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
existing.DiskPct = entry.DiskPct
existing.TotalMemoryMB = entry.TotalMemoryMB
existing.CommittedMemoryMB = entry.CommittedMemoryMB
+ existing.Draining = drainOverride
if entry.GoldenVersion != "" {
existing.GoldenVersion = entry.GoldenVersion
}
@@ -274,8 +316,9 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {
}
} else {
// New worker
+ entry.Draining = drainOverride
r.workers[entry.ID] = &entry
- log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s)", entry.ID, entry.Region, entry.GRPCAddr)
+ log.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s, draining=%v)", entry.ID, entry.Region, entry.GRPCAddr, drainOverride)
}
// Per-sandbox stats indexing. Update fresh entries; prune sandboxes that
@@ -377,90 +420,137 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {
log.Printf("redis_registry: gRPC connection initiated to worker %s at %s", workerID, grpcAddr)
}
-// GetLeastLoadedWorker returns the worker with the best combination of remaining capacity
-// and resource headroom. Workers under heavy resource pressure (CPU > 90% or mem > 90%)
-// are skipped. If region is non-empty, only workers in that region are considered.
-// If no workers match the region, falls back to all workers.
+// GetLeastLoadedWorker returns the worker with the best combination of slot
+// allocation and actual host-memory headroom. Workers above routingHardCapPct
+// on CPU/mem/disk, with no slot capacity left, or marked draining are skipped.
+// If region is non-empty, only workers in that region are considered; if none
+// match, falls back to all workers.
+//
+// Ranking score (lower is better):
+//
+// score = Current/Capacity + MemPct/100
+//
+// MemPct is real RSS-based usage, not committed memory: an idle 16GB-max
+// sandbox occupying 200MB of host RAM should not be treated as if it had
+// reserved 16GB. Committed-memory accounting over-reserves for the common
+// idle-but-large case and pushed traffic away from workers that actually had
+// plenty of headroom. CPU and disk are handled by the hard cap, not the
+// score, since they're spikier and a transient burst shouldn't permanently
+// disprefer a worker.
func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry, pb.SandboxWorkerClient, error) {
r.mu.Lock()
defer r.mu.Unlock()
- // Simple strategy: pick the worker with fewest sandboxes.
- // Skip workers under heavy resource pressure.
- // Skip idle reserves unless all active workers are above 60% committed.
- // Read Redis routing counters to get real-time sandbox counts across both CPs
routingCtx, routingCancel := context.WithTimeout(context.Background(), time.Second)
defer routingCancel()
- var eligible []*WorkerEntry
- for _, w := range r.workers {
- if region != "" && w.Region != region {
- continue
- }
- if w.Draining {
- continue
- }
- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
- continue
- }
- // Use Redis routing counter if higher than heartbeat count
+ eligible := r.collectEligibleLocked(region, false /* anyRegion */)
+ if len(eligible) == 0 && region != "" {
+ eligible = r.collectEligibleLocked(region, true /* anyRegion */)
+ }
+ if len(eligible) == 0 {
+ return nil, nil, fmt.Errorf("no workers available")
+ }
+
+ // Apply the cross-CP routing counter so an in-flight placement on the
+ // other CP is reflected before we score. Heartbeats reconcile to truth
+ // within 10s; until then this counter is the only way the other CP's
+ // recent picks show up here.
+ for _, w := range eligible {
rCount, err := r.rdb.Get(routingCtx, "routing:count:"+w.ID).Int()
if err == nil && rCount > w.Current {
w.Current = rCount
}
- eligible = append(eligible, w)
- }
-
- // Fallback: try any region
- if len(eligible) == 0 && region != "" {
- for _, w := range r.workers {
- if w.CPUPct > 90 || w.MemPct > 90 || w.DiskPct > 90 {
- continue
- }
- eligible = append(eligible, w)
- }
}
- if len(eligible) == 0 {
- return nil, nil, fmt.Errorf("no workers available")
+ // Score each eligible worker; track the minimum so we can tie-break.
+ type scored struct {
+ w *WorkerEntry
+ s float64
}
-
- // Find workers tied for fewest sandboxes, round-robin among them
- minCount := eligible[0].Current
- for _, w := range eligible[1:] {
- if w.Current < minCount {
- minCount = w.Current
+ scoredWorkers := make([]scored, 0, len(eligible))
+ minScore := scoreWorker(eligible[0])
+ for _, w := range eligible {
+ s := scoreWorker(w)
+ if s < minScore {
+ minScore = s
}
+ scoredWorkers = append(scoredWorkers, scored{w, s})
}
+
+ // Strict tie window. With float scores genuine ties are rare except in the
+ // clean-cluster case (all workers at 0 sandboxes, equal MemPct), where RR
+ // across both CPs keeps the spread even. Any real difference in load —
+ // one extra sandbox or a percent more memory — picks a single winner, so
+ // we get the bias toward the lighter worker that the old +1-smoothing
+ // logic was failing to provide.
+ const tieEpsilon = 1e-9
var tied []*WorkerEntry
- for _, w := range eligible {
- if w.Current <= minCount+1 { // within 1 of the minimum
- tied = append(tied, w)
+ for _, sc := range scoredWorkers {
+ if sc.s-minScore < tieEpsilon {
+ tied = append(tied, sc.w)
}
}
- // Use Redis-based round-robin counter so both CPs spread evenly
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
- rr, _ := r.rdb.Incr(ctx, "routing:rr").Result()
- cancel()
- best := tied[rr%int64(len(tied))]
+ var best *WorkerEntry
+ if len(tied) == 1 {
+ best = tied[0]
+ } else {
+ // Cross-CP round-robin among genuine ties.
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ rr, _ := r.rdb.Incr(ctx, "routing:rr").Result()
+ cancel()
+ best = tied[rr%int64(len(tied))]
+ }
client, ok := r.clients[best.ID]
if !ok {
return nil, nil, fmt.Errorf("no gRPC connection to worker %s", best.ID)
}
- // Atomically increment sandbox count in Redis so BOTH CPs see it instantly.
- // The heartbeat will correct to the real count within 10s.
+ // Publish the increment so the other CP sees this placement before its
+ // next heartbeat reconcile. TTL bridges quiet windows between placements.
ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
r.rdb.Incr(ctx2, "routing:count:"+best.ID)
- r.rdb.Expire(ctx2, "routing:count:"+best.ID, 15*time.Second)
+ r.rdb.Expire(ctx2, "routing:count:"+best.ID, routingCountTTL)
cancel2()
- best.Current++ // also update local for this CP
+ best.Current++
return best, client, nil
}
+// collectEligibleLocked returns workers passing the routing eligibility gates.
+// If anyRegion is true the region filter is dropped (used for cross-region
+// fallback when a region is starved). Caller must hold r.mu.
+func (r *RedisWorkerRegistry) collectEligibleLocked(region string, anyRegion bool) []*WorkerEntry {
+ var out []*WorkerEntry
+ for _, w := range r.workers {
+ if !anyRegion && region != "" && w.Region != region {
+ continue
+ }
+ if w.Draining {
+ continue
+ }
+ if w.CPUPct >= routingHardCapPct || w.MemPct >= routingHardCapPct || w.DiskPct >= routingHardCapPct {
+ continue
+ }
+ if w.Capacity <= 0 || w.Current >= w.Capacity {
+ continue
+ }
+ out = append(out, w)
+ }
+ return out
+}
+
+// scoreWorker computes a placement score where lower is better. Combines slot
+// allocation with actual memory pressure. See GetLeastLoadedWorker comment for
+// rationale.
+func scoreWorker(w *WorkerEntry) float64 {
+ slotPressure := float64(w.Current) / float64(w.Capacity)
+ memPressure := w.MemPct / 100.0
+ return slotPressure + memPressure
+}
+
// GetWorkerClient returns the gRPC client for a specific worker.
func (r *RedisWorkerRegistry) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {
// Fast path: read lock, check connection state, return if healthy.
@@ -535,8 +625,31 @@ func (r *RedisWorkerRegistry) GetAllWorkers() []*WorkerEntry {
return result
}
-// SetDraining marks a worker as draining — it will not receive new sandboxes.
+// SetDraining marks a worker as draining cluster-wide. The drain state is
+// published to Redis under drainKeyPrefix+workerID, where every CP's
+// handleHeartbeat reads it on the next heartbeat (≤10s) and applies it to its
+// in-memory entry. This makes drain state a cross-CP fact rather than a
+// per-CP local override.
+//
+// The local in-memory map is also updated immediately so the calling CP's
+// next placement decision sees the change without waiting for the heartbeat
+// roundtrip. Redis errors are logged but not returned — local state still
+// takes effect, and the worker will undrain naturally via the 24h TTL even if
+// the operator can't reach the API to clear it explicitly.
func (r *RedisWorkerRegistry) SetDraining(workerID string, draining bool) {
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ key := drainKeyPrefix + workerID
+ if draining {
+ if err := r.rdb.Set(ctx, key, "1", drainKeyTTL).Err(); err != nil {
+ log.Printf("redis_registry: SetDraining(%s, true): Redis SET failed: %v (local-only)", workerID, err)
+ }
+ } else {
+ if err := r.rdb.Del(ctx, key).Err(); err != nil {
+ log.Printf("redis_registry: SetDraining(%s, false): Redis DEL failed: %v (local-only)", workerID, err)
+ }
+ }
+
r.mu.Lock()
defer r.mu.Unlock()
if w, ok := r.workers[workerID]; ok {
diff --git a/internal/controlplane/redis_registry_test.go b/internal/controlplane/redis_registry_test.go
new file mode 100644
index 00000000..59a9b1c2
--- /dev/null
+++ b/internal/controlplane/redis_registry_test.go
@@ -0,0 +1,197 @@
+package controlplane
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// newTestRegistries creates two RedisWorkerRegistry instances against the same
+// test Redis instance, simulating two control planes sharing state. Skips the
+// test when Redis is not reachable. Returns the registries and a cleanup
+// function that removes any keys created under the supplied workerID.
+func newTestRegistries(t *testing.T, workerID string) (*RedisWorkerRegistry, *RedisWorkerRegistry) {
+ t.Helper()
+ const redisURL = "redis://localhost:6379/15"
+
+ probe := redis.NewClient(&redis.Options{Addr: "localhost:6379", DB: 15})
+ pingCtx, pingCancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer pingCancel()
+ if err := probe.Ping(pingCtx).Err(); err != nil {
+ probe.Close()
+ t.Skipf("skipping: Redis not available at localhost:6379: %v", err)
+ }
+
+ cleanupKeys := func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ probe.Del(ctx, drainKeyPrefix+workerID)
+ probe.Del(ctx, "worker:"+workerID)
+ probe.Del(ctx, "routing:count:"+workerID)
+ }
+ cleanupKeys()
+
+ cp1, err := NewRedisWorkerRegistry(redisURL)
+ if err != nil {
+ t.Fatalf("cp1 NewRedisWorkerRegistry: %v", err)
+ }
+ cp2, err := NewRedisWorkerRegistry(redisURL)
+ if err != nil {
+ cp1.Stop()
+ t.Fatalf("cp2 NewRedisWorkerRegistry: %v", err)
+ }
+
+ t.Cleanup(func() {
+ cp1.Stop()
+ cp2.Stop()
+ cleanupKeys()
+ probe.Close()
+ })
+
+ return cp1, cp2
+}
+
+func TestSetDrainingPublishesToRedis(t *testing.T) {
+ workerID := fmt.Sprintf("test-drain-publish-%d", time.Now().UnixNano())
+ cp, _ := newTestRegistries(t, workerID)
+
+ // Bootstrap so SetDraining has a local entry to flip.
+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})
+
+ cp.SetDraining(workerID, true)
+
+ // Local cache reflects the change immediately.
+ if w := cp.GetWorker(workerID); w == nil || !w.Draining {
+ t.Fatalf("expected local cache draining=true, got %+v", w)
+ }
+
+ // Redis has the key with content "1" and a TTL.
+ ctx := context.Background()
+ val, err := cp.rdb.Get(ctx, drainKeyPrefix+workerID).Result()
+ if err != nil || val != "1" {
+ t.Fatalf("expected drain key value \"1\", got val=%q err=%v", val, err)
+ }
+ ttl, err := cp.rdb.TTL(ctx, drainKeyPrefix+workerID).Result()
+ if err != nil {
+ t.Fatalf("TTL fetch failed: %v", err)
+ }
+ if ttl <= 0 || ttl > drainKeyTTL {
+ t.Fatalf("expected TTL within (0, %s], got %s", drainKeyTTL, ttl)
+ }
+
+ // Clearing removes the key.
+ cp.SetDraining(workerID, false)
+ if exists, _ := cp.rdb.Exists(ctx, drainKeyPrefix+workerID).Result(); exists != 0 {
+ t.Fatalf("expected drain key removed after SetDraining(false)")
+ }
+ if w := cp.GetWorker(workerID); w == nil || w.Draining {
+ t.Fatalf("expected local cache draining=false, got %+v", w)
+ }
+}
+
+func TestHeartbeatAppliesRedisDrainOverride(t *testing.T) {
+ workerID := fmt.Sprintf("test-drain-heartbeat-%d", time.Now().UnixNano())
+ cp, _ := newTestRegistries(t, workerID)
+
+ // Worker exists, not draining locally.
+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})
+ if w := cp.GetWorker(workerID); w == nil || w.Draining {
+ t.Fatalf("expected initial draining=false, got %+v", w)
+ }
+
+ // External actor sets the drain key directly (e.g. another CP).
+ ctx := context.Background()
+ if err := cp.rdb.Set(ctx, drainKeyPrefix+workerID, "1", drainKeyTTL).Err(); err != nil {
+ t.Fatalf("seeding drain key: %v", err)
+ }
+
+ // Next heartbeat picks up the override.
+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})
+ if w := cp.GetWorker(workerID); w == nil || !w.Draining {
+ t.Fatalf("expected heartbeat to apply drain override, got %+v", w)
+ }
+
+ // Clearing the key in Redis lets the next heartbeat reset draining.
+ if err := cp.rdb.Del(ctx, drainKeyPrefix+workerID).Err(); err != nil {
+ t.Fatalf("deleting drain key: %v", err)
+ }
+ cp.handleHeartbeat(WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50})
+ if w := cp.GetWorker(workerID); w == nil || w.Draining {
+ t.Fatalf("expected heartbeat to clear drain when key removed, got %+v", w)
+ }
+}
+
+func TestSetDrainingPropagatesAcrossControlPlanes(t *testing.T) {
+ workerID := fmt.Sprintf("test-drain-cross-cp-%d", time.Now().UnixNano())
+ cp1, cp2 := newTestRegistries(t, workerID)
+
+ entry := WorkerEntry{ID: workerID, Region: "us-east-1", Capacity: 50}
+ cp1.handleHeartbeat(entry)
+ cp2.handleHeartbeat(entry)
+
+ // Initially neither CP sees the worker as draining.
+ if cp1.GetWorker(workerID).Draining || cp2.GetWorker(workerID).Draining {
+ t.Fatal("neither CP should see drain initially")
+ }
+
+ // Operator hits CP1 with drain. CP1 reflects immediately; CP2 lags until
+ // its next heartbeat.
+ cp1.SetDraining(workerID, true)
+ if !cp1.GetWorker(workerID).Draining {
+ t.Fatal("cp1 should reflect drain immediately on SetDraining")
+ }
+ if cp2.GetWorker(workerID).Draining {
+ t.Fatal("cp2 should not yet reflect drain — its local map hasn't been refreshed")
+ }
+
+ // CP2's next heartbeat for that worker pulls the Redis key and converges.
+ cp2.handleHeartbeat(entry)
+ if !cp2.GetWorker(workerID).Draining {
+ t.Fatal("cp2 should converge to draining after heartbeat reads Redis key")
+ }
+
+ // Operator clears drain via CP2. CP1 converges on its next heartbeat.
+ cp2.SetDraining(workerID, false)
+ if cp2.GetWorker(workerID).Draining {
+ t.Fatal("cp2 should clear drain immediately on SetDraining(false)")
+ }
+ cp1.handleHeartbeat(entry)
+ if cp1.GetWorker(workerID).Draining {
+ t.Fatal("cp1 should converge to not-draining after heartbeat reads cleared key")
+ }
+}
+
+func TestPlacementSkipsDrainingMarkedViaRedis(t *testing.T) {
+ workerID := fmt.Sprintf("test-drain-placement-%d", time.Now().UnixNano())
+ cp, _ := newTestRegistries(t, workerID)
+
+ // Single eligible-looking worker entry.
+ cp.handleHeartbeat(WorkerEntry{
+ ID: workerID,
+ Region: "us-east-1",
+ GRPCAddr: "127.0.0.1:1", // dial will fail async; placement only needs the entry
+ Capacity: 50,
+ Current: 0,
+ MemPct: 10,
+ })
+
+ // Without the drain marker, placement finds the worker (or fails on the
+ // gRPC client lookup, which still proves it passed the eligibility gate).
+ _, _, err := cp.GetLeastLoadedWorker("us-east-1")
+ preDrainNoWorkers := err != nil && err.Error() == "no workers available"
+ if preDrainNoWorkers {
+ t.Fatal("worker should be eligible before drain marker is set")
+ }
+
+ // Set the drain marker via the public API.
+ cp.SetDraining(workerID, true)
+
+ // Now placement should report no workers available.
+ _, _, err = cp.GetLeastLoadedWorker("us-east-1")
+ if err == nil || err.Error() != "no workers available" {
+ t.Fatalf("expected no-workers error after drain, got err=%v", err)
+ }
+}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index 5d7ea706..ded3cf65 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -2,6 +2,7 @@ package controlplane
import (
"context"
+ "errors"
"fmt"
"log"
"sort"
@@ -80,6 +81,13 @@ type ScalerConfig struct {
MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.
MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.
IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.
+
+ // MachineSizes is a ranked list of provider-specific machine sizes the
+ // scaler tries in order on each scale-up. On a quota or capacity error
+ // (compute.ErrQuotaExceeded), the scaler falls through to the next size.
+ // Empty → use the pool's configured default. Non-quota errors fail the
+ // launch immediately without burning the rest of the list.
+ MachineSizes []string
}
// pendingLaunch tracks an EC2 instance that was launched but hasn't registered yet.
@@ -114,6 +122,8 @@ type Scaler struct {
wg sync.WaitGroup
running bool
+ machineSizes []string // ranked list of provider-specific sizes for scale-up fallback
+
// Rolling replacement: version-aware AMI updates
targetWorkerVersion string // desired worker version (from SSM); workers not matching this get replaced
refreshCount int // tick counter for AMI refresh interval
@@ -147,16 +157,17 @@ func NewScaler(cfg ScalerConfig) *Scaler {
}
return &Scaler{
- pool: cfg.Pool,
- registry: cfg.Registry,
- store: cfg.Store,
- state: stateStore,
- image: cfg.WorkerImage,
- cooldown: cooldown,
- interval: interval,
- minWorkers: minWorkers,
- maxWorkers: maxWorkers,
- idleReserve: idleReserve,
+ pool: cfg.Pool,
+ registry: cfg.Registry,
+ store: cfg.Store,
+ state: stateStore,
+ image: cfg.WorkerImage,
+ cooldown: cooldown,
+ interval: interval,
+ minWorkers: minWorkers,
+ maxWorkers: maxWorkers,
+ idleReserve: idleReserve,
+ machineSizes: cfg.MachineSizes,
}
}
@@ -431,12 +442,7 @@ func (s *Scaler) scaleUp(_ context.Context, region string) {
createCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
- opts := compute.MachineOpts{
- Region: region,
- Image: s.image,
- }
-
- machine, err := s.pool.CreateMachine(createCtx, opts)
+ machine, usedSize, err := s.createMachineWithFallback(createCtx, region)
if err != nil {
log.Printf("scaler: failed to create machine in %s: %v", region, err)
s.state.RemovePendingLaunch(region, placeholderID)
@@ -461,10 +467,51 @@ func (s *Scaler) scaleUp(_ context.Context, region string) {
LaunchedAt: time.Now(),
})
s.state.ResetCreationFailures(region)
- log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)
+ if usedSize != "" {
+ log.Printf("scaler: created machine %s in %s (addr=%s, size=%s), pending registration", machine.ID, region, machine.Addr, usedSize)
+ } else {
+ log.Printf("scaler: created machine %s in %s (addr=%s), pending registration", machine.ID, region, machine.Addr)
+ }
}()
}
+// createMachineWithFallback walks the configured ranked size list and returns
+// on the first successful CreateMachine, or after exhausting all sizes. A
+// non-quota error short-circuits the loop — we don't burn through fallbacks
+// on a malformed image ref or a network timeout. usedSize is the size that
+// succeeded (empty when machineSizes is unset and the pool default is used).
+func (s *Scaler) createMachineWithFallback(ctx context.Context, region string) (*compute.Machine, string, error) {
+ sizes := s.machineSizes
+ if len(sizes) == 0 {
+ // Empty Size → pool falls back to its own configured default. Preserves
+ // the pre-fallback behaviour for deployments that haven't opted in.
+ sizes = []string{""}
+ }
+
+ var lastErr error
+ for i, size := range sizes {
+ opts := compute.MachineOpts{
+ Region: region,
+ Image: s.image,
+ Size: size,
+ }
+ machine, err := s.pool.CreateMachine(ctx, opts)
+ if err == nil {
+ return machine, size, nil
+ }
+ lastErr = err
+ if !errors.Is(err, compute.ErrQuotaExceeded) {
+ return nil, "", err
+ }
+ remaining := len(sizes) - i - 1
+ if remaining > 0 {
+ log.Printf("scaler: %s quota/capacity for size=%q, trying next (%d remaining): %v",
+ region, size, remaining, err)
+ }
+ }
+ return nil, "", fmt.Errorf("all %d machine sizes exhausted in %s: %w", len(sizes), region, lastErr)
+}
+
// expirePending removes pending launches that have either registered or timed out.
func (s *Scaler) expirePending(region string) {
pending := s.state.GetPendingLaunches(region)
diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.go
index e606497e..663bed17 100644
--- a/internal/controlplane/scaler_test.go
+++ b/internal/controlplane/scaler_test.go
@@ -2,8 +2,10 @@ package controlplane
import (
"context"
+ "errors"
"fmt"
"math/rand"
+ "reflect"
"sync"
"sync/atomic"
"testing"
@@ -131,6 +133,15 @@ type mockPool struct {
machines map[string]string // machineID -> region
created int32
destroyed int32
+
+ // Test hooks for createMachineWithFallback. createErrs is consumed left to
+ // right: each CreateMachine call pops one entry; if non-nil it's returned
+ // as the error, otherwise the call falls through to the success path.
+ // Once empty the pool always succeeds (preserves prior test behaviour).
+ // attemptedSizes captures opts.Size on every call so tests can assert the
+ // fallback list was walked in order.
+ createErrs []error
+ attemptedSizes []string
}
func newMockPool() *mockPool {
@@ -138,8 +149,17 @@ func newMockPool() *mockPool {
}
func (p *mockPool) CreateMachine(_ context.Context, opts compute.MachineOpts) (*compute.Machine, error) {
- id := fmt.Sprintf("osb-worker-%d", atomic.AddInt32(&p.created, 1))
p.mu.Lock()
+ p.attemptedSizes = append(p.attemptedSizes, opts.Size)
+ if len(p.createErrs) > 0 {
+ err := p.createErrs[0]
+ p.createErrs = p.createErrs[1:]
+ if err != nil {
+ p.mu.Unlock()
+ return nil, err
+ }
+ }
+ id := fmt.Sprintf("osb-worker-%d", atomic.AddInt32(&p.created, 1))
p.machines[id] = opts.Region
p.mu.Unlock()
return &compute.Machine{ID: id, Addr: "10.0.0.1", Region: opts.Region}, nil
@@ -1430,6 +1450,140 @@ func TestPendingLaunchRegistered(t *testing.T) {
}
}
+// ============================================================
+// Test: Machine-size fallback on quota / capacity errors
+// ============================================================
+
+func TestCreateMachineWithFallback_SkipsQuotaErrors(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+ // First two sizes hit quota, third size succeeds.
+ pool.createErrs = []error{
+ errors.Join(compute.ErrQuotaExceeded, errors.New("Standard_D16ads_v7: QuotaExceeded")),
+ errors.Join(compute.ErrQuotaExceeded, errors.New("Standard_D16ds_v6: ZonalAllocationFailed")),
+ nil, // Standard_D16s_v5 — succeeds
+ }
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ MachineSizes: []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"},
+ })
+
+ machine, used, err := s.createMachineWithFallback(context.Background(), "us-east-1")
+ if err != nil {
+ t.Fatalf("expected success after fallback, got error: %v", err)
+ }
+ if machine == nil {
+ t.Fatal("expected machine to be returned")
+ }
+ if used != "Standard_D16s_v5" {
+ t.Errorf("expected last size to win, got %q", used)
+ }
+
+ wantSizes := []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"}
+ if !reflect.DeepEqual(pool.attemptedSizes, wantSizes) {
+ t.Errorf("expected sizes attempted in order %v, got %v", wantSizes, pool.attemptedSizes)
+ }
+}
+
+func TestCreateMachineWithFallback_NonQuotaShortCircuits(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+ // First size fails with a non-quota error — must not iterate further.
+ pool.createErrs = []error{
+ errors.New("network timeout"),
+ nil,
+ nil,
+ }
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ MachineSizes: []string{"Standard_D16ads_v7", "Standard_D16ds_v6", "Standard_D16s_v5"},
+ })
+
+ _, _, err := s.createMachineWithFallback(context.Background(), "us-east-1")
+ if err == nil {
+ t.Fatal("expected error from non-quota failure")
+ }
+ if errors.Is(err, compute.ErrQuotaExceeded) {
+ t.Errorf("non-quota error must not be tagged ErrQuotaExceeded: %v", err)
+ }
+ if len(pool.attemptedSizes) != 1 {
+ t.Errorf("expected exactly one attempt on non-quota error, got %d (%v)",
+ len(pool.attemptedSizes), pool.attemptedSizes)
+ }
+}
+
+func TestCreateMachineWithFallback_AllSizesQuota(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+ pool.createErrs = []error{
+ errors.Join(compute.ErrQuotaExceeded, errors.New("a: QuotaExceeded")),
+ errors.Join(compute.ErrQuotaExceeded, errors.New("b: SkuNotAvailable")),
+ }
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ MachineSizes: []string{"a", "b"},
+ })
+
+ _, _, err := s.createMachineWithFallback(context.Background(), "us-east-1")
+ if err == nil {
+ t.Fatal("expected error when all sizes fail")
+ }
+ if !errors.Is(err, compute.ErrQuotaExceeded) {
+ t.Errorf("expected wrapped ErrQuotaExceeded after exhausting all sizes, got %v", err)
+ }
+ if len(pool.attemptedSizes) != 2 {
+ t.Errorf("expected both sizes attempted, got %d", len(pool.attemptedSizes))
+ }
+}
+
+func TestCreateMachineWithFallback_EmptyListUsesPoolDefault(t *testing.T) {
+ reg := newMockRegistry()
+ pool := newMockPool()
+
+ s := NewScaler(ScalerConfig{
+ Pool: pool,
+ Registry: reg,
+ Cooldown: time.Second,
+ Interval: 100 * time.Millisecond,
+ MinWorkers: 1,
+ MaxWorkers: 20,
+ // MachineSizes intentionally empty — should call CreateMachine once
+ // with empty Size, deferring to the pool's configured default.
+ })
+
+ machine, used, err := s.createMachineWithFallback(context.Background(), "us-east-1")
+ if err != nil {
+ t.Fatalf("expected success, got %v", err)
+ }
+ if machine == nil {
+ t.Fatal("expected machine")
+ }
+ if used != "" {
+ t.Errorf("expected empty usedSize when MachineSizes is unset, got %q", used)
+ }
+ if len(pool.attemptedSizes) != 1 || pool.attemptedSizes[0] != "" {
+ t.Errorf("expected exactly one attempt with empty Size, got %v", pool.attemptedSizes)
+ }
+}
+
// ============================================================
// Test: In-flight migration tracking
// ============================================================
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 6a4acb62..1197782f 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -1213,8 +1213,7 @@ func (m *Manager) buildQEMUArgs(cpus, memMB int, rootfsPath, workspacePath, tapN
// The virtio-mem backend allocates lazily (only requested-size is committed),
// but maxmem must exceed base+pool for QEMU to accept the device.
// Pool = 16GB - base, so any sandbox can scale up to 16GB total regardless of base.
- // Round up to 128MB block alignment.
- virtioMemPoolMB := ((16384 - memMB + 127) / 128) * 128
+ virtioMemPoolMB := alignVirtioMemBlock(16384 - memMB)
if virtioMemPoolMB < 1024 {
virtioMemPoolMB = 1024 // minimum 1GB pool
}
@@ -2001,23 +2000,29 @@ func (m *Manager) SetResourceLimits(ctx context.Context, sandboxID string, maxPi
if additionalMB < 0 {
additionalMB = 0
}
- // Round up to 128MB block size
- additionalMB = ((additionalMB + 127) / 128) * 128
-
- // Check committed memory across all VMs before attempting hotplug.
- // Reserve 20% of host RAM for OS, QEMU overhead, page cache, etc.
+ additionalMB = alignVirtioMemBlock(additionalMB)
+
+ // Check actual host memory before attempting hotplug. Uses real RSS-based
+ // usage (MemTotal - MemAvailable from /proc/meminfo) rather than the
+ // committed sum: a sandbox configured with maxmem=16GB but actually
+ // using 200MB RSS holds 200MB of host RAM, not 16GB. Committed-based
+ // admission rejects grow requests on workers that have plenty of real
+ // headroom — same misleading-signal bug that was already fixed for
+ // migration admission (grpc_server.go PrepareMigrationIncoming).
+ // Reserve 20% of host RAM as a safety margin for OS, QEMU overhead,
+ // page cache, and the burst the grow request itself will pull in.
if additionalMB > vm.virtioMemRequestedMB {
deltaMB := additionalMB - vm.virtioMemRequestedMB
- committedMB := m.totalCommittedMemoryMB()
hostTotalMB := m.hostMemoryMB()
+ hostUsedMB := m.hostUsedMemoryMB()
reserveMB := hostTotalMB / 5 // 20% safety margin
- availableMB := hostTotalMB - committedMB - reserveMB
+ availableMB := hostTotalMB - hostUsedMB - reserveMB
if deltaMB > availableMB {
- log.Printf("qemu: virtio-mem %s: need %dMB but only %dMB available (committed=%dMB, host=%dMB, reserve=%dMB)",
- sandboxID, deltaMB, availableMB, committedMB, hostTotalMB, reserveMB)
- return fmt.Errorf("insufficient_capacity: need %dMB additional but only %dMB available on this worker (committed=%dMB/%dMB)",
- deltaMB, availableMB, committedMB, hostTotalMB)
+ log.Printf("qemu: virtio-mem %s: need %dMB but only %dMB available (used=%dMB, host=%dMB, reserve=%dMB)",
+ sandboxID, deltaMB, availableMB, hostUsedMB, hostTotalMB, reserveMB)
+ return fmt.Errorf("insufficient_capacity: need %dMB additional but only %dMB available on this worker (used=%dMB/%dMB)",
+ deltaMB, availableMB, hostUsedMB, hostTotalMB)
}
}
@@ -2201,6 +2206,21 @@ func (m *Manager) HostUsedMemoryMB() int {
return m.hostUsedMemoryMB()
}
+// virtioMemBlockSizeMB is the QEMU virtio-mem device block size. All plug
+// requests must be a multiple of this — QMP qom-set rejects non-aligned
+// values. Set in -device virtio-mem-pci,block-size=128M; keep them in sync.
+const virtioMemBlockSizeMB = 128
+
+// alignVirtioMemBlock rounds an additional-memory request up to the virtio-mem
+// device's block size so the QMP qom-set call is accepted. Negative or zero
+// inputs return zero.
+func alignVirtioMemBlock(mb int) int {
+ if mb <= 0 {
+ return 0
+ }
+ return ((mb + virtioMemBlockSizeMB - 1) / virtioMemBlockSizeMB) * virtioMemBlockSizeMB
+}
+
// VMActualMemoryMB returns the QEMU process RSS for a sandbox — true physical
// memory the host kernel has backed with RAM. Includes QEMU overhead plus
// faulted-in guest pages. Scaler passes this value to PrepareMigrationIncoming
@@ -2796,8 +2816,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
// memory immediately on resume. Without this, restored processes that were using
// >baseMemMB would OOM before the post-resume re-scale completes.
if desiredMemMB > bootMemMB {
- additionalMB := desiredMemMB - bootMemMB
- additionalMB = ((additionalMB + 127) / 128) * 128 // align to 128MB block size
+ additionalMB := alignVirtioMemBlock(desiredMemMB - bootMemMB)
if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {
log.Printf("qemu: RestoreFromCheckpoint %s: pre-resume scale to %dMB failed: %v (continuing with base %dMB)",
sandboxID, desiredMemMB, err, bootMemMB)
@@ -2853,7 +2872,7 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
vm.CpuCount = bootCpus
vm.baseMemoryMB = bootMemMB
if desiredMemMB > bootMemMB {
- additionalMB := ((desiredMemMB - bootMemMB + 127) / 128) * 128
+ additionalMB := alignVirtioMemBlock(desiredMemMB - bootMemMB)
vm.MemoryMB = bootMemMB + additionalMB
vm.virtioMemRequestedMB = additionalMB
} else {
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index 121e08a9..e2e0b191 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -484,6 +484,26 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return m.coldBootLocal(ctx, sandboxID, timeout)
}
+ // Re-plug virtio-mem to match the pre-hibernate total BEFORE Cont. The VM
+ // is paused, so the kernel sees the full memory map immediately on resume
+ // — without this, restored processes that were using more than baseMem
+ // OOM before any post-resume scale could land. Mirrors the
+ // RestoreFromCheckpoint path (manager.go:2536). Also keeps host-side
+ // accounting honest: vm.MemoryMB stays equal to what's actually plugged,
+ // not the ceiling, so TotalCommittedMemoryMB reflects reality.
+ pluggedMB := 0
+ if meta.MemoryMB > baseMem {
+ additionalMB := alignVirtioMemBlock(meta.MemoryMB - baseMem)
+ if err := qmpClient.SetVirtioMemSize(additionalMB); err != nil {
+ log.Printf("qemu: wake %s: pre-resume virtio-mem plug to %dMB failed: %v (continuing with base %dMB)",
+ sandboxID, additionalMB, err, baseMem)
+ } else {
+ pluggedMB = additionalMB
+ log.Printf("qemu: wake %s: pre-resume virtio-mem plug %dMB (base=%d, total=%d)",
+ sandboxID, additionalMB, baseMem, baseMem+additionalMB)
+ }
+ }
+
if err := qmpClient.Cont(); err != nil {
qmpClient.Close()
cmd.Process.Kill()
@@ -542,16 +562,17 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
}
vm := &VMInstance{
- ID: sandboxID,
- Template: meta.Template,
- Status: types.SandboxStatusRunning,
- StartedAt: now,
- EndAt: now.Add(ttl),
- CpuCount: meta.CpuCount,
- MemoryMB: meta.MemoryMB,
- baseMemoryMB: baseMem,
- HostPort: hostPort,
- GuestPort: netCfg.GuestPort,
+ ID: sandboxID,
+ Template: meta.Template,
+ Status: types.SandboxStatusRunning,
+ StartedAt: now,
+ EndAt: now.Add(ttl),
+ CpuCount: meta.CpuCount,
+ MemoryMB: baseMem + pluggedMB, // actually-plugged total, not the ceiling — keeps committed accounting honest
+ baseMemoryMB: baseMem,
+ virtioMemRequestedMB: pluggedMB,
+ HostPort: hostPort,
+ GuestPort: netCfg.GuestPort,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
diff --git a/internal/qemu/virtio_mem_test.go b/internal/qemu/virtio_mem_test.go
new file mode 100644
index 00000000..04419421
--- /dev/null
+++ b/internal/qemu/virtio_mem_test.go
@@ -0,0 +1,41 @@
+package qemu
+
+import "testing"
+
+func TestAlignVirtioMemBlock(t *testing.T) {
+ tests := []struct {
+ name string
+ in int
+ want int
+ }{
+ {"zero stays zero", 0, 0},
+ {"negative stays zero", -10, 0},
+ {"exactly one block", 128, 128},
+ {"under one block rounds up", 1, 128},
+ {"between blocks rounds up", 200, 256},
+ {"exactly two blocks", 256, 256},
+ {"non-aligned mid-range", 1000, 1024},
+ {"aligned 1GB", 1024, 1024},
+ {"7GB-ish — wake replug case", 7168, 7168},
+ {"7GB-ish minus a hair", 7167, 7168},
+ {"7GB-ish plus a hair", 7169, 7296},
+ // 16GB ceiling — buildQEMUArgs uses 16384-base; test the boundary.
+ {"16GB", 16384, 16384},
+ {"16GB minus base 1024", 16384 - 1024, 15360},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := alignVirtioMemBlock(tc.in)
+ if got != tc.want {
+ t.Errorf("alignVirtioMemBlock(%d) = %d, want %d", tc.in, got, tc.want)
+ }
+ if got > 0 && got%virtioMemBlockSizeMB != 0 {
+ t.Errorf("alignVirtioMemBlock(%d) = %d is not a multiple of block size %d",
+ tc.in, got, virtioMemBlockSizeMB)
+ }
+ if tc.in > 0 && got < tc.in {
+ t.Errorf("alignVirtioMemBlock(%d) = %d, must round up (>= input)", tc.in, got)
+ }
+ })
+ }
+}