An open-source, faster Devin alternative
TypeScript
scheduler: switch migration admission from committed to actual memory
Brian Reardona34ebff4db8b
diff --git a/deploy/packer/round.txt b/deploy/packer/round.txtindex 97b4c0ed..285753ec 100644--- a/deploy/packer/round.txt+++ b/deploy/packer/round.txt@@ -1 +1 @@-round-8+round-9diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 26d194a5..48836951 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -532,6 +532,8 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {CPUPct: w.CPUPct,MemPct: w.MemPct,DiskPct: w.DiskPct,+ TotalMemoryMB: w.TotalMemoryMB,+ CommittedMemoryMB: w.CommittedMemoryMB,GoldenVersion: w.GoldenVersion,WorkerVersion: w.WorkerVersion,})diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 535fd280..7a97e5ae 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -575,8 +575,10 @@ func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []continue}- // Find target: least-loaded worker that isn't the hot one and isn't draining- target := s.findMigrationTarget(region, w.ID)+ // Find target: least-loaded worker that isn't the hot one and isn't draining.+ // Pass 0 for requiredMemMB — evacuateBatch migrates whatever fits; individual+ // over-size sandboxes fail their own prepare and are retried elsewhere.+ target := s.findMigrationTarget(region, w.ID, 0)if target == nil {log.Printf("scaler: worker %s under pressure (cpu=%.1f%% mem=%.1f%% disk=%.1f%%) but no migration target available",w.ID, w.CPUPct, w.MemPct, w.DiskPct)@@ -593,7 +595,20 @@ func (s *Scaler) evacuateHotWorkers(_ context.Context, region string, workers []// findMigrationTarget returns the best worker to receive migrated sandboxes.// Accounts for in-flight migrations so we don't pile onto the same target.-func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfo {+// findMigrationTarget returns the best worker to receive a migrated sandbox.+// requiredMemMB is the real RAM the migration will land (source VM RSS);+// workers whose actual used memory wouldn't leave that much headroom are+// rejected. This mirrors the worker's PrepareMigrationIncoming gate exactly+// so the scaler doesn't pick targets that will then reject the prepare.+// Pass 0 for requiredMemMB to skip the memory check (used by pre-flight+// "does ANY target exist" probes where we don't yet know the sandbox size).+//+// Scheduling on actual (not committed/configured) memory matters: a 16GB-max+// sandbox idling at 200MB RSS consumes 200MB of real host RAM, not 16GB. If+// we scheduled on the configured ceiling, a cluster at 50% committed would+// need 2x the workers of one at 50% actual — expensive dead weight for an+// idle-heavy workload like sandboxes.+func (s *Scaler) findMigrationTarget(region, excludeWorkerID string, requiredMemMB int32) *WorkerInfo {workers := s.registry.GetWorkersByRegion(region)var best *WorkerInfo@@ -611,6 +626,16 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string) *WorkerInfoif remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 || w.DiskPct > 85 {continue}+ // Actual-memory check. Uses host's real used RAM (derived from MemPct)+ // with a 10% safety margin — matches the worker's admission formula.+ if requiredMemMB > 0 && w.TotalMemoryMB > 0 {+ actualUsedMB := int(w.MemPct * float64(w.TotalMemoryMB) / 100)+ reserveMB := w.TotalMemoryMB / 10+ availableMB := w.TotalMemoryMB - actualUsedMB - reserveMB+ if int(requiredMemMB) > availableMB {+ continue+ }+ }resourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0 * (100.0 - w.DiskPct) / 100.0score := float64(remaining) * resourceScoreif score > bestScore {@@ -865,16 +890,42 @@ func (s *Scaler) drainWorker(workerID, machineID, region string) {continue}- // Find target for this batch- target := s.findMigrationTarget(region, workerID)- if target == nil {- log.Printf("scaler: drain: no migration target for %s (%d sandboxes), waiting for natural expiry", workerID, len(running))+ // Pre-flight: is there ANY viable target in the region? We don't yet+ // know the sandbox memory sizes (those come from PreCopyDrives inside+ // liveMigrateSandbox), so pass 0 — this just confirms a non-draining+ // worker exists with slot capacity. Per-sandbox memory fit is checked+ // later by liveMigrateSandbox using the real sandbox size.+ //+ // If no target exists and we're under maxWorkers, proactively scale+ // up. This covers the case where committed memory is saturated on+ // every existing target but actual CPU/RAM usage is low, so the+ // utilization-based scale-up path in Evaluate() won't trigger.+ if probe := s.findMigrationTarget(region, workerID, 0); probe == nil {+ effective := 0+ for _, w := range s.registry.GetWorkersByRegion(region) {+ if !s.state.IsDraining(w.MachineID) {+ effective+++ }+ }+ pending := len(s.state.GetPendingLaunches(region))+ if effective+pending < s.maxWorkers {+ log.Printf("scaler: drain: no migration target for %s (%d sandboxes), triggering scale-up", workerID, len(running))+ s.scaleUp(ctx, region)+ select {+ case <-ctx.Done():+ return+ case <-time.After(60 * time.Second):+ }+ continue+ }+ log.Printf("scaler: drain: no migration target for %s (%d sandboxes) and at max workers (%d), waiting for natural expiry", workerID, len(running), s.maxWorkers)s.waitForNaturalDrain(ctx, workerID)return}// Migrate a batch — bounded parallelism to avoid overwhelming- // network/disk on source and target workers.+ // network/disk on source and target workers. Each sandbox picks its+ // own target (based on its own memory footprint) inside liveMigrateSandbox.batch := runningif len(batch) > evacuationBatchSize {batch = batch[:evacuationBatchSize]@@ -887,8 +938,8 @@ func (s *Scaler) drainWorker(workerID, machineID, region string) {wg.Add(1)go func(sbID string) {defer wg.Done()- if err := s.liveMigrateSandbox(ctx, sbID, workerID, target.ID); err != nil {- log.Printf("scaler: drain: migrate %s to %s failed: %v", sbID, target.ID, err)+ if err := s.liveMigrateSandbox(ctx, sbID, workerID, ""); err != nil {+ log.Printf("scaler: drain: migrate %s failed: %v", sbID, err)atomic.AddInt64(&failCount, 1)}}(sandboxID)@@ -1077,6 +1128,12 @@ func (s *Scaler) getWorkerInfo(workerID string) *WorkerInfo {// liveMigrateSandbox performs a full live migration of a sandbox between workers.// Steps: pre-copy drives to S3 → prepare target → QMP migrate → complete → update DB.+//+// If targetWorkerID is empty, a target is picked after pre-copy using the+// sandbox's actual memory footprint (so an oversize sandbox doesn't get+// routed to a worker that can only reserve 4GB). Callers that need to force+// a specific destination (e.g. evacuateBatch, which uses a pre-scored+// target for the whole batch) pass it explicitly.func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerID, targetWorkerID string) error {// Prevent double-migrateif !s.state.AcquireMigrationLock(sandboxID) {@@ -1084,36 +1141,17 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker}defer s.state.ReleaseMigrationLock(sandboxID)- // Mark sandbox as migrating in DB — blocks exec routing during migration- migrationCompleted := false- if s.store != nil {- if err := s.store.SetMigrating(ctx, sandboxID, targetWorkerID); err != nil {- log.Printf("scaler: failed to set migrating state for %s: %v", sandboxID, err)- }- defer func() {- if !migrationCompleted && s.store != nil {- s.store.FailMigration(ctx, sandboxID)- }- }()- }-- // Track in-flight migration to target so other evacuations don't pile on- s.state.IncrInFlight(targetWorkerID)- defer s.state.DecrInFlight(targetWorkerID)-sourceClient, err := s.registry.GetWorkerClient(sourceWorkerID)if err != nil {return fmt.Errorf("source worker %s unreachable: %w", sourceWorkerID, err)}- targetClient, err := s.registry.GetWorkerClient(targetWorkerID)- if err != nil {- return fmt.Errorf("target worker %s unreachable: %w", targetWorkerID, err)- }t0 := time.Now()// Step 1: Pre-copy drives to S3 (source uploads thin overlay — never flattens).// Target worker rebases to its own base if golden versions differ.+ // Pre-copy before target selection — we need BaseMemoryMb from the+ // response to pick a target that can actually reserve that much.preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 10*time.Minute)defer preCopyCancel()preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{@@ -1166,6 +1204,57 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker}}+ // Real RAM the migration will land on the target = source VM's current+ // RSS (reported by PreCopyDrives). Fall back to the configured base+ // memory if the source is an older worker that doesn't report RSS.+ // Final safety floor: 256MB (QEMU overhead alone).+ actualMemMB := preCopyResp.ActualMemoryMb+ if actualMemMB == 0 {+ actualMemMB = memoryMB+ }+ if actualMemMB < 256 {+ actualMemMB = 256+ }++ // Target selection: if caller didn't pre-pick, find a worker with enough+ // actual-memory headroom for this sandbox's real footprint. Must happen+ // after PreCopyDrives so we know the RSS.+ if targetWorkerID == "" {+ srcInfo := s.getWorkerInfo(sourceWorkerID)+ if srcInfo == nil {+ return fmt.Errorf("source worker %s not in registry", sourceWorkerID)+ }+ target := s.findMigrationTarget(srcInfo.Region, sourceWorkerID, actualMemMB)+ if target == nil {+ return fmt.Errorf("no viable migration target in %s for %dMB actual-RSS sandbox", srcInfo.Region, actualMemMB)+ }+ targetWorkerID = target.ID+ }++ targetClient, err := s.registry.GetWorkerClient(targetWorkerID)+ if err != nil {+ return fmt.Errorf("target worker %s unreachable: %w", targetWorkerID, err)+ }++ // Mark sandbox as migrating in DB — blocks exec routing during migration.+ // Must happen after target selection because the DB row records the+ // destination worker.+ migrationCompleted := false+ if s.store != nil {+ if err := s.store.SetMigrating(ctx, sandboxID, targetWorkerID); err != nil {+ log.Printf("scaler: failed to set migrating state for %s: %v", sandboxID, err)+ }+ defer func() {+ if !migrationCompleted && s.store != nil {+ s.store.FailMigration(ctx, sandboxID)+ }+ }()+ }++ // Track in-flight migration to target so other evacuations don't pile on.+ s.state.IncrInFlight(targetWorkerID)+ defer s.state.DecrInFlight(targetWorkerID)+prepCtx, prepCancel := context.WithTimeout(ctx, 10*time.Minute)defer prepCancel()prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{@@ -1178,7 +1267,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerWorkspaceS3Key: preCopyResp.WorkspaceKey,OverlayMode: true,SourceGoldenVersion: sourceGoldenVersion,- TargetMemoryMb: 4096,+ TargetMemoryMb: actualMemMB,})if err != nil {return fmt.Errorf("prepare target: %w", err)diff --git a/internal/controlplane/scaler_test.go b/internal/controlplane/scaler_test.goindex 39a1479f..b1d32718 100644--- a/internal/controlplane/scaler_test.go+++ b/internal/controlplane/scaler_test.go@@ -646,7 +646,7 @@ func TestFindMigrationTargetSelectsLeastLoaded(t *testing.T) {})s := newTestScaler(reg, pool)- target := s.findMigrationTarget("us-east-1", "hot")+ target := s.findMigrationTarget("us-east-1", "hot", 0)if target == nil {t.Fatal("expected a migration target")@@ -671,7 +671,7 @@ func TestFindMigrationTargetSkipsPressuredWorkers(t *testing.T) {})s := newTestScaler(reg, pool)- target := s.findMigrationTarget("us-east-1", "hot")+ target := s.findMigrationTarget("us-east-1", "hot", 0)if target != nil {t.Errorf("expected no target (all workers under pressure), got %s", target.ID)@@ -694,7 +694,7 @@ func TestFindMigrationTargetSkipsDraining(t *testing.T) {s := newTestScaler(reg, pool)s.state.SetDraining("osb-worker-draining", &drainState{WorkerID: "draining"})- target := s.findMigrationTarget("us-east-1", "hot")+ target := s.findMigrationTarget("us-east-1", "hot", 0)if target != nil {t.Errorf("expected no target (only candidate is draining), got %s", target.ID)}@@ -725,7 +725,7 @@ func TestFindMigrationTargetAccountsForInFlight(t *testing.T) {s.state.IncrInFlight("target1")}- target := s.findMigrationTarget("us-east-1", "source")+ target := s.findMigrationTarget("us-east-1", "source", 0)if target == nil {t.Fatal("expected a migration target")}@@ -749,13 +749,74 @@ func TestFindMigrationTargetSkipsHighDisk(t *testing.T) {})s := newTestScaler(reg, pool)- target := s.findMigrationTarget("us-east-1", "source")+ target := s.findMigrationTarget("us-east-1", "source", 0)if target != nil {t.Errorf("expected no target (only candidate has disk > 85%%), got %s", target.ID)}}+// TestFindMigrationTargetSkipsWorkerShortOnActualMemory verifies that a+// worker is rejected when its actual memory (MemPct × TotalMemoryMB) plus+// the migration's requiredMemMB exceeds the 90% admission line. Without+// this, the scaler picks a target whose prepare will fail and the drain+// churns in a retry loop.+func TestFindMigrationTargetSkipsWorkerShortOnActualMemory(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ reg.addWorker(&WorkerInfo{+ ID: "source", MachineID: "osb-worker-source", Region: "us-east-1",+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,+ TotalMemoryMB: 64000,+ })+ // 60% actual used × 64GB = 38.4GB used. Reserve 6.4GB. Available ≈ 19.2GB.+ // 16GB should fit, 22GB should not.+ reg.addWorker(&WorkerInfo{+ ID: "ok", MachineID: "osb-worker-ok", Region: "us-east-1",+ Capacity: 50, Current: 5, CPUPct: 30, MemPct: 60, DiskPct: 20,+ TotalMemoryMB: 64000,+ })++ s := newTestScaler(reg, pool)++ target := s.findMigrationTarget("us-east-1", "source", 16000)+ if target == nil || target.ID != "ok" {+ t.Fatalf("expected 'ok' for 16GB request, got %v", target)+ }++ target = s.findMigrationTarget("us-east-1", "source", 22000)+ if target != nil {+ t.Errorf("expected no target for 22GB request (insufficient actual headroom), got %s", target.ID)+ }+}++// TestFindMigrationTargetZeroRequiredMemSkipsCheck verifies that passing 0+// for requiredMemMB disables the actual-memory gate — this is used by the+// drain loop's pre-flight "does ANY target exist" probe before we know+// the sandbox size.+func TestFindMigrationTargetZeroRequiredMemSkipsCheck(t *testing.T) {+ reg := newMockRegistry()+ pool := newMockPool()++ reg.addWorker(&WorkerInfo{+ ID: "source", MachineID: "osb-worker-source", Region: "us-east-1",+ Capacity: 50, Current: 45, CPUPct: 85, MemPct: 50, DiskPct: 30,+ })+ // Would fail a memory check (80% used), but slot/pressure checks pass.+ reg.addWorker(&WorkerInfo{+ ID: "candidate", MachineID: "osb-worker-candidate", Region: "us-east-1",+ Capacity: 50, Current: 5, CPUPct: 30, MemPct: 80, DiskPct: 20,+ TotalMemoryMB: 64000,+ })++ s := newTestScaler(reg, pool)+ target := s.findMigrationTarget("us-east-1", "source", 0)+ if target == nil || target.ID != "candidate" {+ t.Errorf("expected 'candidate' with 0 requiredMemMB (pre-flight), got %v", target)+ }+}+// ============================================================// Test: Drain timeout → hibernate// ============================================================@@ -966,7 +1027,7 @@ func TestConcurrentScaleUpDown200(t *testing.T) {// Query state (read contention)_ = reg.RegionUtilization("us-east-1")_, _, _ = reg.RegionResourcePressure("us-east-1")- _ = s.findMigrationTarget("us-east-1", "nonexistent")+ _ = s.findMigrationTarget("us-east-1", "nonexistent", 0)}time.Sleep(time.Duration(rng.Intn(5)) * time.Millisecond)@@ -1240,7 +1301,7 @@ func TestInFlightTrackingPreventsOverload(t *testing.T) {s.state.IncrInFlight("target")}- target := s.findMigrationTarget("us-east-1", "other")+ target := s.findMigrationTarget("us-east-1", "other", 0)if target != nil {t.Error("expected no target — in-flight migrations fill remaining capacity")}diff --git a/internal/controlplane/worker_registry.go b/internal/controlplane/worker_registry.goindex 6bed9e81..7dc9e77f 100644--- a/internal/controlplane/worker_registry.go+++ b/internal/controlplane/worker_registry.go@@ -23,6 +23,8 @@ type WorkerInfo struct {CPUPct float64 `json:"cpu_pct"`MemPct float64 `json:"mem_pct"`DiskPct float64 `json:"disk_pct"`+ TotalMemoryMB int `json:"total_memory_mb,omitempty"`+ CommittedMemoryMB int `json:"committed_memory_mb,omitempty"`GoldenVersion string `json:"golden_version,omitempty"`WorkerVersion string `json:"worker_version,omitempty"`LastSeen time.Time `json:"-"`diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex b5492dd2..9dd1cd02 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1905,6 +1905,71 @@ func (m *Manager) hostMemoryMB() int {return 64 * 1024}+// hostUsedMemoryMB returns actual host memory in use (MemTotal − MemAvailable).+// MemAvailable already discounts reclaimable caches/buffers, so this is the+// honest number for "RAM the kernel really can't hand out without reclaiming."+// Used for actual-memory-based migration scheduling in place of committed+// tracking (which over-reserves for idle sandboxes with large maxmem).+func (m *Manager) hostUsedMemoryMB() int {+ data, err := os.ReadFile("/proc/meminfo")+ if err != nil {+ return 0+ }+ var totalKB, availKB int+ for _, line := range strings.Split(string(data), "\n") {+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ switch fields[0] {+ case "MemTotal:":+ totalKB, _ = strconv.Atoi(fields[1])+ case "MemAvailable:":+ availKB, _ = strconv.Atoi(fields[1])+ }+ }+ if totalKB == 0 {+ return 0+ }+ return (totalKB - availKB) / 1024+}++// HostUsedMemoryMB exposes used memory for the capacity checker interface.+func (m *Manager) HostUsedMemoryMB() int {+ return m.hostUsedMemoryMB()+}++// 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+// so the target reserves what will really land, not the configured maximum.+func (m *Manager) VMActualMemoryMB(sandboxID string) int {+ m.mu.RLock()+ vm, ok := m.vms[sandboxID]+ m.mu.RUnlock()+ if !ok || vm.pid == 0 {+ return 0+ }+ return readProcRSSMB(vm.pid)+}++func readProcRSSMB(pid int) int {+ data, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", pid))+ if err != nil {+ return 0+ }+ for _, line := range strings.Split(string(data), "\n") {+ if strings.HasPrefix(line, "VmRSS:") {+ fields := strings.Fields(line)+ if len(fields) >= 2 {+ kb, _ := strconv.Atoi(fields[1])+ return kb / 1024+ }+ }+ }+ return 0+}+// Stats returns live resource usage from the VM.func (m *Manager) Stats(ctx context.Context, sandboxID string) (*sandbox.SandboxStats, error) {vm, err := m.getReadyVM(ctx, sandboxID)diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex d9751902..b5a680f3 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -574,16 +574,22 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin// Always uploads the thin overlay (never flattens). The target worker rebases// to its own base image if golden versions differ.// Returns S3 keys, golden version, and base CPU/memory for QEMU matching.-func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVer string, baseCPU, baseMem int, err error) {+func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVer string, baseCPU, baseMem, actualMem int, err error) {m.mu.RLock()vm, exists := m.vms[sandboxID]+ var pid intif exists {goldenVer = vm.goldenVersionbaseCPU = vm.CpuCountbaseMem = vm.baseMemoryMB+ pid = vm.pid}m.mu.RUnlock()+ if pid > 0 {+ actualMem = readProcRSSMB(pid)+ }+mc := &MigrationCoordinator{manager: m,checkpointStore: checkpointStore,diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex a5cf7bf3..c11e2103 100644--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@ -34,15 +34,21 @@ import (type LiveMigrator interface {PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error)PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string) (incomingAddr string, hostPort int, err error)- PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVersion string, baseCPU, baseMem int, err error)+ PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVersion string, baseCPU, baseMem, actualMem int, err error)CompleteIncomingMigration(ctx context.Context, sandboxID string) errorLiveMigrate(ctx context.Context, sandboxID, incomingAddr string) error}// CapacityChecker is implemented by VM managers that can report memory capacity.+// HostUsedMemoryMB reflects actual RAM pressure on the host (MemTotal−MemAvailable)+// and is the basis for migration admission control. TotalCommittedMemoryMB is kept+// for observability but is NOT used to gate scheduling any longer — committed+// over-reserves for idle sandboxes with large maxmem ceilings, forcing the+// cluster to over-provision workers for the same real workload.type CapacityChecker interface {TotalCommittedMemoryMB() intHostMemoryMB() int+ HostUsedMemoryMB() int}// GoldenRebuilder is implemented by VM managers that support golden snapshot rebuild.@@ -966,16 +972,17 @@ func (s *GRPCServer) PreCopyDrives(ctx context.Context, req *pb.PreCopyDrivesReqif s.migrator == nil {return nil, fmt.Errorf("live migration not supported on this worker")}- rootfsKey, workspaceKey, goldenVersion, baseCPU, baseMem, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore)+ rootfsKey, workspaceKey, goldenVersion, baseCPU, baseMem, actualMem, err := s.migrator.PreCopyDrives(ctx, req.SandboxId, s.checkpointStore)if err != nil {return nil, fmt.Errorf("pre-copy drives: %w", err)}return &pb.PreCopyDrivesResponse{- RootfsKey: rootfsKey,- WorkspaceKey: workspaceKey,- GoldenVersion: goldenVersion,- BaseMemoryMb: int32(baseMem),- BaseCpuCount: int32(baseCPU),+ RootfsKey: rootfsKey,+ WorkspaceKey: workspaceKey,+ GoldenVersion: goldenVersion,+ BaseMemoryMb: int32(baseMem),+ BaseCpuCount: int32(baseCPU),+ ActualMemoryMb: int32(actualMem),}, nil}@@ -984,17 +991,22 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepareturn nil, fmt.Errorf("live migration not supported on this worker")}- // If target_memory_mb is set, check capacity before creating the target QEMU.- // This prevents multiple concurrent migrations from overcommitting this worker.+ // Capacity guard — actual-memory-based. The caller passes the source VM's+ // current RSS as TargetMemoryMb (i.e., the physical RAM the migration will+ // really land on this host). We admit if that fits inside free host+ // memory after a 10% safety margin. This replaces committed-memory+ // admission: committed over-reserved for idle sandboxes with large+ // maxmem ceilings, which caused drains to stall on workers that had+ // plenty of real headroom.if req.TargetMemoryMb > 0 {if cc, ok := s.manager.(CapacityChecker); ok {- committedMB := cc.TotalCommittedMemoryMB()hostTotalMB := cc.HostMemoryMB()- reserveMB := hostTotalMB / 5- availableMB := hostTotalMB - committedMB - reserveMB+ hostUsedMB := cc.HostUsedMemoryMB()+ reserveMB := hostTotalMB / 10+ availableMB := hostTotalMB - hostUsedMB - reserveMBif int(req.TargetMemoryMb) > availableMB {- return nil, fmt.Errorf("insufficient_capacity: migration target needs %dMB but only %dMB available (committed=%dMB/%dMB)",- req.TargetMemoryMb, availableMB, committedMB, hostTotalMB)+ return nil, fmt.Errorf("insufficient_capacity: migration target needs %dMB but only %dMB actual available (used=%dMB/%dMB)",+ req.TargetMemoryMb, availableMB, hostUsedMB, hostTotalMB)}}}diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex 48097568..1a6a3e0a 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -2780,8 +2780,13 @@ type PreCopyDrivesResponse struct {GoldenVersion string `protobuf:"bytes,3,opt,name=golden_version,json=goldenVersion,proto3" json:"golden_version,omitempty"` // golden version the sandbox was created fromBaseMemoryMb int32 `protobuf:"varint,4,opt,name=base_memory_mb,json=baseMemoryMb,proto3" json:"base_memory_mb,omitempty"` // QEMU -m value from source (target must match for migration)BaseCpuCount int32 `protobuf:"varint,5,opt,name=base_cpu_count,json=baseCpuCount,proto3" json:"base_cpu_count,omitempty"` // QEMU -smp value from source (target must match for migration)- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ // actual_memory_mb is the source QEMU process's current RSS in MB — a true+ // measure of how much host RAM the migration will land on the target.+ // Used for actual-memory-based scheduling instead of committed/configured+ // memory (which over-reserves on idle sandboxes).+ ActualMemoryMb int32 `protobuf:"varint,6,opt,name=actual_memory_mb,json=actualMemoryMb,proto3" json:"actual_memory_mb,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PreCopyDrivesResponse) Reset() {@@ -2849,6 +2854,13 @@ func (x *PreCopyDrivesResponse) GetBaseCpuCount() int32 {return 0}+func (x *PreCopyDrivesResponse) GetActualMemoryMb() int32 {+ if x != nil {+ return x.ActualMemoryMb+ }+ return 0+}+type PrepareMigrationIncomingRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`@@ -3524,14 +3536,15 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x18SetSandboxLimitsResponse\";\n" +"\x14PreCopyDrivesRequest\x12\x1d\n" +"\n" +- "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xce\x01\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xf8\x01\n" +"\x15PreCopyDrivesResponse\x12\x1d\n" +"\n" +"rootfs_key\x18\x01 \x01(\tR\trootfsKey\x12#\n" +"\rworkspace_key\x18\x02 \x01(\tR\fworkspaceKey\x12%\n" +"\x0egolden_version\x18\x03 \x01(\tR\rgoldenVersion\x12$\n" +"\x0ebase_memory_mb\x18\x04 \x01(\x05R\fbaseMemoryMb\x12$\n" +- "\x0ebase_cpu_count\x18\x05 \x01(\x05R\fbaseCpuCount\"\xcc\x03\n" ++ "\x0ebase_cpu_count\x18\x05 \x01(\x05R\fbaseCpuCount\x12(\n" ++ "\x10actual_memory_mb\x18\x06 \x01(\x05R\x0eactualMemoryMb\"\xcc\x03\n" +"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +diff --git a/proto/worker/worker.proto b/proto/worker/worker.protoindex 370212ea..12a2d216 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -331,6 +331,11 @@ message PreCopyDrivesResponse {string golden_version = 3; // golden version the sandbox was created fromint32 base_memory_mb = 4; // QEMU -m value from source (target must match for migration)int32 base_cpu_count = 5; // QEMU -smp value from source (target must match for migration)+ // actual_memory_mb is the source QEMU process's current RSS in MB — a true+ // measure of how much host RAM the migration will land on the target.+ // Used for actual-memory-based scheduling instead of committed/configured+ // memory (which over-reserves on idle sandboxes).+ int32 actual_memory_mb = 6;}message PrepareMigrationIncomingRequest {