Skip to content

An open-source, faster Devin alternative

TypeScript

PTY/exec sessions survive live migration via lazy worker-side rebind to in-VM agent

Brian Reardon0a11db7d5c59
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 63c58804..e5a2dc03 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -129,8 +129,13 @@ func main() {
// Backend-specific exec session factory
var execSessionFactory func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error)
+ // Lazy reattach to an existing agent-side exec session — populated when the
+ // local map misses (live migration or worker restart).
+ var execSessionRebinder func(sandboxID, sessionID string) (*sandbox.ExecSessionHandle, error)
// Backend-specific PTY session factory
var ptySessionFactory func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error)
+ // Lazy reattach for PTY sessions, same role as execSessionRebinder.
+ var ptySessionRebinder func(sandboxID, sessionID string) (*sandbox.PTYSessionHandle, error)
// Backend-specific autosaver syncer
var autosaverSyncer worker.SyncFSer
// Backend-specific graceful shutdown
@@ -296,6 +301,14 @@ func main() {
return createExecSessionQEMU(agent, sandboxID, req)
}
+ execSessionRebinder = func(sandboxID, sessionID string) (*sandbox.ExecSessionHandle, error) {
+ agent, err := qmMgr.GetAgent(sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)
+ }
+ return rebindExecSessionQEMU(agent, sandboxID, sessionID)
+ }
+
ptySessionFactory = func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {
agent, err := qmMgr.GetAgent(sandboxID)
if err != nil {
@@ -304,6 +317,14 @@ func main() {
return createPTYSessionQEMU(agent, sandboxID, req)
}
+ ptySessionRebinder = func(sandboxID, sessionID string) (*sandbox.PTYSessionHandle, error) {
+ agent, err := qmMgr.GetAgent(sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)
+ }
+ return rebindPTYSessionQEMU(agent, sandboxID, sessionID)
+ }
+
doGracefulShutdown = func(checkpointStore *storage.CheckpointStore, store *db.Store) {
if checkpointStore == nil {
return
@@ -348,13 +369,27 @@ func main() {
}
// Initialize exec session manager
- execMgr := sandbox.NewAgentExecSessionManager(execSessionFactory)
+ execMgr := sandbox.NewAgentExecSessionManager(execSessionFactory, execSessionRebinder)
defer execMgr.CloseAll()
// Initialize PTY manager
- ptyMgr := sandbox.NewAgentPTYManager(ptySessionFactory)
+ ptyMgr := sandbox.NewAgentPTYManager(ptySessionFactory, ptySessionRebinder)
defer ptyMgr.CloseAll()
+ // On outgoing migration, drop SOURCE-side PTY/exec handles so any WS
+ // blocked on a now-orphaned gRPC stream unblocks immediately. The edge DO
+ // then redials, the destination worker's RebindFromAgent picks up the
+ // still-alive in-VM session, and the user's terminal continues without
+ // any visible interruption beyond the redial latency. Wired here (not
+ // inside the QEMU manager) because the session managers live in the
+ // worker layer and the QEMU layer shouldn't depend on them.
+ if qemuMgr != nil {
+ qemuMgr.SetMigrationOutgoingCallback(func(sandboxID string) {
+ ptyMgr.ReleaseForSandbox(sandboxID)
+ execMgr.RemoveSessions(sandboxID)
+ })
+ }
+
// Initialize per-sandbox SQLite manager (forward-declared above so the
// graceful-shutdown closure can capture it).
sandboxDBMgr = sandbox.NewSandboxDBManager(cfg.DataDir)
@@ -926,6 +961,61 @@ func buildCheckpointBackend(label, endpoint, region, accessKeyID, secretAccessKe
})
}
+// rebindExecSessionQEMU opens a fresh ExecSessionAttach stream against an
+// EXISTING agent-side exec session. The agent already has the process and
+// the scrollback ring — reattach delivers the scrollback snapshot followed
+// by live output, same shape as the original create flow.
+//
+// The local handle's Command/Args metadata is left blank: it isn't load-
+// bearing for the WS bridge (handlers.go uses the handle only for SandboxID
+// match + scrollback + stdin pipe). If we later need it post-migration, an
+// agent.ExecSessionList() lookup keyed on sessionID can populate it.
+func rebindExecSessionQEMU(agent *qm.AgentClient, sandboxID, sessionID string) (*sandbox.ExecSessionHandle, error) {
+ scrollback := sandbox.NewScrollbackBuffer(0)
+ done := make(chan struct{})
+ stdinR, stdinW := io.Pipe()
+
+ handle := &sandbox.ExecSessionHandle{
+ ID: sessionID,
+ SandboxID: sandboxID,
+ Running: true,
+ StartedAt: time.Now(),
+ Done: done,
+ Scrollback: scrollback,
+ StdinWriter: stdinW,
+ OnKill: func(signal int) error {
+ stdinW.Close()
+ return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))
+ },
+ }
+
+ // Same goroutine shape as the create path — attach + send first message
+ // (bind to existing session) + pump stdin/scrollback. The agent will
+ // emit a "session not found" error to stream.Recv() if the session is
+ // gone, causing consumeExecOutput to return immediately; the caller's
+ // timeout on the WS upgrade will then fail. Acceptable for an edge case
+ // where the user reconnects right as the exec process exits.
+ go runExecRebindQEMU(agent, sessionID, stdinR, done, scrollback, handle)
+
+ return handle, nil
+}
+
+// runExecRebindQEMU mirrors runExecStreamQEMU but binds to an existing
+// session_id instead of expecting Create to have just allocated it.
+func runExecRebindQEMU(agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {
+ defer close(done)
+ defer stdinR.Close()
+ stream, err := agent.ExecSessionAttach(context.Background())
+ if err != nil {
+ return
+ }
+ if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {
+ return
+ }
+ go forwardStdin(stdinR, stream)
+ consumeExecOutput(stream, scrollback, handle)
+}
+
// createExecSessionQEMU creates an exec session using a QEMU agent client.
func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {
agentPB := &agentpb.ExecSessionCreateRequest{
@@ -1074,6 +1164,44 @@ func (c *grpcPTYConn) Close() error {
return nil
}
+// rebindPTYSessionQEMU opens a fresh PTYAttach stream against an EXISTING
+// agent-side PTY session — i.e. the agent already has the shell + tty, we
+// just need a host-side I/O channel into it. Used after a live migration or
+// worker restart wipes the destination worker's local session map.
+//
+// Failure modes:
+// - agent returns "pty session <id> not found" on the first stream.Recv() →
+// the session is genuinely gone (process exited or VM rebooted). We don't
+// distinguish this from a transport error here — caller treats both as
+// "not found" and returns 404 to the edge.
+// - the bidi stream opens successfully → the agent looked up the session
+// and is now streaming. Return a PTYSessionHandle that adapts the stream
+// just like the create path's grpcPTYConn.
+func rebindPTYSessionQEMU(agent *qm.AgentClient, sandboxID, sessionID string) (*sandbox.PTYSessionHandle, error) {
+ ctx, cancel := context.WithCancel(context.Background())
+ stream, err := agent.PTYAttach(ctx)
+ if err != nil {
+ cancel()
+ return nil, fmt.Errorf("rebind PTY stream: %w", err)
+ }
+ // First message binds the stream to an existing session in the agent.
+ // Cols/Rows omitted — the agent keeps whatever the original Create
+ // set; a fresh client that wants to resize will send PTYResize.
+ if err := stream.Send(&agentpb.PTYInput{SessionId: sessionID}); err != nil {
+ cancel()
+ return nil, fmt.Errorf("send PTY session ID for rebind: %w", err)
+ }
+
+ conn := &grpcPTYConn{stream: stream, cancel: cancel}
+ done := make(chan struct{})
+ return &sandbox.PTYSessionHandle{
+ ID: sessionID,
+ SandboxID: sandboxID,
+ PTY: conn,
+ Done: done,
+ }, nil
+}
+
// createPTYSessionQEMU creates a PTY session using gRPC PTYAttach (QEMU backend).
func createPTYSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {
cols := int32(req.Cols)
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 7c63aa4a..cf724b0d 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -333,7 +333,8 @@ type Manager struct {
// Metadata service callbacks (set via SetMetadataCallbacks)
onSandboxReady func(sandboxID, guestIP, template string, startedAt time.Time)
- onSandboxDestroy func(sandboxID string)
+ onSandboxDestroy func(sandboxID string)
+ onMigrationOutgoing func(sandboxID string)
// Hibernation upload status callback (set via SetHibernationUploadCallback).
// Invoked from the async archive+upload goroutine in doHibernate exactly once
@@ -430,6 +431,18 @@ func (m *Manager) SetMetadataCallbacks(
m.onSandboxDestroy = onDestroy
}
+// SetMigrationOutgoingCallback registers a callback fired AFTER a successful
+// outgoing LiveMigrate has handed the VM off to the destination worker and
+// cleaned up local QEMU + network state. Used to release per-sandbox session
+// handles (PTY, exec) without killing the in-VM session — the destination
+// worker now owns it. Without this hook the source worker's gRPC PTY/exec
+// streams sit on a dead vsock connection, so the edge DO sees no upstream
+// close, never redials, and the user's WS appears alive but is silently
+// black-holed.
+func (m *Manager) SetMigrationOutgoingCallback(cb func(sandboxID string)) {
+ m.onMigrationOutgoing = cb
+}
+
// SetSecretsProxy configures the secrets proxy integration for token substitution.
// Must be called before any sandboxes are created.
func (m *Manager) SetSecretsProxy(sp SecretsProxyIntegration) {
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index afb74313..0bc9c6c6 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -349,6 +349,14 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco
mc.manager.onSandboxDestroy(sandboxID)
}
+ // Release source-side PTY/exec session handles. Distinct from destroy:
+ // the in-VM session is still alive on the DESTINATION worker, so we must
+ // not call onKill paths that would hit the agent (the call would either
+ // fail or, worse, succeed against a now-unrelated host).
+ if mc.manager.onMigrationOutgoing != nil {
+ mc.manager.onMigrationOutgoing(sandboxID)
+ }
+
return nil
}
diff --git a/internal/sandbox/exec_session.go b/internal/sandbox/exec_session.go
index 162ce925..0958566e 100644
--- a/internal/sandbox/exec_session.go
+++ b/internal/sandbox/exec_session.go
@@ -10,12 +10,14 @@ import (
)
// ExecSessionManager manages exec sessions on the host side.
-// Mirrors PTYManager's pattern: supports both Podman (stub) and Firecracker
-// (via createFunc override).
type ExecSessionManager struct {
mu sync.RWMutex
sessions map[string]*ExecSessionHandle
createFunc func(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error)
+ // rebindFunc binds a NEW gRPC ExecSessionAttach stream to an EXISTING
+ // agent-side session by ID. Used after live migration (or worker restart)
+ // makes the local session map empty while the in-VM session keeps running.
+ rebindFunc func(sandboxID, sessionID string) (*ExecSessionHandle, error)
}
// ExecSessionHandle holds the state for an exec session on the host side.
@@ -41,15 +43,52 @@ func NewExecSessionManager() *ExecSessionManager {
}
}
-// NewAgentExecSessionManager creates an exec session manager that delegates to
-// a custom create function (used by Firecracker mode).
-func NewAgentExecSessionManager(createFunc func(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error)) *ExecSessionManager {
+// NewAgentExecSessionManager creates an exec session manager that delegates
+// session creation to createFunc (gRPC ExecSessionCreate) and recovery to
+// rebindFunc (gRPC ExecSessionAttach against an existing in-VM session).
+// rebindFunc may be nil — RebindFromAgent then always reports "not found".
+func NewAgentExecSessionManager(
+ createFunc func(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error),
+ rebindFunc func(sandboxID, sessionID string) (*ExecSessionHandle, error),
+) *ExecSessionManager {
return &ExecSessionManager{
sessions: make(map[string]*ExecSessionHandle),
createFunc: createFunc,
+ rebindFunc: rebindFunc,
}
}
+// RebindFromAgent attempts to look up sessionID against the in-VM agent and,
+// if it's still alive, register a fresh local handle that streams through a
+// new ExecSessionAttach. Used after live migration or worker restart wipes
+// the local session map. Returns the registered handle on success, or an
+// error if the agent reports the session is gone.
+func (m *ExecSessionManager) RebindFromAgent(sandboxID, sessionID string) (*ExecSessionHandle, error) {
+ if m.rebindFunc == nil {
+ return nil, fmt.Errorf("exec session %s not found", sessionID)
+ }
+ // Drop stale local entry first — its gRPC stream targets the old worker.
+ m.mu.Lock()
+ if stale, ok := m.sessions[sessionID]; ok {
+ delete(m.sessions, sessionID)
+ if stale.OnKill != nil {
+ // Don't actually kill — just release local pipes. The agent owns
+ // the process and we want it to keep running.
+ _ = stale
+ }
+ }
+ m.mu.Unlock()
+
+ handle, err := m.rebindFunc(sandboxID, sessionID)
+ if err != nil {
+ return nil, err
+ }
+ m.mu.Lock()
+ m.sessions[handle.ID] = handle
+ m.mu.Unlock()
+ return handle, nil
+}
+
// CreateSession creates a new exec session.
func (m *ExecSessionManager) CreateSession(sandboxID string, req types.ExecSessionCreateRequest) (*ExecSessionHandle, error) {
if m.createFunc == nil {
diff --git a/internal/sandbox/pty.go b/internal/sandbox/pty.go
index 2409b915..b20e67e3 100644
--- a/internal/sandbox/pty.go
+++ b/internal/sandbox/pty.go
@@ -17,6 +17,13 @@ type PTYManager struct {
// createFunc creates PTY sessions via the Firecracker agent.
createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error)
+
+ // rebindFunc binds a NEW gRPC PTYAttach stream to an EXISTING agent-side
+ // session by ID. Used after live migration (or worker restart): the in-VM
+ // agent retains the PTY/shell across the move, but the destination worker's
+ // in-process session map is empty. Falling back to rebind on cache miss
+ // makes session_id portable across workers without touching the agent.
+ rebindFunc func(sandboxID, sessionID string) (*PTYSessionHandle, error)
}
// PTYSessionHandle holds the state for an active PTY session.
@@ -33,13 +40,48 @@ type PTYSessionHandle struct {
onResize func(cols, rows int) error
}
-// NewAgentPTYManager creates a PTY manager that delegates to a custom
-// create function (used by Firecracker mode).
-func NewAgentPTYManager(createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error)) *PTYManager {
+// NewAgentPTYManager creates a PTY manager that delegates session creation
+// to createFunc (gRPC PTYCreate against the in-VM agent) and session
+// recovery to rebindFunc (gRPC PTYAttach against an existing in-VM session).
+// rebindFunc may be nil — RebindFromAgent then always reports "not found",
+// so the manager behaves as a strict local cache with no agent fallback.
+func NewAgentPTYManager(
+ createFunc func(sandboxID string, req types.PTYCreateRequest) (*PTYSessionHandle, error),
+ rebindFunc func(sandboxID, sessionID string) (*PTYSessionHandle, error),
+) *PTYManager {
return &PTYManager{
sessions: make(map[string]*PTYSessionHandle),
createFunc: createFunc,
+ rebindFunc: rebindFunc,
+ }
+}
+
+// RebindFromAgent attempts to look up sessionID against the in-VM agent and,
+// if it's still alive, register a fresh local handle that streams through a
+// new PTYAttach. Used after live migration or worker restart wipes the local
+// session map. Returns the registered handle on success, or an error if the
+// agent reports the session is gone (or if rebindFunc was not configured).
+func (pm *PTYManager) RebindFromAgent(sandboxID, sessionID string) (*PTYSessionHandle, error) {
+ if pm.rebindFunc == nil {
+ return nil, fmt.Errorf("PTY session %s not found", sessionID)
+ }
+ // Drop any stale local entry first — its underlying gRPC stream points at
+ // the old worker's agent connection and won't ever produce bytes again.
+ pm.mu.Lock()
+ if stale, ok := pm.sessions[sessionID]; ok {
+ delete(pm.sessions, sessionID)
+ _ = stale.PTY.Close()
+ }
+ pm.mu.Unlock()
+
+ handle, err := pm.rebindFunc(sandboxID, sessionID)
+ if err != nil {
+ return nil, err
}
+ pm.mu.Lock()
+ pm.sessions[handle.ID] = handle
+ pm.mu.Unlock()
+ return handle, nil
}
// CreateSession starts a new PTY session inside a sandbox.
@@ -117,6 +159,28 @@ func (pm *PTYManager) KillSession(sessionID string) error {
return nil
}
+// ReleaseForSandbox drops every local session belonging to sandboxID and
+// closes its underlying gRPC PTY stream so any in-flight WS handler blocked
+// on session.PTY.Read() unblocks immediately. Does NOT invoke onKill — the
+// in-VM PTY is owned by the agent and may have migrated to another worker
+// that's still serving it. Use this on the SOURCE side of a live migration
+// (or after DestroySandbox) so the edge DO sees the upstream close, redials,
+// and lands on the destination worker where RebindFromAgent can take over.
+func (pm *PTYManager) ReleaseForSandbox(sandboxID string) {
+ pm.mu.Lock()
+ var toRelease []*PTYSessionHandle
+ for id, s := range pm.sessions {
+ if s.SandboxID == sandboxID {
+ toRelease = append(toRelease, s)
+ delete(pm.sessions, id)
+ }
+ }
+ pm.mu.Unlock()
+ for _, s := range toRelease {
+ _ = s.PTY.Close()
+ }
+}
+
// CloseAll terminates all PTY sessions.
func (pm *PTYManager) CloseAll() {
pm.mu.Lock()
diff --git a/internal/worker/handlers.go b/internal/worker/handlers.go
index 9b5deee8..0b379fc3 100644
--- a/internal/worker/handlers.go
+++ b/internal/worker/handlers.go
@@ -133,7 +133,15 @@ func (s *HTTPServer) execSessionWebSocket(c echo.Context) error {
session, err := s.execSessionManager.GetSession(sessionID)
if err != nil {
- return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ // Local cache miss — possible post-migration first attach. Ask the
+ // agent; if the in-VM session is still alive, register a new local
+ // handle that streams through ExecSessionAttach.
+ rebound, rebindErr := s.execSessionManager.RebindFromAgent(id, sessionID)
+ if rebindErr != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ session = rebound
+ log.Printf("worker exec: rebound session=%s sandbox=%s from agent", sessionID, id)
}
if session.SandboxID != id {
@@ -549,8 +557,16 @@ func (s *HTTPServer) ptyWebSocket(c echo.Context) error {
session, err := s.ptyManager.GetSession(sessionID)
if err != nil {
- log.Printf("worker PTY: GetSession(%s) failed: %v", sessionID, err)
- return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ // Local cache miss — try a lazy rebind against the agent. If the
+ // in-VM PTY is still alive (the common case after live migration or
+ // worker process restart), register a new local handle and continue.
+ rebound, rebindErr := s.ptyManager.RebindFromAgent(id, sessionID)
+ if rebindErr != nil {
+ log.Printf("worker PTY: GetSession(%s) miss, rebind also failed: get=%v rebind=%v", sessionID, err, rebindErr)
+ return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
+ }
+ session = rebound
+ log.Printf("worker PTY: rebound session=%s sandbox=%s from agent", sessionID, id)
}
if session.SandboxID != id {