An open-source, faster Devin alternative
TypeScript
switch to migration style
Brian Reardon0b39fe0d3677
diff --git a/internal/controlplane/grpc_pool.go b/internal/controlplane/grpc_pool.gonew file mode 100644index 00000000..856b9416--- /dev/null+++ b/internal/controlplane/grpc_pool.go@@ -0,0 +1,107 @@+// grpc_pool.go — gRPC connection pool for control plane → worker communication.+//+// Problem: A single HTTP/2 connection multiplexes all RPCs over one TCP stream.+// Under concurrent load (100+ simultaneous sandbox creates/destroys), the 64KB+// send window becomes a bottleneck — RPCs queue behind each other (head-of-line+// blocking), causing timeouts.+//+// Solution: Maintain a pool of independent gRPC connections per worker. Each RPC+// is dispatched round-robin across the pool, spreading load across multiple+// HTTP/2 streams. Pool size scales with worker capacity (1 conn per 25 sandboxes,+// min 8, max 16).+package controlplane++import (+ "log"+ "sync/atomic"+ "time"++ "google.golang.org/grpc"+ "google.golang.org/grpc/keepalive"++ "github.com/opensandbox/opensandbox/internal/grpctls"+ pb "github.com/opensandbox/opensandbox/proto/worker"+)++// grpcPool holds multiple gRPC connections to a single worker.+// All connections target the same address; round-robin distributes RPCs.+type grpcPool struct {+ conns []*grpc.ClientConn // underlying transport connections+ clients []pb.SandboxWorkerClient // gRPC stubs, one per connection+ counter uint64 // atomic round-robin counter+}++// dialPool creates a pool of gRPC connections to a worker at grpcAddr.+// The capacity parameter (worker's max sandbox count) determines pool size:+// - 1 connection per 25 sandboxes+// - minimum 8 connections (handles burst traffic on small workers)+// - maximum 16 connections (diminishing returns beyond this)+//+// Each connection is configured with:+// - mTLS credentials (loaded from grpctls)+// - 256MB max message size (for large file transfers)+// - 30s keepalive interval (detects dead connections before RPCs fail)+func dialPool(grpcAddr string, capacity int) (*grpcPool, error) {+ poolSize := 8+ if capacity > 0 {+ poolSize = capacity / 25+ }+ if poolSize < 8 {+ poolSize = 8+ }+ if poolSize > 16 {+ poolSize = 16+ }++ creds, err := grpctls.ClientCredentials()+ if err != nil {+ return nil, err+ }++ pool := &grpcPool{+ conns: make([]*grpc.ClientConn, 0, poolSize),+ clients: make([]pb.SandboxWorkerClient, 0, poolSize),+ }++ for i := 0; i < poolSize; i++ {+ conn, err := grpc.NewClient(grpcAddr,+ grpc.WithTransportCredentials(creds),+ grpc.WithDefaultCallOptions(+ grpc.MaxCallRecvMsgSize(256*1024*1024),+ grpc.MaxCallSendMsgSize(256*1024*1024),+ ),+ grpc.WithKeepaliveParams(keepalive.ClientParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ PermitWithoutStream: true,+ }),+ )+ if err != nil {+ pool.close() // clean up any connections already opened+ return nil, err+ }+ // Force immediate connection (grpc.NewClient is lazy by default).+ // Without this, keepalive can't detect a dead connection until the+ // first RPC, which may be too late.+ conn.Connect()+ pool.conns = append(pool.conns, conn)+ pool.clients = append(pool.clients, pb.NewSandboxWorkerClient(conn))+ }++ log.Printf("grpc_pool: created %d connections to %s", poolSize, grpcAddr)+ return pool, nil+}++// get returns the next client via atomic round-robin.+// Safe for concurrent use — no locks needed.+func (p *grpcPool) get() pb.SandboxWorkerClient {+ idx := atomic.AddUint64(&p.counter, 1) % uint64(len(p.clients))+ return p.clients[idx]+}++// close shuts down all connections in the pool.+func (p *grpcPool) close() {+ for _, conn := range p.conns {+ conn.Close()+ }+}diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.goindex e9e481eb..99186888 100644--- a/internal/controlplane/redis_registry.go+++ b/internal/controlplane/redis_registry.go@@ -1,3 +1,18 @@+// redis_registry.go — Worker discovery and health tracking via Redis.+//+// Workers send heartbeats to Redis every 10s (key: worker:{id}, TTL: 30s).+// The control plane discovers workers through two mechanisms:+//+// 1. Pub/sub (fast path): Workers publish heartbeats to "workers:heartbeat".+// The registry subscribes and updates its in-memory cache immediately.+// This provides sub-second worker discovery.+//+// 2. Periodic SCAN (reconciliation): Every 10s, the registry scans all+// worker:* keys in Redis. Workers whose keys have expired (TTL elapsed)+// are removed. This handles cases where pub/sub messages are lost.+//+// For each discovered worker, the registry maintains a gRPC connection pool+// (see grpc_pool.go) used to dispatch sandbox operations.package controlplaneimport (@@ -6,47 +21,41 @@ import ("fmt""log""sync"- "sync/atomic""time""github.com/redis/go-redis/v9"- "google.golang.org/grpc""google.golang.org/grpc/connectivity"- "google.golang.org/grpc/keepalive"-- "github.com/opensandbox/opensandbox/internal/grpctls"pb "github.com/opensandbox/opensandbox/proto/worker")-// WorkerEntry represents a worker in the Redis-backed registry.+// WorkerEntry represents a worker's current state as reported via heartbeat.+// Updated on every heartbeat (every 10s) with the latest load metrics.type WorkerEntry struct {ID string `json:"worker_id"`- MachineID string `json:"machine_id,omitempty"` // EC2 instance ID+ MachineID string `json:"machine_id,omitempty"`Region string `json:"region"`GRPCAddr string `json:"grpc_addr"`HTTPAddr string `json:"http_addr"`- Capacity int `json:"capacity"`- Current int `json:"current"`- CPUPct float64 `json:"cpu_pct"`- MemPct float64 `json:"mem_pct"`+ Capacity int `json:"capacity"` // max sandboxes this worker can run+ Current int `json:"current"` // sandboxes currently running+ CPUPct float64 `json:"cpu_pct"` // current CPU usage percentage+ MemPct float64 `json:"mem_pct"` // current memory usage percentage}-// RedisWorkerRegistry maintains an in-memory cache of worker state-// backed by Redis pub/sub for real-time updates and periodic SCAN for reconciliation.-// It also maintains a persistent gRPC connection pool to workers.+// RedisWorkerRegistry maintains an in-memory cache of known workers,+// backed by Redis for discovery, and a gRPC connection pool per worker+// for dispatching sandbox operations.type RedisWorkerRegistry struct {rdb *redis.Clientmu sync.RWMutex- workers map[string]*WorkerEntry // in-memory hot cache- conns map[string]*grpc.ClientConn // persistent gRPC connections- clients map[string]pb.SandboxWorkerClient // cached gRPC clients (primary)- clientPools map[string][]pb.SandboxWorkerClient // connection pool per worker- poolCounter uint64 // round-robin counter- stop chan struct{}+ workers map[string]*WorkerEntry // workerID → latest state+ pools map[string]*grpcPool // workerID → gRPC connection pool+ stop chan struct{}}// NewRedisWorkerRegistry connects to Redis and returns a new registry.+// Call Start() to begin worker discovery.func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {opts, err := redis.ParseURL(redisURL)if err != nil {@@ -64,25 +73,21 @@ func NewRedisWorkerRegistry(redisURL string) (*RedisWorkerRegistry, error) {return &RedisWorkerRegistry{rdb: rdb,- workers: make(map[string]*WorkerEntry),- conns: make(map[string]*grpc.ClientConn),- clients: make(map[string]pb.SandboxWorkerClient),- clientPools: make(map[string][]pb.SandboxWorkerClient),- stop: make(chan struct{}),+ workers: make(map[string]*WorkerEntry),+ pools: make(map[string]*grpcPool),+ stop: make(chan struct{}),}, nil}-// Start subscribes to the workers:heartbeat pub/sub channel and runs-// periodic reconciliation by scanning worker:* keys in Redis.+// Start begins worker discovery via pub/sub and periodic reconciliation.func (r *RedisWorkerRegistry) Start() {- // Pub/sub subscribergo r.subscribeLoop()-- // Periodic reconciliation + stale worker cleanupgo r.reconcileLoop()}-// subscribeLoop listens for heartbeat messages via Redis pub/sub.+// subscribeLoop listens for worker heartbeats via Redis pub/sub.+// Provides fast (~millisecond) discovery of new workers and load updates.+// Automatically reconnects if the pub/sub channel drops.func (r *RedisWorkerRegistry) subscribeLoop() {for {select {@@ -119,15 +124,14 @@ func (r *RedisWorkerRegistry) subscribeLoop() {}}-// reconcileLoop periodically scans Redis for worker:* keys.-// Workers present in Redis are added/updated; workers absent from Redis-// for 2 consecutive cycles are removed. This is the primary discovery-// mechanism — pub/sub provides faster first-detection but is not required.+// reconcileLoop periodically scans Redis for worker:* keys and prunes stale workers.+// Runs every 10s as a safety net — if a pub/sub heartbeat is missed, the SCAN+// will still discover/remove workers within one cycle.func (r *RedisWorkerRegistry) reconcileLoop() {ticker := time.NewTicker(10 * time.Second)defer ticker.Stop()- // Do an initial scan immediately+ // Initial scan on startup so workers are available immediately.r.reconcileAndPrune()for {@@ -141,7 +145,7 @@ func (r *RedisWorkerRegistry) reconcileLoop() {}// reconcileAndPrune scans all worker:* keys in Redis, updates the in-memory-// map, and removes any workers whose keys have expired (TTL elapsed).+// cache, and removes workers whose heartbeat keys have expired (worker is down).func (r *RedisWorkerRegistry) reconcileAndPrune() {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()@@ -175,30 +179,30 @@ func (r *RedisWorkerRegistry) reconcileAndPrune() {}}- // Remove workers not found in this scan+ // Workers not found in Redis have stopped sending heartbeats — remove them.r.mu.Lock()defer r.mu.Unlock()for id := range r.workers {if !seen[id] {log.Printf("redis_registry: worker %s no longer in Redis, removing", id)delete(r.workers, id)- if conn, ok := r.conns[id]; ok {- conn.Close()- delete(r.conns, id)- delete(r.clients, id)+ if pool, ok := r.pools[id]; ok {+ pool.close()+ delete(r.pools, id)}}}}-// handleHeartbeat updates the in-memory worker map and dials gRPC if this is a new worker.+// handleHeartbeat processes a worker heartbeat: updates the in-memory cache+// and ensures a healthy gRPC connection pool exists for this worker.func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {r.mu.Lock()defer r.mu.Unlock()existing, ok := r.workers[entry.ID]if ok {- // Update existing entry+ // Update load metrics for existing worker.existing.Current = entry.Currentexisting.Capacity = entry.Capacityexisting.CPUPct = entry.CPUPct@@ -213,17 +217,19 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {existing.MachineID = entry.MachineID}} else {- // New worker+ // First time seeing this worker — add to cache.r.workers[entry.ID] = &entrylog.Printf("redis_registry: new worker registered: %s (region=%s, grpc=%s)", entry.ID, entry.Region, entry.GRPCAddr)}- // Ensure gRPC connection exists and is healthy.- // Re-dial if address changed OR connection is in a failed state.+ // Ensure a gRPC connection pool exists and is healthy.+ // Re-create the pool if the worker's gRPC address changed (e.g. new IP after+ // restart) or if the primary connection entered a failed state.if entry.GRPCAddr != "" {- if conn, hasConn := r.conns[entry.ID]; hasConn {+ pool, hasPool := r.pools[entry.ID]+ if hasPool {addrChanged := existing != nil && existing.GRPCAddr != entry.GRPCAddr- state := conn.GetState()+ state := pool.conns[0].GetState()connDead := state == connectivity.TransientFailure || state == connectivity.Shutdownif addrChanged || connDead {if addrChanged {@@ -231,94 +237,34 @@ func (r *RedisWorkerRegistry) handleHeartbeat(entry WorkerEntry) {entry.ID, existing.GRPCAddr, entry.GRPCAddr)} else {log.Printf("redis_registry: worker %s gRPC connection in %s state, re-dialing",- entry.ID, conn.GetState().String())+ entry.ID, state.String())}- conn.Close()- delete(r.conns, entry.ID)- delete(r.clients, entry.ID)- r.dialWorkerLocked(entry.ID, entry.GRPCAddr)+ pool.close()+ delete(r.pools, entry.ID)+ hasPool = false}- } else {- r.dialWorkerLocked(entry.ID, entry.GRPCAddr)}- }-}--// dialWorkerLocked dials a gRPC connection to a worker. Must be called with r.mu held.-func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {- creds, err := grpctls.ClientCredentials()- if err != nil {- log.Printf("redis_registry: failed to load TLS credentials for worker %s: %v", workerID, err)- return- }- conn, err := grpc.NewClient(grpcAddr,- grpc.WithTransportCredentials(creds),- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- grpc.WithKeepaliveParams(keepalive.ClientParameters{- Time: 30 * time.Second,- Timeout: 10 * time.Second,- PermitWithoutStream: true,- }),- )- if err != nil {- log.Printf("redis_registry: failed to dial gRPC for worker %s at %s: %v", workerID, grpcAddr, err)- return- }- // Force the lazy connection to start connecting immediately.- // Without this, grpc.NewClient stays IDLE until the first RPC,- // which means keepalive can't detect a dead connection.- conn.Connect()- r.conns[workerID] = conn-- // Create a pool of gRPC clients over multiple connections to avoid- // HTTP/2 head-of-line blocking under concurrent load. A single HTTP/2- // connection with 64KB send window becomes a bottleneck when 100+- // concurrent RPCs share it.- // Scale pool size by worker capacity: 1 connection per 25 sandboxes, min 8, max 16.- poolSize := 8 // default- if w, ok := r.workers[workerID]; ok && w.Capacity > 0 {- poolSize = w.Capacity / 25- }- if poolSize < 8 {- poolSize = 8- }- if poolSize > 16 {- poolSize = 16- }- clients := make([]pb.SandboxWorkerClient, poolSize)- clients[0] = pb.NewSandboxWorkerClient(conn)- for i := 1; i < poolSize; i++ {- extraConn, err := grpc.NewClient(grpcAddr,- grpc.WithTransportCredentials(creds),- grpc.WithDefaultCallOptions(- grpc.MaxCallRecvMsgSize(256*1024*1024),- grpc.MaxCallSendMsgSize(256*1024*1024),- ),- grpc.WithKeepaliveParams(keepalive.ClientParameters{- Time: 30 * time.Second,- Timeout: 10 * time.Second,- PermitWithoutStream: true,- }),- )- if err != nil {- log.Printf("redis_registry: failed to create pool connection %d for worker %s: %v", i, workerID, err)- break+ if !hasPool {+ capacity := entry.Capacity+ if w, ok := r.workers[entry.ID]; ok {+ capacity = w.Capacity+ }+ pool, err := dialPool(entry.GRPCAddr, capacity)+ if err != nil {+ log.Printf("redis_registry: failed to dial gRPC pool for worker %s at %s: %v", entry.ID, entry.GRPCAddr, err)+ } else {+ r.pools[entry.ID] = pool+ }}- extraConn.Connect()- clients[i] = pb.NewSandboxWorkerClient(extraConn)}- r.clients[workerID] = clients[0] // default client for GetWorkerClient- r.clientPools[workerID] = clients- log.Printf("redis_registry: gRPC connection pool (%d) initiated to worker %s at %s", len(clients), workerID, grpcAddr)}-// GetLeastLoadedWorker returns the worker with the best combination of remaining capacity-// and resource headroom. Workers under heavy resource pressure (CPU > 90% or mem > 90%)-// are skipped. If region is non-empty, only workers in that region are considered.-// If no workers match the region, falls back to all workers.+// --- Worker selection ---++// GetLeastLoadedWorker picks the best worker for a new sandbox.+// Scoring: remaining capacity × resource headroom (CPU + memory).+// Workers with >90% CPU or memory are excluded.+// Prefers workers in the requested region, falls back to any region.func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry, pb.SandboxWorkerClient, error) {r.mu.RLock()defer r.mu.RUnlock()@@ -326,7 +272,7 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,var best *WorkerEntrybestScore := -1.0- // First pass: try workers in the requested region+ // First pass: workers in the requested region.for _, w := range r.workers {if region != "" && w.Region != region {continue@@ -335,11 +281,9 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,if remaining <= 0 {continue}- // Skip workers under heavy resource pressureif w.CPUPct > 90 || w.MemPct > 90 {continue}- // Score: remaining capacity weighted by resource headroomresourceScore := (100.0 - w.CPUPct) / 100.0 * (100.0 - w.MemPct) / 100.0score := float64(remaining) * resourceScoreif score > bestScore {@@ -348,7 +292,7 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,}}- // Fallback: try any region+ // Fallback: any region if no match found.if best == nil && region != "" {for _, w := range r.workers {remaining := w.Capacity - w.Current@@ -371,34 +315,28 @@ func (r *RedisWorkerRegistry) GetLeastLoadedWorker(region string) (*WorkerEntry,return nil, nil, fmt.Errorf("no workers available")}- client, ok := r.clients[best.ID]+ pool, ok := r.pools[best.ID]if !ok {return nil, nil, fmt.Errorf("no gRPC connection to worker %s", best.ID)}- return best, client, nil+ return best, pool.get(), nil}-// GetWorkerClient returns the gRPC client for a specific worker.+// GetWorkerClient returns a gRPC client for a specific worker, selected+// round-robin from the connection pool.func (r *RedisWorkerRegistry) GetWorkerClient(workerID string) (pb.SandboxWorkerClient, error) {r.mu.RLock()defer r.mu.RUnlock()- // Round-robin across connection pool to avoid HTTP/2 head-of-line blocking- pool, ok := r.clientPools[workerID]- if ok && len(pool) > 0 {- idx := atomic.AddUint64(&r.poolCounter, 1) % uint64(len(pool))- return pool[idx], nil- }-- client, ok := r.clients[workerID]+ pool, ok := r.pools[workerID]if !ok {return nil, fmt.Errorf("no gRPC connection to worker %s", workerID)}- return client, nil+ return pool.get(), nil}-// GetWorker returns the entry for a specific worker.+// GetWorker returns the cached state for a specific worker, or nil if unknown.func (r *RedisWorkerRegistry) GetWorker(workerID string) *WorkerEntry {r.mu.RLock()defer r.mu.RUnlock()@@ -417,24 +355,26 @@ func (r *RedisWorkerRegistry) GetAllWorkers() []*WorkerEntry {return result}-// Stop closes the Redis client and all gRPC connections.+// Stop shuts down the registry: stops discovery loops, closes all gRPC+// connection pools, and disconnects from Redis.func (r *RedisWorkerRegistry) Stop() {close(r.stop)r.mu.Lock()defer r.mu.Unlock()- for id, conn := range r.conns {- conn.Close()- delete(r.conns, id)- delete(r.clients, id)+ for id, pool := range r.pools {+ pool.close()+ delete(r.pools, id)}r.rdb.Close()log.Println("redis_registry: stopped")}-// Regions returns all known regions (satisfies ScalerRegistry).+// --- Autoscaler interface (ScalerRegistry) ---++// Regions returns all regions that have at least one registered worker.func (r *RedisWorkerRegistry) Regions() []string {r.mu.RLock()defer r.mu.RUnlock()@@ -451,7 +391,7 @@ func (r *RedisWorkerRegistry) Regions() []string {return regions}-// GetWorkersByRegion returns workers in a region (satisfies ScalerRegistry).+// GetWorkersByRegion returns all workers in a specific region.func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {r.mu.RLock()defer r.mu.RUnlock()@@ -475,7 +415,8 @@ func (r *RedisWorkerRegistry) GetWorkersByRegion(region string) []*WorkerInfo {return result}-// RegionResourcePressure returns the maximum CPU and memory usage across all workers in a region (satisfies ScalerRegistry).+// RegionResourcePressure returns the peak CPU and memory usage across all+// workers in a region. Used by the autoscaler to decide when to scale up.func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxMem float64) {workers := r.GetWorkersByRegion(region)for _, w := range workers {@@ -489,7 +430,8 @@ func (r *RedisWorkerRegistry) RegionResourcePressure(region string) (maxCPU, maxreturn maxCPU, maxMem}-// RegionUtilization returns the average utilization for a region (satisfies ScalerRegistry).+// RegionUtilization returns the average sandbox utilization (current/capacity)+// across all workers in a region. Used by the autoscaler for scale-down decisions.func (r *RedisWorkerRegistry) RegionUtilization(region string) float64 {workers := r.GetWorkersByRegion(region)if len(workers) == 0 {diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex f542b825..63ef43c5 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -9,7 +9,6 @@ import ("fmt""io""log"- "net""os""os/exec""path/filepath"@@ -1763,13 +1762,8 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)}- // Sync filesystem and quiesce agent before snapshot.- // Don't unmount /workspace — open FDs prevent clean unmount, and forcing it- // corrupts the ext4 journal. Just sync to flush dirty pages, then savevm- // captures a consistent state.- // SIGUSR1 resets the virtio-serial listener's active flag so that- // restores from this checkpoint (loadvm or fork) have a clean agent- // that immediately accepts the new host-side connection.+ // Sync filesystem before snapshot. Flush dirty pages so the drives are+ // consistent when we copy them while the VM is paused.if vm.agent != nil {syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)_, syncErr := vm.agent.Exec(syncCtx, &pb.ExecRequest{@@ -1781,97 +1775,122 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDif syncErr != nil {log.Printf("qemu: CreateCheckpoint %s/%s: sync failed: %v", sandboxID, checkpointID, syncErr)}+ // Close the agent connection before pausing — the agent's SIGUSR1 handler+ // resets the virtio-serial listener so forks start with a clean Accept state.vm.agent.Close()vm.agent = niltime.Sleep(500 * time.Millisecond) // let guest process SIGUSR1}- // savevm creates an internal snapshot — memory + device state + disk deltas- // all stored inside the qcow2 files. The VM pauses during savevm and resumes after.+ // Migration-based checkpoint: pause the VM, dump memory + device state to a+ // file, copy the quiesced drives, then resume. This avoids savevm/loadvm which+ // has a ~0.5% virtio-serial state corruption issue after loadvm.if vm.qmp == nil {return "", "", fmt.Errorf("QMP connection not available for %s", sandboxID)}- snapshotName := "cp-" + checkpointID- if err := vm.qmp.SaveVM(snapshotName); err != nil {- return "", "", fmt.Errorf("savevm failed: %w", err)++ // Pause the VM — all I/O stops, drives are quiesced.+ if err := vm.qmp.Stop(); err != nil {+ return "", "", fmt.Errorf("stop VM: %w", err)+ }++ // Set up the cache staging directory before migration so we can dump directly there.+ cacheDir := m.checkpointCacheDir(checkpointID)+ stagingDir := cacheDir + ".staging"+ if mkErr := os.MkdirAll(filepath.Join(stagingDir, "snapshot"), 0755); mkErr != nil {+ _ = vm.qmp.Cont() // resume on failure+ return "", "", fmt.Errorf("mkdir staging: %w", mkErr)+ }++ // Dump memory + device state via QEMU migration protocol.+ // The migrate command writes the full VM state (RAM, device registers, virtio+ // queue state) to the file. Unlike savevm, this produces a standalone file+ // decoupled from the qcow2 drives.+ memFile := filepath.Join(stagingDir, "mem")+ migrateURI := fmt.Sprintf("exec:cat > %s", memFile)+ if err := vm.qmp.Migrate(migrateURI); err != nil {+ _ = vm.qmp.Cont()+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("migrate: %w", err)+ }+ if err := vm.qmp.WaitMigration(5 * time.Minute); err != nil {+ _ = vm.qmp.Cont()+ os.RemoveAll(stagingDir)+ return "", "", fmt.Errorf("wait migration: %w", err)+ }++ // Copy drives while VM is still paused — guaranteed consistent.+ srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")+ srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")+ _ = copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2"))+ _ = copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2"))++ // Compress the memory dump for faster fork I/O.+ memZst := memFile + ".zst"+ compressCmd := exec.Command("zstd", "-3", "--rm", "-q", memFile, "-o", memZst)+ if compErr := compressCmd.Run(); compErr != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: zstd compress failed: %v (using uncompressed)", sandboxID, checkpointID, compErr)+ // Fall back to uncompressed — memFile still exists if zstd failed+ }++ log.Printf("qemu: CreateCheckpoint %s/%s: migration + drive copy complete (%dms)",+ sandboxID, checkpointID, time.Since(t0).Milliseconds())++ // Resume the source VM.+ if err := vm.qmp.Cont(); err != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: WARNING: cont failed after migration: %v", sandboxID, checkpointID, err)}- log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())- // Reconnect agent + remount workspace (VM resumed after savevm)+ // Reconnect agent (connection was closed before migration).agentClient, reconnErr := m.waitForAgentSocket(context.Background(), vm.agentSockPath, 10*time.Second)if reconnErr != nil {- log.Printf("qemu: CreateCheckpoint %s/%s: agent reconnect failed (attempt 1): %v, retrying with longer timeout", sandboxID, checkpointID, reconnErr)+ log.Printf("qemu: CreateCheckpoint %s/%s: agent reconnect failed (attempt 1): %v, retrying", sandboxID, checkpointID, reconnErr)agentClient, reconnErr = m.waitForAgentSocket(context.Background(), vm.agentSockPath, 30*time.Second)- if reconnErr != nil {- log.Printf("qemu: CreateCheckpoint %s/%s: WARNING: agent reconnect failed after retry: %v (checkpoint is valid, agent connection lost temporarily)", sandboxID, checkpointID, reconnErr)- }}if reconnErr == nil {vm.agent = agentClient} else {- // Agent reconnect failed — kill the VM to prevent an unmanageable orphan.- // The checkpoint itself is valid (savevm completed), so the user can fork from it.log.Printf("qemu: CreateCheckpoint %s/%s: CRITICAL: agent reconnect failed, killing orphan VM", sandboxID, checkpointID)if vm.qmp != nil {_ = vm.qmp.Quit()vm.qmp.Close()vm.qmp = nil}- // Remove from vms map so it's not considered runningm.mu.Lock()delete(m.vms, sandboxID)m.mu.Unlock()}- // Cache the drive files for ForkFromCheckpoint (which needs a separate QEMU process).- // Synchronous: reflink copy is instant (~1ms), and the image builder destroys the- // build sandbox immediately after checkpoint — async would race with destruction.- // Cache the checkpoint drives for ForkFromCheckpoint.- // Copy to a temp dir OUTSIDE the lock (disk I/O can take seconds), then- // atomically rename into the cache under the write lock (<1ms).- // This prevents concurrent ForkFromCheckpoint reads from blocking on disk I/O.- cacheDir := m.checkpointCacheDir(checkpointID)- stagingDir := cacheDir + ".staging"+ // Write metadata and finalize cache.rootfsKey = fmt.Sprintf("checkpoints/%s/%s/rootfs.tar.zst", sandboxID, checkpointID)workspaceKey = fmt.Sprintf("checkpoints/%s/%s/workspace.tar.zst", sandboxID, checkpointID)- if mkErr := os.MkdirAll(filepath.Join(stagingDir, "snapshot"), 0755); mkErr != nil {- log.Printf("qemu: checkpoint %s: mkdir staging failed: %v", checkpointID, mkErr)- } else {- // Copy qcow2 drives to staging (slow, no lock held)- srcRootfs := filepath.Join(vm.sandboxDir, "rootfs.qcow2")- srcWorkspace := filepath.Join(vm.sandboxDir, "workspace.qcow2")- _ = copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2"))- _ = copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2"))-- // Write metadata to staging- meta := &SnapshotMeta{- SandboxID: vm.ID,- Network: vm.network,- GuestCID: vm.guestCID,- GuestMAC: vm.guestMAC,- BootArgs: vm.bootArgs,- CpuCount: vm.CpuCount,- MemoryMB: vm.MemoryMB,- BaseMemoryMB: vm.baseMemoryMB,- Template: vm.Template,- GuestPort: vm.GuestPort,- SnapshotedAt: time.Now(),- }- metaJSON, _ := json.Marshal(meta)- _ = os.WriteFile(filepath.Join(stagingDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)- _ = os.WriteFile(filepath.Join(stagingDir, "snapshot-name"), []byte(snapshotName), 0644)-- // Atomic rename into cache under write lock (<1ms)- m.checkpointCacheMu.Lock()- os.RemoveAll(cacheDir) // remove stale cache if exists- if renameErr := os.Rename(stagingDir, cacheDir); renameErr != nil {- log.Printf("qemu: checkpoint %s: rename staging to cache failed: %v", checkpointID, renameErr)- }- m.checkpointCacheMu.Unlock()-- log.Printf("qemu: checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())+ meta := &SnapshotMeta{+ SandboxID: vm.ID,+ Network: vm.network,+ GuestCID: vm.guestCID,+ GuestMAC: vm.guestMAC,+ BootArgs: vm.bootArgs,+ CpuCount: vm.CpuCount,+ MemoryMB: vm.MemoryMB,+ BaseMemoryMB: vm.baseMemoryMB,+ Template: vm.Template,+ GuestPort: vm.GuestPort,+ SnapshotedAt: time.Now(),+ }+ metaJSON, _ := json.Marshal(meta)+ _ = os.WriteFile(filepath.Join(stagingDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)++ // Atomic rename into cache under write lock.+ m.checkpointCacheMu.Lock()+ os.RemoveAll(cacheDir)+ if renameErr := os.Rename(stagingDir, cacheDir); renameErr != nil {+ log.Printf("qemu: checkpoint %s: rename staging to cache failed: %v", checkpointID, renameErr)}+ m.checkpointCacheMu.Unlock()++ log.Printf("qemu: checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())+if onReady != nil {onReady()}@@ -2137,7 +2156,6 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, ccacheDir := m.checkpointCacheDir(checkpointID)metaPath := filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")- // qcow2 drives contain the savevm snapshot datacachedRootfs := filepath.Join(cacheDir, "rootfs.qcow2")cachedWorkspace := filepath.Join(cacheDir, "workspace.qcow2")if !fileExists(cachedRootfs) || !fileExists(cachedWorkspace) {@@ -2145,12 +2163,6 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, creturn nil, fmt.Errorf("checkpoint %s: qcow2 files not found in cache", checkpointID)}- // Read snapshot name- snapshotName := "cp-" + checkpointID- if data, err := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); err == nil {- snapshotName = strings.TrimSpace(string(data))- }-var meta SnapshotMetaif data, err := os.ReadFile(metaPath); err == nil {json.Unmarshal(data, &meta)@@ -2242,8 +2254,23 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c)qmpSockPath := filepath.Join(sandboxDir, "qmp.sock")- os.Remove(qmpSockPath)agentSockPath := filepath.Join(sandboxDir, "agent.sock")++ // Determine the migration memory file — prefer zstd-compressed.+ memZst := filepath.Join(cacheDir, "mem.zst")+ memRaw := filepath.Join(cacheDir, "mem")+ var incomingURI string+ if fileExists(memZst) {+ incomingURI = fmt.Sprintf("exec:zstdcat %s", memZst)+ } else if fileExists(memRaw) {+ incomingURI = fmt.Sprintf("exec:cat %s", memRaw)+ } else {+ // Backward compat: no mem file means this is a savevm-based checkpoint.+ // Fall back to the old loadvm path.+ incomingURI = ""+ }++ os.Remove(qmpSockPath)os.Remove(agentSockPath)logPath := filepath.Join(sandboxDir, "qemu.log")@@ -2253,10 +2280,16 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, creturn nil, fmt.Errorf("create log file: %w", err)}- // Start QEMU paused — we'll loadvm then contargs := m.buildQEMUArgs(cpus, memMB, rootfsPath, workspacePath,netCfg.TAPName, guestMAC, agentSockPath, qmpSockPath, bootArgs)- args = append(args, "-S") // start paused++ if incomingURI != "" {+ // Migration-based restore: QEMU loads state from the mem dump file.+ args = append(args, "-incoming", incomingURI)+ } else {+ // Savevm-based fallback: start paused, then loadvm.+ args = append(args, "-S")+ }cmd := exec.Command(m.cfg.QEMUBin, args...)cmd.Stdout = logFile@@ -2268,7 +2301,8 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c}logFile.Close()- log.Printf("qemu: ForkFromCheckpoint %s → %s: QEMU started (pid=%d), connecting QMP...", checkpointID, id, cmd.Process.Pid)+ log.Printf("qemu: ForkFromCheckpoint %s → %s: QEMU started (pid=%d, migration=%v)",+ checkpointID, id, cmd.Process.Pid, incomingURI != "")qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)if err != nil {@@ -2277,17 +2311,30 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cm.cleanupVM(netCfg, sandboxDir)return nil, fmt.Errorf("QMP connect: %w", err)}- log.Printf("qemu: ForkFromCheckpoint %s → %s: QMP connected, loading snapshot %s...", checkpointID, id, snapshotName)- // loadvm restores from the internal snapshot in the qcow2 drives- if err := qmpClient.LoadVM(snapshotName); err != nil {- qmpClient.Close()- cmd.Process.Kill()- cmd.Wait()- m.cleanupVM(netCfg, sandboxDir)- return nil, fmt.Errorf("loadvm: %w", err)+ if incomingURI != "" {+ // Migration-based: wait for incoming migration to finish loading, then resume.+ if err := m.waitForMigrationReady(qmpClient, 30*time.Second); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("migration load: %w", err)+ }+ } else {+ // Savevm fallback: load the internal snapshot.+ snapshotName := "cp-" + checkpointID+ if data, readErr := os.ReadFile(filepath.Join(cacheDir, "snapshot-name")); readErr == nil {+ snapshotName = strings.TrimSpace(string(data))+ }+ if err := qmpClient.LoadVM(snapshotName); err != nil {+ qmpClient.Close()+ cmd.Process.Kill()+ cmd.Wait()+ m.cleanupVM(netCfg, sandboxDir)+ return nil, fmt.Errorf("loadvm: %w", err)+ }}- log.Printf("qemu: ForkFromCheckpoint %s → %s: loadvm done, resuming...", checkpointID, id)if err := qmpClient.Cont(); err != nil {qmpClient.Close()@@ -2296,53 +2343,18 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cm.cleanupVM(netCfg, sandboxDir)return nil, fmt.Errorf("QMP cont: %w", err)}- log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), checking agent socket exists...",+ log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), connecting agent...",checkpointID, id, time.Since(t0).Milliseconds())- // Check if the agent socket file exists before trying gRPC dial- if _, statErr := os.Stat(agentSockPath); statErr != nil {- log.Printf("qemu: ForkFromCheckpoint %s → %s: WARNING agent socket not found: %v", checkpointID, id, statErr)- } else {- log.Printf("qemu: ForkFromCheckpoint %s → %s: agent socket exists, dialing...", checkpointID, id)- }-- // Check QEMU process is alive- if cmd.Process != nil {- if procErr := cmd.Process.Signal(syscall.Signal(0)); procErr != nil {- log.Printf("qemu: ForkFromCheckpoint %s → %s: WARNING QEMU process not alive: %v", checkpointID, id, procErr)- }+ // Connect agent — migration-based restores are reliable (no virtio-serial+ // state issues), so use a shorter timeout.+ agentTimeout := 30 * time.Second+ if incomingURI != "" {+ agentTimeout = 10 * time.Second}-- // Connect agent via Unix socketvar agent *AgentClient- agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)+ agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, agentTimeout)if err != nil {- // Log QEMU process state on failure- procAlive := "unknown"- if cmd.Process != nil {- if procErr := cmd.Process.Signal(syscall.Signal(0)); procErr != nil {- procAlive = fmt.Sprintf("dead: %v", procErr)- } else {- procAlive = "alive"- }- }- // Check socket exists- sockExists := "no"- if fi, statErr := os.Stat(agentSockPath); statErr == nil {- sockExists = fmt.Sprintf("yes (mode=%s)", fi.Mode())- }- // Try raw unix dial to see if socket accepts connections- rawConn, rawErr := net.DialTimeout("unix", agentSockPath, 2*time.Second)- rawDial := "failed"- if rawErr == nil {- rawDial = "ok"- rawConn.Close()- } else {- rawDial = fmt.Sprintf("failed: %v", rawErr)- }- log.Printf("qemu: ForkFromCheckpoint %s → %s: agent connect FAILED — qemu=%s, socket=%s, rawDial=%s, err=%v",- checkpointID, id, procAlive, sockExists, rawDial, err)-qmpClient.Close()cmd.Process.Kill()cmd.Wait()diff --git a/internal/storage/blob.go b/internal/storage/blob.goindex e83242ce..1217a4a7 100644--- a/internal/storage/blob.go+++ b/internal/storage/blob.go@@ -28,6 +28,8 @@ type BlobClient interface {Head(ctx context.Context, bucket, key string) (int64, error)// Delete removes the object at the given key.Delete(ctx context.Context, bucket, key string) error+ // BackendName returns a human-readable name for the storage backend (e.g. "S3", "Azure Blob").+ BackendName() string}// NewBlobClient creates the appropriate blob client based on the endpoint.diff --git a/internal/storage/blob_azure.go b/internal/storage/blob_azure.goindex c89431a8..229d7c1d 100644--- a/internal/storage/blob_azure.go+++ b/internal/storage/blob_azure.go@@ -15,6 +15,8 @@ type azureBlobClient struct {connStr string}+func (c *azureBlobClient) BackendName() string { return "Azure Blob" }+// normalizeKey strips the container name prefix from the key if present.// S3 keys often include the bucket name (e.g., "checkpoints/sb-xxx/...") because// S3 treats bucket and key as separate. Azure Blob uses container + blob name,diff --git a/internal/storage/blob_s3.go b/internal/storage/blob_s3.goindex 081a961b..4c8711b6 100644--- a/internal/storage/blob_s3.go+++ b/internal/storage/blob_s3.go@@ -17,6 +17,8 @@ type s3BlobClient struct {client *s3.Client}+func (c *s3BlobClient) BackendName() string { return "S3" }+// buildS3Client creates an S3 client from config.func buildS3Client(cfg S3Config) (*s3.Client, error) {forcePathStyle := cfg.ForcePathStylediff --git a/internal/storage/s3.go b/internal/storage/s3.goindex 775d8a4c..0486b453 100644--- a/internal/storage/s3.go+++ b/internal/storage/s3.go@@ -9,7 +9,6 @@ import ("os""path/filepath""sort"- "strings""sync""time"@@ -48,11 +47,7 @@ func NewCheckpointStore(cfg S3Config) (*CheckpointStore, error) {return nil, fmt.Errorf("failed to create blob client: %w", err)}- backend := "S3"- if strings.Contains(cfg.Endpoint, ".blob.core.windows.net") {- backend = "Azure Blob"- }- log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", backend, cfg.Endpoint, cfg.Bucket)+ log.Printf("storage: using %s backend (endpoint=%s, bucket=%s)", blob.BackendName(), cfg.Endpoint, cfg.Bucket)return &CheckpointStore{blob: blob,