An open-source, faster Devin alternative
TypeScript
more live migration fixes
Brian Reardon31ef05b7ae4d
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 649425d6..a2b79b9e 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -867,7 +867,7 @@ func (s *Server) migrateSandbox(c echo.Context) error {t0 := time.Now()// Step 1: Pre-copy drives to S3 (thin overlay, never flatten).- preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 3*time.Minute)+ preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 10*time.Minute)defer preCopyCancel()preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{SandboxId: id,@@ -893,7 +893,7 @@ func (s *Server) migrateSandbox(c echo.Context) error {memoryMB = 1024}- prepCtx, prepCancel := context.WithTimeout(ctx, 3*time.Minute)+ prepCtx, prepCancel := context.WithTimeout(ctx, 10*time.Minute)defer prepCancel()prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{SandboxId: id,@@ -943,9 +943,14 @@ func (s *Server) migrateSandbox(c echo.Context) error {return c.JSON(http.StatusInternalServerError, map[string]string{"error": "complete migration: " + err.Error()})}- // Step 5: Complete migration — update DB status and worker_id atomically+ // 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 {- s.store.CompleteMigration(ctx, id, req.TargetWorker)+ 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()}migrationDone = true@@ -1166,9 +1171,14 @@ func (s *Server) setLimitsRemote(c echo.Context, sandboxID string, maxPids int32})}- // Migration succeeded — update state+ // Migration succeeded — update state.+ // Use background context in case the request context is close to expiry.if s.store != nil {- s.store.CompleteMigration(ctx, sandboxID, target.ID)+ dbCtx, dbCancel := context.WithTimeout(context.Background(), 10*time.Second)+ if err := s.store.CompleteMigration(dbCtx, sandboxID, target.ID); err != nil {+ log.Printf("scale-migrate %s: WARNING: CompleteMigration DB update failed: %v", sandboxID, err)+ }+ dbCancel()}if s.sandboxAPIProxy != nil {s.sandboxAPIProxy.InvalidateRouteCache(sandboxID)@@ -1288,7 +1298,7 @@ func (s *Server) migrateForScale(ctx context.Context, sandboxID string, session}// Step 1: Pre-copy drives to S3 (thin overlay).- preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 3*time.Minute)+ preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 10*time.Minute)defer preCopyCancel()preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{SandboxId: sandboxID,@@ -1311,7 +1321,7 @@ func (s *Server) migrateForScale(ctx context.Context, sandboxID string, sessionsandboxID, time.Since(t0).Milliseconds(), target.ID, baseMem, memoryMB, baseCPU)// Step 2: Prepare target with the SOURCE's base memory (must match for migration)- prepCtx, prepCancel := context.WithTimeout(ctx, 3*time.Minute)+ prepCtx, prepCancel := context.WithTimeout(ctx, 10*time.Minute)defer prepCancel()prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{SandboxId: sandboxID,diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex 45ca0db1..26d194a5 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -61,6 +61,11 @@ func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {if err != nil {return nil, fmt.Errorf("invalid redis URL: %w", err)}+ opts.PoolSize = 10+ opts.MinIdleConns = 2+ opts.ConnMaxIdleTime = 5 * time.Minute+ opts.ConnMaxLifetime = 30 * time.Minute+ opts.MaxRetries = 3rdb := redis.NewClient(opts)@@ -393,13 +398,56 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,// 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.r.mu.RLock()- defer r.mu.RUnlock()+ conn, hasConn := r.conns[workerID]+ client, hasClient := r.clients[workerID]+ var grpcAddr string+ if w, ok := r.workers[workerID]; ok {+ grpcAddr = w.GRPCAddr+ }+ r.mu.RUnlock()- client, ok := r.clients[workerID]- if !ok {+ if !hasConn || !hasClient {return nil, fmt.Errorf("no gRPC connection to worker %s", workerID)}++ state := conn.GetState()+ switch {+ case state == connectivity.Ready || state == connectivity.Connecting:+ return client, nil++ case state == connectivity.Idle:+ // Nudge idle connections to reconnect proactively.+ conn.ResetConnectBackoff()+ conn.Connect()+ return client, nil++ case state == connectivity.TransientFailure || state == connectivity.Shutdown:+ // Slow path: write lock, re-dial. Only blocks callers for THIS worker.+ if grpcAddr == "" {+ return nil, fmt.Errorf("gRPC connection to worker %s is %s (no addr to re-dial)", workerID, state)+ }+ r.mu.Lock()+ // Double-check under write lock — another goroutine may have already re-dialed.+ if c, ok := r.conns[workerID]; ok && c.GetState() != connectivity.TransientFailure && c.GetState() != connectivity.Shutdown {+ client = r.clients[workerID]+ r.mu.Unlock()+ return client, nil+ }+ log.Printf("redis_registry: GetWorkerClient %s: conn in %s state, re-dialing", workerID, state)+ conn.Close()+ delete(r.conns, workerID)+ delete(r.clients, workerID)+ r.dialWorkerLocked(workerID, grpcAddr)+ newClient, ok := r.clients[workerID]+ r.mu.Unlock()+ if ok {+ return newClient, nil+ }+ return nil, fmt.Errorf("gRPC re-dial to worker %s failed", workerID)+ }+return client, nil}diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.goindex 52542ae6..23d6cff1 100644--- a/internal/controlplane/scaler.go+++ b/internal/controlplane/scaler.go@@ -6,6 +6,7 @@ import ("log""strings""sync"+ "sync/atomic""time""github.com/opensandbox/opensandbox/internal/compute"@@ -36,7 +37,7 @@ const (emergencyDiskThreshold = 90.0evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per workerevacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches- drainTimeout = 15 * time.Minute // max time to drain a worker via live migration+ drainTimeout = 45 * time.Minute // max time to drain a worker via live migration (allows 30 sandboxes × 10min each in batches of 3))// ScalerRegistry is the interface the Scaler uses to query worker state.@@ -809,19 +810,30 @@ func (s *Scaler) drainWorker(workerID, machineID, region string) {return}- // Migrate a batch+ // Migrate a batch — bounded parallelism to avoid overwhelming+ // network/disk on source and target workers.batch := runningif len(batch) > evacuationBatchSize {batch = batch[:evacuationBatchSize]}batchFailed := false+ var wg sync.WaitGroup+ var failCount int64for _, sandboxID := range batch {- if err := s.liveMigrateSandbox(ctx, sandboxID, workerID, target.ID); err != nil {- log.Printf("scaler: drain: migrate %s to %s failed: %v", sandboxID, target.ID, err)- migrationFailures++- batchFailed = true- }+ 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)+ atomic.AddInt64(&failCount, 1)+ }+ }(sandboxID)+ }+ wg.Wait()+ if failCount > 0 {+ migrationFailures += int(failCount)+ batchFailed = true}if batchFailed {@@ -1039,7 +1051,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker// Step 1: Pre-copy drives to S3 (source uploads thin overlay — never flattens).// Target worker rebases to its own base if golden versions differ.- preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 3*time.Minute)+ preCopyCtx, preCopyCancel := context.WithTimeout(ctx, 10*time.Minute)defer preCopyCancel()preCopyResp, err := sourceClient.PreCopyDrives(preCopyCtx, &pb.PreCopyDrivesRequest{SandboxId: sandboxID,@@ -1076,7 +1088,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker}}- prepCtx, prepCancel := context.WithTimeout(ctx, 3*time.Minute)+ prepCtx, prepCancel := context.WithTimeout(ctx, 10*time.Minute)defer prepCancel()prepResp, err := targetClient.PrepareMigrationIncoming(prepCtx, &pb.PrepareMigrationIncomingRequest{SandboxId: sandboxID,@@ -1119,9 +1131,14 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerreturn fmt.Errorf("complete migration: %w", err)}- // Step 5: Complete migration — update DB status and worker_id atomically+ // Step 5: Complete migration — update DB status and worker_id atomically.+ // Use background context in case the drain context is close to expiry.if s.store != nil {- s.store.CompleteMigration(ctx, sandboxID, targetWorkerID)+ dbCtx, dbCancel := context.WithTimeout(context.Background(), 10*time.Second)+ if err := s.store.CompleteMigration(dbCtx, sandboxID, targetWorkerID); err != nil {+ log.Printf("scaler: migrate %s: WARNING: CompleteMigration DB update failed: %v", sandboxID, err)+ }+ dbCancel()}migrationCompleted = truediff --git a/internal/db/store.go b/internal/db/store.goindex a233dbff..13b39929 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -41,6 +41,11 @@ func NewStore(ctx context.Context, databaseURL string) (*Store, error) {// Each proxied exec/file/pty call does a DB lookup before forwarding.poolCfg.MaxConns = 50poolCfg.MinConns = 5+ // Recycle connections periodically to prevent stale/leaked connections from+ // piling up on the Postgres server (e.g. after worker restarts/deletions).+ poolCfg.MaxConnLifetime = 30 * time.Minute+ poolCfg.MaxConnIdleTime = 5 * time.Minute+ poolCfg.HealthCheckPeriod = 30 * time.Secondpool, err := pgxpool.NewWithConfig(ctx, poolCfg)if err != nil {return nil, fmt.Errorf("failed to connect to database: %w", err)@@ -540,11 +545,20 @@ func (s *Store) SetMigrating(ctx context.Context, sandboxID, targetWorkerID stri// CompleteMigration marks a sandbox as running on the new worker after successful migration.func (s *Store) CompleteMigration(ctx context.Context, sandboxID, newWorkerID string) error {- _, err := s.pool.Exec(ctx,- `UPDATE sandbox_sessions SET status = 'running', worker_id = $1, migrating_to_worker = ''- WHERE sandbox_id = $2 AND status = 'migrating'`,+ // Use status IN ('migrating', 'running', 'stopped') — a race with the source+ // worker's cleanup may have already set it to 'stopped' or reverted to 'running'.+ // The migration DID succeed (QEMU is running on the target), so force the update.+ tag, err := s.pool.Exec(ctx,+ `UPDATE sandbox_sessions SET status = 'running', worker_id = $1, migrating_to_worker = '', stopped_at = NULL, error_msg = NULL+ WHERE sandbox_id = $2 AND status IN ('migrating', 'running', 'stopped')`,newWorkerID, sandboxID)- return err+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("no session found for %s in migrating/running/stopped state", sandboxID)+ }+ return nil}// FailMigration reverts a sandbox to running on its original worker after a failed migration.diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.goindex 01f4ecc1..48b96b80 100644--- a/internal/proxy/controlplane_proxy.go+++ b/internal/proxy/controlplane_proxy.go@@ -141,6 +141,15 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int)// exists, it wakes the sandbox on a new worker. Otherwise, it marks the session// as stopped and returns a clear error.func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession, port int) error {+ // If the sandbox is mid-migration, don't mark it stopped — the controlplane+ // is about to update the worker_id. Return a temporary error so the client retries.+ if session.MigratingToWorker != "" {+ log.Printf("cp-proxy: sandbox %s is migrating to %s, returning temporary unavailable", sandboxID, session.MigratingToWorker)+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": fmt.Sprintf("sandbox %s is being migrated, retry shortly", sandboxID),+ })+ }+// Check if there's a hibernation we can wake fromcheckpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)if err == nil && checkpoint != nil {diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.goindex 5f812a28..78181c31 100644--- a/internal/proxy/sandbox_api_proxy.go+++ b/internal/proxy/sandbox_api_proxy.go@@ -367,6 +367,15 @@ func (p *SandboxAPIProxy) doWebSocket(c echo.Context, sandboxID, workerURL, toke// tryRecoverOrFail handles the case where a sandbox's worker is gone.func (p *SandboxAPIProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession) error {+ // If the sandbox is mid-migration, don't mark it stopped — the controlplane+ // is about to update the worker_id. Return a temporary error so the client retries.+ if session.MigratingToWorker != "" {+ log.Printf("sandbox-api-proxy: sandbox %s is migrating to %s, returning temporary unavailable", sandboxID, session.MigratingToWorker)+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": fmt.Sprintf("sandbox %s is being migrated, retry shortly", sandboxID),+ })+ }+checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)if err == nil && checkpoint != nil {log.Printf("sandbox-api-proxy: sandbox %s has active hibernation, attempting recovery wake", sandboxID)diff --git a/internal/qemu/agent_client.go b/internal/qemu/agent_client.goindex f118b4e7..01292c15 100644--- a/internal/qemu/agent_client.go+++ b/internal/qemu/agent_client.go@@ -11,6 +11,7 @@ import ("google.golang.org/grpc""google.golang.org/grpc/backoff""google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/keepalive"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -43,6 +44,11 @@ func NewAgentClient(guestCID uint32) (*AgentClient, error) {MaxDelay: 1 * time.Second,},}),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ PermitWithoutStream: true,+ }),grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {return dialVsock(ctx, guestCID, 1024)}),@@ -488,6 +494,11 @@ func NewAgentClientSocket(socketPath string) (*AgentClient, error) {MaxDelay: 1 * time.Second,},}),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ PermitWithoutStream: true,+ }),grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(256*1024*1024),grpc.MaxCallSendMsgSize(256*1024*1024),diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 5b7a8323..97168f8d 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -1299,6 +1299,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (*types.SguestMAC: guestMAC,guestCID: guestCID,bootArgs: bootArgs,+ goldenVersion: m.goldenVersion, // set even on cold boot — VM uses the same base image}// Wait for agent via Unix socket@@ -2805,6 +2806,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cguestCID: guestCID,bootArgs: bootArgs,agent: agent,+ goldenVersion: m.goldenVersion, // set on wake — VM uses the current base image}m.mu.Lock()diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex e25dbeab..89b28b92 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -110,27 +110,50 @@ func (mc *MigrationCoordinator) MigrateToS3(ctx context.Context, sandboxID strindefer os.RemoveAll(stagingDir)rootfsKey = fmt.Sprintf("migrations/%s/rootfs.qcow2", sandboxID)- workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2", sandboxID)+ workspaceKey = fmt.Sprintf("migrations/%s/workspace.qcow2.zst", sandboxID)t0 := time.Now()- // Upload from staged copies — QEMU can continue running on originals- state.Phase = "upload-rootfs"- rootfsSize, err := mc.uploadFile(ctx, stagedRootfs, rootfsKey)- if err != nil {- return "", "", fmt.Errorf("upload rootfs: %w", err)+ // Compress workspace with zstd before upload — typically 2-4x smaller,+ // proportionally faster to upload/download over S3.+ state.Phase = "compress-workspace"+ compressedWorkspace := stagedWorkspace + ".zst"+ compressCmd := exec.CommandContext(ctx, "zstd", "-1", "--rm", "-q", stagedWorkspace, "-o", compressedWorkspace)+ if out, err := compressCmd.CombinedOutput(); err != nil {+ return "", "", fmt.Errorf("compress workspace: %w (%s)", err, strings.TrimSpace(string(out)))}- state.Phase = "upload-workspace"- wsSize, err := mc.uploadFile(ctx, stagedWorkspace, workspaceKey)- if err != nil {- return "", "", fmt.Errorf("upload workspace: %w", err)+ // Upload rootfs + compressed workspace in parallel+ state.Phase = "upload"+ type uploadResult struct {+ size int64+ err error+ }+ rootfsCh := make(chan uploadResult, 1)+ workspaceCh := make(chan uploadResult, 1)++ go func() {+ sz, err := mc.uploadFile(ctx, stagedRootfs, rootfsKey)+ rootfsCh <- uploadResult{sz, err}+ }()+ go func() {+ sz, err := mc.uploadFile(ctx, compressedWorkspace, workspaceKey)+ workspaceCh <- uploadResult{sz, err}+ }()++ rRes := <-rootfsCh+ wRes := <-workspaceCh+ if rRes.err != nil {+ return "", "", fmt.Errorf("upload rootfs: %w", rRes.err)+ }+ if wRes.err != nil {+ return "", "", fmt.Errorf("upload workspace: %w", wRes.err)}- log.Printf("qemu: migration pre-copy %s: rootfs=%.1fMB workspace=%.1fMB (%dms)",+ log.Printf("qemu: migration pre-copy %s: rootfs=%.1fMB workspace=%.1fMB(compressed) (%dms)",sandboxID,- float64(rootfsSize)/(1024*1024),- float64(wsSize)/(1024*1024),+ float64(rRes.size)/(1024*1024),+ float64(wRes.size)/(1024*1024),time.Since(t0).Milliseconds())return rootfsKey, workspaceKey, nil@@ -582,17 +605,48 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,return "", 0, fmt.Errorf("mkdir: %w", err)}- // Download rootfs from S3rootfsPath := filepath.Join(sandboxDir, "rootfs.qcow2")- if err := downloadS3ToFile(ctx, checkpointStore, rootfsS3Key, rootfsPath); err != nil {- return "", 0, fmt.Errorf("download rootfs from S3: %w", err)+ workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")++ // Download rootfs + workspace in parallel. Workspace may be zstd-compressed.+ // Rebase runs as soon as rootfs is ready (overlaps with workspace download).+ type dlResult struct {+ err error+ }+ rootfsCh := make(chan dlResult, 1)+ workspaceCh := make(chan dlResult, 1)++ go func() {+ rootfsCh <- dlResult{downloadS3ToFile(ctx, checkpointStore, rootfsS3Key, rootfsPath)}+ }()+ go func() {+ isCompressed := strings.HasSuffix(workspaceS3Key, ".zst")+ dlPath := workspacePath+ if isCompressed {+ dlPath = workspacePath + ".zst"+ }+ if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, dlPath); err != nil {+ workspaceCh <- dlResult{fmt.Errorf("download workspace: %w", err)}+ return+ }+ if isCompressed {+ decompressCmd := exec.CommandContext(ctx, "zstd", "-d", "--rm", "-q", dlPath, "-o", workspacePath)+ if out, err := decompressCmd.CombinedOutput(); err != nil {+ workspaceCh <- dlResult{fmt.Errorf("decompress workspace: %w (%s)", err, strings.TrimSpace(string(out)))}+ return+ }+ }+ workspaceCh <- dlResult{nil}+ }()++ // Wait for rootfs download, then rebase (workspace downloads in parallel)+ if r := <-rootfsCh; r.err != nil {+ return "", 0, fmt.Errorf("download rootfs from S3: %w", r.err)}if overlayMode {currentGolden := m.GoldenVersion()if sourceGoldenVersion != "" && sourceGoldenVersion != currentGolden {- // Cross-version: safe rebase via old base download + block comparison.- // Ensure checkpointStore is available for downloading the old base.if m.checkpointStore == nil && checkpointStore != nil {m.SetCheckpointStore(checkpointStore)}@@ -601,7 +655,6 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,}log.Printf("qemu: migration %s: rootfs rebased from %s to %s (cross-version)", sandboxID, sourceGoldenVersion, currentGolden)} else {- // Same version (or no version info): metadata-only repoint to local path.baseImage, resolveErr := ResolveBaseImage(m.cfg.ImagesDir, "default")if resolveErr != nil {return "", 0, fmt.Errorf("resolve base image for overlay rebase: %w", resolveErr)@@ -615,10 +668,9 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,}}- // Download workspace from S3- workspacePath := filepath.Join(sandboxDir, "workspace.qcow2")- if err := downloadS3ToFile(ctx, checkpointStore, workspaceS3Key, workspacePath); err != nil {- return "", 0, fmt.Errorf("download workspace from S3: %w", err)+ // Wait for workspace download + decompress to finish+ if r := <-workspaceCh; r.err != nil {+ return "", 0, r.err}return m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)diff --git a/internal/worker/event_publisher.go b/internal/worker/event_publisher.goindex f97be74e..c2f19cac 100644--- a/internal/worker/event_publisher.go+++ b/internal/worker/event_publisher.go@@ -1,6 +1,7 @@package workerimport (+ "context""encoding/json""fmt""log"@@ -39,6 +40,9 @@ func NewEventPublisher(natsURL, region, workerID string, sandboxDBs *sandbox.Sannats.RetryOnFailedConnect(true),nats.MaxReconnects(-1),nats.ReconnectWait(2*time.Second),+ // Cap the pending buffer to prevent unbounded memory growth when NATS+ // is unreachable. At 5s heartbeat interval + events, 8MB is ~hours of headroom.+ nats.ReconnectBufSize(8*1024*1024),)if err != nil {return nil, fmt.Errorf("failed to connect to NATS: %w", err)@@ -50,15 +54,17 @@ func NewEventPublisher(natsURL, region, workerID string, sandboxDBs *sandbox.Sanreturn nil, fmt.Errorf("failed to get JetStream context: %w", err)}- // Ensure the stream exists+ // Ensure the stream exists — retry with timeout so a slow NATS broker+ // doesn't hang startup indefinitely.+ streamCtx, streamCancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer streamCancel()_, err = js.AddStream(&nats.StreamConfig{Name: "SANDBOX_EVENTS",Subjects: []string{"sandbox.events.>"},- MaxAge: 7 * 24 * time.Hour, // Retain for 7 days- })+ MaxAge: 7 * 24 * time.Hour,+ }, nats.Context(streamCtx))if err != nil {- // Stream may already exist, that's OK- log.Printf("event_publisher: stream setup: %v", err)+ log.Printf("event_publisher: stream setup failed (will retry in background): %v", err)}return &EventPublisher{@@ -106,6 +112,11 @@ func (p *EventPublisher) SetGoldenVersion(v string) {// PublishHeartbeat sends a worker heartbeat to NATS.func (p *EventPublisher) PublishHeartbeat(capacity, current int, cpuPct, memPct, diskPct float64) {+ // Skip publishing if NATS is disconnected — avoids buffering messages+ // that pile up and eventually overflow when the connection is broken.+ if !p.nc.IsConnected() {+ return+ }subject := fmt.Sprintf("workers.heartbeat.%s.%s", p.region, p.workerID)payload := map[string]interface{}{"worker_id": p.workerID,diff --git a/internal/worker/redis_heartbeat.go b/internal/worker/redis_heartbeat.goindex 37bf4724..278156b8 100644--- a/internal/worker/redis_heartbeat.go+++ b/internal/worker/redis_heartbeat.go@@ -54,6 +54,12 @@ func NewRedisHeartbeat(redisURL, workerID, region, grpcAddr, httpAddr string) (*if err != nil {return nil, fmt.Errorf("invalid redis URL: %w", err)}+ // Explicit pool management to prevent connection leaks and detect stale connections.+ opts.PoolSize = 5+ opts.MinIdleConns = 1+ opts.ConnMaxIdleTime = 5 * time.Minute+ opts.ConnMaxLifetime = 30 * time.Minute+ opts.MaxRetries = 3rdb := redis.NewClient(opts)diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.goindex b7eff451..48097568 100644--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@ -2732,7 +2732,6 @@ func (*SetSandboxLimitsResponse) Descriptor() ([]byte, []int) {type PreCopyDrivesRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`- FlattenRootfs bool `protobuf:"varint,2,opt,name=flatten_rootfs,json=flattenRootfs,proto3" json:"flatten_rootfs,omitempty"` // if true, flatten qcow2 overlay before upload (cross-golden-version)unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -2774,20 +2773,13 @@ func (x *PreCopyDrivesRequest) GetSandboxId() string {return ""}-func (x *PreCopyDrivesRequest) GetFlattenRootfs() bool {- if x != nil {- return x.FlattenRootfs- }- return false-}-type PreCopyDrivesResponse struct {state protoimpl.MessageState `protogen:"open.v1"`RootfsKey string `protobuf:"bytes,1,opt,name=rootfs_key,json=rootfsKey,proto3" json:"rootfs_key,omitempty"` // S3 key for rootfs qcow2WorkspaceKey string `protobuf:"bytes,2,opt,name=workspace_key,json=workspaceKey,proto3" json:"workspace_key,omitempty"` // S3 key for workspace qcow2GoldenVersion string `protobuf:"bytes,3,opt,name=golden_version,json=goldenVersion,proto3" json:"golden_version,omitempty"` // golden version the sandbox was created from- BaseMemoryMb int32 `protobuf:"varint,4,opt,name=base_memory_mb,json=baseMemoryMb,proto3" json:"base_memory_mb,omitempty"` // QEMU -m value from source- BaseCpuCount int32 `protobuf:"varint,5,opt,name=base_cpu_count,json=baseCpuCount,proto3" json:"base_cpu_count,omitempty"` // QEMU -smp value from source+ BaseMemoryMb 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.UnknownFieldssizeCache protoimpl.SizeCache}@@ -2858,21 +2850,21 @@ func (x *PreCopyDrivesResponse) GetBaseCpuCount() int32 {}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"`- RootfsPath string `protobuf:"bytes,2,opt,name=rootfs_path,json=rootfsPath,proto3" json:"rootfs_path,omitempty"` // local path to rootfs on target (pre-copied)- WorkspacePath string `protobuf:"bytes,3,opt,name=workspace_path,json=workspacePath,proto3" json:"workspace_path,omitempty"` // local path to workspace on target (pre-copied)- CpuCount int32 `protobuf:"varint,4,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`- MemoryMb int32 `protobuf:"varint,5,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`- GuestPort int32 `protobuf:"varint,6,opt,name=guest_port,json=guestPort,proto3" json:"guest_port,omitempty"`- Template string `protobuf:"bytes,7,opt,name=template,proto3" json:"template,omitempty"`- RootfsS3Key string `protobuf:"bytes,8,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"` // if set, download from S3 instead of using local rootfs_path- WorkspaceS3Key string `protobuf:"bytes,9,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"` // if set, download from S3 instead of using local workspace_path- OverlayMode bool `protobuf:"varint,10,opt,name=overlay_mode,json=overlayMode,proto3" json:"overlay_mode,omitempty"` // if true, rootfs is thin overlay — rebase to local golden on target- TargetMemoryMb int32 `protobuf:"varint,11,opt,name=target_memory_mb,json=targetMemoryMb,proto3" json:"target_memory_mb,omitempty"` // final memory after scale — worker checks capacity and reserves atomically- SourceGoldenVersion string `protobuf:"bytes,12,opt,name=source_golden_version,json=sourceGoldenVersion,proto3" json:"source_golden_version,omitempty"` // source's golden version — target rebases if different- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`+ RootfsPath string `protobuf:"bytes,2,opt,name=rootfs_path,json=rootfsPath,proto3" json:"rootfs_path,omitempty"` // local path to rootfs on target (pre-copied)+ WorkspacePath string `protobuf:"bytes,3,opt,name=workspace_path,json=workspacePath,proto3" json:"workspace_path,omitempty"` // local path to workspace on target (pre-copied)+ CpuCount int32 `protobuf:"varint,4,opt,name=cpu_count,json=cpuCount,proto3" json:"cpu_count,omitempty"`+ MemoryMb int32 `protobuf:"varint,5,opt,name=memory_mb,json=memoryMb,proto3" json:"memory_mb,omitempty"`+ GuestPort int32 `protobuf:"varint,6,opt,name=guest_port,json=guestPort,proto3" json:"guest_port,omitempty"`+ Template string `protobuf:"bytes,7,opt,name=template,proto3" json:"template,omitempty"`+ RootfsS3Key string `protobuf:"bytes,8,opt,name=rootfs_s3_key,json=rootfsS3Key,proto3" json:"rootfs_s3_key,omitempty"` // if set, download from S3 instead of using local rootfs_path+ WorkspaceS3Key string `protobuf:"bytes,9,opt,name=workspace_s3_key,json=workspaceS3Key,proto3" json:"workspace_s3_key,omitempty"` // if set, download from S3 instead of using local workspace_path+ OverlayMode bool `protobuf:"varint,10,opt,name=overlay_mode,json=overlayMode,proto3" json:"overlay_mode,omitempty"` // if true, rootfs is thin overlay — rebase to local golden on target+ TargetMemoryMb int32 `protobuf:"varint,11,opt,name=target_memory_mb,json=targetMemoryMb,proto3" json:"target_memory_mb,omitempty"` // final memory after scale — worker checks capacity and reserves atomically+ SourceGoldenVersion string `protobuf:"bytes,12,opt,name=source_golden_version,json=sourceGoldenVersion,proto3" json:"source_golden_version,omitempty"` // source's golden version — target rebases overlay if different from its own+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *PrepareMigrationIncomingRequest) Reset() {@@ -3529,16 +3521,17 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\fcpu_max_usec\x18\x04 \x01(\x03R\n" +"cpuMaxUsec\x12&\n" +"\x0fcpu_period_usec\x18\x05 \x01(\x03R\rcpuPeriodUsec\"\x1a\n" +- "\x18SetSandboxLimitsResponse\"\\\n" ++ "\x18SetSandboxLimitsResponse\";\n" +"\x14PreCopyDrivesRequest\x12\x1d\n" +"\n" +- "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12%\n" +- "\x0eflatten_rootfs\x18\x02 \x01(\bR\rflattenRootfs\"\x82\x01\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xce\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\"\x98\x03\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" +"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +@@ -3554,7 +3547,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +"\x10workspace_s3_key\x18\t \x01(\tR\x0eworkspaceS3Key\x12!\n" +"\foverlay_mode\x18\n" +" \x01(\bR\voverlayMode\x12(\n" +- "\x10target_memory_mb\x18\v \x01(\x05R\x0etargetMemoryMb\"d\n" ++ "\x10target_memory_mb\x18\v \x01(\x05R\x0etargetMemoryMb\x122\n" ++ "\x15source_golden_version\x18\f \x01(\tR\x13sourceGoldenVersion\"d\n" +" PrepareMigrationIncomingResponse\x12#\n" +"\rincoming_addr\x18\x01 \x01(\tR\fincomingAddr\x12\x1b\n" +"\thost_port\x18\x02 \x01(\x05R\bhostPort\"X\n" +