Skip to content

An open-source, faster Devin alternative

TypeScript

serial migrations, in flight guard, prevent zombie ticks

Brian Reardon213fc5fbbd59
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 63a6c113..cd67963e 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -183,7 +183,10 @@ func main() {
log.Printf("opensandbox: sandbox domain configured (%s)", cfg.SandboxDomain)
}
- // Initialize Redis worker registry in server mode
+ // Initialize Redis worker registry in server mode. The scaler reference
+ // is hoisted to outer scope so the API server can be wired with it later
+ // for the migrate endpoint (see server.SetMigrator below).
+ var scalerOrchestrator *controlplane.Scaler
var redisRegistry *controlplane.RedisWorkerRegistry
if cfg.Mode == "server" && cfg.RedisURL != "" {
var err error
@@ -500,6 +503,11 @@ func main() {
}
scalerState := controlplane.NewRedisScalerState(redisRegistry.RedisClient())
+ // Note: this scaler is also exposed via scalerOrchestrator so the
+ // API server can wire it (server.SetMigrator) below. POST
+ // /api/sandboxes/:id/migrate then flows through the same
+ // per-target-serialized, in-flight-tracked, abort-cleaned-up
+ // code path as the scaler's drain.
scaler := controlplane.NewScaler(controlplane.ScalerConfig{
Pool: pool,
Registry: redisRegistry,
@@ -520,6 +528,7 @@ func main() {
CellID: cfg.CellID,
})
defer scaler.Stop()
+ scalerOrchestrator = scaler
// Leader election: only the leader runs the scaler. The
// per-sandbox autoscaler (created later) consults this same
@@ -626,6 +635,14 @@ func main() {
// Token never leaves this process; the UI proxies its queries through
// /api/sandboxes/:id/logs. Empty token disables the endpoint (503).
server.SetAxiomQueryConfig(cfg.AxiomQueryToken, cfg.AxiomDataset)
+
+ // Wire the scaler as the API's migration orchestrator. nil-safe — when
+ // the scaler isn't running (combined mode, no pool) the migrate endpoint
+ // returns 503 instead of routing through the old duplicated inline path.
+ if scalerOrchestrator != nil {
+ server.SetMigrator(scalerOrchestrator)
+ log.Printf("opensandbox: migrate API wired to scaler orchestrator (shared per-target serialization)")
+ }
if cfg.AxiomQueryToken != "" {
log.Printf("opensandbox: sandbox session logs read API enabled (dataset=%s)", cfg.AxiomDataset)
}
diff --git a/internal/api/router.go b/internal/api/router.go
index bb591619..17a7007b 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -78,6 +78,26 @@ type Server struct {
// single-PG mode or tests); resolveSecretStoreInto + template lookup fall
// back to s.store in that case.
edge *edgeclient.Client
+
+ // migrator delegates live-migration to the scaler's orchestrator so the
+ // API path (POST /api/sandboxes/:id/migrate) shares the per-target
+ // serialization + abort-on-failure cleanup the scaler uses for drains.
+ // nil disables the migrate endpoint (returns 503).
+ migrator MigrationOrchestrator
+}
+
+// MigrationOrchestrator is the slice of the scaler the API needs to delegate
+// migration requests to. Defined as an interface here (rather than importing
+// the concrete *controlplane.Scaler) so the API package stays test-friendly
+// and the dependency direction is API → interface ← controlplane.
+type MigrationOrchestrator interface {
+ LiveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerID, targetWorkerID string) error
+}
+
+// SetMigrator wires the scaler-backed migration orchestrator. Called from
+// cmd/server/main.go after the scaler is constructed.
+func (s *Server) SetMigrator(m MigrationOrchestrator) {
+ s.migrator = m
}
// SetEdgeClient wires the api-edge HTTP client. Caller is responsible for
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index fb170331..3633e94e 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1059,6 +1059,14 @@ func (s *Server) setTimeout(c echo.Context) error {
// migrateSandbox performs live migration of a sandbox to a different worker.
// POST /api/sandboxes/:id/migrate {"targetWorker": "w-azure-osb-worker-xxx"}
+//
+// Delegates to the scaler's LiveMigrateSandbox so the user-driven API path
+// shares the same per-target serialization, in-flight tracking, abort-on-
+// failure cleanup, and source/target consistency guarantees as the scaler's
+// drain path. Previously this handler had its own inline copy of the
+// migration sequence that bypassed all those protections, meaning a user
+// firing parallel /migrate calls at a single target could OOM-kill the
+// target worker the same way the parallel-drain cascade did.
func (s *Server) migrateSandbox(c echo.Context) error {
id := c.Param("id")
ctx := c.Request().Context()
@@ -1073,6 +1081,9 @@ func (s *Server) migrateSandbox(c echo.Context) error {
if s.workerRegistry == nil || s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "migration requires server mode with worker registry"})
}
+ if s.migrator == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "migration orchestrator not configured (scaler missing)"})
+ }
// Look up sandbox to find source worker
session, err := s.store.GetSandboxSession(ctx, id)
@@ -1083,137 +1094,16 @@ func (s *Server) migrateSandbox(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandbox must be running to migrate"})
}
- // Mark as migrating — blocks exec/proxy routing until migration completes
- migrationDone := false
- if s.store != nil {
- if err := s.store.SetMigrating(ctx, id, req.TargetWorker); err != nil {
- log.Printf("migrate %s: failed to set migrating state: %v", id, err)
- }
- // Guarantee we revert on failure
- defer func() {
- if !migrationDone && s.store != nil {
- s.store.FailMigration(ctx, id)
- }
- }()
- }
-
- // Get source and target worker gRPC clients
- sourceClient, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
- if err != nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "source worker unreachable: " + err.Error()})
- }
- targetClient, err := s.workerRegistry.GetWorkerClient(req.TargetWorker)
- if err != nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "target worker unreachable: " + err.Error()})
- }
-
t0 := time.Now()
-
- // Step 1: Pre-copy drives to S3 (thin overlay, never flatten).
- preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 10*time.Minute)
- defer preCopyCancel()
- preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{
- SandboxId: id,
- })
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "pre-copy drives: " + err.Error()})
- }
-
- if preCopyResp.GoldenVersion == "" {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "source sandbox has no goldenVersion — cannot live migrate safely; use hibernate/wake instead"})
- }
-
- log.Printf("migrate %s: drives pre-copied to S3 (%dms, golden=%s)", id, time.Since(t0).Milliseconds(), preCopyResp.GoldenVersion)
-
- // Step 2: Prepare target (downloads thin overlay, rebases if needed, starts QEMU -incoming).
- // CPU and memory come from the source worker — must match exactly for QEMU migration.
- cpuCount := preCopyResp.BaseCpuCount
- memoryMB := preCopyResp.BaseMemoryMb
- if cpuCount == 0 {
- cpuCount = 2
- }
- if memoryMB == 0 {
- memoryMB = 1024
- }
-
- prepCtx, prepCancel := context.WithTimeout(ctx, 10*time.Minute)
- defer prepCancel()
- prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{
- SandboxId: id,
- CpuCount: cpuCount,
- MemoryMb: memoryMB,
- GuestPort: 80,
- Template: session.Template,
- RootfsS3Key: preCopyResp.RootfsKey,
- WorkspaceS3Key: preCopyResp.WorkspaceKey,
- OverlayMode: true,
- SourceGoldenVersion: preCopyResp.GoldenVersion,
- // Carry the secrets-proxy session from source → target. Without
- // this the destination has no substitution map and outbound HTTPS
- // from the migrated VM would leak `osb_sealed_xxx` env vars
- // verbatim to upstream services. Empty when no secret store.
- SealedTokens: preCopyResp.SealedTokens,
- EgressAllowlist: preCopyResp.EgressAllowlist,
- TokenHosts: preCopyResp.TokenHosts,
- SealedNames: preCopyResp.SealedNames,
- })
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "prepare target: " + err.Error()})
- }
-
- log.Printf("migrate %s: target prepared at %s (host port %d, secrets=%d)", id, prepResp.IncomingAddr, prepResp.HostPort, len(preCopyResp.SealedTokens))
-
- // Step 3: Live migrate from source to target
- migrateCtx, migrateCancel := context.WithTimeout(ctx, 5*time.Minute)
- defer migrateCancel()
- _, err = sourceClient.LiveMigrate(migrateCtx, &pb.LiveMigrateRequest{
- SandboxId: id,
- IncomingAddr: prepResp.IncomingAddr,
- })
- if err != nil {
- cleanCtx, cleanCancel := context.WithTimeout(context.Background(), 10*time.Second)
- targetClient.DestroySandbox(cleanCtx, &pb.DestroySandboxRequest{SandboxId: id})
- cleanCancel()
- log.Printf("migrate %s: live migrate failed, cleaned up target on %s: %v", id, req.TargetWorker, err)
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "live migrate: " + err.Error()})
- }
-
- log.Printf("migrate %s: QMP migration complete (%dms)", id, time.Since(t0).Milliseconds())
-
- // Step 4: Complete migration on target (reconnect agent, patch network)
- completeCtx, completeCancel := context.WithTimeout(ctx, 30*time.Second)
- defer completeCancel()
- _, err = targetClient.CompleteMigrationIncoming(completeCtx, &pb.CompleteMigrationIncomingRequest{
- SandboxId: id,
- })
- if err != nil {
- cleanCtx, cleanCancel := context.WithTimeout(context.Background(), 10*time.Second)
- targetClient.DestroySandbox(cleanCtx, &pb.DestroySandboxRequest{SandboxId: id})
- cleanCancel()
- log.Printf("migrate %s: complete failed, cleaned up target on %s: %v", id, req.TargetWorker, err)
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "complete migration: " + err.Error()})
- }
-
- // Step 5: Complete migration — update DB status and worker_id atomically.
- // Use background context — the request context may be close to expiry for large migrations.
- if s.store != nil {
- completeDBCtx, completeDBCancel := context.WithTimeout(context.Background(), 10*time.Second)
- if err := s.store.CompleteMigration(completeDBCtx, id, req.TargetWorker); err != nil {
- log.Printf("migrate %s: WARNING: CompleteMigration DB update failed: %v", id, err)
- }
- completeDBCancel()
- // Mirror to D1 sandboxes_index so the dashboard's cross-cell view and
- // the proxyToCellSDK routing reflect the new worker immediately. The
- // new worker's `created` event would eventually sync it, but emitting
- // here closes the window where stale routing would re-target the
- // vanished source worker. Reads org from the existing session.
- if session, err := s.store.GetSandboxSession(context.Background(), id); err == nil {
- s.publishSandboxLifecycleEvent(context.Background(), "migrated", id, session.OrgID, req.TargetWorker, "user_migrate")
- }
+ if err := s.migrator.LiveMigrateSandbox(ctx, id, session.WorkerID, req.TargetWorker); err != nil {
+ // LiveMigrateSandbox sets cell-PG state on failure (FailMigration /
+ // FailMigrationPostQMP) and emits the relevant stopped/migrated D1
+ // event itself. Don't double-flip here — just surface the error.
+ log.Printf("migrate %s: LiveMigrateSandbox failed: %v", id, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
}
- migrationDone = true
- // Invalidate proxy route cache so next request routes to the new worker
+ // Invalidate proxy route cache so next request routes to the new worker.
if s.sandboxAPIProxy != nil {
s.sandboxAPIProxy.InvalidateRouteCache(id)
}
@@ -1230,6 +1120,7 @@ func (s *Server) migrateSandbox(c echo.Context) error {
})
}
+
// effectivePlan returns the org's billing plan for billing gates, resolving it
// from the most authoritative source available. Plan is a GLOBAL signal: it
// changes via the edge (Stripe → DO mark-pro → D1), and no single cell has the
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index ed306b21..39c46320 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -42,7 +42,16 @@ const (
emergencyDiskThreshold = 90.0
evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
- drainTimeout = 45 * time.Minute // max time to drain a worker via live migration (allows 30 sandboxes × 10min each in batches of 3)
+ // drainTimeout caps total wall-clock time for a single drain. With
+ // per-target serialization (one in-flight migration per target), a
+ // drain bottlenecked on a single target processes sandboxes serially
+ // at ~30–60s each. At 250 sandboxes/worker (prod capacity) and 60s
+ // per migration, worst-case is ~4 hours. The prior 45-min cap was
+ // sized for the old fan-onto-one-target model and would orphan most
+ // of a full drain. Bumping to 6h leaves headroom for large workloads;
+ // genuine stuck drains are caught by per-migration timeouts + the
+ // natural-expiry fallback in drainWorker.
+ drainTimeout = 6 * time.Hour
creationFailureThreshold = 3 // consecutive failures before exponential backoff
creationBackoffMin = 1 * time.Minute // initial backoff after threshold hit
@@ -753,9 +762,20 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string, requiredMem
if s.state.IsDraining(w.MachineID) {
continue
}
- // Subtract in-flight migrations from remaining capacity
- pending := s.state.GetInFlight(w.ID)
- remaining := w.Capacity - w.Current - pending
+ // Hard cap: one in-flight migration per target. Each
+ // PrepareMigrationIncoming spawns a QEMU receiver that pre-allocates
+ // the sandbox's full memory; running multiple in parallel against
+ // the same target stacks those pre-allocations and OOM-kills the
+ // worker process under cgroup memory limits. Cascading symptoms on
+ // failure: gRPC "connection refused" (worker shutting down),
+ // "client connection closing" (mid-call), and "migration wait
+ // failed" (target QEMU killed mid-transfer). Multiple targets can
+ // still receive migrations in parallel — the constraint is
+ // one-per-target, not one-globally.
+ if s.state.GetInFlight(w.ID) > 0 {
+ continue
+ }
+ remaining := w.Capacity - w.Current
if remaining <= 0 || w.CPUPct > 85 || w.MemPct > 85 || w.DiskPct > 85 {
continue
}
@@ -779,6 +799,44 @@ func (s *Scaler) findMigrationTarget(region, excludeWorkerID string, requiredMem
return best
}
+// waitForMigrationTarget is findMigrationTarget wrapped in a polling loop. It
+// returns the first eligible target, or nil if ctx expires before one becomes
+// free. Used by liveMigrateSandbox so a batch that briefly outpaces target
+// availability (every target has an in-flight migration) waits for a slot
+// instead of erroring out immediately. The outer drain timeout still bounds
+// the total wall-clock — this just smooths over the inner contention window.
+//
+// 5s poll interval matches the typical live-migrate completion time on small
+// sandboxes; pollSlower (15s) kicks in after the first minute so a genuinely
+// stuck drain doesn't burn CPU on tight retries.
+func (s *Scaler) waitForMigrationTarget(ctx context.Context, region, excludeWorkerID string, requiredMemMB int32) *WorkerInfo {
+ const (
+ pollFast = 5 * time.Second
+ pollSlow = 15 * time.Second
+ fastFor = 60 * time.Second
+ )
+ if target := s.findMigrationTarget(region, excludeWorkerID, requiredMemMB); target != nil {
+ return target
+ }
+ t0 := time.Now()
+ for {
+ interval := pollFast
+ if time.Since(t0) > fastFor {
+ interval = pollSlow
+ }
+ select {
+ case <-ctx.Done():
+ return nil
+ case <-time.After(interval):
+ }
+ if target := s.findMigrationTarget(region, excludeWorkerID, requiredMemMB); target != nil {
+ log.Printf("scaler: waitForMigrationTarget: %s available after %v wait (region=%s, mem=%dMB)",
+ target.ID, time.Since(t0).Round(time.Second), region, requiredMemMB)
+ return target
+ }
+ }
+}
+
// evacuateBatch live-migrates up to count sandboxes off sourceWorker, picking
// a fresh target per sandbox.
//
@@ -1060,11 +1118,28 @@ func (s *Scaler) replaceOneStale(ctx context.Context, region string, target *Wor
// at that exact moment.
s.drainWorker(target.ID, target.MachineID, region)
- // 2. Terminate the (now-empty) stale worker. Frees the quota slot for the
- // replacement scaleUp below. We do this even on partial drain — the
- // natural-expiry path will catch any stragglers on the source via
- // sandbox timeouts; better to free quota and unblock the dance than
- // keep an old-version worker around.
+ // 2. If drain left sandboxes behind (drainTimeout fired, all targets
+ // saturated, etc.), HIBERNATE the leftovers before terminating.
+ // Hibernate is well-tested and doesn't depend on a target worker
+ // being ready — the snapshot lands in S3 and any worker can wake
+ // the sandbox on next access. Without this fallback, terminating
+ // a non-empty source would orphan running customer workload
+ // (status flips to 'error' via MarkOrphanedOnWorker, the
+ // customer's process just disappears).
+ leftover := s.countSandboxesOnWorker(target.ID)
+ if leftover > 0 {
+ log.Printf("scaler: rolling replace: drain of %s returned with %d sandbox(es) still on it — hibernating the rest before termination", target.ID, leftover)
+ s.hibernateAllOnWorker(target.ID)
+ leftover = s.countSandboxesOnWorker(target.ID)
+ if leftover > 0 {
+ log.Printf("scaler: rolling replace: %s still has %d sandbox(es) after hibernate fallback — NOT terminating; next scaler tick will re-attempt", target.ID, leftover)
+ return
+ }
+ }
+ if leftover < 0 {
+ log.Printf("scaler: rolling replace: %s unreachable, can't confirm empty — NOT terminating", target.ID)
+ return
+ }
if s.pool != nil && target.MachineID != "" {
termCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
if err := s.pool.DestroyMachine(termCtx, target.MachineID); err != nil {
@@ -1314,21 +1389,27 @@ func (s *Scaler) getDrainingWorkerSandboxCount(workerID string) int {
}
// hibernateAllOnWorker attempts to hibernate all running sandboxes on a worker.
-// Best-effort — logs failures but doesn't block.
-func (s *Scaler) hibernateAllOnWorker(workerID string) {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+// Best-effort — logs failures but doesn't block. Returns the count actually
+// hibernated.
+//
+// Outer timeout is 30 min total; each per-sandbox hibernate gets its own 2-min
+// sub-timeout so one slow snapshot doesn't starve the rest. Previous 2-min
+// total timeout was sized for a 1-3 sandbox emergency burst and would only
+// hibernate the first few sandboxes when used as a drain fallback.
+func (s *Scaler) hibernateAllOnWorker(workerID string) int {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
client, err := s.registry.GetWorkerClient(workerID)
if err != nil {
log.Printf("scaler: hibernate-all: no gRPC client for %s: %v", workerID, err)
- return
+ return 0
}
listResp, err := client.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
if err != nil {
log.Printf("scaler: hibernate-all: ListSandboxes failed for %s: %v", workerID, err)
- return
+ return 0
}
hibernated := 0
@@ -1336,9 +1417,17 @@ func (s *Scaler) hibernateAllOnWorker(workerID string) {
if sb.Status != "running" {
continue
}
- _, err := client.HibernateSandbox(ctx, &pb.HibernateSandboxRequest{
+ select {
+ case <-ctx.Done():
+ log.Printf("scaler: hibernate-all: outer timeout reached on %s after %d hibernated", workerID, hibernated)
+ return hibernated
+ default:
+ }
+ hibCtx, hibCancel := context.WithTimeout(ctx, 2*time.Minute)
+ _, err := client.HibernateSandbox(hibCtx, &pb.HibernateSandboxRequest{
SandboxId: sb.SandboxId,
})
+ hibCancel()
if err != nil {
log.Printf("scaler: hibernate-all: hibernate %s failed: %v", sb.SandboxId, err)
continue
@@ -1347,6 +1436,60 @@ func (s *Scaler) hibernateAllOnWorker(workerID string) {
}
log.Printf("scaler: hibernate-all: %d sandboxes hibernated on worker %s", hibernated, workerID)
+ return hibernated
+}
+
+// abortIncomingOnTarget calls DestroySandbox on the migration target as a
+// best-effort cleanup after a failed live-migration. PrepareMigrationIncoming
+// spawned a QEMU receiver process and registered the sandbox in the target's
+// m.vms map; if migration didn't complete, that state leaks. The receiver
+// process stays alive (it's a real QEMU pid that vmAlive's Signal(0) check
+// passes), m.vms keeps the entry, and usage_ticker emits billing events at
+// the default memory tier for as long as the worker runs. DestroySandbox
+// kills the pid + removes from m.vms in one shot.
+//
+// Errors are logged but not returned — the caller is in a failure-recovery
+// path that has already done what it needed for the source-side state.
+func (s *Scaler) abortIncomingOnTarget(targetWorkerID, sandboxID string) {
+ if targetWorkerID == "" {
+ return
+ }
+ client, err := s.registry.GetWorkerClient(targetWorkerID)
+ if err != nil {
+ log.Printf("scaler: abort-incoming: target %s unreachable for cleanup of %s: %v", targetWorkerID, sandboxID, err)
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if _, err := client.DestroySandbox(ctx, &pb.DestroySandboxRequest{SandboxId: sandboxID}); err != nil {
+ log.Printf("scaler: abort-incoming: DestroySandbox(%s) on target %s failed: %v — orphan may leak until ghost-reaper catches it", sandboxID, targetWorkerID, err)
+ return
+ }
+ log.Printf("scaler: abort-incoming: cleaned up failed migration receiver %s on target %s", sandboxID, targetWorkerID)
+}
+
+// countSandboxesOnWorker returns the number of running sandboxes the worker
+// reports. Used by replaceOneStale to decide whether termination is safe.
+// Returns -1 if the worker is unreachable (caller should treat as "don't
+// terminate" — we can't tell if it's empty).
+func (s *Scaler) countSandboxesOnWorker(workerID string) int {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ client, err := s.registry.GetWorkerClient(workerID)
+ if err != nil {
+ return -1
+ }
+ resp, err := client.ListSandboxes(ctx, &pb.ListSandboxesRequest{})
+ if err != nil {
+ return -1
+ }
+ n := 0
+ for _, sb := range resp.Sandboxes {
+ if sb.Status == "running" {
+ n++
+ }
+ }
+ return n
}
// destroyDrainedMachine tags and terminates a machine after drain.
@@ -1411,6 +1554,17 @@ func (s *Scaler) getWorkerInfo(workerID string) *WorkerInfo {
// --- Live Migration Orchestration ---
+// LiveMigrateSandbox is the public entry point for live migration. Both the
+// scaler's drain path AND the API's POST /api/sandboxes/:id/migrate handler
+// flow through this — keeping a single implementation ensures both paths
+// share the per-target serialization, in-flight tracking, abort-on-failure
+// cleanup, and source/target consistency guarantees. Previously the API had
+// its own copy that bypassed all of these, so any caller of the API could
+// trigger the same parallel-migration OOM cascade the scaler's drain fixed.
+func (s *Scaler) LiveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerID, targetWorkerID string) error {
+ return s.liveMigrateSandbox(ctx, sandboxID, sourceWorkerID, targetWorkerID)
+}
+
// liveMigrateSandbox performs a full live migration of a sandbox between workers.
// Steps: pre-copy drives to S3 → prepare target → QMP migrate → complete → update DB.
//
@@ -1418,7 +1572,8 @@ func (s *Scaler) getWorkerInfo(workerID string) *WorkerInfo {
// 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.
+// target for the whole batch; or the API handler when the user names a
+// target) pass it explicitly.
func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerID, targetWorkerID string) error {
// Prevent double-migrate
if !s.state.AcquireMigrationLock(sandboxID) {
@@ -1509,9 +1664,15 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
if srcInfo == nil {
return fmt.Errorf("source worker %s not in registry", sourceWorkerID)
}
- target := s.findMigrationTarget(srcInfo.Region, sourceWorkerID, actualMemMB)
+ // Wait up to 2 min for a target to become free. With per-target
+ // serialization, parallel batches may temporarily have all targets
+ // in-flight; waiting smooths over that contention instead of
+ // failing-then-retrying through the outer drain loop.
+ waitCtx, waitCancel := context.WithTimeout(ctx, 2*time.Minute)
+ target := s.waitForMigrationTarget(waitCtx, srcInfo.Region, sourceWorkerID, actualMemMB)
+ waitCancel()
if target == nil {
- return fmt.Errorf("no viable migration target in %s for %dMB actual-RSS sandbox", srcInfo.Region, actualMemMB)
+ return fmt.Errorf("no viable migration target in %s for %dMB actual-RSS sandbox (waited up to 2m)", srcInfo.Region, actualMemMB)
}
targetWorkerID = target.ID
}
@@ -1565,6 +1726,16 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
// fired yet (only fires on success), so D1's worker_id was
// never moved off source. No event needed.
}
+ // Abort on target: clean up the half-prepared receiver. Without
+ // this, the QEMU receiver process (started by PrepareMigrationIncoming
+ // with the sandbox's full memory pre-allocated) sits around forever
+ // pretending to be a live sandbox — usage_ticker emits billing
+ // events for it at the default memory tier, and the ghost-reaper
+ // can't catch it because the qemu process is genuinely alive
+ // (just stuck in -incoming wait). DestroySandbox sends Kill which
+ // removes from m.vms and tears down the qemu pid. Best-effort —
+ // log on failure but don't propagate.
+ s.abortIncomingOnTarget(targetWorkerID, sandboxID)
}()
}
diff --git a/internal/db/store.go b/internal/db/store.go
index 1a92e684..3a0aa158 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "log"
"time"
"github.com/google/uuid"
@@ -823,16 +824,59 @@ func (s *Store) FailMigration(ctx context.Context, sandboxID string) error {
return err
}
+// closeOpenScaleEventsForSandboxes closes any open sandbox_scale_events rows
+// for the given sandboxes. Caller is responsible for the surrounding tx so the
+// close-out is atomic with whatever status transition triggered it.
+//
+// Exists because three raw-SQL paths (FailMigrationPostQMP, MarkOrphanedOnWorker,
+// MarkOrphanedSandboxes) transition sandboxes to terminal states *outside*
+// UpdateSandboxSessionStatus, which has its own inline close-out. Without this
+// helper each path duplicated the same UPDATE — and at least one of them
+// (MarkOrphanedOnWorker) was missing it entirely, leaving scale_events open
+// after the sandbox died. GetOrgUsage then attributed phantom GB-seconds to
+// the dead sandbox until manual cleanup.
+//
+// Safe to call with an empty slice (no-op).
+func closeOpenScaleEventsForSandboxes(ctx context.Context, tx pgx.Tx, sandboxIDs []string) error {
+ if len(sandboxIDs) == 0 {
+ return nil
+ }
+ _, err := tx.Exec(ctx,
+ `UPDATE sandbox_scale_events SET ended_at = now()
+ WHERE sandbox_id = ANY($1) AND ended_at IS NULL`,
+ sandboxIDs)
+ return err
+}
+
// FailMigrationPostQMP marks a sandbox as error after QMP transfer succeeded but the migration
// failed to complete (typically agent-connect on target). After QMP, the source has shut down
// its QEMU, so neither side has a healthy VM. Marking error (rather than reverting to running)
// stops drainWorker from believing the sandbox is still alive on the source.
+//
+// Wrapped in a tx with closeOpenScaleEvents: pre-fix, the status update
+// bypassed UpdateSandboxSessionStatus (which has its own close-out), so
+// sandbox_scale_events rows stayed open after the sandbox died. GetOrgUsage
+// then over-counted the dead sandbox as still running indefinitely — a
+// phantom-billing leak that grows linearly with time since the failure.
func (s *Store) FailMigrationPostQMP(ctx context.Context, sandboxID, errorMsg string) error {
- _, err := s.pool.Exec(ctx,
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ tag, err := tx.Exec(ctx,
`UPDATE sandbox_sessions SET status = 'error', migrating_to_worker = '', stopped_at = now(), error_msg = $2
WHERE sandbox_id = $1 AND status = 'migrating'`,
sandboxID, errorMsg)
- return err
+ if err != nil {
+ return err
+ }
+ if tag.RowsAffected() > 0 {
+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, []string{sandboxID}); err != nil {
+ return fmt.Errorf("close scale events: %w", err)
+ }
+ }
+ return tx.Commit(ctx)
}
// OrphanedSandbox is one row affected by MarkOrphanedOnWorker /
@@ -850,8 +894,17 @@ type OrphanedSandbox struct {
// missed — e.g. a sandbox that vanished from the worker (failed migration cleanup) but whose DB
// row still references the worker. Returns the affected (sandbox_id, org_id) pairs so the
// caller can publish `stopped` events; without them, D1 keeps the row at `running`.
+//
+// Wrapped in a tx with closeOpenScaleEvents (see FailMigrationPostQMP for the
+// pattern). Pre-fix, scale_events rows for sandboxes marked error here stayed
+// open, so GetOrgUsage continued attributing GB-seconds to the (dead) sandbox.
func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg string) ([]OrphanedSandbox, error) {
- rows, err := s.pool.Query(ctx,
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ rows, err := tx.Query(ctx,
`UPDATE sandbox_sessions SET status = 'error', migrating_to_worker = '', stopped_at = now(), error_msg = $2
WHERE worker_id = $1 AND status IN ('running', 'migrating')
RETURNING sandbox_id, org_id, worker_id`,
@@ -859,16 +912,32 @@ func (s *Store) MarkOrphanedOnWorker(ctx context.Context, workerID, errorMsg str
if err != nil {
return nil, err
}
- defer rows.Close()
var orphans []OrphanedSandbox
for rows.Next() {
var o OrphanedSandbox
if err := rows.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); err != nil {
+ rows.Close()
return nil, err
}
orphans = append(orphans, o)
}
- return orphans, rows.Err()
+ rows.Close()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if len(orphans) > 0 {
+ ids := make([]string, len(orphans))
+ for i, o := range orphans {
+ ids[i] = o.SandboxID
+ }
+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, ids); err != nil {
+ return nil, fmt.Errorf("close scale events: %w", err)
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return nil, err
+ }
+ return orphans, nil
}
// RecoverStaleMigrations resets any sandbox stuck in 'migrating' status for more than the given duration.
@@ -910,20 +979,44 @@ func (s *Store) MarkOrphanedSandboxes(ctx context.Context, liveWorkers map[strin
var orphans []OrphanedSandbox
for _, workerID := range deadWorkers {
- upd, err := s.pool.Query(ctx,
+ // Wrap in a tx so the status update + scale-event close-out are atomic.
+ // Pre-fix this was a bare UPDATE, leaving scale_events open after the
+ // status change — same phantom-billing pattern as FailMigrationPostQMP.
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ continue
+ }
+ upd, err := tx.Query(ctx,
`UPDATE sandbox_sessions SET status = 'error', error_msg = 'worker lost', stopped_at = now()
WHERE worker_id = $1 AND status = 'running'
RETURNING sandbox_id, org_id, worker_id`, workerID)
if err != nil {
+ tx.Rollback(ctx)
continue
}
+ var batchOrphans []OrphanedSandbox
for upd.Next() {
var o OrphanedSandbox
if err := upd.Scan(&o.SandboxID, &o.OrgID, &o.WorkerID); err == nil {
- orphans = append(orphans, o)
+ batchOrphans = append(batchOrphans, o)
}
}
upd.Close()
+ if len(batchOrphans) > 0 {
+ ids := make([]string, len(batchOrphans))
+ for i, o := range batchOrphans {
+ ids[i] = o.SandboxID
+ }
+ if err := closeOpenScaleEventsForSandboxes(ctx, tx, ids); err != nil {
+ log.Printf("MarkOrphanedSandboxes: close scale events for worker %s: %v", workerID, err)
+ tx.Rollback(ctx)
+ continue
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ continue
+ }
+ orphans = append(orphans, batchOrphans...)
}
return orphans, nil
}
diff --git a/internal/qemu/ghost_reaper.go b/internal/qemu/ghost_reaper.go
index 0138cf88..c1f35833 100644
--- a/internal/qemu/ghost_reaper.go
+++ b/internal/qemu/ghost_reaper.go
@@ -2,7 +2,10 @@ package qemu
import (
"context"
+ "fmt"
"log"
+ "os"
+ "strings"
"syscall"
"time"
)
@@ -26,25 +29,63 @@ import (
const reaperInterval = 30 * time.Second
-// vmAlive reports whether the qemu process backing this VM is still running.
-// Uses signal-0 ("does this process exist?") which is non-blocking and safe to
-// call on every tick. Survives transient QMP unresponsiveness (e.g. during a
-// savevm) because it checks the OS process, not the QMP socket.
+// vmAlive reports whether the qemu process backing this VM is still running
+// and functional. "Functional" excludes zombie (Z-state) processes — a zombie
+// has exited but its parent hasn't reaped it, so Signal(0) succeeds (kernel
+// still has the PID entry) but the process is doing nothing. Treating zombies
+// as alive means usage_ticker keeps emitting billing events for a dead VM,
+// and the ghost-reaper can't drain the m.vms entry.
//
-// Returns false for: nil cmd, nil cmd.Process, or a reaped/exited process.
+// Three checks in order:
+// 1. ProcessState — if cmd.Wait() returned, definitively dead.
+// 2. /proc/<pid>/stat — if state is Z (zombie) or X (dying), treat as dead.
+// 3. Signal(0) — fallback liveness probe; ESRCH means PID gone.
+//
+// Returns false for: nil cmd, nil cmd.Process, reaped process, zombie, or
+// "no such process".
func vmAlive(vm *VMInstance) bool {
if vm == nil || vm.cmd == nil || vm.cmd.Process == nil {
return false
}
- // If cmd.Wait() already returned, ProcessState is non-nil and Exited() is true.
if vm.cmd.ProcessState != nil && vm.cmd.ProcessState.Exited() {
return false
}
- // Signal(0) is the standard Unix "test process existence" probe. Returns
- // nil if the process is still around, ESRCH/"already finished" otherwise.
+ if state, ok := procState(vm.cmd.Process.Pid); ok {
+ // State chars from man proc(5): R(unning), S(leeping), D(disk-sleep),
+ // Z(ombie), T(stopped), t(traced), W(paging old kernels), X(dying),
+ // x(dead old kernels), K(wakekill), P(parked), I(idle).
+ // Z and X mean "kernel is about to clean up, no useful work happening."
+ if state == "Z" || state == "X" || state == "x" {
+ return false
+ }
+ }
return vm.cmd.Process.Signal(syscall.Signal(0)) == nil
}
+// procState reads /proc/<pid>/stat and returns the process state char (one of
+// RSDZTtWXxKPI). Returns ("", false) if the file can't be read — caller should
+// fall back to Signal(0). Cheap (~1 syscall) and Linux-only; on platforms
+// without /proc the (false) return naturally degrades.
+func procState(pid int) (string, bool) {
+ data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return "", false
+ }
+ // Format: "PID (comm) STATE PPID ..."
+ // comm may contain spaces and parens; find the last ')' to skip it.
+ s := string(data)
+ idx := strings.LastIndexByte(s, ')')
+ if idx == -1 || idx+2 >= len(s) {
+ return "", false
+ }
+ // After ')' there's a space then the state char.
+ rest := s[idx+2:]
+ if len(rest) == 0 {
+ return "", false
+ }
+ return string(rest[0]), true
+}
+
// IsSandboxAlive returns true iff the manager has a tracked VM for this id AND
// its qemu process is still running. Used by usage_ticker before emitting
// billing events so a ghost m.vms entry can't drive billing on a dead sandbox.