Skip to content

An open-source, faster Devin alternative

TypeScript

fixes - add logs for transient

Brian Reardon9aa71ac0bb74
diff --git a/internal/agent/server.go b/internal/agent/server.go
index 3730570f..3d9cf084 100644
--- a/internal/agent/server.go
+++ b/internal/agent/server.go
@@ -101,6 +101,18 @@ func (s *Server) GracefulStop() {
}
}
+// ForceStop immediately stops the gRPC server, closing all connections.
+// Used before savevm to ensure the active virtio-serial connection is torn down
+// synchronously, so onClose fires and active=false before the snapshot.
+func (s *Server) ForceStop() {
+ s.mu.Lock()
+ gs := s.grpcServer
+ s.mu.Unlock()
+ if gs != nil {
+ gs.Stop()
+ }
+}
+
// GetVersion returns the agent's build version.
func (s *Server) GetVersion(ctx context.Context, req *pb.GetVersionRequest) (*pb.GetVersionResponse, error) {
return &pb.GetVersionResponse{Version: s.version}, nil
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 14448c7d..6df8a009 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -517,6 +517,12 @@ func (s *Server) killSandbox(c echo.Context) error {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
+ // Mark stopped immediately so it no longer counts toward concurrency limits.
+ if s.store != nil {
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)
+ s.cleanupPreviewURLs(c.Request().Context(), id)
+ }
+
if err := s.manager.Kill(c.Request().Context(), id); err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
@@ -528,11 +534,6 @@ func (s *Server) killSandbox(c echo.Context) error {
s.router.Unregister(id)
}
- if s.store != nil {
- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)
- s.cleanupPreviewURLs(c.Request().Context(), id)
- }
-
if s.sandboxDBs != nil {
_ = s.sandboxDBs.Remove(id)
}
@@ -555,13 +556,15 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
})
}
+ // Mark stopped immediately so it no longer counts toward concurrency limits.
+ // The actual VM teardown below is best-effort.
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
+ s.cleanupPreviewURLs(c.Request().Context(), sandboxID)
+
// Attempt gRPC destroy (best-effort)
client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
if err != nil {
- // Worker is unreachable — mark as error in PG
log.Printf("sandbox: worker %s unreachable for destroy: %v", session.WorkerID, err)
- errMsg := "worker unreachable"
- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "error", &errMsg)
return c.NoContent(http.StatusNoContent)
}
@@ -572,9 +575,6 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
log.Printf("sandbox: gRPC destroy failed for %s: %v", sandboxID, err)
}
- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
- s.cleanupPreviewURLs(c.Request().Context(), sandboxID)
-
return c.NoContent(http.StatusNoContent)
}
@@ -1584,14 +1584,14 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
// Boot VM in background
go func() {
- createCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
-
var createErr error
if grpcClient != nil {
- // Server mode: dispatch to worker via gRPC
- _, createErr = grpcClient.CreateSandbox(createCtx, &pb.CreateSandboxRequest{
+ // Use background context — the fork has its own internal timeouts
+ // (30s agent connect, 10s QMP, 5s network patch). An external deadline
+ // here causes orphaned VMs: the gRPC layer returns DeadlineExceeded
+ // while the worker finishes creating the VM, leaving it untracked.
+ _, createErr = grpcClient.CreateSandbox(context.Background(), &pb.CreateSandboxRequest{
Template: originalCfg.Template,
Timeout: int32(timeout),
Envs: originalCfg.Envs,
@@ -1605,7 +1605,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
SandboxId: sandboxID,
})
} else {
- // Combined mode: create locally
+ // Combined mode: create locally — no external timeout, same reasoning as above
cfg := originalCfg
cfg.Timeout = timeout
cfg.TemplateRootfsKey = *cp.RootfsS3Key
@@ -1617,9 +1617,9 @@ func (s *Server) createFromCheckpointCore(c echo.Context) (map[string]interface{
ForkFromCheckpoint(ctx context.Context, checkpointID string, cfg types.SandboxConfig) (*types.Sandbox, error)
})
if hasFork {
- _, createErr = forkMgr.ForkFromCheckpoint(createCtx, checkpointID.String(), cfg)
+ _, createErr = forkMgr.ForkFromCheckpoint(context.Background(), checkpointID.String(), cfg)
} else {
- _, createErr = s.manager.Create(createCtx, cfg)
+ _, createErr = s.manager.Create(context.Background(), cfg)
}
}
diff --git a/internal/controlplane/redis_registry.go b/internal/controlplane/redis_registry.go
index 1e25fb08..c4918438 100644
--- a/internal/controlplane/redis_registry.go
+++ b/internal/controlplane/redis_registry.go
@@ -6,6 +6,7 @@ import (
"fmt"
"log"
"sync"
+ "sync/atomic"
"time"
"github.com/redis/go-redis/v9"
@@ -37,10 +38,12 @@ type WorkerEntry struct {
type RedisWorkerRegistry struct {
rdb *redis.Client
mu 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
- stop chan struct{}
+ 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{}
}
// NewRedisWorkerRegistry connects to Redis and returns a new registry.
@@ -61,10 +64,11 @@ 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),
- stop: make(chan struct{}),
+ 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{}),
}, nil
}
@@ -268,8 +272,47 @@ func (r *RedisWorkerRegistry) dialWorkerLocked(workerID, grpcAddr string) {
// which means keepalive can't detect a dead connection.
conn.Connect()
r.conns[workerID] = conn
- r.clients[workerID] = pb.NewSandboxWorkerClient(conn)
- log.Printf("redis_registry: gRPC connection initiated to worker %s at %s", workerID, grpcAddr)
+
+ // 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 4, 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
+ }
+ 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
@@ -341,6 +384,13 @@ func (r *RedisWorkerRegistry) GetWorkerClient(workerID string) (pb.SandboxWorker
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]
if !ok {
return nil, fmt.Errorf("no gRPC connection to worker %s", workerID)
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 67e1818e..3731cb3d 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -273,15 +273,17 @@ func (s *Server) destroySandbox(c echo.Context) error {
return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
}
+ // Mark stopped immediately so it no longer counts toward concurrency limits.
+ _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
+
// Get worker gRPC address
worker := s.registry.GetWorker(session.WorkerID)
if worker == nil {
- // Worker is down, just mark as error
- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "error", strPtr("worker unreachable"))
+ log.Printf("controlplane: worker %s unreachable for destroy of %s", session.WorkerID, sandboxID)
return c.NoContent(http.StatusNoContent)
}
- // Call gRPC DestroySandbox
+ // Call gRPC DestroySandbox (best-effort — sandbox already marked stopped)
ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
defer cancel()
@@ -300,8 +302,6 @@ func (s *Server) destroySandbox(c echo.Context) error {
log.Printf("controlplane: gRPC destroy failed: %v", err)
}
- _ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
-
return c.NoContent(http.StatusNoContent)
}
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index fda67737..f542b825 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"log"
+ "net"
"os"
"os/exec"
"path/filepath"
@@ -645,7 +646,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
// Connect to agent via Unix socket
var agentClient *AgentClient
- agentClient, err = m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)
+ agentClient, err = m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
if err != nil {
log.Printf("qemu: golden-create %s: agent not ready, falling back to cold boot: %v", id, err)
qmpClient.Close()
@@ -1174,6 +1175,7 @@ func (m *Manager) waitForAgentSocket(ctx context.Context, socketPath string, tim
deadline := t0.Add(timeout)
var lastErr error
attempts := 0
+ pingFailures := 0
for time.Now().Before(deadline) {
attempts++
@@ -1181,6 +1183,7 @@ func (m *Manager) waitForAgentSocket(ctx context.Context, socketPath string, tim
client, err := NewAgentClientSocket(socketPath)
if err != nil {
lastErr = err
+ pingFailures = 0
if attempts <= 3 || attempts%10 == 0 {
log.Printf("qemu: waitForAgentSocket: attempt %d dial %s failed (%dms): %v",
attempts, socketPath, time.Since(tAttempt).Milliseconds(), err)
@@ -1193,9 +1196,20 @@ func (m *Manager) waitForAgentSocket(ctx context.Context, socketPath string, tim
_, err = client.Ping(pingCtx)
cancel()
if err != nil {
- client.Close()
+ pingFailures++
lastErr = err
- time.Sleep(50 * time.Millisecond)
+ client.Close()
+ if pingFailures <= 3 || pingFailures%5 == 0 {
+ log.Printf("qemu: waitForAgentSocket: attempt %d ping %s failed (%dms, streak=%d): %v",
+ attempts, socketPath, time.Since(tAttempt).Milliseconds(), pingFailures, err)
+ }
+ // After several ping failures, back off longer to give the guest
+ // agent time to fully resume after loadvm.
+ if pingFailures >= 5 {
+ time.Sleep(500 * time.Millisecond)
+ } else {
+ time.Sleep(100 * time.Millisecond)
+ }
continue
}
@@ -1204,7 +1218,7 @@ func (m *Manager) waitForAgentSocket(ctx context.Context, socketPath string, tim
return client, nil
}
- return nil, fmt.Errorf("agent not ready after %v (%d attempts): %v", timeout, attempts, lastErr)
+ return nil, fmt.Errorf("agent not ready after %v (%d attempts, %d ping failures): %v", timeout, attempts, pingFailures, lastErr)
}
// Get returns sandbox info by ID.
@@ -1812,22 +1826,25 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
// 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.
- m.checkpointCacheMu.Lock()
- defer m.checkpointCacheMu.Unlock()
+ // 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"
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(cacheDir, "snapshot"), 0755); mkErr != nil {
- log.Printf("qemu: checkpoint %s: mkdir cache failed: %v", checkpointID, mkErr)
+ 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 (they contain the snapshot data)
+ // 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(cacheDir, "rootfs.qcow2"))
- _ = copyFileReflink(srcWorkspace, filepath.Join(cacheDir, "workspace.qcow2"))
+ _ = copyFileReflink(srcRootfs, filepath.Join(stagingDir, "rootfs.qcow2"))
+ _ = copyFileReflink(srcWorkspace, filepath.Join(stagingDir, "workspace.qcow2"))
- // Write metadata
+ // Write metadata to staging
meta := &SnapshotMeta{
SandboxID: vm.ID,
Network: vm.network,
@@ -1836,13 +1853,22 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
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(cacheDir, "snapshot", "snapshot-meta.json"), metaJSON, 0644)
- _ = os.WriteFile(filepath.Join(cacheDir, "snapshot-name"), []byte(snapshotName), 0644)
+ _ = 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())
}
@@ -2242,6 +2268,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)
+
qmpClient, err := waitForQMP(qmpSockPath, 10*time.Second)
if err != nil {
cmd.Process.Kill()
@@ -2249,6 +2277,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
m.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 {
@@ -2258,6 +2287,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
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()
@@ -2266,12 +2296,53 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
m.cleanupVM(netCfg, sandboxDir)
return nil, fmt.Errorf("QMP cont: %w", err)
}
- log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms)", checkpointID, id, time.Since(t0).Milliseconds())
+ log.Printf("qemu: ForkFromCheckpoint %s → %s: VM resumed (%dms), checking agent socket exists...",
+ 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 via Unix socket
var agent *AgentClient
- agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, 10*time.Second)
+ agent, err = m.waitForAgentSocket(context.Background(), agentSockPath, 30*time.Second)
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()
@@ -2279,6 +2350,8 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
return nil, fmt.Errorf("agent connect: %w", err)
}
+ log.Printf("qemu: ForkFromCheckpoint %s → %s: agent connected, patching network...", checkpointID, id)
+
// Patch network (fork gets new IPs) + sync clock
if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {
log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)
@@ -2287,10 +2360,6 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
log.Printf("qemu: ForkFromCheckpoint %s: clock sync failed: %v", id, err)
}
- if err := patchGuestNetwork(context.Background(), agent, netCfg); err != nil {
- log.Printf("qemu: ForkFromCheckpoint %s: network patch failed: %v", id, err)
- }
-
// Set env vars
if len(cfg.Envs) > 0 {
envCtx, envCancel := context.WithTimeout(context.Background(), 5*time.Second)
diff --git a/internal/storage/blob_azure.go b/internal/storage/blob_azure.go
index 1dee25b4..c89431a8 100644
--- a/internal/storage/blob_azure.go
+++ b/internal/storage/blob_azure.go
@@ -4,16 +4,29 @@ import (
"context"
"fmt"
"io"
+ "strings"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
)
// azureBlobClient implements BlobClient using the native Azure Blob SDK.
type azureBlobClient struct {
- client *azblob.Client
+ client *azblob.Client
connStr string
}
+// 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,
+// so we strip the redundant prefix to avoid "container/container/..." paths.
+func normalizeKey(container, key string) string {
+ prefix := container + "/"
+ if strings.HasPrefix(key, prefix) {
+ return strings.TrimPrefix(key, prefix)
+ }
+ return key
+}
+
func (c *azureBlobClient) ensureClient() error {
if c.client != nil {
return nil
@@ -30,7 +43,7 @@ func (c *azureBlobClient) Upload(ctx context.Context, container, key string, bod
if err := c.ensureClient(); err != nil {
return err
}
- _, err := c.client.UploadStream(ctx, container, key, body, nil)
+ _, err := c.client.UploadStream(ctx, container, normalizeKey(container, key), body, nil)
return err
}
@@ -38,7 +51,7 @@ func (c *azureBlobClient) Download(ctx context.Context, container, key string) (
if err := c.ensureClient(); err != nil {
return nil, err
}
- resp, err := c.client.DownloadStream(ctx, container, key, nil)
+ resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), nil)
if err != nil {
return nil, err
}
@@ -49,7 +62,7 @@ func (c *azureBlobClient) DownloadRange(ctx context.Context, container, key stri
if err := c.ensureClient(); err != nil {
return nil, err
}
- resp, err := c.client.DownloadStream(ctx, container, key, &azblob.DownloadStreamOptions{
+ resp, err := c.client.DownloadStream(ctx, container, normalizeKey(container, key), &azblob.DownloadStreamOptions{
Range: azblob.HTTPRange{Offset: offset, Count: length},
})
if err != nil {
@@ -62,7 +75,7 @@ func (c *azureBlobClient) Head(ctx context.Context, container, key string) (int6
if err := c.ensureClient(); err != nil {
return 0, err
}
- resp, err := c.client.ServiceClient().NewContainerClient(container).NewBlobClient(key).GetProperties(ctx, nil)
+ resp, err := c.client.ServiceClient().NewContainerClient(container).NewBlobClient(normalizeKey(container, key)).GetProperties(ctx, nil)
if err != nil {
return 0, err
}
@@ -76,6 +89,6 @@ func (c *azureBlobClient) Delete(ctx context.Context, container, key string) err
if err := c.ensureClient(); err != nil {
return err
}
- _, err := c.client.DeleteBlob(ctx, container, key, nil)
+ _, err := c.client.DeleteBlob(ctx, container, normalizeKey(container, key), nil)
return err
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index d300d699..c83fa99b 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -156,7 +156,14 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
Status: string(sb.Status),
}, nil
}
- log.Printf("grpc: ForkFromCheckpoint %s failed: %v, falling back to standard Create", req.CheckpointId, err)
+ // Only fall back to S3 download if the checkpoint isn't cached locally
+ // (cross-worker restore). If the fork failed for other reasons (agent
+ // timeout, QMP error), retrying via S3 won't help and the blob may
+ // not even exist.
+ if !strings.Contains(err.Error(), "not found in cache") {
+ return nil, fmt.Errorf("fork from checkpoint %s: %w", req.CheckpointId, err)
+ }
+ log.Printf("grpc: ForkFromCheckpoint %s: not in local cache, falling back to S3 download", req.CheckpointId)
}
// Handle sandbox snapshot template: resolve S3 keys to local paths.