Skip to content

An open-source, faster Devin alternative

TypeScript

testing fixes

Brian Reardon9db1692fa4dd
diff --git a/internal/api/exec_session.go b/internal/api/exec_session.go
index 77f80535..683142f8 100644
--- a/internal/api/exec_session.go
+++ b/internal/api/exec_session.go
@@ -3,13 +3,16 @@ package api
import (
"context"
"encoding/binary"
+ "fmt"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
)
func (s *Server) createExecSession(c echo.Context) error {
@@ -225,6 +228,15 @@ func (s *Server) execRun(c echo.Context) error {
})
}
+ // Server mode: route exec to the worker that owns this sandbox via gRPC
+ if s.workerRegistry != nil {
+ return s.execRunRemote(c, id, req)
+ }
+
+ if s.manager == nil {
+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
+ }
+
var result *types.ProcessResult
routeOp := func(ctx context.Context) error {
@@ -250,6 +262,54 @@ func (s *Server) execRun(c echo.Context) error {
return c.JSON(http.StatusOK, result)
}
+// execRunRemote routes an exec/run request to the worker via gRPC.
+func (s *Server) execRunRemote(c echo.Context, sandboxID string, req types.ProcessConfig) error {
+ orgID, _ := auth.GetOrgID(c)
+
+ session, err := s.store.GetSandboxSession(c.Request().Context(), sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+ if session.OrgID != orgID {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "sandbox not found"})
+ }
+
+ client, err := s.workerRegistry.GetWorkerClient(session.WorkerID)
+ if err != nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": fmt.Sprintf("worker unavailable: %v", err),
+ })
+ }
+
+ timeout := int32(req.Timeout)
+ if timeout <= 0 {
+ timeout = 30
+ }
+
+ grpcCtx, cancel := context.WithTimeout(c.Request().Context(), time.Duration(timeout+5)*time.Second)
+ defer cancel()
+
+ resp, err := client.ExecCommand(grpcCtx, &pb.ExecCommandRequest{
+ SandboxId: sandboxID,
+ Command: req.Command,
+ Args: req.Args,
+ Envs: req.Env,
+ Cwd: req.Cwd,
+ Timeout: timeout,
+ })
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
+ })
+ }
+
+ return c.JSON(http.StatusOK, &types.ProcessResult{
+ ExitCode: int(resp.ExitCode),
+ Stdout: resp.Stdout,
+ Stderr: resp.Stderr,
+ })
+}
+
func (s *Server) killExecSession(c echo.Context) error {
if s.execSessionManager == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
diff --git a/internal/db/store.go b/internal/db/store.go
index 28a7aa2b..f27aa11a 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -879,8 +879,23 @@ func (s *Store) CountCheckpoints(ctx context.Context, sandboxID string) (int, er
}
// DeleteCheckpoint deletes a checkpoint (only if owned by org).
+// Clears any sandbox_sessions FK references first to avoid constraint violations.
func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpointID uuid.UUID) error {
- tag, err := s.pool.Exec(ctx,
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+
+ // Clear FK references from sandboxes forked from this checkpoint
+ _, err = tx.Exec(ctx,
+ `UPDATE sandbox_sessions SET based_on_checkpoint_id = NULL WHERE based_on_checkpoint_id = $1`,
+ checkpointID)
+ if err != nil {
+ return fmt.Errorf("clear checkpoint references: %w", err)
+ }
+
+ tag, err := tx.Exec(ctx,
`DELETE FROM sandbox_checkpoints WHERE id = $1 AND org_id = $2`,
checkpointID, orgID)
if err != nil {
@@ -889,7 +904,8 @@ func (s *Store) DeleteCheckpoint(ctx context.Context, orgID uuid.UUID, checkpoin
if tag.RowsAffected() == 0 {
return fmt.Errorf("checkpoint not found or not owned by org")
}
- return nil
+
+ return tx.Commit(ctx)
}
// --- Checkpoint Patch operations ---
diff --git a/internal/firecracker/api.go b/internal/firecracker/api.go
index c8788e21..017c1afb 100644
--- a/internal/firecracker/api.go
+++ b/internal/firecracker/api.go
@@ -142,8 +142,8 @@ func (c *FirecrackerClient) CreateSnapshot(snapshotPath, memFilePath string) err
// LoadSnapshot restores a VM from a snapshot.
// If resumeVM is true, the VM starts running immediately after load.
// clockDeltaUs is the microseconds elapsed since the snapshot was taken; Firecracker
-// advances the guest clock by this amount so the VM wakes with the correct wall time.
-// Pass 0 to skip clock correction (e.g. for legacy snapshots without a recorded time).
+// The clockDeltaUs parameter is accepted for interface compatibility but not sent
+// to Firecracker (the API does not support clock correction).
func (c *FirecrackerClient) LoadSnapshot(snapshotPath, memFilePath string, resumeVM bool, clockDeltaUs int64) error {
body := map[string]interface{}{
"snapshot_path": snapshotPath,
@@ -154,9 +154,6 @@ func (c *FirecrackerClient) LoadSnapshot(snapshotPath, memFilePath string, resum
"enable_diff_snapshots": false,
"resume_vm": resumeVM,
}
- if clockDeltaUs > 0 {
- body["clock_delta_us"] = clockDeltaUs
- }
return c.put("/snapshot/load", body)
}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 44401acf..51bb1e3c 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -449,6 +449,13 @@ func (m *Manager) waitForAgent(ctx context.Context, vsockPath string, timeout ti
var lastErr error
attempts := 0
+ // Log initial vsock file state for diagnostics
+ if _, err := os.Stat(vsockPath); err != nil {
+ log.Printf("firecracker: waitForAgent: vsock.sock does not exist yet at %s", vsockPath)
+ } else {
+ log.Printf("firecracker: waitForAgent: vsock.sock exists at %s", vsockPath)
+ }
+
for time.Now().Before(deadline) {
attempts++
tAttempt := time.Now()
diff --git a/internal/firecracker/snapshot.go b/internal/firecracker/snapshot.go
index 0f608729..3fa0fc99 100644
--- a/internal/firecracker/snapshot.go
+++ b/internal/firecracker/snapshot.go
@@ -12,6 +12,7 @@ import (
"os/exec"
"path/filepath"
"strings"
+ "syscall"
"time"
"github.com/google/uuid"
@@ -82,10 +83,15 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
}
log.Printf("firecracker: hibernate %s: guest sync done (%dms)", vm.ID, time.Since(t0).Milliseconds())
- // Step 2: Close gRPC connection — vsock must be inactive before snapshot
+ // Step 2: Close gRPC connection — vsock must be inactive before snapshot.
+ // Allow time for the vsock virtqueues to drain after closing the connection.
+ // Without this delay, FIN-ACK packets from the guest may still be in the
+ // vsock TX virtqueue when the VM is paused, leaving vhost-vsock in a broken
+ // state after snapshot restore (connections hang indefinitely).
if vm.agent != nil {
vm.agent.Close()
vm.agent = nil
+ time.Sleep(500 * time.Millisecond)
}
// Step 3: Pause the VM
@@ -401,6 +407,27 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return nil, fmt.Errorf("load snapshot: %w", err)
}
log.Printf("firecracker: wake %s: snapshot restored (hot)", sandboxID)
+
+ // Wait for vsock.sock to appear — Firecracker recreates it from vmstate
+ vsockDeadline := time.Now().Add(5 * time.Second)
+ for !fileExists(vsockPath) && time.Now().Before(vsockDeadline) {
+ time.Sleep(50 * time.Millisecond)
+ }
+ if !fileExists(vsockPath) {
+ // Log Firecracker output for diagnosis
+ if logData, err := os.ReadFile(filepath.Join(sandboxDir, "firecracker.log")); err == nil {
+ log.Printf("firecracker: wake %s: vsock.sock NOT found at %s after 5s — FC log:\n%s",
+ sandboxID, vsockPath, string(logData))
+ }
+ // Check if Firecracker process is still alive
+ if cmd.Process != nil {
+ if err := cmd.Process.Signal(syscall.Signal(0)); err != nil {
+ log.Printf("firecracker: wake %s: FC process died: %v", sandboxID, err)
+ }
+ }
+ } else {
+ log.Printf("firecracker: wake %s: vsock.sock ready at %s", sandboxID, vsockPath)
+ }
} else {
// Cold boot: configure + boot fresh VM with restored drives.
// Filesystem state is preserved but running processes are not.
@@ -786,10 +813,12 @@ func (m *Manager) doSaveAsTemplate(ctx context.Context, vm *VMInstance, template
}
}
- // Step 2: Close gRPC connection (vsock must be inactive before Firecracker pause)
+ // Step 2: Close gRPC connection (vsock must be inactive before Firecracker pause).
+ // Drain delay prevents stale vsock virtqueue entries from breaking vhost-vsock after restore.
if vm.agent != nil {
vm.agent.Close()
vm.agent = nil
+ time.Sleep(500 * time.Millisecond)
}
// Step 3: Pause the VM
@@ -971,10 +1000,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
})
}
- // Step 2: Close gRPC connection (vsock must be inactive before pause)
+ // Step 2: Close gRPC connection (vsock must be inactive before pause).
+ // Drain delay prevents stale vsock virtqueue entries from breaking vhost-vsock after restore.
if vm.agent != nil {
vm.agent.Close()
vm.agent = nil
+ time.Sleep(500 * time.Millisecond)
}
// Step 3: Pause the VM
@@ -2080,6 +2111,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {
})
agent.Close()
+ time.Sleep(500 * time.Millisecond) // drain vsock virtqueues before pause
if err := fcClient.PauseVM(); err != nil {
cmd.Process.Kill()